1 /*
2 * Copyright (C) 2008 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 LOG_TAG "ResourceType"
18 //#define LOG_NDEBUG 0
19
20 #include <ctype.h>
21 #include <memory.h>
22 #include <stddef.h>
23 #include <stdint.h>
24 #include <stdlib.h>
25 #include <string.h>
26
27 #include <algorithm>
28 #include <limits>
29 #include <map>
30 #include <memory>
31 #include <set>
32 #include <type_traits>
33
34 #include <android-base/macros.h>
35 #include <androidfw/ByteBucketArray.h>
36 #include <androidfw/ResourceTypes.h>
37 #include <androidfw/TypeWrappers.h>
38 #include <cutils/atomic.h>
39 #include <utils/ByteOrder.h>
40 #include <utils/Debug.h>
41 #include <utils/Log.h>
42 #include <utils/String16.h>
43 #include <utils/String8.h>
44
45 #ifdef __ANDROID__
46 #include <binder/TextOutput.h>
47 #endif
48
49 #ifndef INT32_MAX
50 #define INT32_MAX ((int32_t)(2147483647))
51 #endif
52
53 namespace android {
54
55 #if defined(_WIN32)
56 #undef nhtol
57 #undef htonl
58 #define ntohl(x) ( ((x) << 24) | (((x) >> 24) & 255) | (((x) << 8) & 0xff0000) | (((x) >> 8) & 0xff00) )
59 #define htonl(x) ntohl(x)
60 #define ntohs(x) ( (((x) << 8) & 0xff00) | (((x) >> 8) & 255) )
61 #define htons(x) ntohs(x)
62 #endif
63
64 #define IDMAP_MAGIC 0x504D4449
65
66 #define APP_PACKAGE_ID 0x7f
67 #define SYS_PACKAGE_ID 0x01
68
69 static const bool kDebugStringPoolNoisy = false;
70 static const bool kDebugXMLNoisy = false;
71 static const bool kDebugTableNoisy = false;
72 static const bool kDebugTableGetEntry = false;
73 static const bool kDebugTableSuperNoisy = false;
74 static const bool kDebugLoadTableNoisy = false;
75 static const bool kDebugLoadTableSuperNoisy = false;
76 static const bool kDebugTableTheme = false;
77 static const bool kDebugResXMLTree = false;
78 static const bool kDebugLibNoisy = false;
79
80 // TODO: This code uses 0xFFFFFFFF converted to bag_set* as a sentinel value. This is bad practice.
81
82 // Standard C isspace() is only required to look at the low byte of its input, so
83 // produces incorrect results for UTF-16 characters. For safety's sake, assume that
84 // any high-byte UTF-16 code point is not whitespace.
isspace16(char16_t c)85 inline int isspace16(char16_t c) {
86 return (c < 0x0080 && isspace(c));
87 }
88
89 template<typename T>
max(T a,T b)90 inline static T max(T a, T b) {
91 return a > b ? a : b;
92 }
93
94 // range checked; guaranteed to NUL-terminate within the stated number of available slots
95 // NOTE: if this truncates the dst string due to running out of space, no attempt is
96 // made to avoid splitting surrogate pairs.
strcpy16_dtoh(char16_t * dst,const uint16_t * src,size_t avail)97 static void strcpy16_dtoh(char16_t* dst, const uint16_t* src, size_t avail)
98 {
99 char16_t* last = dst + avail - 1;
100 while (*src && (dst < last)) {
101 char16_t s = dtohs(static_cast<char16_t>(*src));
102 *dst++ = s;
103 src++;
104 }
105 *dst = 0;
106 }
107
validate_chunk(const ResChunk_header * chunk,size_t minSize,const uint8_t * dataEnd,const char * name)108 static status_t validate_chunk(const ResChunk_header* chunk,
109 size_t minSize,
110 const uint8_t* dataEnd,
111 const char* name)
112 {
113 const uint16_t headerSize = dtohs(chunk->headerSize);
114 const uint32_t size = dtohl(chunk->size);
115
116 if (headerSize >= minSize) {
117 if (headerSize <= size) {
118 if (((headerSize|size)&0x3) == 0) {
119 if ((size_t)size <= (size_t)(dataEnd-((const uint8_t*)chunk))) {
120 return NO_ERROR;
121 }
122 ALOGW("%s data size 0x%x extends beyond resource end %p.",
123 name, size, (void*)(dataEnd-((const uint8_t*)chunk)));
124 return BAD_TYPE;
125 }
126 ALOGW("%s size 0x%x or headerSize 0x%x is not on an integer boundary.",
127 name, (int)size, (int)headerSize);
128 return BAD_TYPE;
129 }
130 ALOGW("%s size 0x%x is smaller than header size 0x%x.",
131 name, size, headerSize);
132 return BAD_TYPE;
133 }
134 ALOGW("%s header size 0x%04x is too small.",
135 name, headerSize);
136 return BAD_TYPE;
137 }
138
fill9patchOffsets(Res_png_9patch * patch)139 static void fill9patchOffsets(Res_png_9patch* patch) {
140 patch->xDivsOffset = sizeof(Res_png_9patch);
141 patch->yDivsOffset = patch->xDivsOffset + (patch->numXDivs * sizeof(int32_t));
142 patch->colorsOffset = patch->yDivsOffset + (patch->numYDivs * sizeof(int32_t));
143 }
144
copyFrom_dtoh(const Res_value & src)145 void Res_value::copyFrom_dtoh(const Res_value& src)
146 {
147 size = dtohs(src.size);
148 res0 = src.res0;
149 dataType = src.dataType;
150 data = dtohl(src.data);
151 }
152
deviceToFile()153 void Res_png_9patch::deviceToFile()
154 {
155 int32_t* xDivs = getXDivs();
156 for (int i = 0; i < numXDivs; i++) {
157 xDivs[i] = htonl(xDivs[i]);
158 }
159 int32_t* yDivs = getYDivs();
160 for (int i = 0; i < numYDivs; i++) {
161 yDivs[i] = htonl(yDivs[i]);
162 }
163 paddingLeft = htonl(paddingLeft);
164 paddingRight = htonl(paddingRight);
165 paddingTop = htonl(paddingTop);
166 paddingBottom = htonl(paddingBottom);
167 uint32_t* colors = getColors();
168 for (int i=0; i<numColors; i++) {
169 colors[i] = htonl(colors[i]);
170 }
171 }
172
fileToDevice()173 void Res_png_9patch::fileToDevice()
174 {
175 int32_t* xDivs = getXDivs();
176 for (int i = 0; i < numXDivs; i++) {
177 xDivs[i] = ntohl(xDivs[i]);
178 }
179 int32_t* yDivs = getYDivs();
180 for (int i = 0; i < numYDivs; i++) {
181 yDivs[i] = ntohl(yDivs[i]);
182 }
183 paddingLeft = ntohl(paddingLeft);
184 paddingRight = ntohl(paddingRight);
185 paddingTop = ntohl(paddingTop);
186 paddingBottom = ntohl(paddingBottom);
187 uint32_t* colors = getColors();
188 for (int i=0; i<numColors; i++) {
189 colors[i] = ntohl(colors[i]);
190 }
191 }
192
serializedSize() const193 size_t Res_png_9patch::serializedSize() const
194 {
195 // The size of this struct is 32 bytes on the 32-bit target system
196 // 4 * int8_t
197 // 4 * int32_t
198 // 3 * uint32_t
199 return 32
200 + numXDivs * sizeof(int32_t)
201 + numYDivs * sizeof(int32_t)
202 + numColors * sizeof(uint32_t);
203 }
204
serialize(const Res_png_9patch & patch,const int32_t * xDivs,const int32_t * yDivs,const uint32_t * colors)205 void* Res_png_9patch::serialize(const Res_png_9patch& patch, const int32_t* xDivs,
206 const int32_t* yDivs, const uint32_t* colors)
207 {
208 // Use calloc since we're going to leave a few holes in the data
209 // and want this to run cleanly under valgrind
210 void* newData = calloc(1, patch.serializedSize());
211 serialize(patch, xDivs, yDivs, colors, newData);
212 return newData;
213 }
214
serialize(const Res_png_9patch & patch,const int32_t * xDivs,const int32_t * yDivs,const uint32_t * colors,void * outData)215 void Res_png_9patch::serialize(const Res_png_9patch& patch, const int32_t* xDivs,
216 const int32_t* yDivs, const uint32_t* colors, void* outData)
217 {
218 uint8_t* data = (uint8_t*) outData;
219 memcpy(data, &patch.wasDeserialized, 4); // copy wasDeserialized, numXDivs, numYDivs, numColors
220 memcpy(data + 12, &patch.paddingLeft, 16); // copy paddingXXXX
221 data += 32;
222
223 memcpy(data, xDivs, patch.numXDivs * sizeof(int32_t));
224 data += patch.numXDivs * sizeof(int32_t);
225 memcpy(data, yDivs, patch.numYDivs * sizeof(int32_t));
226 data += patch.numYDivs * sizeof(int32_t);
227 memcpy(data, colors, patch.numColors * sizeof(uint32_t));
228
229 fill9patchOffsets(reinterpret_cast<Res_png_9patch*>(outData));
230 }
231
assertIdmapHeader(const void * idmap,size_t size)232 static bool assertIdmapHeader(const void* idmap, size_t size) {
233 if (reinterpret_cast<uintptr_t>(idmap) & 0x03) {
234 ALOGE("idmap: header is not word aligned");
235 return false;
236 }
237
238 if (size < ResTable::IDMAP_HEADER_SIZE_BYTES) {
239 ALOGW("idmap: header too small (%d bytes)", (uint32_t) size);
240 return false;
241 }
242
243 const uint32_t magic = htodl(*reinterpret_cast<const uint32_t*>(idmap));
244 if (magic != IDMAP_MAGIC) {
245 ALOGW("idmap: no magic found in header (is 0x%08x, expected 0x%08x)",
246 magic, IDMAP_MAGIC);
247 return false;
248 }
249
250 const uint32_t version = htodl(*(reinterpret_cast<const uint32_t*>(idmap) + 1));
251 if (version != ResTable::IDMAP_CURRENT_VERSION) {
252 // We are strict about versions because files with this format are
253 // auto-generated and don't need backwards compatibility.
254 ALOGW("idmap: version mismatch in header (is 0x%08x, expected 0x%08x)",
255 version, ResTable::IDMAP_CURRENT_VERSION);
256 return false;
257 }
258 return true;
259 }
260
261 class IdmapEntries {
262 public:
IdmapEntries()263 IdmapEntries() : mData(NULL) {}
264
hasEntries() const265 bool hasEntries() const {
266 if (mData == NULL) {
267 return false;
268 }
269
270 return (dtohs(*mData) > 0);
271 }
272
byteSize() const273 size_t byteSize() const {
274 if (mData == NULL) {
275 return 0;
276 }
277 uint16_t entryCount = dtohs(mData[2]);
278 return (sizeof(uint16_t) * 4) + (sizeof(uint32_t) * static_cast<size_t>(entryCount));
279 }
280
targetTypeId() const281 uint8_t targetTypeId() const {
282 if (mData == NULL) {
283 return 0;
284 }
285 return dtohs(mData[0]);
286 }
287
overlayTypeId() const288 uint8_t overlayTypeId() const {
289 if (mData == NULL) {
290 return 0;
291 }
292 return dtohs(mData[1]);
293 }
294
setTo(const void * entryHeader,size_t size)295 status_t setTo(const void* entryHeader, size_t size) {
296 if (reinterpret_cast<uintptr_t>(entryHeader) & 0x03) {
297 ALOGE("idmap: entry header is not word aligned");
298 return UNKNOWN_ERROR;
299 }
300
301 if (size < sizeof(uint16_t) * 4) {
302 ALOGE("idmap: entry header is too small (%u bytes)", (uint32_t) size);
303 return UNKNOWN_ERROR;
304 }
305
306 const uint16_t* header = reinterpret_cast<const uint16_t*>(entryHeader);
307 const uint16_t targetTypeId = dtohs(header[0]);
308 const uint16_t overlayTypeId = dtohs(header[1]);
309 if (targetTypeId == 0 || overlayTypeId == 0 || targetTypeId > 255 || overlayTypeId > 255) {
310 ALOGE("idmap: invalid type map (%u -> %u)", targetTypeId, overlayTypeId);
311 return UNKNOWN_ERROR;
312 }
313
314 uint16_t entryCount = dtohs(header[2]);
315 if (size < sizeof(uint32_t) * (entryCount + 2)) {
316 ALOGE("idmap: too small (%u bytes) for the number of entries (%u)",
317 (uint32_t) size, (uint32_t) entryCount);
318 return UNKNOWN_ERROR;
319 }
320 mData = header;
321 return NO_ERROR;
322 }
323
lookup(uint16_t entryId,uint16_t * outEntryId) const324 status_t lookup(uint16_t entryId, uint16_t* outEntryId) const {
325 uint16_t entryCount = dtohs(mData[2]);
326 uint16_t offset = dtohs(mData[3]);
327
328 if (entryId < offset) {
329 // The entry is not present in this idmap
330 return BAD_INDEX;
331 }
332
333 entryId -= offset;
334
335 if (entryId >= entryCount) {
336 // The entry is not present in this idmap
337 return BAD_INDEX;
338 }
339
340 // It is safe to access the type here without checking the size because
341 // we have checked this when it was first loaded.
342 const uint32_t* entries = reinterpret_cast<const uint32_t*>(mData) + 2;
343 uint32_t mappedEntry = dtohl(entries[entryId]);
344 if (mappedEntry == 0xffffffff) {
345 // This entry is not present in this idmap
346 return BAD_INDEX;
347 }
348 *outEntryId = static_cast<uint16_t>(mappedEntry);
349 return NO_ERROR;
350 }
351
352 private:
353 const uint16_t* mData;
354 };
355
parseIdmap(const void * idmap,size_t size,uint8_t * outPackageId,KeyedVector<uint8_t,IdmapEntries> * outMap)356 status_t parseIdmap(const void* idmap, size_t size, uint8_t* outPackageId, KeyedVector<uint8_t, IdmapEntries>* outMap) {
357 if (!assertIdmapHeader(idmap, size)) {
358 return UNKNOWN_ERROR;
359 }
360
361 size -= ResTable::IDMAP_HEADER_SIZE_BYTES;
362 if (size < sizeof(uint16_t) * 2) {
363 ALOGE("idmap: too small to contain any mapping");
364 return UNKNOWN_ERROR;
365 }
366
367 const uint16_t* data = reinterpret_cast<const uint16_t*>(
368 reinterpret_cast<const uint8_t*>(idmap) + ResTable::IDMAP_HEADER_SIZE_BYTES);
369
370 uint16_t targetPackageId = dtohs(*(data++));
371 if (targetPackageId == 0 || targetPackageId > 255) {
372 ALOGE("idmap: target package ID is invalid (%02x)", targetPackageId);
373 return UNKNOWN_ERROR;
374 }
375
376 uint16_t mapCount = dtohs(*(data++));
377 if (mapCount == 0) {
378 ALOGE("idmap: no mappings");
379 return UNKNOWN_ERROR;
380 }
381
382 if (mapCount > 255) {
383 ALOGW("idmap: too many mappings. Only 255 are possible but %u are present", (uint32_t) mapCount);
384 }
385
386 while (size > sizeof(uint16_t) * 4) {
387 IdmapEntries entries;
388 status_t err = entries.setTo(data, size);
389 if (err != NO_ERROR) {
390 return err;
391 }
392
393 ssize_t index = outMap->add(entries.overlayTypeId(), entries);
394 if (index < 0) {
395 return NO_MEMORY;
396 }
397
398 data += entries.byteSize() / sizeof(uint16_t);
399 size -= entries.byteSize();
400 }
401
402 if (outPackageId != NULL) {
403 *outPackageId = static_cast<uint8_t>(targetPackageId);
404 }
405 return NO_ERROR;
406 }
407
deserialize(void * inData)408 Res_png_9patch* Res_png_9patch::deserialize(void* inData)
409 {
410
411 Res_png_9patch* patch = reinterpret_cast<Res_png_9patch*>(inData);
412 patch->wasDeserialized = true;
413 fill9patchOffsets(patch);
414
415 return patch;
416 }
417
418 // --------------------------------------------------------------------
419 // --------------------------------------------------------------------
420 // --------------------------------------------------------------------
421
ResStringPool()422 ResStringPool::ResStringPool()
423 : mError(NO_INIT), mOwnedData(NULL), mHeader(NULL), mCache(NULL)
424 {
425 }
426
ResStringPool(const void * data,size_t size,bool copyData)427 ResStringPool::ResStringPool(const void* data, size_t size, bool copyData)
428 : mError(NO_INIT), mOwnedData(NULL), mHeader(NULL), mCache(NULL)
429 {
430 setTo(data, size, copyData);
431 }
432
~ResStringPool()433 ResStringPool::~ResStringPool()
434 {
435 uninit();
436 }
437
setToEmpty()438 void ResStringPool::setToEmpty()
439 {
440 uninit();
441
442 mOwnedData = calloc(1, sizeof(ResStringPool_header));
443 ResStringPool_header* header = (ResStringPool_header*) mOwnedData;
444 mSize = 0;
445 mEntries = NULL;
446 mStrings = NULL;
447 mStringPoolSize = 0;
448 mEntryStyles = NULL;
449 mStyles = NULL;
450 mStylePoolSize = 0;
451 mHeader = (const ResStringPool_header*) header;
452 }
453
setTo(const void * data,size_t size,bool copyData)454 status_t ResStringPool::setTo(const void* data, size_t size, bool copyData)
455 {
456 if (!data || !size) {
457 return (mError=BAD_TYPE);
458 }
459
460 uninit();
461
462 // The chunk must be at least the size of the string pool header.
463 if (size < sizeof(ResStringPool_header)) {
464 ALOGW("Bad string block: data size %zu is too small to be a string block", size);
465 return (mError=BAD_TYPE);
466 }
467
468 // The data is at least as big as a ResChunk_header, so we can safely validate the other
469 // header fields.
470 // `data + size` is safe because the source of `size` comes from the kernel/filesystem.
471 if (validate_chunk(reinterpret_cast<const ResChunk_header*>(data), sizeof(ResStringPool_header),
472 reinterpret_cast<const uint8_t*>(data) + size,
473 "ResStringPool_header") != NO_ERROR) {
474 ALOGW("Bad string block: malformed block dimensions");
475 return (mError=BAD_TYPE);
476 }
477
478 const bool notDeviceEndian = htods(0xf0) != 0xf0;
479
480 if (copyData || notDeviceEndian) {
481 mOwnedData = malloc(size);
482 if (mOwnedData == NULL) {
483 return (mError=NO_MEMORY);
484 }
485 memcpy(mOwnedData, data, size);
486 data = mOwnedData;
487 }
488
489 // The size has been checked, so it is safe to read the data in the ResStringPool_header
490 // data structure.
491 mHeader = (const ResStringPool_header*)data;
492
493 if (notDeviceEndian) {
494 ResStringPool_header* h = const_cast<ResStringPool_header*>(mHeader);
495 h->header.headerSize = dtohs(mHeader->header.headerSize);
496 h->header.type = dtohs(mHeader->header.type);
497 h->header.size = dtohl(mHeader->header.size);
498 h->stringCount = dtohl(mHeader->stringCount);
499 h->styleCount = dtohl(mHeader->styleCount);
500 h->flags = dtohl(mHeader->flags);
501 h->stringsStart = dtohl(mHeader->stringsStart);
502 h->stylesStart = dtohl(mHeader->stylesStart);
503 }
504
505 if (mHeader->header.headerSize > mHeader->header.size
506 || mHeader->header.size > size) {
507 ALOGW("Bad string block: header size %d or total size %d is larger than data size %d\n",
508 (int)mHeader->header.headerSize, (int)mHeader->header.size, (int)size);
509 return (mError=BAD_TYPE);
510 }
511 mSize = mHeader->header.size;
512 mEntries = (const uint32_t*)
513 (((const uint8_t*)data)+mHeader->header.headerSize);
514
515 if (mHeader->stringCount > 0) {
516 if ((mHeader->stringCount*sizeof(uint32_t) < mHeader->stringCount) // uint32 overflow?
517 || (mHeader->header.headerSize+(mHeader->stringCount*sizeof(uint32_t)))
518 > size) {
519 ALOGW("Bad string block: entry of %d items extends past data size %d\n",
520 (int)(mHeader->header.headerSize+(mHeader->stringCount*sizeof(uint32_t))),
521 (int)size);
522 return (mError=BAD_TYPE);
523 }
524
525 size_t charSize;
526 if (mHeader->flags&ResStringPool_header::UTF8_FLAG) {
527 charSize = sizeof(uint8_t);
528 } else {
529 charSize = sizeof(uint16_t);
530 }
531
532 // There should be at least space for the smallest string
533 // (2 bytes length, null terminator).
534 if (mHeader->stringsStart >= (mSize - sizeof(uint16_t))) {
535 ALOGW("Bad string block: string pool starts at %d, after total size %d\n",
536 (int)mHeader->stringsStart, (int)mHeader->header.size);
537 return (mError=BAD_TYPE);
538 }
539
540 mStrings = (const void*)
541 (((const uint8_t*)data) + mHeader->stringsStart);
542
543 if (mHeader->styleCount == 0) {
544 mStringPoolSize = (mSize - mHeader->stringsStart) / charSize;
545 } else {
546 // check invariant: styles starts before end of data
547 if (mHeader->stylesStart >= (mSize - sizeof(uint16_t))) {
548 ALOGW("Bad style block: style block starts at %d past data size of %d\n",
549 (int)mHeader->stylesStart, (int)mHeader->header.size);
550 return (mError=BAD_TYPE);
551 }
552 // check invariant: styles follow the strings
553 if (mHeader->stylesStart <= mHeader->stringsStart) {
554 ALOGW("Bad style block: style block starts at %d, before strings at %d\n",
555 (int)mHeader->stylesStart, (int)mHeader->stringsStart);
556 return (mError=BAD_TYPE);
557 }
558 mStringPoolSize =
559 (mHeader->stylesStart-mHeader->stringsStart)/charSize;
560 }
561
562 // check invariant: stringCount > 0 requires a string pool to exist
563 if (mStringPoolSize == 0) {
564 ALOGW("Bad string block: stringCount is %d but pool size is 0\n", (int)mHeader->stringCount);
565 return (mError=BAD_TYPE);
566 }
567
568 if (notDeviceEndian) {
569 size_t i;
570 uint32_t* e = const_cast<uint32_t*>(mEntries);
571 for (i=0; i<mHeader->stringCount; i++) {
572 e[i] = dtohl(mEntries[i]);
573 }
574 if (!(mHeader->flags&ResStringPool_header::UTF8_FLAG)) {
575 const uint16_t* strings = (const uint16_t*)mStrings;
576 uint16_t* s = const_cast<uint16_t*>(strings);
577 for (i=0; i<mStringPoolSize; i++) {
578 s[i] = dtohs(strings[i]);
579 }
580 }
581 }
582
583 if ((mHeader->flags&ResStringPool_header::UTF8_FLAG &&
584 ((uint8_t*)mStrings)[mStringPoolSize-1] != 0) ||
585 (!(mHeader->flags&ResStringPool_header::UTF8_FLAG) &&
586 ((uint16_t*)mStrings)[mStringPoolSize-1] != 0)) {
587 ALOGW("Bad string block: last string is not 0-terminated\n");
588 return (mError=BAD_TYPE);
589 }
590 } else {
591 mStrings = NULL;
592 mStringPoolSize = 0;
593 }
594
595 if (mHeader->styleCount > 0) {
596 mEntryStyles = mEntries + mHeader->stringCount;
597 // invariant: integer overflow in calculating mEntryStyles
598 if (mEntryStyles < mEntries) {
599 ALOGW("Bad string block: integer overflow finding styles\n");
600 return (mError=BAD_TYPE);
601 }
602
603 if (((const uint8_t*)mEntryStyles-(const uint8_t*)mHeader) > (int)size) {
604 ALOGW("Bad string block: entry of %d styles extends past data size %d\n",
605 (int)((const uint8_t*)mEntryStyles-(const uint8_t*)mHeader),
606 (int)size);
607 return (mError=BAD_TYPE);
608 }
609 mStyles = (const uint32_t*)
610 (((const uint8_t*)data)+mHeader->stylesStart);
611 if (mHeader->stylesStart >= mHeader->header.size) {
612 ALOGW("Bad string block: style pool starts %d, after total size %d\n",
613 (int)mHeader->stylesStart, (int)mHeader->header.size);
614 return (mError=BAD_TYPE);
615 }
616 mStylePoolSize =
617 (mHeader->header.size-mHeader->stylesStart)/sizeof(uint32_t);
618
619 if (notDeviceEndian) {
620 size_t i;
621 uint32_t* e = const_cast<uint32_t*>(mEntryStyles);
622 for (i=0; i<mHeader->styleCount; i++) {
623 e[i] = dtohl(mEntryStyles[i]);
624 }
625 uint32_t* s = const_cast<uint32_t*>(mStyles);
626 for (i=0; i<mStylePoolSize; i++) {
627 s[i] = dtohl(mStyles[i]);
628 }
629 }
630
631 const ResStringPool_span endSpan = {
632 { htodl(ResStringPool_span::END) },
633 htodl(ResStringPool_span::END), htodl(ResStringPool_span::END)
634 };
635 if (memcmp(&mStyles[mStylePoolSize-(sizeof(endSpan)/sizeof(uint32_t))],
636 &endSpan, sizeof(endSpan)) != 0) {
637 ALOGW("Bad string block: last style is not 0xFFFFFFFF-terminated\n");
638 return (mError=BAD_TYPE);
639 }
640 } else {
641 mEntryStyles = NULL;
642 mStyles = NULL;
643 mStylePoolSize = 0;
644 }
645
646 return (mError=NO_ERROR);
647 }
648
getError() const649 status_t ResStringPool::getError() const
650 {
651 return mError;
652 }
653
uninit()654 void ResStringPool::uninit()
655 {
656 mError = NO_INIT;
657 if (mHeader != NULL && mCache != NULL) {
658 for (size_t x = 0; x < mHeader->stringCount; x++) {
659 if (mCache[x] != NULL) {
660 free(mCache[x]);
661 mCache[x] = NULL;
662 }
663 }
664 free(mCache);
665 mCache = NULL;
666 }
667 if (mOwnedData) {
668 free(mOwnedData);
669 mOwnedData = NULL;
670 }
671 }
672
673 /**
674 * Strings in UTF-16 format have length indicated by a length encoded in the
675 * stored data. It is either 1 or 2 characters of length data. This allows a
676 * maximum length of 0x7FFFFFF (2147483647 bytes), but if you're storing that
677 * much data in a string, you're abusing them.
678 *
679 * If the high bit is set, then there are two characters or 4 bytes of length
680 * data encoded. In that case, drop the high bit of the first character and
681 * add it together with the next character.
682 */
683 static inline size_t
decodeLength(const uint16_t ** str)684 decodeLength(const uint16_t** str)
685 {
686 size_t len = **str;
687 if ((len & 0x8000) != 0) {
688 (*str)++;
689 len = ((len & 0x7FFF) << 16) | **str;
690 }
691 (*str)++;
692 return len;
693 }
694
695 /**
696 * Strings in UTF-8 format have length indicated by a length encoded in the
697 * stored data. It is either 1 or 2 characters of length data. This allows a
698 * maximum length of 0x7FFF (32767 bytes), but you should consider storing
699 * text in another way if you're using that much data in a single string.
700 *
701 * If the high bit is set, then there are two characters or 2 bytes of length
702 * data encoded. In that case, drop the high bit of the first character and
703 * add it together with the next character.
704 */
705 static inline size_t
decodeLength(const uint8_t ** str)706 decodeLength(const uint8_t** str)
707 {
708 size_t len = **str;
709 if ((len & 0x80) != 0) {
710 (*str)++;
711 len = ((len & 0x7F) << 8) | **str;
712 }
713 (*str)++;
714 return len;
715 }
716
stringAt(size_t idx,size_t * u16len) const717 const char16_t* ResStringPool::stringAt(size_t idx, size_t* u16len) const
718 {
719 if (mError == NO_ERROR && idx < mHeader->stringCount) {
720 const bool isUTF8 = (mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0;
721 const uint32_t off = mEntries[idx]/(isUTF8?sizeof(uint8_t):sizeof(uint16_t));
722 if (off < (mStringPoolSize-1)) {
723 if (!isUTF8) {
724 const uint16_t* strings = (uint16_t*)mStrings;
725 const uint16_t* str = strings+off;
726
727 *u16len = decodeLength(&str);
728 if ((uint32_t)(str+*u16len-strings) < mStringPoolSize) {
729 // Reject malformed (non null-terminated) strings
730 if (str[*u16len] != 0x0000) {
731 ALOGW("Bad string block: string #%d is not null-terminated",
732 (int)idx);
733 return NULL;
734 }
735 return reinterpret_cast<const char16_t*>(str);
736 } else {
737 ALOGW("Bad string block: string #%d extends to %d, past end at %d\n",
738 (int)idx, (int)(str+*u16len-strings), (int)mStringPoolSize);
739 }
740 } else {
741 const uint8_t* strings = (uint8_t*)mStrings;
742 const uint8_t* u8str = strings+off;
743
744 *u16len = decodeLength(&u8str);
745 size_t u8len = decodeLength(&u8str);
746
747 // encLen must be less than 0x7FFF due to encoding.
748 if ((uint32_t)(u8str+u8len-strings) < mStringPoolSize) {
749 AutoMutex lock(mDecodeLock);
750
751 if (mCache != NULL && mCache[idx] != NULL) {
752 return mCache[idx];
753 }
754
755 // Retrieve the actual length of the utf8 string if the
756 // encoded length was truncated
757 if (stringDecodeAt(idx, u8str, u8len, &u8len) == NULL) {
758 return NULL;
759 }
760
761 // Since AAPT truncated lengths longer than 0x7FFF, check
762 // that the bits that remain after truncation at least match
763 // the bits of the actual length
764 ssize_t actualLen = utf8_to_utf16_length(u8str, u8len);
765 if (actualLen < 0 || ((size_t)actualLen & 0x7FFF) != *u16len) {
766 ALOGW("Bad string block: string #%lld decoded length is not correct "
767 "%lld vs %llu\n",
768 (long long)idx, (long long)actualLen, (long long)*u16len);
769 return NULL;
770 }
771
772 *u16len = (size_t) actualLen;
773 char16_t *u16str = (char16_t *)calloc(*u16len+1, sizeof(char16_t));
774 if (!u16str) {
775 ALOGW("No memory when trying to allocate decode cache for string #%d\n",
776 (int)idx);
777 return NULL;
778 }
779
780 utf8_to_utf16(u8str, u8len, u16str, *u16len + 1);
781
782 if (mCache == NULL) {
783 #ifndef __ANDROID__
784 if (kDebugStringPoolNoisy) {
785 ALOGI("CREATING STRING CACHE OF %zu bytes",
786 mHeader->stringCount*sizeof(char16_t**));
787 }
788 #else
789 // We do not want to be in this case when actually running Android.
790 ALOGW("CREATING STRING CACHE OF %zu bytes",
791 static_cast<size_t>(mHeader->stringCount*sizeof(char16_t**)));
792 #endif
793 mCache = (char16_t**)calloc(mHeader->stringCount, sizeof(char16_t*));
794 if (mCache == NULL) {
795 ALOGW("No memory trying to allocate decode cache table of %d bytes\n",
796 (int)(mHeader->stringCount*sizeof(char16_t**)));
797 return NULL;
798 }
799 }
800
801 if (kDebugStringPoolNoisy) {
802 ALOGI("Caching UTF8 string: %s", u8str);
803 }
804
805 mCache[idx] = u16str;
806 return u16str;
807 } else {
808 ALOGW("Bad string block: string #%lld extends to %lld, past end at %lld\n",
809 (long long)idx, (long long)(u8str+u8len-strings),
810 (long long)mStringPoolSize);
811 }
812 }
813 } else {
814 ALOGW("Bad string block: string #%d entry is at %d, past end at %d\n",
815 (int)idx, (int)(off*sizeof(uint16_t)),
816 (int)(mStringPoolSize*sizeof(uint16_t)));
817 }
818 }
819 return NULL;
820 }
821
string8At(size_t idx,size_t * outLen) const822 const char* ResStringPool::string8At(size_t idx, size_t* outLen) const
823 {
824 if (mError == NO_ERROR && idx < mHeader->stringCount) {
825 if ((mHeader->flags&ResStringPool_header::UTF8_FLAG) == 0) {
826 return NULL;
827 }
828 const uint32_t off = mEntries[idx]/sizeof(char);
829 if (off < (mStringPoolSize-1)) {
830 const uint8_t* strings = (uint8_t*)mStrings;
831 const uint8_t* str = strings+off;
832
833 // Decode the UTF-16 length. This is not used if we're not
834 // converting to UTF-16 from UTF-8.
835 decodeLength(&str);
836
837 const size_t encLen = decodeLength(&str);
838 *outLen = encLen;
839
840 if ((uint32_t)(str+encLen-strings) < mStringPoolSize) {
841 return stringDecodeAt(idx, str, encLen, outLen);
842
843 } else {
844 ALOGW("Bad string block: string #%d extends to %d, past end at %d\n",
845 (int)idx, (int)(str+encLen-strings), (int)mStringPoolSize);
846 }
847 } else {
848 ALOGW("Bad string block: string #%d entry is at %d, past end at %d\n",
849 (int)idx, (int)(off*sizeof(uint16_t)),
850 (int)(mStringPoolSize*sizeof(uint16_t)));
851 }
852 }
853 return NULL;
854 }
855
856 /**
857 * AAPT incorrectly writes a truncated string length when the string size
858 * exceeded the maximum possible encode length value (0x7FFF). To decode a
859 * truncated length, iterate through length values that end in the encode length
860 * bits. Strings that exceed the maximum encode length are not placed into
861 * StringPools in AAPT2.
862 **/
stringDecodeAt(size_t idx,const uint8_t * str,const size_t encLen,size_t * outLen) const863 const char* ResStringPool::stringDecodeAt(size_t idx, const uint8_t* str,
864 const size_t encLen, size_t* outLen) const {
865 const uint8_t* strings = (uint8_t*)mStrings;
866
867 size_t i = 0, end = encLen;
868 while ((uint32_t)(str+end-strings) < mStringPoolSize) {
869 if (str[end] == 0x00) {
870 if (i != 0) {
871 ALOGW("Bad string block: string #%d is truncated (actual length is %d)",
872 (int)idx, (int)end);
873 }
874
875 *outLen = end;
876 return (const char*)str;
877 }
878
879 end = (++i << (sizeof(uint8_t) * 8 * 2 - 1)) | encLen;
880 }
881
882 // Reject malformed (non null-terminated) strings
883 ALOGW("Bad string block: string #%d is not null-terminated",
884 (int)idx);
885 return NULL;
886 }
887
string8ObjectAt(size_t idx) const888 const String8 ResStringPool::string8ObjectAt(size_t idx) const
889 {
890 size_t len;
891 const char *str = string8At(idx, &len);
892 if (str != NULL) {
893 return String8(str, len);
894 }
895
896 const char16_t *str16 = stringAt(idx, &len);
897 if (str16 != NULL) {
898 return String8(str16, len);
899 }
900 return String8();
901 }
902
styleAt(const ResStringPool_ref & ref) const903 const ResStringPool_span* ResStringPool::styleAt(const ResStringPool_ref& ref) const
904 {
905 return styleAt(ref.index);
906 }
907
styleAt(size_t idx) const908 const ResStringPool_span* ResStringPool::styleAt(size_t idx) const
909 {
910 if (mError == NO_ERROR && idx < mHeader->styleCount) {
911 const uint32_t off = (mEntryStyles[idx]/sizeof(uint32_t));
912 if (off < mStylePoolSize) {
913 return (const ResStringPool_span*)(mStyles+off);
914 } else {
915 ALOGW("Bad string block: style #%d entry is at %d, past end at %d\n",
916 (int)idx, (int)(off*sizeof(uint32_t)),
917 (int)(mStylePoolSize*sizeof(uint32_t)));
918 }
919 }
920 return NULL;
921 }
922
indexOfString(const char16_t * str,size_t strLen) const923 ssize_t ResStringPool::indexOfString(const char16_t* str, size_t strLen) const
924 {
925 if (mError != NO_ERROR) {
926 return mError;
927 }
928
929 size_t len;
930
931 if ((mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0) {
932 if (kDebugStringPoolNoisy) {
933 ALOGI("indexOfString UTF-8: %s", String8(str, strLen).string());
934 }
935
936 // The string pool contains UTF 8 strings; we don't want to cause
937 // temporary UTF-16 strings to be created as we search.
938 if (mHeader->flags&ResStringPool_header::SORTED_FLAG) {
939 // Do a binary search for the string... this is a little tricky,
940 // because the strings are sorted with strzcmp16(). So to match
941 // the ordering, we need to convert strings in the pool to UTF-16.
942 // But we don't want to hit the cache, so instead we will have a
943 // local temporary allocation for the conversions.
944 size_t convBufferLen = strLen + 4;
945 char16_t* convBuffer = (char16_t*)calloc(convBufferLen, sizeof(char16_t));
946 ssize_t l = 0;
947 ssize_t h = mHeader->stringCount-1;
948
949 ssize_t mid;
950 while (l <= h) {
951 mid = l + (h - l)/2;
952 const uint8_t* s = (const uint8_t*)string8At(mid, &len);
953 int c;
954 if (s != NULL) {
955 char16_t* end = utf8_to_utf16(s, len, convBuffer, convBufferLen);
956 c = strzcmp16(convBuffer, end-convBuffer, str, strLen);
957 } else {
958 c = -1;
959 }
960 if (kDebugStringPoolNoisy) {
961 ALOGI("Looking at %s, cmp=%d, l/mid/h=%d/%d/%d\n",
962 (const char*)s, c, (int)l, (int)mid, (int)h);
963 }
964 if (c == 0) {
965 if (kDebugStringPoolNoisy) {
966 ALOGI("MATCH!");
967 }
968 free(convBuffer);
969 return mid;
970 } else if (c < 0) {
971 l = mid + 1;
972 } else {
973 h = mid - 1;
974 }
975 }
976 free(convBuffer);
977 } else {
978 // It is unusual to get the ID from an unsorted string block...
979 // most often this happens because we want to get IDs for style
980 // span tags; since those always appear at the end of the string
981 // block, start searching at the back.
982 String8 str8(str, strLen);
983 const size_t str8Len = str8.size();
984 for (int i=mHeader->stringCount-1; i>=0; i--) {
985 const char* s = string8At(i, &len);
986 if (kDebugStringPoolNoisy) {
987 ALOGI("Looking at %s, i=%d\n", String8(s).string(), i);
988 }
989 if (s && str8Len == len && memcmp(s, str8.string(), str8Len) == 0) {
990 if (kDebugStringPoolNoisy) {
991 ALOGI("MATCH!");
992 }
993 return i;
994 }
995 }
996 }
997
998 } else {
999 if (kDebugStringPoolNoisy) {
1000 ALOGI("indexOfString UTF-16: %s", String8(str, strLen).string());
1001 }
1002
1003 if (mHeader->flags&ResStringPool_header::SORTED_FLAG) {
1004 // Do a binary search for the string...
1005 ssize_t l = 0;
1006 ssize_t h = mHeader->stringCount-1;
1007
1008 ssize_t mid;
1009 while (l <= h) {
1010 mid = l + (h - l)/2;
1011 const char16_t* s = stringAt(mid, &len);
1012 int c = s ? strzcmp16(s, len, str, strLen) : -1;
1013 if (kDebugStringPoolNoisy) {
1014 ALOGI("Looking at %s, cmp=%d, l/mid/h=%d/%d/%d\n",
1015 String8(s).string(), c, (int)l, (int)mid, (int)h);
1016 }
1017 if (c == 0) {
1018 if (kDebugStringPoolNoisy) {
1019 ALOGI("MATCH!");
1020 }
1021 return mid;
1022 } else if (c < 0) {
1023 l = mid + 1;
1024 } else {
1025 h = mid - 1;
1026 }
1027 }
1028 } else {
1029 // It is unusual to get the ID from an unsorted string block...
1030 // most often this happens because we want to get IDs for style
1031 // span tags; since those always appear at the end of the string
1032 // block, start searching at the back.
1033 for (int i=mHeader->stringCount-1; i>=0; i--) {
1034 const char16_t* s = stringAt(i, &len);
1035 if (kDebugStringPoolNoisy) {
1036 ALOGI("Looking at %s, i=%d\n", String8(s).string(), i);
1037 }
1038 if (s && strLen == len && strzcmp16(s, len, str, strLen) == 0) {
1039 if (kDebugStringPoolNoisy) {
1040 ALOGI("MATCH!");
1041 }
1042 return i;
1043 }
1044 }
1045 }
1046 }
1047
1048 return NAME_NOT_FOUND;
1049 }
1050
size() const1051 size_t ResStringPool::size() const
1052 {
1053 return (mError == NO_ERROR) ? mHeader->stringCount : 0;
1054 }
1055
styleCount() const1056 size_t ResStringPool::styleCount() const
1057 {
1058 return (mError == NO_ERROR) ? mHeader->styleCount : 0;
1059 }
1060
bytes() const1061 size_t ResStringPool::bytes() const
1062 {
1063 return (mError == NO_ERROR) ? mHeader->header.size : 0;
1064 }
1065
data() const1066 const void* ResStringPool::data() const
1067 {
1068 return mHeader;
1069 }
1070
isSorted() const1071 bool ResStringPool::isSorted() const
1072 {
1073 return (mHeader->flags&ResStringPool_header::SORTED_FLAG)!=0;
1074 }
1075
isUTF8() const1076 bool ResStringPool::isUTF8() const
1077 {
1078 return (mHeader->flags&ResStringPool_header::UTF8_FLAG)!=0;
1079 }
1080
1081 // --------------------------------------------------------------------
1082 // --------------------------------------------------------------------
1083 // --------------------------------------------------------------------
1084
ResXMLParser(const ResXMLTree & tree)1085 ResXMLParser::ResXMLParser(const ResXMLTree& tree)
1086 : mTree(tree), mEventCode(BAD_DOCUMENT)
1087 {
1088 }
1089
restart()1090 void ResXMLParser::restart()
1091 {
1092 mCurNode = NULL;
1093 mEventCode = mTree.mError == NO_ERROR ? START_DOCUMENT : BAD_DOCUMENT;
1094 }
getStrings() const1095 const ResStringPool& ResXMLParser::getStrings() const
1096 {
1097 return mTree.mStrings;
1098 }
1099
getEventType() const1100 ResXMLParser::event_code_t ResXMLParser::getEventType() const
1101 {
1102 return mEventCode;
1103 }
1104
next()1105 ResXMLParser::event_code_t ResXMLParser::next()
1106 {
1107 if (mEventCode == START_DOCUMENT) {
1108 mCurNode = mTree.mRootNode;
1109 mCurExt = mTree.mRootExt;
1110 return (mEventCode=mTree.mRootCode);
1111 } else if (mEventCode >= FIRST_CHUNK_CODE) {
1112 return nextNode();
1113 }
1114 return mEventCode;
1115 }
1116
getCommentID() const1117 int32_t ResXMLParser::getCommentID() const
1118 {
1119 return mCurNode != NULL ? dtohl(mCurNode->comment.index) : -1;
1120 }
1121
getComment(size_t * outLen) const1122 const char16_t* ResXMLParser::getComment(size_t* outLen) const
1123 {
1124 int32_t id = getCommentID();
1125 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1126 }
1127
getLineNumber() const1128 uint32_t ResXMLParser::getLineNumber() const
1129 {
1130 return mCurNode != NULL ? dtohl(mCurNode->lineNumber) : -1;
1131 }
1132
getTextID() const1133 int32_t ResXMLParser::getTextID() const
1134 {
1135 if (mEventCode == TEXT) {
1136 return dtohl(((const ResXMLTree_cdataExt*)mCurExt)->data.index);
1137 }
1138 return -1;
1139 }
1140
getText(size_t * outLen) const1141 const char16_t* ResXMLParser::getText(size_t* outLen) const
1142 {
1143 int32_t id = getTextID();
1144 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1145 }
1146
getTextValue(Res_value * outValue) const1147 ssize_t ResXMLParser::getTextValue(Res_value* outValue) const
1148 {
1149 if (mEventCode == TEXT) {
1150 outValue->copyFrom_dtoh(((const ResXMLTree_cdataExt*)mCurExt)->typedData);
1151 return sizeof(Res_value);
1152 }
1153 return BAD_TYPE;
1154 }
1155
getNamespacePrefixID() const1156 int32_t ResXMLParser::getNamespacePrefixID() const
1157 {
1158 if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) {
1159 return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->prefix.index);
1160 }
1161 return -1;
1162 }
1163
getNamespacePrefix(size_t * outLen) const1164 const char16_t* ResXMLParser::getNamespacePrefix(size_t* outLen) const
1165 {
1166 int32_t id = getNamespacePrefixID();
1167 //printf("prefix=%d event=%p\n", id, mEventCode);
1168 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1169 }
1170
getNamespaceUriID() const1171 int32_t ResXMLParser::getNamespaceUriID() const
1172 {
1173 if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) {
1174 return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->uri.index);
1175 }
1176 return -1;
1177 }
1178
getNamespaceUri(size_t * outLen) const1179 const char16_t* ResXMLParser::getNamespaceUri(size_t* outLen) const
1180 {
1181 int32_t id = getNamespaceUriID();
1182 //printf("uri=%d event=%p\n", id, mEventCode);
1183 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1184 }
1185
getElementNamespaceID() const1186 int32_t ResXMLParser::getElementNamespaceID() const
1187 {
1188 if (mEventCode == START_TAG) {
1189 return dtohl(((const ResXMLTree_attrExt*)mCurExt)->ns.index);
1190 }
1191 if (mEventCode == END_TAG) {
1192 return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->ns.index);
1193 }
1194 return -1;
1195 }
1196
getElementNamespace(size_t * outLen) const1197 const char16_t* ResXMLParser::getElementNamespace(size_t* outLen) const
1198 {
1199 int32_t id = getElementNamespaceID();
1200 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1201 }
1202
getElementNameID() const1203 int32_t ResXMLParser::getElementNameID() const
1204 {
1205 if (mEventCode == START_TAG) {
1206 return dtohl(((const ResXMLTree_attrExt*)mCurExt)->name.index);
1207 }
1208 if (mEventCode == END_TAG) {
1209 return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->name.index);
1210 }
1211 return -1;
1212 }
1213
getElementName(size_t * outLen) const1214 const char16_t* ResXMLParser::getElementName(size_t* outLen) const
1215 {
1216 int32_t id = getElementNameID();
1217 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1218 }
1219
getAttributeCount() const1220 size_t ResXMLParser::getAttributeCount() const
1221 {
1222 if (mEventCode == START_TAG) {
1223 return dtohs(((const ResXMLTree_attrExt*)mCurExt)->attributeCount);
1224 }
1225 return 0;
1226 }
1227
getAttributeNamespaceID(size_t idx) const1228 int32_t ResXMLParser::getAttributeNamespaceID(size_t idx) const
1229 {
1230 if (mEventCode == START_TAG) {
1231 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1232 if (idx < dtohs(tag->attributeCount)) {
1233 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1234 (((const uint8_t*)tag)
1235 + dtohs(tag->attributeStart)
1236 + (dtohs(tag->attributeSize)*idx));
1237 return dtohl(attr->ns.index);
1238 }
1239 }
1240 return -2;
1241 }
1242
getAttributeNamespace(size_t idx,size_t * outLen) const1243 const char16_t* ResXMLParser::getAttributeNamespace(size_t idx, size_t* outLen) const
1244 {
1245 int32_t id = getAttributeNamespaceID(idx);
1246 //printf("attribute namespace=%d idx=%d event=%p\n", id, idx, mEventCode);
1247 if (kDebugXMLNoisy) {
1248 printf("getAttributeNamespace 0x%zx=0x%x\n", idx, id);
1249 }
1250 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1251 }
1252
getAttributeNamespace8(size_t idx,size_t * outLen) const1253 const char* ResXMLParser::getAttributeNamespace8(size_t idx, size_t* outLen) const
1254 {
1255 int32_t id = getAttributeNamespaceID(idx);
1256 //printf("attribute namespace=%d idx=%d event=%p\n", id, idx, mEventCode);
1257 if (kDebugXMLNoisy) {
1258 printf("getAttributeNamespace 0x%zx=0x%x\n", idx, id);
1259 }
1260 return id >= 0 ? mTree.mStrings.string8At(id, outLen) : NULL;
1261 }
1262
getAttributeNameID(size_t idx) const1263 int32_t ResXMLParser::getAttributeNameID(size_t idx) const
1264 {
1265 if (mEventCode == START_TAG) {
1266 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1267 if (idx < dtohs(tag->attributeCount)) {
1268 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1269 (((const uint8_t*)tag)
1270 + dtohs(tag->attributeStart)
1271 + (dtohs(tag->attributeSize)*idx));
1272 return dtohl(attr->name.index);
1273 }
1274 }
1275 return -1;
1276 }
1277
getAttributeName(size_t idx,size_t * outLen) const1278 const char16_t* ResXMLParser::getAttributeName(size_t idx, size_t* outLen) const
1279 {
1280 int32_t id = getAttributeNameID(idx);
1281 //printf("attribute name=%d idx=%d event=%p\n", id, idx, mEventCode);
1282 if (kDebugXMLNoisy) {
1283 printf("getAttributeName 0x%zx=0x%x\n", idx, id);
1284 }
1285 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1286 }
1287
getAttributeName8(size_t idx,size_t * outLen) const1288 const char* ResXMLParser::getAttributeName8(size_t idx, size_t* outLen) const
1289 {
1290 int32_t id = getAttributeNameID(idx);
1291 //printf("attribute name=%d idx=%d event=%p\n", id, idx, mEventCode);
1292 if (kDebugXMLNoisy) {
1293 printf("getAttributeName 0x%zx=0x%x\n", idx, id);
1294 }
1295 return id >= 0 ? mTree.mStrings.string8At(id, outLen) : NULL;
1296 }
1297
getAttributeNameResID(size_t idx) const1298 uint32_t ResXMLParser::getAttributeNameResID(size_t idx) const
1299 {
1300 int32_t id = getAttributeNameID(idx);
1301 if (id >= 0 && (size_t)id < mTree.mNumResIds) {
1302 uint32_t resId = dtohl(mTree.mResIds[id]);
1303 if (mTree.mDynamicRefTable != NULL) {
1304 mTree.mDynamicRefTable->lookupResourceId(&resId);
1305 }
1306 return resId;
1307 }
1308 return 0;
1309 }
1310
getAttributeValueStringID(size_t idx) const1311 int32_t ResXMLParser::getAttributeValueStringID(size_t idx) const
1312 {
1313 if (mEventCode == START_TAG) {
1314 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1315 if (idx < dtohs(tag->attributeCount)) {
1316 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1317 (((const uint8_t*)tag)
1318 + dtohs(tag->attributeStart)
1319 + (dtohs(tag->attributeSize)*idx));
1320 return dtohl(attr->rawValue.index);
1321 }
1322 }
1323 return -1;
1324 }
1325
getAttributeStringValue(size_t idx,size_t * outLen) const1326 const char16_t* ResXMLParser::getAttributeStringValue(size_t idx, size_t* outLen) const
1327 {
1328 int32_t id = getAttributeValueStringID(idx);
1329 if (kDebugXMLNoisy) {
1330 printf("getAttributeValue 0x%zx=0x%x\n", idx, id);
1331 }
1332 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1333 }
1334
getAttributeDataType(size_t idx) const1335 int32_t ResXMLParser::getAttributeDataType(size_t idx) const
1336 {
1337 if (mEventCode == START_TAG) {
1338 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1339 if (idx < dtohs(tag->attributeCount)) {
1340 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1341 (((const uint8_t*)tag)
1342 + dtohs(tag->attributeStart)
1343 + (dtohs(tag->attributeSize)*idx));
1344 uint8_t type = attr->typedValue.dataType;
1345 if (type != Res_value::TYPE_DYNAMIC_REFERENCE) {
1346 return type;
1347 }
1348
1349 // This is a dynamic reference. We adjust those references
1350 // to regular references at this level, so lie to the caller.
1351 return Res_value::TYPE_REFERENCE;
1352 }
1353 }
1354 return Res_value::TYPE_NULL;
1355 }
1356
getAttributeData(size_t idx) const1357 int32_t ResXMLParser::getAttributeData(size_t idx) const
1358 {
1359 if (mEventCode == START_TAG) {
1360 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1361 if (idx < dtohs(tag->attributeCount)) {
1362 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1363 (((const uint8_t*)tag)
1364 + dtohs(tag->attributeStart)
1365 + (dtohs(tag->attributeSize)*idx));
1366 if (mTree.mDynamicRefTable == NULL ||
1367 !mTree.mDynamicRefTable->requiresLookup(&attr->typedValue)) {
1368 return dtohl(attr->typedValue.data);
1369 }
1370 uint32_t data = dtohl(attr->typedValue.data);
1371 if (mTree.mDynamicRefTable->lookupResourceId(&data) == NO_ERROR) {
1372 return data;
1373 }
1374 }
1375 }
1376 return 0;
1377 }
1378
getAttributeValue(size_t idx,Res_value * outValue) const1379 ssize_t ResXMLParser::getAttributeValue(size_t idx, Res_value* outValue) const
1380 {
1381 if (mEventCode == START_TAG) {
1382 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1383 if (idx < dtohs(tag->attributeCount)) {
1384 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1385 (((const uint8_t*)tag)
1386 + dtohs(tag->attributeStart)
1387 + (dtohs(tag->attributeSize)*idx));
1388 outValue->copyFrom_dtoh(attr->typedValue);
1389 if (mTree.mDynamicRefTable != NULL &&
1390 mTree.mDynamicRefTable->lookupResourceValue(outValue) != NO_ERROR) {
1391 return BAD_TYPE;
1392 }
1393 return sizeof(Res_value);
1394 }
1395 }
1396 return BAD_TYPE;
1397 }
1398
indexOfAttribute(const char * ns,const char * attr) const1399 ssize_t ResXMLParser::indexOfAttribute(const char* ns, const char* attr) const
1400 {
1401 String16 nsStr(ns != NULL ? ns : "");
1402 String16 attrStr(attr);
1403 return indexOfAttribute(ns ? nsStr.string() : NULL, ns ? nsStr.size() : 0,
1404 attrStr.string(), attrStr.size());
1405 }
1406
indexOfAttribute(const char16_t * ns,size_t nsLen,const char16_t * attr,size_t attrLen) const1407 ssize_t ResXMLParser::indexOfAttribute(const char16_t* ns, size_t nsLen,
1408 const char16_t* attr, size_t attrLen) const
1409 {
1410 if (mEventCode == START_TAG) {
1411 if (attr == NULL) {
1412 return NAME_NOT_FOUND;
1413 }
1414 const size_t N = getAttributeCount();
1415 if (mTree.mStrings.isUTF8()) {
1416 String8 ns8, attr8;
1417 if (ns != NULL) {
1418 ns8 = String8(ns, nsLen);
1419 }
1420 attr8 = String8(attr, attrLen);
1421 if (kDebugStringPoolNoisy) {
1422 ALOGI("indexOfAttribute UTF8 %s (%zu) / %s (%zu)", ns8.string(), nsLen,
1423 attr8.string(), attrLen);
1424 }
1425 for (size_t i=0; i<N; i++) {
1426 size_t curNsLen = 0, curAttrLen = 0;
1427 const char* curNs = getAttributeNamespace8(i, &curNsLen);
1428 const char* curAttr = getAttributeName8(i, &curAttrLen);
1429 if (kDebugStringPoolNoisy) {
1430 ALOGI(" curNs=%s (%zu), curAttr=%s (%zu)", curNs, curNsLen, curAttr, curAttrLen);
1431 }
1432 if (curAttr != NULL && curNsLen == nsLen && curAttrLen == attrLen
1433 && memcmp(attr8.string(), curAttr, attrLen) == 0) {
1434 if (ns == NULL) {
1435 if (curNs == NULL) {
1436 if (kDebugStringPoolNoisy) {
1437 ALOGI(" FOUND!");
1438 }
1439 return i;
1440 }
1441 } else if (curNs != NULL) {
1442 //printf(" --> ns=%s, curNs=%s\n",
1443 // String8(ns).string(), String8(curNs).string());
1444 if (memcmp(ns8.string(), curNs, nsLen) == 0) {
1445 if (kDebugStringPoolNoisy) {
1446 ALOGI(" FOUND!");
1447 }
1448 return i;
1449 }
1450 }
1451 }
1452 }
1453 } else {
1454 if (kDebugStringPoolNoisy) {
1455 ALOGI("indexOfAttribute UTF16 %s (%zu) / %s (%zu)",
1456 String8(ns, nsLen).string(), nsLen,
1457 String8(attr, attrLen).string(), attrLen);
1458 }
1459 for (size_t i=0; i<N; i++) {
1460 size_t curNsLen = 0, curAttrLen = 0;
1461 const char16_t* curNs = getAttributeNamespace(i, &curNsLen);
1462 const char16_t* curAttr = getAttributeName(i, &curAttrLen);
1463 if (kDebugStringPoolNoisy) {
1464 ALOGI(" curNs=%s (%zu), curAttr=%s (%zu)",
1465 String8(curNs, curNsLen).string(), curNsLen,
1466 String8(curAttr, curAttrLen).string(), curAttrLen);
1467 }
1468 if (curAttr != NULL && curNsLen == nsLen && curAttrLen == attrLen
1469 && (memcmp(attr, curAttr, attrLen*sizeof(char16_t)) == 0)) {
1470 if (ns == NULL) {
1471 if (curNs == NULL) {
1472 if (kDebugStringPoolNoisy) {
1473 ALOGI(" FOUND!");
1474 }
1475 return i;
1476 }
1477 } else if (curNs != NULL) {
1478 //printf(" --> ns=%s, curNs=%s\n",
1479 // String8(ns).string(), String8(curNs).string());
1480 if (memcmp(ns, curNs, nsLen*sizeof(char16_t)) == 0) {
1481 if (kDebugStringPoolNoisy) {
1482 ALOGI(" FOUND!");
1483 }
1484 return i;
1485 }
1486 }
1487 }
1488 }
1489 }
1490 }
1491
1492 return NAME_NOT_FOUND;
1493 }
1494
indexOfID() const1495 ssize_t ResXMLParser::indexOfID() const
1496 {
1497 if (mEventCode == START_TAG) {
1498 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->idIndex);
1499 if (idx > 0) return (idx-1);
1500 }
1501 return NAME_NOT_FOUND;
1502 }
1503
indexOfClass() const1504 ssize_t ResXMLParser::indexOfClass() const
1505 {
1506 if (mEventCode == START_TAG) {
1507 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->classIndex);
1508 if (idx > 0) return (idx-1);
1509 }
1510 return NAME_NOT_FOUND;
1511 }
1512
indexOfStyle() const1513 ssize_t ResXMLParser::indexOfStyle() const
1514 {
1515 if (mEventCode == START_TAG) {
1516 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->styleIndex);
1517 if (idx > 0) return (idx-1);
1518 }
1519 return NAME_NOT_FOUND;
1520 }
1521
nextNode()1522 ResXMLParser::event_code_t ResXMLParser::nextNode()
1523 {
1524 if (mEventCode < 0) {
1525 return mEventCode;
1526 }
1527
1528 do {
1529 const ResXMLTree_node* next = (const ResXMLTree_node*)
1530 (((const uint8_t*)mCurNode) + dtohl(mCurNode->header.size));
1531 if (kDebugXMLNoisy) {
1532 ALOGI("Next node: prev=%p, next=%p\n", mCurNode, next);
1533 }
1534
1535 if (((const uint8_t*)next) >= mTree.mDataEnd) {
1536 mCurNode = NULL;
1537 return (mEventCode=END_DOCUMENT);
1538 }
1539
1540 if (mTree.validateNode(next) != NO_ERROR) {
1541 mCurNode = NULL;
1542 return (mEventCode=BAD_DOCUMENT);
1543 }
1544
1545 mCurNode = next;
1546 const uint16_t headerSize = dtohs(next->header.headerSize);
1547 const uint32_t totalSize = dtohl(next->header.size);
1548 mCurExt = ((const uint8_t*)next) + headerSize;
1549 size_t minExtSize = 0;
1550 event_code_t eventCode = (event_code_t)dtohs(next->header.type);
1551 switch ((mEventCode=eventCode)) {
1552 case RES_XML_START_NAMESPACE_TYPE:
1553 case RES_XML_END_NAMESPACE_TYPE:
1554 minExtSize = sizeof(ResXMLTree_namespaceExt);
1555 break;
1556 case RES_XML_START_ELEMENT_TYPE:
1557 minExtSize = sizeof(ResXMLTree_attrExt);
1558 break;
1559 case RES_XML_END_ELEMENT_TYPE:
1560 minExtSize = sizeof(ResXMLTree_endElementExt);
1561 break;
1562 case RES_XML_CDATA_TYPE:
1563 minExtSize = sizeof(ResXMLTree_cdataExt);
1564 break;
1565 default:
1566 ALOGW("Unknown XML block: header type %d in node at %d\n",
1567 (int)dtohs(next->header.type),
1568 (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)));
1569 continue;
1570 }
1571
1572 if ((totalSize-headerSize) < minExtSize) {
1573 ALOGW("Bad XML block: header type 0x%x in node at 0x%x has size %d, need %d\n",
1574 (int)dtohs(next->header.type),
1575 (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)),
1576 (int)(totalSize-headerSize), (int)minExtSize);
1577 return (mEventCode=BAD_DOCUMENT);
1578 }
1579
1580 //printf("CurNode=%p, CurExt=%p, headerSize=%d, minExtSize=%d\n",
1581 // mCurNode, mCurExt, headerSize, minExtSize);
1582
1583 return eventCode;
1584 } while (true);
1585 }
1586
getPosition(ResXMLParser::ResXMLPosition * pos) const1587 void ResXMLParser::getPosition(ResXMLParser::ResXMLPosition* pos) const
1588 {
1589 pos->eventCode = mEventCode;
1590 pos->curNode = mCurNode;
1591 pos->curExt = mCurExt;
1592 }
1593
setPosition(const ResXMLParser::ResXMLPosition & pos)1594 void ResXMLParser::setPosition(const ResXMLParser::ResXMLPosition& pos)
1595 {
1596 mEventCode = pos.eventCode;
1597 mCurNode = pos.curNode;
1598 mCurExt = pos.curExt;
1599 }
1600
setSourceResourceId(const uint32_t resId)1601 void ResXMLParser::setSourceResourceId(const uint32_t resId)
1602 {
1603 mSourceResourceId = resId;
1604 }
1605
getSourceResourceId() const1606 uint32_t ResXMLParser::getSourceResourceId() const
1607 {
1608 return mSourceResourceId;
1609 }
1610
1611 // --------------------------------------------------------------------
1612
1613 static volatile int32_t gCount = 0;
1614
ResXMLTree(std::shared_ptr<const DynamicRefTable> dynamicRefTable)1615 ResXMLTree::ResXMLTree(std::shared_ptr<const DynamicRefTable> dynamicRefTable)
1616 : ResXMLParser(*this)
1617 , mDynamicRefTable(std::move(dynamicRefTable))
1618 , mError(NO_INIT), mOwnedData(NULL)
1619 {
1620 if (kDebugResXMLTree) {
1621 ALOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1);
1622 }
1623 restart();
1624 }
1625
ResXMLTree()1626 ResXMLTree::ResXMLTree()
1627 : ResXMLParser(*this)
1628 , mDynamicRefTable(nullptr)
1629 , mError(NO_INIT), mOwnedData(NULL)
1630 {
1631 if (kDebugResXMLTree) {
1632 ALOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1);
1633 }
1634 restart();
1635 }
1636
~ResXMLTree()1637 ResXMLTree::~ResXMLTree()
1638 {
1639 if (kDebugResXMLTree) {
1640 ALOGI("Destroying ResXMLTree in %p #%d\n", this, android_atomic_dec(&gCount)-1);
1641 }
1642 uninit();
1643 }
1644
setTo(const void * data,size_t size,bool copyData)1645 status_t ResXMLTree::setTo(const void* data, size_t size, bool copyData)
1646 {
1647 uninit();
1648 mEventCode = START_DOCUMENT;
1649
1650 if (!data || !size) {
1651 return (mError=BAD_TYPE);
1652 }
1653
1654 if (copyData) {
1655 mOwnedData = malloc(size);
1656 if (mOwnedData == NULL) {
1657 return (mError=NO_MEMORY);
1658 }
1659 memcpy(mOwnedData, data, size);
1660 data = mOwnedData;
1661 }
1662
1663 mHeader = (const ResXMLTree_header*)data;
1664 mSize = dtohl(mHeader->header.size);
1665 if (dtohs(mHeader->header.headerSize) > mSize || mSize > size) {
1666 ALOGW("Bad XML block: header size %d or total size %d is larger than data size %d\n",
1667 (int)dtohs(mHeader->header.headerSize),
1668 (int)dtohl(mHeader->header.size), (int)size);
1669 mError = BAD_TYPE;
1670 restart();
1671 return mError;
1672 }
1673 mDataEnd = ((const uint8_t*)mHeader) + mSize;
1674
1675 mStrings.uninit();
1676 mRootNode = NULL;
1677 mResIds = NULL;
1678 mNumResIds = 0;
1679
1680 // First look for a couple interesting chunks: the string block
1681 // and first XML node.
1682 const ResChunk_header* chunk =
1683 (const ResChunk_header*)(((const uint8_t*)mHeader) + dtohs(mHeader->header.headerSize));
1684 const ResChunk_header* lastChunk = chunk;
1685 while (((const uint8_t*)chunk) < (mDataEnd-sizeof(ResChunk_header)) &&
1686 ((const uint8_t*)chunk) < (mDataEnd-dtohl(chunk->size))) {
1687 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), mDataEnd, "XML");
1688 if (err != NO_ERROR) {
1689 mError = err;
1690 goto done;
1691 }
1692 const uint16_t type = dtohs(chunk->type);
1693 const size_t size = dtohl(chunk->size);
1694 if (kDebugXMLNoisy) {
1695 printf("Scanning @ %p: type=0x%x, size=0x%zx\n",
1696 (void*)(((uintptr_t)chunk)-((uintptr_t)mHeader)), type, size);
1697 }
1698 if (type == RES_STRING_POOL_TYPE) {
1699 mStrings.setTo(chunk, size);
1700 } else if (type == RES_XML_RESOURCE_MAP_TYPE) {
1701 mResIds = (const uint32_t*)
1702 (((const uint8_t*)chunk)+dtohs(chunk->headerSize));
1703 mNumResIds = (dtohl(chunk->size)-dtohs(chunk->headerSize))/sizeof(uint32_t);
1704 } else if (type >= RES_XML_FIRST_CHUNK_TYPE
1705 && type <= RES_XML_LAST_CHUNK_TYPE) {
1706 if (validateNode((const ResXMLTree_node*)chunk) != NO_ERROR) {
1707 mError = BAD_TYPE;
1708 goto done;
1709 }
1710 mCurNode = (const ResXMLTree_node*)lastChunk;
1711 if (nextNode() == BAD_DOCUMENT) {
1712 mError = BAD_TYPE;
1713 goto done;
1714 }
1715 mRootNode = mCurNode;
1716 mRootExt = mCurExt;
1717 mRootCode = mEventCode;
1718 break;
1719 } else {
1720 if (kDebugXMLNoisy) {
1721 printf("Skipping unknown chunk!\n");
1722 }
1723 }
1724 lastChunk = chunk;
1725 chunk = (const ResChunk_header*)
1726 (((const uint8_t*)chunk) + size);
1727 }
1728
1729 if (mRootNode == NULL) {
1730 ALOGW("Bad XML block: no root element node found\n");
1731 mError = BAD_TYPE;
1732 goto done;
1733 }
1734
1735 mError = mStrings.getError();
1736
1737 done:
1738 restart();
1739 return mError;
1740 }
1741
getError() const1742 status_t ResXMLTree::getError() const
1743 {
1744 return mError;
1745 }
1746
uninit()1747 void ResXMLTree::uninit()
1748 {
1749 mError = NO_INIT;
1750 mStrings.uninit();
1751 if (mOwnedData) {
1752 free(mOwnedData);
1753 mOwnedData = NULL;
1754 }
1755 restart();
1756 }
1757
validateNode(const ResXMLTree_node * node) const1758 status_t ResXMLTree::validateNode(const ResXMLTree_node* node) const
1759 {
1760 const uint16_t eventCode = dtohs(node->header.type);
1761
1762 status_t err = validate_chunk(
1763 &node->header, sizeof(ResXMLTree_node),
1764 mDataEnd, "ResXMLTree_node");
1765
1766 if (err >= NO_ERROR) {
1767 // Only perform additional validation on START nodes
1768 if (eventCode != RES_XML_START_ELEMENT_TYPE) {
1769 return NO_ERROR;
1770 }
1771
1772 const uint16_t headerSize = dtohs(node->header.headerSize);
1773 const uint32_t size = dtohl(node->header.size);
1774 const ResXMLTree_attrExt* attrExt = (const ResXMLTree_attrExt*)
1775 (((const uint8_t*)node) + headerSize);
1776 // check for sensical values pulled out of the stream so far...
1777 if ((size >= headerSize + sizeof(ResXMLTree_attrExt))
1778 && ((void*)attrExt > (void*)node)) {
1779 const size_t attrSize = ((size_t)dtohs(attrExt->attributeSize))
1780 * dtohs(attrExt->attributeCount);
1781 if ((dtohs(attrExt->attributeStart)+attrSize) <= (size-headerSize)) {
1782 return NO_ERROR;
1783 }
1784 ALOGW("Bad XML block: node attributes use 0x%x bytes, only have 0x%x bytes\n",
1785 (unsigned int)(dtohs(attrExt->attributeStart)+attrSize),
1786 (unsigned int)(size-headerSize));
1787 }
1788 else {
1789 ALOGW("Bad XML start block: node header size 0x%x, size 0x%x\n",
1790 (unsigned int)headerSize, (unsigned int)size);
1791 }
1792 return BAD_TYPE;
1793 }
1794
1795 return err;
1796
1797 #if 0
1798 const bool isStart = dtohs(node->header.type) == RES_XML_START_ELEMENT_TYPE;
1799
1800 const uint16_t headerSize = dtohs(node->header.headerSize);
1801 const uint32_t size = dtohl(node->header.size);
1802
1803 if (headerSize >= (isStart ? sizeof(ResXMLTree_attrNode) : sizeof(ResXMLTree_node))) {
1804 if (size >= headerSize) {
1805 if (((const uint8_t*)node) <= (mDataEnd-size)) {
1806 if (!isStart) {
1807 return NO_ERROR;
1808 }
1809 if ((((size_t)dtohs(node->attributeSize))*dtohs(node->attributeCount))
1810 <= (size-headerSize)) {
1811 return NO_ERROR;
1812 }
1813 ALOGW("Bad XML block: node attributes use 0x%x bytes, only have 0x%x bytes\n",
1814 ((int)dtohs(node->attributeSize))*dtohs(node->attributeCount),
1815 (int)(size-headerSize));
1816 return BAD_TYPE;
1817 }
1818 ALOGW("Bad XML block: node at 0x%x extends beyond data end 0x%x\n",
1819 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)), (int)mSize);
1820 return BAD_TYPE;
1821 }
1822 ALOGW("Bad XML block: node at 0x%x header size 0x%x smaller than total size 0x%x\n",
1823 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)),
1824 (int)headerSize, (int)size);
1825 return BAD_TYPE;
1826 }
1827 ALOGW("Bad XML block: node at 0x%x header size 0x%x too small\n",
1828 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)),
1829 (int)headerSize);
1830 return BAD_TYPE;
1831 #endif
1832 }
1833
1834 // --------------------------------------------------------------------
1835 // --------------------------------------------------------------------
1836 // --------------------------------------------------------------------
1837
copyFromDeviceNoSwap(const ResTable_config & o)1838 void ResTable_config::copyFromDeviceNoSwap(const ResTable_config& o) {
1839 const size_t size = dtohl(o.size);
1840 if (size >= sizeof(ResTable_config)) {
1841 *this = o;
1842 } else {
1843 memcpy(this, &o, size);
1844 memset(((uint8_t*)this)+size, 0, sizeof(ResTable_config)-size);
1845 }
1846 }
1847
unpackLanguageOrRegion(const char in[2],const char base,char out[4])1848 /* static */ size_t unpackLanguageOrRegion(const char in[2], const char base,
1849 char out[4]) {
1850 if (in[0] & 0x80) {
1851 // The high bit is "1", which means this is a packed three letter
1852 // language code.
1853
1854 // The smallest 5 bits of the second char are the first alphabet.
1855 const uint8_t first = in[1] & 0x1f;
1856 // The last three bits of the second char and the first two bits
1857 // of the first char are the second alphabet.
1858 const uint8_t second = ((in[1] & 0xe0) >> 5) + ((in[0] & 0x03) << 3);
1859 // Bits 3 to 7 (inclusive) of the first char are the third alphabet.
1860 const uint8_t third = (in[0] & 0x7c) >> 2;
1861
1862 out[0] = first + base;
1863 out[1] = second + base;
1864 out[2] = third + base;
1865 out[3] = 0;
1866
1867 return 3;
1868 }
1869
1870 if (in[0]) {
1871 memcpy(out, in, 2);
1872 memset(out + 2, 0, 2);
1873 return 2;
1874 }
1875
1876 memset(out, 0, 4);
1877 return 0;
1878 }
1879
packLanguageOrRegion(const char * in,const char base,char out[2])1880 /* static */ void packLanguageOrRegion(const char* in, const char base,
1881 char out[2]) {
1882 if (in[2] == 0 || in[2] == '-') {
1883 out[0] = in[0];
1884 out[1] = in[1];
1885 } else {
1886 uint8_t first = (in[0] - base) & 0x007f;
1887 uint8_t second = (in[1] - base) & 0x007f;
1888 uint8_t third = (in[2] - base) & 0x007f;
1889
1890 out[0] = (0x80 | (third << 2) | (second >> 3));
1891 out[1] = ((second << 5) | first);
1892 }
1893 }
1894
1895
packLanguage(const char * language)1896 void ResTable_config::packLanguage(const char* language) {
1897 packLanguageOrRegion(language, 'a', this->language);
1898 }
1899
packRegion(const char * region)1900 void ResTable_config::packRegion(const char* region) {
1901 packLanguageOrRegion(region, '0', this->country);
1902 }
1903
unpackLanguage(char language[4]) const1904 size_t ResTable_config::unpackLanguage(char language[4]) const {
1905 return unpackLanguageOrRegion(this->language, 'a', language);
1906 }
1907
unpackRegion(char region[4]) const1908 size_t ResTable_config::unpackRegion(char region[4]) const {
1909 return unpackLanguageOrRegion(this->country, '0', region);
1910 }
1911
1912
copyFromDtoH(const ResTable_config & o)1913 void ResTable_config::copyFromDtoH(const ResTable_config& o) {
1914 copyFromDeviceNoSwap(o);
1915 size = sizeof(ResTable_config);
1916 mcc = dtohs(mcc);
1917 mnc = dtohs(mnc);
1918 density = dtohs(density);
1919 screenWidth = dtohs(screenWidth);
1920 screenHeight = dtohs(screenHeight);
1921 sdkVersion = dtohs(sdkVersion);
1922 minorVersion = dtohs(minorVersion);
1923 smallestScreenWidthDp = dtohs(smallestScreenWidthDp);
1924 screenWidthDp = dtohs(screenWidthDp);
1925 screenHeightDp = dtohs(screenHeightDp);
1926 }
1927
swapHtoD()1928 void ResTable_config::swapHtoD() {
1929 size = htodl(size);
1930 mcc = htods(mcc);
1931 mnc = htods(mnc);
1932 density = htods(density);
1933 screenWidth = htods(screenWidth);
1934 screenHeight = htods(screenHeight);
1935 sdkVersion = htods(sdkVersion);
1936 minorVersion = htods(minorVersion);
1937 smallestScreenWidthDp = htods(smallestScreenWidthDp);
1938 screenWidthDp = htods(screenWidthDp);
1939 screenHeightDp = htods(screenHeightDp);
1940 }
1941
compareLocales(const ResTable_config & l,const ResTable_config & r)1942 /* static */ inline int compareLocales(const ResTable_config &l, const ResTable_config &r) {
1943 if (l.locale != r.locale) {
1944 return (l.locale > r.locale) ? 1 : -1;
1945 }
1946
1947 // The language & region are equal, so compare the scripts, variants and
1948 // numbering systms in this order. Comparison of variants and numbering
1949 // systems should happen very infrequently (if at all.)
1950 // The comparison code relies on memcmp low-level optimizations that make it
1951 // more efficient than strncmp.
1952 const char emptyScript[sizeof(l.localeScript)] = {'\0', '\0', '\0', '\0'};
1953 const char *lScript = l.localeScriptWasComputed ? emptyScript : l.localeScript;
1954 const char *rScript = r.localeScriptWasComputed ? emptyScript : r.localeScript;
1955
1956 int script = memcmp(lScript, rScript, sizeof(l.localeScript));
1957 if (script) {
1958 return script;
1959 }
1960
1961 int variant = memcmp(l.localeVariant, r.localeVariant, sizeof(l.localeVariant));
1962 if (variant) {
1963 return variant;
1964 }
1965
1966 return memcmp(l.localeNumberingSystem, r.localeNumberingSystem,
1967 sizeof(l.localeNumberingSystem));
1968 }
1969
compare(const ResTable_config & o) const1970 int ResTable_config::compare(const ResTable_config& o) const {
1971 if (imsi != o.imsi) {
1972 return (imsi > o.imsi) ? 1 : -1;
1973 }
1974
1975 int32_t diff = compareLocales(*this, o);
1976 if (diff < 0) {
1977 return -1;
1978 }
1979 if (diff > 0) {
1980 return 1;
1981 }
1982
1983 if (screenType != o.screenType) {
1984 return (screenType > o.screenType) ? 1 : -1;
1985 }
1986 if (input != o.input) {
1987 return (input > o.input) ? 1 : -1;
1988 }
1989 if (screenSize != o.screenSize) {
1990 return (screenSize > o.screenSize) ? 1 : -1;
1991 }
1992 if (version != o.version) {
1993 return (version > o.version) ? 1 : -1;
1994 }
1995 if (screenLayout != o.screenLayout) {
1996 return (screenLayout > o.screenLayout) ? 1 : -1;
1997 }
1998 if (screenLayout2 != o.screenLayout2) {
1999 return (screenLayout2 > o.screenLayout2) ? 1 : -1;
2000 }
2001 if (colorMode != o.colorMode) {
2002 return (colorMode > o.colorMode) ? 1 : -1;
2003 }
2004 if (uiMode != o.uiMode) {
2005 return (uiMode > o.uiMode) ? 1 : -1;
2006 }
2007 if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
2008 return (smallestScreenWidthDp > o.smallestScreenWidthDp) ? 1 : -1;
2009 }
2010 if (screenSizeDp != o.screenSizeDp) {
2011 return (screenSizeDp > o.screenSizeDp) ? 1 : -1;
2012 }
2013 return 0;
2014 }
2015
compareLogical(const ResTable_config & o) const2016 int ResTable_config::compareLogical(const ResTable_config& o) const {
2017 if (mcc != o.mcc) {
2018 return mcc < o.mcc ? -1 : 1;
2019 }
2020 if (mnc != o.mnc) {
2021 return mnc < o.mnc ? -1 : 1;
2022 }
2023
2024 int diff = compareLocales(*this, o);
2025 if (diff < 0) {
2026 return -1;
2027 }
2028 if (diff > 0) {
2029 return 1;
2030 }
2031
2032 if ((screenLayout & MASK_LAYOUTDIR) != (o.screenLayout & MASK_LAYOUTDIR)) {
2033 return (screenLayout & MASK_LAYOUTDIR) < (o.screenLayout & MASK_LAYOUTDIR) ? -1 : 1;
2034 }
2035 if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
2036 return smallestScreenWidthDp < o.smallestScreenWidthDp ? -1 : 1;
2037 }
2038 if (screenWidthDp != o.screenWidthDp) {
2039 return screenWidthDp < o.screenWidthDp ? -1 : 1;
2040 }
2041 if (screenHeightDp != o.screenHeightDp) {
2042 return screenHeightDp < o.screenHeightDp ? -1 : 1;
2043 }
2044 if (screenWidth != o.screenWidth) {
2045 return screenWidth < o.screenWidth ? -1 : 1;
2046 }
2047 if (screenHeight != o.screenHeight) {
2048 return screenHeight < o.screenHeight ? -1 : 1;
2049 }
2050 if (density != o.density) {
2051 return density < o.density ? -1 : 1;
2052 }
2053 if (orientation != o.orientation) {
2054 return orientation < o.orientation ? -1 : 1;
2055 }
2056 if (touchscreen != o.touchscreen) {
2057 return touchscreen < o.touchscreen ? -1 : 1;
2058 }
2059 if (input != o.input) {
2060 return input < o.input ? -1 : 1;
2061 }
2062 if (screenLayout != o.screenLayout) {
2063 return screenLayout < o.screenLayout ? -1 : 1;
2064 }
2065 if (screenLayout2 != o.screenLayout2) {
2066 return screenLayout2 < o.screenLayout2 ? -1 : 1;
2067 }
2068 if (colorMode != o.colorMode) {
2069 return colorMode < o.colorMode ? -1 : 1;
2070 }
2071 if (uiMode != o.uiMode) {
2072 return uiMode < o.uiMode ? -1 : 1;
2073 }
2074 if (version != o.version) {
2075 return version < o.version ? -1 : 1;
2076 }
2077 return 0;
2078 }
2079
diff(const ResTable_config & o) const2080 int ResTable_config::diff(const ResTable_config& o) const {
2081 int diffs = 0;
2082 if (mcc != o.mcc) diffs |= CONFIG_MCC;
2083 if (mnc != o.mnc) diffs |= CONFIG_MNC;
2084 if (orientation != o.orientation) diffs |= CONFIG_ORIENTATION;
2085 if (density != o.density) diffs |= CONFIG_DENSITY;
2086 if (touchscreen != o.touchscreen) diffs |= CONFIG_TOUCHSCREEN;
2087 if (((inputFlags^o.inputFlags)&(MASK_KEYSHIDDEN|MASK_NAVHIDDEN)) != 0)
2088 diffs |= CONFIG_KEYBOARD_HIDDEN;
2089 if (keyboard != o.keyboard) diffs |= CONFIG_KEYBOARD;
2090 if (navigation != o.navigation) diffs |= CONFIG_NAVIGATION;
2091 if (screenSize != o.screenSize) diffs |= CONFIG_SCREEN_SIZE;
2092 if (version != o.version) diffs |= CONFIG_VERSION;
2093 if ((screenLayout & MASK_LAYOUTDIR) != (o.screenLayout & MASK_LAYOUTDIR)) diffs |= CONFIG_LAYOUTDIR;
2094 if ((screenLayout & ~MASK_LAYOUTDIR) != (o.screenLayout & ~MASK_LAYOUTDIR)) diffs |= CONFIG_SCREEN_LAYOUT;
2095 if ((screenLayout2 & MASK_SCREENROUND) != (o.screenLayout2 & MASK_SCREENROUND)) diffs |= CONFIG_SCREEN_ROUND;
2096 if ((colorMode & MASK_WIDE_COLOR_GAMUT) != (o.colorMode & MASK_WIDE_COLOR_GAMUT)) diffs |= CONFIG_COLOR_MODE;
2097 if ((colorMode & MASK_HDR) != (o.colorMode & MASK_HDR)) diffs |= CONFIG_COLOR_MODE;
2098 if (uiMode != o.uiMode) diffs |= CONFIG_UI_MODE;
2099 if (smallestScreenWidthDp != o.smallestScreenWidthDp) diffs |= CONFIG_SMALLEST_SCREEN_SIZE;
2100 if (screenSizeDp != o.screenSizeDp) diffs |= CONFIG_SCREEN_SIZE;
2101
2102 const int diff = compareLocales(*this, o);
2103 if (diff) diffs |= CONFIG_LOCALE;
2104
2105 return diffs;
2106 }
2107
2108 // There isn't a well specified "importance" order between variants and
2109 // scripts. We can't easily tell whether, say "en-Latn-US" is more or less
2110 // specific than "en-US-POSIX".
2111 //
2112 // We therefore arbitrarily decide to give priority to variants over
2113 // scripts since it seems more useful to do so. We will consider
2114 // "en-US-POSIX" to be more specific than "en-Latn-US".
2115 //
2116 // Unicode extension keywords are considered to be less important than
2117 // scripts and variants.
getImportanceScoreOfLocale() const2118 inline int ResTable_config::getImportanceScoreOfLocale() const {
2119 return (localeVariant[0] ? 4 : 0)
2120 + (localeScript[0] && !localeScriptWasComputed ? 2: 0)
2121 + (localeNumberingSystem[0] ? 1: 0);
2122 }
2123
isLocaleMoreSpecificThan(const ResTable_config & o) const2124 int ResTable_config::isLocaleMoreSpecificThan(const ResTable_config& o) const {
2125 if (locale || o.locale) {
2126 if (language[0] != o.language[0]) {
2127 if (!language[0]) return -1;
2128 if (!o.language[0]) return 1;
2129 }
2130
2131 if (country[0] != o.country[0]) {
2132 if (!country[0]) return -1;
2133 if (!o.country[0]) return 1;
2134 }
2135 }
2136
2137 return getImportanceScoreOfLocale() - o.getImportanceScoreOfLocale();
2138 }
2139
isMoreSpecificThan(const ResTable_config & o) const2140 bool ResTable_config::isMoreSpecificThan(const ResTable_config& o) const {
2141 // The order of the following tests defines the importance of one
2142 // configuration parameter over another. Those tests first are more
2143 // important, trumping any values in those following them.
2144 if (imsi || o.imsi) {
2145 if (mcc != o.mcc) {
2146 if (!mcc) return false;
2147 if (!o.mcc) return true;
2148 }
2149
2150 if (mnc != o.mnc) {
2151 if (!mnc) return false;
2152 if (!o.mnc) return true;
2153 }
2154 }
2155
2156 if (locale || o.locale) {
2157 const int diff = isLocaleMoreSpecificThan(o);
2158 if (diff < 0) {
2159 return false;
2160 }
2161
2162 if (diff > 0) {
2163 return true;
2164 }
2165 }
2166
2167 if (screenLayout || o.screenLayout) {
2168 if (((screenLayout^o.screenLayout) & MASK_LAYOUTDIR) != 0) {
2169 if (!(screenLayout & MASK_LAYOUTDIR)) return false;
2170 if (!(o.screenLayout & MASK_LAYOUTDIR)) return true;
2171 }
2172 }
2173
2174 if (smallestScreenWidthDp || o.smallestScreenWidthDp) {
2175 if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
2176 if (!smallestScreenWidthDp) return false;
2177 if (!o.smallestScreenWidthDp) return true;
2178 }
2179 }
2180
2181 if (screenSizeDp || o.screenSizeDp) {
2182 if (screenWidthDp != o.screenWidthDp) {
2183 if (!screenWidthDp) return false;
2184 if (!o.screenWidthDp) return true;
2185 }
2186
2187 if (screenHeightDp != o.screenHeightDp) {
2188 if (!screenHeightDp) return false;
2189 if (!o.screenHeightDp) return true;
2190 }
2191 }
2192
2193 if (screenLayout || o.screenLayout) {
2194 if (((screenLayout^o.screenLayout) & MASK_SCREENSIZE) != 0) {
2195 if (!(screenLayout & MASK_SCREENSIZE)) return false;
2196 if (!(o.screenLayout & MASK_SCREENSIZE)) return true;
2197 }
2198 if (((screenLayout^o.screenLayout) & MASK_SCREENLONG) != 0) {
2199 if (!(screenLayout & MASK_SCREENLONG)) return false;
2200 if (!(o.screenLayout & MASK_SCREENLONG)) return true;
2201 }
2202 }
2203
2204 if (screenLayout2 || o.screenLayout2) {
2205 if (((screenLayout2^o.screenLayout2) & MASK_SCREENROUND) != 0) {
2206 if (!(screenLayout2 & MASK_SCREENROUND)) return false;
2207 if (!(o.screenLayout2 & MASK_SCREENROUND)) return true;
2208 }
2209 }
2210
2211 if (colorMode || o.colorMode) {
2212 if (((colorMode^o.colorMode) & MASK_HDR) != 0) {
2213 if (!(colorMode & MASK_HDR)) return false;
2214 if (!(o.colorMode & MASK_HDR)) return true;
2215 }
2216 if (((colorMode^o.colorMode) & MASK_WIDE_COLOR_GAMUT) != 0) {
2217 if (!(colorMode & MASK_WIDE_COLOR_GAMUT)) return false;
2218 if (!(o.colorMode & MASK_WIDE_COLOR_GAMUT)) return true;
2219 }
2220 }
2221
2222 if (orientation != o.orientation) {
2223 if (!orientation) return false;
2224 if (!o.orientation) return true;
2225 }
2226
2227 if (uiMode || o.uiMode) {
2228 if (((uiMode^o.uiMode) & MASK_UI_MODE_TYPE) != 0) {
2229 if (!(uiMode & MASK_UI_MODE_TYPE)) return false;
2230 if (!(o.uiMode & MASK_UI_MODE_TYPE)) return true;
2231 }
2232 if (((uiMode^o.uiMode) & MASK_UI_MODE_NIGHT) != 0) {
2233 if (!(uiMode & MASK_UI_MODE_NIGHT)) return false;
2234 if (!(o.uiMode & MASK_UI_MODE_NIGHT)) return true;
2235 }
2236 }
2237
2238 // density is never 'more specific'
2239 // as the default just equals 160
2240
2241 if (touchscreen != o.touchscreen) {
2242 if (!touchscreen) return false;
2243 if (!o.touchscreen) return true;
2244 }
2245
2246 if (input || o.input) {
2247 if (((inputFlags^o.inputFlags) & MASK_KEYSHIDDEN) != 0) {
2248 if (!(inputFlags & MASK_KEYSHIDDEN)) return false;
2249 if (!(o.inputFlags & MASK_KEYSHIDDEN)) return true;
2250 }
2251
2252 if (((inputFlags^o.inputFlags) & MASK_NAVHIDDEN) != 0) {
2253 if (!(inputFlags & MASK_NAVHIDDEN)) return false;
2254 if (!(o.inputFlags & MASK_NAVHIDDEN)) return true;
2255 }
2256
2257 if (keyboard != o.keyboard) {
2258 if (!keyboard) return false;
2259 if (!o.keyboard) return true;
2260 }
2261
2262 if (navigation != o.navigation) {
2263 if (!navigation) return false;
2264 if (!o.navigation) return true;
2265 }
2266 }
2267
2268 if (screenSize || o.screenSize) {
2269 if (screenWidth != o.screenWidth) {
2270 if (!screenWidth) return false;
2271 if (!o.screenWidth) return true;
2272 }
2273
2274 if (screenHeight != o.screenHeight) {
2275 if (!screenHeight) return false;
2276 if (!o.screenHeight) return true;
2277 }
2278 }
2279
2280 if (version || o.version) {
2281 if (sdkVersion != o.sdkVersion) {
2282 if (!sdkVersion) return false;
2283 if (!o.sdkVersion) return true;
2284 }
2285
2286 if (minorVersion != o.minorVersion) {
2287 if (!minorVersion) return false;
2288 if (!o.minorVersion) return true;
2289 }
2290 }
2291 return false;
2292 }
2293
2294 // Codes for specially handled languages and regions
2295 static const char kEnglish[2] = {'e', 'n'}; // packed version of "en"
2296 static const char kUnitedStates[2] = {'U', 'S'}; // packed version of "US"
2297 static const char kFilipino[2] = {'\xAD', '\x05'}; // packed version of "fil"
2298 static const char kTagalog[2] = {'t', 'l'}; // packed version of "tl"
2299
2300 // Checks if two language or region codes are identical
areIdentical(const char code1[2],const char code2[2])2301 inline bool areIdentical(const char code1[2], const char code2[2]) {
2302 return code1[0] == code2[0] && code1[1] == code2[1];
2303 }
2304
langsAreEquivalent(const char lang1[2],const char lang2[2])2305 inline bool langsAreEquivalent(const char lang1[2], const char lang2[2]) {
2306 return areIdentical(lang1, lang2) ||
2307 (areIdentical(lang1, kTagalog) && areIdentical(lang2, kFilipino)) ||
2308 (areIdentical(lang1, kFilipino) && areIdentical(lang2, kTagalog));
2309 }
2310
isLocaleBetterThan(const ResTable_config & o,const ResTable_config * requested) const2311 bool ResTable_config::isLocaleBetterThan(const ResTable_config& o,
2312 const ResTable_config* requested) const {
2313 if (requested->locale == 0) {
2314 // The request doesn't have a locale, so no resource is better
2315 // than the other.
2316 return false;
2317 }
2318
2319 if (locale == 0 && o.locale == 0) {
2320 // The locale part of both resources is empty, so none is better
2321 // than the other.
2322 return false;
2323 }
2324
2325 // Non-matching locales have been filtered out, so both resources
2326 // match the requested locale.
2327 //
2328 // Because of the locale-related checks in match() and the checks, we know
2329 // that:
2330 // 1) The resource languages are either empty or match the request;
2331 // and
2332 // 2) If the request's script is known, the resource scripts are either
2333 // unknown or match the request.
2334
2335 if (!langsAreEquivalent(language, o.language)) {
2336 // The languages of the two resources are not equivalent. If we are
2337 // here, we can only assume that the two resources matched the request
2338 // because one doesn't have a language and the other has a matching
2339 // language.
2340 //
2341 // We consider the one that has the language specified a better match.
2342 //
2343 // The exception is that we consider no-language resources a better match
2344 // for US English and similar locales than locales that are a descendant
2345 // of Internatinal English (en-001), since no-language resources are
2346 // where the US English resource have traditionally lived for most apps.
2347 if (areIdentical(requested->language, kEnglish)) {
2348 if (areIdentical(requested->country, kUnitedStates)) {
2349 // For US English itself, we consider a no-locale resource a
2350 // better match if the other resource has a country other than
2351 // US specified.
2352 if (language[0] != '\0') {
2353 return country[0] == '\0' || areIdentical(country, kUnitedStates);
2354 } else {
2355 return !(o.country[0] == '\0' || areIdentical(o.country, kUnitedStates));
2356 }
2357 } else if (localeDataIsCloseToUsEnglish(requested->country)) {
2358 if (language[0] != '\0') {
2359 return localeDataIsCloseToUsEnglish(country);
2360 } else {
2361 return !localeDataIsCloseToUsEnglish(o.country);
2362 }
2363 }
2364 }
2365 return (language[0] != '\0');
2366 }
2367
2368 // If we are here, both the resources have an equivalent non-empty language
2369 // to the request.
2370 //
2371 // Because the languages are equivalent, computeScript() always returns a
2372 // non-empty script for languages it knows about, and we have passed the
2373 // script checks in match(), the scripts are either all unknown or are all
2374 // the same. So we can't gain anything by checking the scripts. We need to
2375 // check the region and variant.
2376
2377 // See if any of the regions is better than the other.
2378 const int region_comparison = localeDataCompareRegions(
2379 country, o.country,
2380 requested->language, requested->localeScript, requested->country);
2381 if (region_comparison != 0) {
2382 return (region_comparison > 0);
2383 }
2384
2385 // The regions are the same. Try the variant.
2386 const bool localeMatches = strncmp(
2387 localeVariant, requested->localeVariant, sizeof(localeVariant)) == 0;
2388 const bool otherMatches = strncmp(
2389 o.localeVariant, requested->localeVariant, sizeof(localeVariant)) == 0;
2390 if (localeMatches != otherMatches) {
2391 return localeMatches;
2392 }
2393
2394 // The variants are the same, try numbering system.
2395 const bool localeNumsysMatches = strncmp(localeNumberingSystem,
2396 requested->localeNumberingSystem,
2397 sizeof(localeNumberingSystem)) == 0;
2398 const bool otherNumsysMatches = strncmp(o.localeNumberingSystem,
2399 requested->localeNumberingSystem,
2400 sizeof(localeNumberingSystem)) == 0;
2401 if (localeNumsysMatches != otherNumsysMatches) {
2402 return localeNumsysMatches;
2403 }
2404
2405 // Finally, the languages, although equivalent, may still be different
2406 // (like for Tagalog and Filipino). Identical is better than just
2407 // equivalent.
2408 if (areIdentical(language, requested->language)
2409 && !areIdentical(o.language, requested->language)) {
2410 return true;
2411 }
2412
2413 return false;
2414 }
2415
isBetterThan(const ResTable_config & o,const ResTable_config * requested) const2416 bool ResTable_config::isBetterThan(const ResTable_config& o,
2417 const ResTable_config* requested) const {
2418 if (requested) {
2419 if (imsi || o.imsi) {
2420 if ((mcc != o.mcc) && requested->mcc) {
2421 return (mcc);
2422 }
2423
2424 if ((mnc != o.mnc) && requested->mnc) {
2425 return (mnc);
2426 }
2427 }
2428
2429 if (isLocaleBetterThan(o, requested)) {
2430 return true;
2431 }
2432
2433 if (screenLayout || o.screenLayout) {
2434 if (((screenLayout^o.screenLayout) & MASK_LAYOUTDIR) != 0
2435 && (requested->screenLayout & MASK_LAYOUTDIR)) {
2436 int myLayoutDir = screenLayout & MASK_LAYOUTDIR;
2437 int oLayoutDir = o.screenLayout & MASK_LAYOUTDIR;
2438 return (myLayoutDir > oLayoutDir);
2439 }
2440 }
2441
2442 if (smallestScreenWidthDp || o.smallestScreenWidthDp) {
2443 // The configuration closest to the actual size is best.
2444 // We assume that larger configs have already been filtered
2445 // out at this point. That means we just want the largest one.
2446 if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
2447 return smallestScreenWidthDp > o.smallestScreenWidthDp;
2448 }
2449 }
2450
2451 if (screenSizeDp || o.screenSizeDp) {
2452 // "Better" is based on the sum of the difference between both
2453 // width and height from the requested dimensions. We are
2454 // assuming the invalid configs (with smaller dimens) have
2455 // already been filtered. Note that if a particular dimension
2456 // is unspecified, we will end up with a large value (the
2457 // difference between 0 and the requested dimension), which is
2458 // good since we will prefer a config that has specified a
2459 // dimension value.
2460 int myDelta = 0, otherDelta = 0;
2461 if (requested->screenWidthDp) {
2462 myDelta += requested->screenWidthDp - screenWidthDp;
2463 otherDelta += requested->screenWidthDp - o.screenWidthDp;
2464 }
2465 if (requested->screenHeightDp) {
2466 myDelta += requested->screenHeightDp - screenHeightDp;
2467 otherDelta += requested->screenHeightDp - o.screenHeightDp;
2468 }
2469 if (kDebugTableSuperNoisy) {
2470 ALOGI("Comparing this %dx%d to other %dx%d in %dx%d: myDelta=%d otherDelta=%d",
2471 screenWidthDp, screenHeightDp, o.screenWidthDp, o.screenHeightDp,
2472 requested->screenWidthDp, requested->screenHeightDp, myDelta, otherDelta);
2473 }
2474 if (myDelta != otherDelta) {
2475 return myDelta < otherDelta;
2476 }
2477 }
2478
2479 if (screenLayout || o.screenLayout) {
2480 if (((screenLayout^o.screenLayout) & MASK_SCREENSIZE) != 0
2481 && (requested->screenLayout & MASK_SCREENSIZE)) {
2482 // A little backwards compatibility here: undefined is
2483 // considered equivalent to normal. But only if the
2484 // requested size is at least normal; otherwise, small
2485 // is better than the default.
2486 int mySL = (screenLayout & MASK_SCREENSIZE);
2487 int oSL = (o.screenLayout & MASK_SCREENSIZE);
2488 int fixedMySL = mySL;
2489 int fixedOSL = oSL;
2490 if ((requested->screenLayout & MASK_SCREENSIZE) >= SCREENSIZE_NORMAL) {
2491 if (fixedMySL == 0) fixedMySL = SCREENSIZE_NORMAL;
2492 if (fixedOSL == 0) fixedOSL = SCREENSIZE_NORMAL;
2493 }
2494 // For screen size, the best match is the one that is
2495 // closest to the requested screen size, but not over
2496 // (the not over part is dealt with in match() below).
2497 if (fixedMySL == fixedOSL) {
2498 // If the two are the same, but 'this' is actually
2499 // undefined, then the other is really a better match.
2500 if (mySL == 0) return false;
2501 return true;
2502 }
2503 if (fixedMySL != fixedOSL) {
2504 return fixedMySL > fixedOSL;
2505 }
2506 }
2507 if (((screenLayout^o.screenLayout) & MASK_SCREENLONG) != 0
2508 && (requested->screenLayout & MASK_SCREENLONG)) {
2509 return (screenLayout & MASK_SCREENLONG);
2510 }
2511 }
2512
2513 if (screenLayout2 || o.screenLayout2) {
2514 if (((screenLayout2^o.screenLayout2) & MASK_SCREENROUND) != 0 &&
2515 (requested->screenLayout2 & MASK_SCREENROUND)) {
2516 return screenLayout2 & MASK_SCREENROUND;
2517 }
2518 }
2519
2520 if (colorMode || o.colorMode) {
2521 if (((colorMode^o.colorMode) & MASK_WIDE_COLOR_GAMUT) != 0 &&
2522 (requested->colorMode & MASK_WIDE_COLOR_GAMUT)) {
2523 return colorMode & MASK_WIDE_COLOR_GAMUT;
2524 }
2525 if (((colorMode^o.colorMode) & MASK_HDR) != 0 &&
2526 (requested->colorMode & MASK_HDR)) {
2527 return colorMode & MASK_HDR;
2528 }
2529 }
2530
2531 if ((orientation != o.orientation) && requested->orientation) {
2532 return (orientation);
2533 }
2534
2535 if (uiMode || o.uiMode) {
2536 if (((uiMode^o.uiMode) & MASK_UI_MODE_TYPE) != 0
2537 && (requested->uiMode & MASK_UI_MODE_TYPE)) {
2538 return (uiMode & MASK_UI_MODE_TYPE);
2539 }
2540 if (((uiMode^o.uiMode) & MASK_UI_MODE_NIGHT) != 0
2541 && (requested->uiMode & MASK_UI_MODE_NIGHT)) {
2542 return (uiMode & MASK_UI_MODE_NIGHT);
2543 }
2544 }
2545
2546 if (screenType || o.screenType) {
2547 if (density != o.density) {
2548 // Use the system default density (DENSITY_MEDIUM, 160dpi) if none specified.
2549 const int thisDensity = density ? density : int(ResTable_config::DENSITY_MEDIUM);
2550 const int otherDensity = o.density ? o.density : int(ResTable_config::DENSITY_MEDIUM);
2551
2552 // We always prefer DENSITY_ANY over scaling a density bucket.
2553 if (thisDensity == ResTable_config::DENSITY_ANY) {
2554 return true;
2555 } else if (otherDensity == ResTable_config::DENSITY_ANY) {
2556 return false;
2557 }
2558
2559 int requestedDensity = requested->density;
2560 if (requested->density == 0 ||
2561 requested->density == ResTable_config::DENSITY_ANY) {
2562 requestedDensity = ResTable_config::DENSITY_MEDIUM;
2563 }
2564
2565 // DENSITY_ANY is now dealt with. We should look to
2566 // pick a density bucket and potentially scale it.
2567 // Any density is potentially useful
2568 // because the system will scale it. Scaling down
2569 // is generally better than scaling up.
2570 int h = thisDensity;
2571 int l = otherDensity;
2572 bool bImBigger = true;
2573 if (l > h) {
2574 int t = h;
2575 h = l;
2576 l = t;
2577 bImBigger = false;
2578 }
2579
2580 if (requestedDensity >= h) {
2581 // requested value higher than both l and h, give h
2582 return bImBigger;
2583 }
2584 if (l >= requestedDensity) {
2585 // requested value lower than both l and h, give l
2586 return !bImBigger;
2587 }
2588 // saying that scaling down is 2x better than up
2589 if (((2 * l) - requestedDensity) * h > requestedDensity * requestedDensity) {
2590 return !bImBigger;
2591 } else {
2592 return bImBigger;
2593 }
2594 }
2595
2596 if ((touchscreen != o.touchscreen) && requested->touchscreen) {
2597 return (touchscreen);
2598 }
2599 }
2600
2601 if (input || o.input) {
2602 const int keysHidden = inputFlags & MASK_KEYSHIDDEN;
2603 const int oKeysHidden = o.inputFlags & MASK_KEYSHIDDEN;
2604 if (keysHidden != oKeysHidden) {
2605 const int reqKeysHidden =
2606 requested->inputFlags & MASK_KEYSHIDDEN;
2607 if (reqKeysHidden) {
2608
2609 if (!keysHidden) return false;
2610 if (!oKeysHidden) return true;
2611 // For compatibility, we count KEYSHIDDEN_NO as being
2612 // the same as KEYSHIDDEN_SOFT. Here we disambiguate
2613 // these by making an exact match more specific.
2614 if (reqKeysHidden == keysHidden) return true;
2615 if (reqKeysHidden == oKeysHidden) return false;
2616 }
2617 }
2618
2619 const int navHidden = inputFlags & MASK_NAVHIDDEN;
2620 const int oNavHidden = o.inputFlags & MASK_NAVHIDDEN;
2621 if (navHidden != oNavHidden) {
2622 const int reqNavHidden =
2623 requested->inputFlags & MASK_NAVHIDDEN;
2624 if (reqNavHidden) {
2625
2626 if (!navHidden) return false;
2627 if (!oNavHidden) return true;
2628 }
2629 }
2630
2631 if ((keyboard != o.keyboard) && requested->keyboard) {
2632 return (keyboard);
2633 }
2634
2635 if ((navigation != o.navigation) && requested->navigation) {
2636 return (navigation);
2637 }
2638 }
2639
2640 if (screenSize || o.screenSize) {
2641 // "Better" is based on the sum of the difference between both
2642 // width and height from the requested dimensions. We are
2643 // assuming the invalid configs (with smaller sizes) have
2644 // already been filtered. Note that if a particular dimension
2645 // is unspecified, we will end up with a large value (the
2646 // difference between 0 and the requested dimension), which is
2647 // good since we will prefer a config that has specified a
2648 // size value.
2649 int myDelta = 0, otherDelta = 0;
2650 if (requested->screenWidth) {
2651 myDelta += requested->screenWidth - screenWidth;
2652 otherDelta += requested->screenWidth - o.screenWidth;
2653 }
2654 if (requested->screenHeight) {
2655 myDelta += requested->screenHeight - screenHeight;
2656 otherDelta += requested->screenHeight - o.screenHeight;
2657 }
2658 if (myDelta != otherDelta) {
2659 return myDelta < otherDelta;
2660 }
2661 }
2662
2663 if (version || o.version) {
2664 if ((sdkVersion != o.sdkVersion) && requested->sdkVersion) {
2665 return (sdkVersion > o.sdkVersion);
2666 }
2667
2668 if ((minorVersion != o.minorVersion) &&
2669 requested->minorVersion) {
2670 return (minorVersion);
2671 }
2672 }
2673
2674 return false;
2675 }
2676 return isMoreSpecificThan(o);
2677 }
2678
match(const ResTable_config & settings) const2679 bool ResTable_config::match(const ResTable_config& settings) const {
2680 if (imsi != 0) {
2681 if (mcc != 0 && mcc != settings.mcc) {
2682 return false;
2683 }
2684 if (mnc != 0 && mnc != settings.mnc) {
2685 return false;
2686 }
2687 }
2688 if (locale != 0) {
2689 // Don't consider country and variants when deciding matches.
2690 // (Theoretically, the variant can also affect the script. For
2691 // example, "ar-alalc97" probably implies the Latin script, but since
2692 // CLDR doesn't support getting likely scripts for that, we'll assume
2693 // the variant doesn't change the script.)
2694 //
2695 // If two configs differ only in their country and variant,
2696 // they can be weeded out in the isMoreSpecificThan test.
2697 if (!langsAreEquivalent(language, settings.language)) {
2698 return false;
2699 }
2700
2701 // For backward compatibility and supporting private-use locales, we
2702 // fall back to old behavior if we couldn't determine the script for
2703 // either of the desired locale or the provided locale. But if we could determine
2704 // the scripts, they should be the same for the locales to match.
2705 bool countriesMustMatch = false;
2706 char computed_script[4];
2707 const char* script;
2708 if (settings.localeScript[0] == '\0') { // could not determine the request's script
2709 countriesMustMatch = true;
2710 } else {
2711 if (localeScript[0] == '\0' && !localeScriptWasComputed) {
2712 // script was not provided or computed, so we try to compute it
2713 localeDataComputeScript(computed_script, language, country);
2714 if (computed_script[0] == '\0') { // we could not compute the script
2715 countriesMustMatch = true;
2716 } else {
2717 script = computed_script;
2718 }
2719 } else { // script was provided, so just use it
2720 script = localeScript;
2721 }
2722 }
2723
2724 if (countriesMustMatch) {
2725 if (country[0] != '\0' && !areIdentical(country, settings.country)) {
2726 return false;
2727 }
2728 } else {
2729 if (memcmp(script, settings.localeScript, sizeof(settings.localeScript)) != 0) {
2730 return false;
2731 }
2732 }
2733 }
2734
2735 if (screenConfig != 0) {
2736 const int layoutDir = screenLayout&MASK_LAYOUTDIR;
2737 const int setLayoutDir = settings.screenLayout&MASK_LAYOUTDIR;
2738 if (layoutDir != 0 && layoutDir != setLayoutDir) {
2739 return false;
2740 }
2741
2742 const int screenSize = screenLayout&MASK_SCREENSIZE;
2743 const int setScreenSize = settings.screenLayout&MASK_SCREENSIZE;
2744 // Any screen sizes for larger screens than the setting do not
2745 // match.
2746 if (screenSize != 0 && screenSize > setScreenSize) {
2747 return false;
2748 }
2749
2750 const int screenLong = screenLayout&MASK_SCREENLONG;
2751 const int setScreenLong = settings.screenLayout&MASK_SCREENLONG;
2752 if (screenLong != 0 && screenLong != setScreenLong) {
2753 return false;
2754 }
2755
2756 const int uiModeType = uiMode&MASK_UI_MODE_TYPE;
2757 const int setUiModeType = settings.uiMode&MASK_UI_MODE_TYPE;
2758 if (uiModeType != 0 && uiModeType != setUiModeType) {
2759 return false;
2760 }
2761
2762 const int uiModeNight = uiMode&MASK_UI_MODE_NIGHT;
2763 const int setUiModeNight = settings.uiMode&MASK_UI_MODE_NIGHT;
2764 if (uiModeNight != 0 && uiModeNight != setUiModeNight) {
2765 return false;
2766 }
2767
2768 if (smallestScreenWidthDp != 0
2769 && smallestScreenWidthDp > settings.smallestScreenWidthDp) {
2770 return false;
2771 }
2772 }
2773
2774 if (screenConfig2 != 0) {
2775 const int screenRound = screenLayout2 & MASK_SCREENROUND;
2776 const int setScreenRound = settings.screenLayout2 & MASK_SCREENROUND;
2777 if (screenRound != 0 && screenRound != setScreenRound) {
2778 return false;
2779 }
2780
2781 const int hdr = colorMode & MASK_HDR;
2782 const int setHdr = settings.colorMode & MASK_HDR;
2783 if (hdr != 0 && hdr != setHdr) {
2784 return false;
2785 }
2786
2787 const int wideColorGamut = colorMode & MASK_WIDE_COLOR_GAMUT;
2788 const int setWideColorGamut = settings.colorMode & MASK_WIDE_COLOR_GAMUT;
2789 if (wideColorGamut != 0 && wideColorGamut != setWideColorGamut) {
2790 return false;
2791 }
2792 }
2793
2794 if (screenSizeDp != 0) {
2795 if (screenWidthDp != 0 && screenWidthDp > settings.screenWidthDp) {
2796 if (kDebugTableSuperNoisy) {
2797 ALOGI("Filtering out width %d in requested %d", screenWidthDp,
2798 settings.screenWidthDp);
2799 }
2800 return false;
2801 }
2802 if (screenHeightDp != 0 && screenHeightDp > settings.screenHeightDp) {
2803 if (kDebugTableSuperNoisy) {
2804 ALOGI("Filtering out height %d in requested %d", screenHeightDp,
2805 settings.screenHeightDp);
2806 }
2807 return false;
2808 }
2809 }
2810 if (screenType != 0) {
2811 if (orientation != 0 && orientation != settings.orientation) {
2812 return false;
2813 }
2814 // density always matches - we can scale it. See isBetterThan
2815 if (touchscreen != 0 && touchscreen != settings.touchscreen) {
2816 return false;
2817 }
2818 }
2819 if (input != 0) {
2820 const int keysHidden = inputFlags&MASK_KEYSHIDDEN;
2821 const int setKeysHidden = settings.inputFlags&MASK_KEYSHIDDEN;
2822 if (keysHidden != 0 && keysHidden != setKeysHidden) {
2823 // For compatibility, we count a request for KEYSHIDDEN_NO as also
2824 // matching the more recent KEYSHIDDEN_SOFT. Basically
2825 // KEYSHIDDEN_NO means there is some kind of keyboard available.
2826 if (kDebugTableSuperNoisy) {
2827 ALOGI("Matching keysHidden: have=%d, config=%d\n", keysHidden, setKeysHidden);
2828 }
2829 if (keysHidden != KEYSHIDDEN_NO || setKeysHidden != KEYSHIDDEN_SOFT) {
2830 if (kDebugTableSuperNoisy) {
2831 ALOGI("No match!");
2832 }
2833 return false;
2834 }
2835 }
2836 const int navHidden = inputFlags&MASK_NAVHIDDEN;
2837 const int setNavHidden = settings.inputFlags&MASK_NAVHIDDEN;
2838 if (navHidden != 0 && navHidden != setNavHidden) {
2839 return false;
2840 }
2841 if (keyboard != 0 && keyboard != settings.keyboard) {
2842 return false;
2843 }
2844 if (navigation != 0 && navigation != settings.navigation) {
2845 return false;
2846 }
2847 }
2848 if (screenSize != 0) {
2849 if (screenWidth != 0 && screenWidth > settings.screenWidth) {
2850 return false;
2851 }
2852 if (screenHeight != 0 && screenHeight > settings.screenHeight) {
2853 return false;
2854 }
2855 }
2856 if (version != 0) {
2857 if (sdkVersion != 0 && sdkVersion > settings.sdkVersion) {
2858 return false;
2859 }
2860 if (minorVersion != 0 && minorVersion != settings.minorVersion) {
2861 return false;
2862 }
2863 }
2864 return true;
2865 }
2866
appendDirLocale(String8 & out) const2867 void ResTable_config::appendDirLocale(String8& out) const {
2868 if (!language[0]) {
2869 return;
2870 }
2871 const bool scriptWasProvided = localeScript[0] != '\0' && !localeScriptWasComputed;
2872 if (!scriptWasProvided && !localeVariant[0] && !localeNumberingSystem[0]) {
2873 // Legacy format.
2874 if (out.size() > 0) {
2875 out.append("-");
2876 }
2877
2878 char buf[4];
2879 size_t len = unpackLanguage(buf);
2880 out.append(buf, len);
2881
2882 if (country[0]) {
2883 out.append("-r");
2884 len = unpackRegion(buf);
2885 out.append(buf, len);
2886 }
2887 return;
2888 }
2889
2890 // We are writing the modified BCP 47 tag.
2891 // It starts with 'b+' and uses '+' as a separator.
2892
2893 if (out.size() > 0) {
2894 out.append("-");
2895 }
2896 out.append("b+");
2897
2898 char buf[4];
2899 size_t len = unpackLanguage(buf);
2900 out.append(buf, len);
2901
2902 if (scriptWasProvided) {
2903 out.append("+");
2904 out.append(localeScript, sizeof(localeScript));
2905 }
2906
2907 if (country[0]) {
2908 out.append("+");
2909 len = unpackRegion(buf);
2910 out.append(buf, len);
2911 }
2912
2913 if (localeVariant[0]) {
2914 out.append("+");
2915 out.append(localeVariant, strnlen(localeVariant, sizeof(localeVariant)));
2916 }
2917
2918 if (localeNumberingSystem[0]) {
2919 out.append("+u+nu+");
2920 out.append(localeNumberingSystem,
2921 strnlen(localeNumberingSystem, sizeof(localeNumberingSystem)));
2922 }
2923 }
2924
getBcp47Locale(char str[RESTABLE_MAX_LOCALE_LEN],bool canonicalize) const2925 void ResTable_config::getBcp47Locale(char str[RESTABLE_MAX_LOCALE_LEN], bool canonicalize) const {
2926 memset(str, 0, RESTABLE_MAX_LOCALE_LEN);
2927
2928 // This represents the "any" locale value, which has traditionally been
2929 // represented by the empty string.
2930 if (language[0] == '\0' && country[0] == '\0') {
2931 return;
2932 }
2933
2934 size_t charsWritten = 0;
2935 if (language[0] != '\0') {
2936 if (canonicalize && areIdentical(language, kTagalog)) {
2937 // Replace Tagalog with Filipino if we are canonicalizing
2938 str[0] = 'f'; str[1] = 'i'; str[2] = 'l'; str[3] = '\0'; // 3-letter code for Filipino
2939 charsWritten += 3;
2940 } else {
2941 charsWritten += unpackLanguage(str);
2942 }
2943 }
2944
2945 if (localeScript[0] != '\0' && !localeScriptWasComputed) {
2946 if (charsWritten > 0) {
2947 str[charsWritten++] = '-';
2948 }
2949 memcpy(str + charsWritten, localeScript, sizeof(localeScript));
2950 charsWritten += sizeof(localeScript);
2951 }
2952
2953 if (country[0] != '\0') {
2954 if (charsWritten > 0) {
2955 str[charsWritten++] = '-';
2956 }
2957 charsWritten += unpackRegion(str + charsWritten);
2958 }
2959
2960 if (localeVariant[0] != '\0') {
2961 if (charsWritten > 0) {
2962 str[charsWritten++] = '-';
2963 }
2964 memcpy(str + charsWritten, localeVariant, sizeof(localeVariant));
2965 charsWritten += strnlen(str + charsWritten, sizeof(localeVariant));
2966 }
2967
2968 // Add Unicode extension only if at least one other locale component is present
2969 if (localeNumberingSystem[0] != '\0' && charsWritten > 0) {
2970 static constexpr char NU_PREFIX[] = "-u-nu-";
2971 static constexpr size_t NU_PREFIX_LEN = sizeof(NU_PREFIX) - 1;
2972 memcpy(str + charsWritten, NU_PREFIX, NU_PREFIX_LEN);
2973 charsWritten += NU_PREFIX_LEN;
2974 memcpy(str + charsWritten, localeNumberingSystem, sizeof(localeNumberingSystem));
2975 }
2976 }
2977
2978 struct LocaleParserState {
2979 enum State : uint8_t {
2980 BASE, UNICODE_EXTENSION, IGNORE_THE_REST
2981 } parserState;
2982 enum UnicodeState : uint8_t {
2983 /* Initial state after the Unicode singleton is detected. Either a keyword
2984 * or an attribute is expected. */
2985 NO_KEY,
2986 /* Unicode extension key (but not attribute) is expected. Next states:
2987 * NO_KEY, IGNORE_KEY or NUMBERING_SYSTEM. */
2988 EXPECT_KEY,
2989 /* A key is detected, however it is not supported for now. Ignore its
2990 * value. Next states: IGNORE_KEY or NUMBERING_SYSTEM. */
2991 IGNORE_KEY,
2992 /* Numbering system key was detected. Store its value in the configuration
2993 * localeNumberingSystem field. Next state: EXPECT_KEY */
2994 NUMBERING_SYSTEM
2995 } unicodeState;
2996
LocaleParserStateandroid::LocaleParserState2997 LocaleParserState(): parserState(BASE), unicodeState(NO_KEY) {}
2998 };
2999
assignLocaleComponent(ResTable_config * config,const char * start,size_t size,LocaleParserState state)3000 /* static */ inline LocaleParserState assignLocaleComponent(ResTable_config* config,
3001 const char* start, size_t size, LocaleParserState state) {
3002
3003 /* It is assumed that this function is not invoked with state.parserState
3004 * set to IGNORE_THE_REST. The condition is checked by setBcp47Locale
3005 * function. */
3006
3007 if (state.parserState == LocaleParserState::UNICODE_EXTENSION) {
3008 switch (size) {
3009 case 1:
3010 /* Other BCP 47 extensions are not supported at the moment */
3011 state.parserState = LocaleParserState::IGNORE_THE_REST;
3012 break;
3013 case 2:
3014 if (state.unicodeState == LocaleParserState::NO_KEY ||
3015 state.unicodeState == LocaleParserState::EXPECT_KEY) {
3016 /* Analyze Unicode extension key. Currently only 'nu'
3017 * (numbering system) is supported.*/
3018 if ((start[0] == 'n' || start[0] == 'N') &&
3019 (start[1] == 'u' || start[1] == 'U')) {
3020 state.unicodeState = LocaleParserState::NUMBERING_SYSTEM;
3021 } else {
3022 state.unicodeState = LocaleParserState::IGNORE_KEY;
3023 }
3024 } else {
3025 /* Keys are not allowed in other state allowed, ignore the rest. */
3026 state.parserState = LocaleParserState::IGNORE_THE_REST;
3027 }
3028 break;
3029 case 3:
3030 case 4:
3031 case 5:
3032 case 6:
3033 case 7:
3034 case 8:
3035 switch (state.unicodeState) {
3036 case LocaleParserState::NUMBERING_SYSTEM:
3037 /* Accept only the first occurrence of the numbering system. */
3038 if (config->localeNumberingSystem[0] == '\0') {
3039 for (size_t i = 0; i < size; ++i) {
3040 config->localeNumberingSystem[i] = tolower(start[i]);
3041 }
3042 state.unicodeState = LocaleParserState::EXPECT_KEY;
3043 } else {
3044 state.parserState = LocaleParserState::IGNORE_THE_REST;
3045 }
3046 break;
3047 case LocaleParserState::IGNORE_KEY:
3048 /* Unsupported Unicode keyword. Ignore. */
3049 state.unicodeState = LocaleParserState::EXPECT_KEY;
3050 break;
3051 case LocaleParserState::EXPECT_KEY:
3052 /* A keyword followed by an attribute is not allowed. */
3053 state.parserState = LocaleParserState::IGNORE_THE_REST;
3054 break;
3055 case LocaleParserState::NO_KEY:
3056 /* Extension attribute. Do nothing. */
3057 break;
3058 default:
3059 break;
3060 }
3061 break;
3062 default:
3063 /* Unexpected field length - ignore the rest and treat as an error */
3064 state.parserState = LocaleParserState::IGNORE_THE_REST;
3065 }
3066 return state;
3067 }
3068
3069 switch (size) {
3070 case 0:
3071 state.parserState = LocaleParserState::IGNORE_THE_REST;
3072 break;
3073 case 1:
3074 state.parserState = (start[0] == 'u' || start[0] == 'U')
3075 ? LocaleParserState::UNICODE_EXTENSION
3076 : LocaleParserState::IGNORE_THE_REST;
3077 break;
3078 case 2:
3079 case 3:
3080 config->language[0] ? config->packRegion(start) : config->packLanguage(start);
3081 break;
3082 case 4:
3083 if ('0' <= start[0] && start[0] <= '9') {
3084 // this is a variant, so fall through
3085 } else {
3086 config->localeScript[0] = toupper(start[0]);
3087 for (size_t i = 1; i < 4; ++i) {
3088 config->localeScript[i] = tolower(start[i]);
3089 }
3090 break;
3091 }
3092 FALLTHROUGH_INTENDED;
3093 case 5:
3094 case 6:
3095 case 7:
3096 case 8:
3097 for (size_t i = 0; i < size; ++i) {
3098 config->localeVariant[i] = tolower(start[i]);
3099 }
3100 break;
3101 default:
3102 state.parserState = LocaleParserState::IGNORE_THE_REST;
3103 }
3104
3105 return state;
3106 }
3107
setBcp47Locale(const char * in)3108 void ResTable_config::setBcp47Locale(const char* in) {
3109 clearLocale();
3110
3111 const char* start = in;
3112 LocaleParserState state;
3113 while (const char* separator = strchr(start, '-')) {
3114 const size_t size = separator - start;
3115 state = assignLocaleComponent(this, start, size, state);
3116 if (state.parserState == LocaleParserState::IGNORE_THE_REST) {
3117 fprintf(stderr, "Invalid BCP-47 locale string: %s\n", in);
3118 break;
3119 }
3120 start = (separator + 1);
3121 }
3122
3123 if (state.parserState != LocaleParserState::IGNORE_THE_REST) {
3124 const size_t size = strlen(start);
3125 assignLocaleComponent(this, start, size, state);
3126 }
3127
3128 localeScriptWasComputed = (localeScript[0] == '\0');
3129 if (localeScriptWasComputed) {
3130 computeScript();
3131 }
3132 }
3133
toString() const3134 String8 ResTable_config::toString() const {
3135 String8 res;
3136
3137 if (mcc != 0) {
3138 if (res.size() > 0) res.append("-");
3139 res.appendFormat("mcc%d", dtohs(mcc));
3140 }
3141 if (mnc != 0) {
3142 if (res.size() > 0) res.append("-");
3143 res.appendFormat("mnc%d", dtohs(mnc));
3144 }
3145
3146 appendDirLocale(res);
3147
3148 if ((screenLayout&MASK_LAYOUTDIR) != 0) {
3149 if (res.size() > 0) res.append("-");
3150 switch (screenLayout&ResTable_config::MASK_LAYOUTDIR) {
3151 case ResTable_config::LAYOUTDIR_LTR:
3152 res.append("ldltr");
3153 break;
3154 case ResTable_config::LAYOUTDIR_RTL:
3155 res.append("ldrtl");
3156 break;
3157 default:
3158 res.appendFormat("layoutDir=%d",
3159 dtohs(screenLayout&ResTable_config::MASK_LAYOUTDIR));
3160 break;
3161 }
3162 }
3163 if (smallestScreenWidthDp != 0) {
3164 if (res.size() > 0) res.append("-");
3165 res.appendFormat("sw%ddp", dtohs(smallestScreenWidthDp));
3166 }
3167 if (screenWidthDp != 0) {
3168 if (res.size() > 0) res.append("-");
3169 res.appendFormat("w%ddp", dtohs(screenWidthDp));
3170 }
3171 if (screenHeightDp != 0) {
3172 if (res.size() > 0) res.append("-");
3173 res.appendFormat("h%ddp", dtohs(screenHeightDp));
3174 }
3175 if ((screenLayout&MASK_SCREENSIZE) != SCREENSIZE_ANY) {
3176 if (res.size() > 0) res.append("-");
3177 switch (screenLayout&ResTable_config::MASK_SCREENSIZE) {
3178 case ResTable_config::SCREENSIZE_SMALL:
3179 res.append("small");
3180 break;
3181 case ResTable_config::SCREENSIZE_NORMAL:
3182 res.append("normal");
3183 break;
3184 case ResTable_config::SCREENSIZE_LARGE:
3185 res.append("large");
3186 break;
3187 case ResTable_config::SCREENSIZE_XLARGE:
3188 res.append("xlarge");
3189 break;
3190 default:
3191 res.appendFormat("screenLayoutSize=%d",
3192 dtohs(screenLayout&ResTable_config::MASK_SCREENSIZE));
3193 break;
3194 }
3195 }
3196 if ((screenLayout&MASK_SCREENLONG) != 0) {
3197 if (res.size() > 0) res.append("-");
3198 switch (screenLayout&ResTable_config::MASK_SCREENLONG) {
3199 case ResTable_config::SCREENLONG_NO:
3200 res.append("notlong");
3201 break;
3202 case ResTable_config::SCREENLONG_YES:
3203 res.append("long");
3204 break;
3205 default:
3206 res.appendFormat("screenLayoutLong=%d",
3207 dtohs(screenLayout&ResTable_config::MASK_SCREENLONG));
3208 break;
3209 }
3210 }
3211 if ((screenLayout2&MASK_SCREENROUND) != 0) {
3212 if (res.size() > 0) res.append("-");
3213 switch (screenLayout2&MASK_SCREENROUND) {
3214 case SCREENROUND_NO:
3215 res.append("notround");
3216 break;
3217 case SCREENROUND_YES:
3218 res.append("round");
3219 break;
3220 default:
3221 res.appendFormat("screenRound=%d", dtohs(screenLayout2&MASK_SCREENROUND));
3222 break;
3223 }
3224 }
3225 if ((colorMode&MASK_WIDE_COLOR_GAMUT) != 0) {
3226 if (res.size() > 0) res.append("-");
3227 switch (colorMode&MASK_WIDE_COLOR_GAMUT) {
3228 case ResTable_config::WIDE_COLOR_GAMUT_NO:
3229 res.append("nowidecg");
3230 break;
3231 case ResTable_config::WIDE_COLOR_GAMUT_YES:
3232 res.append("widecg");
3233 break;
3234 default:
3235 res.appendFormat("wideColorGamut=%d", dtohs(colorMode&MASK_WIDE_COLOR_GAMUT));
3236 break;
3237 }
3238 }
3239 if ((colorMode&MASK_HDR) != 0) {
3240 if (res.size() > 0) res.append("-");
3241 switch (colorMode&MASK_HDR) {
3242 case ResTable_config::HDR_NO:
3243 res.append("lowdr");
3244 break;
3245 case ResTable_config::HDR_YES:
3246 res.append("highdr");
3247 break;
3248 default:
3249 res.appendFormat("hdr=%d", dtohs(colorMode&MASK_HDR));
3250 break;
3251 }
3252 }
3253 if (orientation != ORIENTATION_ANY) {
3254 if (res.size() > 0) res.append("-");
3255 switch (orientation) {
3256 case ResTable_config::ORIENTATION_PORT:
3257 res.append("port");
3258 break;
3259 case ResTable_config::ORIENTATION_LAND:
3260 res.append("land");
3261 break;
3262 case ResTable_config::ORIENTATION_SQUARE:
3263 res.append("square");
3264 break;
3265 default:
3266 res.appendFormat("orientation=%d", dtohs(orientation));
3267 break;
3268 }
3269 }
3270 if ((uiMode&MASK_UI_MODE_TYPE) != UI_MODE_TYPE_ANY) {
3271 if (res.size() > 0) res.append("-");
3272 switch (uiMode&ResTable_config::MASK_UI_MODE_TYPE) {
3273 case ResTable_config::UI_MODE_TYPE_DESK:
3274 res.append("desk");
3275 break;
3276 case ResTable_config::UI_MODE_TYPE_CAR:
3277 res.append("car");
3278 break;
3279 case ResTable_config::UI_MODE_TYPE_TELEVISION:
3280 res.append("television");
3281 break;
3282 case ResTable_config::UI_MODE_TYPE_APPLIANCE:
3283 res.append("appliance");
3284 break;
3285 case ResTable_config::UI_MODE_TYPE_WATCH:
3286 res.append("watch");
3287 break;
3288 case ResTable_config::UI_MODE_TYPE_VR_HEADSET:
3289 res.append("vrheadset");
3290 break;
3291 default:
3292 res.appendFormat("uiModeType=%d",
3293 dtohs(screenLayout&ResTable_config::MASK_UI_MODE_TYPE));
3294 break;
3295 }
3296 }
3297 if ((uiMode&MASK_UI_MODE_NIGHT) != 0) {
3298 if (res.size() > 0) res.append("-");
3299 switch (uiMode&ResTable_config::MASK_UI_MODE_NIGHT) {
3300 case ResTable_config::UI_MODE_NIGHT_NO:
3301 res.append("notnight");
3302 break;
3303 case ResTable_config::UI_MODE_NIGHT_YES:
3304 res.append("night");
3305 break;
3306 default:
3307 res.appendFormat("uiModeNight=%d",
3308 dtohs(uiMode&MASK_UI_MODE_NIGHT));
3309 break;
3310 }
3311 }
3312 if (density != DENSITY_DEFAULT) {
3313 if (res.size() > 0) res.append("-");
3314 switch (density) {
3315 case ResTable_config::DENSITY_LOW:
3316 res.append("ldpi");
3317 break;
3318 case ResTable_config::DENSITY_MEDIUM:
3319 res.append("mdpi");
3320 break;
3321 case ResTable_config::DENSITY_TV:
3322 res.append("tvdpi");
3323 break;
3324 case ResTable_config::DENSITY_HIGH:
3325 res.append("hdpi");
3326 break;
3327 case ResTable_config::DENSITY_XHIGH:
3328 res.append("xhdpi");
3329 break;
3330 case ResTable_config::DENSITY_XXHIGH:
3331 res.append("xxhdpi");
3332 break;
3333 case ResTable_config::DENSITY_XXXHIGH:
3334 res.append("xxxhdpi");
3335 break;
3336 case ResTable_config::DENSITY_NONE:
3337 res.append("nodpi");
3338 break;
3339 case ResTable_config::DENSITY_ANY:
3340 res.append("anydpi");
3341 break;
3342 default:
3343 res.appendFormat("%ddpi", dtohs(density));
3344 break;
3345 }
3346 }
3347 if (touchscreen != TOUCHSCREEN_ANY) {
3348 if (res.size() > 0) res.append("-");
3349 switch (touchscreen) {
3350 case ResTable_config::TOUCHSCREEN_NOTOUCH:
3351 res.append("notouch");
3352 break;
3353 case ResTable_config::TOUCHSCREEN_FINGER:
3354 res.append("finger");
3355 break;
3356 case ResTable_config::TOUCHSCREEN_STYLUS:
3357 res.append("stylus");
3358 break;
3359 default:
3360 res.appendFormat("touchscreen=%d", dtohs(touchscreen));
3361 break;
3362 }
3363 }
3364 if ((inputFlags&MASK_KEYSHIDDEN) != 0) {
3365 if (res.size() > 0) res.append("-");
3366 switch (inputFlags&MASK_KEYSHIDDEN) {
3367 case ResTable_config::KEYSHIDDEN_NO:
3368 res.append("keysexposed");
3369 break;
3370 case ResTable_config::KEYSHIDDEN_YES:
3371 res.append("keyshidden");
3372 break;
3373 case ResTable_config::KEYSHIDDEN_SOFT:
3374 res.append("keyssoft");
3375 break;
3376 }
3377 }
3378 if (keyboard != KEYBOARD_ANY) {
3379 if (res.size() > 0) res.append("-");
3380 switch (keyboard) {
3381 case ResTable_config::KEYBOARD_NOKEYS:
3382 res.append("nokeys");
3383 break;
3384 case ResTable_config::KEYBOARD_QWERTY:
3385 res.append("qwerty");
3386 break;
3387 case ResTable_config::KEYBOARD_12KEY:
3388 res.append("12key");
3389 break;
3390 default:
3391 res.appendFormat("keyboard=%d", dtohs(keyboard));
3392 break;
3393 }
3394 }
3395 if ((inputFlags&MASK_NAVHIDDEN) != 0) {
3396 if (res.size() > 0) res.append("-");
3397 switch (inputFlags&MASK_NAVHIDDEN) {
3398 case ResTable_config::NAVHIDDEN_NO:
3399 res.append("navexposed");
3400 break;
3401 case ResTable_config::NAVHIDDEN_YES:
3402 res.append("navhidden");
3403 break;
3404 default:
3405 res.appendFormat("inputFlagsNavHidden=%d",
3406 dtohs(inputFlags&MASK_NAVHIDDEN));
3407 break;
3408 }
3409 }
3410 if (navigation != NAVIGATION_ANY) {
3411 if (res.size() > 0) res.append("-");
3412 switch (navigation) {
3413 case ResTable_config::NAVIGATION_NONAV:
3414 res.append("nonav");
3415 break;
3416 case ResTable_config::NAVIGATION_DPAD:
3417 res.append("dpad");
3418 break;
3419 case ResTable_config::NAVIGATION_TRACKBALL:
3420 res.append("trackball");
3421 break;
3422 case ResTable_config::NAVIGATION_WHEEL:
3423 res.append("wheel");
3424 break;
3425 default:
3426 res.appendFormat("navigation=%d", dtohs(navigation));
3427 break;
3428 }
3429 }
3430 if (screenSize != 0) {
3431 if (res.size() > 0) res.append("-");
3432 res.appendFormat("%dx%d", dtohs(screenWidth), dtohs(screenHeight));
3433 }
3434 if (version != 0) {
3435 if (res.size() > 0) res.append("-");
3436 res.appendFormat("v%d", dtohs(sdkVersion));
3437 if (minorVersion != 0) {
3438 res.appendFormat(".%d", dtohs(minorVersion));
3439 }
3440 }
3441
3442 return res;
3443 }
3444
3445 // --------------------------------------------------------------------
3446 // --------------------------------------------------------------------
3447 // --------------------------------------------------------------------
3448
3449 struct ResTable::Header
3450 {
Headerandroid::ResTable::Header3451 explicit Header(ResTable* _owner) : owner(_owner), ownedData(NULL), header(NULL),
3452 resourceIDMap(NULL), resourceIDMapSize(0) { }
3453
~Headerandroid::ResTable::Header3454 ~Header()
3455 {
3456 free(resourceIDMap);
3457 }
3458
3459 const ResTable* const owner;
3460 void* ownedData;
3461 const ResTable_header* header;
3462 size_t size;
3463 const uint8_t* dataEnd;
3464 size_t index;
3465 int32_t cookie;
3466
3467 ResStringPool values;
3468 uint32_t* resourceIDMap;
3469 size_t resourceIDMapSize;
3470 };
3471
3472 struct ResTable::Entry {
3473 ResTable_config config;
3474 const ResTable_entry* entry;
3475 const ResTable_type* type;
3476 uint32_t specFlags;
3477 const Package* package;
3478
3479 StringPoolRef typeStr;
3480 StringPoolRef keyStr;
3481 };
3482
3483 struct ResTable::Type
3484 {
Typeandroid::ResTable::Type3485 Type(const Header* _header, const Package* _package, size_t count)
3486 : header(_header), package(_package), entryCount(count),
3487 typeSpec(NULL), typeSpecFlags(NULL) { }
3488 const Header* const header;
3489 const Package* const package;
3490 const size_t entryCount;
3491 const ResTable_typeSpec* typeSpec;
3492 const uint32_t* typeSpecFlags;
3493 IdmapEntries idmapEntries;
3494 Vector<const ResTable_type*> configs;
3495 };
3496
3497 struct ResTable::Package
3498 {
Packageandroid::ResTable::Package3499 Package(ResTable* _owner, const Header* _header, const ResTable_package* _package)
3500 : owner(_owner), header(_header), package(_package), typeIdOffset(0) {
3501 if (dtohs(package->header.headerSize) == sizeof(*package)) {
3502 // The package structure is the same size as the definition.
3503 // This means it contains the typeIdOffset field.
3504 typeIdOffset = package->typeIdOffset;
3505 }
3506 }
3507
3508 const ResTable* const owner;
3509 const Header* const header;
3510 const ResTable_package* const package;
3511
3512 ResStringPool typeStrings;
3513 ResStringPool keyStrings;
3514
3515 size_t typeIdOffset;
3516 bool definesOverlayable = false;
3517 };
3518
3519 // A group of objects describing a particular resource package.
3520 // The first in 'package' is always the root object (from the resource
3521 // table that defined the package); the ones after are skins on top of it.
3522 struct ResTable::PackageGroup
3523 {
PackageGroupandroid::ResTable::PackageGroup3524 PackageGroup(
3525 ResTable* _owner, const String16& _name, uint32_t _id,
3526 bool appAsLib, bool _isSystemAsset, bool _isDynamic)
3527 : owner(_owner)
3528 , name(_name)
3529 , id(_id)
3530 , largestTypeId(0)
3531 , dynamicRefTable(static_cast<uint8_t>(_id), appAsLib)
3532 , isSystemAsset(_isSystemAsset)
3533 , isDynamic(_isDynamic)
3534 { }
3535
~PackageGroupandroid::ResTable::PackageGroup3536 ~PackageGroup() {
3537 clearBagCache();
3538 const size_t numTypes = types.size();
3539 for (size_t i = 0; i < numTypes; i++) {
3540 TypeList& typeList = types.editItemAt(i);
3541 const size_t numInnerTypes = typeList.size();
3542 for (size_t j = 0; j < numInnerTypes; j++) {
3543 if (typeList[j]->package->owner == owner) {
3544 delete typeList[j];
3545 }
3546 }
3547 typeList.clear();
3548 }
3549
3550 const size_t N = packages.size();
3551 for (size_t i=0; i<N; i++) {
3552 Package* pkg = packages[i];
3553 if (pkg->owner == owner) {
3554 delete pkg;
3555 }
3556 }
3557 }
3558
3559 /**
3560 * Clear all cache related data that depends on parameters/configuration.
3561 * This includes the bag caches and filtered types.
3562 */
clearBagCacheandroid::ResTable::PackageGroup3563 void clearBagCache() {
3564 for (size_t i = 0; i < typeCacheEntries.size(); i++) {
3565 if (kDebugTableNoisy) {
3566 printf("type=%zu\n", i);
3567 }
3568 const TypeList& typeList = types[i];
3569 if (!typeList.isEmpty()) {
3570 TypeCacheEntry& cacheEntry = typeCacheEntries.editItemAt(i);
3571
3572 // Reset the filtered configurations.
3573 cacheEntry.filteredConfigs.clear();
3574
3575 bag_set** typeBags = cacheEntry.cachedBags;
3576 if (kDebugTableNoisy) {
3577 printf("typeBags=%p\n", typeBags);
3578 }
3579
3580 if (typeBags) {
3581 const size_t N = typeList[0]->entryCount;
3582 if (kDebugTableNoisy) {
3583 printf("type->entryCount=%zu\n", N);
3584 }
3585 for (size_t j = 0; j < N; j++) {
3586 if (typeBags[j] && typeBags[j] != (bag_set*)0xFFFFFFFF) {
3587 free(typeBags[j]);
3588 }
3589 }
3590 free(typeBags);
3591 cacheEntry.cachedBags = NULL;
3592 }
3593 }
3594 }
3595 }
3596
findType16android::ResTable::PackageGroup3597 ssize_t findType16(const char16_t* type, size_t len) const {
3598 const size_t N = packages.size();
3599 for (size_t i = 0; i < N; i++) {
3600 ssize_t index = packages[i]->typeStrings.indexOfString(type, len);
3601 if (index >= 0) {
3602 return index + packages[i]->typeIdOffset;
3603 }
3604 }
3605 return -1;
3606 }
3607
3608 const ResTable* const owner;
3609 String16 const name;
3610 uint32_t const id;
3611
3612 // This is mainly used to keep track of the loaded packages
3613 // and to clean them up properly. Accessing resources happens from
3614 // the 'types' array.
3615 Vector<Package*> packages;
3616
3617 ByteBucketArray<TypeList> types;
3618
3619 uint8_t largestTypeId;
3620
3621 // Cached objects dependent on the parameters/configuration of this ResTable.
3622 // Gets cleared whenever the parameters/configuration changes.
3623 // These are stored here in a parallel structure because the data in `types` may
3624 // be shared by other ResTable's (framework resources are shared this way).
3625 ByteBucketArray<TypeCacheEntry> typeCacheEntries;
3626
3627 // The table mapping dynamic references to resolved references for
3628 // this package group.
3629 // TODO: We may be able to support dynamic references in overlays
3630 // by having these tables in a per-package scope rather than
3631 // per-package-group.
3632 DynamicRefTable dynamicRefTable;
3633
3634 // If the package group comes from a system asset. Used in
3635 // determining non-system locales.
3636 const bool isSystemAsset;
3637 const bool isDynamic;
3638 };
3639
Theme(const ResTable & table)3640 ResTable::Theme::Theme(const ResTable& table)
3641 : mTable(table)
3642 , mTypeSpecFlags(0)
3643 {
3644 memset(mPackages, 0, sizeof(mPackages));
3645 }
3646
~Theme()3647 ResTable::Theme::~Theme()
3648 {
3649 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3650 package_info* pi = mPackages[i];
3651 if (pi != NULL) {
3652 free_package(pi);
3653 }
3654 }
3655 }
3656
free_package(package_info * pi)3657 void ResTable::Theme::free_package(package_info* pi)
3658 {
3659 for (size_t j = 0; j <= Res_MAXTYPE; j++) {
3660 theme_entry* te = pi->types[j].entries;
3661 if (te != NULL) {
3662 free(te);
3663 }
3664 }
3665 free(pi);
3666 }
3667
copy_package(package_info * pi)3668 ResTable::Theme::package_info* ResTable::Theme::copy_package(package_info* pi)
3669 {
3670 package_info* newpi = (package_info*)malloc(sizeof(package_info));
3671 for (size_t j = 0; j <= Res_MAXTYPE; j++) {
3672 size_t cnt = pi->types[j].numEntries;
3673 newpi->types[j].numEntries = cnt;
3674 theme_entry* te = pi->types[j].entries;
3675 size_t cnt_max = SIZE_MAX / sizeof(theme_entry);
3676 if (te != NULL && (cnt < 0xFFFFFFFF-1) && (cnt < cnt_max)) {
3677 theme_entry* newte = (theme_entry*)malloc(cnt*sizeof(theme_entry));
3678 newpi->types[j].entries = newte;
3679 memcpy(newte, te, cnt*sizeof(theme_entry));
3680 } else {
3681 newpi->types[j].entries = NULL;
3682 }
3683 }
3684 return newpi;
3685 }
3686
applyStyle(uint32_t resID,bool force)3687 status_t ResTable::Theme::applyStyle(uint32_t resID, bool force)
3688 {
3689 const bag_entry* bag;
3690 uint32_t bagTypeSpecFlags = 0;
3691 mTable.lock();
3692 const ssize_t N = mTable.getBagLocked(resID, &bag, &bagTypeSpecFlags);
3693 if (kDebugTableNoisy) {
3694 ALOGV("Applying style 0x%08x to theme %p, count=%zu", resID, this, N);
3695 }
3696 if (N < 0) {
3697 mTable.unlock();
3698 return N;
3699 }
3700
3701 mTypeSpecFlags |= bagTypeSpecFlags;
3702
3703 uint32_t curPackage = 0xffffffff;
3704 ssize_t curPackageIndex = 0;
3705 package_info* curPI = NULL;
3706 uint32_t curType = 0xffffffff;
3707 size_t numEntries = 0;
3708 theme_entry* curEntries = NULL;
3709
3710 const bag_entry* end = bag + N;
3711 while (bag < end) {
3712 const uint32_t attrRes = bag->map.name.ident;
3713 const uint32_t p = Res_GETPACKAGE(attrRes);
3714 const uint32_t t = Res_GETTYPE(attrRes);
3715 const uint32_t e = Res_GETENTRY(attrRes);
3716
3717 if (curPackage != p) {
3718 const ssize_t pidx = mTable.getResourcePackageIndex(attrRes);
3719 if (pidx < 0) {
3720 ALOGE("Style contains key with bad package: 0x%08x\n", attrRes);
3721 bag++;
3722 continue;
3723 }
3724 curPackage = p;
3725 curPackageIndex = pidx;
3726 curPI = mPackages[pidx];
3727 if (curPI == NULL) {
3728 curPI = (package_info*)malloc(sizeof(package_info));
3729 memset(curPI, 0, sizeof(*curPI));
3730 mPackages[pidx] = curPI;
3731 }
3732 curType = 0xffffffff;
3733 }
3734 if (curType != t) {
3735 if (t > Res_MAXTYPE) {
3736 ALOGE("Style contains key with bad type: 0x%08x\n", attrRes);
3737 bag++;
3738 continue;
3739 }
3740 curType = t;
3741 curEntries = curPI->types[t].entries;
3742 if (curEntries == NULL) {
3743 PackageGroup* const grp = mTable.mPackageGroups[curPackageIndex];
3744 const TypeList& typeList = grp->types[t];
3745 size_t cnt = typeList.isEmpty() ? 0 : typeList[0]->entryCount;
3746 size_t cnt_max = SIZE_MAX / sizeof(theme_entry);
3747 size_t buff_size = (cnt < cnt_max && cnt < 0xFFFFFFFF-1) ?
3748 cnt*sizeof(theme_entry) : 0;
3749 curEntries = (theme_entry*)malloc(buff_size);
3750 memset(curEntries, Res_value::TYPE_NULL, buff_size);
3751 curPI->types[t].numEntries = cnt;
3752 curPI->types[t].entries = curEntries;
3753 }
3754 numEntries = curPI->types[t].numEntries;
3755 }
3756 if (e >= numEntries) {
3757 ALOGE("Style contains key with bad entry: 0x%08x\n", attrRes);
3758 bag++;
3759 continue;
3760 }
3761 theme_entry* curEntry = curEntries + e;
3762 if (kDebugTableNoisy) {
3763 ALOGV("Attr 0x%08x: type=0x%x, data=0x%08x; curType=0x%x",
3764 attrRes, bag->map.value.dataType, bag->map.value.data,
3765 curEntry->value.dataType);
3766 }
3767 if (force || (curEntry->value.dataType == Res_value::TYPE_NULL
3768 && curEntry->value.data != Res_value::DATA_NULL_EMPTY)) {
3769 curEntry->stringBlock = bag->stringBlock;
3770 curEntry->typeSpecFlags |= bagTypeSpecFlags;
3771 curEntry->value = bag->map.value;
3772 }
3773
3774 bag++;
3775 }
3776
3777 mTable.unlock();
3778
3779 if (kDebugTableTheme) {
3780 ALOGI("Applying style 0x%08x (force=%d) theme %p...\n", resID, force, this);
3781 dumpToLog();
3782 }
3783
3784 return NO_ERROR;
3785 }
3786
setTo(const Theme & other)3787 status_t ResTable::Theme::setTo(const Theme& other)
3788 {
3789 if (kDebugTableTheme) {
3790 ALOGI("Setting theme %p from theme %p...\n", this, &other);
3791 dumpToLog();
3792 other.dumpToLog();
3793 }
3794
3795 if (&mTable == &other.mTable) {
3796 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3797 if (mPackages[i] != NULL) {
3798 free_package(mPackages[i]);
3799 }
3800 if (other.mPackages[i] != NULL) {
3801 mPackages[i] = copy_package(other.mPackages[i]);
3802 } else {
3803 mPackages[i] = NULL;
3804 }
3805 }
3806 } else {
3807 // @todo: need to really implement this, not just copy
3808 // the system package (which is still wrong because it isn't
3809 // fixing up resource references).
3810 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3811 if (mPackages[i] != NULL) {
3812 free_package(mPackages[i]);
3813 }
3814 if (i == 0 && other.mPackages[i] != NULL) {
3815 mPackages[i] = copy_package(other.mPackages[i]);
3816 } else {
3817 mPackages[i] = NULL;
3818 }
3819 }
3820 }
3821
3822 mTypeSpecFlags = other.mTypeSpecFlags;
3823
3824 if (kDebugTableTheme) {
3825 ALOGI("Final theme:");
3826 dumpToLog();
3827 }
3828
3829 return NO_ERROR;
3830 }
3831
clear()3832 status_t ResTable::Theme::clear()
3833 {
3834 if (kDebugTableTheme) {
3835 ALOGI("Clearing theme %p...\n", this);
3836 dumpToLog();
3837 }
3838
3839 for (size_t i = 0; i < Res_MAXPACKAGE; i++) {
3840 if (mPackages[i] != NULL) {
3841 free_package(mPackages[i]);
3842 mPackages[i] = NULL;
3843 }
3844 }
3845
3846 mTypeSpecFlags = 0;
3847
3848 if (kDebugTableTheme) {
3849 ALOGI("Final theme:");
3850 dumpToLog();
3851 }
3852
3853 return NO_ERROR;
3854 }
3855
getAttribute(uint32_t resID,Res_value * outValue,uint32_t * outTypeSpecFlags) const3856 ssize_t ResTable::Theme::getAttribute(uint32_t resID, Res_value* outValue,
3857 uint32_t* outTypeSpecFlags) const
3858 {
3859 int cnt = 20;
3860
3861 if (outTypeSpecFlags != NULL) *outTypeSpecFlags = 0;
3862
3863 do {
3864 const ssize_t p = mTable.getResourcePackageIndex(resID);
3865 const uint32_t t = Res_GETTYPE(resID);
3866 const uint32_t e = Res_GETENTRY(resID);
3867
3868 if (kDebugTableTheme) {
3869 ALOGI("Looking up attr 0x%08x in theme %p", resID, this);
3870 }
3871
3872 if (p >= 0) {
3873 const package_info* const pi = mPackages[p];
3874 if (kDebugTableTheme) {
3875 ALOGI("Found package: %p", pi);
3876 }
3877 if (pi != NULL) {
3878 if (kDebugTableTheme) {
3879 ALOGI("Desired type index is %u in avail %zu", t, Res_MAXTYPE + 1);
3880 }
3881 if (t <= Res_MAXTYPE) {
3882 const type_info& ti = pi->types[t];
3883 if (kDebugTableTheme) {
3884 ALOGI("Desired entry index is %u in avail %zu", e, ti.numEntries);
3885 }
3886 if (e < ti.numEntries) {
3887 const theme_entry& te = ti.entries[e];
3888 if (outTypeSpecFlags != NULL) {
3889 *outTypeSpecFlags |= te.typeSpecFlags;
3890 }
3891 if (kDebugTableTheme) {
3892 ALOGI("Theme value: type=0x%x, data=0x%08x",
3893 te.value.dataType, te.value.data);
3894 }
3895 const uint8_t type = te.value.dataType;
3896 if (type == Res_value::TYPE_ATTRIBUTE) {
3897 if (cnt > 0) {
3898 cnt--;
3899 resID = te.value.data;
3900 continue;
3901 }
3902 ALOGW("Too many attribute references, stopped at: 0x%08x\n", resID);
3903 return BAD_INDEX;
3904 } else if (type != Res_value::TYPE_NULL
3905 || te.value.data == Res_value::DATA_NULL_EMPTY) {
3906 *outValue = te.value;
3907 return te.stringBlock;
3908 }
3909 return BAD_INDEX;
3910 }
3911 }
3912 }
3913 }
3914 break;
3915
3916 } while (true);
3917
3918 return BAD_INDEX;
3919 }
3920
resolveAttributeReference(Res_value * inOutValue,ssize_t blockIndex,uint32_t * outLastRef,uint32_t * inoutTypeSpecFlags,ResTable_config * inoutConfig) const3921 ssize_t ResTable::Theme::resolveAttributeReference(Res_value* inOutValue,
3922 ssize_t blockIndex, uint32_t* outLastRef,
3923 uint32_t* inoutTypeSpecFlags, ResTable_config* inoutConfig) const
3924 {
3925 //printf("Resolving type=0x%x\n", inOutValue->dataType);
3926 if (inOutValue->dataType == Res_value::TYPE_ATTRIBUTE) {
3927 uint32_t newTypeSpecFlags;
3928 blockIndex = getAttribute(inOutValue->data, inOutValue, &newTypeSpecFlags);
3929 if (kDebugTableTheme) {
3930 ALOGI("Resolving attr reference: blockIndex=%d, type=0x%x, data=0x%x\n",
3931 (int)blockIndex, (int)inOutValue->dataType, inOutValue->data);
3932 }
3933 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newTypeSpecFlags;
3934 //printf("Retrieved attribute new type=0x%x\n", inOutValue->dataType);
3935 if (blockIndex < 0) {
3936 return blockIndex;
3937 }
3938 }
3939 return mTable.resolveReference(inOutValue, blockIndex, outLastRef,
3940 inoutTypeSpecFlags, inoutConfig);
3941 }
3942
getChangingConfigurations() const3943 uint32_t ResTable::Theme::getChangingConfigurations() const
3944 {
3945 return mTypeSpecFlags;
3946 }
3947
dumpToLog() const3948 void ResTable::Theme::dumpToLog() const
3949 {
3950 ALOGI("Theme %p:\n", this);
3951 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3952 package_info* pi = mPackages[i];
3953 if (pi == NULL) continue;
3954
3955 ALOGI(" Package #0x%02x:\n", (int)(i + 1));
3956 for (size_t j = 0; j <= Res_MAXTYPE; j++) {
3957 type_info& ti = pi->types[j];
3958 if (ti.numEntries == 0) continue;
3959 ALOGI(" Type #0x%02x:\n", (int)(j + 1));
3960 for (size_t k = 0; k < ti.numEntries; k++) {
3961 const theme_entry& te = ti.entries[k];
3962 if (te.value.dataType == Res_value::TYPE_NULL) continue;
3963 ALOGI(" 0x%08x: t=0x%x, d=0x%08x (block=%d)\n",
3964 (int)Res_MAKEID(i, j, k),
3965 te.value.dataType, (int)te.value.data, (int)te.stringBlock);
3966 }
3967 }
3968 }
3969 }
3970
ResTable()3971 ResTable::ResTable()
3972 : mError(NO_INIT), mNextPackageId(2)
3973 {
3974 memset(&mParams, 0, sizeof(mParams));
3975 memset(mPackageMap, 0, sizeof(mPackageMap));
3976 if (kDebugTableSuperNoisy) {
3977 ALOGI("Creating ResTable %p\n", this);
3978 }
3979 }
3980
ResTable(const void * data,size_t size,const int32_t cookie,bool copyData)3981 ResTable::ResTable(const void* data, size_t size, const int32_t cookie, bool copyData)
3982 : mError(NO_INIT), mNextPackageId(2)
3983 {
3984 memset(&mParams, 0, sizeof(mParams));
3985 memset(mPackageMap, 0, sizeof(mPackageMap));
3986 addInternal(data, size, NULL, 0, false, cookie, copyData);
3987 LOG_FATAL_IF(mError != NO_ERROR, "Error parsing resource table");
3988 if (kDebugTableSuperNoisy) {
3989 ALOGI("Creating ResTable %p\n", this);
3990 }
3991 }
3992
~ResTable()3993 ResTable::~ResTable()
3994 {
3995 if (kDebugTableSuperNoisy) {
3996 ALOGI("Destroying ResTable in %p\n", this);
3997 }
3998 uninit();
3999 }
4000
getResourcePackageIndex(uint32_t resID) const4001 inline ssize_t ResTable::getResourcePackageIndex(uint32_t resID) const
4002 {
4003 return ((ssize_t)mPackageMap[Res_GETPACKAGE(resID)+1])-1;
4004 }
4005
getResourcePackageIndexFromPackage(uint8_t packageID) const4006 inline ssize_t ResTable::getResourcePackageIndexFromPackage(uint8_t packageID) const
4007 {
4008 return ((ssize_t)mPackageMap[packageID])-1;
4009 }
4010
add(const void * data,size_t size,const int32_t cookie,bool copyData)4011 status_t ResTable::add(const void* data, size_t size, const int32_t cookie, bool copyData) {
4012 return addInternal(data, size, NULL, 0, false, cookie, copyData);
4013 }
4014
add(const void * data,size_t size,const void * idmapData,size_t idmapDataSize,const int32_t cookie,bool copyData,bool appAsLib)4015 status_t ResTable::add(const void* data, size_t size, const void* idmapData, size_t idmapDataSize,
4016 const int32_t cookie, bool copyData, bool appAsLib) {
4017 return addInternal(data, size, idmapData, idmapDataSize, appAsLib, cookie, copyData);
4018 }
4019
add(Asset * asset,const int32_t cookie,bool copyData)4020 status_t ResTable::add(Asset* asset, const int32_t cookie, bool copyData) {
4021 const void* data = asset->getBuffer(true);
4022 if (data == NULL) {
4023 ALOGW("Unable to get buffer of resource asset file");
4024 return UNKNOWN_ERROR;
4025 }
4026
4027 return addInternal(data, static_cast<size_t>(asset->getLength()), NULL, false, 0, cookie,
4028 copyData);
4029 }
4030
add(Asset * asset,Asset * idmapAsset,const int32_t cookie,bool copyData,bool appAsLib,bool isSystemAsset)4031 status_t ResTable::add(
4032 Asset* asset, Asset* idmapAsset, const int32_t cookie, bool copyData,
4033 bool appAsLib, bool isSystemAsset) {
4034 const void* data = asset->getBuffer(true);
4035 if (data == NULL) {
4036 ALOGW("Unable to get buffer of resource asset file");
4037 return UNKNOWN_ERROR;
4038 }
4039
4040 size_t idmapSize = 0;
4041 const void* idmapData = NULL;
4042 if (idmapAsset != NULL) {
4043 idmapData = idmapAsset->getBuffer(true);
4044 if (idmapData == NULL) {
4045 ALOGW("Unable to get buffer of idmap asset file");
4046 return UNKNOWN_ERROR;
4047 }
4048 idmapSize = static_cast<size_t>(idmapAsset->getLength());
4049 }
4050
4051 return addInternal(data, static_cast<size_t>(asset->getLength()),
4052 idmapData, idmapSize, appAsLib, cookie, copyData, isSystemAsset);
4053 }
4054
add(ResTable * src,bool isSystemAsset)4055 status_t ResTable::add(ResTable* src, bool isSystemAsset)
4056 {
4057 mError = src->mError;
4058
4059 for (size_t i=0; i < src->mHeaders.size(); i++) {
4060 mHeaders.add(src->mHeaders[i]);
4061 }
4062
4063 for (size_t i=0; i < src->mPackageGroups.size(); i++) {
4064 PackageGroup* srcPg = src->mPackageGroups[i];
4065 PackageGroup* pg = new PackageGroup(this, srcPg->name, srcPg->id,
4066 false /* appAsLib */, isSystemAsset || srcPg->isSystemAsset, srcPg->isDynamic);
4067 for (size_t j=0; j<srcPg->packages.size(); j++) {
4068 pg->packages.add(srcPg->packages[j]);
4069 }
4070
4071 for (size_t j = 0; j < srcPg->types.size(); j++) {
4072 if (srcPg->types[j].isEmpty()) {
4073 continue;
4074 }
4075
4076 TypeList& typeList = pg->types.editItemAt(j);
4077 typeList.appendVector(srcPg->types[j]);
4078 }
4079 pg->dynamicRefTable.addMappings(srcPg->dynamicRefTable);
4080 pg->largestTypeId = max(pg->largestTypeId, srcPg->largestTypeId);
4081 mPackageGroups.add(pg);
4082 }
4083
4084 memcpy(mPackageMap, src->mPackageMap, sizeof(mPackageMap));
4085
4086 return mError;
4087 }
4088
addEmpty(const int32_t cookie)4089 status_t ResTable::addEmpty(const int32_t cookie) {
4090 Header* header = new Header(this);
4091 header->index = mHeaders.size();
4092 header->cookie = cookie;
4093 header->values.setToEmpty();
4094 header->ownedData = calloc(1, sizeof(ResTable_header));
4095
4096 ResTable_header* resHeader = (ResTable_header*) header->ownedData;
4097 resHeader->header.type = RES_TABLE_TYPE;
4098 resHeader->header.headerSize = sizeof(ResTable_header);
4099 resHeader->header.size = sizeof(ResTable_header);
4100
4101 header->header = (const ResTable_header*) resHeader;
4102 mHeaders.add(header);
4103 return (mError=NO_ERROR);
4104 }
4105
addInternal(const void * data,size_t dataSize,const void * idmapData,size_t idmapDataSize,bool appAsLib,const int32_t cookie,bool copyData,bool isSystemAsset)4106 status_t ResTable::addInternal(const void* data, size_t dataSize, const void* idmapData, size_t idmapDataSize,
4107 bool appAsLib, const int32_t cookie, bool copyData, bool isSystemAsset)
4108 {
4109 if (!data) {
4110 return NO_ERROR;
4111 }
4112
4113 if (dataSize < sizeof(ResTable_header)) {
4114 ALOGE("Invalid data. Size(%d) is smaller than a ResTable_header(%d).",
4115 (int) dataSize, (int) sizeof(ResTable_header));
4116 return UNKNOWN_ERROR;
4117 }
4118
4119 Header* header = new Header(this);
4120 header->index = mHeaders.size();
4121 header->cookie = cookie;
4122 if (idmapData != NULL) {
4123 header->resourceIDMap = (uint32_t*) malloc(idmapDataSize);
4124 if (header->resourceIDMap == NULL) {
4125 delete header;
4126 return (mError = NO_MEMORY);
4127 }
4128 memcpy(header->resourceIDMap, idmapData, idmapDataSize);
4129 header->resourceIDMapSize = idmapDataSize;
4130 }
4131 mHeaders.add(header);
4132
4133 const bool notDeviceEndian = htods(0xf0) != 0xf0;
4134
4135 if (kDebugLoadTableNoisy) {
4136 ALOGV("Adding resources to ResTable: data=%p, size=%zu, cookie=%d, copy=%d "
4137 "idmap=%p\n", data, dataSize, cookie, copyData, idmapData);
4138 }
4139
4140 if (copyData || notDeviceEndian) {
4141 header->ownedData = malloc(dataSize);
4142 if (header->ownedData == NULL) {
4143 return (mError=NO_MEMORY);
4144 }
4145 memcpy(header->ownedData, data, dataSize);
4146 data = header->ownedData;
4147 }
4148
4149 header->header = (const ResTable_header*)data;
4150 header->size = dtohl(header->header->header.size);
4151 if (kDebugLoadTableSuperNoisy) {
4152 ALOGI("Got size %zu, again size 0x%x, raw size 0x%x\n", header->size,
4153 dtohl(header->header->header.size), header->header->header.size);
4154 }
4155 if (kDebugLoadTableNoisy) {
4156 ALOGV("Loading ResTable @%p:\n", header->header);
4157 }
4158 if (dtohs(header->header->header.headerSize) > header->size
4159 || header->size > dataSize) {
4160 ALOGW("Bad resource table: header size 0x%x or total size 0x%x is larger than data size 0x%x\n",
4161 (int)dtohs(header->header->header.headerSize),
4162 (int)header->size, (int)dataSize);
4163 return (mError=BAD_TYPE);
4164 }
4165 if (((dtohs(header->header->header.headerSize)|header->size)&0x3) != 0) {
4166 ALOGW("Bad resource table: header size 0x%x or total size 0x%x is not on an integer boundary\n",
4167 (int)dtohs(header->header->header.headerSize),
4168 (int)header->size);
4169 return (mError=BAD_TYPE);
4170 }
4171 header->dataEnd = ((const uint8_t*)header->header) + header->size;
4172
4173 // Iterate through all chunks.
4174 size_t curPackage = 0;
4175
4176 const ResChunk_header* chunk =
4177 (const ResChunk_header*)(((const uint8_t*)header->header)
4178 + dtohs(header->header->header.headerSize));
4179 while (((const uint8_t*)chunk) <= (header->dataEnd-sizeof(ResChunk_header)) &&
4180 ((const uint8_t*)chunk) <= (header->dataEnd-dtohl(chunk->size))) {
4181 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), header->dataEnd, "ResTable");
4182 if (err != NO_ERROR) {
4183 return (mError=err);
4184 }
4185 if (kDebugTableNoisy) {
4186 ALOGV("Chunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n",
4187 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
4188 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)));
4189 }
4190 const size_t csize = dtohl(chunk->size);
4191 const uint16_t ctype = dtohs(chunk->type);
4192 if (ctype == RES_STRING_POOL_TYPE) {
4193 if (header->values.getError() != NO_ERROR) {
4194 // Only use the first string chunk; ignore any others that
4195 // may appear.
4196 status_t err = header->values.setTo(chunk, csize);
4197 if (err != NO_ERROR) {
4198 return (mError=err);
4199 }
4200 } else {
4201 ALOGW("Multiple string chunks found in resource table.");
4202 }
4203 } else if (ctype == RES_TABLE_PACKAGE_TYPE) {
4204 if (curPackage >= dtohl(header->header->packageCount)) {
4205 ALOGW("More package chunks were found than the %d declared in the header.",
4206 dtohl(header->header->packageCount));
4207 return (mError=BAD_TYPE);
4208 }
4209
4210 if (parsePackage(
4211 (ResTable_package*)chunk, header, appAsLib, isSystemAsset) != NO_ERROR) {
4212 return mError;
4213 }
4214 curPackage++;
4215 } else {
4216 ALOGW("Unknown chunk type 0x%x in table at %p.\n",
4217 ctype,
4218 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)));
4219 }
4220 chunk = (const ResChunk_header*)
4221 (((const uint8_t*)chunk) + csize);
4222 }
4223
4224 if (curPackage < dtohl(header->header->packageCount)) {
4225 ALOGW("Fewer package chunks (%d) were found than the %d declared in the header.",
4226 (int)curPackage, dtohl(header->header->packageCount));
4227 return (mError=BAD_TYPE);
4228 }
4229 mError = header->values.getError();
4230 if (mError != NO_ERROR) {
4231 ALOGW("No string values found in resource table!");
4232 }
4233
4234 if (kDebugTableNoisy) {
4235 ALOGV("Returning from add with mError=%d\n", mError);
4236 }
4237 return mError;
4238 }
4239
getError() const4240 status_t ResTable::getError() const
4241 {
4242 return mError;
4243 }
4244
uninit()4245 void ResTable::uninit()
4246 {
4247 mError = NO_INIT;
4248 size_t N = mPackageGroups.size();
4249 for (size_t i=0; i<N; i++) {
4250 PackageGroup* g = mPackageGroups[i];
4251 delete g;
4252 }
4253 N = mHeaders.size();
4254 for (size_t i=0; i<N; i++) {
4255 Header* header = mHeaders[i];
4256 if (header->owner == this) {
4257 if (header->ownedData) {
4258 free(header->ownedData);
4259 }
4260 delete header;
4261 }
4262 }
4263
4264 mPackageGroups.clear();
4265 mHeaders.clear();
4266 }
4267
getResourceName(uint32_t resID,bool allowUtf8,resource_name * outName) const4268 bool ResTable::getResourceName(uint32_t resID, bool allowUtf8, resource_name* outName) const
4269 {
4270 if (mError != NO_ERROR) {
4271 return false;
4272 }
4273
4274 const ssize_t p = getResourcePackageIndex(resID);
4275 const int t = Res_GETTYPE(resID);
4276 const int e = Res_GETENTRY(resID);
4277
4278 if (p < 0) {
4279 if (Res_GETPACKAGE(resID)+1 == 0) {
4280 ALOGW("No package identifier when getting name for resource number 0x%08x", resID);
4281 } else {
4282 #ifndef STATIC_ANDROIDFW_FOR_TOOLS
4283 ALOGW("No known package when getting name for resource number 0x%08x", resID);
4284 #endif
4285 }
4286 return false;
4287 }
4288 if (t < 0) {
4289 ALOGW("No type identifier when getting name for resource number 0x%08x", resID);
4290 return false;
4291 }
4292
4293 const PackageGroup* const grp = mPackageGroups[p];
4294 if (grp == NULL) {
4295 ALOGW("Bad identifier when getting name for resource number 0x%08x", resID);
4296 return false;
4297 }
4298
4299 Entry entry;
4300 status_t err = getEntry(grp, t, e, NULL, &entry);
4301 if (err != NO_ERROR) {
4302 return false;
4303 }
4304
4305 outName->package = grp->name.string();
4306 outName->packageLen = grp->name.size();
4307 if (allowUtf8) {
4308 outName->type8 = entry.typeStr.string8(&outName->typeLen);
4309 outName->name8 = entry.keyStr.string8(&outName->nameLen);
4310 } else {
4311 outName->type8 = NULL;
4312 outName->name8 = NULL;
4313 }
4314 if (outName->type8 == NULL) {
4315 outName->type = entry.typeStr.string16(&outName->typeLen);
4316 // If we have a bad index for some reason, we should abort.
4317 if (outName->type == NULL) {
4318 return false;
4319 }
4320 }
4321 if (outName->name8 == NULL) {
4322 outName->name = entry.keyStr.string16(&outName->nameLen);
4323 // If we have a bad index for some reason, we should abort.
4324 if (outName->name == NULL) {
4325 return false;
4326 }
4327 }
4328
4329 return true;
4330 }
4331
getResource(uint32_t resID,Res_value * outValue,bool mayBeBag,uint16_t density,uint32_t * outSpecFlags,ResTable_config * outConfig) const4332 ssize_t ResTable::getResource(uint32_t resID, Res_value* outValue, bool mayBeBag, uint16_t density,
4333 uint32_t* outSpecFlags, ResTable_config* outConfig) const
4334 {
4335 if (mError != NO_ERROR) {
4336 return mError;
4337 }
4338
4339 const ssize_t p = getResourcePackageIndex(resID);
4340 const int t = Res_GETTYPE(resID);
4341 const int e = Res_GETENTRY(resID);
4342
4343 if (p < 0) {
4344 if (Res_GETPACKAGE(resID)+1 == 0) {
4345 ALOGW("No package identifier when getting value for resource number 0x%08x", resID);
4346 } else {
4347 ALOGW("No known package when getting value for resource number 0x%08x", resID);
4348 }
4349 return BAD_INDEX;
4350 }
4351 if (t < 0) {
4352 ALOGW("No type identifier when getting value for resource number 0x%08x", resID);
4353 return BAD_INDEX;
4354 }
4355
4356 const PackageGroup* const grp = mPackageGroups[p];
4357 if (grp == NULL) {
4358 ALOGW("Bad identifier when getting value for resource number 0x%08x", resID);
4359 return BAD_INDEX;
4360 }
4361
4362 // Allow overriding density
4363 ResTable_config desiredConfig = mParams;
4364 if (density > 0) {
4365 desiredConfig.density = density;
4366 }
4367
4368 Entry entry;
4369 status_t err = getEntry(grp, t, e, &desiredConfig, &entry);
4370 if (err != NO_ERROR) {
4371 // Only log the failure when we're not running on the host as
4372 // part of a tool. The caller will do its own logging.
4373 #ifndef STATIC_ANDROIDFW_FOR_TOOLS
4374 ALOGW("Failure getting entry for 0x%08x (t=%d e=%d) (error %d)\n",
4375 resID, t, e, err);
4376 #endif
4377 return err;
4378 }
4379
4380 if ((dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) != 0) {
4381 if (!mayBeBag) {
4382 ALOGW("Requesting resource 0x%08x failed because it is complex\n", resID);
4383 }
4384 return BAD_VALUE;
4385 }
4386
4387 const Res_value* value = reinterpret_cast<const Res_value*>(
4388 reinterpret_cast<const uint8_t*>(entry.entry) + entry.entry->size);
4389
4390 outValue->size = dtohs(value->size);
4391 outValue->res0 = value->res0;
4392 outValue->dataType = value->dataType;
4393 outValue->data = dtohl(value->data);
4394
4395 // The reference may be pointing to a resource in a shared library. These
4396 // references have build-time generated package IDs. These ids may not match
4397 // the actual package IDs of the corresponding packages in this ResTable.
4398 // We need to fix the package ID based on a mapping.
4399 if (grp->dynamicRefTable.lookupResourceValue(outValue) != NO_ERROR) {
4400 ALOGW("Failed to resolve referenced package: 0x%08x", outValue->data);
4401 return BAD_VALUE;
4402 }
4403
4404 if (kDebugTableNoisy) {
4405 size_t len;
4406 printf("Found value: pkg=%zu, type=%d, str=%s, int=%d\n",
4407 entry.package->header->index,
4408 outValue->dataType,
4409 outValue->dataType == Res_value::TYPE_STRING ?
4410 String8(entry.package->header->values.stringAt(outValue->data, &len)).string() :
4411 "",
4412 outValue->data);
4413 }
4414
4415 if (outSpecFlags != NULL) {
4416 *outSpecFlags = entry.specFlags;
4417 }
4418
4419 if (outConfig != NULL) {
4420 *outConfig = entry.config;
4421 }
4422
4423 return entry.package->header->index;
4424 }
4425
resolveReference(Res_value * value,ssize_t blockIndex,uint32_t * outLastRef,uint32_t * inoutTypeSpecFlags,ResTable_config * outConfig) const4426 ssize_t ResTable::resolveReference(Res_value* value, ssize_t blockIndex,
4427 uint32_t* outLastRef, uint32_t* inoutTypeSpecFlags,
4428 ResTable_config* outConfig) const
4429 {
4430 int count=0;
4431 while (blockIndex >= 0 && value->dataType == Res_value::TYPE_REFERENCE
4432 && value->data != 0 && count < 20) {
4433 if (outLastRef) *outLastRef = value->data;
4434 uint32_t newFlags = 0;
4435 const ssize_t newIndex = getResource(value->data, value, true, 0, &newFlags,
4436 outConfig);
4437 if (newIndex == BAD_INDEX) {
4438 return BAD_INDEX;
4439 }
4440 if (kDebugTableTheme) {
4441 ALOGI("Resolving reference 0x%x: newIndex=%d, type=0x%x, data=0x%x\n",
4442 value->data, (int)newIndex, (int)value->dataType, value->data);
4443 }
4444 //printf("Getting reference 0x%08x: newIndex=%d\n", value->data, newIndex);
4445 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newFlags;
4446 if (newIndex < 0) {
4447 // This can fail if the resource being referenced is a style...
4448 // in this case, just return the reference, and expect the
4449 // caller to deal with.
4450 return blockIndex;
4451 }
4452 blockIndex = newIndex;
4453 count++;
4454 }
4455 return blockIndex;
4456 }
4457
valueToString(const Res_value * value,size_t stringBlock,char16_t[TMP_BUFFER_SIZE],size_t * outLen) const4458 const char16_t* ResTable::valueToString(
4459 const Res_value* value, size_t stringBlock,
4460 char16_t /*tmpBuffer*/ [TMP_BUFFER_SIZE], size_t* outLen) const
4461 {
4462 if (!value) {
4463 return NULL;
4464 }
4465 if (value->dataType == value->TYPE_STRING) {
4466 return getTableStringBlock(stringBlock)->stringAt(value->data, outLen);
4467 }
4468 // XXX do int to string conversions.
4469 return NULL;
4470 }
4471
lockBag(uint32_t resID,const bag_entry ** outBag) const4472 ssize_t ResTable::lockBag(uint32_t resID, const bag_entry** outBag) const
4473 {
4474 mLock.lock();
4475 ssize_t err = getBagLocked(resID, outBag);
4476 if (err < NO_ERROR) {
4477 //printf("*** get failed! unlocking\n");
4478 mLock.unlock();
4479 }
4480 return err;
4481 }
4482
unlockBag(const bag_entry *) const4483 void ResTable::unlockBag(const bag_entry* /*bag*/) const
4484 {
4485 //printf("<<< unlockBag %p\n", this);
4486 mLock.unlock();
4487 }
4488
lock() const4489 void ResTable::lock() const
4490 {
4491 mLock.lock();
4492 }
4493
unlock() const4494 void ResTable::unlock() const
4495 {
4496 mLock.unlock();
4497 }
4498
getBagLocked(uint32_t resID,const bag_entry ** outBag,uint32_t * outTypeSpecFlags) const4499 ssize_t ResTable::getBagLocked(uint32_t resID, const bag_entry** outBag,
4500 uint32_t* outTypeSpecFlags) const
4501 {
4502 if (mError != NO_ERROR) {
4503 return mError;
4504 }
4505
4506 const ssize_t p = getResourcePackageIndex(resID);
4507 const int t = Res_GETTYPE(resID);
4508 const int e = Res_GETENTRY(resID);
4509
4510 if (p < 0) {
4511 ALOGW("Invalid package identifier when getting bag for resource number 0x%08x", resID);
4512 return BAD_INDEX;
4513 }
4514 if (t < 0) {
4515 ALOGW("No type identifier when getting bag for resource number 0x%08x", resID);
4516 return BAD_INDEX;
4517 }
4518
4519 //printf("Get bag: id=0x%08x, p=%d, t=%d\n", resID, p, t);
4520 PackageGroup* const grp = mPackageGroups[p];
4521 if (grp == NULL) {
4522 ALOGW("Bad identifier when getting bag for resource number 0x%08x", resID);
4523 return BAD_INDEX;
4524 }
4525
4526 const TypeList& typeConfigs = grp->types[t];
4527 if (typeConfigs.isEmpty()) {
4528 ALOGW("Type identifier 0x%x does not exist.", t+1);
4529 return BAD_INDEX;
4530 }
4531
4532 const size_t NENTRY = typeConfigs[0]->entryCount;
4533 if (e >= (int)NENTRY) {
4534 ALOGW("Entry identifier 0x%x is larger than entry count 0x%x",
4535 e, (int)typeConfigs[0]->entryCount);
4536 return BAD_INDEX;
4537 }
4538
4539 // First see if we've already computed this bag...
4540 TypeCacheEntry& cacheEntry = grp->typeCacheEntries.editItemAt(t);
4541 bag_set** typeSet = cacheEntry.cachedBags;
4542 if (typeSet) {
4543 bag_set* set = typeSet[e];
4544 if (set) {
4545 if (set != (bag_set*)0xFFFFFFFF) {
4546 if (outTypeSpecFlags != NULL) {
4547 *outTypeSpecFlags = set->typeSpecFlags;
4548 }
4549 *outBag = (bag_entry*)(set+1);
4550 if (kDebugTableSuperNoisy) {
4551 ALOGI("Found existing bag for: 0x%x\n", resID);
4552 }
4553 return set->numAttrs;
4554 }
4555 ALOGW("Attempt to retrieve bag 0x%08x which is invalid or in a cycle.",
4556 resID);
4557 return BAD_INDEX;
4558 }
4559 }
4560
4561 // Bag not found, we need to compute it!
4562 if (!typeSet) {
4563 typeSet = (bag_set**)calloc(NENTRY, sizeof(bag_set*));
4564 if (!typeSet) return NO_MEMORY;
4565 cacheEntry.cachedBags = typeSet;
4566 }
4567
4568 // Mark that we are currently working on this one.
4569 typeSet[e] = (bag_set*)0xFFFFFFFF;
4570
4571 if (kDebugTableNoisy) {
4572 ALOGI("Building bag: %x\n", resID);
4573 }
4574
4575 // Now collect all bag attributes
4576 Entry entry;
4577 status_t err = getEntry(grp, t, e, &mParams, &entry);
4578 if (err != NO_ERROR) {
4579 return err;
4580 }
4581
4582 const uint16_t entrySize = dtohs(entry.entry->size);
4583 const uint32_t parent = entrySize >= sizeof(ResTable_map_entry)
4584 ? dtohl(((const ResTable_map_entry*)entry.entry)->parent.ident) : 0;
4585 const uint32_t count = entrySize >= sizeof(ResTable_map_entry)
4586 ? dtohl(((const ResTable_map_entry*)entry.entry)->count) : 0;
4587
4588 size_t N = count;
4589
4590 if (kDebugTableNoisy) {
4591 ALOGI("Found map: size=%x parent=%x count=%d\n", entrySize, parent, count);
4592
4593 // If this map inherits from another, we need to start
4594 // with its parent's values. Otherwise start out empty.
4595 ALOGI("Creating new bag, entrySize=0x%08x, parent=0x%08x\n", entrySize, parent);
4596 }
4597
4598 // This is what we are building.
4599 bag_set* set = NULL;
4600
4601 if (parent) {
4602 uint32_t resolvedParent = parent;
4603
4604 // Bags encode a parent reference without using the standard
4605 // Res_value structure. That means we must always try to
4606 // resolve a parent reference in case it is actually a
4607 // TYPE_DYNAMIC_REFERENCE.
4608 status_t err = grp->dynamicRefTable.lookupResourceId(&resolvedParent);
4609 if (err != NO_ERROR) {
4610 ALOGE("Failed resolving bag parent id 0x%08x", parent);
4611 return UNKNOWN_ERROR;
4612 }
4613
4614 const bag_entry* parentBag;
4615 uint32_t parentTypeSpecFlags = 0;
4616 const ssize_t NP = getBagLocked(resolvedParent, &parentBag, &parentTypeSpecFlags);
4617 const size_t NT = ((NP >= 0) ? NP : 0) + N;
4618 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*NT);
4619 if (set == NULL) {
4620 return NO_MEMORY;
4621 }
4622 if (NP > 0) {
4623 memcpy(set+1, parentBag, NP*sizeof(bag_entry));
4624 set->numAttrs = NP;
4625 if (kDebugTableNoisy) {
4626 ALOGI("Initialized new bag with %zd inherited attributes.\n", NP);
4627 }
4628 } else {
4629 if (kDebugTableNoisy) {
4630 ALOGI("Initialized new bag with no inherited attributes.\n");
4631 }
4632 set->numAttrs = 0;
4633 }
4634 set->availAttrs = NT;
4635 set->typeSpecFlags = parentTypeSpecFlags;
4636 } else {
4637 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*N);
4638 if (set == NULL) {
4639 return NO_MEMORY;
4640 }
4641 set->numAttrs = 0;
4642 set->availAttrs = N;
4643 set->typeSpecFlags = 0;
4644 }
4645
4646 set->typeSpecFlags |= entry.specFlags;
4647
4648 // Now merge in the new attributes...
4649 size_t curOff = (reinterpret_cast<uintptr_t>(entry.entry) - reinterpret_cast<uintptr_t>(entry.type))
4650 + dtohs(entry.entry->size);
4651 const ResTable_map* map;
4652 bag_entry* entries = (bag_entry*)(set+1);
4653 size_t curEntry = 0;
4654 uint32_t pos = 0;
4655 if (kDebugTableNoisy) {
4656 ALOGI("Starting with set %p, entries=%p, avail=%zu\n", set, entries, set->availAttrs);
4657 }
4658 while (pos < count) {
4659 if (kDebugTableNoisy) {
4660 ALOGI("Now at %p\n", (void*)curOff);
4661 }
4662
4663 if (curOff > (dtohl(entry.type->header.size)-sizeof(ResTable_map))) {
4664 ALOGW("ResTable_map at %d is beyond type chunk data %d",
4665 (int)curOff, dtohl(entry.type->header.size));
4666 free(set);
4667 return BAD_TYPE;
4668 }
4669 map = (const ResTable_map*)(((const uint8_t*)entry.type) + curOff);
4670 N++;
4671
4672 uint32_t newName = htodl(map->name.ident);
4673 if (!Res_INTERNALID(newName)) {
4674 // Attributes don't have a resource id as the name. They specify
4675 // other data, which would be wrong to change via a lookup.
4676 if (grp->dynamicRefTable.lookupResourceId(&newName) != NO_ERROR) {
4677 ALOGE("Failed resolving ResTable_map name at %d with ident 0x%08x",
4678 (int) curOff, (int) newName);
4679 free(set);
4680 return UNKNOWN_ERROR;
4681 }
4682 }
4683
4684 bool isInside;
4685 uint32_t oldName = 0;
4686 while ((isInside=(curEntry < set->numAttrs))
4687 && (oldName=entries[curEntry].map.name.ident) < newName) {
4688 if (kDebugTableNoisy) {
4689 ALOGI("#%zu: Keeping existing attribute: 0x%08x\n",
4690 curEntry, entries[curEntry].map.name.ident);
4691 }
4692 curEntry++;
4693 }
4694
4695 if ((!isInside) || oldName != newName) {
4696 // This is a new attribute... figure out what to do with it.
4697 if (set->numAttrs >= set->availAttrs) {
4698 // Need to alloc more memory...
4699 const size_t newAvail = set->availAttrs+N;
4700 void *oldSet = set;
4701 set = (bag_set*)realloc(set,
4702 sizeof(bag_set)
4703 + sizeof(bag_entry)*newAvail);
4704 if (set == NULL) {
4705 free(oldSet);
4706 return NO_MEMORY;
4707 }
4708 set->availAttrs = newAvail;
4709 entries = (bag_entry*)(set+1);
4710 if (kDebugTableNoisy) {
4711 ALOGI("Reallocated set %p, entries=%p, avail=%zu\n",
4712 set, entries, set->availAttrs);
4713 }
4714 }
4715 if (isInside) {
4716 // Going in the middle, need to make space.
4717 memmove(entries+curEntry+1, entries+curEntry,
4718 sizeof(bag_entry)*(set->numAttrs-curEntry));
4719 set->numAttrs++;
4720 }
4721 if (kDebugTableNoisy) {
4722 ALOGI("#%zu: Inserting new attribute: 0x%08x\n", curEntry, newName);
4723 }
4724 } else {
4725 if (kDebugTableNoisy) {
4726 ALOGI("#%zu: Replacing existing attribute: 0x%08x\n", curEntry, oldName);
4727 }
4728 }
4729
4730 bag_entry* cur = entries+curEntry;
4731
4732 cur->stringBlock = entry.package->header->index;
4733 cur->map.name.ident = newName;
4734 cur->map.value.copyFrom_dtoh(map->value);
4735 status_t err = grp->dynamicRefTable.lookupResourceValue(&cur->map.value);
4736 if (err != NO_ERROR) {
4737 ALOGE("Reference item(0x%08x) in bag could not be resolved.", cur->map.value.data);
4738 return UNKNOWN_ERROR;
4739 }
4740
4741 if (kDebugTableNoisy) {
4742 ALOGI("Setting entry #%zu %p: block=%zd, name=0x%08d, type=%d, data=0x%08x\n",
4743 curEntry, cur, cur->stringBlock, cur->map.name.ident,
4744 cur->map.value.dataType, cur->map.value.data);
4745 }
4746
4747 // On to the next!
4748 curEntry++;
4749 pos++;
4750 const size_t size = dtohs(map->value.size);
4751 curOff += size + sizeof(*map)-sizeof(map->value);
4752 }
4753
4754 if (curEntry > set->numAttrs) {
4755 set->numAttrs = curEntry;
4756 }
4757
4758 // And this is it...
4759 typeSet[e] = set;
4760 if (set) {
4761 if (outTypeSpecFlags != NULL) {
4762 *outTypeSpecFlags = set->typeSpecFlags;
4763 }
4764 *outBag = (bag_entry*)(set+1);
4765 if (kDebugTableNoisy) {
4766 ALOGI("Returning %zu attrs\n", set->numAttrs);
4767 }
4768 return set->numAttrs;
4769 }
4770 return BAD_INDEX;
4771 }
4772
setParameters(const ResTable_config * params)4773 void ResTable::setParameters(const ResTable_config* params)
4774 {
4775 AutoMutex _lock(mLock);
4776 AutoMutex _lock2(mFilteredConfigLock);
4777
4778 if (kDebugTableGetEntry) {
4779 ALOGI("Setting parameters: %s\n", params->toString().string());
4780 }
4781 mParams = *params;
4782 for (size_t p = 0; p < mPackageGroups.size(); p++) {
4783 PackageGroup* packageGroup = mPackageGroups.editItemAt(p);
4784 if (kDebugTableNoisy) {
4785 ALOGI("CLEARING BAGS FOR GROUP %zu!", p);
4786 }
4787 packageGroup->clearBagCache();
4788
4789 // Find which configurations match the set of parameters. This allows for a much
4790 // faster lookup in Lookup() if the set of values is narrowed down.
4791 for (size_t t = 0; t < packageGroup->types.size(); t++) {
4792 if (packageGroup->types[t].isEmpty()) {
4793 continue;
4794 }
4795
4796 TypeList& typeList = packageGroup->types.editItemAt(t);
4797
4798 // Retrieve the cache entry for this type.
4799 TypeCacheEntry& cacheEntry = packageGroup->typeCacheEntries.editItemAt(t);
4800
4801 for (size_t ts = 0; ts < typeList.size(); ts++) {
4802 Type* type = typeList.editItemAt(ts);
4803
4804 std::shared_ptr<Vector<const ResTable_type*>> newFilteredConfigs =
4805 std::make_shared<Vector<const ResTable_type*>>();
4806
4807 for (size_t ti = 0; ti < type->configs.size(); ti++) {
4808 ResTable_config config;
4809 config.copyFromDtoH(type->configs[ti]->config);
4810
4811 if (config.match(mParams)) {
4812 newFilteredConfigs->add(type->configs[ti]);
4813 }
4814 }
4815
4816 if (kDebugTableNoisy) {
4817 ALOGD("Updating pkg=%zu type=%zu with %zu filtered configs",
4818 p, t, newFilteredConfigs->size());
4819 }
4820
4821 cacheEntry.filteredConfigs.add(newFilteredConfigs);
4822 }
4823 }
4824 }
4825 }
4826
getParameters(ResTable_config * params) const4827 void ResTable::getParameters(ResTable_config* params) const
4828 {
4829 mLock.lock();
4830 *params = mParams;
4831 mLock.unlock();
4832 }
4833
4834 struct id_name_map {
4835 uint32_t id;
4836 size_t len;
4837 char16_t name[6];
4838 };
4839
4840 const static id_name_map ID_NAMES[] = {
4841 { ResTable_map::ATTR_TYPE, 5, { '^', 't', 'y', 'p', 'e' } },
4842 { ResTable_map::ATTR_L10N, 5, { '^', 'l', '1', '0', 'n' } },
4843 { ResTable_map::ATTR_MIN, 4, { '^', 'm', 'i', 'n' } },
4844 { ResTable_map::ATTR_MAX, 4, { '^', 'm', 'a', 'x' } },
4845 { ResTable_map::ATTR_OTHER, 6, { '^', 'o', 't', 'h', 'e', 'r' } },
4846 { ResTable_map::ATTR_ZERO, 5, { '^', 'z', 'e', 'r', 'o' } },
4847 { ResTable_map::ATTR_ONE, 4, { '^', 'o', 'n', 'e' } },
4848 { ResTable_map::ATTR_TWO, 4, { '^', 't', 'w', 'o' } },
4849 { ResTable_map::ATTR_FEW, 4, { '^', 'f', 'e', 'w' } },
4850 { ResTable_map::ATTR_MANY, 5, { '^', 'm', 'a', 'n', 'y' } },
4851 };
4852
identifierForName(const char16_t * name,size_t nameLen,const char16_t * type,size_t typeLen,const char16_t * package,size_t packageLen,uint32_t * outTypeSpecFlags) const4853 uint32_t ResTable::identifierForName(const char16_t* name, size_t nameLen,
4854 const char16_t* type, size_t typeLen,
4855 const char16_t* package,
4856 size_t packageLen,
4857 uint32_t* outTypeSpecFlags) const
4858 {
4859 if (kDebugTableSuperNoisy) {
4860 printf("Identifier for name: error=%d\n", mError);
4861 }
4862
4863 // Check for internal resource identifier as the very first thing, so
4864 // that we will always find them even when there are no resources.
4865 if (name[0] == '^') {
4866 const int N = (sizeof(ID_NAMES)/sizeof(ID_NAMES[0]));
4867 size_t len;
4868 for (int i=0; i<N; i++) {
4869 const id_name_map* m = ID_NAMES + i;
4870 len = m->len;
4871 if (len != nameLen) {
4872 continue;
4873 }
4874 for (size_t j=1; j<len; j++) {
4875 if (m->name[j] != name[j]) {
4876 goto nope;
4877 }
4878 }
4879 if (outTypeSpecFlags) {
4880 *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC;
4881 }
4882 return m->id;
4883 nope:
4884 ;
4885 }
4886 if (nameLen > 7) {
4887 if (name[1] == 'i' && name[2] == 'n'
4888 && name[3] == 'd' && name[4] == 'e' && name[5] == 'x'
4889 && name[6] == '_') {
4890 int index = atoi(String8(name + 7, nameLen - 7).string());
4891 if (Res_CHECKID(index)) {
4892 ALOGW("Array resource index: %d is too large.",
4893 index);
4894 return 0;
4895 }
4896 if (outTypeSpecFlags) {
4897 *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC;
4898 }
4899 return Res_MAKEARRAY(index);
4900 }
4901 }
4902 return 0;
4903 }
4904
4905 if (mError != NO_ERROR) {
4906 return 0;
4907 }
4908
4909 bool fakePublic = false;
4910
4911 // Figure out the package and type we are looking in...
4912
4913 const char16_t* packageEnd = NULL;
4914 const char16_t* typeEnd = NULL;
4915 const char16_t* const nameEnd = name+nameLen;
4916 const char16_t* p = name;
4917 while (p < nameEnd) {
4918 if (*p == ':') packageEnd = p;
4919 else if (*p == '/') typeEnd = p;
4920 p++;
4921 }
4922 if (*name == '@') {
4923 name++;
4924 if (*name == '*') {
4925 fakePublic = true;
4926 name++;
4927 }
4928 }
4929 if (name >= nameEnd) {
4930 return 0;
4931 }
4932
4933 if (packageEnd) {
4934 package = name;
4935 packageLen = packageEnd-name;
4936 name = packageEnd+1;
4937 } else if (!package) {
4938 return 0;
4939 }
4940
4941 if (typeEnd) {
4942 type = name;
4943 typeLen = typeEnd-name;
4944 name = typeEnd+1;
4945 } else if (!type) {
4946 return 0;
4947 }
4948
4949 if (name >= nameEnd) {
4950 return 0;
4951 }
4952 nameLen = nameEnd-name;
4953
4954 if (kDebugTableNoisy) {
4955 printf("Looking for identifier: type=%s, name=%s, package=%s\n",
4956 String8(type, typeLen).string(),
4957 String8(name, nameLen).string(),
4958 String8(package, packageLen).string());
4959 }
4960
4961 const String16 attr("attr");
4962 const String16 attrPrivate("^attr-private");
4963
4964 const size_t NG = mPackageGroups.size();
4965 for (size_t ig=0; ig<NG; ig++) {
4966 const PackageGroup* group = mPackageGroups[ig];
4967
4968 if (strzcmp16(package, packageLen,
4969 group->name.string(), group->name.size())) {
4970 if (kDebugTableNoisy) {
4971 printf("Skipping package group: %s\n", String8(group->name).string());
4972 }
4973 continue;
4974 }
4975
4976 const size_t packageCount = group->packages.size();
4977 for (size_t pi = 0; pi < packageCount; pi++) {
4978 const char16_t* targetType = type;
4979 size_t targetTypeLen = typeLen;
4980
4981 do {
4982 ssize_t ti = group->packages[pi]->typeStrings.indexOfString(
4983 targetType, targetTypeLen);
4984 if (ti < 0) {
4985 continue;
4986 }
4987
4988 ti += group->packages[pi]->typeIdOffset;
4989
4990 const uint32_t identifier = findEntry(group, ti, name, nameLen,
4991 outTypeSpecFlags);
4992 if (identifier != 0) {
4993 if (fakePublic && outTypeSpecFlags) {
4994 *outTypeSpecFlags |= ResTable_typeSpec::SPEC_PUBLIC;
4995 }
4996 return identifier;
4997 }
4998 } while (strzcmp16(attr.string(), attr.size(), targetType, targetTypeLen) == 0
4999 && (targetType = attrPrivate.string())
5000 && (targetTypeLen = attrPrivate.size())
5001 );
5002 }
5003 }
5004 return 0;
5005 }
5006
findEntry(const PackageGroup * group,ssize_t typeIndex,const char16_t * name,size_t nameLen,uint32_t * outTypeSpecFlags) const5007 uint32_t ResTable::findEntry(const PackageGroup* group, ssize_t typeIndex, const char16_t* name,
5008 size_t nameLen, uint32_t* outTypeSpecFlags) const {
5009 const TypeList& typeList = group->types[typeIndex];
5010 const size_t typeCount = typeList.size();
5011 for (size_t i = 0; i < typeCount; i++) {
5012 const Type* t = typeList[i];
5013 const ssize_t ei = t->package->keyStrings.indexOfString(name, nameLen);
5014 if (ei < 0) {
5015 continue;
5016 }
5017
5018 const size_t configCount = t->configs.size();
5019 for (size_t j = 0; j < configCount; j++) {
5020 const TypeVariant tv(t->configs[j]);
5021 for (TypeVariant::iterator iter = tv.beginEntries();
5022 iter != tv.endEntries();
5023 iter++) {
5024 const ResTable_entry* entry = *iter;
5025 if (entry == NULL) {
5026 continue;
5027 }
5028
5029 if (dtohl(entry->key.index) == (size_t) ei) {
5030 uint32_t resId = Res_MAKEID(group->id - 1, typeIndex, iter.index());
5031 if (outTypeSpecFlags) {
5032 Entry result;
5033 if (getEntry(group, typeIndex, iter.index(), NULL, &result) != NO_ERROR) {
5034 ALOGW("Failed to find spec flags for 0x%08x", resId);
5035 return 0;
5036 }
5037 *outTypeSpecFlags = result.specFlags;
5038 }
5039 return resId;
5040 }
5041 }
5042 }
5043 }
5044 return 0;
5045 }
5046
expandResourceRef(const char16_t * refStr,size_t refLen,String16 * outPackage,String16 * outType,String16 * outName,const String16 * defType,const String16 * defPackage,const char ** outErrorMsg,bool * outPublicOnly)5047 bool ResTable::expandResourceRef(const char16_t* refStr, size_t refLen,
5048 String16* outPackage,
5049 String16* outType,
5050 String16* outName,
5051 const String16* defType,
5052 const String16* defPackage,
5053 const char** outErrorMsg,
5054 bool* outPublicOnly)
5055 {
5056 const char16_t* packageEnd = NULL;
5057 const char16_t* typeEnd = NULL;
5058 const char16_t* p = refStr;
5059 const char16_t* const end = p + refLen;
5060 while (p < end) {
5061 if (*p == ':') packageEnd = p;
5062 else if (*p == '/') {
5063 typeEnd = p;
5064 break;
5065 }
5066 p++;
5067 }
5068 p = refStr;
5069 if (*p == '@') p++;
5070
5071 if (outPublicOnly != NULL) {
5072 *outPublicOnly = true;
5073 }
5074 if (*p == '*') {
5075 p++;
5076 if (outPublicOnly != NULL) {
5077 *outPublicOnly = false;
5078 }
5079 }
5080
5081 if (packageEnd) {
5082 *outPackage = String16(p, packageEnd-p);
5083 p = packageEnd+1;
5084 } else {
5085 if (!defPackage) {
5086 if (outErrorMsg) {
5087 *outErrorMsg = "No resource package specified";
5088 }
5089 return false;
5090 }
5091 *outPackage = *defPackage;
5092 }
5093 if (typeEnd) {
5094 *outType = String16(p, typeEnd-p);
5095 p = typeEnd+1;
5096 } else {
5097 if (!defType) {
5098 if (outErrorMsg) {
5099 *outErrorMsg = "No resource type specified";
5100 }
5101 return false;
5102 }
5103 *outType = *defType;
5104 }
5105 *outName = String16(p, end-p);
5106 if(**outPackage == 0) {
5107 if(outErrorMsg) {
5108 *outErrorMsg = "Resource package cannot be an empty string";
5109 }
5110 return false;
5111 }
5112 if(**outType == 0) {
5113 if(outErrorMsg) {
5114 *outErrorMsg = "Resource type cannot be an empty string";
5115 }
5116 return false;
5117 }
5118 if(**outName == 0) {
5119 if(outErrorMsg) {
5120 *outErrorMsg = "Resource id cannot be an empty string";
5121 }
5122 return false;
5123 }
5124 return true;
5125 }
5126
get_hex(char c,bool * outError)5127 static uint32_t get_hex(char c, bool* outError)
5128 {
5129 if (c >= '0' && c <= '9') {
5130 return c - '0';
5131 } else if (c >= 'a' && c <= 'f') {
5132 return c - 'a' + 0xa;
5133 } else if (c >= 'A' && c <= 'F') {
5134 return c - 'A' + 0xa;
5135 }
5136 *outError = true;
5137 return 0;
5138 }
5139
5140 struct unit_entry
5141 {
5142 const char* name;
5143 size_t len;
5144 uint8_t type;
5145 uint32_t unit;
5146 float scale;
5147 };
5148
5149 static const unit_entry unitNames[] = {
5150 { "px", strlen("px"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PX, 1.0f },
5151 { "dip", strlen("dip"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
5152 { "dp", strlen("dp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
5153 { "sp", strlen("sp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_SP, 1.0f },
5154 { "pt", strlen("pt"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PT, 1.0f },
5155 { "in", strlen("in"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_IN, 1.0f },
5156 { "mm", strlen("mm"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_MM, 1.0f },
5157 { "%", strlen("%"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION, 1.0f/100 },
5158 { "%p", strlen("%p"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION_PARENT, 1.0f/100 },
5159 { NULL, 0, 0, 0, 0 }
5160 };
5161
parse_unit(const char * str,Res_value * outValue,float * outScale,const char ** outEnd)5162 static bool parse_unit(const char* str, Res_value* outValue,
5163 float* outScale, const char** outEnd)
5164 {
5165 const char* end = str;
5166 while (*end != 0 && !isspace((unsigned char)*end)) {
5167 end++;
5168 }
5169 const size_t len = end-str;
5170
5171 const char* realEnd = end;
5172 while (*realEnd != 0 && isspace((unsigned char)*realEnd)) {
5173 realEnd++;
5174 }
5175 if (*realEnd != 0) {
5176 return false;
5177 }
5178
5179 const unit_entry* cur = unitNames;
5180 while (cur->name) {
5181 if (len == cur->len && strncmp(cur->name, str, len) == 0) {
5182 outValue->dataType = cur->type;
5183 outValue->data = cur->unit << Res_value::COMPLEX_UNIT_SHIFT;
5184 *outScale = cur->scale;
5185 *outEnd = end;
5186 //printf("Found unit %s for %s\n", cur->name, str);
5187 return true;
5188 }
5189 cur++;
5190 }
5191
5192 return false;
5193 }
5194
U16StringToInt(const char16_t * s,size_t len,Res_value * outValue)5195 bool U16StringToInt(const char16_t* s, size_t len, Res_value* outValue)
5196 {
5197 while (len > 0 && isspace16(*s)) {
5198 s++;
5199 len--;
5200 }
5201
5202 if (len <= 0) {
5203 return false;
5204 }
5205
5206 size_t i = 0;
5207 int64_t val = 0;
5208 bool neg = false;
5209
5210 if (*s == '-') {
5211 neg = true;
5212 i++;
5213 }
5214
5215 if (s[i] < '0' || s[i] > '9') {
5216 return false;
5217 }
5218
5219 static_assert(std::is_same<uint32_t, Res_value::data_type>::value,
5220 "Res_value::data_type has changed. The range checks in this "
5221 "function are no longer correct.");
5222
5223 // Decimal or hex?
5224 bool isHex;
5225 if (len > 1 && s[i] == '0' && s[i+1] == 'x') {
5226 isHex = true;
5227 i += 2;
5228
5229 if (neg) {
5230 return false;
5231 }
5232
5233 if (i == len) {
5234 // Just u"0x"
5235 return false;
5236 }
5237
5238 bool error = false;
5239 while (i < len && !error) {
5240 val = (val*16) + get_hex(s[i], &error);
5241 i++;
5242
5243 if (val > std::numeric_limits<uint32_t>::max()) {
5244 return false;
5245 }
5246 }
5247 if (error) {
5248 return false;
5249 }
5250 } else {
5251 isHex = false;
5252 while (i < len) {
5253 if (s[i] < '0' || s[i] > '9') {
5254 return false;
5255 }
5256 val = (val*10) + s[i]-'0';
5257 i++;
5258
5259 if ((neg && -val < std::numeric_limits<int32_t>::min()) ||
5260 (!neg && val > std::numeric_limits<int32_t>::max())) {
5261 return false;
5262 }
5263 }
5264 }
5265
5266 if (neg) val = -val;
5267
5268 while (i < len && isspace16(s[i])) {
5269 i++;
5270 }
5271
5272 if (i != len) {
5273 return false;
5274 }
5275
5276 if (outValue) {
5277 outValue->dataType =
5278 isHex ? outValue->TYPE_INT_HEX : outValue->TYPE_INT_DEC;
5279 outValue->data = static_cast<Res_value::data_type>(val);
5280 }
5281 return true;
5282 }
5283
stringToInt(const char16_t * s,size_t len,Res_value * outValue)5284 bool ResTable::stringToInt(const char16_t* s, size_t len, Res_value* outValue)
5285 {
5286 return U16StringToInt(s, len, outValue);
5287 }
5288
stringToFloat(const char16_t * s,size_t len,Res_value * outValue)5289 bool ResTable::stringToFloat(const char16_t* s, size_t len, Res_value* outValue)
5290 {
5291 while (len > 0 && isspace16(*s)) {
5292 s++;
5293 len--;
5294 }
5295
5296 if (len <= 0) {
5297 return false;
5298 }
5299
5300 char buf[128];
5301 int i=0;
5302 while (len > 0 && *s != 0 && i < 126) {
5303 if (*s > 255) {
5304 return false;
5305 }
5306 buf[i++] = *s++;
5307 len--;
5308 }
5309
5310 if (len > 0) {
5311 return false;
5312 }
5313 if ((buf[0] < '0' || buf[0] > '9') && buf[0] != '.' && buf[0] != '-' && buf[0] != '+') {
5314 return false;
5315 }
5316
5317 buf[i] = 0;
5318 const char* end;
5319 float f = strtof(buf, (char**)&end);
5320
5321 if (*end != 0 && !isspace((unsigned char)*end)) {
5322 // Might be a unit...
5323 float scale;
5324 if (parse_unit(end, outValue, &scale, &end)) {
5325 f *= scale;
5326 const bool neg = f < 0;
5327 if (neg) f = -f;
5328 uint64_t bits = (uint64_t)(f*(1<<23)+.5f);
5329 uint32_t radix;
5330 uint32_t shift;
5331 if ((bits&0x7fffff) == 0) {
5332 // Always use 23p0 if there is no fraction, just to make
5333 // things easier to read.
5334 radix = Res_value::COMPLEX_RADIX_23p0;
5335 shift = 23;
5336 } else if ((bits&0xffffffffff800000LL) == 0) {
5337 // Magnitude is zero -- can fit in 0 bits of precision.
5338 radix = Res_value::COMPLEX_RADIX_0p23;
5339 shift = 0;
5340 } else if ((bits&0xffffffff80000000LL) == 0) {
5341 // Magnitude can fit in 8 bits of precision.
5342 radix = Res_value::COMPLEX_RADIX_8p15;
5343 shift = 8;
5344 } else if ((bits&0xffffff8000000000LL) == 0) {
5345 // Magnitude can fit in 16 bits of precision.
5346 radix = Res_value::COMPLEX_RADIX_16p7;
5347 shift = 16;
5348 } else {
5349 // Magnitude needs entire range, so no fractional part.
5350 radix = Res_value::COMPLEX_RADIX_23p0;
5351 shift = 23;
5352 }
5353 int32_t mantissa = (int32_t)(
5354 (bits>>shift) & Res_value::COMPLEX_MANTISSA_MASK);
5355 if (neg) {
5356 mantissa = (-mantissa) & Res_value::COMPLEX_MANTISSA_MASK;
5357 }
5358 outValue->data |=
5359 (radix<<Res_value::COMPLEX_RADIX_SHIFT)
5360 | (mantissa<<Res_value::COMPLEX_MANTISSA_SHIFT);
5361 //printf("Input value: %f 0x%016Lx, mult: %f, radix: %d, shift: %d, final: 0x%08x\n",
5362 // f * (neg ? -1 : 1), bits, f*(1<<23),
5363 // radix, shift, outValue->data);
5364 return true;
5365 }
5366 return false;
5367 }
5368
5369 while (*end != 0 && isspace((unsigned char)*end)) {
5370 end++;
5371 }
5372
5373 if (*end == 0) {
5374 if (outValue) {
5375 outValue->dataType = outValue->TYPE_FLOAT;
5376 *(float*)(&outValue->data) = f;
5377 return true;
5378 }
5379 }
5380
5381 return false;
5382 }
5383
stringToValue(Res_value * outValue,String16 * outString,const char16_t * s,size_t len,bool preserveSpaces,bool coerceType,uint32_t attrID,const String16 * defType,const String16 * defPackage,Accessor * accessor,void * accessorCookie,uint32_t attrType,bool enforcePrivate) const5384 bool ResTable::stringToValue(Res_value* outValue, String16* outString,
5385 const char16_t* s, size_t len,
5386 bool preserveSpaces, bool coerceType,
5387 uint32_t attrID,
5388 const String16* defType,
5389 const String16* defPackage,
5390 Accessor* accessor,
5391 void* accessorCookie,
5392 uint32_t attrType,
5393 bool enforcePrivate) const
5394 {
5395 bool localizationSetting = accessor != NULL && accessor->getLocalizationSetting();
5396 const char* errorMsg = NULL;
5397
5398 outValue->size = sizeof(Res_value);
5399 outValue->res0 = 0;
5400
5401 // First strip leading/trailing whitespace. Do this before handling
5402 // escapes, so they can be used to force whitespace into the string.
5403 if (!preserveSpaces) {
5404 while (len > 0 && isspace16(*s)) {
5405 s++;
5406 len--;
5407 }
5408 while (len > 0 && isspace16(s[len-1])) {
5409 len--;
5410 }
5411 // If the string ends with '\', then we keep the space after it.
5412 if (len > 0 && s[len-1] == '\\' && s[len] != 0) {
5413 len++;
5414 }
5415 }
5416
5417 //printf("Value for: %s\n", String8(s, len).string());
5418
5419 uint32_t l10nReq = ResTable_map::L10N_NOT_REQUIRED;
5420 uint32_t attrMin = 0x80000000, attrMax = 0x7fffffff;
5421 bool fromAccessor = false;
5422 if (attrID != 0 && !Res_INTERNALID(attrID)) {
5423 const ssize_t p = getResourcePackageIndex(attrID);
5424 const bag_entry* bag;
5425 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
5426 //printf("For attr 0x%08x got bag of %d\n", attrID, cnt);
5427 if (cnt >= 0) {
5428 while (cnt > 0) {
5429 //printf("Entry 0x%08x = 0x%08x\n", bag->map.name.ident, bag->map.value.data);
5430 switch (bag->map.name.ident) {
5431 case ResTable_map::ATTR_TYPE:
5432 attrType = bag->map.value.data;
5433 break;
5434 case ResTable_map::ATTR_MIN:
5435 attrMin = bag->map.value.data;
5436 break;
5437 case ResTable_map::ATTR_MAX:
5438 attrMax = bag->map.value.data;
5439 break;
5440 case ResTable_map::ATTR_L10N:
5441 l10nReq = bag->map.value.data;
5442 break;
5443 }
5444 bag++;
5445 cnt--;
5446 }
5447 unlockBag(bag);
5448 } else if (accessor && accessor->getAttributeType(attrID, &attrType)) {
5449 fromAccessor = true;
5450 if (attrType == ResTable_map::TYPE_ENUM
5451 || attrType == ResTable_map::TYPE_FLAGS
5452 || attrType == ResTable_map::TYPE_INTEGER) {
5453 accessor->getAttributeMin(attrID, &attrMin);
5454 accessor->getAttributeMax(attrID, &attrMax);
5455 }
5456 if (localizationSetting) {
5457 l10nReq = accessor->getAttributeL10N(attrID);
5458 }
5459 }
5460 }
5461
5462 const bool canStringCoerce =
5463 coerceType && (attrType&ResTable_map::TYPE_STRING) != 0;
5464
5465 if (*s == '@') {
5466 outValue->dataType = outValue->TYPE_REFERENCE;
5467
5468 // Note: we don't check attrType here because the reference can
5469 // be to any other type; we just need to count on the client making
5470 // sure the referenced type is correct.
5471
5472 //printf("Looking up ref: %s\n", String8(s, len).string());
5473
5474 // It's a reference!
5475 if (len == 5 && s[1]=='n' && s[2]=='u' && s[3]=='l' && s[4]=='l') {
5476 // Special case @null as undefined. This will be converted by
5477 // AssetManager to TYPE_NULL with data DATA_NULL_UNDEFINED.
5478 outValue->data = 0;
5479 return true;
5480 } else if (len == 6 && s[1]=='e' && s[2]=='m' && s[3]=='p' && s[4]=='t' && s[5]=='y') {
5481 // Special case @empty as explicitly defined empty value.
5482 outValue->dataType = Res_value::TYPE_NULL;
5483 outValue->data = Res_value::DATA_NULL_EMPTY;
5484 return true;
5485 } else {
5486 bool createIfNotFound = false;
5487 const char16_t* resourceRefName;
5488 int resourceNameLen;
5489 if (len > 2 && s[1] == '+') {
5490 createIfNotFound = true;
5491 resourceRefName = s + 2;
5492 resourceNameLen = len - 2;
5493 } else if (len > 2 && s[1] == '*') {
5494 enforcePrivate = false;
5495 resourceRefName = s + 2;
5496 resourceNameLen = len - 2;
5497 } else {
5498 createIfNotFound = false;
5499 resourceRefName = s + 1;
5500 resourceNameLen = len - 1;
5501 }
5502 String16 package, type, name;
5503 if (!expandResourceRef(resourceRefName,resourceNameLen, &package, &type, &name,
5504 defType, defPackage, &errorMsg)) {
5505 if (accessor != NULL) {
5506 accessor->reportError(accessorCookie, errorMsg);
5507 }
5508 return false;
5509 }
5510
5511 uint32_t specFlags = 0;
5512 uint32_t rid = identifierForName(name.string(), name.size(), type.string(),
5513 type.size(), package.string(), package.size(), &specFlags);
5514 if (rid != 0) {
5515 if (enforcePrivate) {
5516 if (accessor == NULL || accessor->getAssetsPackage() != package) {
5517 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
5518 if (accessor != NULL) {
5519 accessor->reportError(accessorCookie, "Resource is not public.");
5520 }
5521 return false;
5522 }
5523 }
5524 }
5525
5526 if (accessor) {
5527 rid = Res_MAKEID(
5528 accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
5529 Res_GETTYPE(rid), Res_GETENTRY(rid));
5530 if (kDebugTableNoisy) {
5531 ALOGI("Incl %s:%s/%s: 0x%08x\n",
5532 String8(package).string(), String8(type).string(),
5533 String8(name).string(), rid);
5534 }
5535 }
5536
5537 uint32_t packageId = Res_GETPACKAGE(rid) + 1;
5538 if (packageId != APP_PACKAGE_ID && packageId != SYS_PACKAGE_ID) {
5539 outValue->dataType = Res_value::TYPE_DYNAMIC_REFERENCE;
5540 }
5541 outValue->data = rid;
5542 return true;
5543 }
5544
5545 if (accessor) {
5546 uint32_t rid = accessor->getCustomResourceWithCreation(package, type, name,
5547 createIfNotFound);
5548 if (rid != 0) {
5549 if (kDebugTableNoisy) {
5550 ALOGI("Pckg %s:%s/%s: 0x%08x\n",
5551 String8(package).string(), String8(type).string(),
5552 String8(name).string(), rid);
5553 }
5554 uint32_t packageId = Res_GETPACKAGE(rid) + 1;
5555 if (packageId == 0x00) {
5556 outValue->data = rid;
5557 outValue->dataType = Res_value::TYPE_DYNAMIC_REFERENCE;
5558 return true;
5559 } else if (packageId == APP_PACKAGE_ID || packageId == SYS_PACKAGE_ID) {
5560 // We accept packageId's generated as 0x01 in order to support
5561 // building the android system resources
5562 outValue->data = rid;
5563 return true;
5564 }
5565 }
5566 }
5567 }
5568
5569 if (accessor != NULL) {
5570 accessor->reportError(accessorCookie, "No resource found that matches the given name");
5571 }
5572 return false;
5573 }
5574
5575 // if we got to here, and localization is required and it's not a reference,
5576 // complain and bail.
5577 if (l10nReq == ResTable_map::L10N_SUGGESTED) {
5578 if (localizationSetting) {
5579 if (accessor != NULL) {
5580 accessor->reportError(accessorCookie, "This attribute must be localized.");
5581 }
5582 }
5583 }
5584
5585 if (*s == '#') {
5586 // It's a color! Convert to an integer of the form 0xaarrggbb.
5587 uint32_t color = 0;
5588 bool error = false;
5589 if (len == 4) {
5590 outValue->dataType = outValue->TYPE_INT_COLOR_RGB4;
5591 color |= 0xFF000000;
5592 color |= get_hex(s[1], &error) << 20;
5593 color |= get_hex(s[1], &error) << 16;
5594 color |= get_hex(s[2], &error) << 12;
5595 color |= get_hex(s[2], &error) << 8;
5596 color |= get_hex(s[3], &error) << 4;
5597 color |= get_hex(s[3], &error);
5598 } else if (len == 5) {
5599 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB4;
5600 color |= get_hex(s[1], &error) << 28;
5601 color |= get_hex(s[1], &error) << 24;
5602 color |= get_hex(s[2], &error) << 20;
5603 color |= get_hex(s[2], &error) << 16;
5604 color |= get_hex(s[3], &error) << 12;
5605 color |= get_hex(s[3], &error) << 8;
5606 color |= get_hex(s[4], &error) << 4;
5607 color |= get_hex(s[4], &error);
5608 } else if (len == 7) {
5609 outValue->dataType = outValue->TYPE_INT_COLOR_RGB8;
5610 color |= 0xFF000000;
5611 color |= get_hex(s[1], &error) << 20;
5612 color |= get_hex(s[2], &error) << 16;
5613 color |= get_hex(s[3], &error) << 12;
5614 color |= get_hex(s[4], &error) << 8;
5615 color |= get_hex(s[5], &error) << 4;
5616 color |= get_hex(s[6], &error);
5617 } else if (len == 9) {
5618 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB8;
5619 color |= get_hex(s[1], &error) << 28;
5620 color |= get_hex(s[2], &error) << 24;
5621 color |= get_hex(s[3], &error) << 20;
5622 color |= get_hex(s[4], &error) << 16;
5623 color |= get_hex(s[5], &error) << 12;
5624 color |= get_hex(s[6], &error) << 8;
5625 color |= get_hex(s[7], &error) << 4;
5626 color |= get_hex(s[8], &error);
5627 } else {
5628 error = true;
5629 }
5630 if (!error) {
5631 if ((attrType&ResTable_map::TYPE_COLOR) == 0) {
5632 if (!canStringCoerce) {
5633 if (accessor != NULL) {
5634 accessor->reportError(accessorCookie,
5635 "Color types not allowed");
5636 }
5637 return false;
5638 }
5639 } else {
5640 outValue->data = color;
5641 //printf("Color input=%s, output=0x%x\n", String8(s, len).string(), color);
5642 return true;
5643 }
5644 } else {
5645 if ((attrType&ResTable_map::TYPE_COLOR) != 0) {
5646 if (accessor != NULL) {
5647 accessor->reportError(accessorCookie, "Color value not valid --"
5648 " must be #rgb, #argb, #rrggbb, or #aarrggbb");
5649 }
5650 #if 0
5651 fprintf(stderr, "%s: Color ID %s value %s is not valid\n",
5652 "Resource File", //(const char*)in->getPrintableSource(),
5653 String8(*curTag).string(),
5654 String8(s, len).string());
5655 #endif
5656 return false;
5657 }
5658 }
5659 }
5660
5661 if (*s == '?') {
5662 outValue->dataType = outValue->TYPE_ATTRIBUTE;
5663
5664 // Note: we don't check attrType here because the reference can
5665 // be to any other type; we just need to count on the client making
5666 // sure the referenced type is correct.
5667
5668 //printf("Looking up attr: %s\n", String8(s, len).string());
5669
5670 static const String16 attr16("attr");
5671 String16 package, type, name;
5672 if (!expandResourceRef(s+1, len-1, &package, &type, &name,
5673 &attr16, defPackage, &errorMsg)) {
5674 if (accessor != NULL) {
5675 accessor->reportError(accessorCookie, errorMsg);
5676 }
5677 return false;
5678 }
5679
5680 //printf("Pkg: %s, Type: %s, Name: %s\n",
5681 // String8(package).string(), String8(type).string(),
5682 // String8(name).string());
5683 uint32_t specFlags = 0;
5684 uint32_t rid =
5685 identifierForName(name.string(), name.size(),
5686 type.string(), type.size(),
5687 package.string(), package.size(), &specFlags);
5688 if (rid != 0) {
5689 if (enforcePrivate) {
5690 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
5691 if (accessor != NULL) {
5692 accessor->reportError(accessorCookie, "Attribute is not public.");
5693 }
5694 return false;
5695 }
5696 }
5697
5698 if (accessor) {
5699 rid = Res_MAKEID(
5700 accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
5701 Res_GETTYPE(rid), Res_GETENTRY(rid));
5702 }
5703
5704 uint32_t packageId = Res_GETPACKAGE(rid) + 1;
5705 if (packageId != APP_PACKAGE_ID && packageId != SYS_PACKAGE_ID) {
5706 outValue->dataType = Res_value::TYPE_DYNAMIC_ATTRIBUTE;
5707 }
5708 outValue->data = rid;
5709 return true;
5710 }
5711
5712 if (accessor) {
5713 uint32_t rid = accessor->getCustomResource(package, type, name);
5714 if (rid != 0) {
5715 uint32_t packageId = Res_GETPACKAGE(rid) + 1;
5716 if (packageId == 0x00) {
5717 outValue->data = rid;
5718 outValue->dataType = Res_value::TYPE_DYNAMIC_ATTRIBUTE;
5719 return true;
5720 } else if (packageId == APP_PACKAGE_ID || packageId == SYS_PACKAGE_ID) {
5721 // We accept packageId's generated as 0x01 in order to support
5722 // building the android system resources
5723 outValue->data = rid;
5724 return true;
5725 }
5726 }
5727 }
5728
5729 if (accessor != NULL) {
5730 accessor->reportError(accessorCookie, "No resource found that matches the given name");
5731 }
5732 return false;
5733 }
5734
5735 if (stringToInt(s, len, outValue)) {
5736 if ((attrType&ResTable_map::TYPE_INTEGER) == 0) {
5737 // If this type does not allow integers, but does allow floats,
5738 // fall through on this error case because the float type should
5739 // be able to accept any integer value.
5740 if (!canStringCoerce && (attrType&ResTable_map::TYPE_FLOAT) == 0) {
5741 if (accessor != NULL) {
5742 accessor->reportError(accessorCookie, "Integer types not allowed");
5743 }
5744 return false;
5745 }
5746 } else {
5747 if (((int32_t)outValue->data) < ((int32_t)attrMin)
5748 || ((int32_t)outValue->data) > ((int32_t)attrMax)) {
5749 if (accessor != NULL) {
5750 accessor->reportError(accessorCookie, "Integer value out of range");
5751 }
5752 return false;
5753 }
5754 return true;
5755 }
5756 }
5757
5758 if (stringToFloat(s, len, outValue)) {
5759 if (outValue->dataType == Res_value::TYPE_DIMENSION) {
5760 if ((attrType&ResTable_map::TYPE_DIMENSION) != 0) {
5761 return true;
5762 }
5763 if (!canStringCoerce) {
5764 if (accessor != NULL) {
5765 accessor->reportError(accessorCookie, "Dimension types not allowed");
5766 }
5767 return false;
5768 }
5769 } else if (outValue->dataType == Res_value::TYPE_FRACTION) {
5770 if ((attrType&ResTable_map::TYPE_FRACTION) != 0) {
5771 return true;
5772 }
5773 if (!canStringCoerce) {
5774 if (accessor != NULL) {
5775 accessor->reportError(accessorCookie, "Fraction types not allowed");
5776 }
5777 return false;
5778 }
5779 } else if ((attrType&ResTable_map::TYPE_FLOAT) == 0) {
5780 if (!canStringCoerce) {
5781 if (accessor != NULL) {
5782 accessor->reportError(accessorCookie, "Float types not allowed");
5783 }
5784 return false;
5785 }
5786 } else {
5787 return true;
5788 }
5789 }
5790
5791 if (len == 4) {
5792 if ((s[0] == 't' || s[0] == 'T') &&
5793 (s[1] == 'r' || s[1] == 'R') &&
5794 (s[2] == 'u' || s[2] == 'U') &&
5795 (s[3] == 'e' || s[3] == 'E')) {
5796 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
5797 if (!canStringCoerce) {
5798 if (accessor != NULL) {
5799 accessor->reportError(accessorCookie, "Boolean types not allowed");
5800 }
5801 return false;
5802 }
5803 } else {
5804 outValue->dataType = outValue->TYPE_INT_BOOLEAN;
5805 outValue->data = (uint32_t)-1;
5806 return true;
5807 }
5808 }
5809 }
5810
5811 if (len == 5) {
5812 if ((s[0] == 'f' || s[0] == 'F') &&
5813 (s[1] == 'a' || s[1] == 'A') &&
5814 (s[2] == 'l' || s[2] == 'L') &&
5815 (s[3] == 's' || s[3] == 'S') &&
5816 (s[4] == 'e' || s[4] == 'E')) {
5817 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
5818 if (!canStringCoerce) {
5819 if (accessor != NULL) {
5820 accessor->reportError(accessorCookie, "Boolean types not allowed");
5821 }
5822 return false;
5823 }
5824 } else {
5825 outValue->dataType = outValue->TYPE_INT_BOOLEAN;
5826 outValue->data = 0;
5827 return true;
5828 }
5829 }
5830 }
5831
5832 if ((attrType&ResTable_map::TYPE_ENUM) != 0) {
5833 const ssize_t p = getResourcePackageIndex(attrID);
5834 const bag_entry* bag;
5835 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
5836 //printf("Got %d for enum\n", cnt);
5837 if (cnt >= 0) {
5838 resource_name rname;
5839 while (cnt > 0) {
5840 if (!Res_INTERNALID(bag->map.name.ident)) {
5841 //printf("Trying attr #%08x\n", bag->map.name.ident);
5842 if (getResourceName(bag->map.name.ident, false, &rname)) {
5843 #if 0
5844 printf("Matching %s against %s (0x%08x)\n",
5845 String8(s, len).string(),
5846 String8(rname.name, rname.nameLen).string(),
5847 bag->map.name.ident);
5848 #endif
5849 if (strzcmp16(s, len, rname.name, rname.nameLen) == 0) {
5850 outValue->dataType = bag->map.value.dataType;
5851 outValue->data = bag->map.value.data;
5852 unlockBag(bag);
5853 return true;
5854 }
5855 }
5856
5857 }
5858 bag++;
5859 cnt--;
5860 }
5861 unlockBag(bag);
5862 }
5863
5864 if (fromAccessor) {
5865 if (accessor->getAttributeEnum(attrID, s, len, outValue)) {
5866 return true;
5867 }
5868 }
5869 }
5870
5871 if ((attrType&ResTable_map::TYPE_FLAGS) != 0) {
5872 const ssize_t p = getResourcePackageIndex(attrID);
5873 const bag_entry* bag;
5874 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
5875 //printf("Got %d for flags\n", cnt);
5876 if (cnt >= 0) {
5877 bool failed = false;
5878 resource_name rname;
5879 outValue->dataType = Res_value::TYPE_INT_HEX;
5880 outValue->data = 0;
5881 const char16_t* end = s + len;
5882 const char16_t* pos = s;
5883 while (pos < end && !failed) {
5884 const char16_t* start = pos;
5885 pos++;
5886 while (pos < end && *pos != '|') {
5887 pos++;
5888 }
5889 //printf("Looking for: %s\n", String8(start, pos-start).string());
5890 const bag_entry* bagi = bag;
5891 ssize_t i;
5892 for (i=0; i<cnt; i++, bagi++) {
5893 if (!Res_INTERNALID(bagi->map.name.ident)) {
5894 //printf("Trying attr #%08x\n", bagi->map.name.ident);
5895 if (getResourceName(bagi->map.name.ident, false, &rname)) {
5896 #if 0
5897 printf("Matching %s against %s (0x%08x)\n",
5898 String8(start,pos-start).string(),
5899 String8(rname.name, rname.nameLen).string(),
5900 bagi->map.name.ident);
5901 #endif
5902 if (strzcmp16(start, pos-start, rname.name, rname.nameLen) == 0) {
5903 outValue->data |= bagi->map.value.data;
5904 break;
5905 }
5906 }
5907 }
5908 }
5909 if (i >= cnt) {
5910 // Didn't find this flag identifier.
5911 failed = true;
5912 }
5913 if (pos < end) {
5914 pos++;
5915 }
5916 }
5917 unlockBag(bag);
5918 if (!failed) {
5919 //printf("Final flag value: 0x%lx\n", outValue->data);
5920 return true;
5921 }
5922 }
5923
5924
5925 if (fromAccessor) {
5926 if (accessor->getAttributeFlags(attrID, s, len, outValue)) {
5927 //printf("Final flag value: 0x%lx\n", outValue->data);
5928 return true;
5929 }
5930 }
5931 }
5932
5933 if ((attrType&ResTable_map::TYPE_STRING) == 0) {
5934 if (accessor != NULL) {
5935 accessor->reportError(accessorCookie, "String types not allowed");
5936 }
5937 return false;
5938 }
5939
5940 // Generic string handling...
5941 outValue->dataType = outValue->TYPE_STRING;
5942 if (outString) {
5943 bool failed = collectString(outString, s, len, preserveSpaces, &errorMsg);
5944 if (accessor != NULL) {
5945 accessor->reportError(accessorCookie, errorMsg);
5946 }
5947 return failed;
5948 }
5949
5950 return true;
5951 }
5952
collectString(String16 * outString,const char16_t * s,size_t len,bool preserveSpaces,const char ** outErrorMsg,bool append)5953 bool ResTable::collectString(String16* outString,
5954 const char16_t* s, size_t len,
5955 bool preserveSpaces,
5956 const char** outErrorMsg,
5957 bool append)
5958 {
5959 String16 tmp;
5960
5961 char quoted = 0;
5962 const char16_t* p = s;
5963 while (p < (s+len)) {
5964 while (p < (s+len)) {
5965 const char16_t c = *p;
5966 if (c == '\\') {
5967 break;
5968 }
5969 if (!preserveSpaces) {
5970 if (quoted == 0 && isspace16(c)
5971 && (c != ' ' || isspace16(*(p+1)))) {
5972 break;
5973 }
5974 if (c == '"' && (quoted == 0 || quoted == '"')) {
5975 break;
5976 }
5977 if (c == '\'' && (quoted == 0 || quoted == '\'')) {
5978 /*
5979 * In practice, when people write ' instead of \'
5980 * in a string, they are doing it by accident
5981 * instead of really meaning to use ' as a quoting
5982 * character. Warn them so they don't lose it.
5983 */
5984 if (outErrorMsg) {
5985 *outErrorMsg = "Apostrophe not preceded by \\";
5986 }
5987 return false;
5988 }
5989 }
5990 p++;
5991 }
5992 if (p < (s+len)) {
5993 if (p > s) {
5994 tmp.append(String16(s, p-s));
5995 }
5996 if (!preserveSpaces && (*p == '"' || *p == '\'')) {
5997 if (quoted == 0) {
5998 quoted = *p;
5999 } else {
6000 quoted = 0;
6001 }
6002 p++;
6003 } else if (!preserveSpaces && isspace16(*p)) {
6004 // Space outside of a quote -- consume all spaces and
6005 // leave a single plain space char.
6006 tmp.append(String16(" "));
6007 p++;
6008 while (p < (s+len) && isspace16(*p)) {
6009 p++;
6010 }
6011 } else if (*p == '\\') {
6012 p++;
6013 if (p < (s+len)) {
6014 switch (*p) {
6015 case 't':
6016 tmp.append(String16("\t"));
6017 break;
6018 case 'n':
6019 tmp.append(String16("\n"));
6020 break;
6021 case '#':
6022 tmp.append(String16("#"));
6023 break;
6024 case '@':
6025 tmp.append(String16("@"));
6026 break;
6027 case '?':
6028 tmp.append(String16("?"));
6029 break;
6030 case '"':
6031 tmp.append(String16("\""));
6032 break;
6033 case '\'':
6034 tmp.append(String16("'"));
6035 break;
6036 case '\\':
6037 tmp.append(String16("\\"));
6038 break;
6039 case 'u':
6040 {
6041 char16_t chr = 0;
6042 int i = 0;
6043 while (i < 4 && p[1] != 0) {
6044 p++;
6045 i++;
6046 int c;
6047 if (*p >= '0' && *p <= '9') {
6048 c = *p - '0';
6049 } else if (*p >= 'a' && *p <= 'f') {
6050 c = *p - 'a' + 10;
6051 } else if (*p >= 'A' && *p <= 'F') {
6052 c = *p - 'A' + 10;
6053 } else {
6054 if (outErrorMsg) {
6055 *outErrorMsg = "Bad character in \\u unicode escape sequence";
6056 }
6057 return false;
6058 }
6059 chr = (chr<<4) | c;
6060 }
6061 tmp.append(String16(&chr, 1));
6062 } break;
6063 default:
6064 // ignore unknown escape chars.
6065 break;
6066 }
6067 p++;
6068 }
6069 }
6070 len -= (p-s);
6071 s = p;
6072 }
6073 }
6074
6075 if (tmp.size() != 0) {
6076 if (len > 0) {
6077 tmp.append(String16(s, len));
6078 }
6079 if (append) {
6080 outString->append(tmp);
6081 } else {
6082 outString->setTo(tmp);
6083 }
6084 } else {
6085 if (append) {
6086 outString->append(String16(s, len));
6087 } else {
6088 outString->setTo(s, len);
6089 }
6090 }
6091
6092 return true;
6093 }
6094
getBasePackageCount() const6095 size_t ResTable::getBasePackageCount() const
6096 {
6097 if (mError != NO_ERROR) {
6098 return 0;
6099 }
6100 return mPackageGroups.size();
6101 }
6102
getBasePackageName(size_t idx) const6103 const String16 ResTable::getBasePackageName(size_t idx) const
6104 {
6105 if (mError != NO_ERROR) {
6106 return String16();
6107 }
6108 LOG_FATAL_IF(idx >= mPackageGroups.size(),
6109 "Requested package index %d past package count %d",
6110 (int)idx, (int)mPackageGroups.size());
6111 return mPackageGroups[idx]->name;
6112 }
6113
getBasePackageId(size_t idx) const6114 uint32_t ResTable::getBasePackageId(size_t idx) const
6115 {
6116 if (mError != NO_ERROR) {
6117 return 0;
6118 }
6119 LOG_FATAL_IF(idx >= mPackageGroups.size(),
6120 "Requested package index %d past package count %d",
6121 (int)idx, (int)mPackageGroups.size());
6122 return mPackageGroups[idx]->id;
6123 }
6124
getLastTypeIdForPackage(size_t idx) const6125 uint32_t ResTable::getLastTypeIdForPackage(size_t idx) const
6126 {
6127 if (mError != NO_ERROR) {
6128 return 0;
6129 }
6130 LOG_FATAL_IF(idx >= mPackageGroups.size(),
6131 "Requested package index %d past package count %d",
6132 (int)idx, (int)mPackageGroups.size());
6133 const PackageGroup* const group = mPackageGroups[idx];
6134 return group->largestTypeId;
6135 }
6136
getTableCount() const6137 size_t ResTable::getTableCount() const
6138 {
6139 return mHeaders.size();
6140 }
6141
getTableStringBlock(size_t index) const6142 const ResStringPool* ResTable::getTableStringBlock(size_t index) const
6143 {
6144 return &mHeaders[index]->values;
6145 }
6146
getTableCookie(size_t index) const6147 int32_t ResTable::getTableCookie(size_t index) const
6148 {
6149 return mHeaders[index]->cookie;
6150 }
6151
getDynamicRefTableForCookie(int32_t cookie) const6152 const DynamicRefTable* ResTable::getDynamicRefTableForCookie(int32_t cookie) const
6153 {
6154 const size_t N = mPackageGroups.size();
6155 for (size_t i = 0; i < N; i++) {
6156 const PackageGroup* pg = mPackageGroups[i];
6157 size_t M = pg->packages.size();
6158 for (size_t j = 0; j < M; j++) {
6159 if (pg->packages[j]->header->cookie == cookie) {
6160 return &pg->dynamicRefTable;
6161 }
6162 }
6163 }
6164 return NULL;
6165 }
6166
compareResTableConfig(const ResTable_config & a,const ResTable_config & b)6167 static bool compareResTableConfig(const ResTable_config& a, const ResTable_config& b) {
6168 return a.compare(b) < 0;
6169 }
6170
6171 template <typename Func>
forEachConfiguration(bool ignoreMipmap,bool ignoreAndroidPackage,bool includeSystemConfigs,const Func & f) const6172 void ResTable::forEachConfiguration(bool ignoreMipmap, bool ignoreAndroidPackage,
6173 bool includeSystemConfigs, const Func& f) const {
6174 const size_t packageCount = mPackageGroups.size();
6175 const String16 android("android");
6176 for (size_t i = 0; i < packageCount; i++) {
6177 const PackageGroup* packageGroup = mPackageGroups[i];
6178 if (ignoreAndroidPackage && android == packageGroup->name) {
6179 continue;
6180 }
6181 if (!includeSystemConfigs && packageGroup->isSystemAsset) {
6182 continue;
6183 }
6184 const size_t typeCount = packageGroup->types.size();
6185 for (size_t j = 0; j < typeCount; j++) {
6186 const TypeList& typeList = packageGroup->types[j];
6187 const size_t numTypes = typeList.size();
6188 for (size_t k = 0; k < numTypes; k++) {
6189 const Type* type = typeList[k];
6190 const ResStringPool& typeStrings = type->package->typeStrings;
6191 if (ignoreMipmap && typeStrings.string8ObjectAt(
6192 type->typeSpec->id - 1) == "mipmap") {
6193 continue;
6194 }
6195
6196 const size_t numConfigs = type->configs.size();
6197 for (size_t m = 0; m < numConfigs; m++) {
6198 const ResTable_type* config = type->configs[m];
6199 ResTable_config cfg;
6200 memset(&cfg, 0, sizeof(ResTable_config));
6201 cfg.copyFromDtoH(config->config);
6202
6203 f(cfg);
6204 }
6205 }
6206 }
6207 }
6208 }
6209
getConfigurations(Vector<ResTable_config> * configs,bool ignoreMipmap,bool ignoreAndroidPackage,bool includeSystemConfigs) const6210 void ResTable::getConfigurations(Vector<ResTable_config>* configs, bool ignoreMipmap,
6211 bool ignoreAndroidPackage, bool includeSystemConfigs) const {
6212 auto func = [&](const ResTable_config& cfg) {
6213 const auto beginIter = configs->begin();
6214 const auto endIter = configs->end();
6215
6216 auto iter = std::lower_bound(beginIter, endIter, cfg, compareResTableConfig);
6217 if (iter == endIter || iter->compare(cfg) != 0) {
6218 configs->insertAt(cfg, std::distance(beginIter, iter));
6219 }
6220 };
6221 forEachConfiguration(ignoreMipmap, ignoreAndroidPackage, includeSystemConfigs, func);
6222 }
6223
compareString8AndCString(const String8 & str,const char * cStr)6224 static bool compareString8AndCString(const String8& str, const char* cStr) {
6225 return strcmp(str.string(), cStr) < 0;
6226 }
6227
getLocales(Vector<String8> * locales,bool includeSystemLocales,bool mergeEquivalentLangs) const6228 void ResTable::getLocales(Vector<String8>* locales, bool includeSystemLocales,
6229 bool mergeEquivalentLangs) const {
6230 char locale[RESTABLE_MAX_LOCALE_LEN];
6231
6232 forEachConfiguration(false, false, includeSystemLocales, [&](const ResTable_config& cfg) {
6233 cfg.getBcp47Locale(locale, mergeEquivalentLangs /* canonicalize if merging */);
6234
6235 const auto beginIter = locales->begin();
6236 const auto endIter = locales->end();
6237
6238 auto iter = std::lower_bound(beginIter, endIter, locale, compareString8AndCString);
6239 if (iter == endIter || strcmp(iter->string(), locale) != 0) {
6240 locales->insertAt(String8(locale), std::distance(beginIter, iter));
6241 }
6242 });
6243 }
6244
StringPoolRef(const ResStringPool * pool,uint32_t index)6245 StringPoolRef::StringPoolRef(const ResStringPool* pool, uint32_t index)
6246 : mPool(pool), mIndex(index) {}
6247
string8(size_t * outLen) const6248 const char* StringPoolRef::string8(size_t* outLen) const {
6249 if (mPool != NULL) {
6250 return mPool->string8At(mIndex, outLen);
6251 }
6252 if (outLen != NULL) {
6253 *outLen = 0;
6254 }
6255 return NULL;
6256 }
6257
string16(size_t * outLen) const6258 const char16_t* StringPoolRef::string16(size_t* outLen) const {
6259 if (mPool != NULL) {
6260 return mPool->stringAt(mIndex, outLen);
6261 }
6262 if (outLen != NULL) {
6263 *outLen = 0;
6264 }
6265 return NULL;
6266 }
6267
getResourceFlags(uint32_t resID,uint32_t * outFlags) const6268 bool ResTable::getResourceFlags(uint32_t resID, uint32_t* outFlags) const {
6269 if (mError != NO_ERROR) {
6270 return false;
6271 }
6272
6273 const ssize_t p = getResourcePackageIndex(resID);
6274 const int t = Res_GETTYPE(resID);
6275 const int e = Res_GETENTRY(resID);
6276
6277 if (p < 0) {
6278 if (Res_GETPACKAGE(resID)+1 == 0) {
6279 ALOGW("No package identifier when getting flags for resource number 0x%08x", resID);
6280 } else {
6281 ALOGW("No known package when getting flags for resource number 0x%08x", resID);
6282 }
6283 return false;
6284 }
6285 if (t < 0) {
6286 ALOGW("No type identifier when getting flags for resource number 0x%08x", resID);
6287 return false;
6288 }
6289
6290 const PackageGroup* const grp = mPackageGroups[p];
6291 if (grp == NULL) {
6292 ALOGW("Bad identifier when getting flags for resource number 0x%08x", resID);
6293 return false;
6294 }
6295
6296 Entry entry;
6297 status_t err = getEntry(grp, t, e, NULL, &entry);
6298 if (err != NO_ERROR) {
6299 return false;
6300 }
6301
6302 *outFlags = entry.specFlags;
6303 return true;
6304 }
6305
isPackageDynamic(uint8_t packageID) const6306 bool ResTable::isPackageDynamic(uint8_t packageID) const {
6307 if (mError != NO_ERROR) {
6308 return false;
6309 }
6310 if (packageID == 0) {
6311 ALOGW("Invalid package number 0x%08x", packageID);
6312 return false;
6313 }
6314
6315 const ssize_t p = getResourcePackageIndexFromPackage(packageID);
6316
6317 if (p < 0) {
6318 ALOGW("Unknown package number 0x%08x", packageID);
6319 return false;
6320 }
6321
6322 const PackageGroup* const grp = mPackageGroups[p];
6323 if (grp == NULL) {
6324 ALOGW("Bad identifier for package number 0x%08x", packageID);
6325 return false;
6326 }
6327
6328 return grp->isDynamic;
6329 }
6330
isResourceDynamic(uint32_t resID) const6331 bool ResTable::isResourceDynamic(uint32_t resID) const {
6332 if (mError != NO_ERROR) {
6333 return false;
6334 }
6335
6336 const ssize_t p = getResourcePackageIndex(resID);
6337 const int t = Res_GETTYPE(resID);
6338 const int e = Res_GETENTRY(resID);
6339
6340 if (p < 0) {
6341 if (Res_GETPACKAGE(resID)+1 == 0) {
6342 ALOGW("No package identifier for resource number 0x%08x", resID);
6343 } else {
6344 ALOGW("No known package for resource number 0x%08x", resID);
6345 }
6346 return false;
6347 }
6348 if (t < 0) {
6349 ALOGW("No type identifier for resource number 0x%08x", resID);
6350 return false;
6351 }
6352
6353 const PackageGroup* const grp = mPackageGroups[p];
6354 if (grp == NULL) {
6355 ALOGW("Bad identifier for resource number 0x%08x", resID);
6356 return false;
6357 }
6358
6359 Entry entry;
6360 status_t err = getEntry(grp, t, e, NULL, &entry);
6361 if (err != NO_ERROR) {
6362 return false;
6363 }
6364
6365 return grp->isDynamic;
6366 }
6367
keyCompare(const ResTable_sparseTypeEntry & entry,uint16_t entryIdx)6368 static bool keyCompare(const ResTable_sparseTypeEntry& entry , uint16_t entryIdx) {
6369 return dtohs(entry.idx) < entryIdx;
6370 }
6371
getEntry(const PackageGroup * packageGroup,int typeIndex,int entryIndex,const ResTable_config * config,Entry * outEntry) const6372 status_t ResTable::getEntry(
6373 const PackageGroup* packageGroup, int typeIndex, int entryIndex,
6374 const ResTable_config* config,
6375 Entry* outEntry) const
6376 {
6377 const TypeList& typeList = packageGroup->types[typeIndex];
6378 if (typeList.isEmpty()) {
6379 ALOGV("Skipping entry type index 0x%02x because type is NULL!\n", typeIndex);
6380 return BAD_TYPE;
6381 }
6382
6383 const ResTable_type* bestType = NULL;
6384 uint32_t bestOffset = ResTable_type::NO_ENTRY;
6385 const Package* bestPackage = NULL;
6386 uint32_t specFlags = 0;
6387 uint8_t actualTypeIndex = typeIndex;
6388 ResTable_config bestConfig;
6389 memset(&bestConfig, 0, sizeof(bestConfig));
6390
6391 // Iterate over the Types of each package.
6392 const size_t typeCount = typeList.size();
6393 for (size_t i = 0; i < typeCount; i++) {
6394 const Type* const typeSpec = typeList[i];
6395
6396 int realEntryIndex = entryIndex;
6397 int realTypeIndex = typeIndex;
6398 bool currentTypeIsOverlay = false;
6399
6400 // Runtime overlay packages provide a mapping of app resource
6401 // ID to package resource ID.
6402 if (typeSpec->idmapEntries.hasEntries()) {
6403 uint16_t overlayEntryIndex;
6404 if (typeSpec->idmapEntries.lookup(entryIndex, &overlayEntryIndex) != NO_ERROR) {
6405 // No such mapping exists
6406 continue;
6407 }
6408 realEntryIndex = overlayEntryIndex;
6409 realTypeIndex = typeSpec->idmapEntries.overlayTypeId() - 1;
6410 currentTypeIsOverlay = true;
6411 }
6412
6413 // Check that the entry idx is within range of the declared entry count (ResTable_typeSpec).
6414 // Particular types (ResTable_type) may be encoded with sparse entries, and so their
6415 // entryCount do not need to match.
6416 if (static_cast<size_t>(realEntryIndex) >= typeSpec->entryCount) {
6417 ALOGW("For resource 0x%08x, entry index(%d) is beyond type entryCount(%d)",
6418 Res_MAKEID(packageGroup->id - 1, typeIndex, entryIndex),
6419 entryIndex, static_cast<int>(typeSpec->entryCount));
6420 // We should normally abort here, but some legacy apps declare
6421 // resources in the 'android' package (old bug in AAPT).
6422 continue;
6423 }
6424
6425 // Aggregate all the flags for each package that defines this entry.
6426 if (typeSpec->typeSpecFlags != NULL) {
6427 specFlags |= dtohl(typeSpec->typeSpecFlags[realEntryIndex]);
6428 } else {
6429 specFlags = -1;
6430 }
6431
6432 const Vector<const ResTable_type*>* candidateConfigs = &typeSpec->configs;
6433
6434 std::shared_ptr<Vector<const ResTable_type*>> filteredConfigs;
6435 if (config && memcmp(&mParams, config, sizeof(mParams)) == 0) {
6436 // Grab the lock first so we can safely get the current filtered list.
6437 AutoMutex _lock(mFilteredConfigLock);
6438
6439 // This configuration is equal to the one we have previously cached for,
6440 // so use the filtered configs.
6441
6442 const TypeCacheEntry& cacheEntry = packageGroup->typeCacheEntries[typeIndex];
6443 if (i < cacheEntry.filteredConfigs.size()) {
6444 if (cacheEntry.filteredConfigs[i]) {
6445 // Grab a reference to the shared_ptr so it doesn't get destroyed while
6446 // going through this list.
6447 filteredConfigs = cacheEntry.filteredConfigs[i];
6448
6449 // Use this filtered list.
6450 candidateConfigs = filteredConfigs.get();
6451 }
6452 }
6453 }
6454
6455 const size_t numConfigs = candidateConfigs->size();
6456 for (size_t c = 0; c < numConfigs; c++) {
6457 const ResTable_type* const thisType = candidateConfigs->itemAt(c);
6458 if (thisType == NULL) {
6459 continue;
6460 }
6461
6462 ResTable_config thisConfig;
6463 thisConfig.copyFromDtoH(thisType->config);
6464
6465 // Check to make sure this one is valid for the current parameters.
6466 if (config != NULL && !thisConfig.match(*config)) {
6467 continue;
6468 }
6469
6470 const uint32_t* const eindex = reinterpret_cast<const uint32_t*>(
6471 reinterpret_cast<const uint8_t*>(thisType) + dtohs(thisType->header.headerSize));
6472
6473 uint32_t thisOffset;
6474
6475 // Check if there is the desired entry in this type.
6476 if (thisType->flags & ResTable_type::FLAG_SPARSE) {
6477 // This is encoded as a sparse map, so perform a binary search.
6478 const ResTable_sparseTypeEntry* sparseIndices =
6479 reinterpret_cast<const ResTable_sparseTypeEntry*>(eindex);
6480 const ResTable_sparseTypeEntry* result = std::lower_bound(
6481 sparseIndices, sparseIndices + dtohl(thisType->entryCount), realEntryIndex,
6482 keyCompare);
6483 if (result == sparseIndices + dtohl(thisType->entryCount)
6484 || dtohs(result->idx) != realEntryIndex) {
6485 // No entry found.
6486 continue;
6487 }
6488
6489 // Extract the offset from the entry. Each offset must be a multiple of 4
6490 // so we store it as the real offset divided by 4.
6491 thisOffset = dtohs(result->offset) * 4u;
6492 } else {
6493 if (static_cast<uint32_t>(realEntryIndex) >= dtohl(thisType->entryCount)) {
6494 // Entry does not exist.
6495 continue;
6496 }
6497
6498 thisOffset = dtohl(eindex[realEntryIndex]);
6499 }
6500
6501 if (thisOffset == ResTable_type::NO_ENTRY) {
6502 // There is no entry for this index and configuration.
6503 continue;
6504 }
6505
6506 if (bestType != NULL) {
6507 // Check if this one is less specific than the last found. If so,
6508 // we will skip it. We check starting with things we most care
6509 // about to those we least care about.
6510 if (!thisConfig.isBetterThan(bestConfig, config)) {
6511 if (!currentTypeIsOverlay || thisConfig.compare(bestConfig) != 0) {
6512 continue;
6513 }
6514 }
6515 }
6516
6517 bestType = thisType;
6518 bestOffset = thisOffset;
6519 bestConfig = thisConfig;
6520 bestPackage = typeSpec->package;
6521 actualTypeIndex = realTypeIndex;
6522
6523 // If no config was specified, any type will do, so skip
6524 if (config == NULL) {
6525 break;
6526 }
6527 }
6528 }
6529
6530 if (bestType == NULL) {
6531 return BAD_INDEX;
6532 }
6533
6534 bestOffset += dtohl(bestType->entriesStart);
6535
6536 if (bestOffset > (dtohl(bestType->header.size)-sizeof(ResTable_entry))) {
6537 ALOGW("ResTable_entry at 0x%x is beyond type chunk data 0x%x",
6538 bestOffset, dtohl(bestType->header.size));
6539 return BAD_TYPE;
6540 }
6541 if ((bestOffset & 0x3) != 0) {
6542 ALOGW("ResTable_entry at 0x%x is not on an integer boundary", bestOffset);
6543 return BAD_TYPE;
6544 }
6545
6546 const ResTable_entry* const entry = reinterpret_cast<const ResTable_entry*>(
6547 reinterpret_cast<const uint8_t*>(bestType) + bestOffset);
6548 if (dtohs(entry->size) < sizeof(*entry)) {
6549 ALOGW("ResTable_entry size 0x%x is too small", dtohs(entry->size));
6550 return BAD_TYPE;
6551 }
6552
6553 if (outEntry != NULL) {
6554 outEntry->entry = entry;
6555 outEntry->config = bestConfig;
6556 outEntry->type = bestType;
6557 outEntry->specFlags = specFlags;
6558 outEntry->package = bestPackage;
6559 outEntry->typeStr = StringPoolRef(&bestPackage->typeStrings, actualTypeIndex - bestPackage->typeIdOffset);
6560 outEntry->keyStr = StringPoolRef(&bestPackage->keyStrings, dtohl(entry->key.index));
6561 }
6562 return NO_ERROR;
6563 }
6564
parsePackage(const ResTable_package * const pkg,const Header * const header,bool appAsLib,bool isSystemAsset)6565 status_t ResTable::parsePackage(const ResTable_package* const pkg,
6566 const Header* const header, bool appAsLib, bool isSystemAsset)
6567 {
6568 const uint8_t* base = (const uint8_t*)pkg;
6569 status_t err = validate_chunk(&pkg->header, sizeof(*pkg) - sizeof(pkg->typeIdOffset),
6570 header->dataEnd, "ResTable_package");
6571 if (err != NO_ERROR) {
6572 return (mError=err);
6573 }
6574
6575 const uint32_t pkgSize = dtohl(pkg->header.size);
6576
6577 if (dtohl(pkg->typeStrings) >= pkgSize) {
6578 ALOGW("ResTable_package type strings at 0x%x are past chunk size 0x%x.",
6579 dtohl(pkg->typeStrings), pkgSize);
6580 return (mError=BAD_TYPE);
6581 }
6582 if ((dtohl(pkg->typeStrings)&0x3) != 0) {
6583 ALOGW("ResTable_package type strings at 0x%x is not on an integer boundary.",
6584 dtohl(pkg->typeStrings));
6585 return (mError=BAD_TYPE);
6586 }
6587 if (dtohl(pkg->keyStrings) >= pkgSize) {
6588 ALOGW("ResTable_package key strings at 0x%x are past chunk size 0x%x.",
6589 dtohl(pkg->keyStrings), pkgSize);
6590 return (mError=BAD_TYPE);
6591 }
6592 if ((dtohl(pkg->keyStrings)&0x3) != 0) {
6593 ALOGW("ResTable_package key strings at 0x%x is not on an integer boundary.",
6594 dtohl(pkg->keyStrings));
6595 return (mError=BAD_TYPE);
6596 }
6597
6598 uint32_t id = dtohl(pkg->id);
6599 KeyedVector<uint8_t, IdmapEntries> idmapEntries;
6600
6601 if (header->resourceIDMap != NULL) {
6602 uint8_t targetPackageId = 0;
6603 status_t err = parseIdmap(header->resourceIDMap, header->resourceIDMapSize, &targetPackageId, &idmapEntries);
6604 if (err != NO_ERROR) {
6605 ALOGW("Overlay is broken");
6606 return (mError=err);
6607 }
6608 id = targetPackageId;
6609 }
6610
6611 bool isDynamic = false;
6612 if (id >= 256) {
6613 LOG_ALWAYS_FATAL("Package id out of range");
6614 return NO_ERROR;
6615 } else if (id == 0 || (id == 0x7f && appAsLib) || isSystemAsset) {
6616 // This is a library or a system asset, so assign an ID
6617 id = mNextPackageId++;
6618 isDynamic = true;
6619 }
6620
6621 PackageGroup* group = NULL;
6622 Package* package = new Package(this, header, pkg);
6623 if (package == NULL) {
6624 return (mError=NO_MEMORY);
6625 }
6626
6627 err = package->typeStrings.setTo(base+dtohl(pkg->typeStrings),
6628 header->dataEnd-(base+dtohl(pkg->typeStrings)));
6629 if (err != NO_ERROR) {
6630 delete group;
6631 delete package;
6632 return (mError=err);
6633 }
6634
6635 err = package->keyStrings.setTo(base+dtohl(pkg->keyStrings),
6636 header->dataEnd-(base+dtohl(pkg->keyStrings)));
6637 if (err != NO_ERROR) {
6638 delete group;
6639 delete package;
6640 return (mError=err);
6641 }
6642
6643 size_t idx = mPackageMap[id];
6644 if (idx == 0) {
6645 idx = mPackageGroups.size() + 1;
6646 char16_t tmpName[sizeof(pkg->name)/sizeof(pkg->name[0])];
6647 strcpy16_dtoh(tmpName, pkg->name, sizeof(pkg->name)/sizeof(pkg->name[0]));
6648 group = new PackageGroup(this, String16(tmpName), id, appAsLib, isSystemAsset, isDynamic);
6649 if (group == NULL) {
6650 delete package;
6651 return (mError=NO_MEMORY);
6652 }
6653
6654 err = mPackageGroups.add(group);
6655 if (err < NO_ERROR) {
6656 return (mError=err);
6657 }
6658
6659 mPackageMap[id] = static_cast<uint8_t>(idx);
6660
6661 // Find all packages that reference this package
6662 size_t N = mPackageGroups.size();
6663 for (size_t i = 0; i < N; i++) {
6664 mPackageGroups[i]->dynamicRefTable.addMapping(
6665 group->name, static_cast<uint8_t>(group->id));
6666 }
6667 } else {
6668 group = mPackageGroups.itemAt(idx - 1);
6669 if (group == NULL) {
6670 return (mError=UNKNOWN_ERROR);
6671 }
6672 }
6673
6674 err = group->packages.add(package);
6675 if (err < NO_ERROR) {
6676 return (mError=err);
6677 }
6678
6679 // Iterate through all chunks.
6680 const ResChunk_header* chunk =
6681 (const ResChunk_header*)(((const uint8_t*)pkg)
6682 + dtohs(pkg->header.headerSize));
6683 const uint8_t* endPos = ((const uint8_t*)pkg) + dtohs(pkg->header.size);
6684 while (((const uint8_t*)chunk) <= (endPos-sizeof(ResChunk_header)) &&
6685 ((const uint8_t*)chunk) <= (endPos-dtohl(chunk->size))) {
6686 if (kDebugTableNoisy) {
6687 ALOGV("PackageChunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n",
6688 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
6689 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)));
6690 }
6691 const size_t csize = dtohl(chunk->size);
6692 const uint16_t ctype = dtohs(chunk->type);
6693 if (ctype == RES_TABLE_TYPE_SPEC_TYPE) {
6694 const ResTable_typeSpec* typeSpec = (const ResTable_typeSpec*)(chunk);
6695 err = validate_chunk(&typeSpec->header, sizeof(*typeSpec),
6696 endPos, "ResTable_typeSpec");
6697 if (err != NO_ERROR) {
6698 return (mError=err);
6699 }
6700
6701 const size_t typeSpecSize = dtohl(typeSpec->header.size);
6702 const size_t newEntryCount = dtohl(typeSpec->entryCount);
6703
6704 if (kDebugLoadTableNoisy) {
6705 ALOGI("TypeSpec off %p: type=0x%x, headerSize=0x%x, size=%p\n",
6706 (void*)(base-(const uint8_t*)chunk),
6707 dtohs(typeSpec->header.type),
6708 dtohs(typeSpec->header.headerSize),
6709 (void*)typeSpecSize);
6710 }
6711 // look for block overrun or int overflow when multiplying by 4
6712 if ((dtohl(typeSpec->entryCount) > (INT32_MAX/sizeof(uint32_t))
6713 || dtohs(typeSpec->header.headerSize)+(sizeof(uint32_t)*newEntryCount)
6714 > typeSpecSize)) {
6715 ALOGW("ResTable_typeSpec entry index to %p extends beyond chunk end %p.",
6716 (void*)(dtohs(typeSpec->header.headerSize) + (sizeof(uint32_t)*newEntryCount)),
6717 (void*)typeSpecSize);
6718 return (mError=BAD_TYPE);
6719 }
6720
6721 if (typeSpec->id == 0) {
6722 ALOGW("ResTable_type has an id of 0.");
6723 return (mError=BAD_TYPE);
6724 }
6725
6726 if (newEntryCount > 0) {
6727 bool addToType = true;
6728 uint8_t typeIndex = typeSpec->id - 1;
6729 ssize_t idmapIndex = idmapEntries.indexOfKey(typeSpec->id);
6730 if (idmapIndex >= 0) {
6731 typeIndex = idmapEntries[idmapIndex].targetTypeId() - 1;
6732 } else if (header->resourceIDMap != NULL) {
6733 // This is an overlay, but the types in this overlay are not
6734 // overlaying anything according to the idmap. We can skip these
6735 // as they will otherwise conflict with the other resources in the package
6736 // without a mapping.
6737 addToType = false;
6738 }
6739
6740 if (addToType) {
6741 TypeList& typeList = group->types.editItemAt(typeIndex);
6742 if (!typeList.isEmpty()) {
6743 const Type* existingType = typeList[0];
6744 if (existingType->entryCount != newEntryCount && idmapIndex < 0) {
6745 ALOGW("ResTable_typeSpec entry count inconsistent: "
6746 "given %d, previously %d",
6747 (int) newEntryCount, (int) existingType->entryCount);
6748 // We should normally abort here, but some legacy apps declare
6749 // resources in the 'android' package (old bug in AAPT).
6750 }
6751 }
6752
6753 Type* t = new Type(header, package, newEntryCount);
6754 t->typeSpec = typeSpec;
6755 t->typeSpecFlags = (const uint32_t*)(
6756 ((const uint8_t*)typeSpec) + dtohs(typeSpec->header.headerSize));
6757 if (idmapIndex >= 0) {
6758 t->idmapEntries = idmapEntries[idmapIndex];
6759 }
6760 typeList.add(t);
6761 group->largestTypeId = max(group->largestTypeId, typeSpec->id);
6762 }
6763 } else {
6764 ALOGV("Skipping empty ResTable_typeSpec for type %d", typeSpec->id);
6765 }
6766
6767 } else if (ctype == RES_TABLE_TYPE_TYPE) {
6768 const ResTable_type* type = (const ResTable_type*)(chunk);
6769 err = validate_chunk(&type->header, sizeof(*type)-sizeof(ResTable_config)+4,
6770 endPos, "ResTable_type");
6771 if (err != NO_ERROR) {
6772 return (mError=err);
6773 }
6774
6775 const uint32_t typeSize = dtohl(type->header.size);
6776 const size_t newEntryCount = dtohl(type->entryCount);
6777
6778 if (kDebugLoadTableNoisy) {
6779 printf("Type off %p: type=0x%x, headerSize=0x%x, size=%u\n",
6780 (void*)(base-(const uint8_t*)chunk),
6781 dtohs(type->header.type),
6782 dtohs(type->header.headerSize),
6783 typeSize);
6784 }
6785 if (dtohs(type->header.headerSize)+(sizeof(uint32_t)*newEntryCount) > typeSize) {
6786 ALOGW("ResTable_type entry index to %p extends beyond chunk end 0x%x.",
6787 (void*)(dtohs(type->header.headerSize) + (sizeof(uint32_t)*newEntryCount)),
6788 typeSize);
6789 return (mError=BAD_TYPE);
6790 }
6791
6792 if (newEntryCount != 0
6793 && dtohl(type->entriesStart) > (typeSize-sizeof(ResTable_entry))) {
6794 ALOGW("ResTable_type entriesStart at 0x%x extends beyond chunk end 0x%x.",
6795 dtohl(type->entriesStart), typeSize);
6796 return (mError=BAD_TYPE);
6797 }
6798
6799 if (type->id == 0) {
6800 ALOGW("ResTable_type has an id of 0.");
6801 return (mError=BAD_TYPE);
6802 }
6803
6804 if (newEntryCount > 0) {
6805 bool addToType = true;
6806 uint8_t typeIndex = type->id - 1;
6807 ssize_t idmapIndex = idmapEntries.indexOfKey(type->id);
6808 if (idmapIndex >= 0) {
6809 typeIndex = idmapEntries[idmapIndex].targetTypeId() - 1;
6810 } else if (header->resourceIDMap != NULL) {
6811 // This is an overlay, but the types in this overlay are not
6812 // overlaying anything according to the idmap. We can skip these
6813 // as they will otherwise conflict with the other resources in the package
6814 // without a mapping.
6815 addToType = false;
6816 }
6817
6818 if (addToType) {
6819 TypeList& typeList = group->types.editItemAt(typeIndex);
6820 if (typeList.isEmpty()) {
6821 ALOGE("No TypeSpec for type %d", type->id);
6822 return (mError=BAD_TYPE);
6823 }
6824
6825 Type* t = typeList.editItemAt(typeList.size() - 1);
6826 if (t->package != package) {
6827 ALOGE("No TypeSpec for type %d", type->id);
6828 return (mError=BAD_TYPE);
6829 }
6830
6831 t->configs.add(type);
6832
6833 if (kDebugTableGetEntry) {
6834 ResTable_config thisConfig;
6835 thisConfig.copyFromDtoH(type->config);
6836 ALOGI("Adding config to type %d: %s\n", type->id,
6837 thisConfig.toString().string());
6838 }
6839 }
6840 } else {
6841 ALOGV("Skipping empty ResTable_type for type %d", type->id);
6842 }
6843
6844 } else if (ctype == RES_TABLE_LIBRARY_TYPE) {
6845
6846 if (group->dynamicRefTable.entries().size() == 0) {
6847 const ResTable_lib_header* lib = (const ResTable_lib_header*) chunk;
6848 status_t err = validate_chunk(&lib->header, sizeof(*lib),
6849 endPos, "ResTable_lib_header");
6850 if (err != NO_ERROR) {
6851 return (mError=err);
6852 }
6853
6854 err = group->dynamicRefTable.load(lib);
6855 if (err != NO_ERROR) {
6856 return (mError=err);
6857 }
6858
6859 // Fill in the reference table with the entries we already know about.
6860 size_t N = mPackageGroups.size();
6861 for (size_t i = 0; i < N; i++) {
6862 group->dynamicRefTable.addMapping(mPackageGroups[i]->name, mPackageGroups[i]->id);
6863 }
6864 } else {
6865 ALOGW("Found multiple library tables, ignoring...");
6866 }
6867 } else {
6868 if (ctype == RES_TABLE_OVERLAYABLE_TYPE) {
6869 package->definesOverlayable = true;
6870 }
6871
6872 status_t err = validate_chunk(chunk, sizeof(ResChunk_header),
6873 endPos, "ResTable_package:unknown");
6874 if (err != NO_ERROR) {
6875 return (mError=err);
6876 }
6877 }
6878 chunk = (const ResChunk_header*)
6879 (((const uint8_t*)chunk) + csize);
6880 }
6881
6882 return NO_ERROR;
6883 }
6884
DynamicRefTable()6885 DynamicRefTable::DynamicRefTable() : DynamicRefTable(0, false) {}
6886
DynamicRefTable(uint8_t packageId,bool appAsLib)6887 DynamicRefTable::DynamicRefTable(uint8_t packageId, bool appAsLib)
6888 : mAssignedPackageId(packageId)
6889 , mAppAsLib(appAsLib)
6890 {
6891 memset(mLookupTable, 0, sizeof(mLookupTable));
6892
6893 // Reserved package ids
6894 mLookupTable[APP_PACKAGE_ID] = APP_PACKAGE_ID;
6895 mLookupTable[SYS_PACKAGE_ID] = SYS_PACKAGE_ID;
6896 }
6897
load(const ResTable_lib_header * const header)6898 status_t DynamicRefTable::load(const ResTable_lib_header* const header)
6899 {
6900 const uint32_t entryCount = dtohl(header->count);
6901 const uint32_t expectedSize = dtohl(header->header.size) - dtohl(header->header.headerSize);
6902 if (entryCount > (expectedSize / sizeof(ResTable_lib_entry))) {
6903 ALOGE("ResTable_lib_header size %u is too small to fit %u entries (x %u).",
6904 expectedSize, entryCount, (uint32_t)sizeof(ResTable_lib_entry));
6905 return UNKNOWN_ERROR;
6906 }
6907
6908 const ResTable_lib_entry* entry = (const ResTable_lib_entry*)(((uint8_t*) header) +
6909 dtohl(header->header.headerSize));
6910 for (uint32_t entryIndex = 0; entryIndex < entryCount; entryIndex++) {
6911 uint32_t packageId = dtohl(entry->packageId);
6912 char16_t tmpName[sizeof(entry->packageName) / sizeof(char16_t)];
6913 strcpy16_dtoh(tmpName, entry->packageName, sizeof(entry->packageName) / sizeof(char16_t));
6914 if (kDebugLibNoisy) {
6915 ALOGV("Found lib entry %s with id %d\n", String8(tmpName).string(),
6916 dtohl(entry->packageId));
6917 }
6918 if (packageId >= 256) {
6919 ALOGE("Bad package id 0x%08x", packageId);
6920 return UNKNOWN_ERROR;
6921 }
6922 mEntries.replaceValueFor(String16(tmpName), (uint8_t) packageId);
6923 entry = entry + 1;
6924 }
6925 return NO_ERROR;
6926 }
6927
addMappings(const DynamicRefTable & other)6928 status_t DynamicRefTable::addMappings(const DynamicRefTable& other) {
6929 if (mAssignedPackageId != other.mAssignedPackageId) {
6930 return UNKNOWN_ERROR;
6931 }
6932
6933 const size_t entryCount = other.mEntries.size();
6934 for (size_t i = 0; i < entryCount; i++) {
6935 ssize_t index = mEntries.indexOfKey(other.mEntries.keyAt(i));
6936 if (index < 0) {
6937 mEntries.add(String16(other.mEntries.keyAt(i)), other.mEntries[i]);
6938 } else {
6939 if (other.mEntries[i] != mEntries[index]) {
6940 return UNKNOWN_ERROR;
6941 }
6942 }
6943 }
6944
6945 // Merge the lookup table. No entry can conflict
6946 // (value of 0 means not set).
6947 for (size_t i = 0; i < 256; i++) {
6948 if (mLookupTable[i] != other.mLookupTable[i]) {
6949 if (mLookupTable[i] == 0) {
6950 mLookupTable[i] = other.mLookupTable[i];
6951 } else if (other.mLookupTable[i] != 0) {
6952 return UNKNOWN_ERROR;
6953 }
6954 }
6955 }
6956 return NO_ERROR;
6957 }
6958
addMapping(const String16 & packageName,uint8_t packageId)6959 status_t DynamicRefTable::addMapping(const String16& packageName, uint8_t packageId)
6960 {
6961 ssize_t index = mEntries.indexOfKey(packageName);
6962 if (index < 0) {
6963 return UNKNOWN_ERROR;
6964 }
6965 mLookupTable[mEntries.valueAt(index)] = packageId;
6966 return NO_ERROR;
6967 }
6968
addMapping(uint8_t buildPackageId,uint8_t runtimePackageId)6969 void DynamicRefTable::addMapping(uint8_t buildPackageId, uint8_t runtimePackageId) {
6970 mLookupTable[buildPackageId] = runtimePackageId;
6971 }
6972
lookupResourceId(uint32_t * resId) const6973 status_t DynamicRefTable::lookupResourceId(uint32_t* resId) const {
6974 uint32_t res = *resId;
6975 size_t packageId = Res_GETPACKAGE(res) + 1;
6976
6977 if (!Res_VALIDID(res)) {
6978 // Cannot look up a null or invalid id, so no lookup needs to be done.
6979 return NO_ERROR;
6980 }
6981
6982 if (packageId == APP_PACKAGE_ID && !mAppAsLib) {
6983 // No lookup needs to be done, app package IDs are absolute.
6984 return NO_ERROR;
6985 }
6986
6987 if (packageId == 0 || (packageId == APP_PACKAGE_ID && mAppAsLib)) {
6988 // The package ID is 0x00. That means that a shared library is accessing
6989 // its own local resource.
6990 // Or if app resource is loaded as shared library, the resource which has
6991 // app package Id is local resources.
6992 // so we fix up those resources with the calling package ID.
6993 *resId = (0xFFFFFF & (*resId)) | (((uint32_t) mAssignedPackageId) << 24);
6994 return NO_ERROR;
6995 }
6996
6997 // Do a proper lookup.
6998 uint8_t translatedId = mLookupTable[packageId];
6999 if (translatedId == 0) {
7000 ALOGW("DynamicRefTable(0x%02x): No mapping for build-time package ID 0x%02x.",
7001 (uint8_t)mAssignedPackageId, (uint8_t)packageId);
7002 for (size_t i = 0; i < 256; i++) {
7003 if (mLookupTable[i] != 0) {
7004 ALOGW("e[0x%02x] -> 0x%02x", (uint8_t)i, mLookupTable[i]);
7005 }
7006 }
7007 return UNKNOWN_ERROR;
7008 }
7009
7010 *resId = (res & 0x00ffffff) | (((uint32_t) translatedId) << 24);
7011 return NO_ERROR;
7012 }
7013
requiresLookup(const Res_value * value) const7014 bool DynamicRefTable::requiresLookup(const Res_value* value) const {
7015 // Only resolve non-dynamic references and attributes if the package is loaded as a
7016 // library or if a shared library is attempting to retrieve its own resource
7017 if ((value->dataType == Res_value::TYPE_REFERENCE ||
7018 value->dataType == Res_value::TYPE_ATTRIBUTE) &&
7019 (mAppAsLib || (Res_GETPACKAGE(value->data) + 1) == 0)) {
7020 return true;
7021 }
7022 return value->dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE ||
7023 value->dataType == Res_value::TYPE_DYNAMIC_REFERENCE;
7024 }
7025
lookupResourceValue(Res_value * value) const7026 status_t DynamicRefTable::lookupResourceValue(Res_value* value) const {
7027 if (!requiresLookup(value)) {
7028 return NO_ERROR;
7029 }
7030
7031 uint8_t resolvedType = Res_value::TYPE_REFERENCE;
7032 switch (value->dataType) {
7033 case Res_value::TYPE_ATTRIBUTE:
7034 resolvedType = Res_value::TYPE_ATTRIBUTE;
7035 FALLTHROUGH_INTENDED;
7036 case Res_value::TYPE_REFERENCE:
7037 break;
7038 case Res_value::TYPE_DYNAMIC_ATTRIBUTE:
7039 resolvedType = Res_value::TYPE_ATTRIBUTE;
7040 FALLTHROUGH_INTENDED;
7041 case Res_value::TYPE_DYNAMIC_REFERENCE:
7042 break;
7043 default:
7044 return NO_ERROR;
7045 }
7046
7047 status_t err = lookupResourceId(&value->data);
7048 if (err != NO_ERROR) {
7049 return err;
7050 }
7051
7052 value->dataType = resolvedType;
7053 return NO_ERROR;
7054 }
7055
7056 class IdmapMatchingResources;
7057
7058 class IdmapTypeMapping {
7059 public:
add(uint32_t targetResId,uint32_t overlayResId)7060 void add(uint32_t targetResId, uint32_t overlayResId) {
7061 uint8_t targetTypeId = Res_GETTYPE(targetResId);
7062 if (mData.find(targetTypeId) == mData.end()) {
7063 mData.emplace(targetTypeId, std::set<std::pair<uint32_t, uint32_t>>());
7064 }
7065 auto& entries = mData[targetTypeId];
7066 entries.insert(std::make_pair(targetResId, overlayResId));
7067 }
7068
empty() const7069 bool empty() const {
7070 return mData.empty();
7071 }
7072
7073 private:
7074 // resource type ID in context of target -> set of resource entries mapping target -> overlay
7075 std::map<uint8_t, std::set<std::pair<uint32_t, uint32_t>>> mData;
7076
7077 friend IdmapMatchingResources;
7078 };
7079
7080 class IdmapMatchingResources {
7081 public:
IdmapMatchingResources(std::unique_ptr<IdmapTypeMapping> tm)7082 IdmapMatchingResources(std::unique_ptr<IdmapTypeMapping> tm) : mTypeMapping(std::move(tm)) {
7083 assert(mTypeMapping);
7084 for (auto ti = mTypeMapping->mData.cbegin(); ti != mTypeMapping->mData.cend(); ++ti) {
7085 uint32_t lastSeen = 0xffffffff;
7086 size_t totalEntries = 0;
7087 for (auto ei = ti->second.cbegin(); ei != ti->second.cend(); ++ei) {
7088 assert(lastSeen == 0xffffffff || lastSeen < ei->first);
7089 mEntryPadding[ei->first] = (lastSeen == 0xffffffff) ? 0 : ei->first - lastSeen - 1;
7090 lastSeen = ei->first;
7091 totalEntries += 1 + mEntryPadding[ei->first];
7092 }
7093 mNumberOfEntriesIncludingPadding[ti->first] = totalEntries;
7094 }
7095 }
7096
getTypeMapping() const7097 const std::map<uint8_t, std::set<std::pair<uint32_t, uint32_t>>>& getTypeMapping() const {
7098 return mTypeMapping->mData;
7099 }
7100
getNumberOfEntriesIncludingPadding(uint8_t type) const7101 size_t getNumberOfEntriesIncludingPadding(uint8_t type) const {
7102 return mNumberOfEntriesIncludingPadding.at(type);
7103 }
7104
getPadding(uint32_t resid) const7105 size_t getPadding(uint32_t resid) const {
7106 return mEntryPadding.at(resid);
7107 }
7108
7109 private:
7110 // resource type ID in context of target -> set of resource entries mapping target -> overlay
7111 const std::unique_ptr<IdmapTypeMapping> mTypeMapping;
7112
7113 // resource ID in context of target -> trailing padding for that resource (call FixPadding
7114 // before use)
7115 std::map<uint32_t, size_t> mEntryPadding;
7116
7117 // resource type ID in context of target -> total number of entries, including padding entries,
7118 // for that type (call FixPadding before use)
7119 std::map<uint8_t, size_t> mNumberOfEntriesIncludingPadding;
7120 };
7121
createIdmap(const ResTable & targetResTable,uint32_t targetCrc,uint32_t overlayCrc,const char * targetPath,const char * overlayPath,void ** outData,size_t * outSize) const7122 status_t ResTable::createIdmap(const ResTable& targetResTable,
7123 uint32_t targetCrc, uint32_t overlayCrc,
7124 const char* targetPath, const char* overlayPath,
7125 void** outData, size_t* outSize) const
7126 {
7127 if (targetPath == NULL || overlayPath == NULL || outData == NULL || outSize == NULL) {
7128 ALOGE("idmap: unexpected NULL parameter");
7129 return UNKNOWN_ERROR;
7130 }
7131 if (strlen(targetPath) > 255) {
7132 ALOGE("idmap: target path exceeds idmap file format limit of 255 chars");
7133 return UNKNOWN_ERROR;
7134 }
7135 if (strlen(overlayPath) > 255) {
7136 ALOGE("idmap: overlay path exceeds idmap file format limit of 255 chars");
7137 return UNKNOWN_ERROR;
7138 }
7139 if (mPackageGroups.size() == 0 || mPackageGroups[0]->packages.size() == 0) {
7140 ALOGE("idmap: invalid overlay package");
7141 return UNKNOWN_ERROR;
7142 }
7143 if (targetResTable.mPackageGroups.size() == 0 ||
7144 targetResTable.mPackageGroups[0]->packages.size() == 0) {
7145 ALOGE("idmap: invalid target package");
7146 return UNKNOWN_ERROR;
7147 }
7148
7149 // Idmap is not aware of overlayable, exit since policy checks can't be done
7150 if (targetResTable.mPackageGroups[0]->packages[0]->definesOverlayable) {
7151 return UNKNOWN_ERROR;
7152 }
7153
7154 const ResTable_package* targetPackageStruct =
7155 targetResTable.mPackageGroups[0]->packages[0]->package;
7156 const size_t tmpNameSize = arraysize(targetPackageStruct->name);
7157 char16_t tmpName[tmpNameSize];
7158 strcpy16_dtoh(tmpName, targetPackageStruct->name, tmpNameSize);
7159 const String16 targetPackageName(tmpName);
7160
7161 const PackageGroup* packageGroup = mPackageGroups[0];
7162
7163 // find the resources that exist in both packages
7164 auto typeMapping = std::make_unique<IdmapTypeMapping>();
7165 for (size_t typeIndex = 0; typeIndex < packageGroup->types.size(); ++typeIndex) {
7166 const TypeList& typeList = packageGroup->types[typeIndex];
7167 if (typeList.isEmpty()) {
7168 continue;
7169 }
7170 const Type* typeConfigs = typeList[0];
7171
7172 for (size_t entryIndex = 0; entryIndex < typeConfigs->entryCount; ++entryIndex) {
7173 uint32_t overlay_resid = Res_MAKEID(packageGroup->id - 1, typeIndex, entryIndex);
7174 resource_name current_res;
7175 if (!getResourceName(overlay_resid, false, ¤t_res)) {
7176 continue;
7177 }
7178
7179 uint32_t typeSpecFlags = 0u;
7180 const uint32_t target_resid = targetResTable.identifierForName(
7181 current_res.name,
7182 current_res.nameLen,
7183 current_res.type,
7184 current_res.typeLen,
7185 targetPackageName.string(),
7186 targetPackageName.size(),
7187 &typeSpecFlags);
7188
7189 if (target_resid == 0) {
7190 continue;
7191 }
7192
7193 typeMapping->add(target_resid, overlay_resid);
7194 }
7195 }
7196
7197 if (typeMapping->empty()) {
7198 ALOGE("idmap: no matching resources");
7199 return UNKNOWN_ERROR;
7200 }
7201
7202 const IdmapMatchingResources matchingResources(std::move(typeMapping));
7203
7204 // write idmap
7205 *outSize = ResTable::IDMAP_HEADER_SIZE_BYTES; // magic, version, target and overlay crc
7206 *outSize += 2 * sizeof(uint16_t); // target package id, type count
7207 auto fixedTypeMapping = matchingResources.getTypeMapping();
7208 const auto typesEnd = fixedTypeMapping.cend();
7209 for (auto ti = fixedTypeMapping.cbegin(); ti != typesEnd; ++ti) {
7210 *outSize += 4 * sizeof(uint16_t); // target type, overlay type, entry count, entry offset
7211 *outSize += matchingResources.getNumberOfEntriesIncludingPadding(ti->first) *
7212 sizeof(uint32_t); // entries
7213 }
7214 if ((*outData = malloc(*outSize)) == NULL) {
7215 return NO_MEMORY;
7216 }
7217
7218 // write idmap header
7219 uint32_t* data = reinterpret_cast<uint32_t*>(*outData);
7220 *data++ = htodl(IDMAP_MAGIC); // write: magic
7221 *data++ = htodl(ResTable::IDMAP_CURRENT_VERSION); // write: version
7222 *data++ = htodl(targetCrc); // write: target crc
7223 *data++ = htodl(overlayCrc); // write: overlay crc
7224
7225 char* charData = reinterpret_cast<char*>(data);
7226 size_t pathLen = strlen(targetPath);
7227 for (size_t i = 0; i < 256; ++i) {
7228 *charData++ = i < pathLen ? targetPath[i] : '\0'; // write: target path
7229 }
7230 pathLen = strlen(overlayPath);
7231 for (size_t i = 0; i < 256; ++i) {
7232 *charData++ = i < pathLen ? overlayPath[i] : '\0'; // write: overlay path
7233 }
7234 data += (2 * 256) / sizeof(uint32_t);
7235
7236 // write idmap data header
7237 uint16_t* typeData = reinterpret_cast<uint16_t*>(data);
7238 *typeData++ = htods(targetPackageStruct->id); // write: target package id
7239 *typeData++ =
7240 htods(static_cast<uint16_t>(fixedTypeMapping.size())); // write: type count
7241
7242 // write idmap data
7243 for (auto ti = fixedTypeMapping.cbegin(); ti != typesEnd; ++ti) {
7244 const size_t entryCount = matchingResources.getNumberOfEntriesIncludingPadding(ti->first);
7245 auto ei = ti->second.cbegin();
7246 *typeData++ = htods(Res_GETTYPE(ei->first) + 1); // write: target type id
7247 *typeData++ = htods(Res_GETTYPE(ei->second) + 1); // write: overlay type id
7248 *typeData++ = htods(entryCount); // write: entry count
7249 *typeData++ = htods(Res_GETENTRY(ei->first)); // write: (target) entry offset
7250 uint32_t *entryData = reinterpret_cast<uint32_t*>(typeData);
7251 for (; ei != ti->second.cend(); ++ei) {
7252 const size_t padding = matchingResources.getPadding(ei->first);
7253 for (size_t i = 0; i < padding; ++i) {
7254 *entryData++ = htodl(0xffffffff); // write: padding
7255 }
7256 *entryData++ = htodl(Res_GETENTRY(ei->second)); // write: (overlay) entry
7257 }
7258 typeData += entryCount * 2;
7259 }
7260
7261 return NO_ERROR;
7262 }
7263
getIdmapInfo(const void * idmap,size_t sizeBytes,uint32_t * pVersion,uint32_t * pTargetCrc,uint32_t * pOverlayCrc,String8 * pTargetPath,String8 * pOverlayPath)7264 bool ResTable::getIdmapInfo(const void* idmap, size_t sizeBytes,
7265 uint32_t* pVersion,
7266 uint32_t* pTargetCrc, uint32_t* pOverlayCrc,
7267 String8* pTargetPath, String8* pOverlayPath)
7268 {
7269 const uint32_t* map = (const uint32_t*)idmap;
7270 if (!assertIdmapHeader(map, sizeBytes)) {
7271 return false;
7272 }
7273 if (pVersion) {
7274 *pVersion = dtohl(map[1]);
7275 }
7276 if (pTargetCrc) {
7277 *pTargetCrc = dtohl(map[2]);
7278 }
7279 if (pOverlayCrc) {
7280 *pOverlayCrc = dtohl(map[3]);
7281 }
7282 if (pTargetPath) {
7283 pTargetPath->setTo(reinterpret_cast<const char*>(map + 4));
7284 }
7285 if (pOverlayPath) {
7286 pOverlayPath->setTo(reinterpret_cast<const char*>(map + 4 + 256 / sizeof(uint32_t)));
7287 }
7288 return true;
7289 }
7290
7291
7292 #define CHAR16_TO_CSTR(c16, len) (String8(String16(c16,len)).string())
7293
7294 #define CHAR16_ARRAY_EQ(constant, var, len) \
7295 (((len) == (sizeof(constant)/sizeof((constant)[0]))) && (0 == memcmp((var), (constant), (len))))
7296
print_complex(uint32_t complex,bool isFraction)7297 static void print_complex(uint32_t complex, bool isFraction)
7298 {
7299 const float MANTISSA_MULT =
7300 1.0f / (1<<Res_value::COMPLEX_MANTISSA_SHIFT);
7301 const float RADIX_MULTS[] = {
7302 1.0f*MANTISSA_MULT, 1.0f/(1<<7)*MANTISSA_MULT,
7303 1.0f/(1<<15)*MANTISSA_MULT, 1.0f/(1<<23)*MANTISSA_MULT
7304 };
7305
7306 float value = (complex&(Res_value::COMPLEX_MANTISSA_MASK
7307 <<Res_value::COMPLEX_MANTISSA_SHIFT))
7308 * RADIX_MULTS[(complex>>Res_value::COMPLEX_RADIX_SHIFT)
7309 & Res_value::COMPLEX_RADIX_MASK];
7310 printf("%f", value);
7311
7312 if (!isFraction) {
7313 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
7314 case Res_value::COMPLEX_UNIT_PX: printf("px"); break;
7315 case Res_value::COMPLEX_UNIT_DIP: printf("dp"); break;
7316 case Res_value::COMPLEX_UNIT_SP: printf("sp"); break;
7317 case Res_value::COMPLEX_UNIT_PT: printf("pt"); break;
7318 case Res_value::COMPLEX_UNIT_IN: printf("in"); break;
7319 case Res_value::COMPLEX_UNIT_MM: printf("mm"); break;
7320 default: printf(" (unknown unit)"); break;
7321 }
7322 } else {
7323 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
7324 case Res_value::COMPLEX_UNIT_FRACTION: printf("%%"); break;
7325 case Res_value::COMPLEX_UNIT_FRACTION_PARENT: printf("%%p"); break;
7326 default: printf(" (unknown unit)"); break;
7327 }
7328 }
7329 }
7330
7331 // Normalize a string for output
normalizeForOutput(const char * input)7332 String8 ResTable::normalizeForOutput( const char *input )
7333 {
7334 String8 ret;
7335 char buff[2];
7336 buff[1] = '\0';
7337
7338 while (*input != '\0') {
7339 switch (*input) {
7340 // All interesting characters are in the ASCII zone, so we are making our own lives
7341 // easier by scanning the string one byte at a time.
7342 case '\\':
7343 ret += "\\\\";
7344 break;
7345 case '\n':
7346 ret += "\\n";
7347 break;
7348 case '"':
7349 ret += "\\\"";
7350 break;
7351 default:
7352 buff[0] = *input;
7353 ret += buff;
7354 break;
7355 }
7356
7357 input++;
7358 }
7359
7360 return ret;
7361 }
7362
print_value(const Package * pkg,const Res_value & value) const7363 void ResTable::print_value(const Package* pkg, const Res_value& value) const
7364 {
7365 if (value.dataType == Res_value::TYPE_NULL) {
7366 if (value.data == Res_value::DATA_NULL_UNDEFINED) {
7367 printf("(null)\n");
7368 } else if (value.data == Res_value::DATA_NULL_EMPTY) {
7369 printf("(null empty)\n");
7370 } else {
7371 // This should never happen.
7372 printf("(null) 0x%08x\n", value.data);
7373 }
7374 } else if (value.dataType == Res_value::TYPE_REFERENCE) {
7375 printf("(reference) 0x%08x\n", value.data);
7376 } else if (value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE) {
7377 printf("(dynamic reference) 0x%08x\n", value.data);
7378 } else if (value.dataType == Res_value::TYPE_ATTRIBUTE) {
7379 printf("(attribute) 0x%08x\n", value.data);
7380 } else if (value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE) {
7381 printf("(dynamic attribute) 0x%08x\n", value.data);
7382 } else if (value.dataType == Res_value::TYPE_STRING) {
7383 size_t len;
7384 const char* str8 = pkg->header->values.string8At(
7385 value.data, &len);
7386 if (str8 != NULL) {
7387 printf("(string8) \"%s\"\n", normalizeForOutput(str8).string());
7388 } else {
7389 const char16_t* str16 = pkg->header->values.stringAt(
7390 value.data, &len);
7391 if (str16 != NULL) {
7392 printf("(string16) \"%s\"\n",
7393 normalizeForOutput(String8(str16, len).string()).string());
7394 } else {
7395 printf("(string) null\n");
7396 }
7397 }
7398 } else if (value.dataType == Res_value::TYPE_FLOAT) {
7399 printf("(float) %g\n", *(const float*)&value.data);
7400 } else if (value.dataType == Res_value::TYPE_DIMENSION) {
7401 printf("(dimension) ");
7402 print_complex(value.data, false);
7403 printf("\n");
7404 } else if (value.dataType == Res_value::TYPE_FRACTION) {
7405 printf("(fraction) ");
7406 print_complex(value.data, true);
7407 printf("\n");
7408 } else if (value.dataType >= Res_value::TYPE_FIRST_COLOR_INT
7409 && value.dataType <= Res_value::TYPE_LAST_COLOR_INT) {
7410 printf("(color) #%08x\n", value.data);
7411 } else if (value.dataType == Res_value::TYPE_INT_BOOLEAN) {
7412 printf("(boolean) %s\n", value.data ? "true" : "false");
7413 } else if (value.dataType >= Res_value::TYPE_FIRST_INT
7414 && value.dataType <= Res_value::TYPE_LAST_INT) {
7415 printf("(int) 0x%08x or %d\n", value.data, value.data);
7416 } else {
7417 printf("(unknown type) t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)\n",
7418 (int)value.dataType, (int)value.data,
7419 (int)value.size, (int)value.res0);
7420 }
7421 }
7422
print(bool inclValues) const7423 void ResTable::print(bool inclValues) const
7424 {
7425 if (mError != 0) {
7426 printf("mError=0x%x (%s)\n", mError, strerror(mError));
7427 }
7428 size_t pgCount = mPackageGroups.size();
7429 printf("Package Groups (%d)\n", (int)pgCount);
7430 for (size_t pgIndex=0; pgIndex<pgCount; pgIndex++) {
7431 const PackageGroup* pg = mPackageGroups[pgIndex];
7432 printf("Package Group %d id=0x%02x packageCount=%d name=%s\n",
7433 (int)pgIndex, pg->id, (int)pg->packages.size(),
7434 String8(pg->name).string());
7435
7436 const KeyedVector<String16, uint8_t>& refEntries = pg->dynamicRefTable.entries();
7437 const size_t refEntryCount = refEntries.size();
7438 if (refEntryCount > 0) {
7439 printf(" DynamicRefTable entryCount=%d:\n", (int) refEntryCount);
7440 for (size_t refIndex = 0; refIndex < refEntryCount; refIndex++) {
7441 printf(" 0x%02x -> %s\n",
7442 refEntries.valueAt(refIndex),
7443 String8(refEntries.keyAt(refIndex)).string());
7444 }
7445 printf("\n");
7446 }
7447
7448 // Determine the number of resource splits for the resource types in this package.
7449 // It needs to be done outside of the loop below so all of the information for a
7450 // is displayed in a single block. Otherwise, a resource split's resource types
7451 // would be interleaved with other splits.
7452 size_t splitCount = 0;
7453 for (size_t typeIndex = 0; typeIndex < pg->types.size(); typeIndex++) {
7454 splitCount = max(splitCount, pg->types[typeIndex].size());
7455 }
7456
7457 int packageId = pg->id;
7458 for (size_t splitIndex = 0; splitIndex < splitCount; splitIndex++) {
7459 size_t pkgCount = pg->packages.size();
7460 for (size_t pkgIndex=0; pkgIndex<pkgCount; pkgIndex++) {
7461 const Package* pkg = pg->packages[pkgIndex];
7462 // Use a package's real ID, since the ID may have been assigned
7463 // if this package is a shared library.
7464 packageId = pkg->package->id;
7465 char16_t tmpName[sizeof(pkg->package->name)/sizeof(pkg->package->name[0])];
7466 strcpy16_dtoh(tmpName, pkg->package->name,
7467 sizeof(pkg->package->name)/sizeof(pkg->package->name[0]));
7468 printf(" Package %d id=0x%02x name=%s\n", (int)pkgIndex,
7469 pkg->package->id, String8(tmpName).string());
7470 }
7471
7472 for (size_t typeIndex = 0; typeIndex < pg->types.size(); typeIndex++) {
7473 const TypeList& typeList = pg->types[typeIndex];
7474 if (splitIndex >= typeList.size() || typeList.isEmpty()) {
7475 // Only dump if the split exists and contains entries for this type
7476 continue;
7477 }
7478 const Type* typeConfigs = typeList[splitIndex];
7479 const size_t NTC = typeConfigs->configs.size();
7480 printf(" type %d configCount=%d entryCount=%d\n",
7481 (int)typeIndex, (int)NTC, (int)typeConfigs->entryCount);
7482 if (typeConfigs->typeSpecFlags != NULL) {
7483 for (size_t entryIndex=0; entryIndex<typeConfigs->entryCount; entryIndex++) {
7484 uint32_t resID = (0xff000000 & ((packageId)<<24))
7485 | (0x00ff0000 & ((typeIndex+1)<<16))
7486 | (0x0000ffff & (entryIndex));
7487 // Since we are creating resID without actually
7488 // iterating over them, we have no idea which is a
7489 // dynamic reference. We must check.
7490 if (packageId == 0) {
7491 pg->dynamicRefTable.lookupResourceId(&resID);
7492 }
7493
7494 resource_name resName;
7495 if (this->getResourceName(resID, true, &resName)) {
7496 String8 type8;
7497 String8 name8;
7498 if (resName.type8 != NULL) {
7499 type8 = String8(resName.type8, resName.typeLen);
7500 } else {
7501 type8 = String8(resName.type, resName.typeLen);
7502 }
7503 if (resName.name8 != NULL) {
7504 name8 = String8(resName.name8, resName.nameLen);
7505 } else {
7506 name8 = String8(resName.name, resName.nameLen);
7507 }
7508 printf(" spec resource 0x%08x %s:%s/%s: flags=0x%08x\n",
7509 resID,
7510 CHAR16_TO_CSTR(resName.package, resName.packageLen),
7511 type8.string(), name8.string(),
7512 dtohl(typeConfigs->typeSpecFlags[entryIndex]));
7513 } else {
7514 printf(" INVALID TYPE CONFIG FOR RESOURCE 0x%08x\n", resID);
7515 }
7516 }
7517 }
7518 for (size_t configIndex=0; configIndex<NTC; configIndex++) {
7519 const ResTable_type* type = typeConfigs->configs[configIndex];
7520 if ((((uint64_t)type)&0x3) != 0) {
7521 printf(" NON-INTEGER ResTable_type ADDRESS: %p\n", type);
7522 continue;
7523 }
7524
7525 // Always copy the config, as fields get added and we need to
7526 // set the defaults.
7527 ResTable_config thisConfig;
7528 thisConfig.copyFromDtoH(type->config);
7529
7530 String8 configStr = thisConfig.toString();
7531 printf(" config %s", configStr.size() > 0
7532 ? configStr.string() : "(default)");
7533 if (type->flags != 0u) {
7534 printf(" flags=0x%02x", type->flags);
7535 if (type->flags & ResTable_type::FLAG_SPARSE) {
7536 printf(" [sparse]");
7537 }
7538 }
7539
7540 printf(":\n");
7541
7542 size_t entryCount = dtohl(type->entryCount);
7543 uint32_t entriesStart = dtohl(type->entriesStart);
7544 if ((entriesStart&0x3) != 0) {
7545 printf(" NON-INTEGER ResTable_type entriesStart OFFSET: 0x%x\n",
7546 entriesStart);
7547 continue;
7548 }
7549 uint32_t typeSize = dtohl(type->header.size);
7550 if ((typeSize&0x3) != 0) {
7551 printf(" NON-INTEGER ResTable_type header.size: 0x%x\n", typeSize);
7552 continue;
7553 }
7554
7555 const uint32_t* const eindex = (const uint32_t*)
7556 (((const uint8_t*)type) + dtohs(type->header.headerSize));
7557 for (size_t entryIndex=0; entryIndex<entryCount; entryIndex++) {
7558 size_t entryId;
7559 uint32_t thisOffset;
7560 if (type->flags & ResTable_type::FLAG_SPARSE) {
7561 const ResTable_sparseTypeEntry* entry =
7562 reinterpret_cast<const ResTable_sparseTypeEntry*>(
7563 eindex + entryIndex);
7564 entryId = dtohs(entry->idx);
7565 // Offsets are encoded as divided by 4.
7566 thisOffset = static_cast<uint32_t>(dtohs(entry->offset)) * 4u;
7567 } else {
7568 entryId = entryIndex;
7569 thisOffset = dtohl(eindex[entryIndex]);
7570 if (thisOffset == ResTable_type::NO_ENTRY) {
7571 continue;
7572 }
7573 }
7574
7575 uint32_t resID = (0xff000000 & ((packageId)<<24))
7576 | (0x00ff0000 & ((typeIndex+1)<<16))
7577 | (0x0000ffff & (entryId));
7578 if (packageId == 0) {
7579 pg->dynamicRefTable.lookupResourceId(&resID);
7580 }
7581 resource_name resName;
7582 if (this->getResourceName(resID, true, &resName)) {
7583 String8 type8;
7584 String8 name8;
7585 if (resName.type8 != NULL) {
7586 type8 = String8(resName.type8, resName.typeLen);
7587 } else {
7588 type8 = String8(resName.type, resName.typeLen);
7589 }
7590 if (resName.name8 != NULL) {
7591 name8 = String8(resName.name8, resName.nameLen);
7592 } else {
7593 name8 = String8(resName.name, resName.nameLen);
7594 }
7595 printf(" resource 0x%08x %s:%s/%s: ", resID,
7596 CHAR16_TO_CSTR(resName.package, resName.packageLen),
7597 type8.string(), name8.string());
7598 } else {
7599 printf(" INVALID RESOURCE 0x%08x: ", resID);
7600 }
7601 if ((thisOffset&0x3) != 0) {
7602 printf("NON-INTEGER OFFSET: 0x%x\n", thisOffset);
7603 continue;
7604 }
7605 if ((thisOffset+sizeof(ResTable_entry)) > typeSize) {
7606 printf("OFFSET OUT OF BOUNDS: 0x%x+0x%x (size is 0x%x)\n",
7607 entriesStart, thisOffset, typeSize);
7608 continue;
7609 }
7610
7611 const ResTable_entry* ent = (const ResTable_entry*)
7612 (((const uint8_t*)type) + entriesStart + thisOffset);
7613 if (((entriesStart + thisOffset)&0x3) != 0) {
7614 printf("NON-INTEGER ResTable_entry OFFSET: 0x%x\n",
7615 (entriesStart + thisOffset));
7616 continue;
7617 }
7618
7619 uintptr_t esize = dtohs(ent->size);
7620 if ((esize&0x3) != 0) {
7621 printf("NON-INTEGER ResTable_entry SIZE: %p\n", (void *)esize);
7622 continue;
7623 }
7624 if ((thisOffset+esize) > typeSize) {
7625 printf("ResTable_entry OUT OF BOUNDS: 0x%x+0x%x+%p (size is 0x%x)\n",
7626 entriesStart, thisOffset, (void *)esize, typeSize);
7627 continue;
7628 }
7629
7630 const Res_value* valuePtr = NULL;
7631 const ResTable_map_entry* bagPtr = NULL;
7632 Res_value value;
7633 if ((dtohs(ent->flags)&ResTable_entry::FLAG_COMPLEX) != 0) {
7634 printf("<bag>");
7635 bagPtr = (const ResTable_map_entry*)ent;
7636 } else {
7637 valuePtr = (const Res_value*)
7638 (((const uint8_t*)ent) + esize);
7639 value.copyFrom_dtoh(*valuePtr);
7640 printf("t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)",
7641 (int)value.dataType, (int)value.data,
7642 (int)value.size, (int)value.res0);
7643 }
7644
7645 if ((dtohs(ent->flags)&ResTable_entry::FLAG_PUBLIC) != 0) {
7646 printf(" (PUBLIC)");
7647 }
7648 printf("\n");
7649
7650 if (inclValues) {
7651 if (valuePtr != NULL) {
7652 printf(" ");
7653 print_value(typeConfigs->package, value);
7654 } else if (bagPtr != NULL) {
7655 const int N = dtohl(bagPtr->count);
7656 const uint8_t* baseMapPtr = (const uint8_t*)ent;
7657 size_t mapOffset = esize;
7658 const ResTable_map* mapPtr = (ResTable_map*)(baseMapPtr+mapOffset);
7659 const uint32_t parent = dtohl(bagPtr->parent.ident);
7660 uint32_t resolvedParent = parent;
7661 if (Res_GETPACKAGE(resolvedParent) + 1 == 0) {
7662 status_t err =
7663 pg->dynamicRefTable.lookupResourceId(&resolvedParent);
7664 if (err != NO_ERROR) {
7665 resolvedParent = 0;
7666 }
7667 }
7668 printf(" Parent=0x%08x(Resolved=0x%08x), Count=%d\n",
7669 parent, resolvedParent, N);
7670 for (int i=0;
7671 i<N && mapOffset < (typeSize-sizeof(ResTable_map)); i++) {
7672 printf(" #%i (Key=0x%08x): ",
7673 i, dtohl(mapPtr->name.ident));
7674 value.copyFrom_dtoh(mapPtr->value);
7675 print_value(typeConfigs->package, value);
7676 const size_t size = dtohs(mapPtr->value.size);
7677 mapOffset += size + sizeof(*mapPtr)-sizeof(mapPtr->value);
7678 mapPtr = (ResTable_map*)(baseMapPtr+mapOffset);
7679 }
7680 }
7681 }
7682 }
7683 }
7684 }
7685 }
7686 }
7687 }
7688
7689 } // namespace android
7690