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