blob: 6ee5e86c55a2d2b853f88730e9c09a0dd005fc0a [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
Adam Lesinski73f6f9d2017-11-14 10:18:05 -080021#include <algorithm>
Adam Lesinski7ad11102016-10-28 16:39:15 -070022#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
Adam Lesinski7ad11102016-10-28 16:39:15 -070036#include "androidfw/ByteBucketArray.h"
Adam Lesinskida431a22016-12-29 16:08:16 -050037#include "androidfw/Chunk.h"
Adam Lesinski929d6512017-01-16 19:11:19 -080038#include "androidfw/ResourceUtils.h"
Adam Lesinski7ad11102016-10-28 16:39:15 -070039#include "androidfw/Util.h"
40
Adam Lesinski970bd8d2017-09-25 13:21:55 -070041using ::android::base::StringPrintf;
Adam Lesinski7ad11102016-10-28 16:39:15 -070042
43namespace android {
44
Adam Lesinskida431a22016-12-29 16:08:16 -050045constexpr const static int kAppPackageId = 0x7f;
Adam Lesinski7ad11102016-10-28 16:39:15 -070046
47// Element of a TypeSpec array. See TypeSpec.
48struct Type {
49 // The configuration for which this type defines entries.
50 // This is already converted to host endianness.
51 ResTable_config configuration;
52
53 // Pointer to the mmapped data where entry definitions are kept.
54 const ResTable_type* type;
55};
56
57// TypeSpec is going to be immediately proceeded by
58// an array of Type structs, all in the same block of memory.
59struct TypeSpec {
60 // Pointer to the mmapped data where flags are kept.
61 // Flags denote whether the resource entry is public
62 // and under which configurations it varies.
63 const ResTable_typeSpec* type_spec;
64
Adam Lesinski970bd8d2017-09-25 13:21:55 -070065 // Pointer to the mmapped data where the IDMAP mappings for this type
66 // exist. May be nullptr if no IDMAP exists.
67 const IdmapEntry_header* idmap_entries;
68
Adam Lesinski7ad11102016-10-28 16:39:15 -070069 // The number of types that follow this struct.
70 // There is a type for each configuration
71 // that entries are defined for.
72 size_t type_count;
73
74 // Trick to easily access a variable number of Type structs
75 // proceeding this struct, and to ensure their alignment.
76 const Type types[0];
77};
78
79// TypeSpecPtr points to the block of memory that holds
80// a TypeSpec struct, followed by an array of Type structs.
81// TypeSpecPtr is a managed pointer that knows how to delete
82// itself.
83using TypeSpecPtr = util::unique_cptr<TypeSpec>;
84
Adam Lesinskida431a22016-12-29 16:08:16 -050085namespace {
86
Adam Lesinski7ad11102016-10-28 16:39:15 -070087// Builder that helps accumulate Type structs and then create a single
88// contiguous block of memory to store both the TypeSpec struct and
89// the Type structs.
90class TypeSpecPtrBuilder {
91 public:
Adam Lesinski970bd8d2017-09-25 13:21:55 -070092 explicit TypeSpecPtrBuilder(const ResTable_typeSpec* header,
93 const IdmapEntry_header* idmap_header)
94 : header_(header), idmap_header_(idmap_header) {
95 }
Adam Lesinski7ad11102016-10-28 16:39:15 -070096
97 void AddType(const ResTable_type* type) {
98 ResTable_config config;
99 config.copyFromDtoH(type->config);
100 types_.push_back(Type{config, type});
101 }
102
103 TypeSpecPtr Build() {
104 // Check for overflow.
105 if ((std::numeric_limits<size_t>::max() - sizeof(TypeSpec)) / sizeof(Type) < types_.size()) {
106 return {};
107 }
108 TypeSpec* type_spec = (TypeSpec*)::malloc(sizeof(TypeSpec) + (types_.size() * sizeof(Type)));
109 type_spec->type_spec = header_;
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700110 type_spec->idmap_entries = idmap_header_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700111 type_spec->type_count = types_.size();
112 memcpy(type_spec + 1, types_.data(), types_.size() * sizeof(Type));
113 return TypeSpecPtr(type_spec);
114 }
115
116 private:
117 DISALLOW_COPY_AND_ASSIGN(TypeSpecPtrBuilder);
118
119 const ResTable_typeSpec* header_;
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700120 const IdmapEntry_header* idmap_header_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700121 std::vector<Type> types_;
122};
123
124} // namespace
125
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700126LoadedPackage::LoadedPackage() = default;
127LoadedPackage::~LoadedPackage() = default;
128
129// Precondition: The header passed in has already been verified, so reading any fields and trusting
130// the ResChunk_header is safe.
131static bool VerifyResTableType(const ResTable_type* header) {
132 const size_t entry_count = dtohl(header->entryCount);
133 if (entry_count > std::numeric_limits<uint16_t>::max()) {
134 LOG(ERROR) << "Too many entries in RES_TABLE_TYPE_TYPE.";
135 return false;
136 }
137
138 // Make sure that there is enough room for the entry offsets.
139 const size_t offsets_offset = dtohs(header->header.headerSize);
140 const size_t entries_offset = dtohl(header->entriesStart);
141 const size_t offsets_length = sizeof(uint32_t) * entry_count;
142
143 if (offsets_offset > entries_offset || entries_offset - offsets_offset < offsets_length) {
144 LOG(ERROR) << "Entry offsets overlap actual entry data.";
145 return false;
146 }
147
148 if (entries_offset > dtohl(header->header.size)) {
149 LOG(ERROR) << "Entry offsets extend beyond chunk.";
150 return false;
151 }
152
153 if (entries_offset & 0x03) {
154 LOG(ERROR) << "Entries start at unaligned address.";
155 return false;
156 }
157 return true;
158}
159
160static bool VerifyResTableEntry(const ResTable_type* type, uint32_t entry_offset,
161 size_t entry_idx) {
162 // Check that the offset is aligned.
163 if (entry_offset & 0x03) {
164 LOG(ERROR) << "Entry offset at index " << entry_idx << " is not 4-byte aligned.";
165 return false;
166 }
167
168 // Check that the offset doesn't overflow.
169 if (entry_offset > std::numeric_limits<uint32_t>::max() - dtohl(type->entriesStart)) {
170 // Overflow in offset.
171 LOG(ERROR) << "Entry offset at index " << entry_idx << " is too large.";
172 return false;
173 }
174
175 const size_t chunk_size = dtohl(type->header.size);
176
177 entry_offset += dtohl(type->entriesStart);
178 if (entry_offset > chunk_size - sizeof(ResTable_entry)) {
179 LOG(ERROR) << "Entry offset at index " << entry_idx
180 << " is too large. No room for ResTable_entry.";
181 return false;
182 }
183
184 const ResTable_entry* entry = reinterpret_cast<const ResTable_entry*>(
185 reinterpret_cast<const uint8_t*>(type) + entry_offset);
186
187 const size_t entry_size = dtohs(entry->size);
188 if (entry_size < sizeof(*entry)) {
189 LOG(ERROR) << "ResTable_entry size " << entry_size << " at index " << entry_idx
190 << " is too small.";
191 return false;
192 }
193
194 if (entry_size > chunk_size || entry_offset > chunk_size - entry_size) {
195 LOG(ERROR) << "ResTable_entry size " << entry_size << " at index " << entry_idx
196 << " is too large.";
197 return false;
198 }
199
200 if (entry_size < sizeof(ResTable_map_entry)) {
201 // There needs to be room for one Res_value struct.
202 if (entry_offset + entry_size > chunk_size - sizeof(Res_value)) {
203 LOG(ERROR) << "No room for Res_value after ResTable_entry at index " << entry_idx
204 << " for type " << (int)type->id << ".";
205 return false;
206 }
207
208 const Res_value* value =
209 reinterpret_cast<const Res_value*>(reinterpret_cast<const uint8_t*>(entry) + entry_size);
210 const size_t value_size = dtohs(value->size);
211 if (value_size < sizeof(Res_value)) {
212 LOG(ERROR) << "Res_value at index " << entry_idx << " is too small.";
213 return false;
214 }
215
216 if (value_size > chunk_size || entry_offset + entry_size > chunk_size - value_size) {
217 LOG(ERROR) << "Res_value size " << value_size << " at index " << entry_idx
218 << " is too large.";
219 return false;
220 }
221 } else {
222 const ResTable_map_entry* map = reinterpret_cast<const ResTable_map_entry*>(entry);
223 const size_t map_entry_count = dtohl(map->count);
224 size_t map_entries_start = entry_offset + entry_size;
225 if (map_entries_start & 0x03) {
226 LOG(ERROR) << "Map entries at index " << entry_idx << " start at unaligned offset.";
227 return false;
228 }
229
230 // Each entry is sizeof(ResTable_map) big.
231 if (map_entry_count > ((chunk_size - map_entries_start) / sizeof(ResTable_map))) {
232 LOG(ERROR) << "Too many map entries in ResTable_map_entry at index " << entry_idx << ".";
233 return false;
234 }
235 }
236 return true;
237}
238
239template <bool Verified>
240bool LoadedPackage::FindEntry(const TypeSpecPtr& type_spec_ptr, uint16_t entry_idx,
241 const ResTable_config& config, FindEntryResult* out_entry) const {
242 const ResTable_config* best_config = nullptr;
243 const ResTable_type* best_type = nullptr;
244 uint32_t best_offset = 0;
245
246 for (uint32_t i = 0; i < type_spec_ptr->type_count; i++) {
247 const Type* type = &type_spec_ptr->types[i];
Adam Lesinski73f6f9d2017-11-14 10:18:05 -0800248 const ResTable_type* type_chunk = type->type;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700249
250 if (type->configuration.match(config) &&
251 (best_config == nullptr || type->configuration.isBetterThan(*best_config, &config))) {
252 // The configuration matches and is better than the previous selection.
253 // Find the entry value if it exists for this configuration.
Adam Lesinski73f6f9d2017-11-14 10:18:05 -0800254 const size_t entry_count = dtohl(type_chunk->entryCount);
255 const size_t offsets_offset = dtohs(type_chunk->header.headerSize);
256
257 // If the package hasn't been verified, do bounds checking.
258 if (!Verified) {
259 if (!VerifyResTableType(type_chunk)) {
260 continue;
261 }
262 }
263
264 // Check if there is the desired entry in this type.
265
266 if (type_chunk->flags & ResTable_type::FLAG_SPARSE) {
267 // This is encoded as a sparse map, so perform a binary search.
268 const ResTable_sparseTypeEntry* sparse_indices =
269 reinterpret_cast<const ResTable_sparseTypeEntry*>(
270 reinterpret_cast<const uint8_t*>(type_chunk) + offsets_offset);
271 const ResTable_sparseTypeEntry* sparse_indices_end = sparse_indices + entry_count;
272 const ResTable_sparseTypeEntry* result =
273 std::lower_bound(sparse_indices, sparse_indices_end, entry_idx,
274 [](const ResTable_sparseTypeEntry& entry, uint16_t entry_idx) {
275 return dtohs(entry.idx) < entry_idx;
276 });
277
278 if (result == sparse_indices_end || dtohs(result->idx) != entry_idx) {
279 // No entry found.
280 continue;
281 }
282
283 // Extract the offset from the entry. Each offset must be a multiple of 4 so we store it as
284 // the real offset divided by 4.
285 best_offset = dtohs(result->offset) * 4u;
286 } else {
287 if (entry_idx >= entry_count) {
288 // This entry cannot be here.
289 continue;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700290 }
291
292 const uint32_t* entry_offsets = reinterpret_cast<const uint32_t*>(
Adam Lesinski73f6f9d2017-11-14 10:18:05 -0800293 reinterpret_cast<const uint8_t*>(type_chunk) + offsets_offset);
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700294 const uint32_t offset = dtohl(entry_offsets[entry_idx]);
Adam Lesinski73f6f9d2017-11-14 10:18:05 -0800295 if (offset == ResTable_type::NO_ENTRY) {
296 continue;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700297 }
Adam Lesinski73f6f9d2017-11-14 10:18:05 -0800298
299 // There is an entry for this resource, record it.
300 best_offset = offset;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700301 }
Adam Lesinski73f6f9d2017-11-14 10:18:05 -0800302
303 best_config = &type->configuration;
304 best_type = type_chunk;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700305 }
306 }
307
308 if (best_type == nullptr) {
309 return false;
310 }
311
312 if (!Verified) {
313 if (!VerifyResTableEntry(best_type, best_offset, entry_idx)) {
314 return false;
315 }
316 }
317
318 const ResTable_entry* best_entry = reinterpret_cast<const ResTable_entry*>(
319 reinterpret_cast<const uint8_t*>(best_type) + best_offset + dtohl(best_type->entriesStart));
320
321 const uint32_t* flags = reinterpret_cast<const uint32_t*>(type_spec_ptr->type_spec + 1);
322 out_entry->type_flags = dtohl(flags[entry_idx]);
323 out_entry->entry = best_entry;
324 out_entry->config = best_config;
325 out_entry->type_string_ref = StringPoolRef(&type_string_pool_, best_type->id - 1);
326 out_entry->entry_string_ref = StringPoolRef(&key_string_pool_, dtohl(best_entry->key.index));
327 return true;
328}
329
Adam Lesinskida431a22016-12-29 16:08:16 -0500330bool LoadedPackage::FindEntry(uint8_t type_idx, uint16_t entry_idx, const ResTable_config& config,
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700331 FindEntryResult* out_entry) const {
Adam Lesinskida431a22016-12-29 16:08:16 -0500332 ATRACE_CALL();
Adam Lesinskic6aada92017-01-13 15:34:14 -0800333
334 // If the type IDs are offset in this package, we need to take that into account when searching
335 // for a type.
336 const TypeSpecPtr& ptr = type_specs_[type_idx - type_id_offset_];
Adam Lesinski7ad11102016-10-28 16:39:15 -0700337 if (ptr == nullptr) {
338 return false;
339 }
340
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700341 // If there is an IDMAP supplied with this package, translate the entry ID.
342 if (ptr->idmap_entries != nullptr) {
343 if (!LoadedIdmap::Lookup(ptr->idmap_entries, entry_idx, &entry_idx)) {
344 // There is no mapping, so the resource is not meant to be in this overlay package.
345 return false;
346 }
347 }
348
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700349 // Don't bother checking if the entry ID is larger than the number of entries.
Adam Lesinskida431a22016-12-29 16:08:16 -0500350 if (entry_idx >= dtohl(ptr->type_spec->entryCount)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700351 return false;
352 }
353
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700354 if (verified_) {
355 return FindEntry<true>(ptr, entry_idx, config, out_entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700356 }
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700357 return FindEntry<false>(ptr, entry_idx, config, out_entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700358}
359
360static bool VerifyType(const Chunk& chunk) {
361 ATRACE_CALL();
Adam Lesinski136fd072017-03-03 13:50:21 -0800362 const ResTable_type* header = chunk.header<ResTable_type, kResTableTypeMinSize>();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700363
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700364 if (!VerifyResTableType(header)) {
365 return false;
366 }
367
Adam Lesinski7ad11102016-10-28 16:39:15 -0700368 const size_t entry_count = dtohl(header->entryCount);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700369 const size_t offsets_offset = chunk.header_size();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700370
Adam Lesinski73f6f9d2017-11-14 10:18:05 -0800371 if (header->flags & ResTable_type::FLAG_SPARSE) {
372 // This is encoded as a sparse map, so perform a binary search.
373 const ResTable_sparseTypeEntry* sparse_indices =
374 reinterpret_cast<const ResTable_sparseTypeEntry*>(reinterpret_cast<const uint8_t*>(header) +
375 offsets_offset);
376 for (size_t i = 0; i < entry_count; i++) {
377 const uint32_t offset = uint32_t{dtohs(sparse_indices[i].offset)} * 4u;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700378 if (!VerifyResTableEntry(header, offset, i)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700379 return false;
380 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700381 }
Adam Lesinski73f6f9d2017-11-14 10:18:05 -0800382 } else {
383 // Check each entry offset.
384 const uint32_t* offsets = reinterpret_cast<const uint32_t*>(
385 reinterpret_cast<const uint8_t*>(header) + offsets_offset);
386 for (size_t i = 0; i < entry_count; i++) {
387 uint32_t offset = dtohl(offsets[i]);
388 if (offset != ResTable_type::NO_ENTRY) {
389 if (!VerifyResTableEntry(header, offset, i)) {
390 return false;
391 }
392 }
393 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700394 }
395 return true;
396}
397
Adam Lesinski0c405242017-01-13 20:47:26 -0800398void LoadedPackage::CollectConfigurations(bool exclude_mipmap,
399 std::set<ResTable_config>* out_configs) const {
400 const static std::u16string kMipMap = u"mipmap";
401 const size_t type_count = type_specs_.size();
402 for (size_t i = 0; i < type_count; i++) {
403 const util::unique_cptr<TypeSpec>& type_spec = type_specs_[i];
404 if (type_spec != nullptr) {
405 if (exclude_mipmap) {
406 const int type_idx = type_spec->type_spec->id - 1;
407 size_t type_name_len;
408 const char16_t* type_name16 = type_string_pool_.stringAt(type_idx, &type_name_len);
409 if (type_name16 != nullptr) {
410 if (kMipMap.compare(0, std::u16string::npos, type_name16, type_name_len) == 0) {
411 // This is a mipmap type, skip collection.
412 continue;
413 }
414 }
415 const char* type_name = type_string_pool_.string8At(type_idx, &type_name_len);
416 if (type_name != nullptr) {
417 if (strncmp(type_name, "mipmap", type_name_len) == 0) {
418 // This is a mipmap type, skip collection.
419 continue;
420 }
421 }
422 }
423
424 for (size_t j = 0; j < type_spec->type_count; j++) {
425 out_configs->insert(type_spec->types[j].configuration);
426 }
427 }
428 }
429}
430
431void LoadedPackage::CollectLocales(bool canonicalize, std::set<std::string>* out_locales) const {
432 char temp_locale[RESTABLE_MAX_LOCALE_LEN];
433 const size_t type_count = type_specs_.size();
434 for (size_t i = 0; i < type_count; i++) {
435 const util::unique_cptr<TypeSpec>& type_spec = type_specs_[i];
436 if (type_spec != nullptr) {
437 for (size_t j = 0; j < type_spec->type_count; j++) {
438 const ResTable_config& configuration = type_spec->types[j].configuration;
439 if (configuration.locale != 0) {
440 configuration.getBcp47Locale(temp_locale, canonicalize);
441 std::string locale(temp_locale);
442 out_locales->insert(std::move(locale));
443 }
444 }
445 }
446 }
447}
448
Adam Lesinski929d6512017-01-16 19:11:19 -0800449uint32_t LoadedPackage::FindEntryByName(const std::u16string& type_name,
450 const std::u16string& entry_name) const {
451 ssize_t type_idx = type_string_pool_.indexOfString(type_name.data(), type_name.size());
452 if (type_idx < 0) {
453 return 0u;
454 }
455
456 ssize_t key_idx = key_string_pool_.indexOfString(entry_name.data(), entry_name.size());
457 if (key_idx < 0) {
458 return 0u;
459 }
460
461 const TypeSpec* type_spec = type_specs_[type_idx].get();
462 if (type_spec == nullptr) {
463 return 0u;
464 }
465
466 for (size_t ti = 0; ti < type_spec->type_count; ti++) {
467 const Type* type = &type_spec->types[ti];
468 size_t entry_count = dtohl(type->type->entryCount);
469 for (size_t entry_idx = 0; entry_idx < entry_count; entry_idx++) {
470 const uint32_t* entry_offsets = reinterpret_cast<const uint32_t*>(
471 reinterpret_cast<const uint8_t*>(type->type) + dtohs(type->type->header.headerSize));
472 const uint32_t offset = dtohl(entry_offsets[entry_idx]);
473 if (offset != ResTable_type::NO_ENTRY) {
474 const ResTable_entry* entry =
475 reinterpret_cast<const ResTable_entry*>(reinterpret_cast<const uint8_t*>(type->type) +
476 dtohl(type->type->entriesStart) + offset);
477 if (dtohl(entry->key.index) == static_cast<uint32_t>(key_idx)) {
478 // The package ID will be overridden by the caller (due to runtime assignment of package
479 // IDs for shared libraries).
480 return make_resid(0x00, type_idx + type_id_offset_ + 1, entry_idx);
481 }
482 }
483 }
484 }
485 return 0u;
486}
487
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700488const LoadedPackage* LoadedArsc::GetPackageForId(uint32_t resid) const {
489 const uint8_t package_id = get_package_id(resid);
490 for (const auto& loaded_package : packages_) {
491 if (loaded_package->GetPackageId() == package_id) {
492 return loaded_package.get();
493 }
494 }
495 return nullptr;
496}
497
498std::unique_ptr<const LoadedPackage> LoadedPackage::Load(const Chunk& chunk,
499 const LoadedIdmap* loaded_idmap,
500 bool system, bool load_as_shared_library) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700501 ATRACE_CALL();
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700502 std::unique_ptr<LoadedPackage> loaded_package(new LoadedPackage());
Adam Lesinskida431a22016-12-29 16:08:16 -0500503
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700504 // typeIdOffset was added at some point, but we still must recognize apps built before this
505 // was added.
Adam Lesinski33af6c72017-03-29 13:00:35 -0700506 constexpr size_t kMinPackageSize =
507 sizeof(ResTable_package) - sizeof(ResTable_package::typeIdOffset);
508 const ResTable_package* header = chunk.header<ResTable_package, kMinPackageSize>();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700509 if (header == nullptr) {
510 LOG(ERROR) << "Chunk RES_TABLE_PACKAGE_TYPE is too small.";
Adam Lesinskida431a22016-12-29 16:08:16 -0500511 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700512 }
513
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700514 loaded_package->system_ = system;
515
Adam Lesinski7ad11102016-10-28 16:39:15 -0700516 loaded_package->package_id_ = dtohl(header->id);
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700517 if (loaded_package->package_id_ == 0 ||
518 (loaded_package->package_id_ == kAppPackageId && load_as_shared_library)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500519 // Package ID of 0 means this is a shared library.
520 loaded_package->dynamic_ = true;
521 }
522
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700523 if (loaded_idmap != nullptr) {
524 // This is an overlay and so it needs to pretend to be the target package.
525 loaded_package->package_id_ = loaded_idmap->TargetPackageId();
526 loaded_package->overlay_ = true;
527 }
528
Adam Lesinskic6aada92017-01-13 15:34:14 -0800529 if (header->header.headerSize >= sizeof(ResTable_package)) {
530 uint32_t type_id_offset = dtohl(header->typeIdOffset);
531 if (type_id_offset > std::numeric_limits<uint8_t>::max()) {
532 LOG(ERROR) << "Type ID offset in RES_TABLE_PACKAGE_TYPE is too large.";
533 return {};
534 }
535 loaded_package->type_id_offset_ = static_cast<int>(type_id_offset);
536 }
537
Adam Lesinskida431a22016-12-29 16:08:16 -0500538 util::ReadUtf16StringFromDevice(header->name, arraysize(header->name),
539 &loaded_package->package_name_);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700540
541 // A TypeSpec builder. We use this to accumulate the set of Types
542 // available for a TypeSpec, and later build a single, contiguous block
543 // of memory that holds all the Types together with the TypeSpec.
544 std::unique_ptr<TypeSpecPtrBuilder> types_builder;
545
546 // Keep track of the last seen type index. Since type IDs are 1-based,
547 // this records their index, which is 0-based (type ID - 1).
548 uint8_t last_type_idx = 0;
549
550 ChunkIterator iter(chunk.data_ptr(), chunk.data_size());
551 while (iter.HasNext()) {
552 const Chunk child_chunk = iter.Next();
553 switch (child_chunk.type()) {
554 case RES_STRING_POOL_TYPE: {
555 const uintptr_t pool_address =
556 reinterpret_cast<uintptr_t>(child_chunk.header<ResChunk_header>());
557 const uintptr_t header_address = reinterpret_cast<uintptr_t>(header);
558 if (pool_address == header_address + dtohl(header->typeStrings)) {
559 // This string pool is the type string pool.
560 status_t err = loaded_package->type_string_pool_.setTo(
561 child_chunk.header<ResStringPool_header>(), child_chunk.size());
562 if (err != NO_ERROR) {
563 LOG(ERROR) << "Corrupt package type string pool.";
Adam Lesinskida431a22016-12-29 16:08:16 -0500564 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700565 }
566 } else if (pool_address == header_address + dtohl(header->keyStrings)) {
567 // This string pool is the key string pool.
568 status_t err = loaded_package->key_string_pool_.setTo(
569 child_chunk.header<ResStringPool_header>(), child_chunk.size());
570 if (err != NO_ERROR) {
571 LOG(ERROR) << "Corrupt package key string pool.";
Adam Lesinskida431a22016-12-29 16:08:16 -0500572 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700573 }
574 } else {
575 LOG(WARNING) << "Too many string pool chunks found in package.";
576 }
577 } break;
578
579 case RES_TABLE_TYPE_SPEC_TYPE: {
580 ATRACE_NAME("LoadTableTypeSpec");
581
582 // Starting a new TypeSpec, so finish the old one if there was one.
583 if (types_builder) {
584 TypeSpecPtr type_spec_ptr = types_builder->Build();
585 if (type_spec_ptr == nullptr) {
586 LOG(ERROR) << "Too many type configurations, overflow detected.";
Adam Lesinskida431a22016-12-29 16:08:16 -0500587 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700588 }
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700589
590 // We only add the type to the package if there is no IDMAP, or if the type is
591 // overlaying something.
592 if (loaded_idmap == nullptr || type_spec_ptr->idmap_entries != nullptr) {
593 // If this is an overlay, insert it at the target type ID.
594 if (type_spec_ptr->idmap_entries != nullptr) {
595 last_type_idx = dtohs(type_spec_ptr->idmap_entries->target_type_id) - 1;
596 }
597 loaded_package->type_specs_.editItemAt(last_type_idx) = std::move(type_spec_ptr);
598 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700599
600 types_builder = {};
601 last_type_idx = 0;
602 }
603
604 const ResTable_typeSpec* type_spec = child_chunk.header<ResTable_typeSpec>();
605 if (type_spec == nullptr) {
606 LOG(ERROR) << "Chunk RES_TABLE_TYPE_SPEC_TYPE is too small.";
Adam Lesinskida431a22016-12-29 16:08:16 -0500607 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700608 }
609
610 if (type_spec->id == 0) {
611 LOG(ERROR) << "Chunk RES_TABLE_TYPE_SPEC_TYPE has invalid ID 0.";
Adam Lesinskida431a22016-12-29 16:08:16 -0500612 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700613 }
614
Adam Lesinskic6aada92017-01-13 15:34:14 -0800615 if (loaded_package->type_id_offset_ + static_cast<int>(type_spec->id) >
616 std::numeric_limits<uint8_t>::max()) {
617 LOG(ERROR) << "Chunk RES_TABLE_TYPE_SPEC_TYPE has out of range ID.";
618 return {};
619 }
620
Adam Lesinski7ad11102016-10-28 16:39:15 -0700621 // The data portion of this chunk contains entry_count 32bit entries,
622 // each one representing a set of flags.
623 // Here we only validate that the chunk is well formed.
624 const size_t entry_count = dtohl(type_spec->entryCount);
625
626 // There can only be 2^16 entries in a type, because that is the ID
627 // space for entries (EEEE) in the resource ID 0xPPTTEEEE.
628 if (entry_count > std::numeric_limits<uint16_t>::max()) {
629 LOG(ERROR) << "Too many entries in RES_TABLE_TYPE_SPEC_TYPE: " << entry_count << ".";
Adam Lesinskida431a22016-12-29 16:08:16 -0500630 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700631 }
632
633 if (entry_count * sizeof(uint32_t) > chunk.data_size()) {
634 LOG(ERROR) << "Chunk too small to hold entries in RES_TABLE_TYPE_SPEC_TYPE.";
Adam Lesinskida431a22016-12-29 16:08:16 -0500635 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700636 }
637
638 last_type_idx = type_spec->id - 1;
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700639
640 // If this is an overlay, associate the mapping of this type to the target type
641 // from the IDMAP.
642 const IdmapEntry_header* idmap_entry_header = nullptr;
643 if (loaded_idmap != nullptr) {
644 idmap_entry_header = loaded_idmap->GetEntryMapForType(type_spec->id);
645 }
646
647 types_builder = util::make_unique<TypeSpecPtrBuilder>(type_spec, idmap_entry_header);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700648 } break;
649
650 case RES_TABLE_TYPE_TYPE: {
Adam Lesinski136fd072017-03-03 13:50:21 -0800651 const ResTable_type* type = child_chunk.header<ResTable_type, kResTableTypeMinSize>();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700652 if (type == nullptr) {
653 LOG(ERROR) << "Chunk RES_TABLE_TYPE_TYPE is too small.";
Adam Lesinskida431a22016-12-29 16:08:16 -0500654 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700655 }
656
657 if (type->id == 0) {
658 LOG(ERROR) << "Chunk RES_TABLE_TYPE_TYPE has invalid ID 0.";
Adam Lesinskida431a22016-12-29 16:08:16 -0500659 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700660 }
661
662 // Type chunks must be preceded by their TypeSpec chunks.
663 if (!types_builder || type->id - 1 != last_type_idx) {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700664 LOG(ERROR) << "Found RES_TABLE_TYPE_TYPE chunk without RES_TABLE_TYPE_SPEC_TYPE.";
Adam Lesinskida431a22016-12-29 16:08:16 -0500665 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700666 }
667
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700668 // Only verify the type if we haven't already failed verification.
669 if (loaded_package->verified_) {
670 if (!VerifyType(child_chunk)) {
671 LOG(WARNING) << "Package failed verification, resource retrieval may be slower";
672 loaded_package->verified_ = false;
673 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700674 }
675
676 types_builder->AddType(type);
677 } break;
678
Adam Lesinskida431a22016-12-29 16:08:16 -0500679 case RES_TABLE_LIBRARY_TYPE: {
680 const ResTable_lib_header* lib = child_chunk.header<ResTable_lib_header>();
681 if (lib == nullptr) {
682 LOG(ERROR) << "Chunk RES_TABLE_LIBRARY_TYPE is too small.";
683 return {};
684 }
685
686 if (child_chunk.data_size() / sizeof(ResTable_lib_entry) < dtohl(lib->count)) {
687 LOG(ERROR) << "Chunk too small to hold entries in RES_TABLE_LIBRARY_TYPE.";
688 return {};
689 }
690
691 loaded_package->dynamic_package_map_.reserve(dtohl(lib->count));
692
693 const ResTable_lib_entry* const entry_begin =
694 reinterpret_cast<const ResTable_lib_entry*>(child_chunk.data_ptr());
695 const ResTable_lib_entry* const entry_end = entry_begin + dtohl(lib->count);
696 for (auto entry_iter = entry_begin; entry_iter != entry_end; ++entry_iter) {
697 std::string package_name;
698 util::ReadUtf16StringFromDevice(entry_iter->packageName,
699 arraysize(entry_iter->packageName), &package_name);
700
701 if (dtohl(entry_iter->packageId) >= std::numeric_limits<uint8_t>::max()) {
702 LOG(ERROR) << base::StringPrintf(
703 "Package ID %02x in RES_TABLE_LIBRARY_TYPE too large for package '%s'.",
704 dtohl(entry_iter->packageId), package_name.c_str());
705 return {};
706 }
707
708 loaded_package->dynamic_package_map_.emplace_back(std::move(package_name),
709 dtohl(entry_iter->packageId));
710 }
711
712 } break;
713
Adam Lesinski7ad11102016-10-28 16:39:15 -0700714 default:
715 LOG(WARNING) << base::StringPrintf("Unknown chunk type '%02x'.", chunk.type());
716 break;
717 }
718 }
719
720 // Finish the last TypeSpec.
721 if (types_builder) {
722 TypeSpecPtr type_spec_ptr = types_builder->Build();
723 if (type_spec_ptr == nullptr) {
724 LOG(ERROR) << "Too many type configurations, overflow detected.";
Adam Lesinskida431a22016-12-29 16:08:16 -0500725 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700726 }
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700727
728 // We only add the type to the package if there is no IDMAP, or if the type is
729 // overlaying something.
730 if (loaded_idmap == nullptr || type_spec_ptr->idmap_entries != nullptr) {
731 // If this is an overlay, insert it at the target type ID.
732 if (type_spec_ptr->idmap_entries != nullptr) {
733 last_type_idx = dtohs(type_spec_ptr->idmap_entries->target_type_id) - 1;
734 }
735 loaded_package->type_specs_.editItemAt(last_type_idx) = std::move(type_spec_ptr);
736 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700737 }
738
739 if (iter.HadError()) {
740 LOG(ERROR) << iter.GetLastError();
Adam Lesinskida431a22016-12-29 16:08:16 -0500741 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700742 }
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700743 return std::move(loaded_package);
744}
745
746bool LoadedArsc::FindEntry(uint32_t resid, const ResTable_config& config,
747 FindEntryResult* out_entry) const {
748 ATRACE_CALL();
749
750 const uint8_t package_id = get_package_id(resid);
751 const uint8_t type_id = get_type_id(resid);
752 const uint16_t entry_id = get_entry_id(resid);
753
754 if (type_id == 0) {
755 LOG(ERROR) << base::StringPrintf("Invalid ID 0x%08x.", resid);
756 return false;
757 }
758
759 for (const auto& loaded_package : packages_) {
760 if (loaded_package->GetPackageId() == package_id) {
761 return loaded_package->FindEntry(type_id - 1, entry_id, config, out_entry);
762 }
763 }
764 return false;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700765}
766
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700767bool LoadedArsc::LoadTable(const Chunk& chunk, const LoadedIdmap* loaded_idmap,
768 bool load_as_shared_library) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700769 ATRACE_CALL();
770 const ResTable_header* header = chunk.header<ResTable_header>();
771 if (header == nullptr) {
772 LOG(ERROR) << "Chunk RES_TABLE_TYPE is too small.";
773 return false;
774 }
775
776 const size_t package_count = dtohl(header->packageCount);
777 size_t packages_seen = 0;
778
779 packages_.reserve(package_count);
780
781 ChunkIterator iter(chunk.data_ptr(), chunk.data_size());
782 while (iter.HasNext()) {
783 const Chunk child_chunk = iter.Next();
784 switch (child_chunk.type()) {
785 case RES_STRING_POOL_TYPE:
786 // Only use the first string pool. Ignore others.
787 if (global_string_pool_.getError() == NO_INIT) {
788 status_t err = global_string_pool_.setTo(child_chunk.header<ResStringPool_header>(),
789 child_chunk.size());
790 if (err != NO_ERROR) {
791 LOG(ERROR) << "Corrupt string pool.";
792 return false;
793 }
794 } else {
795 LOG(WARNING) << "Multiple string pool chunks found in resource table.";
796 }
797 break;
798
799 case RES_TABLE_PACKAGE_TYPE: {
800 if (packages_seen + 1 > package_count) {
801 LOG(ERROR) << "More package chunks were found than the " << package_count
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700802 << " declared in the header.";
Adam Lesinski7ad11102016-10-28 16:39:15 -0700803 return false;
804 }
805 packages_seen++;
806
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700807 std::unique_ptr<const LoadedPackage> loaded_package =
808 LoadedPackage::Load(child_chunk, loaded_idmap, system_, load_as_shared_library);
Adam Lesinskida431a22016-12-29 16:08:16 -0500809 if (!loaded_package) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700810 return false;
811 }
812 packages_.push_back(std::move(loaded_package));
813 } break;
814
815 default:
816 LOG(WARNING) << base::StringPrintf("Unknown chunk type '%02x'.", chunk.type());
817 break;
818 }
819 }
820
821 if (iter.HadError()) {
822 LOG(ERROR) << iter.GetLastError();
823 return false;
824 }
825 return true;
826}
827
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700828std::unique_ptr<const LoadedArsc> LoadedArsc::Load(const StringPiece& data,
829 const LoadedIdmap* loaded_idmap, bool system,
Adam Lesinski0c405242017-01-13 20:47:26 -0800830 bool load_as_shared_library) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700831 ATRACE_CALL();
832
833 // Not using make_unique because the constructor is private.
834 std::unique_ptr<LoadedArsc> loaded_arsc(new LoadedArsc());
Adam Lesinski0c405242017-01-13 20:47:26 -0800835 loaded_arsc->system_ = system;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700836
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700837 ChunkIterator iter(data.data(), data.size());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700838 while (iter.HasNext()) {
839 const Chunk chunk = iter.Next();
840 switch (chunk.type()) {
841 case RES_TABLE_TYPE:
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700842 if (!loaded_arsc->LoadTable(chunk, loaded_idmap, load_as_shared_library)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700843 return {};
844 }
845 break;
846
847 default:
848 LOG(WARNING) << base::StringPrintf("Unknown chunk type '%02x'.", chunk.type());
849 break;
850 }
851 }
852
853 if (iter.HadError()) {
854 LOG(ERROR) << iter.GetLastError();
855 return {};
856 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800857
858 // Need to force a move for mingw32.
859 return std::move(loaded_arsc);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700860}
861
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700862std::unique_ptr<const LoadedArsc> LoadedArsc::CreateEmpty() {
863 return std::unique_ptr<LoadedArsc>(new LoadedArsc());
864}
865
Adam Lesinski7ad11102016-10-28 16:39:15 -0700866} // namespace android