• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 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 #define ATRACE_TAG ATRACE_TAG_RESOURCES
18 
19 #include "androidfw/LoadedArsc.h"
20 
21 #include <algorithm>
22 #include <cstddef>
23 #include <limits>
24 
25 #include "android-base/logging.h"
26 #include "android-base/stringprintf.h"
27 #include "utils/ByteOrder.h"
28 #include "utils/Trace.h"
29 
30 #ifdef _WIN32
31 #ifdef ERROR
32 #undef ERROR
33 #endif
34 #endif
35 
36 #include "androidfw/Chunk.h"
37 #include "androidfw/ResourceUtils.h"
38 #include "androidfw/Util.h"
39 
40 using android::base::StringPrintf;
41 
42 namespace android {
43 
44 constexpr const static int kFrameworkPackageId = 0x01;
45 constexpr const static int kAppPackageId = 0x7f;
46 
47 namespace {
48 
49 // Builder that helps accumulate Type structs and then create a single
50 // contiguous block of memory to store both the TypeSpec struct and
51 // the Type structs.
52 struct TypeSpecBuilder {
TypeSpecBuilderandroid::__anon4b8180c70111::TypeSpecBuilder53   explicit TypeSpecBuilder(incfs::verified_map_ptr<ResTable_typeSpec> header) : header_(header) {}
54 
AddTypeandroid::__anon4b8180c70111::TypeSpecBuilder55   void AddType(incfs::verified_map_ptr<ResTable_type> type) {
56     TypeSpec::TypeEntry& entry = type_entries.emplace_back();
57     entry.config.copyFromDtoH(type->config);
58     entry.type = type;
59   }
60 
Buildandroid::__anon4b8180c70111::TypeSpecBuilder61   TypeSpec Build() {
62     return {header_, std::move(type_entries)};
63   }
64 
65  private:
66   DISALLOW_COPY_AND_ASSIGN(TypeSpecBuilder);
67 
68   incfs::verified_map_ptr<ResTable_typeSpec> header_;
69   std::vector<TypeSpec::TypeEntry> type_entries;
70 };
71 
72 }  // namespace
73 
74 // Precondition: The header passed in has already been verified, so reading any fields and trusting
75 // the ResChunk_header is safe.
VerifyResTableType(incfs::map_ptr<ResTable_type> header)76 static bool VerifyResTableType(incfs::map_ptr<ResTable_type> header) {
77   if (header->id == 0) {
78     LOG(ERROR) << "RES_TABLE_TYPE_TYPE has invalid ID 0.";
79     return false;
80   }
81 
82   const size_t entry_count = dtohl(header->entryCount);
83   if (entry_count > std::numeric_limits<uint16_t>::max()) {
84     LOG(ERROR) << "RES_TABLE_TYPE_TYPE has too many entries (" << entry_count << ").";
85     return false;
86   }
87 
88   // Make sure that there is enough room for the entry offsets.
89   const size_t offsets_offset = dtohs(header->header.headerSize);
90   const size_t entries_offset = dtohl(header->entriesStart);
91   const size_t offsets_length = header->flags & ResTable_type::FLAG_OFFSET16
92                                     ? sizeof(uint16_t) * entry_count
93                                     : sizeof(uint32_t) * entry_count;
94 
95   if (offsets_offset > entries_offset || entries_offset - offsets_offset < offsets_length) {
96     LOG(ERROR) << "RES_TABLE_TYPE_TYPE entry offsets overlap actual entry data.";
97     return false;
98   }
99 
100   if (entries_offset > dtohl(header->header.size)) {
101     LOG(ERROR) << "RES_TABLE_TYPE_TYPE entry offsets extend beyond chunk.";
102     return false;
103   }
104 
105   if (entries_offset & 0x03U) {
106     LOG(ERROR) << "RES_TABLE_TYPE_TYPE entries start at unaligned address.";
107     return false;
108   }
109   return true;
110 }
111 
112 static base::expected<incfs::verified_map_ptr<ResTable_entry>, NullOrIOError>
VerifyResTableEntry(incfs::verified_map_ptr<ResTable_type> type,uint32_t entry_offset)113 VerifyResTableEntry(incfs::verified_map_ptr<ResTable_type> type, uint32_t entry_offset) {
114   // Check that the offset is aligned.
115   if (UNLIKELY(entry_offset & 0x03U)) {
116     LOG(ERROR) << "Entry at offset " << entry_offset << " is not 4-byte aligned.";
117     return base::unexpected(std::nullopt);
118   }
119 
120   // Check that the offset doesn't overflow.
121   if (UNLIKELY(entry_offset > std::numeric_limits<uint32_t>::max() - dtohl(type->entriesStart))) {
122     // Overflow in offset.
123     LOG(ERROR) << "Entry at offset " << entry_offset << " is too large.";
124     return base::unexpected(std::nullopt);
125   }
126 
127   const size_t chunk_size = dtohl(type->header.size);
128 
129   entry_offset += dtohl(type->entriesStart);
130   if (UNLIKELY(entry_offset > chunk_size - sizeof(ResTable_entry))) {
131     LOG(ERROR) << "Entry at offset " << entry_offset
132                << " is too large. No room for ResTable_entry.";
133     return base::unexpected(std::nullopt);
134   }
135 
136   auto entry = type.offset(entry_offset).convert<ResTable_entry>();
137   if (UNLIKELY(!entry)) {
138     return base::unexpected(IOError::PAGES_MISSING);
139   }
140 
141   const size_t entry_size = entry->size();
142   if (UNLIKELY(entry_size < sizeof(entry.value()))) {
143     LOG(ERROR) << "ResTable_entry size " << entry_size << " at offset " << entry_offset
144                << " is too small.";
145     return base::unexpected(std::nullopt);
146   }
147 
148   if (UNLIKELY(entry_size > chunk_size || entry_offset > chunk_size - entry_size)) {
149     LOG(ERROR) << "ResTable_entry size " << entry_size << " at offset " << entry_offset
150                << " is too large.";
151     return base::unexpected(std::nullopt);
152   }
153 
154   // If entry is compact, value is already encoded, and a compact entry
155   // cannot be a map_entry, we are done verifying
156   if (entry->is_compact())
157     return entry.verified();
158 
159   if (entry_size < sizeof(ResTable_map_entry)) {
160     // There needs to be room for one Res_value struct.
161     if (UNLIKELY(entry_offset + entry_size > chunk_size - sizeof(Res_value))) {
162       LOG(ERROR) << "No room for Res_value after ResTable_entry at offset " << entry_offset
163                  << " for type " << (int)type->id << ".";
164       return base::unexpected(std::nullopt);
165     }
166 
167     auto value = entry.offset(entry_size).convert<Res_value>();
168     if (UNLIKELY(!value)) {
169        return base::unexpected(IOError::PAGES_MISSING);
170     }
171 
172     const size_t value_size = dtohs(value->size);
173     if (UNLIKELY(value_size < sizeof(Res_value))) {
174       LOG(ERROR) << "Res_value at offset " << entry_offset << " is too small.";
175       return base::unexpected(std::nullopt);
176     }
177 
178     if (UNLIKELY(value_size > chunk_size || entry_offset + entry_size > chunk_size - value_size)) {
179       LOG(ERROR) << "Res_value size " << value_size << " at offset " << entry_offset
180                  << " is too large.";
181       return base::unexpected(std::nullopt);
182     }
183   } else {
184     auto map = entry.convert<ResTable_map_entry>();
185     if (UNLIKELY(!map)) {
186       return base::unexpected(IOError::PAGES_MISSING);
187     }
188 
189     const size_t map_entry_count = dtohl(map->count);
190     size_t map_entries_start = entry_offset + entry_size;
191     if (UNLIKELY(map_entries_start & 0x03U)) {
192       LOG(ERROR) << "Map entries at offset " << entry_offset << " start at unaligned offset.";
193       return base::unexpected(std::nullopt);
194     }
195 
196     // Each entry is sizeof(ResTable_map) big.
197     if (UNLIKELY(map_entry_count > ((chunk_size - map_entries_start) / sizeof(ResTable_map)))) {
198       LOG(ERROR) << "Too many map entries in ResTable_map_entry at offset " << entry_offset << ".";
199       return base::unexpected(std::nullopt);
200     }
201   }
202   return entry.verified();
203 }
204 
iterator(const LoadedPackage * lp,size_t ti,size_t ei)205 LoadedPackage::iterator::iterator(const LoadedPackage* lp, size_t ti, size_t ei)
206     : loadedPackage_(lp),
207       typeIndex_(ti),
208       entryIndex_(ei),
209       typeIndexEnd_(lp->resource_ids_.size() + 1) {
210   while (typeIndex_ < typeIndexEnd_ && loadedPackage_->resource_ids_[typeIndex_] == 0) {
211     typeIndex_++;
212   }
213 }
214 
operator ++()215 LoadedPackage::iterator& LoadedPackage::iterator::operator++() {
216   while (typeIndex_ < typeIndexEnd_) {
217     if (entryIndex_ + 1 < loadedPackage_->resource_ids_[typeIndex_]) {
218       entryIndex_++;
219       break;
220     }
221     entryIndex_ = 0;
222     typeIndex_++;
223     if (typeIndex_ < typeIndexEnd_ && loadedPackage_->resource_ids_[typeIndex_] != 0) {
224       break;
225     }
226   }
227   return *this;
228 }
229 
operator *() const230 uint32_t LoadedPackage::iterator::operator*() const {
231   if (typeIndex_ >= typeIndexEnd_) {
232     return 0;
233   }
234   return make_resid(loadedPackage_->package_id_, typeIndex_ + loadedPackage_->type_id_offset_,
235           entryIndex_);
236 }
237 
GetEntry(incfs::verified_map_ptr<ResTable_type> type_chunk,uint16_t entry_index)238 base::expected<incfs::verified_map_ptr<ResTable_entry>, NullOrIOError> LoadedPackage::GetEntry(
239     incfs::verified_map_ptr<ResTable_type> type_chunk, uint16_t entry_index) {
240   base::expected<uint32_t, NullOrIOError> entry_offset = GetEntryOffset(type_chunk, entry_index);
241   if (UNLIKELY(!entry_offset.has_value())) {
242     return base::unexpected(entry_offset.error());
243   }
244   return GetEntryFromOffset(type_chunk, entry_offset.value());
245 }
246 
GetEntryOffset(incfs::verified_map_ptr<ResTable_type> type_chunk,uint16_t entry_index)247 base::expected<uint32_t, NullOrIOError> LoadedPackage::GetEntryOffset(
248     incfs::verified_map_ptr<ResTable_type> type_chunk, uint16_t entry_index) {
249   // The configuration matches and is better than the previous selection.
250   // Find the entry value if it exists for this configuration.
251   const size_t entry_count = dtohl(type_chunk->entryCount);
252   const auto offsets = type_chunk.offset(dtohs(type_chunk->header.headerSize));
253 
254   // Check if there is the desired entry in this type.
255   if (type_chunk->flags & ResTable_type::FLAG_SPARSE) {
256     // This is encoded as a sparse map, so perform a binary search.
257     bool error = false;
258     auto sparse_indices = offsets.convert<ResTable_sparseTypeEntry>().iterator();
259     auto sparse_indices_end = sparse_indices + entry_count;
260     auto result = std::lower_bound(sparse_indices, sparse_indices_end, entry_index,
261                                    [&error](const incfs::map_ptr<ResTable_sparseTypeEntry>& entry,
262                                             uint16_t entry_idx) {
263       if (UNLIKELY(!entry)) {
264         return error = true;
265       }
266       return dtohs(entry->idx) < entry_idx;
267     });
268 
269     if (result == sparse_indices_end) {
270       // No entry found.
271       return base::unexpected(std::nullopt);
272     }
273 
274     const incfs::verified_map_ptr<ResTable_sparseTypeEntry> entry = (*result).verified();
275     if (dtohs(entry->idx) != entry_index) {
276       if (error) {
277         return base::unexpected(IOError::PAGES_MISSING);
278       }
279       return base::unexpected(std::nullopt);
280     }
281 
282     // Extract the offset from the entry. Each offset must be a multiple of 4 so we store it as
283     // the real offset divided by 4.
284     return uint32_t{dtohs(entry->offset)} * 4u;
285   }
286 
287   // This type is encoded as a dense array.
288   if (entry_index >= entry_count) {
289     // This entry cannot be here.
290     return base::unexpected(std::nullopt);
291   }
292 
293   uint32_t result;
294 
295   if (type_chunk->flags & ResTable_type::FLAG_OFFSET16) {
296     const auto entry_offset_ptr = offsets.convert<uint16_t>() + entry_index;
297     if (UNLIKELY(!entry_offset_ptr)) {
298       return base::unexpected(IOError::PAGES_MISSING);
299     }
300     result = offset_from16(entry_offset_ptr.value());
301   } else {
302     const auto entry_offset_ptr = offsets.convert<uint32_t>() + entry_index;
303     if (UNLIKELY(!entry_offset_ptr)) {
304       return base::unexpected(IOError::PAGES_MISSING);
305     }
306     result = dtohl(entry_offset_ptr.value());
307   }
308 
309   if (result == ResTable_type::NO_ENTRY) {
310     return base::unexpected(std::nullopt);
311   }
312   return result;
313 }
314 
315 base::expected<incfs::verified_map_ptr<ResTable_entry>, NullOrIOError>
GetEntryFromOffset(incfs::verified_map_ptr<ResTable_type> type_chunk,uint32_t offset)316 LoadedPackage::GetEntryFromOffset(incfs::verified_map_ptr<ResTable_type> type_chunk,
317                                   uint32_t offset) {
318   auto valid = VerifyResTableEntry(type_chunk, offset);
319   if (UNLIKELY(!valid.has_value())) {
320     return base::unexpected(valid.error());
321   }
322   return valid;
323 }
324 
CollectConfigurations(bool exclude_mipmap,std::set<ResTable_config> * out_configs) const325 base::expected<std::monostate, IOError> LoadedPackage::CollectConfigurations(
326     bool exclude_mipmap, std::set<ResTable_config>* out_configs) const {
327   for (const auto& type_spec : type_specs_) {
328     if (exclude_mipmap) {
329       const int type_idx = type_spec.first - 1;
330       const auto type_name16 = type_string_pool_.stringAt(type_idx);
331       if (UNLIKELY(IsIOError(type_name16))) {
332         return base::unexpected(GetIOError(type_name16.error()));
333       }
334       if (type_name16.has_value()) {
335         if (strncmp16(type_name16->data(), u"mipmap", type_name16->size()) == 0) {
336           // This is a mipmap type, skip collection.
337           continue;
338         }
339       }
340 
341       const auto type_name = type_string_pool_.string8At(type_idx);
342       if (UNLIKELY(IsIOError(type_name))) {
343         return base::unexpected(GetIOError(type_name.error()));
344       }
345       if (type_name.has_value()) {
346         if (strncmp(type_name->data(), "mipmap", type_name->size()) == 0) {
347           // This is a mipmap type, skip collection.
348           continue;
349         }
350       }
351     }
352 
353     for (const auto& type_entry : type_spec.second.type_entries) {
354       out_configs->insert(type_entry.config);
355     }
356   }
357   return {};
358 }
359 
CollectLocales(bool canonicalize,std::set<std::string> * out_locales) const360 void LoadedPackage::CollectLocales(bool canonicalize, std::set<std::string>* out_locales) const {
361   char temp_locale[RESTABLE_MAX_LOCALE_LEN];
362   for (const auto& type_spec : type_specs_) {
363     for (const auto& type_entry : type_spec.second.type_entries) {
364       if (type_entry.config.locale != 0) {
365         type_entry.config.getBcp47Locale(temp_locale, canonicalize);
366         std::string locale(temp_locale);
367         out_locales->insert(std::move(locale));
368       }
369     }
370   }
371 }
372 
FindEntryByName(const std::u16string & type_name,const std::u16string & entry_name) const373 base::expected<uint32_t, NullOrIOError> LoadedPackage::FindEntryByName(
374     const std::u16string& type_name, const std::u16string& entry_name) const {
375   const base::expected<size_t, NullOrIOError> type_idx = type_string_pool_.indexOfString(
376       type_name.data(), type_name.size());
377   if (!type_idx.has_value()) {
378     return base::unexpected(type_idx.error());
379   }
380 
381   const base::expected<size_t, NullOrIOError> key_idx = key_string_pool_.indexOfString(
382       entry_name.data(), entry_name.size());
383   if (!key_idx.has_value()) {
384     return base::unexpected(key_idx.error());
385   }
386 
387   const TypeSpec* type_spec = GetTypeSpecByTypeIndex(*type_idx);
388   if (type_spec == nullptr) {
389     return base::unexpected(std::nullopt);
390   }
391 
392   for (const auto& type_entry : type_spec->type_entries) {
393     const incfs::verified_map_ptr<ResTable_type>& type = type_entry.type;
394 
395     const size_t entry_count = dtohl(type->entryCount);
396     const auto entry_offsets = type.offset(dtohs(type->header.headerSize));
397 
398     for (size_t entry_idx = 0; entry_idx < entry_count; entry_idx++) {
399       uint32_t offset;
400       uint16_t res_idx;
401       if (type->flags & ResTable_type::FLAG_SPARSE) {
402         auto sparse_entry = entry_offsets.convert<ResTable_sparseTypeEntry>() + entry_idx;
403         if (!sparse_entry) {
404           return base::unexpected(IOError::PAGES_MISSING);
405         }
406         offset = dtohs(sparse_entry->offset) * 4u;
407         res_idx  = dtohs(sparse_entry->idx);
408       } else if (type->flags & ResTable_type::FLAG_OFFSET16) {
409         auto entry = entry_offsets.convert<uint16_t>() + entry_idx;
410         if (!entry) {
411           return base::unexpected(IOError::PAGES_MISSING);
412         }
413         offset = offset_from16(entry.value());
414         res_idx = entry_idx;
415       } else {
416         auto entry = entry_offsets.convert<uint32_t>() + entry_idx;
417         if (!entry) {
418           return base::unexpected(IOError::PAGES_MISSING);
419         }
420         offset = dtohl(entry.value());
421         res_idx = entry_idx;
422       }
423 
424       if (offset != ResTable_type::NO_ENTRY) {
425         auto entry = type.offset(dtohl(type->entriesStart) + offset).convert<ResTable_entry>();
426         if (!entry) {
427           return base::unexpected(IOError::PAGES_MISSING);
428         }
429 
430         if (entry->key() == static_cast<uint32_t>(*key_idx)) {
431           // The package ID will be overridden by the caller (due to runtime assignment of package
432           // IDs for shared libraries).
433           return make_resid(0x00, *type_idx + type_id_offset_ + 1, res_idx);
434         }
435       }
436     }
437   }
438   return base::unexpected(std::nullopt);
439 }
440 
GetPackageById(uint8_t package_id) const441 const LoadedPackage* LoadedArsc::GetPackageById(uint8_t package_id) const {
442   for (const auto& loaded_package : packages_) {
443     if (loaded_package->GetPackageId() == package_id) {
444       return loaded_package.get();
445     }
446   }
447   return nullptr;
448 }
449 
Load(const Chunk & chunk,package_property_t property_flags)450 std::unique_ptr<const LoadedPackage> LoadedPackage::Load(const Chunk& chunk,
451                                                          package_property_t property_flags) {
452   ATRACE_NAME("LoadedPackage::Load");
453   std::unique_ptr<LoadedPackage> loaded_package(new LoadedPackage());
454 
455   // typeIdOffset was added at some point, but we still must recognize apps built before this
456   // was added.
457   constexpr size_t kMinPackageSize =
458       sizeof(ResTable_package) - sizeof(ResTable_package::typeIdOffset);
459   const incfs::map_ptr<ResTable_package> header = chunk.header<ResTable_package, kMinPackageSize>();
460   if (!header) {
461     LOG(ERROR) << "RES_TABLE_PACKAGE_TYPE too small.";
462     return {};
463   }
464 
465   if ((property_flags & PROPERTY_SYSTEM) != 0) {
466     loaded_package->property_flags_ |= PROPERTY_SYSTEM;
467   }
468 
469   if ((property_flags & PROPERTY_LOADER) != 0) {
470     loaded_package->property_flags_ |= PROPERTY_LOADER;
471   }
472 
473   if ((property_flags & PROPERTY_OVERLAY) != 0) {
474     // Overlay resources must have an exclusive resource id space for referencing internal
475     // resources.
476     loaded_package->property_flags_ |= PROPERTY_OVERLAY | PROPERTY_DYNAMIC;
477   }
478 
479   loaded_package->package_id_ = dtohl(header->id);
480   if (loaded_package->package_id_ == 0 ||
481       (loaded_package->package_id_ == kAppPackageId && (property_flags & PROPERTY_DYNAMIC) != 0)) {
482     loaded_package->property_flags_ |= PROPERTY_DYNAMIC;
483   }
484 
485   if (header->header.headerSize >= sizeof(ResTable_package)) {
486     uint32_t type_id_offset = dtohl(header->typeIdOffset);
487     if (type_id_offset > std::numeric_limits<uint8_t>::max()) {
488       LOG(ERROR) << "RES_TABLE_PACKAGE_TYPE type ID offset too large.";
489       return {};
490     }
491     loaded_package->type_id_offset_ = static_cast<int>(type_id_offset);
492   }
493 
494   util::ReadUtf16StringFromDevice(header->name, arraysize(header->name),
495                                   &loaded_package->package_name_);
496 
497   // A map of TypeSpec builders, each associated with an type index.
498   // We use these to accumulate the set of Types available for a TypeSpec, and later build a single,
499   // contiguous block of memory that holds all the Types together with the TypeSpec.
500   std::unordered_map<int, std::unique_ptr<TypeSpecBuilder>> type_builder_map;
501 
502   ChunkIterator iter(chunk.data_ptr(), chunk.data_size());
503   while (iter.HasNext()) {
504     const Chunk child_chunk = iter.Next();
505     switch (child_chunk.type()) {
506       case RES_STRING_POOL_TYPE: {
507         const auto pool_address = child_chunk.header<ResChunk_header>();
508         if (!pool_address) {
509           LOG(ERROR) << "RES_STRING_POOL_TYPE is incomplete due to incremental installation.";
510           return {};
511         }
512 
513         if (pool_address == header.offset(dtohl(header->typeStrings)).convert<ResChunk_header>()) {
514           // This string pool is the type string pool.
515           status_t err = loaded_package->type_string_pool_.setTo(
516               child_chunk.header<ResStringPool_header>(), child_chunk.size());
517           if (err != NO_ERROR) {
518             LOG(ERROR) << "RES_STRING_POOL_TYPE for types corrupt.";
519             return {};
520           }
521         } else if (pool_address == header.offset(dtohl(header->keyStrings))
522                                          .convert<ResChunk_header>()) {
523           // This string pool is the key string pool.
524           status_t err = loaded_package->key_string_pool_.setTo(
525               child_chunk.header<ResStringPool_header>(), child_chunk.size());
526           if (err != NO_ERROR) {
527             LOG(ERROR) << "RES_STRING_POOL_TYPE for keys corrupt.";
528             return {};
529           }
530         } else {
531           LOG(WARNING) << "Too many RES_STRING_POOL_TYPEs found in RES_TABLE_PACKAGE_TYPE.";
532         }
533       } break;
534 
535       case RES_TABLE_TYPE_SPEC_TYPE: {
536         const auto type_spec = child_chunk.header<ResTable_typeSpec>();
537         if (!type_spec) {
538           LOG(ERROR) << "RES_TABLE_TYPE_SPEC_TYPE too small.";
539           return {};
540         }
541 
542         if (type_spec->id == 0) {
543           LOG(ERROR) << "RES_TABLE_TYPE_SPEC_TYPE has invalid ID 0.";
544           return {};
545         }
546 
547         if (loaded_package->type_id_offset_ + static_cast<int>(type_spec->id) >
548             std::numeric_limits<uint8_t>::max()) {
549           LOG(ERROR) << "RES_TABLE_TYPE_SPEC_TYPE has out of range ID.";
550           return {};
551         }
552 
553         // The data portion of this chunk contains entry_count 32bit entries,
554         // each one representing a set of flags.
555         // Here we only validate that the chunk is well formed.
556         const size_t entry_count = dtohl(type_spec->entryCount);
557 
558         // There can only be 2^16 entries in a type, because that is the ID
559         // space for entries (EEEE) in the resource ID 0xPPTTEEEE.
560         if (entry_count > std::numeric_limits<uint16_t>::max()) {
561           LOG(ERROR) << "RES_TABLE_TYPE_SPEC_TYPE has too many entries (" << entry_count << ").";
562           return {};
563         }
564 
565         if (entry_count * sizeof(uint32_t) > chunk.data_size()) {
566           LOG(ERROR) << "RES_TABLE_TYPE_SPEC_TYPE too small to hold entries.";
567           return {};
568         }
569 
570         std::unique_ptr<TypeSpecBuilder>& builder_ptr = type_builder_map[type_spec->id];
571         if (builder_ptr == nullptr) {
572           builder_ptr = util::make_unique<TypeSpecBuilder>(type_spec.verified());
573           loaded_package->resource_ids_.set(type_spec->id, entry_count);
574         } else {
575           LOG(WARNING) << StringPrintf("RES_TABLE_TYPE_SPEC_TYPE already defined for ID %02x",
576                                        type_spec->id);
577         }
578       } break;
579 
580       case RES_TABLE_TYPE_TYPE: {
581         const auto type = child_chunk.header<ResTable_type, kResTableTypeMinSize>();
582         if (!type) {
583           LOG(ERROR) << "RES_TABLE_TYPE_TYPE too small.";
584           return {};
585         }
586 
587         if (!VerifyResTableType(type)) {
588           return {};
589         }
590 
591         // Type chunks must be preceded by their TypeSpec chunks.
592         std::unique_ptr<TypeSpecBuilder>& builder_ptr = type_builder_map[type->id];
593         if (builder_ptr != nullptr) {
594           builder_ptr->AddType(type.verified());
595         } else {
596           LOG(ERROR) << StringPrintf(
597               "RES_TABLE_TYPE_TYPE with ID %02x found without preceding RES_TABLE_TYPE_SPEC_TYPE.",
598               type->id);
599           return {};
600         }
601       } break;
602 
603       case RES_TABLE_LIBRARY_TYPE: {
604         const auto lib = child_chunk.header<ResTable_lib_header>();
605         if (!lib) {
606           LOG(ERROR) << "RES_TABLE_LIBRARY_TYPE too small.";
607           return {};
608         }
609 
610         if (child_chunk.data_size() / sizeof(ResTable_lib_entry) < dtohl(lib->count)) {
611           LOG(ERROR) << "RES_TABLE_LIBRARY_TYPE too small to hold entries.";
612           return {};
613         }
614 
615         loaded_package->dynamic_package_map_.reserve(dtohl(lib->count));
616 
617         const auto entry_begin = child_chunk.data_ptr().convert<ResTable_lib_entry>();
618         const auto entry_end = entry_begin + dtohl(lib->count);
619         for (auto entry_iter = entry_begin; entry_iter != entry_end; ++entry_iter) {
620           if (!entry_iter) {
621             return {};
622           }
623 
624           std::string package_name;
625           util::ReadUtf16StringFromDevice(entry_iter->packageName,
626                                           arraysize(entry_iter->packageName), &package_name);
627 
628           if (dtohl(entry_iter->packageId) >= std::numeric_limits<uint8_t>::max()) {
629             LOG(ERROR) << StringPrintf(
630                 "Package ID %02x in RES_TABLE_LIBRARY_TYPE too large for package '%s'.",
631                 dtohl(entry_iter->packageId), package_name.c_str());
632             return {};
633           }
634 
635           loaded_package->dynamic_package_map_.emplace_back(std::move(package_name),
636                                                             dtohl(entry_iter->packageId));
637         }
638       } break;
639 
640       case RES_TABLE_OVERLAYABLE_TYPE: {
641         const auto overlayable = child_chunk.header<ResTable_overlayable_header>();
642         if (!overlayable) {
643           LOG(ERROR) << "RES_TABLE_OVERLAYABLE_TYPE too small.";
644           return {};
645         }
646 
647         std::string name;
648         util::ReadUtf16StringFromDevice(overlayable->name, std::size(overlayable->name), &name);
649         std::string actor;
650         util::ReadUtf16StringFromDevice(overlayable->actor, std::size(overlayable->actor), &actor);
651         auto [name_to_actor_it, inserted] =
652             loaded_package->overlayable_map_.emplace(std::move(name), std::move(actor));
653         if (!inserted) {
654           LOG(ERROR) << "Multiple <overlayable> blocks with the same name '"
655                      << name_to_actor_it->first << "'.";
656           return {};
657         }
658 
659         // Iterate over the overlayable policy chunks contained within the overlayable chunk data
660         ChunkIterator overlayable_iter(child_chunk.data_ptr(), child_chunk.data_size());
661         while (overlayable_iter.HasNext()) {
662           const Chunk overlayable_child_chunk = overlayable_iter.Next();
663 
664           switch (overlayable_child_chunk.type()) {
665             case RES_TABLE_OVERLAYABLE_POLICY_TYPE: {
666               const auto policy_header =
667                   overlayable_child_chunk.header<ResTable_overlayable_policy_header>();
668               if (!policy_header) {
669                 LOG(ERROR) << "RES_TABLE_OVERLAYABLE_POLICY_TYPE too small.";
670                 return {};
671               }
672               if ((overlayable_child_chunk.data_size() / sizeof(ResTable_ref))
673                   < dtohl(policy_header->entry_count)) {
674                 LOG(ERROR) <<  "RES_TABLE_OVERLAYABLE_POLICY_TYPE too small to hold entries.";
675                 return {};
676               }
677 
678               // Retrieve all the resource ids belonging to this policy chunk
679               const auto ids_begin = overlayable_child_chunk.data_ptr().convert<ResTable_ref>();
680               const auto ids_end = ids_begin + dtohl(policy_header->entry_count);
681               std::unordered_set<uint32_t> ids;
682               ids.reserve(ids_end - ids_begin);
683               for (auto id_iter = ids_begin; id_iter != ids_end; ++id_iter) {
684                 if (!id_iter) {
685                   LOG(ERROR) << "NULL ResTable_ref record??";
686                   return {};
687                 }
688                 ids.insert(dtohl(id_iter->ident));
689               }
690 
691               // Add the pairing of overlayable properties and resource ids to the package
692               OverlayableInfo overlayable_info {
693                 .name = name_to_actor_it->first,
694                 .actor = name_to_actor_it->second,
695                 .policy_flags = policy_header->policy_flags
696               };
697               loaded_package->overlayable_infos_.emplace_back(std::move(overlayable_info), std::move(ids));
698               loaded_package->defines_overlayable_ = true;
699               break;
700             }
701 
702             default:
703               LOG(WARNING) << StringPrintf("Unknown chunk type '%02x'.", chunk.type());
704               break;
705           }
706         }
707 
708         if (overlayable_iter.HadError()) {
709           LOG(ERROR) << StringPrintf("Error parsing RES_TABLE_OVERLAYABLE_TYPE: %s",
710                                      overlayable_iter.GetLastError().c_str());
711           if (overlayable_iter.HadFatalError()) {
712             return {};
713           }
714         }
715       } break;
716 
717       case RES_TABLE_STAGED_ALIAS_TYPE: {
718         if (loaded_package->package_id_ != kFrameworkPackageId) {
719           LOG(WARNING) << "Alias chunk ignored for non-framework package '"
720                        << loaded_package->package_name_ << "'";
721           break;
722         }
723 
724         const auto lib_alias = child_chunk.header<ResTable_staged_alias_header>();
725         if (!lib_alias) {
726           LOG(ERROR) << "RES_TABLE_STAGED_ALIAS_TYPE is too small.";
727           return {};
728         }
729         if ((child_chunk.data_size() / sizeof(ResTable_staged_alias_entry))
730             < dtohl(lib_alias->count)) {
731           LOG(ERROR) << "RES_TABLE_STAGED_ALIAS_TYPE is too small to hold entries.";
732           return {};
733         }
734         const auto entry_begin = child_chunk.data_ptr().convert<ResTable_staged_alias_entry>();
735         const auto entry_end = entry_begin + dtohl(lib_alias->count);
736         std::unordered_set<uint32_t> finalized_ids;
737         finalized_ids.reserve(entry_end - entry_begin);
738         loaded_package->alias_id_map_.reserve(entry_end - entry_begin);
739         for (auto entry_iter = entry_begin; entry_iter != entry_end; ++entry_iter) {
740           if (!entry_iter) {
741             LOG(ERROR) << "NULL ResTable_staged_alias_entry record??";
742             return {};
743           }
744           auto finalized_id = dtohl(entry_iter->finalizedResId);
745           if (!finalized_ids.insert(finalized_id).second) {
746             LOG(ERROR) << StringPrintf("Repeated finalized resource id '%08x' in staged aliases.",
747                                        finalized_id);
748             return {};
749           }
750 
751           auto staged_id = dtohl(entry_iter->stagedResId);
752           loaded_package->alias_id_map_.emplace_back(staged_id, finalized_id);
753         }
754 
755         std::sort(loaded_package->alias_id_map_.begin(), loaded_package->alias_id_map_.end(),
756             [](auto&& l, auto&& r) { return l.first < r.first; });
757         const auto duplicate_it =
758             std::adjacent_find(loaded_package->alias_id_map_.begin(),
759                                loaded_package->alias_id_map_.end(),
760                                [](auto&& l, auto&& r) { return l.first == r.first; });
761           if (duplicate_it != loaded_package->alias_id_map_.end()) {
762             LOG(ERROR) << StringPrintf("Repeated staged resource id '%08x' in staged aliases.",
763                                        duplicate_it->first);
764             return {};
765           }
766       } break;
767 
768       default:
769         LOG(WARNING) << StringPrintf("Unknown chunk type '%02x'.", chunk.type());
770         break;
771     }
772   }
773 
774   if (iter.HadError()) {
775     LOG(ERROR) << iter.GetLastError();
776     if (iter.HadFatalError()) {
777       return {};
778     }
779   }
780 
781   // Flatten and construct the TypeSpecs.
782   for (auto& entry : type_builder_map) {
783     TypeSpec type_spec = entry.second->Build();
784     uint8_t type_id = static_cast<uint8_t>(entry.first);
785     loaded_package->type_specs_[type_id] = std::move(type_spec);
786   }
787 
788   return std::move(loaded_package);
789 }
790 
LoadTable(const Chunk & chunk,const LoadedIdmap * loaded_idmap,package_property_t property_flags)791 bool LoadedArsc::LoadTable(const Chunk& chunk, const LoadedIdmap* loaded_idmap,
792                            package_property_t property_flags) {
793   incfs::map_ptr<ResTable_header> header = chunk.header<ResTable_header>();
794   if (!header) {
795     LOG(ERROR) << "RES_TABLE_TYPE too small.";
796     return false;
797   }
798 
799   if (loaded_idmap != nullptr) {
800     global_string_pool_ = util::make_unique<OverlayStringPool>(loaded_idmap);
801   }
802 
803   const size_t package_count = dtohl(header->packageCount);
804   size_t packages_seen = 0;
805 
806   packages_.reserve(package_count);
807 
808   ChunkIterator iter(chunk.data_ptr(), chunk.data_size());
809   while (iter.HasNext()) {
810     const Chunk child_chunk = iter.Next();
811     switch (child_chunk.type()) {
812       case RES_STRING_POOL_TYPE:
813         // Only use the first string pool. Ignore others.
814         if (global_string_pool_->getError() == NO_INIT) {
815           status_t err = global_string_pool_->setTo(child_chunk.header<ResStringPool_header>(),
816                                                     child_chunk.size());
817           if (err != NO_ERROR) {
818             LOG(ERROR) << "RES_STRING_POOL_TYPE corrupt.";
819             return false;
820           }
821         } else {
822           LOG(WARNING) << "Multiple RES_STRING_POOL_TYPEs found in RES_TABLE_TYPE.";
823         }
824         break;
825 
826       case RES_TABLE_PACKAGE_TYPE: {
827         if (packages_seen + 1 > package_count) {
828           LOG(ERROR) << "More package chunks were found than the " << package_count
829                      << " declared in the header.";
830           return false;
831         }
832         packages_seen++;
833 
834         std::unique_ptr<const LoadedPackage> loaded_package =
835             LoadedPackage::Load(child_chunk, property_flags);
836         if (!loaded_package) {
837           return false;
838         }
839         packages_.push_back(std::move(loaded_package));
840       } break;
841 
842       default:
843         LOG(WARNING) << StringPrintf("Unknown chunk type '%02x'.", chunk.type());
844         break;
845     }
846   }
847 
848   if (iter.HadError()) {
849     LOG(ERROR) << iter.GetLastError();
850     if (iter.HadFatalError()) {
851       return false;
852     }
853   }
854   return true;
855 }
856 
LoadStringPool(const LoadedIdmap * loaded_idmap)857 bool LoadedArsc::LoadStringPool(const LoadedIdmap* loaded_idmap) {
858   if (loaded_idmap != nullptr) {
859     global_string_pool_ = util::make_unique<OverlayStringPool>(loaded_idmap);
860   }
861   return true;
862 }
863 
Load(incfs::map_ptr<void> data,const size_t length,const LoadedIdmap * loaded_idmap,const package_property_t property_flags)864 std::unique_ptr<LoadedArsc> LoadedArsc::Load(incfs::map_ptr<void> data,
865                                              const size_t length,
866                                              const LoadedIdmap* loaded_idmap,
867                                              const package_property_t property_flags) {
868   ATRACE_NAME("LoadedArsc::Load");
869 
870   // Not using make_unique because the constructor is private.
871   std::unique_ptr<LoadedArsc> loaded_arsc(new LoadedArsc());
872 
873   ChunkIterator iter(data, length);
874   while (iter.HasNext()) {
875     const Chunk chunk = iter.Next();
876     switch (chunk.type()) {
877       case RES_TABLE_TYPE:
878         if (!loaded_arsc->LoadTable(chunk, loaded_idmap, property_flags)) {
879           return {};
880         }
881         break;
882 
883       default:
884         LOG(WARNING) << StringPrintf("Unknown chunk type '%02x'.", chunk.type());
885         break;
886     }
887   }
888 
889   if (iter.HadError()) {
890     LOG(ERROR) << iter.GetLastError();
891     if (iter.HadFatalError()) {
892       return {};
893     }
894   }
895 
896   return loaded_arsc;
897 }
898 
Load(const LoadedIdmap * loaded_idmap)899 std::unique_ptr<LoadedArsc> LoadedArsc::Load(const LoadedIdmap* loaded_idmap) {
900   ATRACE_NAME("LoadedArsc::Load");
901 
902   // Not using make_unique because the constructor is private.
903   std::unique_ptr<LoadedArsc> loaded_arsc(new LoadedArsc());
904   loaded_arsc->LoadStringPool(loaded_idmap);
905   return loaded_arsc;
906 }
907 
908 
CreateEmpty()909 std::unique_ptr<LoadedArsc> LoadedArsc::CreateEmpty() {
910   return std::unique_ptr<LoadedArsc>(new LoadedArsc());
911 }
912 
913 }  // namespace android
914