xref: /aosp_15_r20/frameworks/base/cmds/idmap2/libidmap2/Idmap.cpp (revision d57664e9bc4670b3ecf6748a746a57c557b6bc9e)
1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "idmap2/Idmap.h"
18 
19 #include <algorithm>
20 #include <cassert>
21 #include <istream>
22 #include <iterator>
23 #include <limits>
24 #include <memory>
25 #include <string>
26 #include <utility>
27 
28 #include "android-base/format.h"
29 #include "android-base/macros.h"
30 #include "androidfw/AssetManager2.h"
31 #include "idmap2/ResourceMapping.h"
32 #include "idmap2/ResourceUtils.h"
33 #include "idmap2/Result.h"
34 #include "idmap2/SysTrace.h"
35 
36 namespace android::idmap2 {
37 
38 namespace {
39 
Read8(std::istream & stream,uint8_t * out)40 bool WARN_UNUSED Read8(std::istream& stream, uint8_t* out) {
41   uint8_t value;
42   if (stream.read(reinterpret_cast<char*>(&value), sizeof(uint8_t))) {
43     *out = value;
44     return true;
45   }
46   return false;
47 }
48 
Read16(std::istream & stream,uint16_t * out)49 bool WARN_UNUSED Read16(std::istream& stream, uint16_t* out) {
50   uint16_t value;
51   if (stream.read(reinterpret_cast<char*>(&value), sizeof(uint16_t))) {
52     *out = dtohs(value);
53     return true;
54   }
55   return false;
56 }
57 
Read32(std::istream & stream,uint32_t * out)58 bool WARN_UNUSED Read32(std::istream& stream, uint32_t* out) {
59   uint32_t value;
60   if (stream.read(reinterpret_cast<char*>(&value), sizeof(uint32_t))) {
61     *out = dtohl(value);
62     return true;
63   }
64   return false;
65 }
66 
ReadString(std::istream & stream,std::string * out)67 bool WARN_UNUSED ReadString(std::istream& stream, std::string* out) {
68   uint32_t size;
69   if (!Read32(stream, &size)) {
70     return false;
71   }
72   if (size == 0) {
73     *out = "";
74     return true;
75   }
76   std::string buf(size, '\0');
77   if (!stream.read(buf.data(), size)) {
78     return false;
79   }
80   uint32_t padding_size = CalculatePadding(size);
81   if (padding_size != 0 && !stream.seekg(padding_size, std::ios_base::cur)) {
82     return false;
83   }
84   *out = std::move(buf);
85   return true;
86 }
87 
88 }  // namespace
89 
FromBinaryStream(std::istream & stream)90 std::unique_ptr<const IdmapHeader> IdmapHeader::FromBinaryStream(std::istream& stream) {
91   std::unique_ptr<IdmapHeader> idmap_header(new IdmapHeader());
92   if (!Read32(stream, &idmap_header->magic_) || !Read32(stream, &idmap_header->version_)) {
93     return nullptr;
94   }
95 
96   if (idmap_header->magic_ != kIdmapMagic || idmap_header->version_ != kIdmapCurrentVersion) {
97     // Do not continue parsing if the file is not a current version idmap.
98     return nullptr;
99   }
100 
101   uint32_t enforce_overlayable;
102   if (!Read32(stream, &idmap_header->target_crc_) || !Read32(stream, &idmap_header->overlay_crc_) ||
103       !Read32(stream, &idmap_header->fulfilled_policies_) ||
104       !Read32(stream, &enforce_overlayable) || !ReadString(stream, &idmap_header->target_path_) ||
105       !ReadString(stream, &idmap_header->overlay_path_) ||
106       !ReadString(stream, &idmap_header->overlay_name_) ||
107       !ReadString(stream, &idmap_header->debug_info_)) {
108     return nullptr;
109   }
110 
111   idmap_header->enforce_overlayable_ = enforce_overlayable != 0U;
112   return std::move(idmap_header);
113 }
114 
IsUpToDate(const TargetResourceContainer & target,const OverlayResourceContainer & overlay,const std::string & overlay_name,PolicyBitmask fulfilled_policies,bool enforce_overlayable) const115 Result<Unit> IdmapHeader::IsUpToDate(const TargetResourceContainer& target,
116                                      const OverlayResourceContainer& overlay,
117                                      const std::string& overlay_name,
118                                      PolicyBitmask fulfilled_policies,
119                                      bool enforce_overlayable) const {
120   const Result<uint32_t> target_crc = target.GetCrc();
121   if (!target_crc) {
122     return Error("failed to get target crc");
123   }
124 
125   const Result<uint32_t> overlay_crc = overlay.GetCrc();
126   if (!overlay_crc) {
127     return Error("failed to get overlay crc");
128   }
129 
130   return IsUpToDate(target.GetPath(), overlay.GetPath(), overlay_name, *target_crc, *overlay_crc,
131                     fulfilled_policies, enforce_overlayable);
132 }
133 
IsUpToDate(const std::string & target_path,const std::string & overlay_path,const std::string & overlay_name,uint32_t target_crc,uint32_t overlay_crc,PolicyBitmask fulfilled_policies,bool enforce_overlayable) const134 Result<Unit> IdmapHeader::IsUpToDate(const std::string& target_path,
135                                      const std::string& overlay_path,
136                                      const std::string& overlay_name, uint32_t target_crc,
137                                      uint32_t overlay_crc, PolicyBitmask fulfilled_policies,
138                                      bool enforce_overlayable) const {
139   if (magic_ != kIdmapMagic) {
140     return Error("bad magic: actual 0x%08x, expected 0x%08x", magic_, kIdmapMagic);
141   }
142 
143   if (version_ != kIdmapCurrentVersion) {
144     return Error("bad version: actual 0x%08x, expected 0x%08x", version_, kIdmapCurrentVersion);
145   }
146 
147   if (target_crc_ != target_crc) {
148     return Error("bad target crc: idmap version 0x%08x, file system version 0x%08x", target_crc_,
149                  target_crc);
150   }
151 
152   if (overlay_crc_ != overlay_crc) {
153     return Error("bad overlay crc: idmap version 0x%08x, file system version 0x%08x", overlay_crc_,
154                  overlay_crc);
155   }
156 
157   if (fulfilled_policies_ != fulfilled_policies) {
158     return Error("bad fulfilled policies: idmap version 0x%08x, file system version 0x%08x",
159                  fulfilled_policies, fulfilled_policies_);
160   }
161 
162   if (enforce_overlayable != enforce_overlayable_) {
163     return Error("bad enforce overlayable: idmap version %s, file system version %s",
164                  enforce_overlayable ? "true" : "false", enforce_overlayable_ ? "true" : "false");
165   }
166 
167   if (target_path != target_path_) {
168     return Error("bad target path: idmap version %s, file system version %s", target_path.c_str(),
169                  target_path_.c_str());
170   }
171 
172   if (overlay_path != overlay_path_) {
173     return Error("bad overlay path: idmap version %s, file system version %s", overlay_path.c_str(),
174                  overlay_path_.c_str());
175   }
176 
177   if (overlay_name != overlay_name_) {
178     return Error("bad overlay name: idmap version %s, file system version %s", overlay_name.c_str(),
179                  overlay_name_.c_str());
180   }
181 
182   return Unit{};
183 }
184 
FromBinaryStream(std::istream & stream)185 std::unique_ptr<const IdmapData::Header> IdmapData::Header::FromBinaryStream(std::istream& stream) {
186   std::unique_ptr<IdmapData::Header> idmap_data_header(new IdmapData::Header());
187   if (!Read32(stream, &idmap_data_header->target_entry_count) ||
188       !Read32(stream, &idmap_data_header->target_entry_inline_count) ||
189       !Read32(stream, &idmap_data_header->target_entry_inline_value_count) ||
190       !Read32(stream, &idmap_data_header->config_count) ||
191       !Read32(stream, &idmap_data_header->overlay_entry_count) ||
192       !Read32(stream, &idmap_data_header->string_pool_index_offset)) {
193     return nullptr;
194   }
195 
196   return std::move(idmap_data_header);
197 }
198 
FromBinaryStream(std::istream & stream)199 std::unique_ptr<const IdmapData> IdmapData::FromBinaryStream(std::istream& stream) {
200   std::unique_ptr<IdmapData> data(new IdmapData());
201   data->header_ = IdmapData::Header::FromBinaryStream(stream);
202   if (!data->header_) {
203     return nullptr;
204   }
205 
206   // Read the mapping of target resource id to overlay resource value.
207   data->target_entries_.resize(data->header_->GetTargetEntryCount());
208   for (size_t i = 0; i < data->header_->GetTargetEntryCount(); i++) {
209     if (!Read32(stream, &data->target_entries_[i].target_id)) {
210       return nullptr;
211     }
212   }
213   for (size_t i = 0; i < data->header_->GetTargetEntryCount(); i++) {
214     if (!Read32(stream, &data->target_entries_[i].overlay_id)) {
215       return nullptr;
216     }
217   }
218 
219   // Read the mapping of target resource id to inline overlay values.
220   struct TargetInlineEntryHeader {
221     ResourceId target_id;
222     uint32_t values_offset;
223     uint32_t values_count;
224   };
225   std::vector<TargetInlineEntryHeader> target_inline_entries(
226       data->header_->GetTargetInlineEntryCount());
227   for (size_t i = 0; i < data->header_->GetTargetInlineEntryCount(); i++) {
228     if (!Read32(stream, &target_inline_entries[i].target_id)) {
229       return nullptr;
230     }
231   }
232   for (size_t i = 0; i < data->header_->GetTargetInlineEntryCount(); i++) {
233     if (!Read32(stream, &target_inline_entries[i].values_offset) ||
234         !Read32(stream, &target_inline_entries[i].values_count)) {
235       return nullptr;
236     }
237   }
238 
239   // Read the inline overlay resource values
240   struct TargetValueHeader {
241     uint32_t config_index;
242     DataType data_type;
243     DataValue data_value;
244   };
245   std::vector<TargetValueHeader> target_values(data->header_->GetTargetInlineEntryValueCount());
246   for (size_t i = 0; i < data->header_->GetTargetInlineEntryValueCount(); i++) {
247     auto& value = target_values[i];
248     if (!Read32(stream, &value.config_index)) {
249       return nullptr;
250     }
251     // skip the padding
252     stream.seekg(3, std::ios::cur);
253     if (!Read8(stream, &value.data_type) || !Read32(stream, &value.data_value)) {
254       return nullptr;
255     }
256   }
257 
258   // Read the configurations
259   std::vector<ConfigDescription> configurations(data->header_->GetConfigCount());
260   if (!configurations.empty()) {
261     if (!stream.read(reinterpret_cast<char*>(&configurations.front()),
262                      sizeof(configurations.front()) * configurations.size())) {
263       return nullptr;
264     }
265   }
266 
267   // Construct complete target inline entries
268   data->target_inline_entries_.reserve(target_inline_entries.size());
269   for (auto&& entry_header : target_inline_entries) {
270     TargetInlineEntry& entry = data->target_inline_entries_.emplace_back();
271     entry.target_id = entry_header.target_id;
272     for (size_t i = 0; i < entry_header.values_count; i++) {
273       const auto& value_header = target_values[entry_header.values_offset + i];
274       const auto& config = configurations[value_header.config_index];
275       auto& value = entry.values[config];
276       value.data_type = value_header.data_type;
277       value.data_value = value_header.data_value;
278     }
279   }
280 
281   // Read the mapping of overlay resource id to target resource id.
282   data->overlay_entries_.resize(data->header_->GetOverlayEntryCount());
283   for (size_t i = 0; i < data->header_->GetOverlayEntryCount(); i++) {
284     if (!Read32(stream, &data->overlay_entries_[i].overlay_id)) {
285       return nullptr;
286     }
287   }
288   for (size_t i = 0; i < data->header_->GetOverlayEntryCount(); i++) {
289     if (!Read32(stream, &data->overlay_entries_[i].target_id)) {
290       return nullptr;
291     }
292   }
293 
294   // Read raw string pool bytes.
295   if (!ReadString(stream, &data->string_pool_data_)) {
296     return nullptr;
297   }
298   return std::move(data);
299 }
300 
CanonicalIdmapPathFor(std::string_view absolute_dir,std::string_view absolute_apk_path)301 std::string Idmap::CanonicalIdmapPathFor(std::string_view absolute_dir,
302                                          std::string_view absolute_apk_path) {
303   assert(absolute_dir.size() > 0 && absolute_dir[0] == "/");
304   assert(absolute_apk_path.size() > 0 && absolute_apk_path[0] == "/");
305   std::string copy(absolute_apk_path.begin() + 1, absolute_apk_path.end());
306   replace(copy.begin(), copy.end(), '/', '@');
307   return fmt::format("{}/{}@idmap", absolute_dir, copy);
308 }
309 
FromBinaryStream(std::istream & stream)310 Result<std::unique_ptr<const Idmap>> Idmap::FromBinaryStream(std::istream& stream) {
311   SYSTRACE << "Idmap::FromBinaryStream";
312   std::unique_ptr<Idmap> idmap(new Idmap());
313 
314   idmap->header_ = IdmapHeader::FromBinaryStream(stream);
315   if (!idmap->header_) {
316     return Error("failed to parse idmap header");
317   }
318 
319   // idmap version 0x01 does not specify the number of data blocks that follow
320   // the idmap header; assume exactly one data block
321   for (int i = 0; i < 1; i++) {
322     std::unique_ptr<const IdmapData> data = IdmapData::FromBinaryStream(stream);
323     if (!data) {
324       return Error("failed to parse data block %d", i);
325     }
326     idmap->data_.push_back(std::move(data));
327   }
328 
329   return {std::move(idmap)};
330 }
331 
FromResourceMapping(const ResourceMapping & resource_mapping)332 Result<std::unique_ptr<const IdmapData>> IdmapData::FromResourceMapping(
333     const ResourceMapping& resource_mapping) {
334   if (resource_mapping.GetTargetToOverlayMap().empty()) {
335     return Error("no resources were overlaid");
336   }
337 
338   std::unique_ptr<IdmapData> data(new IdmapData());
339   data->string_pool_data_ = std::string(resource_mapping.GetStringPoolData());
340   uint32_t inline_value_count = 0;
341   std::set<std::string_view> config_set;
342   for (const auto& mapping : resource_mapping.GetTargetToOverlayMap()) {
343     if (auto overlay_resource = std::get_if<ResourceId>(&mapping.second)) {
344       data->target_entries_.push_back({mapping.first, *overlay_resource});
345     } else {
346       std::map<ConfigDescription, TargetValue> values;
347       for (const auto& [config, value] : std::get<ConfigMap>(mapping.second)) {
348         config_set.insert(config);
349         ConfigDescription cd;
350         if (!ConfigDescription::Parse(config, &cd)) {
351           return Error("failed to parse configuration string '%s'", config.c_str());
352         }
353         values[cd] = value;
354         inline_value_count++;
355       }
356       data->target_inline_entries_.push_back({mapping.first, std::move(values)});
357     }
358   }
359 
360   for (const auto& mapping : resource_mapping.GetOverlayToTargetMap()) {
361     data->overlay_entries_.emplace_back(IdmapData::OverlayEntry{mapping.first, mapping.second});
362   }
363 
364   std::unique_ptr<IdmapData::Header> data_header(new IdmapData::Header());
365   data_header->target_entry_count = static_cast<uint32_t>(data->target_entries_.size());
366   data_header->target_entry_inline_count =
367       static_cast<uint32_t>(data->target_inline_entries_.size());
368   data_header->target_entry_inline_value_count = inline_value_count;
369   data_header->config_count = config_set.size();
370   data_header->overlay_entry_count = static_cast<uint32_t>(data->overlay_entries_.size());
371   data_header->string_pool_index_offset = resource_mapping.GetStringPoolOffset();
372   data->header_ = std::move(data_header);
373   return {std::move(data)};
374 }
375 
FromContainers(const TargetResourceContainer & target,const OverlayResourceContainer & overlay,const std::string & overlay_name,const PolicyBitmask & fulfilled_policies,bool enforce_overlayable)376 Result<std::unique_ptr<const Idmap>> Idmap::FromContainers(const TargetResourceContainer& target,
377                                                            const OverlayResourceContainer& overlay,
378                                                            const std::string& overlay_name,
379                                                            const PolicyBitmask& fulfilled_policies,
380                                                            bool enforce_overlayable) {
381   SYSTRACE << "Idmap::FromApkAssets";
382   std::unique_ptr<IdmapHeader> header(new IdmapHeader());
383   header->magic_ = kIdmapMagic;
384   header->version_ = kIdmapCurrentVersion;
385 
386   const auto target_crc = target.GetCrc();
387   if (!target_crc) {
388     return Error(target_crc.GetError(), "failed to get zip CRC for '%s'", target.GetPath().data());
389   }
390   header->target_crc_ = *target_crc;
391 
392   const auto overlay_crc = overlay.GetCrc();
393   if (!overlay_crc) {
394     return Error(overlay_crc.GetError(), "failed to get zip CRC for '%s'",
395                  overlay.GetPath().data());
396   }
397   header->overlay_crc_ = *overlay_crc;
398 
399   header->fulfilled_policies_ = fulfilled_policies;
400   header->enforce_overlayable_ = enforce_overlayable;
401   header->target_path_ = target.GetPath();
402   header->overlay_path_ = overlay.GetPath();
403   header->overlay_name_ = overlay_name;
404 
405   auto info = overlay.FindOverlayInfo(overlay_name);
406   if (!info) {
407     return Error(info.GetError(), "failed to get overlay info for '%s'", overlay.GetPath().data());
408   }
409 
410   LogInfo log_info;
411   auto resource_mapping = ResourceMapping::FromContainers(
412       target, overlay, *info, fulfilled_policies, enforce_overlayable, log_info);
413   if (!resource_mapping) {
414     return Error(resource_mapping.GetError(), "failed to generate resource map for '%s'",
415                  overlay.GetPath().data());
416   }
417 
418   auto idmap_data = IdmapData::FromResourceMapping(*resource_mapping);
419   if (!idmap_data) {
420     return idmap_data.GetError();
421   }
422 
423   std::unique_ptr<Idmap> idmap(new Idmap());
424   header->debug_info_ = log_info.GetString();
425   idmap->header_ = std::move(header);
426   idmap->data_.push_back(std::move(*idmap_data));
427 
428   return {std::move(idmap)};
429 }
430 
accept(Visitor * v) const431 void IdmapHeader::accept(Visitor* v) const {
432   assert(v != nullptr);
433   v->visit(*this);
434 }
435 
accept(Visitor * v) const436 void IdmapData::Header::accept(Visitor* v) const {
437   assert(v != nullptr);
438   v->visit(*this);
439 }
440 
accept(Visitor * v) const441 void IdmapData::accept(Visitor* v) const {
442   assert(v != nullptr);
443   header_->accept(v);
444   v->visit(*this);
445 }
446 
accept(Visitor * v) const447 void Idmap::accept(Visitor* v) const {
448   assert(v != nullptr);
449   header_->accept(v);
450   v->visit(*this);
451   auto end = data_.cend();
452   for (auto iter = data_.cbegin(); iter != end; ++iter) {
453     (*iter)->accept(v);
454   }
455 }
456 
457 }  // namespace android::idmap2
458