2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #define LOG_TAG "ResourceType"
18 //#define LOG_NDEBUG 0
30 #include <type_traits>
32 #include <androidfw/ByteBucketArray.h>
33 #include <androidfw/ResourceTypes.h>
34 #include <androidfw/TypeWrappers.h>
35 #include <utils/Atomic.h>
36 #include <utils/ByteOrder.h>
37 #include <utils/Debug.h>
38 #include <utils/Log.h>
39 #include <utils/String16.h>
40 #include <utils/String8.h>
43 #include <binder/TextOutput.h>
47 #define INT32_MAX ((int32_t)(2147483647))
55 #define ntohl(x) ( ((x) << 24) | (((x) >> 24) & 255) | (((x) << 8) & 0xff0000) | (((x) >> 8) & 0xff00) )
56 #define htonl(x) ntohl(x)
57 #define ntohs(x) ( (((x) << 8) & 0xff00) | (((x) >> 8) & 255) )
58 #define htons(x) ntohs(x)
61 #define IDMAP_MAGIC 0x504D4449
62 #define IDMAP_CURRENT_VERSION 0x00000001
64 #define APP_PACKAGE_ID 0x7f
65 #define SYS_PACKAGE_ID 0x01
67 static const bool kDebugStringPoolNoisy = false;
68 static const bool kDebugXMLNoisy = false;
69 static const bool kDebugTableNoisy = false;
70 static const bool kDebugTableGetEntry = false;
71 static const bool kDebugTableSuperNoisy = false;
72 static const bool kDebugLoadTableNoisy = false;
73 static const bool kDebugLoadTableSuperNoisy = false;
74 static const bool kDebugTableTheme = false;
75 static const bool kDebugResXMLTree = false;
76 static const bool kDebugLibNoisy = false;
78 // TODO: This code uses 0xFFFFFFFF converted to bag_set* as a sentinel value. This is bad practice.
80 // Standard C isspace() is only required to look at the low byte of its input, so
81 // produces incorrect results for UTF-16 characters. For safety's sake, assume that
82 // any high-byte UTF-16 code point is not whitespace.
83 inline int isspace16(char16_t c) {
84 return (c < 0x0080 && isspace(c));
88 inline static T max(T a, T b) {
92 // range checked; guaranteed to NUL-terminate within the stated number of available slots
93 // NOTE: if this truncates the dst string due to running out of space, no attempt is
94 // made to avoid splitting surrogate pairs.
95 static void strcpy16_dtoh(char16_t* dst, const uint16_t* src, size_t avail)
97 char16_t* last = dst + avail - 1;
98 while (*src && (dst < last)) {
99 char16_t s = dtohs(static_cast<char16_t>(*src));
106 static status_t validate_chunk(const ResChunk_header* chunk,
108 const uint8_t* dataEnd,
111 const uint16_t headerSize = dtohs(chunk->headerSize);
112 const uint32_t size = dtohl(chunk->size);
114 if (headerSize >= minSize) {
115 if (headerSize <= size) {
116 if (((headerSize|size)&0x3) == 0) {
117 if ((size_t)size <= (size_t)(dataEnd-((const uint8_t*)chunk))) {
120 ALOGW("%s data size 0x%x extends beyond resource end %p.",
121 name, size, (void*)(dataEnd-((const uint8_t*)chunk)));
124 ALOGW("%s size 0x%x or headerSize 0x%x is not on an integer boundary.",
125 name, (int)size, (int)headerSize);
128 ALOGW("%s size 0x%x is smaller than header size 0x%x.",
129 name, size, headerSize);
132 ALOGW("%s header size 0x%04x is too small.",
137 static void fill9patchOffsets(Res_png_9patch* patch) {
138 patch->xDivsOffset = sizeof(Res_png_9patch);
139 patch->yDivsOffset = patch->xDivsOffset + (patch->numXDivs * sizeof(int32_t));
140 patch->colorsOffset = patch->yDivsOffset + (patch->numYDivs * sizeof(int32_t));
143 inline void Res_value::copyFrom_dtoh(const Res_value& src)
145 size = dtohs(src.size);
147 dataType = src.dataType;
148 data = dtohl(src.data);
151 void Res_png_9patch::deviceToFile()
153 int32_t* xDivs = getXDivs();
154 for (int i = 0; i < numXDivs; i++) {
155 xDivs[i] = htonl(xDivs[i]);
157 int32_t* yDivs = getYDivs();
158 for (int i = 0; i < numYDivs; i++) {
159 yDivs[i] = htonl(yDivs[i]);
161 paddingLeft = htonl(paddingLeft);
162 paddingRight = htonl(paddingRight);
163 paddingTop = htonl(paddingTop);
164 paddingBottom = htonl(paddingBottom);
165 uint32_t* colors = getColors();
166 for (int i=0; i<numColors; i++) {
167 colors[i] = htonl(colors[i]);
171 void Res_png_9patch::fileToDevice()
173 int32_t* xDivs = getXDivs();
174 for (int i = 0; i < numXDivs; i++) {
175 xDivs[i] = ntohl(xDivs[i]);
177 int32_t* yDivs = getYDivs();
178 for (int i = 0; i < numYDivs; i++) {
179 yDivs[i] = ntohl(yDivs[i]);
181 paddingLeft = ntohl(paddingLeft);
182 paddingRight = ntohl(paddingRight);
183 paddingTop = ntohl(paddingTop);
184 paddingBottom = ntohl(paddingBottom);
185 uint32_t* colors = getColors();
186 for (int i=0; i<numColors; i++) {
187 colors[i] = ntohl(colors[i]);
191 size_t Res_png_9patch::serializedSize() const
193 // The size of this struct is 32 bytes on the 32-bit target system
198 + numXDivs * sizeof(int32_t)
199 + numYDivs * sizeof(int32_t)
200 + numColors * sizeof(uint32_t);
203 void* Res_png_9patch::serialize(const Res_png_9patch& patch, const int32_t* xDivs,
204 const int32_t* yDivs, const uint32_t* colors)
206 // Use calloc since we're going to leave a few holes in the data
207 // and want this to run cleanly under valgrind
208 void* newData = calloc(1, patch.serializedSize());
209 serialize(patch, xDivs, yDivs, colors, newData);
213 void Res_png_9patch::serialize(const Res_png_9patch& patch, const int32_t* xDivs,
214 const int32_t* yDivs, const uint32_t* colors, void* outData)
216 uint8_t* data = (uint8_t*) outData;
217 memcpy(data, &patch.wasDeserialized, 4); // copy wasDeserialized, numXDivs, numYDivs, numColors
218 memcpy(data + 12, &patch.paddingLeft, 16); // copy paddingXXXX
221 memcpy(data, xDivs, patch.numXDivs * sizeof(int32_t));
222 data += patch.numXDivs * sizeof(int32_t);
223 memcpy(data, yDivs, patch.numYDivs * sizeof(int32_t));
224 data += patch.numYDivs * sizeof(int32_t);
225 memcpy(data, colors, patch.numColors * sizeof(uint32_t));
227 fill9patchOffsets(reinterpret_cast<Res_png_9patch*>(outData));
230 static bool assertIdmapHeader(const void* idmap, size_t size) {
231 if (reinterpret_cast<uintptr_t>(idmap) & 0x03) {
232 ALOGE("idmap: header is not word aligned");
236 if (size < ResTable::IDMAP_HEADER_SIZE_BYTES) {
237 ALOGW("idmap: header too small (%d bytes)", (uint32_t) size);
241 const uint32_t magic = htodl(*reinterpret_cast<const uint32_t*>(idmap));
242 if (magic != IDMAP_MAGIC) {
243 ALOGW("idmap: no magic found in header (is 0x%08x, expected 0x%08x)",
248 const uint32_t version = htodl(*(reinterpret_cast<const uint32_t*>(idmap) + 1));
249 if (version != IDMAP_CURRENT_VERSION) {
250 // We are strict about versions because files with this format are
251 // auto-generated and don't need backwards compatibility.
252 ALOGW("idmap: version mismatch in header (is 0x%08x, expected 0x%08x)",
253 version, IDMAP_CURRENT_VERSION);
261 IdmapEntries() : mData(NULL) {}
263 bool hasEntries() const {
268 return (dtohs(*mData) > 0);
271 size_t byteSize() const {
275 uint16_t entryCount = dtohs(mData[2]);
276 return (sizeof(uint16_t) * 4) + (sizeof(uint32_t) * static_cast<size_t>(entryCount));
279 uint8_t targetTypeId() const {
283 return dtohs(mData[0]);
286 uint8_t overlayTypeId() const {
290 return dtohs(mData[1]);
293 status_t setTo(const void* entryHeader, size_t size) {
294 if (reinterpret_cast<uintptr_t>(entryHeader) & 0x03) {
295 ALOGE("idmap: entry header is not word aligned");
296 return UNKNOWN_ERROR;
299 if (size < sizeof(uint16_t) * 4) {
300 ALOGE("idmap: entry header is too small (%u bytes)", (uint32_t) size);
301 return UNKNOWN_ERROR;
304 const uint16_t* header = reinterpret_cast<const uint16_t*>(entryHeader);
305 const uint16_t targetTypeId = dtohs(header[0]);
306 const uint16_t overlayTypeId = dtohs(header[1]);
307 if (targetTypeId == 0 || overlayTypeId == 0 || targetTypeId > 255 || overlayTypeId > 255) {
308 ALOGE("idmap: invalid type map (%u -> %u)", targetTypeId, overlayTypeId);
309 return UNKNOWN_ERROR;
312 uint16_t entryCount = dtohs(header[2]);
313 if (size < sizeof(uint32_t) * (entryCount + 2)) {
314 ALOGE("idmap: too small (%u bytes) for the number of entries (%u)",
315 (uint32_t) size, (uint32_t) entryCount);
316 return UNKNOWN_ERROR;
322 status_t lookup(uint16_t entryId, uint16_t* outEntryId) const {
323 uint16_t entryCount = dtohs(mData[2]);
324 uint16_t offset = dtohs(mData[3]);
326 if (entryId < offset) {
327 // The entry is not present in this idmap
333 if (entryId >= entryCount) {
334 // The entry is not present in this idmap
338 // It is safe to access the type here without checking the size because
339 // we have checked this when it was first loaded.
340 const uint32_t* entries = reinterpret_cast<const uint32_t*>(mData) + 2;
341 uint32_t mappedEntry = dtohl(entries[entryId]);
342 if (mappedEntry == 0xffffffff) {
343 // This entry is not present in this idmap
346 *outEntryId = static_cast<uint16_t>(mappedEntry);
351 const uint16_t* mData;
354 status_t parseIdmap(const void* idmap, size_t size, uint8_t* outPackageId, KeyedVector<uint8_t, IdmapEntries>* outMap) {
355 if (!assertIdmapHeader(idmap, size)) {
356 return UNKNOWN_ERROR;
359 size -= ResTable::IDMAP_HEADER_SIZE_BYTES;
360 if (size < sizeof(uint16_t) * 2) {
361 ALOGE("idmap: too small to contain any mapping");
362 return UNKNOWN_ERROR;
365 const uint16_t* data = reinterpret_cast<const uint16_t*>(
366 reinterpret_cast<const uint8_t*>(idmap) + ResTable::IDMAP_HEADER_SIZE_BYTES);
368 uint16_t targetPackageId = dtohs(*(data++));
369 if (targetPackageId == 0 || targetPackageId > 255) {
370 ALOGE("idmap: target package ID is invalid (%02x)", targetPackageId);
371 return UNKNOWN_ERROR;
374 uint16_t mapCount = dtohs(*(data++));
376 ALOGE("idmap: no mappings");
377 return UNKNOWN_ERROR;
380 if (mapCount > 255) {
381 ALOGW("idmap: too many mappings. Only 255 are possible but %u are present", (uint32_t) mapCount);
384 while (size > sizeof(uint16_t) * 4) {
385 IdmapEntries entries;
386 status_t err = entries.setTo(data, size);
387 if (err != NO_ERROR) {
391 ssize_t index = outMap->add(entries.overlayTypeId(), entries);
396 data += entries.byteSize() / sizeof(uint16_t);
397 size -= entries.byteSize();
400 if (outPackageId != NULL) {
401 *outPackageId = static_cast<uint8_t>(targetPackageId);
406 Res_png_9patch* Res_png_9patch::deserialize(void* inData)
409 Res_png_9patch* patch = reinterpret_cast<Res_png_9patch*>(inData);
410 patch->wasDeserialized = true;
411 fill9patchOffsets(patch);
416 // --------------------------------------------------------------------
417 // --------------------------------------------------------------------
418 // --------------------------------------------------------------------
420 ResStringPool::ResStringPool()
421 : mError(NO_INIT), mOwnedData(NULL), mHeader(NULL), mCache(NULL)
425 ResStringPool::ResStringPool(const void* data, size_t size, bool copyData)
426 : mError(NO_INIT), mOwnedData(NULL), mHeader(NULL), mCache(NULL)
428 setTo(data, size, copyData);
431 ResStringPool::~ResStringPool()
436 void ResStringPool::setToEmpty()
440 mOwnedData = calloc(1, sizeof(ResStringPool_header));
441 ResStringPool_header* header = (ResStringPool_header*) mOwnedData;
449 mHeader = (const ResStringPool_header*) header;
452 status_t ResStringPool::setTo(const void* data, size_t size, bool copyData)
454 if (!data || !size) {
455 return (mError=BAD_TYPE);
460 // The chunk must be at least the size of the string pool header.
461 if (size < sizeof(ResStringPool_header)) {
462 ALOGW("Bad string block: data size %zu is too small to be a string block", size);
463 return (mError=BAD_TYPE);
466 // The data is at least as big as a ResChunk_header, so we can safely validate the other
468 // `data + size` is safe because the source of `size` comes from the kernel/filesystem.
469 if (validate_chunk(reinterpret_cast<const ResChunk_header*>(data), sizeof(ResStringPool_header),
470 reinterpret_cast<const uint8_t*>(data) + size,
471 "ResStringPool_header") != NO_ERROR) {
472 ALOGW("Bad string block: malformed block dimensions");
473 return (mError=BAD_TYPE);
476 const bool notDeviceEndian = htods(0xf0) != 0xf0;
478 if (copyData || notDeviceEndian) {
479 mOwnedData = malloc(size);
480 if (mOwnedData == NULL) {
481 return (mError=NO_MEMORY);
483 memcpy(mOwnedData, data, size);
487 // The size has been checked, so it is safe to read the data in the ResStringPool_header
489 mHeader = (const ResStringPool_header*)data;
491 if (notDeviceEndian) {
492 ResStringPool_header* h = const_cast<ResStringPool_header*>(mHeader);
493 h->header.headerSize = dtohs(mHeader->header.headerSize);
494 h->header.type = dtohs(mHeader->header.type);
495 h->header.size = dtohl(mHeader->header.size);
496 h->stringCount = dtohl(mHeader->stringCount);
497 h->styleCount = dtohl(mHeader->styleCount);
498 h->flags = dtohl(mHeader->flags);
499 h->stringsStart = dtohl(mHeader->stringsStart);
500 h->stylesStart = dtohl(mHeader->stylesStart);
503 if (mHeader->header.headerSize > mHeader->header.size
504 || mHeader->header.size > size) {
505 ALOGW("Bad string block: header size %d or total size %d is larger than data size %d\n",
506 (int)mHeader->header.headerSize, (int)mHeader->header.size, (int)size);
507 return (mError=BAD_TYPE);
509 mSize = mHeader->header.size;
510 mEntries = (const uint32_t*)
511 (((const uint8_t*)data)+mHeader->header.headerSize);
513 if (mHeader->stringCount > 0) {
514 if ((mHeader->stringCount*sizeof(uint32_t) < mHeader->stringCount) // uint32 overflow?
515 || (mHeader->header.headerSize+(mHeader->stringCount*sizeof(uint32_t)))
517 ALOGW("Bad string block: entry of %d items extends past data size %d\n",
518 (int)(mHeader->header.headerSize+(mHeader->stringCount*sizeof(uint32_t))),
520 return (mError=BAD_TYPE);
524 if (mHeader->flags&ResStringPool_header::UTF8_FLAG) {
525 charSize = sizeof(uint8_t);
527 charSize = sizeof(uint16_t);
530 // There should be at least space for the smallest string
531 // (2 bytes length, null terminator).
532 if (mHeader->stringsStart >= (mSize - sizeof(uint16_t))) {
533 ALOGW("Bad string block: string pool starts at %d, after total size %d\n",
534 (int)mHeader->stringsStart, (int)mHeader->header.size);
535 return (mError=BAD_TYPE);
538 mStrings = (const void*)
539 (((const uint8_t*)data) + mHeader->stringsStart);
541 if (mHeader->styleCount == 0) {
542 mStringPoolSize = (mSize - mHeader->stringsStart) / charSize;
544 // check invariant: styles starts before end of data
545 if (mHeader->stylesStart >= (mSize - sizeof(uint16_t))) {
546 ALOGW("Bad style block: style block starts at %d past data size of %d\n",
547 (int)mHeader->stylesStart, (int)mHeader->header.size);
548 return (mError=BAD_TYPE);
550 // check invariant: styles follow the strings
551 if (mHeader->stylesStart <= mHeader->stringsStart) {
552 ALOGW("Bad style block: style block starts at %d, before strings at %d\n",
553 (int)mHeader->stylesStart, (int)mHeader->stringsStart);
554 return (mError=BAD_TYPE);
557 (mHeader->stylesStart-mHeader->stringsStart)/charSize;
560 // check invariant: stringCount > 0 requires a string pool to exist
561 if (mStringPoolSize == 0) {
562 ALOGW("Bad string block: stringCount is %d but pool size is 0\n", (int)mHeader->stringCount);
563 return (mError=BAD_TYPE);
566 if (notDeviceEndian) {
568 uint32_t* e = const_cast<uint32_t*>(mEntries);
569 for (i=0; i<mHeader->stringCount; i++) {
570 e[i] = dtohl(mEntries[i]);
572 if (!(mHeader->flags&ResStringPool_header::UTF8_FLAG)) {
573 const uint16_t* strings = (const uint16_t*)mStrings;
574 uint16_t* s = const_cast<uint16_t*>(strings);
575 for (i=0; i<mStringPoolSize; i++) {
576 s[i] = dtohs(strings[i]);
581 if ((mHeader->flags&ResStringPool_header::UTF8_FLAG &&
582 ((uint8_t*)mStrings)[mStringPoolSize-1] != 0) ||
583 (!(mHeader->flags&ResStringPool_header::UTF8_FLAG) &&
584 ((uint16_t*)mStrings)[mStringPoolSize-1] != 0)) {
585 ALOGW("Bad string block: last string is not 0-terminated\n");
586 return (mError=BAD_TYPE);
593 if (mHeader->styleCount > 0) {
594 mEntryStyles = mEntries + mHeader->stringCount;
595 // invariant: integer overflow in calculating mEntryStyles
596 if (mEntryStyles < mEntries) {
597 ALOGW("Bad string block: integer overflow finding styles\n");
598 return (mError=BAD_TYPE);
601 if (((const uint8_t*)mEntryStyles-(const uint8_t*)mHeader) > (int)size) {
602 ALOGW("Bad string block: entry of %d styles extends past data size %d\n",
603 (int)((const uint8_t*)mEntryStyles-(const uint8_t*)mHeader),
605 return (mError=BAD_TYPE);
607 mStyles = (const uint32_t*)
608 (((const uint8_t*)data)+mHeader->stylesStart);
609 if (mHeader->stylesStart >= mHeader->header.size) {
610 ALOGW("Bad string block: style pool starts %d, after total size %d\n",
611 (int)mHeader->stylesStart, (int)mHeader->header.size);
612 return (mError=BAD_TYPE);
615 (mHeader->header.size-mHeader->stylesStart)/sizeof(uint32_t);
617 if (notDeviceEndian) {
619 uint32_t* e = const_cast<uint32_t*>(mEntryStyles);
620 for (i=0; i<mHeader->styleCount; i++) {
621 e[i] = dtohl(mEntryStyles[i]);
623 uint32_t* s = const_cast<uint32_t*>(mStyles);
624 for (i=0; i<mStylePoolSize; i++) {
625 s[i] = dtohl(mStyles[i]);
629 const ResStringPool_span endSpan = {
630 { htodl(ResStringPool_span::END) },
631 htodl(ResStringPool_span::END), htodl(ResStringPool_span::END)
633 if (memcmp(&mStyles[mStylePoolSize-(sizeof(endSpan)/sizeof(uint32_t))],
634 &endSpan, sizeof(endSpan)) != 0) {
635 ALOGW("Bad string block: last style is not 0xFFFFFFFF-terminated\n");
636 return (mError=BAD_TYPE);
644 return (mError=NO_ERROR);
647 status_t ResStringPool::getError() const
652 void ResStringPool::uninit()
655 if (mHeader != NULL && mCache != NULL) {
656 for (size_t x = 0; x < mHeader->stringCount; x++) {
657 if (mCache[x] != NULL) {
672 * Strings in UTF-16 format have length indicated by a length encoded in the
673 * stored data. It is either 1 or 2 characters of length data. This allows a
674 * maximum length of 0x7FFFFFF (2147483647 bytes), but if you're storing that
675 * much data in a string, you're abusing them.
677 * If the high bit is set, then there are two characters or 4 bytes of length
678 * data encoded. In that case, drop the high bit of the first character and
679 * add it together with the next character.
682 decodeLength(const uint16_t** str)
685 if ((len & 0x8000) != 0) {
687 len = ((len & 0x7FFF) << 16) | **str;
694 * Strings in UTF-8 format have length indicated by a length encoded in the
695 * stored data. It is either 1 or 2 characters of length data. This allows a
696 * maximum length of 0x7FFF (32767 bytes), but you should consider storing
697 * text in another way if you're using that much data in a single string.
699 * If the high bit is set, then there are two characters or 2 bytes of length
700 * data encoded. In that case, drop the high bit of the first character and
701 * add it together with the next character.
704 decodeLength(const uint8_t** str)
707 if ((len & 0x80) != 0) {
709 len = ((len & 0x7F) << 8) | **str;
715 const char16_t* ResStringPool::stringAt(size_t idx, size_t* u16len) const
717 if (mError == NO_ERROR && idx < mHeader->stringCount) {
718 const bool isUTF8 = (mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0;
719 const uint32_t off = mEntries[idx]/(isUTF8?sizeof(uint8_t):sizeof(uint16_t));
720 if (off < (mStringPoolSize-1)) {
722 const uint16_t* strings = (uint16_t*)mStrings;
723 const uint16_t* str = strings+off;
725 *u16len = decodeLength(&str);
726 if ((uint32_t)(str+*u16len-strings) < mStringPoolSize) {
727 // Reject malformed (non null-terminated) strings
728 if (str[*u16len] != 0x0000) {
729 ALOGW("Bad string block: string #%d is not null-terminated",
733 return reinterpret_cast<const char16_t*>(str);
735 ALOGW("Bad string block: string #%d extends to %d, past end at %d\n",
736 (int)idx, (int)(str+*u16len-strings), (int)mStringPoolSize);
739 const uint8_t* strings = (uint8_t*)mStrings;
740 const uint8_t* u8str = strings+off;
742 *u16len = decodeLength(&u8str);
743 size_t u8len = decodeLength(&u8str);
745 // encLen must be less than 0x7FFF due to encoding.
746 if ((uint32_t)(u8str+u8len-strings) < mStringPoolSize) {
747 AutoMutex lock(mDecodeLock);
749 if (mCache == NULL) {
751 if (kDebugStringPoolNoisy) {
752 ALOGI("CREATING STRING CACHE OF %zu bytes",
753 mHeader->stringCount*sizeof(char16_t**));
756 // We do not want to be in this case when actually running Android.
757 ALOGW("CREATING STRING CACHE OF %zu bytes",
758 static_cast<size_t>(mHeader->stringCount*sizeof(char16_t**)));
760 mCache = (char16_t**)calloc(mHeader->stringCount, sizeof(char16_t**));
761 if (mCache == NULL) {
762 ALOGW("No memory trying to allocate decode cache table of %d bytes\n",
763 (int)(mHeader->stringCount*sizeof(char16_t**)));
768 if (mCache[idx] != NULL) {
772 ssize_t actualLen = utf8_to_utf16_length(u8str, u8len);
773 if (actualLen < 0 || (size_t)actualLen != *u16len) {
774 ALOGW("Bad string block: string #%lld decoded length is not correct "
776 (long long)idx, (long long)actualLen, (long long)*u16len);
780 // Reject malformed (non null-terminated) strings
781 if (u8str[u8len] != 0x00) {
782 ALOGW("Bad string block: string #%d is not null-terminated",
787 char16_t *u16str = (char16_t *)calloc(*u16len+1, sizeof(char16_t));
789 ALOGW("No memory when trying to allocate decode cache for string #%d\n",
794 if (kDebugStringPoolNoisy) {
795 ALOGI("Caching UTF8 string: %s", u8str);
797 utf8_to_utf16(u8str, u8len, u16str);
798 mCache[idx] = u16str;
801 ALOGW("Bad string block: string #%lld extends to %lld, past end at %lld\n",
802 (long long)idx, (long long)(u8str+u8len-strings),
803 (long long)mStringPoolSize);
807 ALOGW("Bad string block: string #%d entry is at %d, past end at %d\n",
808 (int)idx, (int)(off*sizeof(uint16_t)),
809 (int)(mStringPoolSize*sizeof(uint16_t)));
815 const char* ResStringPool::string8At(size_t idx, size_t* outLen) const
817 if (mError == NO_ERROR && idx < mHeader->stringCount) {
818 if ((mHeader->flags&ResStringPool_header::UTF8_FLAG) == 0) {
821 const uint32_t off = mEntries[idx]/sizeof(char);
822 if (off < (mStringPoolSize-1)) {
823 const uint8_t* strings = (uint8_t*)mStrings;
824 const uint8_t* str = strings+off;
825 *outLen = decodeLength(&str);
826 size_t encLen = decodeLength(&str);
827 if ((uint32_t)(str+encLen-strings) < mStringPoolSize) {
828 // Reject malformed (non null-terminated) strings
829 if (str[encLen] != 0x00) {
830 ALOGW("Bad string block: string #%d is not null-terminated",
834 return (const char*)str;
836 ALOGW("Bad string block: string #%d extends to %d, past end at %d\n",
837 (int)idx, (int)(str+encLen-strings), (int)mStringPoolSize);
840 ALOGW("Bad string block: string #%d entry is at %d, past end at %d\n",
841 (int)idx, (int)(off*sizeof(uint16_t)),
842 (int)(mStringPoolSize*sizeof(uint16_t)));
848 const String8 ResStringPool::string8ObjectAt(size_t idx) const
851 const char *str = string8At(idx, &len);
853 return String8(str, len);
856 const char16_t *str16 = stringAt(idx, &len);
858 return String8(str16, len);
863 const ResStringPool_span* ResStringPool::styleAt(const ResStringPool_ref& ref) const
865 return styleAt(ref.index);
868 const ResStringPool_span* ResStringPool::styleAt(size_t idx) const
870 if (mError == NO_ERROR && idx < mHeader->styleCount) {
871 const uint32_t off = (mEntryStyles[idx]/sizeof(uint32_t));
872 if (off < mStylePoolSize) {
873 return (const ResStringPool_span*)(mStyles+off);
875 ALOGW("Bad string block: style #%d entry is at %d, past end at %d\n",
876 (int)idx, (int)(off*sizeof(uint32_t)),
877 (int)(mStylePoolSize*sizeof(uint32_t)));
883 ssize_t ResStringPool::indexOfString(const char16_t* str, size_t strLen) const
885 if (mError != NO_ERROR) {
891 if ((mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0) {
892 if (kDebugStringPoolNoisy) {
893 ALOGI("indexOfString UTF-8: %s", String8(str, strLen).string());
896 // The string pool contains UTF 8 strings; we don't want to cause
897 // temporary UTF-16 strings to be created as we search.
898 if (mHeader->flags&ResStringPool_header::SORTED_FLAG) {
899 // Do a binary search for the string... this is a little tricky,
900 // because the strings are sorted with strzcmp16(). So to match
901 // the ordering, we need to convert strings in the pool to UTF-16.
902 // But we don't want to hit the cache, so instead we will have a
903 // local temporary allocation for the conversions.
904 char16_t* convBuffer = (char16_t*)malloc(strLen+4);
906 ssize_t h = mHeader->stringCount-1;
911 const uint8_t* s = (const uint8_t*)string8At(mid, &len);
914 char16_t* end = utf8_to_utf16_n(s, len, convBuffer, strLen+3);
916 c = strzcmp16(convBuffer, end-convBuffer, str, strLen);
920 if (kDebugStringPoolNoisy) {
921 ALOGI("Looking at %s, cmp=%d, l/mid/h=%d/%d/%d\n",
922 (const char*)s, c, (int)l, (int)mid, (int)h);
925 if (kDebugStringPoolNoisy) {
938 // It is unusual to get the ID from an unsorted string block...
939 // most often this happens because we want to get IDs for style
940 // span tags; since those always appear at the end of the string
941 // block, start searching at the back.
942 String8 str8(str, strLen);
943 const size_t str8Len = str8.size();
944 for (int i=mHeader->stringCount-1; i>=0; i--) {
945 const char* s = string8At(i, &len);
946 if (kDebugStringPoolNoisy) {
947 ALOGI("Looking at %s, i=%d\n", String8(s).string(), i);
949 if (s && str8Len == len && memcmp(s, str8.string(), str8Len) == 0) {
950 if (kDebugStringPoolNoisy) {
959 if (kDebugStringPoolNoisy) {
960 ALOGI("indexOfString UTF-16: %s", String8(str, strLen).string());
963 if (mHeader->flags&ResStringPool_header::SORTED_FLAG) {
964 // Do a binary search for the string...
966 ssize_t h = mHeader->stringCount-1;
971 const char16_t* s = stringAt(mid, &len);
972 int c = s ? strzcmp16(s, len, str, strLen) : -1;
973 if (kDebugStringPoolNoisy) {
974 ALOGI("Looking at %s, cmp=%d, l/mid/h=%d/%d/%d\n",
975 String8(s).string(), c, (int)l, (int)mid, (int)h);
978 if (kDebugStringPoolNoisy) {
989 // It is unusual to get the ID from an unsorted string block...
990 // most often this happens because we want to get IDs for style
991 // span tags; since those always appear at the end of the string
992 // block, start searching at the back.
993 for (int i=mHeader->stringCount-1; i>=0; i--) {
994 const char16_t* s = stringAt(i, &len);
995 if (kDebugStringPoolNoisy) {
996 ALOGI("Looking at %s, i=%d\n", String8(s).string(), i);
998 if (s && strLen == len && strzcmp16(s, len, str, strLen) == 0) {
999 if (kDebugStringPoolNoisy) {
1008 return NAME_NOT_FOUND;
1011 size_t ResStringPool::size() const
1013 return (mError == NO_ERROR) ? mHeader->stringCount : 0;
1016 size_t ResStringPool::styleCount() const
1018 return (mError == NO_ERROR) ? mHeader->styleCount : 0;
1021 size_t ResStringPool::bytes() const
1023 return (mError == NO_ERROR) ? mHeader->header.size : 0;
1026 bool ResStringPool::isSorted() const
1028 return (mHeader->flags&ResStringPool_header::SORTED_FLAG)!=0;
1031 bool ResStringPool::isUTF8() const
1033 return (mHeader->flags&ResStringPool_header::UTF8_FLAG)!=0;
1036 // --------------------------------------------------------------------
1037 // --------------------------------------------------------------------
1038 // --------------------------------------------------------------------
1040 ResXMLParser::ResXMLParser(const ResXMLTree& tree)
1041 : mTree(tree), mEventCode(BAD_DOCUMENT)
1045 void ResXMLParser::restart()
1048 mEventCode = mTree.mError == NO_ERROR ? START_DOCUMENT : BAD_DOCUMENT;
1050 const ResStringPool& ResXMLParser::getStrings() const
1052 return mTree.mStrings;
1055 ResXMLParser::event_code_t ResXMLParser::getEventType() const
1060 ResXMLParser::event_code_t ResXMLParser::next()
1062 if (mEventCode == START_DOCUMENT) {
1063 mCurNode = mTree.mRootNode;
1064 mCurExt = mTree.mRootExt;
1065 return (mEventCode=mTree.mRootCode);
1066 } else if (mEventCode >= FIRST_CHUNK_CODE) {
1072 int32_t ResXMLParser::getCommentID() const
1074 return mCurNode != NULL ? dtohl(mCurNode->comment.index) : -1;
1077 const char16_t* ResXMLParser::getComment(size_t* outLen) const
1079 int32_t id = getCommentID();
1080 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1083 uint32_t ResXMLParser::getLineNumber() const
1085 return mCurNode != NULL ? dtohl(mCurNode->lineNumber) : -1;
1088 int32_t ResXMLParser::getTextID() const
1090 if (mEventCode == TEXT) {
1091 return dtohl(((const ResXMLTree_cdataExt*)mCurExt)->data.index);
1096 const char16_t* ResXMLParser::getText(size_t* outLen) const
1098 int32_t id = getTextID();
1099 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1102 ssize_t ResXMLParser::getTextValue(Res_value* outValue) const
1104 if (mEventCode == TEXT) {
1105 outValue->copyFrom_dtoh(((const ResXMLTree_cdataExt*)mCurExt)->typedData);
1106 return sizeof(Res_value);
1111 int32_t ResXMLParser::getNamespacePrefixID() const
1113 if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) {
1114 return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->prefix.index);
1119 const char16_t* ResXMLParser::getNamespacePrefix(size_t* outLen) const
1121 int32_t id = getNamespacePrefixID();
1122 //printf("prefix=%d event=%p\n", id, mEventCode);
1123 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1126 int32_t ResXMLParser::getNamespaceUriID() const
1128 if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) {
1129 return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->uri.index);
1134 const char16_t* ResXMLParser::getNamespaceUri(size_t* outLen) const
1136 int32_t id = getNamespaceUriID();
1137 //printf("uri=%d event=%p\n", id, mEventCode);
1138 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1141 int32_t ResXMLParser::getElementNamespaceID() const
1143 if (mEventCode == START_TAG) {
1144 return dtohl(((const ResXMLTree_attrExt*)mCurExt)->ns.index);
1146 if (mEventCode == END_TAG) {
1147 return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->ns.index);
1152 const char16_t* ResXMLParser::getElementNamespace(size_t* outLen) const
1154 int32_t id = getElementNamespaceID();
1155 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1158 int32_t ResXMLParser::getElementNameID() const
1160 if (mEventCode == START_TAG) {
1161 return dtohl(((const ResXMLTree_attrExt*)mCurExt)->name.index);
1163 if (mEventCode == END_TAG) {
1164 return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->name.index);
1169 const char16_t* ResXMLParser::getElementName(size_t* outLen) const
1171 int32_t id = getElementNameID();
1172 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1175 size_t ResXMLParser::getAttributeCount() const
1177 if (mEventCode == START_TAG) {
1178 return dtohs(((const ResXMLTree_attrExt*)mCurExt)->attributeCount);
1183 int32_t ResXMLParser::getAttributeNamespaceID(size_t idx) const
1185 if (mEventCode == START_TAG) {
1186 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1187 if (idx < dtohs(tag->attributeCount)) {
1188 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1189 (((const uint8_t*)tag)
1190 + dtohs(tag->attributeStart)
1191 + (dtohs(tag->attributeSize)*idx));
1192 return dtohl(attr->ns.index);
1198 const char16_t* ResXMLParser::getAttributeNamespace(size_t idx, size_t* outLen) const
1200 int32_t id = getAttributeNamespaceID(idx);
1201 //printf("attribute namespace=%d idx=%d event=%p\n", id, idx, mEventCode);
1202 if (kDebugXMLNoisy) {
1203 printf("getAttributeNamespace 0x%zx=0x%x\n", idx, id);
1205 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1208 const char* ResXMLParser::getAttributeNamespace8(size_t idx, size_t* outLen) const
1210 int32_t id = getAttributeNamespaceID(idx);
1211 //printf("attribute namespace=%d idx=%d event=%p\n", id, idx, mEventCode);
1212 if (kDebugXMLNoisy) {
1213 printf("getAttributeNamespace 0x%zx=0x%x\n", idx, id);
1215 return id >= 0 ? mTree.mStrings.string8At(id, outLen) : NULL;
1218 int32_t ResXMLParser::getAttributeNameID(size_t idx) const
1220 if (mEventCode == START_TAG) {
1221 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1222 if (idx < dtohs(tag->attributeCount)) {
1223 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1224 (((const uint8_t*)tag)
1225 + dtohs(tag->attributeStart)
1226 + (dtohs(tag->attributeSize)*idx));
1227 return dtohl(attr->name.index);
1233 const char16_t* ResXMLParser::getAttributeName(size_t idx, size_t* outLen) const
1235 int32_t id = getAttributeNameID(idx);
1236 //printf("attribute name=%d idx=%d event=%p\n", id, idx, mEventCode);
1237 if (kDebugXMLNoisy) {
1238 printf("getAttributeName 0x%zx=0x%x\n", idx, id);
1240 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1243 const char* ResXMLParser::getAttributeName8(size_t idx, size_t* outLen) const
1245 int32_t id = getAttributeNameID(idx);
1246 //printf("attribute name=%d idx=%d event=%p\n", id, idx, mEventCode);
1247 if (kDebugXMLNoisy) {
1248 printf("getAttributeName 0x%zx=0x%x\n", idx, id);
1250 return id >= 0 ? mTree.mStrings.string8At(id, outLen) : NULL;
1253 uint32_t ResXMLParser::getAttributeNameResID(size_t idx) const
1255 int32_t id = getAttributeNameID(idx);
1256 if (id >= 0 && (size_t)id < mTree.mNumResIds) {
1257 uint32_t resId = dtohl(mTree.mResIds[id]);
1258 if (mTree.mDynamicRefTable != NULL) {
1259 mTree.mDynamicRefTable->lookupResourceId(&resId);
1266 int32_t ResXMLParser::getAttributeValueStringID(size_t idx) const
1268 if (mEventCode == START_TAG) {
1269 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1270 if (idx < dtohs(tag->attributeCount)) {
1271 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1272 (((const uint8_t*)tag)
1273 + dtohs(tag->attributeStart)
1274 + (dtohs(tag->attributeSize)*idx));
1275 return dtohl(attr->rawValue.index);
1281 const char16_t* ResXMLParser::getAttributeStringValue(size_t idx, size_t* outLen) const
1283 int32_t id = getAttributeValueStringID(idx);
1284 if (kDebugXMLNoisy) {
1285 printf("getAttributeValue 0x%zx=0x%x\n", idx, id);
1287 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1290 int32_t ResXMLParser::getAttributeDataType(size_t idx) const
1292 if (mEventCode == START_TAG) {
1293 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1294 if (idx < dtohs(tag->attributeCount)) {
1295 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1296 (((const uint8_t*)tag)
1297 + dtohs(tag->attributeStart)
1298 + (dtohs(tag->attributeSize)*idx));
1299 uint8_t type = attr->typedValue.dataType;
1300 if (type != Res_value::TYPE_DYNAMIC_REFERENCE) {
1304 // This is a dynamic reference. We adjust those references
1305 // to regular references at this level, so lie to the caller.
1306 return Res_value::TYPE_REFERENCE;
1309 return Res_value::TYPE_NULL;
1312 int32_t ResXMLParser::getAttributeData(size_t idx) const
1314 if (mEventCode == START_TAG) {
1315 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1316 if (idx < dtohs(tag->attributeCount)) {
1317 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1318 (((const uint8_t*)tag)
1319 + dtohs(tag->attributeStart)
1320 + (dtohs(tag->attributeSize)*idx));
1321 if (attr->typedValue.dataType != Res_value::TYPE_DYNAMIC_REFERENCE ||
1322 mTree.mDynamicRefTable == NULL) {
1323 return dtohl(attr->typedValue.data);
1326 uint32_t data = dtohl(attr->typedValue.data);
1327 if (mTree.mDynamicRefTable->lookupResourceId(&data) == NO_ERROR) {
1335 ssize_t ResXMLParser::getAttributeValue(size_t idx, Res_value* outValue) const
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 outValue->copyFrom_dtoh(attr->typedValue);
1345 if (mTree.mDynamicRefTable != NULL &&
1346 mTree.mDynamicRefTable->lookupResourceValue(outValue) != NO_ERROR) {
1349 return sizeof(Res_value);
1355 ssize_t ResXMLParser::indexOfAttribute(const char* ns, const char* attr) const
1357 String16 nsStr(ns != NULL ? ns : "");
1358 String16 attrStr(attr);
1359 return indexOfAttribute(ns ? nsStr.string() : NULL, ns ? nsStr.size() : 0,
1360 attrStr.string(), attrStr.size());
1363 ssize_t ResXMLParser::indexOfAttribute(const char16_t* ns, size_t nsLen,
1364 const char16_t* attr, size_t attrLen) const
1366 if (mEventCode == START_TAG) {
1368 return NAME_NOT_FOUND;
1370 const size_t N = getAttributeCount();
1371 if (mTree.mStrings.isUTF8()) {
1374 ns8 = String8(ns, nsLen);
1376 attr8 = String8(attr, attrLen);
1377 if (kDebugStringPoolNoisy) {
1378 ALOGI("indexOfAttribute UTF8 %s (%zu) / %s (%zu)", ns8.string(), nsLen,
1379 attr8.string(), attrLen);
1381 for (size_t i=0; i<N; i++) {
1382 size_t curNsLen = 0, curAttrLen = 0;
1383 const char* curNs = getAttributeNamespace8(i, &curNsLen);
1384 const char* curAttr = getAttributeName8(i, &curAttrLen);
1385 if (kDebugStringPoolNoisy) {
1386 ALOGI(" curNs=%s (%zu), curAttr=%s (%zu)", curNs, curNsLen, curAttr, curAttrLen);
1388 if (curAttr != NULL && curNsLen == nsLen && curAttrLen == attrLen
1389 && memcmp(attr8.string(), curAttr, attrLen) == 0) {
1391 if (curNs == NULL) {
1392 if (kDebugStringPoolNoisy) {
1397 } else if (curNs != NULL) {
1398 //printf(" --> ns=%s, curNs=%s\n",
1399 // String8(ns).string(), String8(curNs).string());
1400 if (memcmp(ns8.string(), curNs, nsLen) == 0) {
1401 if (kDebugStringPoolNoisy) {
1410 if (kDebugStringPoolNoisy) {
1411 ALOGI("indexOfAttribute UTF16 %s (%zu) / %s (%zu)",
1412 String8(ns, nsLen).string(), nsLen,
1413 String8(attr, attrLen).string(), attrLen);
1415 for (size_t i=0; i<N; i++) {
1416 size_t curNsLen = 0, curAttrLen = 0;
1417 const char16_t* curNs = getAttributeNamespace(i, &curNsLen);
1418 const char16_t* curAttr = getAttributeName(i, &curAttrLen);
1419 if (kDebugStringPoolNoisy) {
1420 ALOGI(" curNs=%s (%zu), curAttr=%s (%zu)",
1421 String8(curNs, curNsLen).string(), curNsLen,
1422 String8(curAttr, curAttrLen).string(), curAttrLen);
1424 if (curAttr != NULL && curNsLen == nsLen && curAttrLen == attrLen
1425 && (memcmp(attr, curAttr, attrLen*sizeof(char16_t)) == 0)) {
1427 if (curNs == NULL) {
1428 if (kDebugStringPoolNoisy) {
1433 } else if (curNs != NULL) {
1434 //printf(" --> ns=%s, curNs=%s\n",
1435 // String8(ns).string(), String8(curNs).string());
1436 if (memcmp(ns, curNs, nsLen*sizeof(char16_t)) == 0) {
1437 if (kDebugStringPoolNoisy) {
1448 return NAME_NOT_FOUND;
1451 ssize_t ResXMLParser::indexOfID() const
1453 if (mEventCode == START_TAG) {
1454 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->idIndex);
1455 if (idx > 0) return (idx-1);
1457 return NAME_NOT_FOUND;
1460 ssize_t ResXMLParser::indexOfClass() const
1462 if (mEventCode == START_TAG) {
1463 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->classIndex);
1464 if (idx > 0) return (idx-1);
1466 return NAME_NOT_FOUND;
1469 ssize_t ResXMLParser::indexOfStyle() const
1471 if (mEventCode == START_TAG) {
1472 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->styleIndex);
1473 if (idx > 0) return (idx-1);
1475 return NAME_NOT_FOUND;
1478 ResXMLParser::event_code_t ResXMLParser::nextNode()
1480 if (mEventCode < 0) {
1485 const ResXMLTree_node* next = (const ResXMLTree_node*)
1486 (((const uint8_t*)mCurNode) + dtohl(mCurNode->header.size));
1487 if (kDebugXMLNoisy) {
1488 ALOGI("Next node: prev=%p, next=%p\n", mCurNode, next);
1491 if (((const uint8_t*)next) >= mTree.mDataEnd) {
1493 return (mEventCode=END_DOCUMENT);
1496 if (mTree.validateNode(next) != NO_ERROR) {
1498 return (mEventCode=BAD_DOCUMENT);
1502 const uint16_t headerSize = dtohs(next->header.headerSize);
1503 const uint32_t totalSize = dtohl(next->header.size);
1504 mCurExt = ((const uint8_t*)next) + headerSize;
1505 size_t minExtSize = 0;
1506 event_code_t eventCode = (event_code_t)dtohs(next->header.type);
1507 switch ((mEventCode=eventCode)) {
1508 case RES_XML_START_NAMESPACE_TYPE:
1509 case RES_XML_END_NAMESPACE_TYPE:
1510 minExtSize = sizeof(ResXMLTree_namespaceExt);
1512 case RES_XML_START_ELEMENT_TYPE:
1513 minExtSize = sizeof(ResXMLTree_attrExt);
1515 case RES_XML_END_ELEMENT_TYPE:
1516 minExtSize = sizeof(ResXMLTree_endElementExt);
1518 case RES_XML_CDATA_TYPE:
1519 minExtSize = sizeof(ResXMLTree_cdataExt);
1522 ALOGW("Unknown XML block: header type %d in node at %d\n",
1523 (int)dtohs(next->header.type),
1524 (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)));
1528 if ((totalSize-headerSize) < minExtSize) {
1529 ALOGW("Bad XML block: header type 0x%x in node at 0x%x has size %d, need %d\n",
1530 (int)dtohs(next->header.type),
1531 (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)),
1532 (int)(totalSize-headerSize), (int)minExtSize);
1533 return (mEventCode=BAD_DOCUMENT);
1536 //printf("CurNode=%p, CurExt=%p, headerSize=%d, minExtSize=%d\n",
1537 // mCurNode, mCurExt, headerSize, minExtSize);
1543 void ResXMLParser::getPosition(ResXMLParser::ResXMLPosition* pos) const
1545 pos->eventCode = mEventCode;
1546 pos->curNode = mCurNode;
1547 pos->curExt = mCurExt;
1550 void ResXMLParser::setPosition(const ResXMLParser::ResXMLPosition& pos)
1552 mEventCode = pos.eventCode;
1553 mCurNode = pos.curNode;
1554 mCurExt = pos.curExt;
1557 // --------------------------------------------------------------------
1559 static volatile int32_t gCount = 0;
1561 ResXMLTree::ResXMLTree(const DynamicRefTable* dynamicRefTable)
1562 : ResXMLParser(*this)
1563 , mDynamicRefTable(dynamicRefTable)
1564 , mError(NO_INIT), mOwnedData(NULL)
1566 if (kDebugResXMLTree) {
1567 ALOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1);
1572 ResXMLTree::ResXMLTree()
1573 : ResXMLParser(*this)
1574 , mDynamicRefTable(NULL)
1575 , mError(NO_INIT), mOwnedData(NULL)
1577 if (kDebugResXMLTree) {
1578 ALOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1);
1583 ResXMLTree::~ResXMLTree()
1585 if (kDebugResXMLTree) {
1586 ALOGI("Destroying ResXMLTree in %p #%d\n", this, android_atomic_dec(&gCount)-1);
1591 status_t ResXMLTree::setTo(const void* data, size_t size, bool copyData)
1594 mEventCode = START_DOCUMENT;
1596 if (!data || !size) {
1597 return (mError=BAD_TYPE);
1601 mOwnedData = malloc(size);
1602 if (mOwnedData == NULL) {
1603 return (mError=NO_MEMORY);
1605 memcpy(mOwnedData, data, size);
1609 mHeader = (const ResXMLTree_header*)data;
1610 mSize = dtohl(mHeader->header.size);
1611 if (dtohs(mHeader->header.headerSize) > mSize || mSize > size) {
1612 ALOGW("Bad XML block: header size %d or total size %d is larger than data size %d\n",
1613 (int)dtohs(mHeader->header.headerSize),
1614 (int)dtohl(mHeader->header.size), (int)size);
1619 mDataEnd = ((const uint8_t*)mHeader) + mSize;
1626 // First look for a couple interesting chunks: the string block
1627 // and first XML node.
1628 const ResChunk_header* chunk =
1629 (const ResChunk_header*)(((const uint8_t*)mHeader) + dtohs(mHeader->header.headerSize));
1630 const ResChunk_header* lastChunk = chunk;
1631 while (((const uint8_t*)chunk) < (mDataEnd-sizeof(ResChunk_header)) &&
1632 ((const uint8_t*)chunk) < (mDataEnd-dtohl(chunk->size))) {
1633 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), mDataEnd, "XML");
1634 if (err != NO_ERROR) {
1638 const uint16_t type = dtohs(chunk->type);
1639 const size_t size = dtohl(chunk->size);
1640 if (kDebugXMLNoisy) {
1641 printf("Scanning @ %p: type=0x%x, size=0x%zx\n",
1642 (void*)(((uintptr_t)chunk)-((uintptr_t)mHeader)), type, size);
1644 if (type == RES_STRING_POOL_TYPE) {
1645 mStrings.setTo(chunk, size);
1646 } else if (type == RES_XML_RESOURCE_MAP_TYPE) {
1647 mResIds = (const uint32_t*)
1648 (((const uint8_t*)chunk)+dtohs(chunk->headerSize));
1649 mNumResIds = (dtohl(chunk->size)-dtohs(chunk->headerSize))/sizeof(uint32_t);
1650 } else if (type >= RES_XML_FIRST_CHUNK_TYPE
1651 && type <= RES_XML_LAST_CHUNK_TYPE) {
1652 if (validateNode((const ResXMLTree_node*)chunk) != NO_ERROR) {
1656 mCurNode = (const ResXMLTree_node*)lastChunk;
1657 if (nextNode() == BAD_DOCUMENT) {
1661 mRootNode = mCurNode;
1663 mRootCode = mEventCode;
1666 if (kDebugXMLNoisy) {
1667 printf("Skipping unknown chunk!\n");
1671 chunk = (const ResChunk_header*)
1672 (((const uint8_t*)chunk) + size);
1675 if (mRootNode == NULL) {
1676 ALOGW("Bad XML block: no root element node found\n");
1681 mError = mStrings.getError();
1688 status_t ResXMLTree::getError() const
1693 void ResXMLTree::uninit()
1704 status_t ResXMLTree::validateNode(const ResXMLTree_node* node) const
1706 const uint16_t eventCode = dtohs(node->header.type);
1708 status_t err = validate_chunk(
1709 &node->header, sizeof(ResXMLTree_node),
1710 mDataEnd, "ResXMLTree_node");
1712 if (err >= NO_ERROR) {
1713 // Only perform additional validation on START nodes
1714 if (eventCode != RES_XML_START_ELEMENT_TYPE) {
1718 const uint16_t headerSize = dtohs(node->header.headerSize);
1719 const uint32_t size = dtohl(node->header.size);
1720 const ResXMLTree_attrExt* attrExt = (const ResXMLTree_attrExt*)
1721 (((const uint8_t*)node) + headerSize);
1722 // check for sensical values pulled out of the stream so far...
1723 if ((size >= headerSize + sizeof(ResXMLTree_attrExt))
1724 && ((void*)attrExt > (void*)node)) {
1725 const size_t attrSize = ((size_t)dtohs(attrExt->attributeSize))
1726 * dtohs(attrExt->attributeCount);
1727 if ((dtohs(attrExt->attributeStart)+attrSize) <= (size-headerSize)) {
1730 ALOGW("Bad XML block: node attributes use 0x%x bytes, only have 0x%x bytes\n",
1731 (unsigned int)(dtohs(attrExt->attributeStart)+attrSize),
1732 (unsigned int)(size-headerSize));
1735 ALOGW("Bad XML start block: node header size 0x%x, size 0x%x\n",
1736 (unsigned int)headerSize, (unsigned int)size);
1744 const bool isStart = dtohs(node->header.type) == RES_XML_START_ELEMENT_TYPE;
1746 const uint16_t headerSize = dtohs(node->header.headerSize);
1747 const uint32_t size = dtohl(node->header.size);
1749 if (headerSize >= (isStart ? sizeof(ResXMLTree_attrNode) : sizeof(ResXMLTree_node))) {
1750 if (size >= headerSize) {
1751 if (((const uint8_t*)node) <= (mDataEnd-size)) {
1755 if ((((size_t)dtohs(node->attributeSize))*dtohs(node->attributeCount))
1756 <= (size-headerSize)) {
1759 ALOGW("Bad XML block: node attributes use 0x%x bytes, only have 0x%x bytes\n",
1760 ((int)dtohs(node->attributeSize))*dtohs(node->attributeCount),
1761 (int)(size-headerSize));
1764 ALOGW("Bad XML block: node at 0x%x extends beyond data end 0x%x\n",
1765 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)), (int)mSize);
1768 ALOGW("Bad XML block: node at 0x%x header size 0x%x smaller than total size 0x%x\n",
1769 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)),
1770 (int)headerSize, (int)size);
1773 ALOGW("Bad XML block: node at 0x%x header size 0x%x too small\n",
1774 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)),
1780 // --------------------------------------------------------------------
1781 // --------------------------------------------------------------------
1782 // --------------------------------------------------------------------
1784 void ResTable_config::copyFromDeviceNoSwap(const ResTable_config& o) {
1785 const size_t size = dtohl(o.size);
1786 if (size >= sizeof(ResTable_config)) {
1789 memcpy(this, &o, size);
1790 memset(((uint8_t*)this)+size, 0, sizeof(ResTable_config)-size);
1794 /* static */ size_t unpackLanguageOrRegion(const char in[2], const char base,
1797 // The high bit is "1", which means this is a packed three letter
1800 // The smallest 5 bits of the second char are the first alphabet.
1801 const uint8_t first = in[1] & 0x1f;
1802 // The last three bits of the second char and the first two bits
1803 // of the first char are the second alphabet.
1804 const uint8_t second = ((in[1] & 0xe0) >> 5) + ((in[0] & 0x03) << 3);
1805 // Bits 3 to 7 (inclusive) of the first char are the third alphabet.
1806 const uint8_t third = (in[0] & 0x7c) >> 2;
1808 out[0] = first + base;
1809 out[1] = second + base;
1810 out[2] = third + base;
1818 memset(out + 2, 0, 2);
1826 /* static */ void packLanguageOrRegion(const char* in, const char base,
1828 if (in[2] == 0 || in[2] == '-') {
1832 uint8_t first = (in[0] - base) & 0x007f;
1833 uint8_t second = (in[1] - base) & 0x007f;
1834 uint8_t third = (in[2] - base) & 0x007f;
1836 out[0] = (0x80 | (third << 2) | (second >> 3));
1837 out[1] = ((second << 5) | first);
1842 void ResTable_config::packLanguage(const char* language) {
1843 packLanguageOrRegion(language, 'a', this->language);
1846 void ResTable_config::packRegion(const char* region) {
1847 packLanguageOrRegion(region, '0', this->country);
1850 size_t ResTable_config::unpackLanguage(char language[4]) const {
1851 return unpackLanguageOrRegion(this->language, 'a', language);
1854 size_t ResTable_config::unpackRegion(char region[4]) const {
1855 return unpackLanguageOrRegion(this->country, '0', region);
1859 void ResTable_config::copyFromDtoH(const ResTable_config& o) {
1860 copyFromDeviceNoSwap(o);
1861 size = sizeof(ResTable_config);
1864 density = dtohs(density);
1865 screenWidth = dtohs(screenWidth);
1866 screenHeight = dtohs(screenHeight);
1867 sdkVersion = dtohs(sdkVersion);
1868 minorVersion = dtohs(minorVersion);
1869 smallestScreenWidthDp = dtohs(smallestScreenWidthDp);
1870 screenWidthDp = dtohs(screenWidthDp);
1871 screenHeightDp = dtohs(screenHeightDp);
1874 void ResTable_config::swapHtoD() {
1878 density = htods(density);
1879 screenWidth = htods(screenWidth);
1880 screenHeight = htods(screenHeight);
1881 sdkVersion = htods(sdkVersion);
1882 minorVersion = htods(minorVersion);
1883 smallestScreenWidthDp = htods(smallestScreenWidthDp);
1884 screenWidthDp = htods(screenWidthDp);
1885 screenHeightDp = htods(screenHeightDp);
1888 /* static */ inline int compareLocales(const ResTable_config &l, const ResTable_config &r) {
1889 if (l.locale != r.locale) {
1890 // NOTE: This is the old behaviour with respect to comparison orders.
1891 // The diff value here doesn't make much sense (given our bit packing scheme)
1892 // but it's stable, and that's all we need.
1893 return l.locale - r.locale;
1896 // The language & region are equal, so compare the scripts and variants.
1897 const char emptyScript[sizeof(l.localeScript)] = {'\0', '\0', '\0', '\0'};
1898 const char *lScript = l.localeScriptWasComputed ? emptyScript : l.localeScript;
1899 const char *rScript = r.localeScriptWasComputed ? emptyScript : r.localeScript;
1900 int script = memcmp(lScript, rScript, sizeof(l.localeScript));
1905 // The language, region and script are equal, so compare variants.
1907 // This should happen very infrequently (if at all.)
1908 return memcmp(l.localeVariant, r.localeVariant, sizeof(l.localeVariant));
1911 int ResTable_config::compare(const ResTable_config& o) const {
1912 int32_t diff = (int32_t)(imsi - o.imsi);
1913 if (diff != 0) return diff;
1914 diff = compareLocales(*this, o);
1915 if (diff != 0) return diff;
1916 diff = (int32_t)(screenType - o.screenType);
1917 if (diff != 0) return diff;
1918 diff = (int32_t)(input - o.input);
1919 if (diff != 0) return diff;
1920 diff = (int32_t)(screenSize - o.screenSize);
1921 if (diff != 0) return diff;
1922 diff = (int32_t)(version - o.version);
1923 if (diff != 0) return diff;
1924 diff = (int32_t)(screenLayout - o.screenLayout);
1925 if (diff != 0) return diff;
1926 diff = (int32_t)(screenLayout2 - o.screenLayout2);
1927 if (diff != 0) return diff;
1928 diff = (int32_t)(uiMode - o.uiMode);
1929 if (diff != 0) return diff;
1930 diff = (int32_t)(smallestScreenWidthDp - o.smallestScreenWidthDp);
1931 if (diff != 0) return diff;
1932 diff = (int32_t)(screenSizeDp - o.screenSizeDp);
1936 int ResTable_config::compareLogical(const ResTable_config& o) const {
1938 return mcc < o.mcc ? -1 : 1;
1941 return mnc < o.mnc ? -1 : 1;
1944 int diff = compareLocales(*this, o);
1952 if ((screenLayout & MASK_LAYOUTDIR) != (o.screenLayout & MASK_LAYOUTDIR)) {
1953 return (screenLayout & MASK_LAYOUTDIR) < (o.screenLayout & MASK_LAYOUTDIR) ? -1 : 1;
1955 if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
1956 return smallestScreenWidthDp < o.smallestScreenWidthDp ? -1 : 1;
1958 if (screenWidthDp != o.screenWidthDp) {
1959 return screenWidthDp < o.screenWidthDp ? -1 : 1;
1961 if (screenHeightDp != o.screenHeightDp) {
1962 return screenHeightDp < o.screenHeightDp ? -1 : 1;
1964 if (screenWidth != o.screenWidth) {
1965 return screenWidth < o.screenWidth ? -1 : 1;
1967 if (screenHeight != o.screenHeight) {
1968 return screenHeight < o.screenHeight ? -1 : 1;
1970 if (density != o.density) {
1971 return density < o.density ? -1 : 1;
1973 if (orientation != o.orientation) {
1974 return orientation < o.orientation ? -1 : 1;
1976 if (touchscreen != o.touchscreen) {
1977 return touchscreen < o.touchscreen ? -1 : 1;
1979 if (input != o.input) {
1980 return input < o.input ? -1 : 1;
1982 if (screenLayout != o.screenLayout) {
1983 return screenLayout < o.screenLayout ? -1 : 1;
1985 if (screenLayout2 != o.screenLayout2) {
1986 return screenLayout2 < o.screenLayout2 ? -1 : 1;
1988 if (uiMode != o.uiMode) {
1989 return uiMode < o.uiMode ? -1 : 1;
1991 if (version != o.version) {
1992 return version < o.version ? -1 : 1;
1997 int ResTable_config::diff(const ResTable_config& o) const {
1999 if (mcc != o.mcc) diffs |= CONFIG_MCC;
2000 if (mnc != o.mnc) diffs |= CONFIG_MNC;
2001 if (orientation != o.orientation) diffs |= CONFIG_ORIENTATION;
2002 if (density != o.density) diffs |= CONFIG_DENSITY;
2003 if (touchscreen != o.touchscreen) diffs |= CONFIG_TOUCHSCREEN;
2004 if (((inputFlags^o.inputFlags)&(MASK_KEYSHIDDEN|MASK_NAVHIDDEN)) != 0)
2005 diffs |= CONFIG_KEYBOARD_HIDDEN;
2006 if (keyboard != o.keyboard) diffs |= CONFIG_KEYBOARD;
2007 if (navigation != o.navigation) diffs |= CONFIG_NAVIGATION;
2008 if (screenSize != o.screenSize) diffs |= CONFIG_SCREEN_SIZE;
2009 if (version != o.version) diffs |= CONFIG_VERSION;
2010 if ((screenLayout & MASK_LAYOUTDIR) != (o.screenLayout & MASK_LAYOUTDIR)) diffs |= CONFIG_LAYOUTDIR;
2011 if ((screenLayout & ~MASK_LAYOUTDIR) != (o.screenLayout & ~MASK_LAYOUTDIR)) diffs |= CONFIG_SCREEN_LAYOUT;
2012 if ((screenLayout2 & MASK_SCREENROUND) != (o.screenLayout2 & MASK_SCREENROUND)) diffs |= CONFIG_SCREEN_ROUND;
2013 if (uiMode != o.uiMode) diffs |= CONFIG_UI_MODE;
2014 if (smallestScreenWidthDp != o.smallestScreenWidthDp) diffs |= CONFIG_SMALLEST_SCREEN_SIZE;
2015 if (screenSizeDp != o.screenSizeDp) diffs |= CONFIG_SCREEN_SIZE;
2017 const int diff = compareLocales(*this, o);
2018 if (diff) diffs |= CONFIG_LOCALE;
2023 int ResTable_config::isLocaleMoreSpecificThan(const ResTable_config& o) const {
2024 if (locale || o.locale) {
2025 if (language[0] != o.language[0]) {
2026 if (!language[0]) return -1;
2027 if (!o.language[0]) return 1;
2030 if (country[0] != o.country[0]) {
2031 if (!country[0]) return -1;
2032 if (!o.country[0]) return 1;
2036 // There isn't a well specified "importance" order between variants and
2037 // scripts. We can't easily tell whether, say "en-Latn-US" is more or less
2038 // specific than "en-US-POSIX".
2040 // We therefore arbitrarily decide to give priority to variants over
2041 // scripts since it seems more useful to do so. We will consider
2042 // "en-US-POSIX" to be more specific than "en-Latn-US".
2044 const int score = ((localeScript[0] != '\0' && !localeScriptWasComputed) ? 1 : 0) +
2045 ((localeVariant[0] != '\0') ? 2 : 0);
2047 const int oScore = (o.localeScript[0] != '\0' && !o.localeScriptWasComputed ? 1 : 0) +
2048 ((o.localeVariant[0] != '\0') ? 2 : 0);
2050 return score - oScore;
2054 bool ResTable_config::isMoreSpecificThan(const ResTable_config& o) const {
2055 // The order of the following tests defines the importance of one
2056 // configuration parameter over another. Those tests first are more
2057 // important, trumping any values in those following them.
2058 if (imsi || o.imsi) {
2060 if (!mcc) return false;
2061 if (!o.mcc) return true;
2065 if (!mnc) return false;
2066 if (!o.mnc) return true;
2070 if (locale || o.locale) {
2071 const int diff = isLocaleMoreSpecificThan(o);
2081 if (screenLayout || o.screenLayout) {
2082 if (((screenLayout^o.screenLayout) & MASK_LAYOUTDIR) != 0) {
2083 if (!(screenLayout & MASK_LAYOUTDIR)) return false;
2084 if (!(o.screenLayout & MASK_LAYOUTDIR)) return true;
2088 if (smallestScreenWidthDp || o.smallestScreenWidthDp) {
2089 if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
2090 if (!smallestScreenWidthDp) return false;
2091 if (!o.smallestScreenWidthDp) return true;
2095 if (screenSizeDp || o.screenSizeDp) {
2096 if (screenWidthDp != o.screenWidthDp) {
2097 if (!screenWidthDp) return false;
2098 if (!o.screenWidthDp) return true;
2101 if (screenHeightDp != o.screenHeightDp) {
2102 if (!screenHeightDp) return false;
2103 if (!o.screenHeightDp) return true;
2107 if (screenLayout || o.screenLayout) {
2108 if (((screenLayout^o.screenLayout) & MASK_SCREENSIZE) != 0) {
2109 if (!(screenLayout & MASK_SCREENSIZE)) return false;
2110 if (!(o.screenLayout & MASK_SCREENSIZE)) return true;
2112 if (((screenLayout^o.screenLayout) & MASK_SCREENLONG) != 0) {
2113 if (!(screenLayout & MASK_SCREENLONG)) return false;
2114 if (!(o.screenLayout & MASK_SCREENLONG)) return true;
2118 if (screenLayout2 || o.screenLayout2) {
2119 if (((screenLayout2^o.screenLayout2) & MASK_SCREENROUND) != 0) {
2120 if (!(screenLayout2 & MASK_SCREENROUND)) return false;
2121 if (!(o.screenLayout2 & MASK_SCREENROUND)) return true;
2125 if (orientation != o.orientation) {
2126 if (!orientation) return false;
2127 if (!o.orientation) return true;
2130 if (uiMode || o.uiMode) {
2131 if (((uiMode^o.uiMode) & MASK_UI_MODE_TYPE) != 0) {
2132 if (!(uiMode & MASK_UI_MODE_TYPE)) return false;
2133 if (!(o.uiMode & MASK_UI_MODE_TYPE)) return true;
2135 if (((uiMode^o.uiMode) & MASK_UI_MODE_NIGHT) != 0) {
2136 if (!(uiMode & MASK_UI_MODE_NIGHT)) return false;
2137 if (!(o.uiMode & MASK_UI_MODE_NIGHT)) return true;
2141 // density is never 'more specific'
2142 // as the default just equals 160
2144 if (touchscreen != o.touchscreen) {
2145 if (!touchscreen) return false;
2146 if (!o.touchscreen) return true;
2149 if (input || o.input) {
2150 if (((inputFlags^o.inputFlags) & MASK_KEYSHIDDEN) != 0) {
2151 if (!(inputFlags & MASK_KEYSHIDDEN)) return false;
2152 if (!(o.inputFlags & MASK_KEYSHIDDEN)) return true;
2155 if (((inputFlags^o.inputFlags) & MASK_NAVHIDDEN) != 0) {
2156 if (!(inputFlags & MASK_NAVHIDDEN)) return false;
2157 if (!(o.inputFlags & MASK_NAVHIDDEN)) return true;
2160 if (keyboard != o.keyboard) {
2161 if (!keyboard) return false;
2162 if (!o.keyboard) return true;
2165 if (navigation != o.navigation) {
2166 if (!navigation) return false;
2167 if (!o.navigation) return true;
2171 if (screenSize || o.screenSize) {
2172 if (screenWidth != o.screenWidth) {
2173 if (!screenWidth) return false;
2174 if (!o.screenWidth) return true;
2177 if (screenHeight != o.screenHeight) {
2178 if (!screenHeight) return false;
2179 if (!o.screenHeight) return true;
2183 if (version || o.version) {
2184 if (sdkVersion != o.sdkVersion) {
2185 if (!sdkVersion) return false;
2186 if (!o.sdkVersion) return true;
2189 if (minorVersion != o.minorVersion) {
2190 if (!minorVersion) return false;
2191 if (!o.minorVersion) return true;
2197 bool ResTable_config::isLocaleBetterThan(const ResTable_config& o,
2198 const ResTable_config* requested) const {
2199 if (requested->locale == 0) {
2200 // The request doesn't have a locale, so no resource is better
2205 if (locale == 0 && o.locale == 0) {
2206 // The locales parts of both resources are empty, so no one is better
2211 // Non-matching locales have been filtered out, so both resources
2212 // match the requested locale.
2214 // Because of the locale-related checks in match() and the checks, we know
2216 // 1) The resource languages are either empty or match the request;
2218 // 2) If the request's script is known, the resource scripts are either
2219 // unknown or match the request.
2221 if (language[0] != o.language[0]) {
2222 // The languages of the two resources are not the same. We can only
2223 // assume that one of the two resources matched the request because one
2224 // doesn't have a language and the other has a matching language.
2226 // We consider the one that has the language specified a better match.
2228 // The exception is that we consider no-language resources a better match
2229 // for US English and similar locales than locales that are a descendant
2230 // of Internatinal English (en-001), since no-language resources are
2231 // where the US English resource have traditionally lived for most apps.
2232 if (requested->language[0] == 'e' && requested->language[1] == 'n') {
2233 if (requested->country[0] == 'U' && requested->country[1] == 'S') {
2234 // For US English itself, we consider a no-locale resource a
2235 // better match if the other resource has a country other than
2237 if (language[0] != '\0') {
2238 return country[0] == '\0' || (country[0] == 'U' && country[1] == 'S');
2240 return !(o.country[0] == '\0' || (o.country[0] == 'U' && o.country[1] == 'S'));
2242 } else if (localeDataIsCloseToUsEnglish(requested->country)) {
2243 if (language[0] != '\0') {
2244 return localeDataIsCloseToUsEnglish(country);
2246 return !localeDataIsCloseToUsEnglish(o.country);
2250 return (language[0] != '\0');
2253 // If we are here, both the resources have the same non-empty language as
2256 // Because the languages are the same, computeScript() always
2257 // returns a non-empty script for languages it knows about, and we have passed
2258 // the script checks in match(), the scripts are either all unknown or are
2259 // all the same. So we can't gain anything by checking the scripts. We need
2260 // to check the region and variant.
2262 // See if any of the regions is better than the other
2263 const int region_comparison = localeDataCompareRegions(
2265 language, requested->localeScript, requested->country);
2266 if (region_comparison != 0) {
2267 return (region_comparison > 0);
2270 // The regions are the same. Try the variant.
2271 if (requested->localeVariant[0] != '\0'
2272 && strncmp(localeVariant, requested->localeVariant, sizeof(localeVariant)) == 0) {
2273 return (strncmp(o.localeVariant, requested->localeVariant, sizeof(localeVariant)) != 0);
2279 bool ResTable_config::isBetterThan(const ResTable_config& o,
2280 const ResTable_config* requested) const {
2282 if (imsi || o.imsi) {
2283 if ((mcc != o.mcc) && requested->mcc) {
2287 if ((mnc != o.mnc) && requested->mnc) {
2292 if (isLocaleBetterThan(o, requested)) {
2296 if (screenLayout || o.screenLayout) {
2297 if (((screenLayout^o.screenLayout) & MASK_LAYOUTDIR) != 0
2298 && (requested->screenLayout & MASK_LAYOUTDIR)) {
2299 int myLayoutDir = screenLayout & MASK_LAYOUTDIR;
2300 int oLayoutDir = o.screenLayout & MASK_LAYOUTDIR;
2301 return (myLayoutDir > oLayoutDir);
2305 if (smallestScreenWidthDp || o.smallestScreenWidthDp) {
2306 // The configuration closest to the actual size is best.
2307 // We assume that larger configs have already been filtered
2308 // out at this point. That means we just want the largest one.
2309 if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
2310 return smallestScreenWidthDp > o.smallestScreenWidthDp;
2314 if (screenSizeDp || o.screenSizeDp) {
2315 // "Better" is based on the sum of the difference between both
2316 // width and height from the requested dimensions. We are
2317 // assuming the invalid configs (with smaller dimens) have
2318 // already been filtered. Note that if a particular dimension
2319 // is unspecified, we will end up with a large value (the
2320 // difference between 0 and the requested dimension), which is
2321 // good since we will prefer a config that has specified a
2323 int myDelta = 0, otherDelta = 0;
2324 if (requested->screenWidthDp) {
2325 myDelta += requested->screenWidthDp - screenWidthDp;
2326 otherDelta += requested->screenWidthDp - o.screenWidthDp;
2328 if (requested->screenHeightDp) {
2329 myDelta += requested->screenHeightDp - screenHeightDp;
2330 otherDelta += requested->screenHeightDp - o.screenHeightDp;
2332 if (kDebugTableSuperNoisy) {
2333 ALOGI("Comparing this %dx%d to other %dx%d in %dx%d: myDelta=%d otherDelta=%d",
2334 screenWidthDp, screenHeightDp, o.screenWidthDp, o.screenHeightDp,
2335 requested->screenWidthDp, requested->screenHeightDp, myDelta, otherDelta);
2337 if (myDelta != otherDelta) {
2338 return myDelta < otherDelta;
2342 if (screenLayout || o.screenLayout) {
2343 if (((screenLayout^o.screenLayout) & MASK_SCREENSIZE) != 0
2344 && (requested->screenLayout & MASK_SCREENSIZE)) {
2345 // A little backwards compatibility here: undefined is
2346 // considered equivalent to normal. But only if the
2347 // requested size is at least normal; otherwise, small
2348 // is better than the default.
2349 int mySL = (screenLayout & MASK_SCREENSIZE);
2350 int oSL = (o.screenLayout & MASK_SCREENSIZE);
2351 int fixedMySL = mySL;
2353 if ((requested->screenLayout & MASK_SCREENSIZE) >= SCREENSIZE_NORMAL) {
2354 if (fixedMySL == 0) fixedMySL = SCREENSIZE_NORMAL;
2355 if (fixedOSL == 0) fixedOSL = SCREENSIZE_NORMAL;
2357 // For screen size, the best match is the one that is
2358 // closest to the requested screen size, but not over
2359 // (the not over part is dealt with in match() below).
2360 if (fixedMySL == fixedOSL) {
2361 // If the two are the same, but 'this' is actually
2362 // undefined, then the other is really a better match.
2363 if (mySL == 0) return false;
2366 if (fixedMySL != fixedOSL) {
2367 return fixedMySL > fixedOSL;
2370 if (((screenLayout^o.screenLayout) & MASK_SCREENLONG) != 0
2371 && (requested->screenLayout & MASK_SCREENLONG)) {
2372 return (screenLayout & MASK_SCREENLONG);
2376 if (screenLayout2 || o.screenLayout2) {
2377 if (((screenLayout2^o.screenLayout2) & MASK_SCREENROUND) != 0 &&
2378 (requested->screenLayout2 & MASK_SCREENROUND)) {
2379 return screenLayout2 & MASK_SCREENROUND;
2383 if ((orientation != o.orientation) && requested->orientation) {
2384 return (orientation);
2387 if (uiMode || o.uiMode) {
2388 if (((uiMode^o.uiMode) & MASK_UI_MODE_TYPE) != 0
2389 && (requested->uiMode & MASK_UI_MODE_TYPE)) {
2390 return (uiMode & MASK_UI_MODE_TYPE);
2392 if (((uiMode^o.uiMode) & MASK_UI_MODE_NIGHT) != 0
2393 && (requested->uiMode & MASK_UI_MODE_NIGHT)) {
2394 return (uiMode & MASK_UI_MODE_NIGHT);
2398 if (screenType || o.screenType) {
2399 if (density != o.density) {
2400 // Use the system default density (DENSITY_MEDIUM, 160dpi) if none specified.
2401 const int thisDensity = density ? density : int(ResTable_config::DENSITY_MEDIUM);
2402 const int otherDensity = o.density ? o.density : int(ResTable_config::DENSITY_MEDIUM);
2404 // We always prefer DENSITY_ANY over scaling a density bucket.
2405 if (thisDensity == ResTable_config::DENSITY_ANY) {
2407 } else if (otherDensity == ResTable_config::DENSITY_ANY) {
2411 int requestedDensity = requested->density;
2412 if (requested->density == 0 ||
2413 requested->density == ResTable_config::DENSITY_ANY) {
2414 requestedDensity = ResTable_config::DENSITY_MEDIUM;
2417 // DENSITY_ANY is now dealt with. We should look to
2418 // pick a density bucket and potentially scale it.
2419 // Any density is potentially useful
2420 // because the system will scale it. Scaling down
2421 // is generally better than scaling up.
2422 int h = thisDensity;
2423 int l = otherDensity;
2424 bool bImBigger = true;
2432 if (requestedDensity >= h) {
2433 // requested value higher than both l and h, give h
2436 if (l >= requestedDensity) {
2437 // requested value lower than both l and h, give l
2440 // saying that scaling down is 2x better than up
2441 if (((2 * l) - requestedDensity) * h > requestedDensity * requestedDensity) {
2448 if ((touchscreen != o.touchscreen) && requested->touchscreen) {
2449 return (touchscreen);
2453 if (input || o.input) {
2454 const int keysHidden = inputFlags & MASK_KEYSHIDDEN;
2455 const int oKeysHidden = o.inputFlags & MASK_KEYSHIDDEN;
2456 if (keysHidden != oKeysHidden) {
2457 const int reqKeysHidden =
2458 requested->inputFlags & MASK_KEYSHIDDEN;
2459 if (reqKeysHidden) {
2461 if (!keysHidden) return false;
2462 if (!oKeysHidden) return true;
2463 // For compatibility, we count KEYSHIDDEN_NO as being
2464 // the same as KEYSHIDDEN_SOFT. Here we disambiguate
2465 // these by making an exact match more specific.
2466 if (reqKeysHidden == keysHidden) return true;
2467 if (reqKeysHidden == oKeysHidden) return false;
2471 const int navHidden = inputFlags & MASK_NAVHIDDEN;
2472 const int oNavHidden = o.inputFlags & MASK_NAVHIDDEN;
2473 if (navHidden != oNavHidden) {
2474 const int reqNavHidden =
2475 requested->inputFlags & MASK_NAVHIDDEN;
2478 if (!navHidden) return false;
2479 if (!oNavHidden) return true;
2483 if ((keyboard != o.keyboard) && requested->keyboard) {
2487 if ((navigation != o.navigation) && requested->navigation) {
2488 return (navigation);
2492 if (screenSize || o.screenSize) {
2493 // "Better" is based on the sum of the difference between both
2494 // width and height from the requested dimensions. We are
2495 // assuming the invalid configs (with smaller sizes) have
2496 // already been filtered. Note that if a particular dimension
2497 // is unspecified, we will end up with a large value (the
2498 // difference between 0 and the requested dimension), which is
2499 // good since we will prefer a config that has specified a
2501 int myDelta = 0, otherDelta = 0;
2502 if (requested->screenWidth) {
2503 myDelta += requested->screenWidth - screenWidth;
2504 otherDelta += requested->screenWidth - o.screenWidth;
2506 if (requested->screenHeight) {
2507 myDelta += requested->screenHeight - screenHeight;
2508 otherDelta += requested->screenHeight - o.screenHeight;
2510 if (myDelta != otherDelta) {
2511 return myDelta < otherDelta;
2515 if (version || o.version) {
2516 if ((sdkVersion != o.sdkVersion) && requested->sdkVersion) {
2517 return (sdkVersion > o.sdkVersion);
2520 if ((minorVersion != o.minorVersion) &&
2521 requested->minorVersion) {
2522 return (minorVersion);
2528 return isMoreSpecificThan(o);
2531 bool ResTable_config::match(const ResTable_config& settings) const {
2533 if (mcc != 0 && mcc != settings.mcc) {
2536 if (mnc != 0 && mnc != settings.mnc) {
2541 // Don't consider country and variants when deciding matches.
2542 // (Theoretically, the variant can also affect the script. For
2543 // example, "ar-alalc97" probably implies the Latin script, but since
2544 // CLDR doesn't support getting likely scripts for that, we'll assume
2545 // the variant doesn't change the script.)
2547 // If two configs differ only in their country and variant,
2548 // they can be weeded out in the isMoreSpecificThan test.
2549 if (language[0] != settings.language[0] || language[1] != settings.language[1]) {
2553 // For backward compatibility and supporting private-use locales, we
2554 // fall back to old behavior if we couldn't determine the script for
2555 // either of the desired locale or the provided locale. But if we could determine
2556 // the scripts, they should be the same for the locales to match.
2557 bool countriesMustMatch = false;
2558 char computed_script[4];
2560 if (settings.localeScript[0] == '\0') { // could not determine the request's script
2561 countriesMustMatch = true;
2563 if (localeScript[0] == '\0' && !localeScriptWasComputed) {
2564 // script was not provided or computed, so we try to compute it
2565 localeDataComputeScript(computed_script, language, country);
2566 if (computed_script[0] == '\0') { // we could not compute the script
2567 countriesMustMatch = true;
2569 script = computed_script;
2571 } else { // script was provided, so just use it
2572 script = localeScript;
2576 if (countriesMustMatch) {
2577 if (country[0] != '\0'
2578 && (country[0] != settings.country[0]
2579 || country[1] != settings.country[1])) {
2583 if (memcmp(script, settings.localeScript, sizeof(settings.localeScript)) != 0) {
2589 if (screenConfig != 0) {
2590 const int layoutDir = screenLayout&MASK_LAYOUTDIR;
2591 const int setLayoutDir = settings.screenLayout&MASK_LAYOUTDIR;
2592 if (layoutDir != 0 && layoutDir != setLayoutDir) {
2596 const int screenSize = screenLayout&MASK_SCREENSIZE;
2597 const int setScreenSize = settings.screenLayout&MASK_SCREENSIZE;
2598 // Any screen sizes for larger screens than the setting do not
2600 if (screenSize != 0 && screenSize > setScreenSize) {
2604 const int screenLong = screenLayout&MASK_SCREENLONG;
2605 const int setScreenLong = settings.screenLayout&MASK_SCREENLONG;
2606 if (screenLong != 0 && screenLong != setScreenLong) {
2610 const int uiModeType = uiMode&MASK_UI_MODE_TYPE;
2611 const int setUiModeType = settings.uiMode&MASK_UI_MODE_TYPE;
2612 if (uiModeType != 0 && uiModeType != setUiModeType) {
2616 const int uiModeNight = uiMode&MASK_UI_MODE_NIGHT;
2617 const int setUiModeNight = settings.uiMode&MASK_UI_MODE_NIGHT;
2618 if (uiModeNight != 0 && uiModeNight != setUiModeNight) {
2622 if (smallestScreenWidthDp != 0
2623 && smallestScreenWidthDp > settings.smallestScreenWidthDp) {
2628 if (screenConfig2 != 0) {
2629 const int screenRound = screenLayout2 & MASK_SCREENROUND;
2630 const int setScreenRound = settings.screenLayout2 & MASK_SCREENROUND;
2631 if (screenRound != 0 && screenRound != setScreenRound) {
2636 if (screenSizeDp != 0) {
2637 if (screenWidthDp != 0 && screenWidthDp > settings.screenWidthDp) {
2638 if (kDebugTableSuperNoisy) {
2639 ALOGI("Filtering out width %d in requested %d", screenWidthDp,
2640 settings.screenWidthDp);
2644 if (screenHeightDp != 0 && screenHeightDp > settings.screenHeightDp) {
2645 if (kDebugTableSuperNoisy) {
2646 ALOGI("Filtering out height %d in requested %d", screenHeightDp,
2647 settings.screenHeightDp);
2652 if (screenType != 0) {
2653 if (orientation != 0 && orientation != settings.orientation) {
2656 // density always matches - we can scale it. See isBetterThan
2657 if (touchscreen != 0 && touchscreen != settings.touchscreen) {
2662 const int keysHidden = inputFlags&MASK_KEYSHIDDEN;
2663 const int setKeysHidden = settings.inputFlags&MASK_KEYSHIDDEN;
2664 if (keysHidden != 0 && keysHidden != setKeysHidden) {
2665 // For compatibility, we count a request for KEYSHIDDEN_NO as also
2666 // matching the more recent KEYSHIDDEN_SOFT. Basically
2667 // KEYSHIDDEN_NO means there is some kind of keyboard available.
2668 if (kDebugTableSuperNoisy) {
2669 ALOGI("Matching keysHidden: have=%d, config=%d\n", keysHidden, setKeysHidden);
2671 if (keysHidden != KEYSHIDDEN_NO || setKeysHidden != KEYSHIDDEN_SOFT) {
2672 if (kDebugTableSuperNoisy) {
2678 const int navHidden = inputFlags&MASK_NAVHIDDEN;
2679 const int setNavHidden = settings.inputFlags&MASK_NAVHIDDEN;
2680 if (navHidden != 0 && navHidden != setNavHidden) {
2683 if (keyboard != 0 && keyboard != settings.keyboard) {
2686 if (navigation != 0 && navigation != settings.navigation) {
2690 if (screenSize != 0) {
2691 if (screenWidth != 0 && screenWidth > settings.screenWidth) {
2694 if (screenHeight != 0 && screenHeight > settings.screenHeight) {
2699 if (sdkVersion != 0 && sdkVersion > settings.sdkVersion) {
2702 if (minorVersion != 0 && minorVersion != settings.minorVersion) {
2709 void ResTable_config::appendDirLocale(String8& out) const {
2713 const bool scriptWasProvided = localeScript[0] != '\0' && !localeScriptWasComputed;
2714 if (!scriptWasProvided && !localeVariant[0]) {
2716 if (out.size() > 0) {
2721 size_t len = unpackLanguage(buf);
2722 out.append(buf, len);
2726 len = unpackRegion(buf);
2727 out.append(buf, len);
2732 // We are writing the modified BCP 47 tag.
2733 // It starts with 'b+' and uses '+' as a separator.
2735 if (out.size() > 0) {
2741 size_t len = unpackLanguage(buf);
2742 out.append(buf, len);
2744 if (scriptWasProvided) {
2746 out.append(localeScript, sizeof(localeScript));
2751 len = unpackRegion(buf);
2752 out.append(buf, len);
2755 if (localeVariant[0]) {
2757 out.append(localeVariant, strnlen(localeVariant, sizeof(localeVariant)));
2761 void ResTable_config::getBcp47Locale(char str[RESTABLE_MAX_LOCALE_LEN]) const {
2762 memset(str, 0, RESTABLE_MAX_LOCALE_LEN);
2764 // This represents the "any" locale value, which has traditionally been
2765 // represented by the empty string.
2766 if (!language[0] && !country[0]) {
2770 size_t charsWritten = 0;
2772 charsWritten += unpackLanguage(str);
2775 if (localeScript[0] && !localeScriptWasComputed) {
2777 str[charsWritten++] = '-';
2779 memcpy(str + charsWritten, localeScript, sizeof(localeScript));
2780 charsWritten += sizeof(localeScript);
2785 str[charsWritten++] = '-';
2787 charsWritten += unpackRegion(str + charsWritten);
2790 if (localeVariant[0]) {
2792 str[charsWritten++] = '-';
2794 memcpy(str + charsWritten, localeVariant, sizeof(localeVariant));
2798 /* static */ inline bool assignLocaleComponent(ResTable_config* config,
2799 const char* start, size_t size) {
2806 config->language[0] ? config->packRegion(start) : config->packLanguage(start);
2809 if ('0' <= start[0] && start[0] <= '9') {
2810 // this is a variant, so fall through
2812 config->localeScript[0] = toupper(start[0]);
2813 for (size_t i = 1; i < 4; ++i) {
2814 config->localeScript[i] = tolower(start[i]);
2822 for (size_t i = 0; i < size; ++i) {
2823 config->localeVariant[i] = tolower(start[i]);
2833 void ResTable_config::setBcp47Locale(const char* in) {
2835 memset(localeScript, 0, sizeof(localeScript));
2836 memset(localeVariant, 0, sizeof(localeVariant));
2838 const char* separator = in;
2839 const char* start = in;
2840 while ((separator = strchr(start, '-')) != NULL) {
2841 const size_t size = separator - start;
2842 if (!assignLocaleComponent(this, start, size)) {
2843 fprintf(stderr, "Invalid BCP-47 locale string: %s", in);
2846 start = (separator + 1);
2849 const size_t size = in + strlen(in) - start;
2850 assignLocaleComponent(this, start, size);
2851 localeScriptWasComputed = (localeScript[0] == '\0');
2852 if (localeScriptWasComputed) {
2857 String8 ResTable_config::toString() const {
2861 if (res.size() > 0) res.append("-");
2862 res.appendFormat("mcc%d", dtohs(mcc));
2865 if (res.size() > 0) res.append("-");
2866 res.appendFormat("mnc%d", dtohs(mnc));
2869 appendDirLocale(res);
2871 if ((screenLayout&MASK_LAYOUTDIR) != 0) {
2872 if (res.size() > 0) res.append("-");
2873 switch (screenLayout&ResTable_config::MASK_LAYOUTDIR) {
2874 case ResTable_config::LAYOUTDIR_LTR:
2875 res.append("ldltr");
2877 case ResTable_config::LAYOUTDIR_RTL:
2878 res.append("ldrtl");
2881 res.appendFormat("layoutDir=%d",
2882 dtohs(screenLayout&ResTable_config::MASK_LAYOUTDIR));
2886 if (smallestScreenWidthDp != 0) {
2887 if (res.size() > 0) res.append("-");
2888 res.appendFormat("sw%ddp", dtohs(smallestScreenWidthDp));
2890 if (screenWidthDp != 0) {
2891 if (res.size() > 0) res.append("-");
2892 res.appendFormat("w%ddp", dtohs(screenWidthDp));
2894 if (screenHeightDp != 0) {
2895 if (res.size() > 0) res.append("-");
2896 res.appendFormat("h%ddp", dtohs(screenHeightDp));
2898 if ((screenLayout&MASK_SCREENSIZE) != SCREENSIZE_ANY) {
2899 if (res.size() > 0) res.append("-");
2900 switch (screenLayout&ResTable_config::MASK_SCREENSIZE) {
2901 case ResTable_config::SCREENSIZE_SMALL:
2902 res.append("small");
2904 case ResTable_config::SCREENSIZE_NORMAL:
2905 res.append("normal");
2907 case ResTable_config::SCREENSIZE_LARGE:
2908 res.append("large");
2910 case ResTable_config::SCREENSIZE_XLARGE:
2911 res.append("xlarge");
2914 res.appendFormat("screenLayoutSize=%d",
2915 dtohs(screenLayout&ResTable_config::MASK_SCREENSIZE));
2919 if ((screenLayout&MASK_SCREENLONG) != 0) {
2920 if (res.size() > 0) res.append("-");
2921 switch (screenLayout&ResTable_config::MASK_SCREENLONG) {
2922 case ResTable_config::SCREENLONG_NO:
2923 res.append("notlong");
2925 case ResTable_config::SCREENLONG_YES:
2929 res.appendFormat("screenLayoutLong=%d",
2930 dtohs(screenLayout&ResTable_config::MASK_SCREENLONG));
2934 if ((screenLayout2&MASK_SCREENROUND) != 0) {
2935 if (res.size() > 0) res.append("-");
2936 switch (screenLayout2&MASK_SCREENROUND) {
2937 case SCREENROUND_NO:
2938 res.append("notround");
2940 case SCREENROUND_YES:
2941 res.append("round");
2944 res.appendFormat("screenRound=%d", dtohs(screenLayout2&MASK_SCREENROUND));
2948 if (orientation != ORIENTATION_ANY) {
2949 if (res.size() > 0) res.append("-");
2950 switch (orientation) {
2951 case ResTable_config::ORIENTATION_PORT:
2954 case ResTable_config::ORIENTATION_LAND:
2957 case ResTable_config::ORIENTATION_SQUARE:
2958 res.append("square");
2961 res.appendFormat("orientation=%d", dtohs(orientation));
2965 if ((uiMode&MASK_UI_MODE_TYPE) != UI_MODE_TYPE_ANY) {
2966 if (res.size() > 0) res.append("-");
2967 switch (uiMode&ResTable_config::MASK_UI_MODE_TYPE) {
2968 case ResTable_config::UI_MODE_TYPE_DESK:
2971 case ResTable_config::UI_MODE_TYPE_CAR:
2974 case ResTable_config::UI_MODE_TYPE_TELEVISION:
2975 res.append("television");
2977 case ResTable_config::UI_MODE_TYPE_APPLIANCE:
2978 res.append("appliance");
2980 case ResTable_config::UI_MODE_TYPE_WATCH:
2981 res.append("watch");
2984 res.appendFormat("uiModeType=%d",
2985 dtohs(screenLayout&ResTable_config::MASK_UI_MODE_TYPE));
2989 if ((uiMode&MASK_UI_MODE_NIGHT) != 0) {
2990 if (res.size() > 0) res.append("-");
2991 switch (uiMode&ResTable_config::MASK_UI_MODE_NIGHT) {
2992 case ResTable_config::UI_MODE_NIGHT_NO:
2993 res.append("notnight");
2995 case ResTable_config::UI_MODE_NIGHT_YES:
2996 res.append("night");
2999 res.appendFormat("uiModeNight=%d",
3000 dtohs(uiMode&MASK_UI_MODE_NIGHT));
3004 if (density != DENSITY_DEFAULT) {
3005 if (res.size() > 0) res.append("-");
3007 case ResTable_config::DENSITY_LOW:
3010 case ResTable_config::DENSITY_MEDIUM:
3013 case ResTable_config::DENSITY_TV:
3014 res.append("tvdpi");
3016 case ResTable_config::DENSITY_HIGH:
3019 case ResTable_config::DENSITY_XHIGH:
3020 res.append("xhdpi");
3022 case ResTable_config::DENSITY_XXHIGH:
3023 res.append("xxhdpi");
3025 case ResTable_config::DENSITY_XXXHIGH:
3026 res.append("xxxhdpi");
3028 case ResTable_config::DENSITY_NONE:
3029 res.append("nodpi");
3031 case ResTable_config::DENSITY_ANY:
3032 res.append("anydpi");
3035 res.appendFormat("%ddpi", dtohs(density));
3039 if (touchscreen != TOUCHSCREEN_ANY) {
3040 if (res.size() > 0) res.append("-");
3041 switch (touchscreen) {
3042 case ResTable_config::TOUCHSCREEN_NOTOUCH:
3043 res.append("notouch");
3045 case ResTable_config::TOUCHSCREEN_FINGER:
3046 res.append("finger");
3048 case ResTable_config::TOUCHSCREEN_STYLUS:
3049 res.append("stylus");
3052 res.appendFormat("touchscreen=%d", dtohs(touchscreen));
3056 if ((inputFlags&MASK_KEYSHIDDEN) != 0) {
3057 if (res.size() > 0) res.append("-");
3058 switch (inputFlags&MASK_KEYSHIDDEN) {
3059 case ResTable_config::KEYSHIDDEN_NO:
3060 res.append("keysexposed");
3062 case ResTable_config::KEYSHIDDEN_YES:
3063 res.append("keyshidden");
3065 case ResTable_config::KEYSHIDDEN_SOFT:
3066 res.append("keyssoft");
3070 if (keyboard != KEYBOARD_ANY) {
3071 if (res.size() > 0) res.append("-");
3073 case ResTable_config::KEYBOARD_NOKEYS:
3074 res.append("nokeys");
3076 case ResTable_config::KEYBOARD_QWERTY:
3077 res.append("qwerty");
3079 case ResTable_config::KEYBOARD_12KEY:
3080 res.append("12key");
3083 res.appendFormat("keyboard=%d", dtohs(keyboard));
3087 if ((inputFlags&MASK_NAVHIDDEN) != 0) {
3088 if (res.size() > 0) res.append("-");
3089 switch (inputFlags&MASK_NAVHIDDEN) {
3090 case ResTable_config::NAVHIDDEN_NO:
3091 res.append("navexposed");
3093 case ResTable_config::NAVHIDDEN_YES:
3094 res.append("navhidden");
3097 res.appendFormat("inputFlagsNavHidden=%d",
3098 dtohs(inputFlags&MASK_NAVHIDDEN));
3102 if (navigation != NAVIGATION_ANY) {
3103 if (res.size() > 0) res.append("-");
3104 switch (navigation) {
3105 case ResTable_config::NAVIGATION_NONAV:
3106 res.append("nonav");
3108 case ResTable_config::NAVIGATION_DPAD:
3111 case ResTable_config::NAVIGATION_TRACKBALL:
3112 res.append("trackball");
3114 case ResTable_config::NAVIGATION_WHEEL:
3115 res.append("wheel");
3118 res.appendFormat("navigation=%d", dtohs(navigation));
3122 if (screenSize != 0) {
3123 if (res.size() > 0) res.append("-");
3124 res.appendFormat("%dx%d", dtohs(screenWidth), dtohs(screenHeight));
3127 if (res.size() > 0) res.append("-");
3128 res.appendFormat("v%d", dtohs(sdkVersion));
3129 if (minorVersion != 0) {
3130 res.appendFormat(".%d", dtohs(minorVersion));
3137 // --------------------------------------------------------------------
3138 // --------------------------------------------------------------------
3139 // --------------------------------------------------------------------
3141 struct ResTable::Header
3143 Header(ResTable* _owner) : owner(_owner), ownedData(NULL), header(NULL),
3144 resourceIDMap(NULL), resourceIDMapSize(0) { }
3148 free(resourceIDMap);
3151 const ResTable* const owner;
3153 const ResTable_header* header;
3155 const uint8_t* dataEnd;
3159 ResStringPool values;
3160 uint32_t* resourceIDMap;
3161 size_t resourceIDMapSize;
3164 struct ResTable::Entry {
3165 ResTable_config config;
3166 const ResTable_entry* entry;
3167 const ResTable_type* type;
3169 const Package* package;
3171 StringPoolRef typeStr;
3172 StringPoolRef keyStr;
3175 struct ResTable::Type
3177 Type(const Header* _header, const Package* _package, size_t count)
3178 : header(_header), package(_package), entryCount(count),
3179 typeSpec(NULL), typeSpecFlags(NULL) { }
3180 const Header* const header;
3181 const Package* const package;
3182 const size_t entryCount;
3183 const ResTable_typeSpec* typeSpec;
3184 const uint32_t* typeSpecFlags;
3185 IdmapEntries idmapEntries;
3186 Vector<const ResTable_type*> configs;
3189 struct ResTable::Package
3191 Package(ResTable* _owner, const Header* _header, const ResTable_package* _package)
3192 : owner(_owner), header(_header), package(_package), typeIdOffset(0) {
3193 if (dtohs(package->header.headerSize) == sizeof(package)) {
3194 // The package structure is the same size as the definition.
3195 // This means it contains the typeIdOffset field.
3196 typeIdOffset = package->typeIdOffset;
3200 const ResTable* const owner;
3201 const Header* const header;
3202 const ResTable_package* const package;
3204 ResStringPool typeStrings;
3205 ResStringPool keyStrings;
3207 size_t typeIdOffset;
3210 // A group of objects describing a particular resource package.
3211 // The first in 'package' is always the root object (from the resource
3212 // table that defined the package); the ones after are skins on top of it.
3213 struct ResTable::PackageGroup
3216 ResTable* _owner, const String16& _name, uint32_t _id,
3217 bool appAsLib, bool _isSystemAsset)
3222 , dynamicRefTable(static_cast<uint8_t>(_id), appAsLib)
3223 , isSystemAsset(_isSystemAsset)
3228 const size_t numTypes = types.size();
3229 for (size_t i = 0; i < numTypes; i++) {
3230 const TypeList& typeList = types[i];
3231 const size_t numInnerTypes = typeList.size();
3232 for (size_t j = 0; j < numInnerTypes; j++) {
3233 if (typeList[j]->package->owner == owner) {
3239 const size_t N = packages.size();
3240 for (size_t i=0; i<N; i++) {
3241 Package* pkg = packages[i];
3242 if (pkg->owner == owner) {
3249 * Clear all cache related data that depends on parameters/configuration.
3250 * This includes the bag caches and filtered types.
3252 void clearBagCache() {
3253 for (size_t i = 0; i < typeCacheEntries.size(); i++) {
3254 if (kDebugTableNoisy) {
3255 printf("type=%zu\n", i);
3257 const TypeList& typeList = types[i];
3258 if (!typeList.isEmpty()) {
3259 TypeCacheEntry& cacheEntry = typeCacheEntries.editItemAt(i);
3261 // Reset the filtered configurations.
3262 cacheEntry.filteredConfigs.clear();
3264 bag_set** typeBags = cacheEntry.cachedBags;
3265 if (kDebugTableNoisy) {
3266 printf("typeBags=%p\n", typeBags);
3270 const size_t N = typeList[0]->entryCount;
3271 if (kDebugTableNoisy) {
3272 printf("type->entryCount=%zu\n", N);
3274 for (size_t j = 0; j < N; j++) {
3275 if (typeBags[j] && typeBags[j] != (bag_set*)0xFFFFFFFF) {
3280 cacheEntry.cachedBags = NULL;
3286 ssize_t findType16(const char16_t* type, size_t len) const {
3287 const size_t N = packages.size();
3288 for (size_t i = 0; i < N; i++) {
3289 ssize_t index = packages[i]->typeStrings.indexOfString(type, len);
3291 return index + packages[i]->typeIdOffset;
3297 const ResTable* const owner;
3298 String16 const name;
3301 // This is mainly used to keep track of the loaded packages
3302 // and to clean them up properly. Accessing resources happens from
3303 // the 'types' array.
3304 Vector<Package*> packages;
3306 ByteBucketArray<TypeList> types;
3308 uint8_t largestTypeId;
3310 // Cached objects dependent on the parameters/configuration of this ResTable.
3311 // Gets cleared whenever the parameters/configuration changes.
3312 // These are stored here in a parallel structure because the data in `types` may
3313 // be shared by other ResTable's (framework resources are shared this way).
3314 ByteBucketArray<TypeCacheEntry> typeCacheEntries;
3316 // The table mapping dynamic references to resolved references for
3317 // this package group.
3318 // TODO: We may be able to support dynamic references in overlays
3319 // by having these tables in a per-package scope rather than
3320 // per-package-group.
3321 DynamicRefTable dynamicRefTable;
3323 // If the package group comes from a system asset. Used in
3324 // determining non-system locales.
3325 const bool isSystemAsset;
3328 ResTable::Theme::Theme(const ResTable& table)
3332 memset(mPackages, 0, sizeof(mPackages));
3335 ResTable::Theme::~Theme()
3337 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3338 package_info* pi = mPackages[i];
3345 void ResTable::Theme::free_package(package_info* pi)
3347 for (size_t j = 0; j <= Res_MAXTYPE; j++) {
3348 theme_entry* te = pi->types[j].entries;
3356 ResTable::Theme::package_info* ResTable::Theme::copy_package(package_info* pi)
3358 package_info* newpi = (package_info*)malloc(sizeof(package_info));
3359 for (size_t j = 0; j <= Res_MAXTYPE; j++) {
3360 size_t cnt = pi->types[j].numEntries;
3361 newpi->types[j].numEntries = cnt;
3362 theme_entry* te = pi->types[j].entries;
3363 size_t cnt_max = SIZE_MAX / sizeof(theme_entry);
3364 if (te != NULL && (cnt < 0xFFFFFFFF-1) && (cnt < cnt_max)) {
3365 theme_entry* newte = (theme_entry*)malloc(cnt*sizeof(theme_entry));
3366 newpi->types[j].entries = newte;
3367 memcpy(newte, te, cnt*sizeof(theme_entry));
3369 newpi->types[j].entries = NULL;
3375 status_t ResTable::Theme::applyStyle(uint32_t resID, bool force)
3377 const bag_entry* bag;
3378 uint32_t bagTypeSpecFlags = 0;
3380 const ssize_t N = mTable.getBagLocked(resID, &bag, &bagTypeSpecFlags);
3381 if (kDebugTableNoisy) {
3382 ALOGV("Applying style 0x%08x to theme %p, count=%zu", resID, this, N);
3389 mTypeSpecFlags |= bagTypeSpecFlags;
3391 uint32_t curPackage = 0xffffffff;
3392 ssize_t curPackageIndex = 0;
3393 package_info* curPI = NULL;
3394 uint32_t curType = 0xffffffff;
3395 size_t numEntries = 0;
3396 theme_entry* curEntries = NULL;
3398 const bag_entry* end = bag + N;
3400 const uint32_t attrRes = bag->map.name.ident;
3401 const uint32_t p = Res_GETPACKAGE(attrRes);
3402 const uint32_t t = Res_GETTYPE(attrRes);
3403 const uint32_t e = Res_GETENTRY(attrRes);
3405 if (curPackage != p) {
3406 const ssize_t pidx = mTable.getResourcePackageIndex(attrRes);
3408 ALOGE("Style contains key with bad package: 0x%08x\n", attrRes);
3413 curPackageIndex = pidx;
3414 curPI = mPackages[pidx];
3415 if (curPI == NULL) {
3416 curPI = (package_info*)malloc(sizeof(package_info));
3417 memset(curPI, 0, sizeof(*curPI));
3418 mPackages[pidx] = curPI;
3420 curType = 0xffffffff;
3423 if (t > Res_MAXTYPE) {
3424 ALOGE("Style contains key with bad type: 0x%08x\n", attrRes);
3429 curEntries = curPI->types[t].entries;
3430 if (curEntries == NULL) {
3431 PackageGroup* const grp = mTable.mPackageGroups[curPackageIndex];
3432 const TypeList& typeList = grp->types[t];
3433 size_t cnt = typeList.isEmpty() ? 0 : typeList[0]->entryCount;
3434 size_t cnt_max = SIZE_MAX / sizeof(theme_entry);
3435 size_t buff_size = (cnt < cnt_max && cnt < 0xFFFFFFFF-1) ?
3436 cnt*sizeof(theme_entry) : 0;
3437 curEntries = (theme_entry*)malloc(buff_size);
3438 memset(curEntries, Res_value::TYPE_NULL, buff_size);
3439 curPI->types[t].numEntries = cnt;
3440 curPI->types[t].entries = curEntries;
3442 numEntries = curPI->types[t].numEntries;
3444 if (e >= numEntries) {
3445 ALOGE("Style contains key with bad entry: 0x%08x\n", attrRes);
3449 theme_entry* curEntry = curEntries + e;
3450 if (kDebugTableNoisy) {
3451 ALOGV("Attr 0x%08x: type=0x%x, data=0x%08x; curType=0x%x",
3452 attrRes, bag->map.value.dataType, bag->map.value.data,
3453 curEntry->value.dataType);
3455 if (force || curEntry->value.dataType == Res_value::TYPE_NULL) {
3456 curEntry->stringBlock = bag->stringBlock;
3457 curEntry->typeSpecFlags |= bagTypeSpecFlags;
3458 curEntry->value = bag->map.value;
3466 if (kDebugTableTheme) {
3467 ALOGI("Applying style 0x%08x (force=%d) theme %p...\n", resID, force, this);
3474 status_t ResTable::Theme::setTo(const Theme& other)
3476 if (kDebugTableTheme) {
3477 ALOGI("Setting theme %p from theme %p...\n", this, &other);
3482 if (&mTable == &other.mTable) {
3483 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3484 if (mPackages[i] != NULL) {
3485 free_package(mPackages[i]);
3487 if (other.mPackages[i] != NULL) {
3488 mPackages[i] = copy_package(other.mPackages[i]);
3490 mPackages[i] = NULL;
3494 // @todo: need to really implement this, not just copy
3495 // the system package (which is still wrong because it isn't
3496 // fixing up resource references).
3497 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3498 if (mPackages[i] != NULL) {
3499 free_package(mPackages[i]);
3501 if (i == 0 && other.mPackages[i] != NULL) {
3502 mPackages[i] = copy_package(other.mPackages[i]);
3504 mPackages[i] = NULL;
3509 mTypeSpecFlags = other.mTypeSpecFlags;
3511 if (kDebugTableTheme) {
3512 ALOGI("Final theme:");
3519 status_t ResTable::Theme::clear()
3521 if (kDebugTableTheme) {
3522 ALOGI("Clearing theme %p...\n", this);
3526 for (size_t i = 0; i < Res_MAXPACKAGE; i++) {
3527 if (mPackages[i] != NULL) {
3528 free_package(mPackages[i]);
3529 mPackages[i] = NULL;
3535 if (kDebugTableTheme) {
3536 ALOGI("Final theme:");
3543 ssize_t ResTable::Theme::getAttribute(uint32_t resID, Res_value* outValue,
3544 uint32_t* outTypeSpecFlags) const
3548 if (outTypeSpecFlags != NULL) *outTypeSpecFlags = 0;
3551 const ssize_t p = mTable.getResourcePackageIndex(resID);
3552 const uint32_t t = Res_GETTYPE(resID);
3553 const uint32_t e = Res_GETENTRY(resID);
3555 if (kDebugTableTheme) {
3556 ALOGI("Looking up attr 0x%08x in theme %p", resID, this);
3560 const package_info* const pi = mPackages[p];
3561 if (kDebugTableTheme) {
3562 ALOGI("Found package: %p", pi);
3565 if (kDebugTableTheme) {
3566 ALOGI("Desired type index is %zd in avail %zu", t, Res_MAXTYPE + 1);
3568 if (t <= Res_MAXTYPE) {
3569 const type_info& ti = pi->types[t];
3570 if (kDebugTableTheme) {
3571 ALOGI("Desired entry index is %u in avail %zu", e, ti.numEntries);
3573 if (e < ti.numEntries) {
3574 const theme_entry& te = ti.entries[e];
3575 if (outTypeSpecFlags != NULL) {
3576 *outTypeSpecFlags |= te.typeSpecFlags;
3578 if (kDebugTableTheme) {
3579 ALOGI("Theme value: type=0x%x, data=0x%08x",
3580 te.value.dataType, te.value.data);
3582 const uint8_t type = te.value.dataType;
3583 if (type == Res_value::TYPE_ATTRIBUTE) {
3586 resID = te.value.data;
3589 ALOGW("Too many attribute references, stopped at: 0x%08x\n", resID);
3591 } else if (type != Res_value::TYPE_NULL) {
3592 *outValue = te.value;
3593 return te.stringBlock;
3607 ssize_t ResTable::Theme::resolveAttributeReference(Res_value* inOutValue,
3608 ssize_t blockIndex, uint32_t* outLastRef,
3609 uint32_t* inoutTypeSpecFlags, ResTable_config* inoutConfig) const
3611 //printf("Resolving type=0x%x\n", inOutValue->dataType);
3612 if (inOutValue->dataType == Res_value::TYPE_ATTRIBUTE) {
3613 uint32_t newTypeSpecFlags;
3614 blockIndex = getAttribute(inOutValue->data, inOutValue, &newTypeSpecFlags);
3615 if (kDebugTableTheme) {
3616 ALOGI("Resolving attr reference: blockIndex=%d, type=0x%x, data=0x%x\n",
3617 (int)blockIndex, (int)inOutValue->dataType, inOutValue->data);
3619 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newTypeSpecFlags;
3620 //printf("Retrieved attribute new type=0x%x\n", inOutValue->dataType);
3621 if (blockIndex < 0) {
3625 return mTable.resolveReference(inOutValue, blockIndex, outLastRef,
3626 inoutTypeSpecFlags, inoutConfig);
3629 uint32_t ResTable::Theme::getChangingConfigurations() const
3631 return mTypeSpecFlags;
3634 void ResTable::Theme::dumpToLog() const
3636 ALOGI("Theme %p:\n", this);
3637 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3638 package_info* pi = mPackages[i];
3639 if (pi == NULL) continue;
3641 ALOGI(" Package #0x%02x:\n", (int)(i + 1));
3642 for (size_t j = 0; j <= Res_MAXTYPE; j++) {
3643 type_info& ti = pi->types[j];
3644 if (ti.numEntries == 0) continue;
3645 ALOGI(" Type #0x%02x:\n", (int)(j + 1));
3646 for (size_t k = 0; k < ti.numEntries; k++) {
3647 const theme_entry& te = ti.entries[k];
3648 if (te.value.dataType == Res_value::TYPE_NULL) continue;
3649 ALOGI(" 0x%08x: t=0x%x, d=0x%08x (block=%d)\n",
3650 (int)Res_MAKEID(i, j, k),
3651 te.value.dataType, (int)te.value.data, (int)te.stringBlock);
3657 ResTable::ResTable()
3658 : mError(NO_INIT), mNextPackageId(2)
3660 memset(&mParams, 0, sizeof(mParams));
3661 memset(mPackageMap, 0, sizeof(mPackageMap));
3662 if (kDebugTableSuperNoisy) {
3663 ALOGI("Creating ResTable %p\n", this);
3667 ResTable::ResTable(const void* data, size_t size, const int32_t cookie, bool copyData)
3668 : mError(NO_INIT), mNextPackageId(2)
3670 memset(&mParams, 0, sizeof(mParams));
3671 memset(mPackageMap, 0, sizeof(mPackageMap));
3672 addInternal(data, size, NULL, 0, false, cookie, copyData);
3673 LOG_FATAL_IF(mError != NO_ERROR, "Error parsing resource table");
3674 if (kDebugTableSuperNoisy) {
3675 ALOGI("Creating ResTable %p\n", this);
3679 ResTable::~ResTable()
3681 if (kDebugTableSuperNoisy) {
3682 ALOGI("Destroying ResTable in %p\n", this);
3687 inline ssize_t ResTable::getResourcePackageIndex(uint32_t resID) const
3689 return ((ssize_t)mPackageMap[Res_GETPACKAGE(resID)+1])-1;
3692 status_t ResTable::add(const void* data, size_t size, const int32_t cookie, bool copyData) {
3693 return addInternal(data, size, NULL, 0, false, cookie, copyData);
3696 status_t ResTable::add(const void* data, size_t size, const void* idmapData, size_t idmapDataSize,
3697 const int32_t cookie, bool copyData, bool appAsLib) {
3698 return addInternal(data, size, idmapData, idmapDataSize, appAsLib, cookie, copyData);
3701 status_t ResTable::add(Asset* asset, const int32_t cookie, bool copyData) {
3702 const void* data = asset->getBuffer(true);
3704 ALOGW("Unable to get buffer of resource asset file");
3705 return UNKNOWN_ERROR;
3708 return addInternal(data, static_cast<size_t>(asset->getLength()), NULL, false, 0, cookie,
3712 status_t ResTable::add(
3713 Asset* asset, Asset* idmapAsset, const int32_t cookie, bool copyData,
3714 bool appAsLib, bool isSystemAsset) {
3715 const void* data = asset->getBuffer(true);
3717 ALOGW("Unable to get buffer of resource asset file");
3718 return UNKNOWN_ERROR;
3721 size_t idmapSize = 0;
3722 const void* idmapData = NULL;
3723 if (idmapAsset != NULL) {
3724 idmapData = idmapAsset->getBuffer(true);
3725 if (idmapData == NULL) {
3726 ALOGW("Unable to get buffer of idmap asset file");
3727 return UNKNOWN_ERROR;
3729 idmapSize = static_cast<size_t>(idmapAsset->getLength());
3732 return addInternal(data, static_cast<size_t>(asset->getLength()),
3733 idmapData, idmapSize, appAsLib, cookie, copyData, isSystemAsset);
3736 status_t ResTable::add(ResTable* src, bool isSystemAsset)
3738 mError = src->mError;
3740 for (size_t i=0; i < src->mHeaders.size(); i++) {
3741 mHeaders.add(src->mHeaders[i]);
3744 for (size_t i=0; i < src->mPackageGroups.size(); i++) {
3745 PackageGroup* srcPg = src->mPackageGroups[i];
3746 PackageGroup* pg = new PackageGroup(this, srcPg->name, srcPg->id,
3747 false /* appAsLib */, isSystemAsset || srcPg->isSystemAsset);
3748 for (size_t j=0; j<srcPg->packages.size(); j++) {
3749 pg->packages.add(srcPg->packages[j]);
3752 for (size_t j = 0; j < srcPg->types.size(); j++) {
3753 if (srcPg->types[j].isEmpty()) {
3757 TypeList& typeList = pg->types.editItemAt(j);
3758 typeList.appendVector(srcPg->types[j]);
3760 pg->dynamicRefTable.addMappings(srcPg->dynamicRefTable);
3761 pg->largestTypeId = max(pg->largestTypeId, srcPg->largestTypeId);
3762 mPackageGroups.add(pg);
3765 memcpy(mPackageMap, src->mPackageMap, sizeof(mPackageMap));
3770 status_t ResTable::addEmpty(const int32_t cookie) {
3771 Header* header = new Header(this);
3772 header->index = mHeaders.size();
3773 header->cookie = cookie;
3774 header->values.setToEmpty();
3775 header->ownedData = calloc(1, sizeof(ResTable_header));
3777 ResTable_header* resHeader = (ResTable_header*) header->ownedData;
3778 resHeader->header.type = RES_TABLE_TYPE;
3779 resHeader->header.headerSize = sizeof(ResTable_header);
3780 resHeader->header.size = sizeof(ResTable_header);
3782 header->header = (const ResTable_header*) resHeader;
3783 mHeaders.add(header);
3784 return (mError=NO_ERROR);
3787 status_t ResTable::addInternal(const void* data, size_t dataSize, const void* idmapData, size_t idmapDataSize,
3788 bool appAsLib, const int32_t cookie, bool copyData, bool isSystemAsset)
3794 if (dataSize < sizeof(ResTable_header)) {
3795 ALOGE("Invalid data. Size(%d) is smaller than a ResTable_header(%d).",
3796 (int) dataSize, (int) sizeof(ResTable_header));
3797 return UNKNOWN_ERROR;
3800 Header* header = new Header(this);
3801 header->index = mHeaders.size();
3802 header->cookie = cookie;
3803 if (idmapData != NULL) {
3804 header->resourceIDMap = (uint32_t*) malloc(idmapDataSize);
3805 if (header->resourceIDMap == NULL) {
3807 return (mError = NO_MEMORY);
3809 memcpy(header->resourceIDMap, idmapData, idmapDataSize);
3810 header->resourceIDMapSize = idmapDataSize;
3812 mHeaders.add(header);
3814 const bool notDeviceEndian = htods(0xf0) != 0xf0;
3816 if (kDebugLoadTableNoisy) {
3817 ALOGV("Adding resources to ResTable: data=%p, size=%zu, cookie=%d, copy=%d "
3818 "idmap=%p\n", data, dataSize, cookie, copyData, idmapData);
3821 if (copyData || notDeviceEndian) {
3822 header->ownedData = malloc(dataSize);
3823 if (header->ownedData == NULL) {
3824 return (mError=NO_MEMORY);
3826 memcpy(header->ownedData, data, dataSize);
3827 data = header->ownedData;
3830 header->header = (const ResTable_header*)data;
3831 header->size = dtohl(header->header->header.size);
3832 if (kDebugLoadTableSuperNoisy) {
3833 ALOGI("Got size %zu, again size 0x%x, raw size 0x%x\n", header->size,
3834 dtohl(header->header->header.size), header->header->header.size);
3836 if (kDebugLoadTableNoisy) {
3837 ALOGV("Loading ResTable @%p:\n", header->header);
3839 if (dtohs(header->header->header.headerSize) > header->size
3840 || header->size > dataSize) {
3841 ALOGW("Bad resource table: header size 0x%x or total size 0x%x is larger than data size 0x%x\n",
3842 (int)dtohs(header->header->header.headerSize),
3843 (int)header->size, (int)dataSize);
3844 return (mError=BAD_TYPE);
3846 if (((dtohs(header->header->header.headerSize)|header->size)&0x3) != 0) {
3847 ALOGW("Bad resource table: header size 0x%x or total size 0x%x is not on an integer boundary\n",
3848 (int)dtohs(header->header->header.headerSize),
3850 return (mError=BAD_TYPE);
3852 header->dataEnd = ((const uint8_t*)header->header) + header->size;
3854 // Iterate through all chunks.
3855 size_t curPackage = 0;
3857 const ResChunk_header* chunk =
3858 (const ResChunk_header*)(((const uint8_t*)header->header)
3859 + dtohs(header->header->header.headerSize));
3860 while (((const uint8_t*)chunk) <= (header->dataEnd-sizeof(ResChunk_header)) &&
3861 ((const uint8_t*)chunk) <= (header->dataEnd-dtohl(chunk->size))) {
3862 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), header->dataEnd, "ResTable");
3863 if (err != NO_ERROR) {
3864 return (mError=err);
3866 if (kDebugTableNoisy) {
3867 ALOGV("Chunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n",
3868 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
3869 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)));
3871 const size_t csize = dtohl(chunk->size);
3872 const uint16_t ctype = dtohs(chunk->type);
3873 if (ctype == RES_STRING_POOL_TYPE) {
3874 if (header->values.getError() != NO_ERROR) {
3875 // Only use the first string chunk; ignore any others that
3877 status_t err = header->values.setTo(chunk, csize);
3878 if (err != NO_ERROR) {
3879 return (mError=err);
3882 ALOGW("Multiple string chunks found in resource table.");
3884 } else if (ctype == RES_TABLE_PACKAGE_TYPE) {
3885 if (curPackage >= dtohl(header->header->packageCount)) {
3886 ALOGW("More package chunks were found than the %d declared in the header.",
3887 dtohl(header->header->packageCount));
3888 return (mError=BAD_TYPE);
3892 (ResTable_package*)chunk, header, appAsLib, isSystemAsset) != NO_ERROR) {
3897 ALOGW("Unknown chunk type 0x%x in table at %p.\n",
3899 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)));
3901 chunk = (const ResChunk_header*)
3902 (((const uint8_t*)chunk) + csize);
3905 if (curPackage < dtohl(header->header->packageCount)) {
3906 ALOGW("Fewer package chunks (%d) were found than the %d declared in the header.",
3907 (int)curPackage, dtohl(header->header->packageCount));
3908 return (mError=BAD_TYPE);
3910 mError = header->values.getError();
3911 if (mError != NO_ERROR) {
3912 ALOGW("No string values found in resource table!");
3915 if (kDebugTableNoisy) {
3916 ALOGV("Returning from add with mError=%d\n", mError);
3921 status_t ResTable::getError() const
3926 void ResTable::uninit()
3929 size_t N = mPackageGroups.size();
3930 for (size_t i=0; i<N; i++) {
3931 PackageGroup* g = mPackageGroups[i];
3934 N = mHeaders.size();
3935 for (size_t i=0; i<N; i++) {
3936 Header* header = mHeaders[i];
3937 if (header->owner == this) {
3938 if (header->ownedData) {
3939 free(header->ownedData);
3945 mPackageGroups.clear();
3949 bool ResTable::getResourceName(uint32_t resID, bool allowUtf8, resource_name* outName) const
3951 if (mError != NO_ERROR) {
3955 const ssize_t p = getResourcePackageIndex(resID);
3956 const int t = Res_GETTYPE(resID);
3957 const int e = Res_GETENTRY(resID);
3960 if (Res_GETPACKAGE(resID)+1 == 0) {
3961 ALOGW("No package identifier when getting name for resource number 0x%08x", resID);
3963 #ifndef STATIC_ANDROIDFW_FOR_TOOLS
3964 ALOGW("No known package when getting name for resource number 0x%08x", resID);
3970 ALOGW("No type identifier when getting name for resource number 0x%08x", resID);
3974 const PackageGroup* const grp = mPackageGroups[p];
3976 ALOGW("Bad identifier when getting name for resource number 0x%08x", resID);
3981 status_t err = getEntry(grp, t, e, NULL, &entry);
3982 if (err != NO_ERROR) {
3986 outName->package = grp->name.string();
3987 outName->packageLen = grp->name.size();
3989 outName->type8 = entry.typeStr.string8(&outName->typeLen);
3990 outName->name8 = entry.keyStr.string8(&outName->nameLen);
3992 outName->type8 = NULL;
3993 outName->name8 = NULL;
3995 if (outName->type8 == NULL) {
3996 outName->type = entry.typeStr.string16(&outName->typeLen);
3997 // If we have a bad index for some reason, we should abort.
3998 if (outName->type == NULL) {
4002 if (outName->name8 == NULL) {
4003 outName->name = entry.keyStr.string16(&outName->nameLen);
4004 // If we have a bad index for some reason, we should abort.
4005 if (outName->name == NULL) {
4013 ssize_t ResTable::getResource(uint32_t resID, Res_value* outValue, bool mayBeBag, uint16_t density,
4014 uint32_t* outSpecFlags, ResTable_config* outConfig) const
4016 if (mError != NO_ERROR) {
4020 const ssize_t p = getResourcePackageIndex(resID);
4021 const int t = Res_GETTYPE(resID);
4022 const int e = Res_GETENTRY(resID);
4025 if (Res_GETPACKAGE(resID)+1 == 0) {
4026 ALOGW("No package identifier when getting value for resource number 0x%08x", resID);
4028 ALOGW("No known package when getting value for resource number 0x%08x", resID);
4033 ALOGW("No type identifier when getting value for resource number 0x%08x", resID);
4037 const PackageGroup* const grp = mPackageGroups[p];
4039 ALOGW("Bad identifier when getting value for resource number 0x%08x", resID);
4043 // Allow overriding density
4044 ResTable_config desiredConfig = mParams;
4046 desiredConfig.density = density;
4050 status_t err = getEntry(grp, t, e, &desiredConfig, &entry);
4051 if (err != NO_ERROR) {
4052 // Only log the failure when we're not running on the host as
4053 // part of a tool. The caller will do its own logging.
4054 #ifndef STATIC_ANDROIDFW_FOR_TOOLS
4055 ALOGW("Failure getting entry for 0x%08x (t=%d e=%d) (error %d)\n",
4061 if ((dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) != 0) {
4063 ALOGW("Requesting resource 0x%08x failed because it is complex\n", resID);
4068 const Res_value* value = reinterpret_cast<const Res_value*>(
4069 reinterpret_cast<const uint8_t*>(entry.entry) + entry.entry->size);
4071 outValue->size = dtohs(value->size);
4072 outValue->res0 = value->res0;
4073 outValue->dataType = value->dataType;
4074 outValue->data = dtohl(value->data);
4076 // The reference may be pointing to a resource in a shared library. These
4077 // references have build-time generated package IDs. These ids may not match
4078 // the actual package IDs of the corresponding packages in this ResTable.
4079 // We need to fix the package ID based on a mapping.
4080 if (grp->dynamicRefTable.lookupResourceValue(outValue) != NO_ERROR) {
4081 ALOGW("Failed to resolve referenced package: 0x%08x", outValue->data);
4085 if (kDebugTableNoisy) {
4087 printf("Found value: pkg=%zu, type=%d, str=%s, int=%d\n",
4088 entry.package->header->index,
4090 outValue->dataType == Res_value::TYPE_STRING ?
4091 String8(entry.package->header->values.stringAt(outValue->data, &len)).string() :
4096 if (outSpecFlags != NULL) {
4097 *outSpecFlags = entry.specFlags;
4100 if (outConfig != NULL) {
4101 *outConfig = entry.config;
4104 return entry.package->header->index;
4107 ssize_t ResTable::resolveReference(Res_value* value, ssize_t blockIndex,
4108 uint32_t* outLastRef, uint32_t* inoutTypeSpecFlags,
4109 ResTable_config* outConfig) const
4112 while (blockIndex >= 0 && value->dataType == Res_value::TYPE_REFERENCE
4113 && value->data != 0 && count < 20) {
4114 if (outLastRef) *outLastRef = value->data;
4115 uint32_t newFlags = 0;
4116 const ssize_t newIndex = getResource(value->data, value, true, 0, &newFlags,
4118 if (newIndex == BAD_INDEX) {
4121 if (kDebugTableTheme) {
4122 ALOGI("Resolving reference 0x%x: newIndex=%d, type=0x%x, data=0x%x\n",
4123 value->data, (int)newIndex, (int)value->dataType, value->data);
4125 //printf("Getting reference 0x%08x: newIndex=%d\n", value->data, newIndex);
4126 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newFlags;
4128 // This can fail if the resource being referenced is a style...
4129 // in this case, just return the reference, and expect the
4130 // caller to deal with.
4133 blockIndex = newIndex;
4139 const char16_t* ResTable::valueToString(
4140 const Res_value* value, size_t stringBlock,
4141 char16_t /*tmpBuffer*/ [TMP_BUFFER_SIZE], size_t* outLen) const
4146 if (value->dataType == value->TYPE_STRING) {
4147 return getTableStringBlock(stringBlock)->stringAt(value->data, outLen);
4149 // XXX do int to string conversions.
4153 ssize_t ResTable::lockBag(uint32_t resID, const bag_entry** outBag) const
4156 ssize_t err = getBagLocked(resID, outBag);
4157 if (err < NO_ERROR) {
4158 //printf("*** get failed! unlocking\n");
4164 void ResTable::unlockBag(const bag_entry* /*bag*/) const
4166 //printf("<<< unlockBag %p\n", this);
4170 void ResTable::lock() const
4175 void ResTable::unlock() const
4180 ssize_t ResTable::getBagLocked(uint32_t resID, const bag_entry** outBag,
4181 uint32_t* outTypeSpecFlags) const
4183 if (mError != NO_ERROR) {
4187 const ssize_t p = getResourcePackageIndex(resID);
4188 const int t = Res_GETTYPE(resID);
4189 const int e = Res_GETENTRY(resID);
4192 ALOGW("Invalid package identifier when getting bag for resource number 0x%08x", resID);
4196 ALOGW("No type identifier when getting bag for resource number 0x%08x", resID);
4200 //printf("Get bag: id=0x%08x, p=%d, t=%d\n", resID, p, t);
4201 PackageGroup* const grp = mPackageGroups[p];
4203 ALOGW("Bad identifier when getting bag for resource number 0x%08x", resID);
4207 const TypeList& typeConfigs = grp->types[t];
4208 if (typeConfigs.isEmpty()) {
4209 ALOGW("Type identifier 0x%x does not exist.", t+1);
4213 const size_t NENTRY = typeConfigs[0]->entryCount;
4214 if (e >= (int)NENTRY) {
4215 ALOGW("Entry identifier 0x%x is larger than entry count 0x%x",
4216 e, (int)typeConfigs[0]->entryCount);
4220 // First see if we've already computed this bag...
4221 TypeCacheEntry& cacheEntry = grp->typeCacheEntries.editItemAt(t);
4222 bag_set** typeSet = cacheEntry.cachedBags;
4224 bag_set* set = typeSet[e];
4226 if (set != (bag_set*)0xFFFFFFFF) {
4227 if (outTypeSpecFlags != NULL) {
4228 *outTypeSpecFlags = set->typeSpecFlags;
4230 *outBag = (bag_entry*)(set+1);
4231 if (kDebugTableSuperNoisy) {
4232 ALOGI("Found existing bag for: 0x%x\n", resID);
4234 return set->numAttrs;
4236 ALOGW("Attempt to retrieve bag 0x%08x which is invalid or in a cycle.",
4242 // Bag not found, we need to compute it!
4244 typeSet = (bag_set**)calloc(NENTRY, sizeof(bag_set*));
4245 if (!typeSet) return NO_MEMORY;
4246 cacheEntry.cachedBags = typeSet;
4249 // Mark that we are currently working on this one.
4250 typeSet[e] = (bag_set*)0xFFFFFFFF;
4252 if (kDebugTableNoisy) {
4253 ALOGI("Building bag: %x\n", resID);
4256 // Now collect all bag attributes
4258 status_t err = getEntry(grp, t, e, &mParams, &entry);
4259 if (err != NO_ERROR) {
4263 const uint16_t entrySize = dtohs(entry.entry->size);
4264 const uint32_t parent = entrySize >= sizeof(ResTable_map_entry)
4265 ? dtohl(((const ResTable_map_entry*)entry.entry)->parent.ident) : 0;
4266 const uint32_t count = entrySize >= sizeof(ResTable_map_entry)
4267 ? dtohl(((const ResTable_map_entry*)entry.entry)->count) : 0;
4271 if (kDebugTableNoisy) {
4272 ALOGI("Found map: size=%x parent=%x count=%d\n", entrySize, parent, count);
4274 // If this map inherits from another, we need to start
4275 // with its parent's values. Otherwise start out empty.
4276 ALOGI("Creating new bag, entrySize=0x%08x, parent=0x%08x\n", entrySize, parent);
4279 // This is what we are building.
4280 bag_set* set = NULL;
4283 uint32_t resolvedParent = parent;
4285 // Bags encode a parent reference without using the standard
4286 // Res_value structure. That means we must always try to
4287 // resolve a parent reference in case it is actually a
4288 // TYPE_DYNAMIC_REFERENCE.
4289 status_t err = grp->dynamicRefTable.lookupResourceId(&resolvedParent);
4290 if (err != NO_ERROR) {
4291 ALOGE("Failed resolving bag parent id 0x%08x", parent);
4292 return UNKNOWN_ERROR;
4295 const bag_entry* parentBag;
4296 uint32_t parentTypeSpecFlags = 0;
4297 const ssize_t NP = getBagLocked(resolvedParent, &parentBag, &parentTypeSpecFlags);
4298 const size_t NT = ((NP >= 0) ? NP : 0) + N;
4299 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*NT);
4304 memcpy(set+1, parentBag, NP*sizeof(bag_entry));
4306 if (kDebugTableNoisy) {
4307 ALOGI("Initialized new bag with %zd inherited attributes.\n", NP);
4310 if (kDebugTableNoisy) {
4311 ALOGI("Initialized new bag with no inherited attributes.\n");
4315 set->availAttrs = NT;
4316 set->typeSpecFlags = parentTypeSpecFlags;
4318 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*N);
4323 set->availAttrs = N;
4324 set->typeSpecFlags = 0;
4327 set->typeSpecFlags |= entry.specFlags;
4329 // Now merge in the new attributes...
4330 size_t curOff = (reinterpret_cast<uintptr_t>(entry.entry) - reinterpret_cast<uintptr_t>(entry.type))
4331 + dtohs(entry.entry->size);
4332 const ResTable_map* map;
4333 bag_entry* entries = (bag_entry*)(set+1);
4334 size_t curEntry = 0;
4336 if (kDebugTableNoisy) {
4337 ALOGI("Starting with set %p, entries=%p, avail=%zu\n", set, entries, set->availAttrs);
4339 while (pos < count) {
4340 if (kDebugTableNoisy) {
4341 ALOGI("Now at %p\n", (void*)curOff);
4344 if (curOff > (dtohl(entry.type->header.size)-sizeof(ResTable_map))) {
4345 ALOGW("ResTable_map at %d is beyond type chunk data %d",
4346 (int)curOff, dtohl(entry.type->header.size));
4349 map = (const ResTable_map*)(((const uint8_t*)entry.type) + curOff);
4352 uint32_t newName = htodl(map->name.ident);
4353 if (!Res_INTERNALID(newName)) {
4354 // Attributes don't have a resource id as the name. They specify
4355 // other data, which would be wrong to change via a lookup.
4356 if (grp->dynamicRefTable.lookupResourceId(&newName) != NO_ERROR) {
4357 ALOGE("Failed resolving ResTable_map name at %d with ident 0x%08x",
4358 (int) curOff, (int) newName);
4359 return UNKNOWN_ERROR;
4364 uint32_t oldName = 0;
4365 while ((isInside=(curEntry < set->numAttrs))
4366 && (oldName=entries[curEntry].map.name.ident) < newName) {
4367 if (kDebugTableNoisy) {
4368 ALOGI("#%zu: Keeping existing attribute: 0x%08x\n",
4369 curEntry, entries[curEntry].map.name.ident);
4374 if ((!isInside) || oldName != newName) {
4375 // This is a new attribute... figure out what to do with it.
4376 if (set->numAttrs >= set->availAttrs) {
4377 // Need to alloc more memory...
4378 const size_t newAvail = set->availAttrs+N;
4379 set = (bag_set*)realloc(set,
4381 + sizeof(bag_entry)*newAvail);
4385 set->availAttrs = newAvail;
4386 entries = (bag_entry*)(set+1);
4387 if (kDebugTableNoisy) {
4388 ALOGI("Reallocated set %p, entries=%p, avail=%zu\n",
4389 set, entries, set->availAttrs);
4393 // Going in the middle, need to make space.
4394 memmove(entries+curEntry+1, entries+curEntry,
4395 sizeof(bag_entry)*(set->numAttrs-curEntry));
4398 if (kDebugTableNoisy) {
4399 ALOGI("#%zu: Inserting new attribute: 0x%08x\n", curEntry, newName);
4402 if (kDebugTableNoisy) {
4403 ALOGI("#%zu: Replacing existing attribute: 0x%08x\n", curEntry, oldName);
4407 bag_entry* cur = entries+curEntry;
4409 cur->stringBlock = entry.package->header->index;
4410 cur->map.name.ident = newName;
4411 cur->map.value.copyFrom_dtoh(map->value);
4412 status_t err = grp->dynamicRefTable.lookupResourceValue(&cur->map.value);
4413 if (err != NO_ERROR) {
4414 ALOGE("Reference item(0x%08x) in bag could not be resolved.", cur->map.value.data);
4415 return UNKNOWN_ERROR;
4418 if (kDebugTableNoisy) {
4419 ALOGI("Setting entry #%zu %p: block=%zd, name=0x%08d, type=%d, data=0x%08x\n",
4420 curEntry, cur, cur->stringBlock, cur->map.name.ident,
4421 cur->map.value.dataType, cur->map.value.data);
4427 const size_t size = dtohs(map->value.size);
4428 curOff += size + sizeof(*map)-sizeof(map->value);
4431 if (curEntry > set->numAttrs) {
4432 set->numAttrs = curEntry;
4435 // And this is it...
4438 if (outTypeSpecFlags != NULL) {
4439 *outTypeSpecFlags = set->typeSpecFlags;
4441 *outBag = (bag_entry*)(set+1);
4442 if (kDebugTableNoisy) {
4443 ALOGI("Returning %zu attrs\n", set->numAttrs);
4445 return set->numAttrs;
4450 void ResTable::setParameters(const ResTable_config* params)
4452 AutoMutex _lock(mLock);
4453 AutoMutex _lock2(mFilteredConfigLock);
4455 if (kDebugTableGetEntry) {
4456 ALOGI("Setting parameters: %s\n", params->toString().string());
4459 for (size_t p = 0; p < mPackageGroups.size(); p++) {
4460 PackageGroup* packageGroup = mPackageGroups.editItemAt(p);
4461 if (kDebugTableNoisy) {
4462 ALOGI("CLEARING BAGS FOR GROUP %zu!", p);
4464 packageGroup->clearBagCache();
4466 // Find which configurations match the set of parameters. This allows for a much
4467 // faster lookup in getEntry() if the set of values is narrowed down.
4468 for (size_t t = 0; t < packageGroup->types.size(); t++) {
4469 if (packageGroup->types[t].isEmpty()) {
4473 TypeList& typeList = packageGroup->types.editItemAt(t);
4475 // Retrieve the cache entry for this type.
4476 TypeCacheEntry& cacheEntry = packageGroup->typeCacheEntries.editItemAt(t);
4478 for (size_t ts = 0; ts < typeList.size(); ts++) {
4479 Type* type = typeList.editItemAt(ts);
4481 std::shared_ptr<Vector<const ResTable_type*>> newFilteredConfigs =
4482 std::make_shared<Vector<const ResTable_type*>>();
4484 for (size_t ti = 0; ti < type->configs.size(); ti++) {
4485 ResTable_config config;
4486 config.copyFromDtoH(type->configs[ti]->config);
4488 if (config.match(mParams)) {
4489 newFilteredConfigs->add(type->configs[ti]);
4493 if (kDebugTableNoisy) {
4494 ALOGD("Updating pkg=%zu type=%zu with %zu filtered configs",
4495 p, t, newFilteredConfigs->size());
4498 cacheEntry.filteredConfigs.add(newFilteredConfigs);
4504 void ResTable::getParameters(ResTable_config* params) const
4511 struct id_name_map {
4517 const static id_name_map ID_NAMES[] = {
4518 { ResTable_map::ATTR_TYPE, 5, { '^', 't', 'y', 'p', 'e' } },
4519 { ResTable_map::ATTR_L10N, 5, { '^', 'l', '1', '0', 'n' } },
4520 { ResTable_map::ATTR_MIN, 4, { '^', 'm', 'i', 'n' } },
4521 { ResTable_map::ATTR_MAX, 4, { '^', 'm', 'a', 'x' } },
4522 { ResTable_map::ATTR_OTHER, 6, { '^', 'o', 't', 'h', 'e', 'r' } },
4523 { ResTable_map::ATTR_ZERO, 5, { '^', 'z', 'e', 'r', 'o' } },
4524 { ResTable_map::ATTR_ONE, 4, { '^', 'o', 'n', 'e' } },
4525 { ResTable_map::ATTR_TWO, 4, { '^', 't', 'w', 'o' } },
4526 { ResTable_map::ATTR_FEW, 4, { '^', 'f', 'e', 'w' } },
4527 { ResTable_map::ATTR_MANY, 5, { '^', 'm', 'a', 'n', 'y' } },
4530 uint32_t ResTable::identifierForName(const char16_t* name, size_t nameLen,
4531 const char16_t* type, size_t typeLen,
4532 const char16_t* package,
4534 uint32_t* outTypeSpecFlags) const
4536 if (kDebugTableSuperNoisy) {
4537 printf("Identifier for name: error=%d\n", mError);
4540 // Check for internal resource identifier as the very first thing, so
4541 // that we will always find them even when there are no resources.
4542 if (name[0] == '^') {
4543 const int N = (sizeof(ID_NAMES)/sizeof(ID_NAMES[0]));
4545 for (int i=0; i<N; i++) {
4546 const id_name_map* m = ID_NAMES + i;
4548 if (len != nameLen) {
4551 for (size_t j=1; j<len; j++) {
4552 if (m->name[j] != name[j]) {
4556 if (outTypeSpecFlags) {
4557 *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC;
4564 if (name[1] == 'i' && name[2] == 'n'
4565 && name[3] == 'd' && name[4] == 'e' && name[5] == 'x'
4566 && name[6] == '_') {
4567 int index = atoi(String8(name + 7, nameLen - 7).string());
4568 if (Res_CHECKID(index)) {
4569 ALOGW("Array resource index: %d is too large.",
4573 if (outTypeSpecFlags) {
4574 *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC;
4576 return Res_MAKEARRAY(index);
4582 if (mError != NO_ERROR) {
4586 bool fakePublic = false;
4588 // Figure out the package and type we are looking in...
4590 const char16_t* packageEnd = NULL;
4591 const char16_t* typeEnd = NULL;
4592 const char16_t* const nameEnd = name+nameLen;
4593 const char16_t* p = name;
4594 while (p < nameEnd) {
4595 if (*p == ':') packageEnd = p;
4596 else if (*p == '/') typeEnd = p;
4606 if (name >= nameEnd) {
4612 packageLen = packageEnd-name;
4613 name = packageEnd+1;
4614 } else if (!package) {
4620 typeLen = typeEnd-name;
4626 if (name >= nameEnd) {
4629 nameLen = nameEnd-name;
4631 if (kDebugTableNoisy) {
4632 printf("Looking for identifier: type=%s, name=%s, package=%s\n",
4633 String8(type, typeLen).string(),
4634 String8(name, nameLen).string(),
4635 String8(package, packageLen).string());
4638 const String16 attr("attr");
4639 const String16 attrPrivate("^attr-private");
4641 const size_t NG = mPackageGroups.size();
4642 for (size_t ig=0; ig<NG; ig++) {
4643 const PackageGroup* group = mPackageGroups[ig];
4645 if (strzcmp16(package, packageLen,
4646 group->name.string(), group->name.size())) {
4647 if (kDebugTableNoisy) {
4648 printf("Skipping package group: %s\n", String8(group->name).string());
4653 const size_t packageCount = group->packages.size();
4654 for (size_t pi = 0; pi < packageCount; pi++) {
4655 const char16_t* targetType = type;
4656 size_t targetTypeLen = typeLen;
4659 ssize_t ti = group->packages[pi]->typeStrings.indexOfString(
4660 targetType, targetTypeLen);
4665 ti += group->packages[pi]->typeIdOffset;
4667 const uint32_t identifier = findEntry(group, ti, name, nameLen,
4669 if (identifier != 0) {
4670 if (fakePublic && outTypeSpecFlags) {
4671 *outTypeSpecFlags |= ResTable_typeSpec::SPEC_PUBLIC;
4675 } while (strzcmp16(attr.string(), attr.size(), targetType, targetTypeLen) == 0
4676 && (targetType = attrPrivate.string())
4677 && (targetTypeLen = attrPrivate.size())
4685 uint32_t ResTable::findEntry(const PackageGroup* group, ssize_t typeIndex, const char16_t* name,
4686 size_t nameLen, uint32_t* outTypeSpecFlags) const {
4687 const TypeList& typeList = group->types[typeIndex];
4688 const size_t typeCount = typeList.size();
4689 for (size_t i = 0; i < typeCount; i++) {
4690 const Type* t = typeList[i];
4691 const ssize_t ei = t->package->keyStrings.indexOfString(name, nameLen);
4696 const size_t configCount = t->configs.size();
4697 for (size_t j = 0; j < configCount; j++) {
4698 const TypeVariant tv(t->configs[j]);
4699 for (TypeVariant::iterator iter = tv.beginEntries();
4700 iter != tv.endEntries();
4702 const ResTable_entry* entry = *iter;
4703 if (entry == NULL) {
4707 if (dtohl(entry->key.index) == (size_t) ei) {
4708 uint32_t resId = Res_MAKEID(group->id - 1, typeIndex, iter.index());
4709 if (outTypeSpecFlags) {
4711 if (getEntry(group, typeIndex, iter.index(), NULL, &result) != NO_ERROR) {
4712 ALOGW("Failed to find spec flags for 0x%08x", resId);
4715 *outTypeSpecFlags = result.specFlags;
4725 bool ResTable::expandResourceRef(const char16_t* refStr, size_t refLen,
4726 String16* outPackage,
4729 const String16* defType,
4730 const String16* defPackage,
4731 const char** outErrorMsg,
4732 bool* outPublicOnly)
4734 const char16_t* packageEnd = NULL;
4735 const char16_t* typeEnd = NULL;
4736 const char16_t* p = refStr;
4737 const char16_t* const end = p + refLen;
4739 if (*p == ':') packageEnd = p;
4740 else if (*p == '/') {
4749 if (outPublicOnly != NULL) {
4750 *outPublicOnly = true;
4754 if (outPublicOnly != NULL) {
4755 *outPublicOnly = false;
4760 *outPackage = String16(p, packageEnd-p);
4765 *outErrorMsg = "No resource package specified";
4769 *outPackage = *defPackage;
4772 *outType = String16(p, typeEnd-p);
4777 *outErrorMsg = "No resource type specified";
4781 *outType = *defType;
4783 *outName = String16(p, end-p);
4784 if(**outPackage == 0) {
4786 *outErrorMsg = "Resource package cannot be an empty string";
4790 if(**outType == 0) {
4792 *outErrorMsg = "Resource type cannot be an empty string";
4796 if(**outName == 0) {
4798 *outErrorMsg = "Resource id cannot be an empty string";
4805 static uint32_t get_hex(char c, bool* outError)
4807 if (c >= '0' && c <= '9') {
4809 } else if (c >= 'a' && c <= 'f') {
4810 return c - 'a' + 0xa;
4811 } else if (c >= 'A' && c <= 'F') {
4812 return c - 'A' + 0xa;
4827 static const unit_entry unitNames[] = {
4828 { "px", strlen("px"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PX, 1.0f },
4829 { "dip", strlen("dip"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
4830 { "dp", strlen("dp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
4831 { "sp", strlen("sp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_SP, 1.0f },
4832 { "pt", strlen("pt"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PT, 1.0f },
4833 { "in", strlen("in"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_IN, 1.0f },
4834 { "mm", strlen("mm"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_MM, 1.0f },
4835 { "%", strlen("%"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION, 1.0f/100 },
4836 { "%p", strlen("%p"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION_PARENT, 1.0f/100 },
4837 { NULL, 0, 0, 0, 0 }
4840 static bool parse_unit(const char* str, Res_value* outValue,
4841 float* outScale, const char** outEnd)
4843 const char* end = str;
4844 while (*end != 0 && !isspace((unsigned char)*end)) {
4847 const size_t len = end-str;
4849 const char* realEnd = end;
4850 while (*realEnd != 0 && isspace((unsigned char)*realEnd)) {
4853 if (*realEnd != 0) {
4857 const unit_entry* cur = unitNames;
4859 if (len == cur->len && strncmp(cur->name, str, len) == 0) {
4860 outValue->dataType = cur->type;
4861 outValue->data = cur->unit << Res_value::COMPLEX_UNIT_SHIFT;
4862 *outScale = cur->scale;
4864 //printf("Found unit %s for %s\n", cur->name, str);
4873 bool U16StringToInt(const char16_t* s, size_t len, Res_value* outValue)
4875 while (len > 0 && isspace16(*s)) {
4893 if (s[i] < '0' || s[i] > '9') {
4897 static_assert(std::is_same<uint32_t, Res_value::data_type>::value,
4898 "Res_value::data_type has changed. The range checks in this "
4899 "function are no longer correct.");
4903 if (len > 1 && s[i] == '0' && s[i+1] == 'x') {
4917 while (i < len && !error) {
4918 val = (val*16) + get_hex(s[i], &error);
4921 if (val > std::numeric_limits<uint32_t>::max()) {
4931 if (s[i] < '0' || s[i] > '9') {
4934 val = (val*10) + s[i]-'0';
4937 if ((neg && -val < std::numeric_limits<int32_t>::min()) ||
4938 (!neg && val > std::numeric_limits<int32_t>::max())) {
4944 if (neg) val = -val;
4946 while (i < len && isspace16(s[i])) {
4955 outValue->dataType =
4956 isHex ? outValue->TYPE_INT_HEX : outValue->TYPE_INT_DEC;
4957 outValue->data = static_cast<Res_value::data_type>(val);
4962 bool ResTable::stringToInt(const char16_t* s, size_t len, Res_value* outValue)
4964 return U16StringToInt(s, len, outValue);
4967 bool ResTable::stringToFloat(const char16_t* s, size_t len, Res_value* outValue)
4969 while (len > 0 && isspace16(*s)) {
4980 while (len > 0 && *s != 0 && i < 126) {
4991 if ((buf[0] < '0' || buf[0] > '9') && buf[0] != '.' && buf[0] != '-' && buf[0] != '+') {
4997 float f = strtof(buf, (char**)&end);
4999 if (*end != 0 && !isspace((unsigned char)*end)) {
5000 // Might be a unit...
5002 if (parse_unit(end, outValue, &scale, &end)) {
5004 const bool neg = f < 0;
5006 uint64_t bits = (uint64_t)(f*(1<<23)+.5f);
5009 if ((bits&0x7fffff) == 0) {
5010 // Always use 23p0 if there is no fraction, just to make
5011 // things easier to read.
5012 radix = Res_value::COMPLEX_RADIX_23p0;
5014 } else if ((bits&0xffffffffff800000LL) == 0) {
5015 // Magnitude is zero -- can fit in 0 bits of precision.
5016 radix = Res_value::COMPLEX_RADIX_0p23;
5018 } else if ((bits&0xffffffff80000000LL) == 0) {
5019 // Magnitude can fit in 8 bits of precision.
5020 radix = Res_value::COMPLEX_RADIX_8p15;
5022 } else if ((bits&0xffffff8000000000LL) == 0) {
5023 // Magnitude can fit in 16 bits of precision.
5024 radix = Res_value::COMPLEX_RADIX_16p7;
5027 // Magnitude needs entire range, so no fractional part.
5028 radix = Res_value::COMPLEX_RADIX_23p0;
5031 int32_t mantissa = (int32_t)(
5032 (bits>>shift) & Res_value::COMPLEX_MANTISSA_MASK);
5034 mantissa = (-mantissa) & Res_value::COMPLEX_MANTISSA_MASK;
5037 (radix<<Res_value::COMPLEX_RADIX_SHIFT)
5038 | (mantissa<<Res_value::COMPLEX_MANTISSA_SHIFT);
5039 //printf("Input value: %f 0x%016Lx, mult: %f, radix: %d, shift: %d, final: 0x%08x\n",
5040 // f * (neg ? -1 : 1), bits, f*(1<<23),
5041 // radix, shift, outValue->data);
5047 while (*end != 0 && isspace((unsigned char)*end)) {
5053 outValue->dataType = outValue->TYPE_FLOAT;
5054 *(float*)(&outValue->data) = f;
5062 bool ResTable::stringToValue(Res_value* outValue, String16* outString,
5063 const char16_t* s, size_t len,
5064 bool preserveSpaces, bool coerceType,
5066 const String16* defType,
5067 const String16* defPackage,
5069 void* accessorCookie,
5071 bool enforcePrivate) const
5073 bool localizationSetting = accessor != NULL && accessor->getLocalizationSetting();
5074 const char* errorMsg = NULL;
5076 outValue->size = sizeof(Res_value);
5079 // First strip leading/trailing whitespace. Do this before handling
5080 // escapes, so they can be used to force whitespace into the string.
5081 if (!preserveSpaces) {
5082 while (len > 0 && isspace16(*s)) {
5086 while (len > 0 && isspace16(s[len-1])) {
5089 // If the string ends with '\', then we keep the space after it.
5090 if (len > 0 && s[len-1] == '\\' && s[len] != 0) {
5095 //printf("Value for: %s\n", String8(s, len).string());
5097 uint32_t l10nReq = ResTable_map::L10N_NOT_REQUIRED;
5098 uint32_t attrMin = 0x80000000, attrMax = 0x7fffffff;
5099 bool fromAccessor = false;
5100 if (attrID != 0 && !Res_INTERNALID(attrID)) {
5101 const ssize_t p = getResourcePackageIndex(attrID);
5102 const bag_entry* bag;
5103 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
5104 //printf("For attr 0x%08x got bag of %d\n", attrID, cnt);
5107 //printf("Entry 0x%08x = 0x%08x\n", bag->map.name.ident, bag->map.value.data);
5108 switch (bag->map.name.ident) {
5109 case ResTable_map::ATTR_TYPE:
5110 attrType = bag->map.value.data;
5112 case ResTable_map::ATTR_MIN:
5113 attrMin = bag->map.value.data;
5115 case ResTable_map::ATTR_MAX:
5116 attrMax = bag->map.value.data;
5118 case ResTable_map::ATTR_L10N:
5119 l10nReq = bag->map.value.data;
5126 } else if (accessor && accessor->getAttributeType(attrID, &attrType)) {
5127 fromAccessor = true;
5128 if (attrType == ResTable_map::TYPE_ENUM
5129 || attrType == ResTable_map::TYPE_FLAGS
5130 || attrType == ResTable_map::TYPE_INTEGER) {
5131 accessor->getAttributeMin(attrID, &attrMin);
5132 accessor->getAttributeMax(attrID, &attrMax);
5134 if (localizationSetting) {
5135 l10nReq = accessor->getAttributeL10N(attrID);
5140 const bool canStringCoerce =
5141 coerceType && (attrType&ResTable_map::TYPE_STRING) != 0;
5144 outValue->dataType = outValue->TYPE_REFERENCE;
5146 // Note: we don't check attrType here because the reference can
5147 // be to any other type; we just need to count on the client making
5148 // sure the referenced type is correct.
5150 //printf("Looking up ref: %s\n", String8(s, len).string());
5152 // It's a reference!
5153 if (len == 5 && s[1]=='n' && s[2]=='u' && s[3]=='l' && s[4]=='l') {
5154 // Special case @null as undefined. This will be converted by
5155 // AssetManager to TYPE_NULL with data DATA_NULL_UNDEFINED.
5158 } else if (len == 6 && s[1]=='e' && s[2]=='m' && s[3]=='p' && s[4]=='t' && s[5]=='y') {
5159 // Special case @empty as explicitly defined empty value.
5160 outValue->dataType = Res_value::TYPE_NULL;
5161 outValue->data = Res_value::DATA_NULL_EMPTY;
5164 bool createIfNotFound = false;
5165 const char16_t* resourceRefName;
5166 int resourceNameLen;
5167 if (len > 2 && s[1] == '+') {
5168 createIfNotFound = true;
5169 resourceRefName = s + 2;
5170 resourceNameLen = len - 2;
5171 } else if (len > 2 && s[1] == '*') {
5172 enforcePrivate = false;
5173 resourceRefName = s + 2;
5174 resourceNameLen = len - 2;
5176 createIfNotFound = false;
5177 resourceRefName = s + 1;
5178 resourceNameLen = len - 1;
5180 String16 package, type, name;
5181 if (!expandResourceRef(resourceRefName,resourceNameLen, &package, &type, &name,
5182 defType, defPackage, &errorMsg)) {
5183 if (accessor != NULL) {
5184 accessor->reportError(accessorCookie, errorMsg);
5189 uint32_t specFlags = 0;
5190 uint32_t rid = identifierForName(name.string(), name.size(), type.string(),
5191 type.size(), package.string(), package.size(), &specFlags);
5193 if (enforcePrivate) {
5194 if (accessor == NULL || accessor->getAssetsPackage() != package) {
5195 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
5196 if (accessor != NULL) {
5197 accessor->reportError(accessorCookie, "Resource is not public.");
5206 accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
5207 Res_GETTYPE(rid), Res_GETENTRY(rid));
5208 if (kDebugTableNoisy) {
5209 ALOGI("Incl %s:%s/%s: 0x%08x\n",
5210 String8(package).string(), String8(type).string(),
5211 String8(name).string(), rid);
5215 uint32_t packageId = Res_GETPACKAGE(rid) + 1;
5216 if (packageId != APP_PACKAGE_ID && packageId != SYS_PACKAGE_ID) {
5217 outValue->dataType = Res_value::TYPE_DYNAMIC_REFERENCE;
5219 outValue->data = rid;
5224 uint32_t rid = accessor->getCustomResourceWithCreation(package, type, name,
5227 if (kDebugTableNoisy) {
5228 ALOGI("Pckg %s:%s/%s: 0x%08x\n",
5229 String8(package).string(), String8(type).string(),
5230 String8(name).string(), rid);
5232 uint32_t packageId = Res_GETPACKAGE(rid) + 1;
5233 if (packageId == 0x00) {
5234 outValue->data = rid;
5235 outValue->dataType = Res_value::TYPE_DYNAMIC_REFERENCE;
5237 } else if (packageId == APP_PACKAGE_ID || packageId == SYS_PACKAGE_ID) {
5238 // We accept packageId's generated as 0x01 in order to support
5239 // building the android system resources
5240 outValue->data = rid;
5247 if (accessor != NULL) {
5248 accessor->reportError(accessorCookie, "No resource found that matches the given name");
5253 // if we got to here, and localization is required and it's not a reference,
5254 // complain and bail.
5255 if (l10nReq == ResTable_map::L10N_SUGGESTED) {
5256 if (localizationSetting) {
5257 if (accessor != NULL) {
5258 accessor->reportError(accessorCookie, "This attribute must be localized.");
5264 // It's a color! Convert to an integer of the form 0xaarrggbb.
5268 outValue->dataType = outValue->TYPE_INT_COLOR_RGB4;
5269 color |= 0xFF000000;
5270 color |= get_hex(s[1], &error) << 20;
5271 color |= get_hex(s[1], &error) << 16;
5272 color |= get_hex(s[2], &error) << 12;
5273 color |= get_hex(s[2], &error) << 8;
5274 color |= get_hex(s[3], &error) << 4;
5275 color |= get_hex(s[3], &error);
5276 } else if (len == 5) {
5277 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB4;
5278 color |= get_hex(s[1], &error) << 28;
5279 color |= get_hex(s[1], &error) << 24;
5280 color |= get_hex(s[2], &error) << 20;
5281 color |= get_hex(s[2], &error) << 16;
5282 color |= get_hex(s[3], &error) << 12;
5283 color |= get_hex(s[3], &error) << 8;
5284 color |= get_hex(s[4], &error) << 4;
5285 color |= get_hex(s[4], &error);
5286 } else if (len == 7) {
5287 outValue->dataType = outValue->TYPE_INT_COLOR_RGB8;
5288 color |= 0xFF000000;
5289 color |= get_hex(s[1], &error) << 20;
5290 color |= get_hex(s[2], &error) << 16;
5291 color |= get_hex(s[3], &error) << 12;
5292 color |= get_hex(s[4], &error) << 8;
5293 color |= get_hex(s[5], &error) << 4;
5294 color |= get_hex(s[6], &error);
5295 } else if (len == 9) {
5296 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB8;
5297 color |= get_hex(s[1], &error) << 28;
5298 color |= get_hex(s[2], &error) << 24;
5299 color |= get_hex(s[3], &error) << 20;
5300 color |= get_hex(s[4], &error) << 16;
5301 color |= get_hex(s[5], &error) << 12;
5302 color |= get_hex(s[6], &error) << 8;
5303 color |= get_hex(s[7], &error) << 4;
5304 color |= get_hex(s[8], &error);
5309 if ((attrType&ResTable_map::TYPE_COLOR) == 0) {
5310 if (!canStringCoerce) {
5311 if (accessor != NULL) {
5312 accessor->reportError(accessorCookie,
5313 "Color types not allowed");
5318 outValue->data = color;
5319 //printf("Color input=%s, output=0x%x\n", String8(s, len).string(), color);
5323 if ((attrType&ResTable_map::TYPE_COLOR) != 0) {
5324 if (accessor != NULL) {
5325 accessor->reportError(accessorCookie, "Color value not valid --"
5326 " must be #rgb, #argb, #rrggbb, or #aarrggbb");
5329 fprintf(stderr, "%s: Color ID %s value %s is not valid\n",
5330 "Resource File", //(const char*)in->getPrintableSource(),
5331 String8(*curTag).string(),
5332 String8(s, len).string());
5340 outValue->dataType = outValue->TYPE_ATTRIBUTE;
5342 // Note: we don't check attrType here because the reference can
5343 // be to any other type; we just need to count on the client making
5344 // sure the referenced type is correct.
5346 //printf("Looking up attr: %s\n", String8(s, len).string());
5348 static const String16 attr16("attr");
5349 String16 package, type, name;
5350 if (!expandResourceRef(s+1, len-1, &package, &type, &name,
5351 &attr16, defPackage, &errorMsg)) {
5352 if (accessor != NULL) {
5353 accessor->reportError(accessorCookie, errorMsg);
5358 //printf("Pkg: %s, Type: %s, Name: %s\n",
5359 // String8(package).string(), String8(type).string(),
5360 // String8(name).string());
5361 uint32_t specFlags = 0;
5363 identifierForName(name.string(), name.size(),
5364 type.string(), type.size(),
5365 package.string(), package.size(), &specFlags);
5367 if (enforcePrivate) {
5368 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
5369 if (accessor != NULL) {
5370 accessor->reportError(accessorCookie, "Attribute is not public.");
5378 accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
5379 Res_GETTYPE(rid), Res_GETENTRY(rid));
5382 uint32_t packageId = Res_GETPACKAGE(rid) + 1;
5383 if (packageId != APP_PACKAGE_ID && packageId != SYS_PACKAGE_ID) {
5384 outValue->dataType = Res_value::TYPE_DYNAMIC_ATTRIBUTE;
5386 outValue->data = rid;
5391 uint32_t rid = accessor->getCustomResource(package, type, name);
5393 uint32_t packageId = Res_GETPACKAGE(rid) + 1;
5394 if (packageId == 0x00) {
5395 outValue->data = rid;
5396 outValue->dataType = Res_value::TYPE_DYNAMIC_ATTRIBUTE;
5398 } else if (packageId == APP_PACKAGE_ID || packageId == SYS_PACKAGE_ID) {
5399 // We accept packageId's generated as 0x01 in order to support
5400 // building the android system resources
5401 outValue->data = rid;
5407 if (accessor != NULL) {
5408 accessor->reportError(accessorCookie, "No resource found that matches the given name");
5413 if (stringToInt(s, len, outValue)) {
5414 if ((attrType&ResTable_map::TYPE_INTEGER) == 0) {
5415 // If this type does not allow integers, but does allow floats,
5416 // fall through on this error case because the float type should
5417 // be able to accept any integer value.
5418 if (!canStringCoerce && (attrType&ResTable_map::TYPE_FLOAT) == 0) {
5419 if (accessor != NULL) {
5420 accessor->reportError(accessorCookie, "Integer types not allowed");
5425 if (((int32_t)outValue->data) < ((int32_t)attrMin)
5426 || ((int32_t)outValue->data) > ((int32_t)attrMax)) {
5427 if (accessor != NULL) {
5428 accessor->reportError(accessorCookie, "Integer value out of range");
5436 if (stringToFloat(s, len, outValue)) {
5437 if (outValue->dataType == Res_value::TYPE_DIMENSION) {
5438 if ((attrType&ResTable_map::TYPE_DIMENSION) != 0) {
5441 if (!canStringCoerce) {
5442 if (accessor != NULL) {
5443 accessor->reportError(accessorCookie, "Dimension types not allowed");
5447 } else if (outValue->dataType == Res_value::TYPE_FRACTION) {
5448 if ((attrType&ResTable_map::TYPE_FRACTION) != 0) {
5451 if (!canStringCoerce) {
5452 if (accessor != NULL) {
5453 accessor->reportError(accessorCookie, "Fraction types not allowed");
5457 } else if ((attrType&ResTable_map::TYPE_FLOAT) == 0) {
5458 if (!canStringCoerce) {
5459 if (accessor != NULL) {
5460 accessor->reportError(accessorCookie, "Float types not allowed");
5470 if ((s[0] == 't' || s[0] == 'T') &&
5471 (s[1] == 'r' || s[1] == 'R') &&
5472 (s[2] == 'u' || s[2] == 'U') &&
5473 (s[3] == 'e' || s[3] == 'E')) {
5474 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
5475 if (!canStringCoerce) {
5476 if (accessor != NULL) {
5477 accessor->reportError(accessorCookie, "Boolean types not allowed");
5482 outValue->dataType = outValue->TYPE_INT_BOOLEAN;
5483 outValue->data = (uint32_t)-1;
5490 if ((s[0] == 'f' || s[0] == 'F') &&
5491 (s[1] == 'a' || s[1] == 'A') &&
5492 (s[2] == 'l' || s[2] == 'L') &&
5493 (s[3] == 's' || s[3] == 'S') &&
5494 (s[4] == 'e' || s[4] == 'E')) {
5495 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
5496 if (!canStringCoerce) {
5497 if (accessor != NULL) {
5498 accessor->reportError(accessorCookie, "Boolean types not allowed");
5503 outValue->dataType = outValue->TYPE_INT_BOOLEAN;
5510 if ((attrType&ResTable_map::TYPE_ENUM) != 0) {
5511 const ssize_t p = getResourcePackageIndex(attrID);
5512 const bag_entry* bag;
5513 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
5514 //printf("Got %d for enum\n", cnt);
5516 resource_name rname;
5518 if (!Res_INTERNALID(bag->map.name.ident)) {
5519 //printf("Trying attr #%08x\n", bag->map.name.ident);
5520 if (getResourceName(bag->map.name.ident, false, &rname)) {
5522 printf("Matching %s against %s (0x%08x)\n",
5523 String8(s, len).string(),
5524 String8(rname.name, rname.nameLen).string(),
5525 bag->map.name.ident);
5527 if (strzcmp16(s, len, rname.name, rname.nameLen) == 0) {
5528 outValue->dataType = bag->map.value.dataType;
5529 outValue->data = bag->map.value.data;
5543 if (accessor->getAttributeEnum(attrID, s, len, outValue)) {
5549 if ((attrType&ResTable_map::TYPE_FLAGS) != 0) {
5550 const ssize_t p = getResourcePackageIndex(attrID);
5551 const bag_entry* bag;
5552 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
5553 //printf("Got %d for flags\n", cnt);
5555 bool failed = false;
5556 resource_name rname;
5557 outValue->dataType = Res_value::TYPE_INT_HEX;
5559 const char16_t* end = s + len;
5560 const char16_t* pos = s;
5561 while (pos < end && !failed) {
5562 const char16_t* start = pos;
5564 while (pos < end && *pos != '|') {
5567 //printf("Looking for: %s\n", String8(start, pos-start).string());
5568 const bag_entry* bagi = bag;
5570 for (i=0; i<cnt; i++, bagi++) {
5571 if (!Res_INTERNALID(bagi->map.name.ident)) {
5572 //printf("Trying attr #%08x\n", bagi->map.name.ident);
5573 if (getResourceName(bagi->map.name.ident, false, &rname)) {
5575 printf("Matching %s against %s (0x%08x)\n",
5576 String8(start,pos-start).string(),
5577 String8(rname.name, rname.nameLen).string(),
5578 bagi->map.name.ident);
5580 if (strzcmp16(start, pos-start, rname.name, rname.nameLen) == 0) {
5581 outValue->data |= bagi->map.value.data;
5588 // Didn't find this flag identifier.
5597 //printf("Final flag value: 0x%lx\n", outValue->data);
5604 if (accessor->getAttributeFlags(attrID, s, len, outValue)) {
5605 //printf("Final flag value: 0x%lx\n", outValue->data);
5611 if ((attrType&ResTable_map::TYPE_STRING) == 0) {
5612 if (accessor != NULL) {
5613 accessor->reportError(accessorCookie, "String types not allowed");
5618 // Generic string handling...
5619 outValue->dataType = outValue->TYPE_STRING;
5621 bool failed = collectString(outString, s, len, preserveSpaces, &errorMsg);
5622 if (accessor != NULL) {
5623 accessor->reportError(accessorCookie, errorMsg);
5631 bool ResTable::collectString(String16* outString,
5632 const char16_t* s, size_t len,
5633 bool preserveSpaces,
5634 const char** outErrorMsg,
5640 const char16_t* p = s;
5641 while (p < (s+len)) {
5642 while (p < (s+len)) {
5643 const char16_t c = *p;
5647 if (!preserveSpaces) {
5648 if (quoted == 0 && isspace16(c)
5649 && (c != ' ' || isspace16(*(p+1)))) {
5652 if (c == '"' && (quoted == 0 || quoted == '"')) {
5655 if (c == '\'' && (quoted == 0 || quoted == '\'')) {
5657 * In practice, when people write ' instead of \'
5658 * in a string, they are doing it by accident
5659 * instead of really meaning to use ' as a quoting
5660 * character. Warn them so they don't lose it.
5663 *outErrorMsg = "Apostrophe not preceded by \\";
5672 tmp.append(String16(s, p-s));
5674 if (!preserveSpaces && (*p == '"' || *p == '\'')) {
5681 } else if (!preserveSpaces && isspace16(*p)) {
5682 // Space outside of a quote -- consume all spaces and
5683 // leave a single plain space char.
5684 tmp.append(String16(" "));
5686 while (p < (s+len) && isspace16(*p)) {
5689 } else if (*p == '\\') {
5694 tmp.append(String16("\t"));
5697 tmp.append(String16("\n"));
5700 tmp.append(String16("#"));
5703 tmp.append(String16("@"));
5706 tmp.append(String16("?"));
5709 tmp.append(String16("\""));
5712 tmp.append(String16("'"));
5715 tmp.append(String16("\\"));
5721 while (i < 4 && p[1] != 0) {
5725 if (*p >= '0' && *p <= '9') {
5727 } else if (*p >= 'a' && *p <= 'f') {
5729 } else if (*p >= 'A' && *p <= 'F') {
5733 *outErrorMsg = "Bad character in \\u unicode escape sequence";
5739 tmp.append(String16(&chr, 1));
5742 // ignore unknown escape chars.
5753 if (tmp.size() != 0) {
5755 tmp.append(String16(s, len));
5758 outString->append(tmp);
5760 outString->setTo(tmp);
5764 outString->append(String16(s, len));
5766 outString->setTo(s, len);
5773 size_t ResTable::getBasePackageCount() const
5775 if (mError != NO_ERROR) {
5778 return mPackageGroups.size();
5781 const String16 ResTable::getBasePackageName(size_t idx) const
5783 if (mError != NO_ERROR) {
5786 LOG_FATAL_IF(idx >= mPackageGroups.size(),
5787 "Requested package index %d past package count %d",
5788 (int)idx, (int)mPackageGroups.size());
5789 return mPackageGroups[idx]->name;
5792 uint32_t ResTable::getBasePackageId(size_t idx) const
5794 if (mError != NO_ERROR) {
5797 LOG_FATAL_IF(idx >= mPackageGroups.size(),
5798 "Requested package index %d past package count %d",
5799 (int)idx, (int)mPackageGroups.size());
5800 return mPackageGroups[idx]->id;
5803 uint32_t ResTable::getLastTypeIdForPackage(size_t idx) const
5805 if (mError != NO_ERROR) {
5808 LOG_FATAL_IF(idx >= mPackageGroups.size(),
5809 "Requested package index %d past package count %d",
5810 (int)idx, (int)mPackageGroups.size());
5811 const PackageGroup* const group = mPackageGroups[idx];
5812 return group->largestTypeId;
5815 size_t ResTable::getTableCount() const
5817 return mHeaders.size();
5820 const ResStringPool* ResTable::getTableStringBlock(size_t index) const
5822 return &mHeaders[index]->values;
5825 int32_t ResTable::getTableCookie(size_t index) const
5827 return mHeaders[index]->cookie;
5830 const DynamicRefTable* ResTable::getDynamicRefTableForCookie(int32_t cookie) const
5832 const size_t N = mPackageGroups.size();
5833 for (size_t i = 0; i < N; i++) {
5834 const PackageGroup* pg = mPackageGroups[i];
5835 size_t M = pg->packages.size();
5836 for (size_t j = 0; j < M; j++) {
5837 if (pg->packages[j]->header->cookie == cookie) {
5838 return &pg->dynamicRefTable;
5845 static bool compareResTableConfig(const ResTable_config& a, const ResTable_config& b) {
5846 return a.compare(b) < 0;
5849 template <typename Func>
5850 void ResTable::forEachConfiguration(bool ignoreMipmap, bool ignoreAndroidPackage,
5851 bool includeSystemConfigs, const Func& f) const {
5852 const size_t packageCount = mPackageGroups.size();
5853 const String16 android("android");
5854 for (size_t i = 0; i < packageCount; i++) {
5855 const PackageGroup* packageGroup = mPackageGroups[i];
5856 if (ignoreAndroidPackage && android == packageGroup->name) {
5859 if (!includeSystemConfigs && packageGroup->isSystemAsset) {
5862 const size_t typeCount = packageGroup->types.size();
5863 for (size_t j = 0; j < typeCount; j++) {
5864 const TypeList& typeList = packageGroup->types[j];
5865 const size_t numTypes = typeList.size();
5866 for (size_t k = 0; k < numTypes; k++) {
5867 const Type* type = typeList[k];
5868 const ResStringPool& typeStrings = type->package->typeStrings;
5869 if (ignoreMipmap && typeStrings.string8ObjectAt(
5870 type->typeSpec->id - 1) == "mipmap") {
5874 const size_t numConfigs = type->configs.size();
5875 for (size_t m = 0; m < numConfigs; m++) {
5876 const ResTable_type* config = type->configs[m];
5877 ResTable_config cfg;
5878 memset(&cfg, 0, sizeof(ResTable_config));
5879 cfg.copyFromDtoH(config->config);
5888 void ResTable::getConfigurations(Vector<ResTable_config>* configs, bool ignoreMipmap,
5889 bool ignoreAndroidPackage, bool includeSystemConfigs) const {
5890 auto func = [&](const ResTable_config& cfg) {
5891 const auto beginIter = configs->begin();
5892 const auto endIter = configs->end();
5894 auto iter = std::lower_bound(beginIter, endIter, cfg, compareResTableConfig);
5895 if (iter == endIter || iter->compare(cfg) != 0) {
5896 configs->insertAt(cfg, std::distance(beginIter, iter));
5899 forEachConfiguration(ignoreMipmap, ignoreAndroidPackage, includeSystemConfigs, func);
5902 static bool compareString8AndCString(const String8& str, const char* cStr) {
5903 return strcmp(str.string(), cStr) < 0;
5906 void ResTable::getLocales(Vector<String8>* locales, bool includeSystemLocales) const {
5907 char locale[RESTABLE_MAX_LOCALE_LEN];
5909 forEachConfiguration(false, false, includeSystemLocales, [&](const ResTable_config& cfg) {
5910 if (cfg.locale != 0) {
5911 cfg.getBcp47Locale(locale);
5913 const auto beginIter = locales->begin();
5914 const auto endIter = locales->end();
5916 auto iter = std::lower_bound(beginIter, endIter, locale, compareString8AndCString);
5917 if (iter == endIter || strcmp(iter->string(), locale) != 0) {
5918 locales->insertAt(String8(locale), std::distance(beginIter, iter));
5924 StringPoolRef::StringPoolRef(const ResStringPool* pool, uint32_t index)
5925 : mPool(pool), mIndex(index) {}
5927 StringPoolRef::StringPoolRef()
5928 : mPool(NULL), mIndex(0) {}
5930 const char* StringPoolRef::string8(size_t* outLen) const {
5931 if (mPool != NULL) {
5932 return mPool->string8At(mIndex, outLen);
5934 if (outLen != NULL) {
5940 const char16_t* StringPoolRef::string16(size_t* outLen) const {
5941 if (mPool != NULL) {
5942 return mPool->stringAt(mIndex, outLen);
5944 if (outLen != NULL) {
5950 bool ResTable::getResourceFlags(uint32_t resID, uint32_t* outFlags) const {
5951 if (mError != NO_ERROR) {
5955 const ssize_t p = getResourcePackageIndex(resID);
5956 const int t = Res_GETTYPE(resID);
5957 const int e = Res_GETENTRY(resID);
5960 if (Res_GETPACKAGE(resID)+1 == 0) {
5961 ALOGW("No package identifier when getting flags for resource number 0x%08x", resID);
5963 ALOGW("No known package when getting flags for resource number 0x%08x", resID);
5968 ALOGW("No type identifier when getting flags for resource number 0x%08x", resID);
5972 const PackageGroup* const grp = mPackageGroups[p];
5974 ALOGW("Bad identifier when getting flags for resource number 0x%08x", resID);
5979 status_t err = getEntry(grp, t, e, NULL, &entry);
5980 if (err != NO_ERROR) {
5984 *outFlags = entry.specFlags;
5988 status_t ResTable::getEntry(
5989 const PackageGroup* packageGroup, int typeIndex, int entryIndex,
5990 const ResTable_config* config,
5991 Entry* outEntry) const
5993 const TypeList& typeList = packageGroup->types[typeIndex];
5994 if (typeList.isEmpty()) {
5995 ALOGV("Skipping entry type index 0x%02x because type is NULL!\n", typeIndex);
5999 const ResTable_type* bestType = NULL;
6000 uint32_t bestOffset = ResTable_type::NO_ENTRY;
6001 const Package* bestPackage = NULL;
6002 uint32_t specFlags = 0;
6003 uint8_t actualTypeIndex = typeIndex;
6004 ResTable_config bestConfig;
6005 memset(&bestConfig, 0, sizeof(bestConfig));
6007 // Iterate over the Types of each package.
6008 const size_t typeCount = typeList.size();
6009 for (size_t i = 0; i < typeCount; i++) {
6010 const Type* const typeSpec = typeList[i];
6012 int realEntryIndex = entryIndex;
6013 int realTypeIndex = typeIndex;
6014 bool currentTypeIsOverlay = false;
6016 // Runtime overlay packages provide a mapping of app resource
6017 // ID to package resource ID.
6018 if (typeSpec->idmapEntries.hasEntries()) {
6019 uint16_t overlayEntryIndex;
6020 if (typeSpec->idmapEntries.lookup(entryIndex, &overlayEntryIndex) != NO_ERROR) {
6021 // No such mapping exists
6024 realEntryIndex = overlayEntryIndex;
6025 realTypeIndex = typeSpec->idmapEntries.overlayTypeId() - 1;
6026 currentTypeIsOverlay = true;
6029 if (static_cast<size_t>(realEntryIndex) >= typeSpec->entryCount) {
6030 ALOGW("For resource 0x%08x, entry index(%d) is beyond type entryCount(%d)",
6031 Res_MAKEID(packageGroup->id - 1, typeIndex, entryIndex),
6032 entryIndex, static_cast<int>(typeSpec->entryCount));
6033 // We should normally abort here, but some legacy apps declare
6034 // resources in the 'android' package (old bug in AAPT).
6038 // Aggregate all the flags for each package that defines this entry.
6039 if (typeSpec->typeSpecFlags != NULL) {
6040 specFlags |= dtohl(typeSpec->typeSpecFlags[realEntryIndex]);
6045 const Vector<const ResTable_type*>* candidateConfigs = &typeSpec->configs;
6047 std::shared_ptr<Vector<const ResTable_type*>> filteredConfigs;
6048 if (config && memcmp(&mParams, config, sizeof(mParams)) == 0) {
6049 // Grab the lock first so we can safely get the current filtered list.
6050 AutoMutex _lock(mFilteredConfigLock);
6052 // This configuration is equal to the one we have previously cached for,
6053 // so use the filtered configs.
6055 const TypeCacheEntry& cacheEntry = packageGroup->typeCacheEntries[typeIndex];
6056 if (i < cacheEntry.filteredConfigs.size()) {
6057 if (cacheEntry.filteredConfigs[i]) {
6058 // Grab a reference to the shared_ptr so it doesn't get destroyed while
6059 // going through this list.
6060 filteredConfigs = cacheEntry.filteredConfigs[i];
6062 // Use this filtered list.
6063 candidateConfigs = filteredConfigs.get();
6068 const size_t numConfigs = candidateConfigs->size();
6069 for (size_t c = 0; c < numConfigs; c++) {
6070 const ResTable_type* const thisType = candidateConfigs->itemAt(c);
6071 if (thisType == NULL) {
6075 ResTable_config thisConfig;
6076 thisConfig.copyFromDtoH(thisType->config);
6078 // Check to make sure this one is valid for the current parameters.
6079 if (config != NULL && !thisConfig.match(*config)) {
6083 // Check if there is the desired entry in this type.
6084 const uint32_t* const eindex = reinterpret_cast<const uint32_t*>(
6085 reinterpret_cast<const uint8_t*>(thisType) + dtohs(thisType->header.headerSize));
6087 uint32_t thisOffset = dtohl(eindex[realEntryIndex]);
6088 if (thisOffset == ResTable_type::NO_ENTRY) {
6089 // There is no entry for this index and configuration.
6093 if (bestType != NULL) {
6094 // Check if this one is less specific than the last found. If so,
6095 // we will skip it. We check starting with things we most care
6096 // about to those we least care about.
6097 if (!thisConfig.isBetterThan(bestConfig, config)) {
6098 if (!currentTypeIsOverlay || thisConfig.compare(bestConfig) != 0) {
6104 bestType = thisType;
6105 bestOffset = thisOffset;
6106 bestConfig = thisConfig;
6107 bestPackage = typeSpec->package;
6108 actualTypeIndex = realTypeIndex;
6110 // If no config was specified, any type will do, so skip
6111 if (config == NULL) {
6117 if (bestType == NULL) {
6121 bestOffset += dtohl(bestType->entriesStart);
6123 if (bestOffset > (dtohl(bestType->header.size)-sizeof(ResTable_entry))) {
6124 ALOGW("ResTable_entry at 0x%x is beyond type chunk data 0x%x",
6125 bestOffset, dtohl(bestType->header.size));
6128 if ((bestOffset & 0x3) != 0) {
6129 ALOGW("ResTable_entry at 0x%x is not on an integer boundary", bestOffset);
6133 const ResTable_entry* const entry = reinterpret_cast<const ResTable_entry*>(
6134 reinterpret_cast<const uint8_t*>(bestType) + bestOffset);
6135 if (dtohs(entry->size) < sizeof(*entry)) {
6136 ALOGW("ResTable_entry size 0x%x is too small", dtohs(entry->size));
6140 if (outEntry != NULL) {
6141 outEntry->entry = entry;
6142 outEntry->config = bestConfig;
6143 outEntry->type = bestType;
6144 outEntry->specFlags = specFlags;
6145 outEntry->package = bestPackage;
6146 outEntry->typeStr = StringPoolRef(&bestPackage->typeStrings, actualTypeIndex - bestPackage->typeIdOffset);
6147 outEntry->keyStr = StringPoolRef(&bestPackage->keyStrings, dtohl(entry->key.index));
6152 status_t ResTable::parsePackage(const ResTable_package* const pkg,
6153 const Header* const header, bool appAsLib, bool isSystemAsset)
6155 const uint8_t* base = (const uint8_t*)pkg;
6156 status_t err = validate_chunk(&pkg->header, sizeof(*pkg) - sizeof(pkg->typeIdOffset),
6157 header->dataEnd, "ResTable_package");
6158 if (err != NO_ERROR) {
6159 return (mError=err);
6162 const uint32_t pkgSize = dtohl(pkg->header.size);
6164 if (dtohl(pkg->typeStrings) >= pkgSize) {
6165 ALOGW("ResTable_package type strings at 0x%x are past chunk size 0x%x.",
6166 dtohl(pkg->typeStrings), pkgSize);
6167 return (mError=BAD_TYPE);
6169 if ((dtohl(pkg->typeStrings)&0x3) != 0) {
6170 ALOGW("ResTable_package type strings at 0x%x is not on an integer boundary.",
6171 dtohl(pkg->typeStrings));
6172 return (mError=BAD_TYPE);
6174 if (dtohl(pkg->keyStrings) >= pkgSize) {
6175 ALOGW("ResTable_package key strings at 0x%x are past chunk size 0x%x.",
6176 dtohl(pkg->keyStrings), pkgSize);
6177 return (mError=BAD_TYPE);
6179 if ((dtohl(pkg->keyStrings)&0x3) != 0) {
6180 ALOGW("ResTable_package key strings at 0x%x is not on an integer boundary.",
6181 dtohl(pkg->keyStrings));
6182 return (mError=BAD_TYPE);
6185 uint32_t id = dtohl(pkg->id);
6186 KeyedVector<uint8_t, IdmapEntries> idmapEntries;
6188 if (header->resourceIDMap != NULL) {
6189 uint8_t targetPackageId = 0;
6190 status_t err = parseIdmap(header->resourceIDMap, header->resourceIDMapSize, &targetPackageId, &idmapEntries);
6191 if (err != NO_ERROR) {
6192 ALOGW("Overlay is broken");
6193 return (mError=err);
6195 id = targetPackageId;
6199 LOG_ALWAYS_FATAL("Package id out of range");
6201 } else if (id == 0 || (id == 0x7f && appAsLib) || isSystemAsset) {
6202 // This is a library or a system asset, so assign an ID
6203 id = mNextPackageId++;
6206 PackageGroup* group = NULL;
6207 Package* package = new Package(this, header, pkg);
6208 if (package == NULL) {
6209 return (mError=NO_MEMORY);
6212 err = package->typeStrings.setTo(base+dtohl(pkg->typeStrings),
6213 header->dataEnd-(base+dtohl(pkg->typeStrings)));
6214 if (err != NO_ERROR) {
6217 return (mError=err);
6220 err = package->keyStrings.setTo(base+dtohl(pkg->keyStrings),
6221 header->dataEnd-(base+dtohl(pkg->keyStrings)));
6222 if (err != NO_ERROR) {
6225 return (mError=err);
6228 size_t idx = mPackageMap[id];
6230 idx = mPackageGroups.size() + 1;
6232 char16_t tmpName[sizeof(pkg->name)/sizeof(pkg->name[0])];
6233 strcpy16_dtoh(tmpName, pkg->name, sizeof(pkg->name)/sizeof(pkg->name[0]));
6234 group = new PackageGroup(this, String16(tmpName), id, appAsLib, isSystemAsset);
6235 if (group == NULL) {
6237 return (mError=NO_MEMORY);
6240 err = mPackageGroups.add(group);
6241 if (err < NO_ERROR) {
6242 return (mError=err);
6245 mPackageMap[id] = static_cast<uint8_t>(idx);
6247 // Find all packages that reference this package
6248 size_t N = mPackageGroups.size();
6249 for (size_t i = 0; i < N; i++) {
6250 mPackageGroups[i]->dynamicRefTable.addMapping(
6251 group->name, static_cast<uint8_t>(group->id));
6254 group = mPackageGroups.itemAt(idx - 1);
6255 if (group == NULL) {
6256 return (mError=UNKNOWN_ERROR);
6260 err = group->packages.add(package);
6261 if (err < NO_ERROR) {
6262 return (mError=err);
6265 // Iterate through all chunks.
6266 const ResChunk_header* chunk =
6267 (const ResChunk_header*)(((const uint8_t*)pkg)
6268 + dtohs(pkg->header.headerSize));
6269 const uint8_t* endPos = ((const uint8_t*)pkg) + dtohs(pkg->header.size);
6270 while (((const uint8_t*)chunk) <= (endPos-sizeof(ResChunk_header)) &&
6271 ((const uint8_t*)chunk) <= (endPos-dtohl(chunk->size))) {
6272 if (kDebugTableNoisy) {
6273 ALOGV("PackageChunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n",
6274 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
6275 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)));
6277 const size_t csize = dtohl(chunk->size);
6278 const uint16_t ctype = dtohs(chunk->type);
6279 if (ctype == RES_TABLE_TYPE_SPEC_TYPE) {
6280 const ResTable_typeSpec* typeSpec = (const ResTable_typeSpec*)(chunk);
6281 err = validate_chunk(&typeSpec->header, sizeof(*typeSpec),
6282 endPos, "ResTable_typeSpec");
6283 if (err != NO_ERROR) {
6284 return (mError=err);
6287 const size_t typeSpecSize = dtohl(typeSpec->header.size);
6288 const size_t newEntryCount = dtohl(typeSpec->entryCount);
6290 if (kDebugLoadTableNoisy) {
6291 ALOGI("TypeSpec off %p: type=0x%x, headerSize=0x%x, size=%p\n",
6292 (void*)(base-(const uint8_t*)chunk),
6293 dtohs(typeSpec->header.type),
6294 dtohs(typeSpec->header.headerSize),
6295 (void*)typeSpecSize);
6297 // look for block overrun or int overflow when multiplying by 4
6298 if ((dtohl(typeSpec->entryCount) > (INT32_MAX/sizeof(uint32_t))
6299 || dtohs(typeSpec->header.headerSize)+(sizeof(uint32_t)*newEntryCount)
6301 ALOGW("ResTable_typeSpec entry index to %p extends beyond chunk end %p.",
6302 (void*)(dtohs(typeSpec->header.headerSize) + (sizeof(uint32_t)*newEntryCount)),
6303 (void*)typeSpecSize);
6304 return (mError=BAD_TYPE);
6307 if (typeSpec->id == 0) {
6308 ALOGW("ResTable_type has an id of 0.");
6309 return (mError=BAD_TYPE);
6312 if (newEntryCount > 0) {
6313 uint8_t typeIndex = typeSpec->id - 1;
6314 ssize_t idmapIndex = idmapEntries.indexOfKey(typeSpec->id);
6315 if (idmapIndex >= 0) {
6316 typeIndex = idmapEntries[idmapIndex].targetTypeId() - 1;
6319 TypeList& typeList = group->types.editItemAt(typeIndex);
6320 if (!typeList.isEmpty()) {
6321 const Type* existingType = typeList[0];
6322 if (existingType->entryCount != newEntryCount && idmapIndex < 0) {
6323 ALOGW("ResTable_typeSpec entry count inconsistent: given %d, previously %d",
6324 (int) newEntryCount, (int) existingType->entryCount);
6325 // We should normally abort here, but some legacy apps declare
6326 // resources in the 'android' package (old bug in AAPT).
6330 Type* t = new Type(header, package, newEntryCount);
6331 t->typeSpec = typeSpec;
6332 t->typeSpecFlags = (const uint32_t*)(
6333 ((const uint8_t*)typeSpec) + dtohs(typeSpec->header.headerSize));
6334 if (idmapIndex >= 0) {
6335 t->idmapEntries = idmapEntries[idmapIndex];
6338 group->largestTypeId = max(group->largestTypeId, typeSpec->id);
6340 ALOGV("Skipping empty ResTable_typeSpec for type %d", typeSpec->id);
6343 } else if (ctype == RES_TABLE_TYPE_TYPE) {
6344 const ResTable_type* type = (const ResTable_type*)(chunk);
6345 err = validate_chunk(&type->header, sizeof(*type)-sizeof(ResTable_config)+4,
6346 endPos, "ResTable_type");
6347 if (err != NO_ERROR) {
6348 return (mError=err);
6351 const uint32_t typeSize = dtohl(type->header.size);
6352 const size_t newEntryCount = dtohl(type->entryCount);
6354 if (kDebugLoadTableNoisy) {
6355 printf("Type off %p: type=0x%x, headerSize=0x%x, size=%u\n",
6356 (void*)(base-(const uint8_t*)chunk),
6357 dtohs(type->header.type),
6358 dtohs(type->header.headerSize),
6361 if (dtohs(type->header.headerSize)+(sizeof(uint32_t)*newEntryCount) > typeSize) {
6362 ALOGW("ResTable_type entry index to %p extends beyond chunk end 0x%x.",
6363 (void*)(dtohs(type->header.headerSize) + (sizeof(uint32_t)*newEntryCount)),
6365 return (mError=BAD_TYPE);
6368 if (newEntryCount != 0
6369 && dtohl(type->entriesStart) > (typeSize-sizeof(ResTable_entry))) {
6370 ALOGW("ResTable_type entriesStart at 0x%x extends beyond chunk end 0x%x.",
6371 dtohl(type->entriesStart), typeSize);
6372 return (mError=BAD_TYPE);
6375 if (type->id == 0) {
6376 ALOGW("ResTable_type has an id of 0.");
6377 return (mError=BAD_TYPE);
6380 if (newEntryCount > 0) {
6381 uint8_t typeIndex = type->id - 1;
6382 ssize_t idmapIndex = idmapEntries.indexOfKey(type->id);
6383 if (idmapIndex >= 0) {
6384 typeIndex = idmapEntries[idmapIndex].targetTypeId() - 1;
6387 TypeList& typeList = group->types.editItemAt(typeIndex);
6388 if (typeList.isEmpty()) {
6389 ALOGE("No TypeSpec for type %d", type->id);
6390 return (mError=BAD_TYPE);
6393 Type* t = typeList.editItemAt(typeList.size() - 1);
6394 if (newEntryCount != t->entryCount) {
6395 ALOGE("ResTable_type entry count inconsistent: given %d, previously %d",
6396 (int)newEntryCount, (int)t->entryCount);
6397 return (mError=BAD_TYPE);
6400 if (t->package != package) {
6401 ALOGE("No TypeSpec for type %d", type->id);
6402 return (mError=BAD_TYPE);
6405 t->configs.add(type);
6407 if (kDebugTableGetEntry) {
6408 ResTable_config thisConfig;
6409 thisConfig.copyFromDtoH(type->config);
6410 ALOGI("Adding config to type %d: %s\n", type->id,
6411 thisConfig.toString().string());
6414 ALOGV("Skipping empty ResTable_type for type %d", type->id);
6417 } else if (ctype == RES_TABLE_LIBRARY_TYPE) {
6419 if (group->dynamicRefTable.entries().size() == 0) {
6420 const ResTable_lib_header* lib = (const ResTable_lib_header*) chunk;
6421 status_t err = validate_chunk(&lib->header, sizeof(*lib),
6422 endPos, "ResTable_lib_header");
6423 if (err != NO_ERROR) {
6424 return (mError=err);
6427 err = group->dynamicRefTable.load(lib);
6428 if (err != NO_ERROR) {
6429 return (mError=err);
6432 // Fill in the reference table with the entries we already know about.
6433 size_t N = mPackageGroups.size();
6434 for (size_t i = 0; i < N; i++) {
6435 group->dynamicRefTable.addMapping(mPackageGroups[i]->name, mPackageGroups[i]->id);
6438 ALOGW("Found multiple library tables, ignoring...");
6441 status_t err = validate_chunk(chunk, sizeof(ResChunk_header),
6442 endPos, "ResTable_package:unknown");
6443 if (err != NO_ERROR) {
6444 return (mError=err);
6447 chunk = (const ResChunk_header*)
6448 (((const uint8_t*)chunk) + csize);
6454 DynamicRefTable::DynamicRefTable(uint8_t packageId, bool appAsLib)
6455 : mAssignedPackageId(packageId)
6456 , mAppAsLib(appAsLib)
6458 memset(mLookupTable, 0, sizeof(mLookupTable));
6460 // Reserved package ids
6461 mLookupTable[APP_PACKAGE_ID] = APP_PACKAGE_ID;
6462 mLookupTable[SYS_PACKAGE_ID] = SYS_PACKAGE_ID;
6465 status_t DynamicRefTable::load(const ResTable_lib_header* const header)
6467 const uint32_t entryCount = dtohl(header->count);
6468 const uint32_t sizeOfEntries = sizeof(ResTable_lib_entry) * entryCount;
6469 const uint32_t expectedSize = dtohl(header->header.size) - dtohl(header->header.headerSize);
6470 if (sizeOfEntries > expectedSize) {
6471 ALOGE("ResTable_lib_header size %u is too small to fit %u entries (x %u).",
6472 expectedSize, entryCount, (uint32_t)sizeof(ResTable_lib_entry));
6473 return UNKNOWN_ERROR;
6476 const ResTable_lib_entry* entry = (const ResTable_lib_entry*)(((uint8_t*) header) +
6477 dtohl(header->header.headerSize));
6478 for (uint32_t entryIndex = 0; entryIndex < entryCount; entryIndex++) {
6479 uint32_t packageId = dtohl(entry->packageId);
6480 char16_t tmpName[sizeof(entry->packageName) / sizeof(char16_t)];
6481 strcpy16_dtoh(tmpName, entry->packageName, sizeof(entry->packageName) / sizeof(char16_t));
6482 if (kDebugLibNoisy) {
6483 ALOGV("Found lib entry %s with id %d\n", String8(tmpName).string(),
6484 dtohl(entry->packageId));
6486 if (packageId >= 256) {
6487 ALOGE("Bad package id 0x%08x", packageId);
6488 return UNKNOWN_ERROR;
6490 mEntries.replaceValueFor(String16(tmpName), (uint8_t) packageId);
6496 status_t DynamicRefTable::addMappings(const DynamicRefTable& other) {
6497 if (mAssignedPackageId != other.mAssignedPackageId) {
6498 return UNKNOWN_ERROR;
6501 const size_t entryCount = other.mEntries.size();
6502 for (size_t i = 0; i < entryCount; i++) {
6503 ssize_t index = mEntries.indexOfKey(other.mEntries.keyAt(i));
6505 mEntries.add(other.mEntries.keyAt(i), other.mEntries[i]);
6507 if (other.mEntries[i] != mEntries[index]) {
6508 return UNKNOWN_ERROR;
6513 // Merge the lookup table. No entry can conflict
6514 // (value of 0 means not set).
6515 for (size_t i = 0; i < 256; i++) {
6516 if (mLookupTable[i] != other.mLookupTable[i]) {
6517 if (mLookupTable[i] == 0) {
6518 mLookupTable[i] = other.mLookupTable[i];
6519 } else if (other.mLookupTable[i] != 0) {
6520 return UNKNOWN_ERROR;
6527 status_t DynamicRefTable::addMapping(const String16& packageName, uint8_t packageId)
6529 ssize_t index = mEntries.indexOfKey(packageName);
6531 return UNKNOWN_ERROR;
6533 mLookupTable[mEntries.valueAt(index)] = packageId;
6537 status_t DynamicRefTable::lookupResourceId(uint32_t* resId) const {
6538 uint32_t res = *resId;
6539 size_t packageId = Res_GETPACKAGE(res) + 1;
6541 if (packageId == APP_PACKAGE_ID && !mAppAsLib) {
6542 // No lookup needs to be done, app package IDs are absolute.
6546 if (packageId == 0 || (packageId == APP_PACKAGE_ID && mAppAsLib)) {
6547 // The package ID is 0x00. That means that a shared library is accessing
6548 // its own local resource.
6549 // Or if app resource is loaded as shared library, the resource which has
6550 // app package Id is local resources.
6551 // so we fix up those resources with the calling package ID.
6552 *resId = (0xFFFFFF & (*resId)) | (((uint32_t) mAssignedPackageId) << 24);
6556 // Do a proper lookup.
6557 uint8_t translatedId = mLookupTable[packageId];
6558 if (translatedId == 0) {
6559 ALOGV("DynamicRefTable(0x%02x): No mapping for build-time package ID 0x%02x.",
6560 (uint8_t)mAssignedPackageId, (uint8_t)packageId);
6561 for (size_t i = 0; i < 256; i++) {
6562 if (mLookupTable[i] != 0) {
6563 ALOGV("e[0x%02x] -> 0x%02x", (uint8_t)i, mLookupTable[i]);
6566 return UNKNOWN_ERROR;
6569 *resId = (res & 0x00ffffff) | (((uint32_t) translatedId) << 24);
6573 status_t DynamicRefTable::lookupResourceValue(Res_value* value) const {
6574 uint8_t resolvedType = Res_value::TYPE_REFERENCE;
6575 switch (value->dataType) {
6576 case Res_value::TYPE_ATTRIBUTE:
6577 resolvedType = Res_value::TYPE_ATTRIBUTE;
6579 case Res_value::TYPE_REFERENCE:
6584 // If the package is loaded as shared library, the resource reference
6585 // also need to be fixed.
6587 case Res_value::TYPE_DYNAMIC_ATTRIBUTE:
6588 resolvedType = Res_value::TYPE_ATTRIBUTE;
6590 case Res_value::TYPE_DYNAMIC_REFERENCE:
6596 status_t err = lookupResourceId(&value->data);
6597 if (err != NO_ERROR) {
6601 value->dataType = resolvedType;
6605 struct IdmapTypeMap {
6606 ssize_t overlayTypeId;
6608 Vector<uint32_t> entryMap;
6611 status_t ResTable::createIdmap(const ResTable& overlay,
6612 uint32_t targetCrc, uint32_t overlayCrc,
6613 const char* targetPath, const char* overlayPath,
6614 void** outData, size_t* outSize) const
6616 // see README for details on the format of map
6617 if (mPackageGroups.size() == 0) {
6618 ALOGW("idmap: target package has no package groups, cannot create idmap\n");
6619 return UNKNOWN_ERROR;
6622 if (mPackageGroups[0]->packages.size() == 0) {
6623 ALOGW("idmap: target package has no packages in its first package group, "
6624 "cannot create idmap\n");
6625 return UNKNOWN_ERROR;
6628 KeyedVector<uint8_t, IdmapTypeMap> map;
6630 // overlaid packages are assumed to contain only one package group
6631 const PackageGroup* pg = mPackageGroups[0];
6633 // starting size is header
6634 *outSize = ResTable::IDMAP_HEADER_SIZE_BYTES;
6636 // target package id and number of types in map
6637 *outSize += 2 * sizeof(uint16_t);
6639 // overlay packages are assumed to contain only one package group
6640 const ResTable_package* overlayPackageStruct = overlay.mPackageGroups[0]->packages[0]->package;
6641 char16_t tmpName[sizeof(overlayPackageStruct->name)/sizeof(overlayPackageStruct->name[0])];
6642 strcpy16_dtoh(tmpName, overlayPackageStruct->name, sizeof(overlayPackageStruct->name)/sizeof(overlayPackageStruct->name[0]));
6643 const String16 overlayPackage(tmpName);
6645 for (size_t typeIndex = 0; typeIndex < pg->types.size(); ++typeIndex) {
6646 const TypeList& typeList = pg->types[typeIndex];
6647 if (typeList.isEmpty()) {
6651 const Type* typeConfigs = typeList[0];
6653 IdmapTypeMap typeMap;
6654 typeMap.overlayTypeId = -1;
6655 typeMap.entryOffset = 0;
6657 for (size_t entryIndex = 0; entryIndex < typeConfigs->entryCount; ++entryIndex) {
6658 uint32_t resID = Res_MAKEID(pg->id - 1, typeIndex, entryIndex);
6659 resource_name resName;
6660 if (!this->getResourceName(resID, false, &resName)) {
6661 if (typeMap.entryMap.isEmpty()) {
6662 typeMap.entryOffset++;
6667 const String16 overlayType(resName.type, resName.typeLen);
6668 const String16 overlayName(resName.name, resName.nameLen);
6669 uint32_t overlayResID = overlay.identifierForName(overlayName.string(),
6671 overlayType.string(),
6673 overlayPackage.string(),
6674 overlayPackage.size());
6675 if (overlayResID == 0) {
6676 if (typeMap.entryMap.isEmpty()) {
6677 typeMap.entryOffset++;
6682 if (typeMap.overlayTypeId == -1) {
6683 typeMap.overlayTypeId = Res_GETTYPE(overlayResID) + 1;
6686 if (Res_GETTYPE(overlayResID) + 1 != static_cast<size_t>(typeMap.overlayTypeId)) {
6687 ALOGE("idmap: can't mix type ids in entry map. Resource 0x%08x maps to 0x%08x"
6688 " but entries should map to resources of type %02zx",
6689 resID, overlayResID, typeMap.overlayTypeId);
6693 if (typeMap.entryOffset + typeMap.entryMap.size() < entryIndex) {
6694 // pad with 0xffffffff's (indicating non-existing entries) before adding this entry
6695 size_t index = typeMap.entryMap.size();
6696 size_t numItems = entryIndex - (typeMap.entryOffset + index);
6697 if (typeMap.entryMap.insertAt(0xffffffff, index, numItems) < 0) {
6701 typeMap.entryMap.add(Res_GETENTRY(overlayResID));
6704 if (!typeMap.entryMap.isEmpty()) {
6705 if (map.add(static_cast<uint8_t>(typeIndex), typeMap) < 0) {
6708 *outSize += (4 * sizeof(uint16_t)) + (typeMap.entryMap.size() * sizeof(uint32_t));
6712 if (map.isEmpty()) {
6713 ALOGW("idmap: no resources in overlay package present in base package");
6714 return UNKNOWN_ERROR;
6717 if ((*outData = malloc(*outSize)) == NULL) {
6721 uint32_t* data = (uint32_t*)*outData;
6722 *data++ = htodl(IDMAP_MAGIC);
6723 *data++ = htodl(IDMAP_CURRENT_VERSION);
6724 *data++ = htodl(targetCrc);
6725 *data++ = htodl(overlayCrc);
6726 const char* paths[] = { targetPath, overlayPath };
6727 for (int j = 0; j < 2; ++j) {
6728 char* p = (char*)data;
6729 const char* path = paths[j];
6730 const size_t I = strlen(path);
6732 ALOGV("path exceeds expected 255 characters: %s\n", path);
6733 return UNKNOWN_ERROR;
6735 for (size_t i = 0; i < 256; ++i) {
6736 *p++ = i < I ? path[i] : '\0';
6738 data += 256 / sizeof(uint32_t);
6740 const size_t mapSize = map.size();
6741 uint16_t* typeData = reinterpret_cast<uint16_t*>(data);
6742 *typeData++ = htods(pg->id);
6743 *typeData++ = htods(mapSize);
6744 for (size_t i = 0; i < mapSize; ++i) {
6745 uint8_t targetTypeId = map.keyAt(i);
6746 const IdmapTypeMap& typeMap = map[i];
6747 *typeData++ = htods(targetTypeId + 1);
6748 *typeData++ = htods(typeMap.overlayTypeId);
6749 *typeData++ = htods(typeMap.entryMap.size());
6750 *typeData++ = htods(typeMap.entryOffset);
6752 const size_t entryCount = typeMap.entryMap.size();
6753 uint32_t* entries = reinterpret_cast<uint32_t*>(typeData);
6754 for (size_t j = 0; j < entryCount; j++) {
6755 entries[j] = htodl(typeMap.entryMap[j]);
6757 typeData += entryCount * 2;
6763 bool ResTable::getIdmapInfo(const void* idmap, size_t sizeBytes,
6765 uint32_t* pTargetCrc, uint32_t* pOverlayCrc,
6766 String8* pTargetPath, String8* pOverlayPath)
6768 const uint32_t* map = (const uint32_t*)idmap;
6769 if (!assertIdmapHeader(map, sizeBytes)) {
6773 *pVersion = dtohl(map[1]);
6776 *pTargetCrc = dtohl(map[2]);
6779 *pOverlayCrc = dtohl(map[3]);
6782 pTargetPath->setTo(reinterpret_cast<const char*>(map + 4));
6785 pOverlayPath->setTo(reinterpret_cast<const char*>(map + 4 + 256 / sizeof(uint32_t)));
6791 #define CHAR16_TO_CSTR(c16, len) (String8(String16(c16,len)).string())
6793 #define CHAR16_ARRAY_EQ(constant, var, len) \
6794 ((len == (sizeof(constant)/sizeof(constant[0]))) && (0 == memcmp((var), (constant), (len))))
6796 static void print_complex(uint32_t complex, bool isFraction)
6798 const float MANTISSA_MULT =
6799 1.0f / (1<<Res_value::COMPLEX_MANTISSA_SHIFT);
6800 const float RADIX_MULTS[] = {
6801 1.0f*MANTISSA_MULT, 1.0f/(1<<7)*MANTISSA_MULT,
6802 1.0f/(1<<15)*MANTISSA_MULT, 1.0f/(1<<23)*MANTISSA_MULT
6805 float value = (complex&(Res_value::COMPLEX_MANTISSA_MASK
6806 <<Res_value::COMPLEX_MANTISSA_SHIFT))
6807 * RADIX_MULTS[(complex>>Res_value::COMPLEX_RADIX_SHIFT)
6808 & Res_value::COMPLEX_RADIX_MASK];
6809 printf("%f", value);
6812 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
6813 case Res_value::COMPLEX_UNIT_PX: printf("px"); break;
6814 case Res_value::COMPLEX_UNIT_DIP: printf("dp"); break;
6815 case Res_value::COMPLEX_UNIT_SP: printf("sp"); break;
6816 case Res_value::COMPLEX_UNIT_PT: printf("pt"); break;
6817 case Res_value::COMPLEX_UNIT_IN: printf("in"); break;
6818 case Res_value::COMPLEX_UNIT_MM: printf("mm"); break;
6819 default: printf(" (unknown unit)"); break;
6822 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
6823 case Res_value::COMPLEX_UNIT_FRACTION: printf("%%"); break;
6824 case Res_value::COMPLEX_UNIT_FRACTION_PARENT: printf("%%p"); break;
6825 default: printf(" (unknown unit)"); break;
6830 // Normalize a string for output
6831 String8 ResTable::normalizeForOutput( const char *input )
6837 while (*input != '\0') {
6839 // All interesting characters are in the ASCII zone, so we are making our own lives
6840 // easier by scanning the string one byte at a time.
6862 void ResTable::print_value(const Package* pkg, const Res_value& value) const
6864 if (value.dataType == Res_value::TYPE_NULL) {
6865 if (value.data == Res_value::DATA_NULL_UNDEFINED) {
6867 } else if (value.data == Res_value::DATA_NULL_EMPTY) {
6868 printf("(null empty)\n");
6870 // This should never happen.
6871 printf("(null) 0x%08x\n", value.data);
6873 } else if (value.dataType == Res_value::TYPE_REFERENCE) {
6874 printf("(reference) 0x%08x\n", value.data);
6875 } else if (value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE) {
6876 printf("(dynamic reference) 0x%08x\n", value.data);
6877 } else if (value.dataType == Res_value::TYPE_ATTRIBUTE) {
6878 printf("(attribute) 0x%08x\n", value.data);
6879 } else if (value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE) {
6880 printf("(dynamic attribute) 0x%08x\n", value.data);
6881 } else if (value.dataType == Res_value::TYPE_STRING) {
6883 const char* str8 = pkg->header->values.string8At(
6886 printf("(string8) \"%s\"\n", normalizeForOutput(str8).string());
6888 const char16_t* str16 = pkg->header->values.stringAt(
6890 if (str16 != NULL) {
6891 printf("(string16) \"%s\"\n",
6892 normalizeForOutput(String8(str16, len).string()).string());
6894 printf("(string) null\n");
6897 } else if (value.dataType == Res_value::TYPE_FLOAT) {
6898 printf("(float) %g\n", *(const float*)&value.data);
6899 } else if (value.dataType == Res_value::TYPE_DIMENSION) {
6900 printf("(dimension) ");
6901 print_complex(value.data, false);
6903 } else if (value.dataType == Res_value::TYPE_FRACTION) {
6904 printf("(fraction) ");
6905 print_complex(value.data, true);
6907 } else if (value.dataType >= Res_value::TYPE_FIRST_COLOR_INT
6908 || value.dataType <= Res_value::TYPE_LAST_COLOR_INT) {
6909 printf("(color) #%08x\n", value.data);
6910 } else if (value.dataType == Res_value::TYPE_INT_BOOLEAN) {
6911 printf("(boolean) %s\n", value.data ? "true" : "false");
6912 } else if (value.dataType >= Res_value::TYPE_FIRST_INT
6913 || value.dataType <= Res_value::TYPE_LAST_INT) {
6914 printf("(int) 0x%08x or %d\n", value.data, value.data);
6916 printf("(unknown type) t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)\n",
6917 (int)value.dataType, (int)value.data,
6918 (int)value.size, (int)value.res0);
6922 void ResTable::print(bool inclValues) const
6925 printf("mError=0x%x (%s)\n", mError, strerror(mError));
6927 size_t pgCount = mPackageGroups.size();
6928 printf("Package Groups (%d)\n", (int)pgCount);
6929 for (size_t pgIndex=0; pgIndex<pgCount; pgIndex++) {
6930 const PackageGroup* pg = mPackageGroups[pgIndex];
6931 printf("Package Group %d id=0x%02x packageCount=%d name=%s\n",
6932 (int)pgIndex, pg->id, (int)pg->packages.size(),
6933 String8(pg->name).string());
6935 const KeyedVector<String16, uint8_t>& refEntries = pg->dynamicRefTable.entries();
6936 const size_t refEntryCount = refEntries.size();
6937 if (refEntryCount > 0) {
6938 printf(" DynamicRefTable entryCount=%d:\n", (int) refEntryCount);
6939 for (size_t refIndex = 0; refIndex < refEntryCount; refIndex++) {
6940 printf(" 0x%02x -> %s\n",
6941 refEntries.valueAt(refIndex),
6942 String8(refEntries.keyAt(refIndex)).string());
6947 int packageId = pg->id;
6948 size_t pkgCount = pg->packages.size();
6949 for (size_t pkgIndex=0; pkgIndex<pkgCount; pkgIndex++) {
6950 const Package* pkg = pg->packages[pkgIndex];
6951 // Use a package's real ID, since the ID may have been assigned
6952 // if this package is a shared library.
6953 packageId = pkg->package->id;
6954 char16_t tmpName[sizeof(pkg->package->name)/sizeof(pkg->package->name[0])];
6955 strcpy16_dtoh(tmpName, pkg->package->name, sizeof(pkg->package->name)/sizeof(pkg->package->name[0]));
6956 printf(" Package %d id=0x%02x name=%s\n", (int)pkgIndex,
6957 pkg->package->id, String8(tmpName).string());
6960 for (size_t typeIndex=0; typeIndex < pg->types.size(); typeIndex++) {
6961 const TypeList& typeList = pg->types[typeIndex];
6962 if (typeList.isEmpty()) {
6965 const Type* typeConfigs = typeList[0];
6966 const size_t NTC = typeConfigs->configs.size();
6967 printf(" type %d configCount=%d entryCount=%d\n",
6968 (int)typeIndex, (int)NTC, (int)typeConfigs->entryCount);
6969 if (typeConfigs->typeSpecFlags != NULL) {
6970 for (size_t entryIndex=0; entryIndex<typeConfigs->entryCount; entryIndex++) {
6971 uint32_t resID = (0xff000000 & ((packageId)<<24))
6972 | (0x00ff0000 & ((typeIndex+1)<<16))
6973 | (0x0000ffff & (entryIndex));
6974 // Since we are creating resID without actually
6975 // iterating over them, we have no idea which is a
6976 // dynamic reference. We must check.
6977 if (packageId == 0) {
6978 pg->dynamicRefTable.lookupResourceId(&resID);
6981 resource_name resName;
6982 if (this->getResourceName(resID, true, &resName)) {
6985 if (resName.type8 != NULL) {
6986 type8 = String8(resName.type8, resName.typeLen);
6988 type8 = String8(resName.type, resName.typeLen);
6990 if (resName.name8 != NULL) {
6991 name8 = String8(resName.name8, resName.nameLen);
6993 name8 = String8(resName.name, resName.nameLen);
6995 printf(" spec resource 0x%08x %s:%s/%s: flags=0x%08x\n",
6997 CHAR16_TO_CSTR(resName.package, resName.packageLen),
6998 type8.string(), name8.string(),
6999 dtohl(typeConfigs->typeSpecFlags[entryIndex]));
7001 printf(" INVALID TYPE CONFIG FOR RESOURCE 0x%08x\n", resID);
7005 for (size_t configIndex=0; configIndex<NTC; configIndex++) {
7006 const ResTable_type* type = typeConfigs->configs[configIndex];
7007 if ((((uint64_t)type)&0x3) != 0) {
7008 printf(" NON-INTEGER ResTable_type ADDRESS: %p\n", type);
7012 // Always copy the config, as fields get added and we need to
7013 // set the defaults.
7014 ResTable_config thisConfig;
7015 thisConfig.copyFromDtoH(type->config);
7017 String8 configStr = thisConfig.toString();
7018 printf(" config %s:\n", configStr.size() > 0
7019 ? configStr.string() : "(default)");
7020 size_t entryCount = dtohl(type->entryCount);
7021 uint32_t entriesStart = dtohl(type->entriesStart);
7022 if ((entriesStart&0x3) != 0) {
7023 printf(" NON-INTEGER ResTable_type entriesStart OFFSET: 0x%x\n", entriesStart);
7026 uint32_t typeSize = dtohl(type->header.size);
7027 if ((typeSize&0x3) != 0) {
7028 printf(" NON-INTEGER ResTable_type header.size: 0x%x\n", typeSize);
7031 for (size_t entryIndex=0; entryIndex<entryCount; entryIndex++) {
7032 const uint32_t* const eindex = (const uint32_t*)
7033 (((const uint8_t*)type) + dtohs(type->header.headerSize));
7035 uint32_t thisOffset = dtohl(eindex[entryIndex]);
7036 if (thisOffset == ResTable_type::NO_ENTRY) {
7040 uint32_t resID = (0xff000000 & ((packageId)<<24))
7041 | (0x00ff0000 & ((typeIndex+1)<<16))
7042 | (0x0000ffff & (entryIndex));
7043 if (packageId == 0) {
7044 pg->dynamicRefTable.lookupResourceId(&resID);
7046 resource_name resName;
7047 if (this->getResourceName(resID, true, &resName)) {
7050 if (resName.type8 != NULL) {
7051 type8 = String8(resName.type8, resName.typeLen);
7053 type8 = String8(resName.type, resName.typeLen);
7055 if (resName.name8 != NULL) {
7056 name8 = String8(resName.name8, resName.nameLen);
7058 name8 = String8(resName.name, resName.nameLen);
7060 printf(" resource 0x%08x %s:%s/%s: ", resID,
7061 CHAR16_TO_CSTR(resName.package, resName.packageLen),
7062 type8.string(), name8.string());
7064 printf(" INVALID RESOURCE 0x%08x: ", resID);
7066 if ((thisOffset&0x3) != 0) {
7067 printf("NON-INTEGER OFFSET: 0x%x\n", thisOffset);
7070 if ((thisOffset+sizeof(ResTable_entry)) > typeSize) {
7071 printf("OFFSET OUT OF BOUNDS: 0x%x+0x%x (size is 0x%x)\n",
7072 entriesStart, thisOffset, typeSize);
7076 const ResTable_entry* ent = (const ResTable_entry*)
7077 (((const uint8_t*)type) + entriesStart + thisOffset);
7078 if (((entriesStart + thisOffset)&0x3) != 0) {
7079 printf("NON-INTEGER ResTable_entry OFFSET: 0x%x\n",
7080 (entriesStart + thisOffset));
7084 uintptr_t esize = dtohs(ent->size);
7085 if ((esize&0x3) != 0) {
7086 printf("NON-INTEGER ResTable_entry SIZE: %p\n", (void *)esize);
7089 if ((thisOffset+esize) > typeSize) {
7090 printf("ResTable_entry OUT OF BOUNDS: 0x%x+0x%x+%p (size is 0x%x)\n",
7091 entriesStart, thisOffset, (void *)esize, typeSize);
7095 const Res_value* valuePtr = NULL;
7096 const ResTable_map_entry* bagPtr = NULL;
7098 if ((dtohs(ent->flags)&ResTable_entry::FLAG_COMPLEX) != 0) {
7100 bagPtr = (const ResTable_map_entry*)ent;
7102 valuePtr = (const Res_value*)
7103 (((const uint8_t*)ent) + esize);
7104 value.copyFrom_dtoh(*valuePtr);
7105 printf("t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)",
7106 (int)value.dataType, (int)value.data,
7107 (int)value.size, (int)value.res0);
7110 if ((dtohs(ent->flags)&ResTable_entry::FLAG_PUBLIC) != 0) {
7111 printf(" (PUBLIC)");
7116 if (valuePtr != NULL) {
7118 print_value(typeConfigs->package, value);
7119 } else if (bagPtr != NULL) {
7120 const int N = dtohl(bagPtr->count);
7121 const uint8_t* baseMapPtr = (const uint8_t*)ent;
7122 size_t mapOffset = esize;
7123 const ResTable_map* mapPtr = (ResTable_map*)(baseMapPtr+mapOffset);
7124 const uint32_t parent = dtohl(bagPtr->parent.ident);
7125 uint32_t resolvedParent = parent;
7126 if (Res_GETPACKAGE(resolvedParent) + 1 == 0) {
7127 status_t err = pg->dynamicRefTable.lookupResourceId(&resolvedParent);
7128 if (err != NO_ERROR) {
7132 printf(" Parent=0x%08x(Resolved=0x%08x), Count=%d\n",
7133 parent, resolvedParent, N);
7134 for (int i=0; i<N && mapOffset < (typeSize-sizeof(ResTable_map)); i++) {
7135 printf(" #%i (Key=0x%08x): ",
7136 i, dtohl(mapPtr->name.ident));
7137 value.copyFrom_dtoh(mapPtr->value);
7138 print_value(typeConfigs->package, value);
7139 const size_t size = dtohs(mapPtr->value.size);
7140 mapOffset += size + sizeof(*mapPtr)-sizeof(mapPtr->value);
7141 mapPtr = (ResTable_map*)(baseMapPtr+mapOffset);
7151 } // namespace android