blob: b62fc813350ed2862ad4e1018d4b832138ea0467 [file] [log] [blame]
Adam Lesinski7ad11102016-10-28 16:39:15 -07001/*
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 <cstddef>
22#include <limits>
23
24#include "android-base/logging.h"
25#include "android-base/stringprintf.h"
26#include "utils/ByteOrder.h"
27#include "utils/Trace.h"
28
29#ifdef _WIN32
30#ifdef ERROR
31#undef ERROR
32#endif
33#endif
34
Adam Lesinski7ad11102016-10-28 16:39:15 -070035#include "androidfw/ByteBucketArray.h"
Adam Lesinskida431a22016-12-29 16:08:16 -050036#include "androidfw/Chunk.h"
Adam Lesinski929d6512017-01-16 19:11:19 -080037#include "androidfw/ResourceUtils.h"
Adam Lesinski7ad11102016-10-28 16:39:15 -070038#include "androidfw/Util.h"
39
Adam Lesinski970bd8d2017-09-25 13:21:55 -070040using ::android::base::StringPrintf;
Adam Lesinski7ad11102016-10-28 16:39:15 -070041
42namespace android {
43
Adam Lesinskida431a22016-12-29 16:08:16 -050044constexpr const static int kAppPackageId = 0x7f;
Adam Lesinski7ad11102016-10-28 16:39:15 -070045
46// Element of a TypeSpec array. See TypeSpec.
47struct Type {
48 // The configuration for which this type defines entries.
49 // This is already converted to host endianness.
50 ResTable_config configuration;
51
52 // Pointer to the mmapped data where entry definitions are kept.
53 const ResTable_type* type;
54};
55
56// TypeSpec is going to be immediately proceeded by
57// an array of Type structs, all in the same block of memory.
58struct TypeSpec {
59 // Pointer to the mmapped data where flags are kept.
60 // Flags denote whether the resource entry is public
61 // and under which configurations it varies.
62 const ResTable_typeSpec* type_spec;
63
Adam Lesinski970bd8d2017-09-25 13:21:55 -070064 // Pointer to the mmapped data where the IDMAP mappings for this type
65 // exist. May be nullptr if no IDMAP exists.
66 const IdmapEntry_header* idmap_entries;
67
Adam Lesinski7ad11102016-10-28 16:39:15 -070068 // The number of types that follow this struct.
69 // There is a type for each configuration
70 // that entries are defined for.
71 size_t type_count;
72
73 // Trick to easily access a variable number of Type structs
74 // proceeding this struct, and to ensure their alignment.
75 const Type types[0];
76};
77
78// TypeSpecPtr points to the block of memory that holds
79// a TypeSpec struct, followed by an array of Type structs.
80// TypeSpecPtr is a managed pointer that knows how to delete
81// itself.
82using TypeSpecPtr = util::unique_cptr<TypeSpec>;
83
Adam Lesinskida431a22016-12-29 16:08:16 -050084namespace {
85
Adam Lesinski7ad11102016-10-28 16:39:15 -070086// Builder that helps accumulate Type structs and then create a single
87// contiguous block of memory to store both the TypeSpec struct and
88// the Type structs.
89class TypeSpecPtrBuilder {
90 public:
Adam Lesinski970bd8d2017-09-25 13:21:55 -070091 explicit TypeSpecPtrBuilder(const ResTable_typeSpec* header,
92 const IdmapEntry_header* idmap_header)
93 : header_(header), idmap_header_(idmap_header) {
94 }
Adam Lesinski7ad11102016-10-28 16:39:15 -070095
96 void AddType(const ResTable_type* type) {
97 ResTable_config config;
98 config.copyFromDtoH(type->config);
99 types_.push_back(Type{config, type});
100 }
101
102 TypeSpecPtr Build() {
103 // Check for overflow.
104 if ((std::numeric_limits<size_t>::max() - sizeof(TypeSpec)) / sizeof(Type) < types_.size()) {
105 return {};
106 }
107 TypeSpec* type_spec = (TypeSpec*)::malloc(sizeof(TypeSpec) + (types_.size() * sizeof(Type)));
108 type_spec->type_spec = header_;
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700109 type_spec->idmap_entries = idmap_header_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700110 type_spec->type_count = types_.size();
111 memcpy(type_spec + 1, types_.data(), types_.size() * sizeof(Type));
112 return TypeSpecPtr(type_spec);
113 }
114
115 private:
116 DISALLOW_COPY_AND_ASSIGN(TypeSpecPtrBuilder);
117
118 const ResTable_typeSpec* header_;
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700119 const IdmapEntry_header* idmap_header_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700120 std::vector<Type> types_;
121};
122
123} // namespace
124
Adam Lesinskida431a22016-12-29 16:08:16 -0500125bool LoadedPackage::FindEntry(uint8_t type_idx, uint16_t entry_idx, const ResTable_config& config,
126 LoadedArscEntry* out_entry, ResTable_config* out_selected_config,
Adam Lesinski7ad11102016-10-28 16:39:15 -0700127 uint32_t* out_flags) const {
Adam Lesinskida431a22016-12-29 16:08:16 -0500128 ATRACE_CALL();
Adam Lesinskic6aada92017-01-13 15:34:14 -0800129
130 // If the type IDs are offset in this package, we need to take that into account when searching
131 // for a type.
132 const TypeSpecPtr& ptr = type_specs_[type_idx - type_id_offset_];
Adam Lesinski7ad11102016-10-28 16:39:15 -0700133 if (ptr == nullptr) {
134 return false;
135 }
136
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700137 // If there is an IDMAP supplied with this package, translate the entry ID.
138 if (ptr->idmap_entries != nullptr) {
139 if (!LoadedIdmap::Lookup(ptr->idmap_entries, entry_idx, &entry_idx)) {
140 // There is no mapping, so the resource is not meant to be in this overlay package.
141 return false;
142 }
143 }
144
Adam Lesinski7ad11102016-10-28 16:39:15 -0700145 // Don't bother checking if the entry ID is larger than
146 // the number of entries.
Adam Lesinskida431a22016-12-29 16:08:16 -0500147 if (entry_idx >= dtohl(ptr->type_spec->entryCount)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700148 return false;
149 }
150
151 const ResTable_config* best_config = nullptr;
152 const ResTable_type* best_type = nullptr;
153 uint32_t best_offset = 0;
154
155 for (uint32_t i = 0; i < ptr->type_count; i++) {
156 const Type* type = &ptr->types[i];
157
158 if (type->configuration.match(config) &&
159 (best_config == nullptr || type->configuration.isBetterThan(*best_config, &config))) {
160 // The configuration matches and is better than the previous selection.
161 // Find the entry value if it exists for this configuration.
162 size_t entry_count = dtohl(type->type->entryCount);
Adam Lesinskida431a22016-12-29 16:08:16 -0500163 if (entry_idx < entry_count) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700164 const uint32_t* entry_offsets = reinterpret_cast<const uint32_t*>(
165 reinterpret_cast<const uint8_t*>(type->type) + dtohs(type->type->header.headerSize));
Adam Lesinskida431a22016-12-29 16:08:16 -0500166 const uint32_t offset = dtohl(entry_offsets[entry_idx]);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700167 if (offset != ResTable_type::NO_ENTRY) {
168 // There is an entry for this resource, record it.
169 best_config = &type->configuration;
170 best_type = type->type;
171 best_offset = offset + dtohl(type->type->entriesStart);
172 }
173 }
174 }
175 }
176
177 if (best_type == nullptr) {
178 return false;
179 }
180
181 const uint32_t* flags = reinterpret_cast<const uint32_t*>(ptr->type_spec + 1);
Adam Lesinskida431a22016-12-29 16:08:16 -0500182 *out_flags = dtohl(flags[entry_idx]);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700183 *out_selected_config = *best_config;
184
185 const ResTable_entry* best_entry = reinterpret_cast<const ResTable_entry*>(
186 reinterpret_cast<const uint8_t*>(best_type) + best_offset);
187 out_entry->entry = best_entry;
188 out_entry->type_string_ref = StringPoolRef(&type_string_pool_, best_type->id - 1);
189 out_entry->entry_string_ref = StringPoolRef(&key_string_pool_, dtohl(best_entry->key.index));
190 return true;
191}
192
193// The destructor gets generated into arbitrary translation units
194// if left implicit, which causes the compiler to complain about
195// forward declarations and incomplete types.
196LoadedArsc::~LoadedArsc() {}
197
Adam Lesinskida431a22016-12-29 16:08:16 -0500198bool LoadedArsc::FindEntry(uint32_t resid, const ResTable_config& config,
199 LoadedArscEntry* out_entry, ResTable_config* out_selected_config,
200 uint32_t* out_flags) const {
201 ATRACE_CALL();
Adam Lesinski929d6512017-01-16 19:11:19 -0800202 const uint8_t package_id = get_package_id(resid);
203 const uint8_t type_id = get_type_id(resid);
204 const uint16_t entry_id = get_entry_id(resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700205
206 if (type_id == 0) {
207 LOG(ERROR) << "Invalid ID 0x" << std::hex << resid << std::dec << ".";
208 return false;
209 }
210
211 for (const auto& loaded_package : packages_) {
212 if (loaded_package->package_id_ == package_id) {
213 return loaded_package->FindEntry(type_id - 1, entry_id, config, out_entry,
214 out_selected_config, out_flags);
215 }
216 }
217 return false;
218}
219
Adam Lesinskida431a22016-12-29 16:08:16 -0500220const LoadedPackage* LoadedArsc::GetPackageForId(uint32_t resid) const {
Adam Lesinski929d6512017-01-16 19:11:19 -0800221 const uint8_t package_id = get_package_id(resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700222 for (const auto& loaded_package : packages_) {
223 if (loaded_package->package_id_ == package_id) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500224 return loaded_package.get();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700225 }
226 }
227 return nullptr;
228}
229
230static bool VerifyType(const Chunk& chunk) {
231 ATRACE_CALL();
Adam Lesinski136fd072017-03-03 13:50:21 -0800232 const ResTable_type* header = chunk.header<ResTable_type, kResTableTypeMinSize>();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700233
234 const size_t entry_count = dtohl(header->entryCount);
235 if (entry_count > std::numeric_limits<uint16_t>::max()) {
236 LOG(ERROR) << "Too many entries in RES_TABLE_TYPE_TYPE.";
237 return false;
238 }
239
240 // Make sure that there is enough room for the entry offsets.
241 const size_t offsets_offset = chunk.header_size();
242 const size_t entries_offset = dtohl(header->entriesStart);
243 const size_t offsets_length = sizeof(uint32_t) * entry_count;
244
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700245 if (offsets_offset > entries_offset || entries_offset - offsets_offset < offsets_length) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700246 LOG(ERROR) << "Entry offsets overlap actual entry data.";
247 return false;
248 }
249
250 if (entries_offset > chunk.size()) {
251 LOG(ERROR) << "Entry offsets extend beyond chunk.";
252 return false;
253 }
254
255 if (entries_offset & 0x03) {
256 LOG(ERROR) << "Entries start at unaligned address.";
257 return false;
258 }
259
260 // Check each entry offset.
261 const uint32_t* offsets =
262 reinterpret_cast<const uint32_t*>(reinterpret_cast<const uint8_t*>(header) + offsets_offset);
263 for (size_t i = 0; i < entry_count; i++) {
264 uint32_t offset = dtohl(offsets[i]);
265 if (offset != ResTable_type::NO_ENTRY) {
266 // Check that the offset is aligned.
267 if (offset & 0x03) {
268 LOG(ERROR) << "Entry offset at index " << i << " is not 4-byte aligned.";
269 return false;
270 }
271
272 // Check that the offset doesn't overflow.
273 if (offset > std::numeric_limits<uint32_t>::max() - entries_offset) {
274 // Overflow in offset.
275 LOG(ERROR) << "Entry offset at index " << i << " is too large.";
276 return false;
277 }
278
279 offset += entries_offset;
280 if (offset > chunk.size() - sizeof(ResTable_entry)) {
281 LOG(ERROR) << "Entry offset at index " << i << " is too large. No room for ResTable_entry.";
282 return false;
283 }
284
285 const ResTable_entry* entry = reinterpret_cast<const ResTable_entry*>(
286 reinterpret_cast<const uint8_t*>(header) + offset);
287 const size_t entry_size = dtohs(entry->size);
288 if (entry_size < sizeof(*entry)) {
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700289 LOG(ERROR) << "ResTable_entry size " << entry_size << " at index " << i << " is too small.";
Adam Lesinski7ad11102016-10-28 16:39:15 -0700290 return false;
291 }
292
293 // Check the declared entrySize.
294 if (entry_size > chunk.size() || offset > chunk.size() - entry_size) {
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700295 LOG(ERROR) << "ResTable_entry size " << entry_size << " at index " << i << " is too large.";
Adam Lesinski7ad11102016-10-28 16:39:15 -0700296 return false;
297 }
298
299 // If this is a map entry, then keep validating.
300 if (entry_size >= sizeof(ResTable_map_entry)) {
301 const ResTable_map_entry* map = reinterpret_cast<const ResTable_map_entry*>(entry);
302 const size_t map_entry_count = dtohl(map->count);
303
304 size_t map_entries_start = offset + entry_size;
305 if (map_entries_start & 0x03) {
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700306 LOG(ERROR) << "Map entries at index " << i << " start at unaligned offset.";
Adam Lesinski7ad11102016-10-28 16:39:15 -0700307 return false;
308 }
309
310 // Each entry is sizeof(ResTable_map) big.
311 if (map_entry_count > ((chunk.size() - map_entries_start) / sizeof(ResTable_map))) {
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700312 LOG(ERROR) << "Too many map entries in ResTable_map_entry at index " << i << ".";
Adam Lesinski7ad11102016-10-28 16:39:15 -0700313 return false;
314 }
315
316 // Great, all the map entries fit!.
317 } else {
318 // There needs to be room for one Res_value struct.
319 if (offset + entry_size > chunk.size() - sizeof(Res_value)) {
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700320 LOG(ERROR) << "No room for Res_value after ResTable_entry at index " << i << " for type "
321 << (int)header->id << " with config " << header->config.toString().string()
322 << ".";
Adam Lesinski7ad11102016-10-28 16:39:15 -0700323 return false;
324 }
325
326 const Res_value* value = reinterpret_cast<const Res_value*>(
327 reinterpret_cast<const uint8_t*>(entry) + entry_size);
328 const size_t value_size = dtohs(value->size);
329 if (value_size < sizeof(Res_value)) {
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700330 LOG(ERROR) << "Res_value at index " << i << " is too small.";
Adam Lesinski7ad11102016-10-28 16:39:15 -0700331 return false;
332 }
333
334 if (value_size > chunk.size() || offset + entry_size > chunk.size() - value_size) {
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700335 LOG(ERROR) << "Res_value size " << value_size << " at index " << i << " is too large.";
Adam Lesinski7ad11102016-10-28 16:39:15 -0700336 return false;
337 }
338 }
339 }
340 }
341 return true;
342}
343
Adam Lesinski0c405242017-01-13 20:47:26 -0800344void LoadedPackage::CollectConfigurations(bool exclude_mipmap,
345 std::set<ResTable_config>* out_configs) const {
346 const static std::u16string kMipMap = u"mipmap";
347 const size_t type_count = type_specs_.size();
348 for (size_t i = 0; i < type_count; i++) {
349 const util::unique_cptr<TypeSpec>& type_spec = type_specs_[i];
350 if (type_spec != nullptr) {
351 if (exclude_mipmap) {
352 const int type_idx = type_spec->type_spec->id - 1;
353 size_t type_name_len;
354 const char16_t* type_name16 = type_string_pool_.stringAt(type_idx, &type_name_len);
355 if (type_name16 != nullptr) {
356 if (kMipMap.compare(0, std::u16string::npos, type_name16, type_name_len) == 0) {
357 // This is a mipmap type, skip collection.
358 continue;
359 }
360 }
361 const char* type_name = type_string_pool_.string8At(type_idx, &type_name_len);
362 if (type_name != nullptr) {
363 if (strncmp(type_name, "mipmap", type_name_len) == 0) {
364 // This is a mipmap type, skip collection.
365 continue;
366 }
367 }
368 }
369
370 for (size_t j = 0; j < type_spec->type_count; j++) {
371 out_configs->insert(type_spec->types[j].configuration);
372 }
373 }
374 }
375}
376
377void LoadedPackage::CollectLocales(bool canonicalize, std::set<std::string>* out_locales) const {
378 char temp_locale[RESTABLE_MAX_LOCALE_LEN];
379 const size_t type_count = type_specs_.size();
380 for (size_t i = 0; i < type_count; i++) {
381 const util::unique_cptr<TypeSpec>& type_spec = type_specs_[i];
382 if (type_spec != nullptr) {
383 for (size_t j = 0; j < type_spec->type_count; j++) {
384 const ResTable_config& configuration = type_spec->types[j].configuration;
385 if (configuration.locale != 0) {
386 configuration.getBcp47Locale(temp_locale, canonicalize);
387 std::string locale(temp_locale);
388 out_locales->insert(std::move(locale));
389 }
390 }
391 }
392 }
393}
394
Adam Lesinski929d6512017-01-16 19:11:19 -0800395uint32_t LoadedPackage::FindEntryByName(const std::u16string& type_name,
396 const std::u16string& entry_name) const {
397 ssize_t type_idx = type_string_pool_.indexOfString(type_name.data(), type_name.size());
398 if (type_idx < 0) {
399 return 0u;
400 }
401
402 ssize_t key_idx = key_string_pool_.indexOfString(entry_name.data(), entry_name.size());
403 if (key_idx < 0) {
404 return 0u;
405 }
406
407 const TypeSpec* type_spec = type_specs_[type_idx].get();
408 if (type_spec == nullptr) {
409 return 0u;
410 }
411
412 for (size_t ti = 0; ti < type_spec->type_count; ti++) {
413 const Type* type = &type_spec->types[ti];
414 size_t entry_count = dtohl(type->type->entryCount);
415 for (size_t entry_idx = 0; entry_idx < entry_count; entry_idx++) {
416 const uint32_t* entry_offsets = reinterpret_cast<const uint32_t*>(
417 reinterpret_cast<const uint8_t*>(type->type) + dtohs(type->type->header.headerSize));
418 const uint32_t offset = dtohl(entry_offsets[entry_idx]);
419 if (offset != ResTable_type::NO_ENTRY) {
420 const ResTable_entry* entry =
421 reinterpret_cast<const ResTable_entry*>(reinterpret_cast<const uint8_t*>(type->type) +
422 dtohl(type->type->entriesStart) + offset);
423 if (dtohl(entry->key.index) == static_cast<uint32_t>(key_idx)) {
424 // The package ID will be overridden by the caller (due to runtime assignment of package
425 // IDs for shared libraries).
426 return make_resid(0x00, type_idx + type_id_offset_ + 1, entry_idx);
427 }
428 }
429 }
430 }
431 return 0u;
432}
433
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700434std::unique_ptr<LoadedPackage> LoadedPackage::Load(const Chunk& chunk,
435 const LoadedIdmap* loaded_idmap) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700436 ATRACE_CALL();
Adam Lesinskida431a22016-12-29 16:08:16 -0500437 std::unique_ptr<LoadedPackage> loaded_package{new LoadedPackage()};
438
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700439 // typeIdOffset was added at some point, but we still must recognize apps built before this
440 // was added.
Adam Lesinski33af6c72017-03-29 13:00:35 -0700441 constexpr size_t kMinPackageSize =
442 sizeof(ResTable_package) - sizeof(ResTable_package::typeIdOffset);
443 const ResTable_package* header = chunk.header<ResTable_package, kMinPackageSize>();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700444 if (header == nullptr) {
445 LOG(ERROR) << "Chunk RES_TABLE_PACKAGE_TYPE is too small.";
Adam Lesinskida431a22016-12-29 16:08:16 -0500446 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700447 }
448
449 loaded_package->package_id_ = dtohl(header->id);
Adam Lesinskida431a22016-12-29 16:08:16 -0500450 if (loaded_package->package_id_ == 0) {
451 // Package ID of 0 means this is a shared library.
452 loaded_package->dynamic_ = true;
453 }
454
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700455 if (loaded_idmap != nullptr) {
456 // This is an overlay and so it needs to pretend to be the target package.
457 loaded_package->package_id_ = loaded_idmap->TargetPackageId();
458 loaded_package->overlay_ = true;
459 }
460
Adam Lesinskic6aada92017-01-13 15:34:14 -0800461 if (header->header.headerSize >= sizeof(ResTable_package)) {
462 uint32_t type_id_offset = dtohl(header->typeIdOffset);
463 if (type_id_offset > std::numeric_limits<uint8_t>::max()) {
464 LOG(ERROR) << "Type ID offset in RES_TABLE_PACKAGE_TYPE is too large.";
465 return {};
466 }
467 loaded_package->type_id_offset_ = static_cast<int>(type_id_offset);
468 }
469
Adam Lesinskida431a22016-12-29 16:08:16 -0500470 util::ReadUtf16StringFromDevice(header->name, arraysize(header->name),
471 &loaded_package->package_name_);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700472
473 // A TypeSpec builder. We use this to accumulate the set of Types
474 // available for a TypeSpec, and later build a single, contiguous block
475 // of memory that holds all the Types together with the TypeSpec.
476 std::unique_ptr<TypeSpecPtrBuilder> types_builder;
477
478 // Keep track of the last seen type index. Since type IDs are 1-based,
479 // this records their index, which is 0-based (type ID - 1).
480 uint8_t last_type_idx = 0;
481
482 ChunkIterator iter(chunk.data_ptr(), chunk.data_size());
483 while (iter.HasNext()) {
484 const Chunk child_chunk = iter.Next();
485 switch (child_chunk.type()) {
486 case RES_STRING_POOL_TYPE: {
487 const uintptr_t pool_address =
488 reinterpret_cast<uintptr_t>(child_chunk.header<ResChunk_header>());
489 const uintptr_t header_address = reinterpret_cast<uintptr_t>(header);
490 if (pool_address == header_address + dtohl(header->typeStrings)) {
491 // This string pool is the type string pool.
492 status_t err = loaded_package->type_string_pool_.setTo(
493 child_chunk.header<ResStringPool_header>(), child_chunk.size());
494 if (err != NO_ERROR) {
495 LOG(ERROR) << "Corrupt package type string pool.";
Adam Lesinskida431a22016-12-29 16:08:16 -0500496 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700497 }
498 } else if (pool_address == header_address + dtohl(header->keyStrings)) {
499 // This string pool is the key string pool.
500 status_t err = loaded_package->key_string_pool_.setTo(
501 child_chunk.header<ResStringPool_header>(), child_chunk.size());
502 if (err != NO_ERROR) {
503 LOG(ERROR) << "Corrupt package key string pool.";
Adam Lesinskida431a22016-12-29 16:08:16 -0500504 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700505 }
506 } else {
507 LOG(WARNING) << "Too many string pool chunks found in package.";
508 }
509 } break;
510
511 case RES_TABLE_TYPE_SPEC_TYPE: {
512 ATRACE_NAME("LoadTableTypeSpec");
513
514 // Starting a new TypeSpec, so finish the old one if there was one.
515 if (types_builder) {
516 TypeSpecPtr type_spec_ptr = types_builder->Build();
517 if (type_spec_ptr == nullptr) {
518 LOG(ERROR) << "Too many type configurations, overflow detected.";
Adam Lesinskida431a22016-12-29 16:08:16 -0500519 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700520 }
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700521
522 // We only add the type to the package if there is no IDMAP, or if the type is
523 // overlaying something.
524 if (loaded_idmap == nullptr || type_spec_ptr->idmap_entries != nullptr) {
525 // If this is an overlay, insert it at the target type ID.
526 if (type_spec_ptr->idmap_entries != nullptr) {
527 last_type_idx = dtohs(type_spec_ptr->idmap_entries->target_type_id) - 1;
528 }
529 loaded_package->type_specs_.editItemAt(last_type_idx) = std::move(type_spec_ptr);
530 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700531
532 types_builder = {};
533 last_type_idx = 0;
534 }
535
536 const ResTable_typeSpec* type_spec = child_chunk.header<ResTable_typeSpec>();
537 if (type_spec == nullptr) {
538 LOG(ERROR) << "Chunk RES_TABLE_TYPE_SPEC_TYPE is too small.";
Adam Lesinskida431a22016-12-29 16:08:16 -0500539 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700540 }
541
542 if (type_spec->id == 0) {
543 LOG(ERROR) << "Chunk RES_TABLE_TYPE_SPEC_TYPE has invalid ID 0.";
Adam Lesinskida431a22016-12-29 16:08:16 -0500544 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700545 }
546
Adam Lesinskic6aada92017-01-13 15:34:14 -0800547 if (loaded_package->type_id_offset_ + static_cast<int>(type_spec->id) >
548 std::numeric_limits<uint8_t>::max()) {
549 LOG(ERROR) << "Chunk RES_TABLE_TYPE_SPEC_TYPE has out of range ID.";
550 return {};
551 }
552
Adam Lesinski7ad11102016-10-28 16:39:15 -0700553 // 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) << "Too many entries in RES_TABLE_TYPE_SPEC_TYPE: " << entry_count << ".";
Adam Lesinskida431a22016-12-29 16:08:16 -0500562 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700563 }
564
565 if (entry_count * sizeof(uint32_t) > chunk.data_size()) {
566 LOG(ERROR) << "Chunk too small to hold entries in RES_TABLE_TYPE_SPEC_TYPE.";
Adam Lesinskida431a22016-12-29 16:08:16 -0500567 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700568 }
569
570 last_type_idx = type_spec->id - 1;
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700571
572 // If this is an overlay, associate the mapping of this type to the target type
573 // from the IDMAP.
574 const IdmapEntry_header* idmap_entry_header = nullptr;
575 if (loaded_idmap != nullptr) {
576 idmap_entry_header = loaded_idmap->GetEntryMapForType(type_spec->id);
577 }
578
579 types_builder = util::make_unique<TypeSpecPtrBuilder>(type_spec, idmap_entry_header);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700580 } break;
581
582 case RES_TABLE_TYPE_TYPE: {
Adam Lesinski136fd072017-03-03 13:50:21 -0800583 const ResTable_type* type = child_chunk.header<ResTable_type, kResTableTypeMinSize>();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700584 if (type == nullptr) {
585 LOG(ERROR) << "Chunk RES_TABLE_TYPE_TYPE is too small.";
Adam Lesinskida431a22016-12-29 16:08:16 -0500586 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700587 }
588
589 if (type->id == 0) {
590 LOG(ERROR) << "Chunk RES_TABLE_TYPE_TYPE has invalid ID 0.";
Adam Lesinskida431a22016-12-29 16:08:16 -0500591 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700592 }
593
594 // Type chunks must be preceded by their TypeSpec chunks.
595 if (!types_builder || type->id - 1 != last_type_idx) {
596 LOG(ERROR) << "Found RES_TABLE_TYPE_TYPE chunk without "
597 "RES_TABLE_TYPE_SPEC_TYPE.";
Adam Lesinskida431a22016-12-29 16:08:16 -0500598 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700599 }
600
601 if (!VerifyType(child_chunk)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500602 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700603 }
604
605 types_builder->AddType(type);
606 } break;
607
Adam Lesinskida431a22016-12-29 16:08:16 -0500608 case RES_TABLE_LIBRARY_TYPE: {
609 const ResTable_lib_header* lib = child_chunk.header<ResTable_lib_header>();
610 if (lib == nullptr) {
611 LOG(ERROR) << "Chunk RES_TABLE_LIBRARY_TYPE is too small.";
612 return {};
613 }
614
615 if (child_chunk.data_size() / sizeof(ResTable_lib_entry) < dtohl(lib->count)) {
616 LOG(ERROR) << "Chunk too small to hold entries in RES_TABLE_LIBRARY_TYPE.";
617 return {};
618 }
619
620 loaded_package->dynamic_package_map_.reserve(dtohl(lib->count));
621
622 const ResTable_lib_entry* const entry_begin =
623 reinterpret_cast<const ResTable_lib_entry*>(child_chunk.data_ptr());
624 const ResTable_lib_entry* const entry_end = entry_begin + dtohl(lib->count);
625 for (auto entry_iter = entry_begin; entry_iter != entry_end; ++entry_iter) {
626 std::string package_name;
627 util::ReadUtf16StringFromDevice(entry_iter->packageName,
628 arraysize(entry_iter->packageName), &package_name);
629
630 if (dtohl(entry_iter->packageId) >= std::numeric_limits<uint8_t>::max()) {
631 LOG(ERROR) << base::StringPrintf(
632 "Package ID %02x in RES_TABLE_LIBRARY_TYPE too large for package '%s'.",
633 dtohl(entry_iter->packageId), package_name.c_str());
634 return {};
635 }
636
637 loaded_package->dynamic_package_map_.emplace_back(std::move(package_name),
638 dtohl(entry_iter->packageId));
639 }
640
641 } break;
642
Adam Lesinski7ad11102016-10-28 16:39:15 -0700643 default:
644 LOG(WARNING) << base::StringPrintf("Unknown chunk type '%02x'.", chunk.type());
645 break;
646 }
647 }
648
649 // Finish the last TypeSpec.
650 if (types_builder) {
651 TypeSpecPtr type_spec_ptr = types_builder->Build();
652 if (type_spec_ptr == nullptr) {
653 LOG(ERROR) << "Too many type configurations, overflow detected.";
Adam Lesinskida431a22016-12-29 16:08:16 -0500654 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700655 }
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700656
657 // We only add the type to the package if there is no IDMAP, or if the type is
658 // overlaying something.
659 if (loaded_idmap == nullptr || type_spec_ptr->idmap_entries != nullptr) {
660 // If this is an overlay, insert it at the target type ID.
661 if (type_spec_ptr->idmap_entries != nullptr) {
662 last_type_idx = dtohs(type_spec_ptr->idmap_entries->target_type_id) - 1;
663 }
664 loaded_package->type_specs_.editItemAt(last_type_idx) = std::move(type_spec_ptr);
665 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700666 }
667
668 if (iter.HadError()) {
669 LOG(ERROR) << iter.GetLastError();
Adam Lesinskida431a22016-12-29 16:08:16 -0500670 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700671 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500672 return loaded_package;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700673}
674
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700675bool LoadedArsc::LoadTable(const Chunk& chunk, const LoadedIdmap* loaded_idmap,
676 bool load_as_shared_library) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700677 ATRACE_CALL();
678 const ResTable_header* header = chunk.header<ResTable_header>();
679 if (header == nullptr) {
680 LOG(ERROR) << "Chunk RES_TABLE_TYPE is too small.";
681 return false;
682 }
683
684 const size_t package_count = dtohl(header->packageCount);
685 size_t packages_seen = 0;
686
687 packages_.reserve(package_count);
688
689 ChunkIterator iter(chunk.data_ptr(), chunk.data_size());
690 while (iter.HasNext()) {
691 const Chunk child_chunk = iter.Next();
692 switch (child_chunk.type()) {
693 case RES_STRING_POOL_TYPE:
694 // Only use the first string pool. Ignore others.
695 if (global_string_pool_.getError() == NO_INIT) {
696 status_t err = global_string_pool_.setTo(child_chunk.header<ResStringPool_header>(),
697 child_chunk.size());
698 if (err != NO_ERROR) {
699 LOG(ERROR) << "Corrupt string pool.";
700 return false;
701 }
702 } else {
703 LOG(WARNING) << "Multiple string pool chunks found in resource table.";
704 }
705 break;
706
707 case RES_TABLE_PACKAGE_TYPE: {
708 if (packages_seen + 1 > package_count) {
709 LOG(ERROR) << "More package chunks were found than the " << package_count
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700710 << " declared in the header.";
Adam Lesinski7ad11102016-10-28 16:39:15 -0700711 return false;
712 }
713 packages_seen++;
714
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700715 std::unique_ptr<LoadedPackage> loaded_package =
716 LoadedPackage::Load(child_chunk, loaded_idmap);
Adam Lesinskida431a22016-12-29 16:08:16 -0500717 if (!loaded_package) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700718 return false;
719 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500720
721 // Mark the package as dynamic if we are forcefully loading the Apk as a shared library.
722 if (loaded_package->package_id_ == kAppPackageId) {
723 loaded_package->dynamic_ = load_as_shared_library;
724 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800725 loaded_package->system_ = system_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700726 packages_.push_back(std::move(loaded_package));
727 } break;
728
729 default:
730 LOG(WARNING) << base::StringPrintf("Unknown chunk type '%02x'.", chunk.type());
731 break;
732 }
733 }
734
735 if (iter.HadError()) {
736 LOG(ERROR) << iter.GetLastError();
737 return false;
738 }
739 return true;
740}
741
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700742std::unique_ptr<const LoadedArsc> LoadedArsc::Load(const StringPiece& data,
743 const LoadedIdmap* loaded_idmap, bool system,
Adam Lesinski0c405242017-01-13 20:47:26 -0800744 bool load_as_shared_library) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700745 ATRACE_CALL();
746
747 // Not using make_unique because the constructor is private.
748 std::unique_ptr<LoadedArsc> loaded_arsc(new LoadedArsc());
Adam Lesinski0c405242017-01-13 20:47:26 -0800749 loaded_arsc->system_ = system;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700750
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700751 ChunkIterator iter(data.data(), data.size());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700752 while (iter.HasNext()) {
753 const Chunk chunk = iter.Next();
754 switch (chunk.type()) {
755 case RES_TABLE_TYPE:
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700756 if (!loaded_arsc->LoadTable(chunk, loaded_idmap, load_as_shared_library)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700757 return {};
758 }
759 break;
760
761 default:
762 LOG(WARNING) << base::StringPrintf("Unknown chunk type '%02x'.", chunk.type());
763 break;
764 }
765 }
766
767 if (iter.HadError()) {
768 LOG(ERROR) << iter.GetLastError();
769 return {};
770 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800771
772 // Need to force a move for mingw32.
773 return std::move(loaded_arsc);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700774}
775
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700776std::unique_ptr<const LoadedArsc> LoadedArsc::CreateEmpty() {
777 return std::unique_ptr<LoadedArsc>(new LoadedArsc());
778}
779
Adam Lesinski7ad11102016-10-28 16:39:15 -0700780} // namespace android