• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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   for (size_t i = 0; i < data->header_->GetTargetEntryCount(); i++) {
208     TargetEntry target_entry{};
209     if (!Read32(stream, &target_entry.target_id) || !Read32(stream, &target_entry.overlay_id)) {
210       return nullptr;
211     }
212     data->target_entries_.emplace_back(target_entry);
213   }
214 
215   // Read the mapping of target resource id to inline overlay values.
216   std::vector<std::tuple<TargetInlineEntry, uint32_t, uint32_t>> target_inline_entries;
217   for (size_t i = 0; i < data->header_->GetTargetInlineEntryCount(); i++) {
218     TargetInlineEntry target_entry{};
219     uint32_t entry_offset;
220     uint32_t entry_count;
221     if (!Read32(stream, &target_entry.target_id) || !Read32(stream, &entry_offset)
222         || !Read32(stream, &entry_count)) {
223       return nullptr;
224     }
225     target_inline_entries.emplace_back(target_entry, entry_offset, entry_count);
226   }
227 
228   // Read the inline overlay resource values
229   std::vector<std::pair<uint32_t, TargetValue>> target_values;
230   uint8_t unused1;
231   uint16_t unused2;
232   for (size_t i = 0; i < data->header_->GetTargetInlineEntryValueCount(); i++) {
233     uint32_t config_index;
234     if (!Read32(stream, &config_index)) {
235       return nullptr;
236     }
237     TargetValue value;
238     if (!Read16(stream, &unused2)
239         || !Read8(stream, &unused1)
240         || !Read8(stream, &value.data_type)
241         || !Read32(stream, &value.data_value)) {
242       return nullptr;
243     }
244     target_values.emplace_back(config_index, value);
245   }
246 
247   // Read the configurations
248   std::vector<ConfigDescription> configurations;
249   for (size_t i = 0; i < data->header_->GetConfigCount(); i++) {
250     ConfigDescription cd;
251     if (!stream.read(reinterpret_cast<char*>(&cd), sizeof(ConfigDescription))) {
252       return nullptr;
253     }
254     configurations.emplace_back(cd);
255   }
256 
257   // Construct complete target inline entries
258   for (auto [target_entry, entry_offset, entry_count] : target_inline_entries) {
259     for(size_t i = 0; i < entry_count; i++) {
260       const auto& target_value = target_values[entry_offset + i];
261       const auto& config = configurations[target_value.first];
262       target_entry.values[config] = target_value.second;
263     }
264     data->target_inline_entries_.emplace_back(target_entry);
265   }
266 
267   // Read the mapping of overlay resource id to target resource id.
268   for (size_t i = 0; i < data->header_->GetOverlayEntryCount(); i++) {
269     OverlayEntry overlay_entry{};
270     if (!Read32(stream, &overlay_entry.overlay_id) || !Read32(stream, &overlay_entry.target_id)) {
271       return nullptr;
272     }
273     data->overlay_entries_.emplace_back(overlay_entry);
274   }
275 
276   // Read raw string pool bytes.
277   if (!ReadString(stream, &data->string_pool_data_)) {
278     return nullptr;
279   }
280   return std::move(data);
281 }
282 
CanonicalIdmapPathFor(std::string_view absolute_dir,std::string_view absolute_apk_path)283 std::string Idmap::CanonicalIdmapPathFor(std::string_view absolute_dir,
284                                          std::string_view absolute_apk_path) {
285   assert(absolute_dir.size() > 0 && absolute_dir[0] == "/");
286   assert(absolute_apk_path.size() > 0 && absolute_apk_path[0] == "/");
287   std::string copy(absolute_apk_path.begin() + 1, absolute_apk_path.end());
288   replace(copy.begin(), copy.end(), '/', '@');
289   return fmt::format("{}/{}@idmap", absolute_dir, copy);
290 }
291 
FromBinaryStream(std::istream & stream)292 Result<std::unique_ptr<const Idmap>> Idmap::FromBinaryStream(std::istream& stream) {
293   SYSTRACE << "Idmap::FromBinaryStream";
294   std::unique_ptr<Idmap> idmap(new Idmap());
295 
296   idmap->header_ = IdmapHeader::FromBinaryStream(stream);
297   if (!idmap->header_) {
298     return Error("failed to parse idmap header");
299   }
300 
301   // idmap version 0x01 does not specify the number of data blocks that follow
302   // the idmap header; assume exactly one data block
303   for (int i = 0; i < 1; i++) {
304     std::unique_ptr<const IdmapData> data = IdmapData::FromBinaryStream(stream);
305     if (!data) {
306       return Error("failed to parse data block %d", i);
307     }
308     idmap->data_.push_back(std::move(data));
309   }
310 
311   return {std::move(idmap)};
312 }
313 
FromResourceMapping(const ResourceMapping & resource_mapping)314 Result<std::unique_ptr<const IdmapData>> IdmapData::FromResourceMapping(
315     const ResourceMapping& resource_mapping) {
316   if (resource_mapping.GetTargetToOverlayMap().empty()) {
317     return Error("no resources were overlaid");
318   }
319 
320   std::unique_ptr<IdmapData> data(new IdmapData());
321   data->string_pool_data_ = std::string(resource_mapping.GetStringPoolData());
322   uint32_t inline_value_count = 0;
323   std::set<std::string> config_set;
324   for (const auto& mapping : resource_mapping.GetTargetToOverlayMap()) {
325     if (auto overlay_resource = std::get_if<ResourceId>(&mapping.second)) {
326       data->target_entries_.push_back({mapping.first, *overlay_resource});
327     } else {
328       std::map<ConfigDescription, TargetValue> values;
329       for (const auto& [config, value] : std::get<ConfigMap>(mapping.second)) {
330         config_set.insert(config);
331         ConfigDescription cd;
332         ConfigDescription::Parse(config, &cd);
333         values[cd] = value;
334         inline_value_count++;
335       }
336       data->target_inline_entries_.push_back({mapping.first, std::move(values)});
337     }
338   }
339 
340   for (const auto& mapping : resource_mapping.GetOverlayToTargetMap()) {
341     data->overlay_entries_.emplace_back(IdmapData::OverlayEntry{mapping.first, mapping.second});
342   }
343 
344   std::unique_ptr<IdmapData::Header> data_header(new IdmapData::Header());
345   data_header->target_entry_count = static_cast<uint32_t>(data->target_entries_.size());
346   data_header->target_entry_inline_count =
347       static_cast<uint32_t>(data->target_inline_entries_.size());
348   data_header->target_entry_inline_value_count = inline_value_count;
349   data_header->config_count = config_set.size();
350   data_header->overlay_entry_count = static_cast<uint32_t>(data->overlay_entries_.size());
351   data_header->string_pool_index_offset = resource_mapping.GetStringPoolOffset();
352   data->header_ = std::move(data_header);
353   return {std::move(data)};
354 }
355 
FromContainers(const TargetResourceContainer & target,const OverlayResourceContainer & overlay,const std::string & overlay_name,const PolicyBitmask & fulfilled_policies,bool enforce_overlayable)356 Result<std::unique_ptr<const Idmap>> Idmap::FromContainers(const TargetResourceContainer& target,
357                                                            const OverlayResourceContainer& overlay,
358                                                            const std::string& overlay_name,
359                                                            const PolicyBitmask& fulfilled_policies,
360                                                            bool enforce_overlayable) {
361   SYSTRACE << "Idmap::FromApkAssets";
362   std::unique_ptr<IdmapHeader> header(new IdmapHeader());
363   header->magic_ = kIdmapMagic;
364   header->version_ = kIdmapCurrentVersion;
365 
366   const auto target_crc = target.GetCrc();
367   if (!target_crc) {
368     return Error(target_crc.GetError(), "failed to get zip CRC for '%s'", target.GetPath().data());
369   }
370   header->target_crc_ = *target_crc;
371 
372   const auto overlay_crc = overlay.GetCrc();
373   if (!overlay_crc) {
374     return Error(overlay_crc.GetError(), "failed to get zip CRC for '%s'",
375                  overlay.GetPath().data());
376   }
377   header->overlay_crc_ = *overlay_crc;
378 
379   header->fulfilled_policies_ = fulfilled_policies;
380   header->enforce_overlayable_ = enforce_overlayable;
381   header->target_path_ = target.GetPath();
382   header->overlay_path_ = overlay.GetPath();
383   header->overlay_name_ = overlay_name;
384 
385   auto info = overlay.FindOverlayInfo(overlay_name);
386   if (!info) {
387     return Error(info.GetError(), "failed to get overlay info for '%s'", overlay.GetPath().data());
388   }
389 
390   LogInfo log_info;
391   auto resource_mapping = ResourceMapping::FromContainers(
392       target, overlay, *info, fulfilled_policies, enforce_overlayable, log_info);
393   if (!resource_mapping) {
394     return Error(resource_mapping.GetError(), "failed to generate resource map for '%s'",
395                  overlay.GetPath().data());
396   }
397 
398   auto idmap_data = IdmapData::FromResourceMapping(*resource_mapping);
399   if (!idmap_data) {
400     return idmap_data.GetError();
401   }
402 
403   std::unique_ptr<Idmap> idmap(new Idmap());
404   header->debug_info_ = log_info.GetString();
405   idmap->header_ = std::move(header);
406   idmap->data_.push_back(std::move(*idmap_data));
407 
408   return {std::move(idmap)};
409 }
410 
accept(Visitor * v) const411 void IdmapHeader::accept(Visitor* v) const {
412   assert(v != nullptr);
413   v->visit(*this);
414 }
415 
accept(Visitor * v) const416 void IdmapData::Header::accept(Visitor* v) const {
417   assert(v != nullptr);
418   v->visit(*this);
419 }
420 
accept(Visitor * v) const421 void IdmapData::accept(Visitor* v) const {
422   assert(v != nullptr);
423   header_->accept(v);
424   v->visit(*this);
425 }
426 
accept(Visitor * v) const427 void Idmap::accept(Visitor* v) const {
428   assert(v != nullptr);
429   header_->accept(v);
430   v->visit(*this);
431   auto end = data_.cend();
432   for (auto iter = data_.cbegin(); iter != end; ++iter) {
433     (*iter)->accept(v);
434   }
435 }
436 
437 }  // namespace android::idmap2
438