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