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/ByteBucketArray.h"
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 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 class TypeSpecPtrBuilder {
53 public:
TypeSpecPtrBuilder(const ResTable_typeSpec * header)54 explicit TypeSpecPtrBuilder(const ResTable_typeSpec* header)
55 : header_(header) {
56 }
57
AddType(const ResTable_type * type)58 void AddType(const ResTable_type* type) {
59 types_.push_back(type);
60 }
61
Build()62 TypeSpecPtr Build() {
63 // Check for overflow.
64 using ElementType = const ResTable_type*;
65 if ((std::numeric_limits<size_t>::max() - sizeof(TypeSpec)) / sizeof(ElementType) <
66 types_.size()) {
67 return {};
68 }
69 TypeSpec* type_spec =
70 (TypeSpec*)::malloc(sizeof(TypeSpec) + (types_.size() * sizeof(ElementType)));
71 type_spec->type_spec = header_;
72 type_spec->type_count = types_.size();
73 memcpy(type_spec + 1, types_.data(), types_.size() * sizeof(ElementType));
74 return TypeSpecPtr(type_spec);
75 }
76
77 private:
78 DISALLOW_COPY_AND_ASSIGN(TypeSpecPtrBuilder);
79
80 const ResTable_typeSpec* header_;
81 std::vector<const ResTable_type*> types_;
82 };
83
84 } // namespace
85
86 LoadedPackage::LoadedPackage() = default;
87 LoadedPackage::~LoadedPackage() = default;
88
89 // Precondition: The header passed in has already been verified, so reading any fields and trusting
90 // the ResChunk_header is safe.
VerifyResTableType(const ResTable_type * header)91 static bool VerifyResTableType(const ResTable_type* header) {
92 if (header->id == 0) {
93 LOG(ERROR) << "RES_TABLE_TYPE_TYPE has invalid ID 0.";
94 return false;
95 }
96
97 const size_t entry_count = dtohl(header->entryCount);
98 if (entry_count > std::numeric_limits<uint16_t>::max()) {
99 LOG(ERROR) << "RES_TABLE_TYPE_TYPE has too many entries (" << entry_count << ").";
100 return false;
101 }
102
103 // Make sure that there is enough room for the entry offsets.
104 const size_t offsets_offset = dtohs(header->header.headerSize);
105 const size_t entries_offset = dtohl(header->entriesStart);
106 const size_t offsets_length = sizeof(uint32_t) * entry_count;
107
108 if (offsets_offset > entries_offset || entries_offset - offsets_offset < offsets_length) {
109 LOG(ERROR) << "RES_TABLE_TYPE_TYPE entry offsets overlap actual entry data.";
110 return false;
111 }
112
113 if (entries_offset > dtohl(header->header.size)) {
114 LOG(ERROR) << "RES_TABLE_TYPE_TYPE entry offsets extend beyond chunk.";
115 return false;
116 }
117
118 if (entries_offset & 0x03) {
119 LOG(ERROR) << "RES_TABLE_TYPE_TYPE entries start at unaligned address.";
120 return false;
121 }
122 return true;
123 }
124
VerifyResTableEntry(const ResTable_type * type,uint32_t entry_offset)125 static bool VerifyResTableEntry(const ResTable_type* type, uint32_t entry_offset) {
126 // Check that the offset is aligned.
127 if (entry_offset & 0x03) {
128 LOG(ERROR) << "Entry at offset " << entry_offset << " is not 4-byte aligned.";
129 return false;
130 }
131
132 // Check that the offset doesn't overflow.
133 if (entry_offset > std::numeric_limits<uint32_t>::max() - dtohl(type->entriesStart)) {
134 // Overflow in offset.
135 LOG(ERROR) << "Entry at offset " << entry_offset << " is too large.";
136 return false;
137 }
138
139 const size_t chunk_size = dtohl(type->header.size);
140
141 entry_offset += dtohl(type->entriesStart);
142 if (entry_offset > chunk_size - sizeof(ResTable_entry)) {
143 LOG(ERROR) << "Entry at offset " << entry_offset
144 << " is too large. No room for ResTable_entry.";
145 return false;
146 }
147
148 const ResTable_entry* entry = reinterpret_cast<const ResTable_entry*>(
149 reinterpret_cast<const uint8_t*>(type) + entry_offset);
150
151 const size_t entry_size = dtohs(entry->size);
152 if (entry_size < sizeof(*entry)) {
153 LOG(ERROR) << "ResTable_entry size " << entry_size << " at offset " << entry_offset
154 << " is too small.";
155 return false;
156 }
157
158 if (entry_size > chunk_size || entry_offset > chunk_size - entry_size) {
159 LOG(ERROR) << "ResTable_entry size " << entry_size << " at offset " << entry_offset
160 << " is too large.";
161 return false;
162 }
163
164 if (entry_size < sizeof(ResTable_map_entry)) {
165 // There needs to be room for one Res_value struct.
166 if (entry_offset + entry_size > chunk_size - sizeof(Res_value)) {
167 LOG(ERROR) << "No room for Res_value after ResTable_entry at offset " << entry_offset
168 << " for type " << (int)type->id << ".";
169 return false;
170 }
171
172 const Res_value* value =
173 reinterpret_cast<const Res_value*>(reinterpret_cast<const uint8_t*>(entry) + entry_size);
174 const size_t value_size = dtohs(value->size);
175 if (value_size < sizeof(Res_value)) {
176 LOG(ERROR) << "Res_value at offset " << entry_offset << " is too small.";
177 return false;
178 }
179
180 if (value_size > chunk_size || entry_offset + entry_size > chunk_size - value_size) {
181 LOG(ERROR) << "Res_value size " << value_size << " at offset " << entry_offset
182 << " is too large.";
183 return false;
184 }
185 } else {
186 const ResTable_map_entry* map = reinterpret_cast<const ResTable_map_entry*>(entry);
187 const size_t map_entry_count = dtohl(map->count);
188 size_t map_entries_start = entry_offset + entry_size;
189 if (map_entries_start & 0x03) {
190 LOG(ERROR) << "Map entries at offset " << entry_offset << " start at unaligned offset.";
191 return false;
192 }
193
194 // Each entry is sizeof(ResTable_map) big.
195 if (map_entry_count > ((chunk_size - map_entries_start) / sizeof(ResTable_map))) {
196 LOG(ERROR) << "Too many map entries in ResTable_map_entry at offset " << entry_offset << ".";
197 return false;
198 }
199 }
200 return true;
201 }
202
iterator(const LoadedPackage * lp,size_t ti,size_t ei)203 LoadedPackage::iterator::iterator(const LoadedPackage* lp, size_t ti, size_t ei)
204 : loadedPackage_(lp),
205 typeIndex_(ti),
206 entryIndex_(ei),
207 typeIndexEnd_(lp->resource_ids_.size() + 1) {
208 while (typeIndex_ < typeIndexEnd_ && loadedPackage_->resource_ids_[typeIndex_] == 0) {
209 typeIndex_++;
210 }
211 }
212
operator ++()213 LoadedPackage::iterator& LoadedPackage::iterator::operator++() {
214 while (typeIndex_ < typeIndexEnd_) {
215 if (entryIndex_ + 1 < loadedPackage_->resource_ids_[typeIndex_]) {
216 entryIndex_++;
217 break;
218 }
219 entryIndex_ = 0;
220 typeIndex_++;
221 if (typeIndex_ < typeIndexEnd_ && loadedPackage_->resource_ids_[typeIndex_] != 0) {
222 break;
223 }
224 }
225 return *this;
226 }
227
operator *() const228 uint32_t LoadedPackage::iterator::operator*() const {
229 if (typeIndex_ >= typeIndexEnd_) {
230 return 0;
231 }
232 return make_resid(loadedPackage_->package_id_, typeIndex_ + loadedPackage_->type_id_offset_,
233 entryIndex_);
234 }
235
GetEntry(const ResTable_type * type_chunk,uint16_t entry_index)236 const ResTable_entry* LoadedPackage::GetEntry(const ResTable_type* type_chunk,
237 uint16_t entry_index) {
238 uint32_t entry_offset = GetEntryOffset(type_chunk, entry_index);
239 if (entry_offset == ResTable_type::NO_ENTRY) {
240 return nullptr;
241 }
242 return GetEntryFromOffset(type_chunk, entry_offset);
243 }
244
GetEntryOffset(const ResTable_type * type_chunk,uint16_t entry_index)245 uint32_t LoadedPackage::GetEntryOffset(const ResTable_type* type_chunk, uint16_t entry_index) {
246 // The configuration matches and is better than the previous selection.
247 // Find the entry value if it exists for this configuration.
248 const size_t entry_count = dtohl(type_chunk->entryCount);
249 const size_t offsets_offset = dtohs(type_chunk->header.headerSize);
250
251 // Check if there is the desired entry in this type.
252
253 if (type_chunk->flags & ResTable_type::FLAG_SPARSE) {
254 // This is encoded as a sparse map, so perform a binary search.
255 const ResTable_sparseTypeEntry* sparse_indices =
256 reinterpret_cast<const ResTable_sparseTypeEntry*>(
257 reinterpret_cast<const uint8_t*>(type_chunk) + offsets_offset);
258 const ResTable_sparseTypeEntry* sparse_indices_end = sparse_indices + entry_count;
259 const ResTable_sparseTypeEntry* result =
260 std::lower_bound(sparse_indices, sparse_indices_end, entry_index,
261 [](const ResTable_sparseTypeEntry& entry, uint16_t entry_idx) {
262 return dtohs(entry.idx) < entry_idx;
263 });
264
265 if (result == sparse_indices_end || dtohs(result->idx) != entry_index) {
266 // No entry found.
267 return ResTable_type::NO_ENTRY;
268 }
269
270 // Extract the offset from the entry. Each offset must be a multiple of 4 so we store it as
271 // the real offset divided by 4.
272 return uint32_t{dtohs(result->offset)} * 4u;
273 }
274
275 // This type is encoded as a dense array.
276 if (entry_index >= entry_count) {
277 // This entry cannot be here.
278 return ResTable_type::NO_ENTRY;
279 }
280
281 const uint32_t* entry_offsets = reinterpret_cast<const uint32_t*>(
282 reinterpret_cast<const uint8_t*>(type_chunk) + offsets_offset);
283 return dtohl(entry_offsets[entry_index]);
284 }
285
GetEntryFromOffset(const ResTable_type * type_chunk,uint32_t offset)286 const ResTable_entry* LoadedPackage::GetEntryFromOffset(const ResTable_type* type_chunk,
287 uint32_t offset) {
288 if (UNLIKELY(!VerifyResTableEntry(type_chunk, offset))) {
289 return nullptr;
290 }
291 return reinterpret_cast<const ResTable_entry*>(reinterpret_cast<const uint8_t*>(type_chunk) +
292 offset + dtohl(type_chunk->entriesStart));
293 }
294
CollectConfigurations(bool exclude_mipmap,std::set<ResTable_config> * out_configs) const295 void LoadedPackage::CollectConfigurations(bool exclude_mipmap,
296 std::set<ResTable_config>* out_configs) const {
297 const static std::u16string kMipMap = u"mipmap";
298 const size_t type_count = type_specs_.size();
299 for (size_t i = 0; i < type_count; i++) {
300 const TypeSpecPtr& type_spec = type_specs_[i];
301 if (type_spec != nullptr) {
302 if (exclude_mipmap) {
303 const int type_idx = type_spec->type_spec->id - 1;
304 size_t type_name_len;
305 const char16_t* type_name16 = type_string_pool_.stringAt(type_idx, &type_name_len);
306 if (type_name16 != nullptr) {
307 if (kMipMap.compare(0, std::u16string::npos, type_name16, type_name_len) == 0) {
308 // This is a mipmap type, skip collection.
309 continue;
310 }
311 }
312 const char* type_name = type_string_pool_.string8At(type_idx, &type_name_len);
313 if (type_name != nullptr) {
314 if (strncmp(type_name, "mipmap", type_name_len) == 0) {
315 // This is a mipmap type, skip collection.
316 continue;
317 }
318 }
319 }
320
321 const auto iter_end = type_spec->types + type_spec->type_count;
322 for (auto iter = type_spec->types; iter != iter_end; ++iter) {
323 ResTable_config config;
324 config.copyFromDtoH((*iter)->config);
325 out_configs->insert(config);
326 }
327 }
328 }
329 }
330
CollectLocales(bool canonicalize,std::set<std::string> * out_locales) const331 void LoadedPackage::CollectLocales(bool canonicalize, std::set<std::string>* out_locales) const {
332 char temp_locale[RESTABLE_MAX_LOCALE_LEN];
333 const size_t type_count = type_specs_.size();
334 for (size_t i = 0; i < type_count; i++) {
335 const TypeSpecPtr& type_spec = type_specs_[i];
336 if (type_spec != nullptr) {
337 const auto iter_end = type_spec->types + type_spec->type_count;
338 for (auto iter = type_spec->types; iter != iter_end; ++iter) {
339 ResTable_config configuration;
340 configuration.copyFromDtoH((*iter)->config);
341 if (configuration.locale != 0) {
342 configuration.getBcp47Locale(temp_locale, canonicalize);
343 std::string locale(temp_locale);
344 out_locales->insert(std::move(locale));
345 }
346 }
347 }
348 }
349 }
350
FindEntryByName(const std::u16string & type_name,const std::u16string & entry_name) const351 uint32_t LoadedPackage::FindEntryByName(const std::u16string& type_name,
352 const std::u16string& entry_name) const {
353 ssize_t type_idx = type_string_pool_.indexOfString(type_name.data(), type_name.size());
354 if (type_idx < 0) {
355 return 0u;
356 }
357
358 ssize_t key_idx = key_string_pool_.indexOfString(entry_name.data(), entry_name.size());
359 if (key_idx < 0) {
360 return 0u;
361 }
362
363 const TypeSpec* type_spec = type_specs_[type_idx].get();
364 if (type_spec == nullptr) {
365 return 0u;
366 }
367
368 const auto iter_end = type_spec->types + type_spec->type_count;
369 for (auto iter = type_spec->types; iter != iter_end; ++iter) {
370 const ResTable_type* type = *iter;
371 size_t entry_count = dtohl(type->entryCount);
372 for (size_t entry_idx = 0; entry_idx < entry_count; entry_idx++) {
373 const uint32_t* entry_offsets = reinterpret_cast<const uint32_t*>(
374 reinterpret_cast<const uint8_t*>(type) + dtohs(type->header.headerSize));
375 const uint32_t offset = dtohl(entry_offsets[entry_idx]);
376 if (offset != ResTable_type::NO_ENTRY) {
377 const ResTable_entry* entry = reinterpret_cast<const ResTable_entry*>(
378 reinterpret_cast<const uint8_t*>(type) + dtohl(type->entriesStart) + offset);
379 if (dtohl(entry->key.index) == static_cast<uint32_t>(key_idx)) {
380 // The package ID will be overridden by the caller (due to runtime assignment of package
381 // IDs for shared libraries).
382 return make_resid(0x00, type_idx + type_id_offset_ + 1, entry_idx);
383 }
384 }
385 }
386 }
387 return 0u;
388 }
389
GetPackageById(uint8_t package_id) const390 const LoadedPackage* LoadedArsc::GetPackageById(uint8_t package_id) const {
391 for (const auto& loaded_package : packages_) {
392 if (loaded_package->GetPackageId() == package_id) {
393 return loaded_package.get();
394 }
395 }
396 return nullptr;
397 }
398
Load(const Chunk & chunk,package_property_t property_flags)399 std::unique_ptr<const LoadedPackage> LoadedPackage::Load(const Chunk& chunk,
400 package_property_t property_flags) {
401 ATRACE_NAME("LoadedPackage::Load");
402 std::unique_ptr<LoadedPackage> loaded_package(new LoadedPackage());
403
404 // typeIdOffset was added at some point, but we still must recognize apps built before this
405 // was added.
406 constexpr size_t kMinPackageSize =
407 sizeof(ResTable_package) - sizeof(ResTable_package::typeIdOffset);
408 const ResTable_package* header = chunk.header<ResTable_package, kMinPackageSize>();
409 if (header == nullptr) {
410 LOG(ERROR) << "RES_TABLE_PACKAGE_TYPE too small.";
411 return {};
412 }
413
414 if ((property_flags & PROPERTY_SYSTEM) != 0) {
415 loaded_package->property_flags_ |= PROPERTY_SYSTEM;
416 }
417
418 if ((property_flags & PROPERTY_LOADER) != 0) {
419 loaded_package->property_flags_ |= PROPERTY_LOADER;
420 }
421
422 if ((property_flags & PROPERTY_OVERLAY) != 0) {
423 // Overlay resources must have an exclusive resource id space for referencing internal
424 // resources.
425 loaded_package->property_flags_ |= PROPERTY_OVERLAY | PROPERTY_DYNAMIC;
426 }
427
428 loaded_package->package_id_ = dtohl(header->id);
429 if (loaded_package->package_id_ == 0 ||
430 (loaded_package->package_id_ == kAppPackageId && (property_flags & PROPERTY_DYNAMIC) != 0)) {
431 loaded_package->property_flags_ |= PROPERTY_DYNAMIC;
432 }
433
434 if (header->header.headerSize >= sizeof(ResTable_package)) {
435 uint32_t type_id_offset = dtohl(header->typeIdOffset);
436 if (type_id_offset > std::numeric_limits<uint8_t>::max()) {
437 LOG(ERROR) << "RES_TABLE_PACKAGE_TYPE type ID offset too large.";
438 return {};
439 }
440 loaded_package->type_id_offset_ = static_cast<int>(type_id_offset);
441 }
442
443 util::ReadUtf16StringFromDevice(header->name, arraysize(header->name),
444 &loaded_package->package_name_);
445
446 // A map of TypeSpec builders, each associated with an type index.
447 // We use these to accumulate the set of Types available for a TypeSpec, and later build a single,
448 // contiguous block of memory that holds all the Types together with the TypeSpec.
449 std::unordered_map<int, std::unique_ptr<TypeSpecPtrBuilder>> type_builder_map;
450
451 ChunkIterator iter(chunk.data_ptr(), chunk.data_size());
452 while (iter.HasNext()) {
453 const Chunk child_chunk = iter.Next();
454 switch (child_chunk.type()) {
455 case RES_STRING_POOL_TYPE: {
456 const uintptr_t pool_address =
457 reinterpret_cast<uintptr_t>(child_chunk.header<ResChunk_header>());
458 const uintptr_t header_address = reinterpret_cast<uintptr_t>(header);
459 if (pool_address == header_address + dtohl(header->typeStrings)) {
460 // This string pool is the type string pool.
461 status_t err = loaded_package->type_string_pool_.setTo(
462 child_chunk.header<ResStringPool_header>(), child_chunk.size());
463 if (err != NO_ERROR) {
464 LOG(ERROR) << "RES_STRING_POOL_TYPE for types corrupt.";
465 return {};
466 }
467 } else if (pool_address == header_address + dtohl(header->keyStrings)) {
468 // This string pool is the key string pool.
469 status_t err = loaded_package->key_string_pool_.setTo(
470 child_chunk.header<ResStringPool_header>(), child_chunk.size());
471 if (err != NO_ERROR) {
472 LOG(ERROR) << "RES_STRING_POOL_TYPE for keys corrupt.";
473 return {};
474 }
475 } else {
476 LOG(WARNING) << "Too many RES_STRING_POOL_TYPEs found in RES_TABLE_PACKAGE_TYPE.";
477 }
478 } break;
479
480 case RES_TABLE_TYPE_SPEC_TYPE: {
481 const ResTable_typeSpec* type_spec = child_chunk.header<ResTable_typeSpec>();
482 if (type_spec == nullptr) {
483 LOG(ERROR) << "RES_TABLE_TYPE_SPEC_TYPE too small.";
484 return {};
485 }
486
487 if (type_spec->id == 0) {
488 LOG(ERROR) << "RES_TABLE_TYPE_SPEC_TYPE has invalid ID 0.";
489 return {};
490 }
491
492 if (loaded_package->type_id_offset_ + static_cast<int>(type_spec->id) >
493 std::numeric_limits<uint8_t>::max()) {
494 LOG(ERROR) << "RES_TABLE_TYPE_SPEC_TYPE has out of range ID.";
495 return {};
496 }
497
498 // The data portion of this chunk contains entry_count 32bit entries,
499 // each one representing a set of flags.
500 // Here we only validate that the chunk is well formed.
501 const size_t entry_count = dtohl(type_spec->entryCount);
502
503 // There can only be 2^16 entries in a type, because that is the ID
504 // space for entries (EEEE) in the resource ID 0xPPTTEEEE.
505 if (entry_count > std::numeric_limits<uint16_t>::max()) {
506 LOG(ERROR) << "RES_TABLE_TYPE_SPEC_TYPE has too many entries (" << entry_count << ").";
507 return {};
508 }
509
510 if (entry_count * sizeof(uint32_t) > chunk.data_size()) {
511 LOG(ERROR) << "RES_TABLE_TYPE_SPEC_TYPE too small to hold entries.";
512 return {};
513 }
514
515 std::unique_ptr<TypeSpecPtrBuilder>& builder_ptr = type_builder_map[type_spec->id - 1];
516 if (builder_ptr == nullptr) {
517 builder_ptr = util::make_unique<TypeSpecPtrBuilder>(type_spec);
518 loaded_package->resource_ids_.set(type_spec->id, entry_count);
519 } else {
520 LOG(WARNING) << StringPrintf("RES_TABLE_TYPE_SPEC_TYPE already defined for ID %02x",
521 type_spec->id);
522 }
523 } break;
524
525 case RES_TABLE_TYPE_TYPE: {
526 const ResTable_type* type = child_chunk.header<ResTable_type, kResTableTypeMinSize>();
527 if (type == nullptr) {
528 LOG(ERROR) << "RES_TABLE_TYPE_TYPE too small.";
529 return {};
530 }
531
532 if (!VerifyResTableType(type)) {
533 return {};
534 }
535
536 // Type chunks must be preceded by their TypeSpec chunks.
537 std::unique_ptr<TypeSpecPtrBuilder>& builder_ptr = type_builder_map[type->id - 1];
538 if (builder_ptr != nullptr) {
539 builder_ptr->AddType(type);
540 } else {
541 LOG(ERROR) << StringPrintf(
542 "RES_TABLE_TYPE_TYPE with ID %02x found without preceding RES_TABLE_TYPE_SPEC_TYPE.",
543 type->id);
544 return {};
545 }
546 } break;
547
548 case RES_TABLE_LIBRARY_TYPE: {
549 const ResTable_lib_header* lib = child_chunk.header<ResTable_lib_header>();
550 if (lib == nullptr) {
551 LOG(ERROR) << "RES_TABLE_LIBRARY_TYPE too small.";
552 return {};
553 }
554
555 if (child_chunk.data_size() / sizeof(ResTable_lib_entry) < dtohl(lib->count)) {
556 LOG(ERROR) << "RES_TABLE_LIBRARY_TYPE too small to hold entries.";
557 return {};
558 }
559
560 loaded_package->dynamic_package_map_.reserve(dtohl(lib->count));
561
562 const ResTable_lib_entry* const entry_begin =
563 reinterpret_cast<const ResTable_lib_entry*>(child_chunk.data_ptr());
564 const ResTable_lib_entry* const entry_end = entry_begin + dtohl(lib->count);
565 for (auto entry_iter = entry_begin; entry_iter != entry_end; ++entry_iter) {
566 std::string package_name;
567 util::ReadUtf16StringFromDevice(entry_iter->packageName,
568 arraysize(entry_iter->packageName), &package_name);
569
570 if (dtohl(entry_iter->packageId) >= std::numeric_limits<uint8_t>::max()) {
571 LOG(ERROR) << StringPrintf(
572 "Package ID %02x in RES_TABLE_LIBRARY_TYPE too large for package '%s'.",
573 dtohl(entry_iter->packageId), package_name.c_str());
574 return {};
575 }
576
577 loaded_package->dynamic_package_map_.emplace_back(std::move(package_name),
578 dtohl(entry_iter->packageId));
579 }
580 } break;
581
582 case RES_TABLE_OVERLAYABLE_TYPE: {
583 const ResTable_overlayable_header* header =
584 child_chunk.header<ResTable_overlayable_header>();
585 if (header == nullptr) {
586 LOG(ERROR) << "RES_TABLE_OVERLAYABLE_TYPE too small.";
587 return {};
588 }
589
590 std::string name;
591 util::ReadUtf16StringFromDevice(header->name, arraysize(header->name), &name);
592 std::string actor;
593 util::ReadUtf16StringFromDevice(header->actor, arraysize(header->actor), &actor);
594
595 if (loaded_package->overlayable_map_.find(name) !=
596 loaded_package->overlayable_map_.end()) {
597 LOG(ERROR) << "Multiple <overlayable> blocks with the same name '" << name << "'.";
598 return {};
599 }
600 loaded_package->overlayable_map_.emplace(name, actor);
601
602 // Iterate over the overlayable policy chunks contained within the overlayable chunk data
603 ChunkIterator overlayable_iter(child_chunk.data_ptr(), child_chunk.data_size());
604 while (overlayable_iter.HasNext()) {
605 const Chunk overlayable_child_chunk = overlayable_iter.Next();
606
607 switch (overlayable_child_chunk.type()) {
608 case RES_TABLE_OVERLAYABLE_POLICY_TYPE: {
609 const ResTable_overlayable_policy_header* policy_header =
610 overlayable_child_chunk.header<ResTable_overlayable_policy_header>();
611 if (policy_header == nullptr) {
612 LOG(ERROR) << "RES_TABLE_OVERLAYABLE_POLICY_TYPE too small.";
613 return {};
614 }
615
616 if ((overlayable_child_chunk.data_size() / sizeof(ResTable_ref))
617 < dtohl(policy_header->entry_count)) {
618 LOG(ERROR) << "RES_TABLE_OVERLAYABLE_POLICY_TYPE too small to hold entries.";
619 return {};
620 }
621
622 // Retrieve all the resource ids belonging to this policy chunk
623 std::unordered_set<uint32_t> ids;
624 const auto ids_begin =
625 reinterpret_cast<const ResTable_ref*>(overlayable_child_chunk.data_ptr());
626 const auto ids_end = ids_begin + dtohl(policy_header->entry_count);
627 for (auto id_iter = ids_begin; id_iter != ids_end; ++id_iter) {
628 ids.insert(dtohl(id_iter->ident));
629 }
630
631 // Add the pairing of overlayable properties and resource ids to the package
632 OverlayableInfo overlayable_info{};
633 overlayable_info.name = name;
634 overlayable_info.actor = actor;
635 overlayable_info.policy_flags = policy_header->policy_flags;
636 loaded_package->overlayable_infos_.push_back(std::make_pair(overlayable_info, ids));
637 loaded_package->defines_overlayable_ = true;
638 break;
639 }
640
641 default:
642 LOG(WARNING) << StringPrintf("Unknown chunk type '%02x'.", chunk.type());
643 break;
644 }
645 }
646
647 if (overlayable_iter.HadError()) {
648 LOG(ERROR) << StringPrintf("Error parsing RES_TABLE_OVERLAYABLE_TYPE: %s",
649 overlayable_iter.GetLastError().c_str());
650 if (overlayable_iter.HadFatalError()) {
651 return {};
652 }
653 }
654 } break;
655
656 default:
657 LOG(WARNING) << StringPrintf("Unknown chunk type '%02x'.", chunk.type());
658 break;
659 }
660 }
661
662 if (iter.HadError()) {
663 LOG(ERROR) << iter.GetLastError();
664 if (iter.HadFatalError()) {
665 return {};
666 }
667 }
668
669 // Flatten and construct the TypeSpecs.
670 for (auto& entry : type_builder_map) {
671 uint8_t type_idx = static_cast<uint8_t>(entry.first);
672 TypeSpecPtr type_spec_ptr = entry.second->Build();
673 if (type_spec_ptr == nullptr) {
674 LOG(ERROR) << "Too many type configurations, overflow detected.";
675 return {};
676 }
677
678 loaded_package->type_specs_.editItemAt(type_idx) = std::move(type_spec_ptr);
679 }
680
681 return std::move(loaded_package);
682 }
683
LoadTable(const Chunk & chunk,const LoadedIdmap * loaded_idmap,package_property_t property_flags)684 bool LoadedArsc::LoadTable(const Chunk& chunk, const LoadedIdmap* loaded_idmap,
685 package_property_t property_flags) {
686 const ResTable_header* header = chunk.header<ResTable_header>();
687 if (header == nullptr) {
688 LOG(ERROR) << "RES_TABLE_TYPE too small.";
689 return false;
690 }
691
692 if (loaded_idmap != nullptr) {
693 global_string_pool_ = util::make_unique<OverlayStringPool>(loaded_idmap);
694 }
695
696 const size_t package_count = dtohl(header->packageCount);
697 size_t packages_seen = 0;
698
699 packages_.reserve(package_count);
700
701 ChunkIterator iter(chunk.data_ptr(), chunk.data_size());
702 while (iter.HasNext()) {
703 const Chunk child_chunk = iter.Next();
704 switch (child_chunk.type()) {
705 case RES_STRING_POOL_TYPE:
706 // Only use the first string pool. Ignore others.
707 if (global_string_pool_->getError() == NO_INIT) {
708 status_t err = global_string_pool_->setTo(child_chunk.header<ResStringPool_header>(),
709 child_chunk.size());
710 if (err != NO_ERROR) {
711 LOG(ERROR) << "RES_STRING_POOL_TYPE corrupt.";
712 return false;
713 }
714 } else {
715 LOG(WARNING) << "Multiple RES_STRING_POOL_TYPEs found in RES_TABLE_TYPE.";
716 }
717 break;
718
719 case RES_TABLE_PACKAGE_TYPE: {
720 if (packages_seen + 1 > package_count) {
721 LOG(ERROR) << "More package chunks were found than the " << package_count
722 << " declared in the header.";
723 return false;
724 }
725 packages_seen++;
726
727 std::unique_ptr<const LoadedPackage> loaded_package =
728 LoadedPackage::Load(child_chunk, property_flags);
729 if (!loaded_package) {
730 return false;
731 }
732 packages_.push_back(std::move(loaded_package));
733 } break;
734
735 default:
736 LOG(WARNING) << StringPrintf("Unknown chunk type '%02x'.", chunk.type());
737 break;
738 }
739 }
740
741 if (iter.HadError()) {
742 LOG(ERROR) << iter.GetLastError();
743 if (iter.HadFatalError()) {
744 return false;
745 }
746 }
747 return true;
748 }
749
Load(const StringPiece & data,const LoadedIdmap * loaded_idmap,const package_property_t property_flags)750 std::unique_ptr<const LoadedArsc> LoadedArsc::Load(const StringPiece& data,
751 const LoadedIdmap* loaded_idmap,
752 const package_property_t property_flags) {
753 ATRACE_NAME("LoadedArsc::Load");
754
755 // Not using make_unique because the constructor is private.
756 std::unique_ptr<LoadedArsc> loaded_arsc(new LoadedArsc());
757
758 ChunkIterator iter(data.data(), data.size());
759 while (iter.HasNext()) {
760 const Chunk chunk = iter.Next();
761 switch (chunk.type()) {
762 case RES_TABLE_TYPE:
763 if (!loaded_arsc->LoadTable(chunk, loaded_idmap, property_flags)) {
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 // Need to force a move for mingw32.
782 return std::move(loaded_arsc);
783 }
784
CreateEmpty()785 std::unique_ptr<const LoadedArsc> LoadedArsc::CreateEmpty() {
786 return std::unique_ptr<LoadedArsc>(new LoadedArsc());
787 }
788
789 } // namespace android
790