• 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 IdmapConstraints> IdmapConstraints::FromBinaryStream(std::istream& stream) {
186     auto idmap_constraints = std::make_unique<IdmapConstraints>();
187     uint32_t count = 0;
188     if (!Read32(stream, &count)) {
189         return nullptr;
190     }
191     for (size_t i = 0; i < count; i++) {
192         IdmapConstraint constraint{};
193         if (!Read32(stream, &constraint.constraint_type)) {
194             return nullptr;
195         }
196         if (!Read32(stream, &constraint.constraint_value)) {
197             return nullptr;
198         }
199         idmap_constraints->constraints.insert(constraint);
200     }
201 
202     return idmap_constraints;
203 }
204 
FromBinaryStream(std::istream & stream)205 std::unique_ptr<const IdmapData::Header> IdmapData::Header::FromBinaryStream(std::istream& stream) {
206   std::unique_ptr<IdmapData::Header> idmap_data_header(new IdmapData::Header());
207   if (!Read32(stream, &idmap_data_header->target_entry_count) ||
208       !Read32(stream, &idmap_data_header->target_entry_inline_count) ||
209       !Read32(stream, &idmap_data_header->target_entry_inline_value_count) ||
210       !Read32(stream, &idmap_data_header->config_count) ||
211       !Read32(stream, &idmap_data_header->overlay_entry_count) ||
212       !Read32(stream, &idmap_data_header->string_pool_index_offset)) {
213     return nullptr;
214   }
215 
216   return std::move(idmap_data_header);
217 }
218 
FromBinaryStream(std::istream & stream)219 std::unique_ptr<const IdmapData> IdmapData::FromBinaryStream(std::istream& stream) {
220   std::unique_ptr<IdmapData> data(new IdmapData());
221   data->header_ = IdmapData::Header::FromBinaryStream(stream);
222   if (!data->header_) {
223     return nullptr;
224   }
225 
226   // Read the mapping of target resource id to overlay resource value.
227   data->target_entries_.resize(data->header_->GetTargetEntryCount());
228   for (size_t i = 0; i < data->header_->GetTargetEntryCount(); i++) {
229     if (!Read32(stream, &data->target_entries_[i].target_id)) {
230       return nullptr;
231     }
232   }
233   for (size_t i = 0; i < data->header_->GetTargetEntryCount(); i++) {
234     if (!Read32(stream, &data->target_entries_[i].overlay_id)) {
235       return nullptr;
236     }
237   }
238 
239   // Read the mapping of target resource id to inline overlay values.
240   struct TargetInlineEntryHeader {
241     ResourceId target_id;
242     uint32_t values_offset;
243     uint32_t values_count;
244   };
245   std::vector<TargetInlineEntryHeader> target_inline_entries(
246       data->header_->GetTargetInlineEntryCount());
247   for (size_t i = 0; i < data->header_->GetTargetInlineEntryCount(); i++) {
248     if (!Read32(stream, &target_inline_entries[i].target_id)) {
249       return nullptr;
250     }
251   }
252   for (size_t i = 0; i < data->header_->GetTargetInlineEntryCount(); i++) {
253     if (!Read32(stream, &target_inline_entries[i].values_offset) ||
254         !Read32(stream, &target_inline_entries[i].values_count)) {
255       return nullptr;
256     }
257   }
258 
259   // Read the inline overlay resource values
260   struct TargetValueHeader {
261     uint32_t config_index;
262     DataType data_type;
263     DataValue data_value;
264   };
265   std::vector<TargetValueHeader> target_values(data->header_->GetTargetInlineEntryValueCount());
266   for (size_t i = 0; i < data->header_->GetTargetInlineEntryValueCount(); i++) {
267     auto& value = target_values[i];
268     if (!Read32(stream, &value.config_index)) {
269       return nullptr;
270     }
271     // skip the padding
272     stream.seekg(3, std::ios::cur);
273     if (!Read8(stream, &value.data_type) || !Read32(stream, &value.data_value)) {
274       return nullptr;
275     }
276   }
277 
278   // Read the configurations
279   std::vector<ConfigDescription> configurations(data->header_->GetConfigCount());
280   if (!configurations.empty()) {
281     if (!stream.read(reinterpret_cast<char*>(&configurations.front()),
282                      sizeof(configurations.front()) * configurations.size())) {
283       return nullptr;
284     }
285   }
286 
287   // Construct complete target inline entries
288   data->target_inline_entries_.reserve(target_inline_entries.size());
289   for (auto&& entry_header : target_inline_entries) {
290     TargetInlineEntry& entry = data->target_inline_entries_.emplace_back();
291     entry.target_id = entry_header.target_id;
292     for (size_t i = 0; i < entry_header.values_count; i++) {
293       const auto& value_header = target_values[entry_header.values_offset + i];
294       const auto& config = configurations[value_header.config_index];
295       auto& value = entry.values[config];
296       value.data_type = value_header.data_type;
297       value.data_value = value_header.data_value;
298     }
299   }
300 
301   // Read the mapping of overlay resource id to target resource id.
302   data->overlay_entries_.resize(data->header_->GetOverlayEntryCount());
303   for (size_t i = 0; i < data->header_->GetOverlayEntryCount(); i++) {
304     if (!Read32(stream, &data->overlay_entries_[i].overlay_id)) {
305       return nullptr;
306     }
307   }
308   for (size_t i = 0; i < data->header_->GetOverlayEntryCount(); i++) {
309     if (!Read32(stream, &data->overlay_entries_[i].target_id)) {
310       return nullptr;
311     }
312   }
313 
314   // Read raw string pool bytes.
315   if (!ReadString(stream, &data->string_pool_data_)) {
316     return nullptr;
317   }
318   return std::move(data);
319 }
320 
CanonicalIdmapPathFor(std::string_view absolute_dir,std::string_view absolute_apk_path)321 std::string Idmap::CanonicalIdmapPathFor(std::string_view absolute_dir,
322                                          std::string_view absolute_apk_path) {
323   assert(absolute_dir.size() > 0 && absolute_dir[0] == "/");
324   assert(absolute_apk_path.size() > 0 && absolute_apk_path[0] == "/");
325   std::string copy(absolute_apk_path.begin() + 1, absolute_apk_path.end());
326   replace(copy.begin(), copy.end(), '/', '@');
327   return fmt::format("{}/{}@idmap", absolute_dir, copy);
328 }
329 
FromBinaryStream(std::istream & stream)330 Result<std::unique_ptr<const Idmap>> Idmap::FromBinaryStream(std::istream& stream) {
331   SYSTRACE << "Idmap::FromBinaryStream";
332   std::unique_ptr<Idmap> idmap(new Idmap());
333 
334   idmap->header_ = IdmapHeader::FromBinaryStream(stream);
335   if (!idmap->header_) {
336     return Error("failed to parse idmap header");
337   }
338   idmap->constraints_ = IdmapConstraints::FromBinaryStream(stream);
339   if (!idmap->constraints_) {
340     return Error("failed to parse idmap constraints");
341   }
342 
343   // idmap version 0x01 does not specify the number of data blocks that follow
344   // the idmap header; assume exactly one data block
345   for (int i = 0; i < 1; i++) {
346     std::unique_ptr<const IdmapData> data = IdmapData::FromBinaryStream(stream);
347     if (!data) {
348       return Error("failed to parse data block %d", i);
349     }
350     idmap->data_.push_back(std::move(data));
351   }
352 
353   return {std::move(idmap)};
354 }
355 
FromResourceMapping(const ResourceMapping & resource_mapping)356 Result<std::unique_ptr<const IdmapData>> IdmapData::FromResourceMapping(
357     const ResourceMapping& resource_mapping) {
358   if (resource_mapping.GetTargetToOverlayMap().empty()) {
359     return Error("no resources were overlaid");
360   }
361 
362   std::unique_ptr<IdmapData> data(new IdmapData());
363   data->string_pool_data_ = std::string(resource_mapping.GetStringPoolData());
364   uint32_t inline_value_count = 0;
365   std::set<std::string_view> config_set;
366   for (const auto& mapping : resource_mapping.GetTargetToOverlayMap()) {
367     if (auto overlay_resource = std::get_if<ResourceId>(&mapping.second)) {
368       data->target_entries_.push_back({mapping.first, *overlay_resource});
369     } else {
370       std::map<ConfigDescription, TargetValue> values;
371       for (const auto& [config, value] : std::get<ConfigMap>(mapping.second)) {
372         config_set.insert(config);
373         ConfigDescription cd;
374         if (!ConfigDescription::Parse(config, &cd)) {
375           return Error("failed to parse configuration string '%s'", config.c_str());
376         }
377         values[cd] = value;
378         inline_value_count++;
379       }
380       data->target_inline_entries_.push_back({mapping.first, std::move(values)});
381     }
382   }
383 
384   for (const auto& mapping : resource_mapping.GetOverlayToTargetMap()) {
385     data->overlay_entries_.emplace_back(IdmapData::OverlayEntry{mapping.first, mapping.second});
386   }
387 
388   std::unique_ptr<IdmapData::Header> data_header(new IdmapData::Header());
389   data_header->target_entry_count = static_cast<uint32_t>(data->target_entries_.size());
390   data_header->target_entry_inline_count =
391       static_cast<uint32_t>(data->target_inline_entries_.size());
392   data_header->target_entry_inline_value_count = inline_value_count;
393   data_header->config_count = config_set.size();
394   data_header->overlay_entry_count = static_cast<uint32_t>(data->overlay_entries_.size());
395   data_header->string_pool_index_offset = resource_mapping.GetStringPoolOffset();
396   data->header_ = std::move(data_header);
397   return {std::move(data)};
398 }
399 
FromContainers(const TargetResourceContainer & target,const OverlayResourceContainer & overlay,const std::string & overlay_name,const PolicyBitmask & fulfilled_policies,bool enforce_overlayable,std::unique_ptr<const IdmapConstraints> && constraints)400 Result<std::unique_ptr<const Idmap>> Idmap::FromContainers(const TargetResourceContainer& target,
401     const OverlayResourceContainer& overlay, const std::string& overlay_name,
402     const PolicyBitmask& fulfilled_policies, bool enforce_overlayable,
403     std::unique_ptr<const IdmapConstraints>&& constraints) {
404   SYSTRACE << "Idmap::FromApkAssets";
405   std::unique_ptr<IdmapHeader> header(new IdmapHeader());
406   header->magic_ = kIdmapMagic;
407   header->version_ = kIdmapCurrentVersion;
408 
409   const auto target_crc = target.GetCrc();
410   if (!target_crc) {
411     return Error(target_crc.GetError(), "failed to get zip CRC for '%s'", target.GetPath().data());
412   }
413   header->target_crc_ = *target_crc;
414 
415   const auto overlay_crc = overlay.GetCrc();
416   if (!overlay_crc) {
417     return Error(overlay_crc.GetError(), "failed to get zip CRC for '%s'",
418                  overlay.GetPath().data());
419   }
420   header->overlay_crc_ = *overlay_crc;
421 
422   header->fulfilled_policies_ = fulfilled_policies;
423   header->enforce_overlayable_ = enforce_overlayable;
424   header->target_path_ = target.GetPath();
425   header->overlay_path_ = overlay.GetPath();
426   header->overlay_name_ = overlay_name;
427 
428   auto info = overlay.FindOverlayInfo(overlay_name);
429   if (!info) {
430     return Error(info.GetError(), "failed to get overlay info for '%s'", overlay.GetPath().data());
431   }
432 
433   LogInfo log_info;
434   auto resource_mapping = ResourceMapping::FromContainers(
435       target, overlay, *info, fulfilled_policies, enforce_overlayable, log_info);
436   if (!resource_mapping) {
437     return Error(resource_mapping.GetError(), "failed to generate resource map for '%s'",
438                  overlay.GetPath().data());
439   }
440 
441   auto idmap_data = IdmapData::FromResourceMapping(*resource_mapping);
442   if (!idmap_data) {
443     return idmap_data.GetError();
444   }
445 
446   std::unique_ptr<Idmap> idmap(new Idmap());
447   header->debug_info_ = log_info.GetString();
448   idmap->header_ = std::move(header);
449   idmap->data_.push_back(std::move(*idmap_data));
450   if (constraints == nullptr) {
451     idmap->constraints_ = std::make_unique<IdmapConstraints>();
452   } else {
453     idmap->constraints_ = std::move(constraints);
454   }
455 
456   return {std::move(idmap)};
457 }
458 
accept(Visitor * v) const459 void IdmapHeader::accept(Visitor* v) const {
460   assert(v != nullptr);
461   v->visit(*this);
462 }
463 
accept(Visitor * v) const464 void IdmapConstraints::accept(Visitor* v) const {
465   assert(v != nullptr);
466   v->visit(*this);
467 }
468 
accept(Visitor * v) const469 void IdmapData::Header::accept(Visitor* v) const {
470   assert(v != nullptr);
471   v->visit(*this);
472 }
473 
accept(Visitor * v) const474 void IdmapData::accept(Visitor* v) const {
475   assert(v != nullptr);
476   header_->accept(v);
477   v->visit(*this);
478 }
479 
accept(Visitor * v) const480 void Idmap::accept(Visitor* v) const {
481   assert(v != nullptr);
482   header_->accept(v);
483   constraints_->accept(v);
484   v->visit(*this);
485   auto end = data_.cend();
486   for (auto iter = data_.cbegin(); iter != end; ++iter) {
487     (*iter)->accept(v);
488   }
489 }
490 
491 }  // namespace android::idmap2
492