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 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 const bool notDeviceEndian = htods(0xf0) != 0xf0;
462 if (copyData || notDeviceEndian) {
463 mOwnedData = malloc(size);
464 if (mOwnedData == NULL) {
465 return (mError=NO_MEMORY);
467 memcpy(mOwnedData, data, size);
471 mHeader = (const ResStringPool_header*)data;
473 if (notDeviceEndian) {
474 ResStringPool_header* h = const_cast<ResStringPool_header*>(mHeader);
475 h->header.headerSize = dtohs(mHeader->header.headerSize);
476 h->header.type = dtohs(mHeader->header.type);
477 h->header.size = dtohl(mHeader->header.size);
478 h->stringCount = dtohl(mHeader->stringCount);
479 h->styleCount = dtohl(mHeader->styleCount);
480 h->flags = dtohl(mHeader->flags);
481 h->stringsStart = dtohl(mHeader->stringsStart);
482 h->stylesStart = dtohl(mHeader->stylesStart);
485 if (mHeader->header.headerSize > mHeader->header.size
486 || mHeader->header.size > size) {
487 ALOGW("Bad string block: header size %d or total size %d is larger than data size %d\n",
488 (int)mHeader->header.headerSize, (int)mHeader->header.size, (int)size);
489 return (mError=BAD_TYPE);
491 mSize = mHeader->header.size;
492 mEntries = (const uint32_t*)
493 (((const uint8_t*)data)+mHeader->header.headerSize);
495 if (mHeader->stringCount > 0) {
496 if ((mHeader->stringCount*sizeof(uint32_t) < mHeader->stringCount) // uint32 overflow?
497 || (mHeader->header.headerSize+(mHeader->stringCount*sizeof(uint32_t)))
499 ALOGW("Bad string block: entry of %d items extends past data size %d\n",
500 (int)(mHeader->header.headerSize+(mHeader->stringCount*sizeof(uint32_t))),
502 return (mError=BAD_TYPE);
506 if (mHeader->flags&ResStringPool_header::UTF8_FLAG) {
507 charSize = sizeof(uint8_t);
509 charSize = sizeof(uint16_t);
512 // There should be at least space for the smallest string
513 // (2 bytes length, null terminator).
514 if (mHeader->stringsStart >= (mSize - sizeof(uint16_t))) {
515 ALOGW("Bad string block: string pool starts at %d, after total size %d\n",
516 (int)mHeader->stringsStart, (int)mHeader->header.size);
517 return (mError=BAD_TYPE);
520 mStrings = (const void*)
521 (((const uint8_t*)data) + mHeader->stringsStart);
523 if (mHeader->styleCount == 0) {
524 mStringPoolSize = (mSize - mHeader->stringsStart) / charSize;
526 // check invariant: styles starts before end of data
527 if (mHeader->stylesStart >= (mSize - sizeof(uint16_t))) {
528 ALOGW("Bad style block: style block starts at %d past data size of %d\n",
529 (int)mHeader->stylesStart, (int)mHeader->header.size);
530 return (mError=BAD_TYPE);
532 // check invariant: styles follow the strings
533 if (mHeader->stylesStart <= mHeader->stringsStart) {
534 ALOGW("Bad style block: style block starts at %d, before strings at %d\n",
535 (int)mHeader->stylesStart, (int)mHeader->stringsStart);
536 return (mError=BAD_TYPE);
539 (mHeader->stylesStart-mHeader->stringsStart)/charSize;
542 // check invariant: stringCount > 0 requires a string pool to exist
543 if (mStringPoolSize == 0) {
544 ALOGW("Bad string block: stringCount is %d but pool size is 0\n", (int)mHeader->stringCount);
545 return (mError=BAD_TYPE);
548 if (notDeviceEndian) {
550 uint32_t* e = const_cast<uint32_t*>(mEntries);
551 for (i=0; i<mHeader->stringCount; i++) {
552 e[i] = dtohl(mEntries[i]);
554 if (!(mHeader->flags&ResStringPool_header::UTF8_FLAG)) {
555 const uint16_t* strings = (const uint16_t*)mStrings;
556 uint16_t* s = const_cast<uint16_t*>(strings);
557 for (i=0; i<mStringPoolSize; i++) {
558 s[i] = dtohs(strings[i]);
563 if ((mHeader->flags&ResStringPool_header::UTF8_FLAG &&
564 ((uint8_t*)mStrings)[mStringPoolSize-1] != 0) ||
565 (!(mHeader->flags&ResStringPool_header::UTF8_FLAG) &&
566 ((uint16_t*)mStrings)[mStringPoolSize-1] != 0)) {
567 ALOGW("Bad string block: last string is not 0-terminated\n");
568 return (mError=BAD_TYPE);
575 if (mHeader->styleCount > 0) {
576 mEntryStyles = mEntries + mHeader->stringCount;
577 // invariant: integer overflow in calculating mEntryStyles
578 if (mEntryStyles < mEntries) {
579 ALOGW("Bad string block: integer overflow finding styles\n");
580 return (mError=BAD_TYPE);
583 if (((const uint8_t*)mEntryStyles-(const uint8_t*)mHeader) > (int)size) {
584 ALOGW("Bad string block: entry of %d styles extends past data size %d\n",
585 (int)((const uint8_t*)mEntryStyles-(const uint8_t*)mHeader),
587 return (mError=BAD_TYPE);
589 mStyles = (const uint32_t*)
590 (((const uint8_t*)data)+mHeader->stylesStart);
591 if (mHeader->stylesStart >= mHeader->header.size) {
592 ALOGW("Bad string block: style pool starts %d, after total size %d\n",
593 (int)mHeader->stylesStart, (int)mHeader->header.size);
594 return (mError=BAD_TYPE);
597 (mHeader->header.size-mHeader->stylesStart)/sizeof(uint32_t);
599 if (notDeviceEndian) {
601 uint32_t* e = const_cast<uint32_t*>(mEntryStyles);
602 for (i=0; i<mHeader->styleCount; i++) {
603 e[i] = dtohl(mEntryStyles[i]);
605 uint32_t* s = const_cast<uint32_t*>(mStyles);
606 for (i=0; i<mStylePoolSize; i++) {
607 s[i] = dtohl(mStyles[i]);
611 const ResStringPool_span endSpan = {
612 { htodl(ResStringPool_span::END) },
613 htodl(ResStringPool_span::END), htodl(ResStringPool_span::END)
615 if (memcmp(&mStyles[mStylePoolSize-(sizeof(endSpan)/sizeof(uint32_t))],
616 &endSpan, sizeof(endSpan)) != 0) {
617 ALOGW("Bad string block: last style is not 0xFFFFFFFF-terminated\n");
618 return (mError=BAD_TYPE);
626 return (mError=NO_ERROR);
629 status_t ResStringPool::getError() const
634 void ResStringPool::uninit()
637 if (mHeader != NULL && mCache != NULL) {
638 for (size_t x = 0; x < mHeader->stringCount; x++) {
639 if (mCache[x] != NULL) {
654 * Strings in UTF-16 format have length indicated by a length encoded in the
655 * stored data. It is either 1 or 2 characters of length data. This allows a
656 * maximum length of 0x7FFFFFF (2147483647 bytes), but if you're storing that
657 * much data in a string, you're abusing them.
659 * If the high bit is set, then there are two characters or 4 bytes of length
660 * data encoded. In that case, drop the high bit of the first character and
661 * add it together with the next character.
664 decodeLength(const uint16_t** str)
667 if ((len & 0x8000) != 0) {
669 len = ((len & 0x7FFF) << 16) | **str;
676 * Strings in UTF-8 format have length indicated by a length encoded in the
677 * stored data. It is either 1 or 2 characters of length data. This allows a
678 * maximum length of 0x7FFF (32767 bytes), but you should consider storing
679 * text in another way if you're using that much data in a single string.
681 * If the high bit is set, then there are two characters or 2 bytes of length
682 * data encoded. In that case, drop the high bit of the first character and
683 * add it together with the next character.
686 decodeLength(const uint8_t** str)
689 if ((len & 0x80) != 0) {
691 len = ((len & 0x7F) << 8) | **str;
697 const char16_t* ResStringPool::stringAt(size_t idx, size_t* u16len) const
699 if (mError == NO_ERROR && idx < mHeader->stringCount) {
700 const bool isUTF8 = (mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0;
701 const uint32_t off = mEntries[idx]/(isUTF8?sizeof(uint8_t):sizeof(uint16_t));
702 if (off < (mStringPoolSize-1)) {
704 const uint16_t* strings = (uint16_t*)mStrings;
705 const uint16_t* str = strings+off;
707 *u16len = decodeLength(&str);
708 if ((uint32_t)(str+*u16len-strings) < mStringPoolSize) {
709 // Reject malformed (non null-terminated) strings
710 if (str[*u16len] != 0x0000) {
711 ALOGW("Bad string block: string #%d is not null-terminated",
715 return reinterpret_cast<const char16_t*>(str);
717 ALOGW("Bad string block: string #%d extends to %d, past end at %d\n",
718 (int)idx, (int)(str+*u16len-strings), (int)mStringPoolSize);
721 const uint8_t* strings = (uint8_t*)mStrings;
722 const uint8_t* u8str = strings+off;
724 *u16len = decodeLength(&u8str);
725 size_t u8len = decodeLength(&u8str);
727 // encLen must be less than 0x7FFF due to encoding.
728 if ((uint32_t)(u8str+u8len-strings) < mStringPoolSize) {
729 AutoMutex lock(mDecodeLock);
731 if (mCache == NULL) {
733 if (kDebugStringPoolNoisy) {
734 ALOGI("CREATING STRING CACHE OF %zu bytes",
735 mHeader->stringCount*sizeof(char16_t**));
738 // We do not want to be in this case when actually running Android.
739 ALOGW("CREATING STRING CACHE OF %zu bytes",
740 static_cast<size_t>(mHeader->stringCount*sizeof(char16_t**)));
742 mCache = (char16_t**)calloc(mHeader->stringCount, sizeof(char16_t*));
743 if (mCache == NULL) {
744 ALOGW("No memory trying to allocate decode cache table of %d bytes\n",
745 (int)(mHeader->stringCount*sizeof(char16_t**)));
750 if (mCache[idx] != NULL) {
754 ssize_t actualLen = utf8_to_utf16_length(u8str, u8len);
755 if (actualLen < 0 || (size_t)actualLen != *u16len) {
756 ALOGW("Bad string block: string #%lld decoded length is not correct "
758 (long long)idx, (long long)actualLen, (long long)*u16len);
762 // Reject malformed (non null-terminated) strings
763 if (u8str[u8len] != 0x00) {
764 ALOGW("Bad string block: string #%d is not null-terminated",
769 char16_t *u16str = (char16_t *)calloc(*u16len+1, sizeof(char16_t));
771 ALOGW("No memory when trying to allocate decode cache for string #%d\n",
776 if (kDebugStringPoolNoisy) {
777 ALOGI("Caching UTF8 string: %s", u8str);
779 utf8_to_utf16(u8str, u8len, u16str, *u16len + 1);
780 mCache[idx] = u16str;
783 ALOGW("Bad string block: string #%lld extends to %lld, past end at %lld\n",
784 (long long)idx, (long long)(u8str+u8len-strings),
785 (long long)mStringPoolSize);
789 ALOGW("Bad string block: string #%d entry is at %d, past end at %d\n",
790 (int)idx, (int)(off*sizeof(uint16_t)),
791 (int)(mStringPoolSize*sizeof(uint16_t)));
797 const char* ResStringPool::string8At(size_t idx, size_t* outLen) const
799 if (mError == NO_ERROR && idx < mHeader->stringCount) {
800 if ((mHeader->flags&ResStringPool_header::UTF8_FLAG) == 0) {
803 const uint32_t off = mEntries[idx]/sizeof(char);
804 if (off < (mStringPoolSize-1)) {
805 const uint8_t* strings = (uint8_t*)mStrings;
806 const uint8_t* str = strings+off;
808 // Decode the UTF-16 length. This is not used if we're not
809 // converting to UTF-16 from UTF-8.
812 const size_t encLen = decodeLength(&str);
815 if ((uint32_t)(str+encLen-strings) < mStringPoolSize) {
816 return (const char*)str;
818 ALOGW("Bad string block: string #%d extends to %d, past end at %d\n",
819 (int)idx, (int)(str+encLen-strings), (int)mStringPoolSize);
822 ALOGW("Bad string block: string #%d entry is at %d, past end at %d\n",
823 (int)idx, (int)(off*sizeof(uint16_t)),
824 (int)(mStringPoolSize*sizeof(uint16_t)));
830 const String8 ResStringPool::string8ObjectAt(size_t idx) const
833 const char *str = string8At(idx, &len);
835 return String8(str, len);
838 const char16_t *str16 = stringAt(idx, &len);
840 return String8(str16, len);
845 const ResStringPool_span* ResStringPool::styleAt(const ResStringPool_ref& ref) const
847 return styleAt(ref.index);
850 const ResStringPool_span* ResStringPool::styleAt(size_t idx) const
852 if (mError == NO_ERROR && idx < mHeader->styleCount) {
853 const uint32_t off = (mEntryStyles[idx]/sizeof(uint32_t));
854 if (off < mStylePoolSize) {
855 return (const ResStringPool_span*)(mStyles+off);
857 ALOGW("Bad string block: style #%d entry is at %d, past end at %d\n",
858 (int)idx, (int)(off*sizeof(uint32_t)),
859 (int)(mStylePoolSize*sizeof(uint32_t)));
865 ssize_t ResStringPool::indexOfString(const char16_t* str, size_t strLen) const
867 if (mError != NO_ERROR) {
873 if ((mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0) {
874 if (kDebugStringPoolNoisy) {
875 ALOGI("indexOfString UTF-8: %s", String8(str, strLen).string());
878 // The string pool contains UTF 8 strings; we don't want to cause
879 // temporary UTF-16 strings to be created as we search.
880 if (mHeader->flags&ResStringPool_header::SORTED_FLAG) {
881 // Do a binary search for the string... this is a little tricky,
882 // because the strings are sorted with strzcmp16(). So to match
883 // the ordering, we need to convert strings in the pool to UTF-16.
884 // But we don't want to hit the cache, so instead we will have a
885 // local temporary allocation for the conversions.
886 size_t convBufferLen = strLen + 4;
887 char16_t* convBuffer = (char16_t*)calloc(convBufferLen, sizeof(char16_t));
889 ssize_t h = mHeader->stringCount-1;
894 const uint8_t* s = (const uint8_t*)string8At(mid, &len);
897 char16_t* end = utf8_to_utf16(s, len, convBuffer, convBufferLen);
898 c = strzcmp16(convBuffer, end-convBuffer, str, strLen);
902 if (kDebugStringPoolNoisy) {
903 ALOGI("Looking at %s, cmp=%d, l/mid/h=%d/%d/%d\n",
904 (const char*)s, c, (int)l, (int)mid, (int)h);
907 if (kDebugStringPoolNoisy) {
920 // It is unusual to get the ID from an unsorted string block...
921 // most often this happens because we want to get IDs for style
922 // span tags; since those always appear at the end of the string
923 // block, start searching at the back.
924 String8 str8(str, strLen);
925 const size_t str8Len = str8.size();
926 for (int i=mHeader->stringCount-1; i>=0; i--) {
927 const char* s = string8At(i, &len);
928 if (kDebugStringPoolNoisy) {
929 ALOGI("Looking at %s, i=%d\n", String8(s).string(), i);
931 if (s && str8Len == len && memcmp(s, str8.string(), str8Len) == 0) {
932 if (kDebugStringPoolNoisy) {
941 if (kDebugStringPoolNoisy) {
942 ALOGI("indexOfString UTF-16: %s", String8(str, strLen).string());
945 if (mHeader->flags&ResStringPool_header::SORTED_FLAG) {
946 // Do a binary search for the string...
948 ssize_t h = mHeader->stringCount-1;
953 const char16_t* s = stringAt(mid, &len);
954 int c = s ? strzcmp16(s, len, str, strLen) : -1;
955 if (kDebugStringPoolNoisy) {
956 ALOGI("Looking at %s, cmp=%d, l/mid/h=%d/%d/%d\n",
957 String8(s).string(), c, (int)l, (int)mid, (int)h);
960 if (kDebugStringPoolNoisy) {
971 // It is unusual to get the ID from an unsorted string block...
972 // most often this happens because we want to get IDs for style
973 // span tags; since those always appear at the end of the string
974 // block, start searching at the back.
975 for (int i=mHeader->stringCount-1; i>=0; i--) {
976 const char16_t* s = stringAt(i, &len);
977 if (kDebugStringPoolNoisy) {
978 ALOGI("Looking at %s, i=%d\n", String8(s).string(), i);
980 if (s && strLen == len && strzcmp16(s, len, str, strLen) == 0) {
981 if (kDebugStringPoolNoisy) {
990 return NAME_NOT_FOUND;
993 size_t ResStringPool::size() const
995 return (mError == NO_ERROR) ? mHeader->stringCount : 0;
998 size_t ResStringPool::styleCount() const
1000 return (mError == NO_ERROR) ? mHeader->styleCount : 0;
1003 size_t ResStringPool::bytes() const
1005 return (mError == NO_ERROR) ? mHeader->header.size : 0;
1008 bool ResStringPool::isSorted() const
1010 return (mHeader->flags&ResStringPool_header::SORTED_FLAG)!=0;
1013 bool ResStringPool::isUTF8() const
1015 return (mHeader->flags&ResStringPool_header::UTF8_FLAG)!=0;
1018 // --------------------------------------------------------------------
1019 // --------------------------------------------------------------------
1020 // --------------------------------------------------------------------
1022 ResXMLParser::ResXMLParser(const ResXMLTree& tree)
1023 : mTree(tree), mEventCode(BAD_DOCUMENT)
1027 void ResXMLParser::restart()
1030 mEventCode = mTree.mError == NO_ERROR ? START_DOCUMENT : BAD_DOCUMENT;
1032 const ResStringPool& ResXMLParser::getStrings() const
1034 return mTree.mStrings;
1037 ResXMLParser::event_code_t ResXMLParser::getEventType() const
1042 ResXMLParser::event_code_t ResXMLParser::next()
1044 if (mEventCode == START_DOCUMENT) {
1045 mCurNode = mTree.mRootNode;
1046 mCurExt = mTree.mRootExt;
1047 return (mEventCode=mTree.mRootCode);
1048 } else if (mEventCode >= FIRST_CHUNK_CODE) {
1054 int32_t ResXMLParser::getCommentID() const
1056 return mCurNode != NULL ? dtohl(mCurNode->comment.index) : -1;
1059 const char16_t* ResXMLParser::getComment(size_t* outLen) const
1061 int32_t id = getCommentID();
1062 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1065 uint32_t ResXMLParser::getLineNumber() const
1067 return mCurNode != NULL ? dtohl(mCurNode->lineNumber) : -1;
1070 int32_t ResXMLParser::getTextID() const
1072 if (mEventCode == TEXT) {
1073 return dtohl(((const ResXMLTree_cdataExt*)mCurExt)->data.index);
1078 const char16_t* ResXMLParser::getText(size_t* outLen) const
1080 int32_t id = getTextID();
1081 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1084 ssize_t ResXMLParser::getTextValue(Res_value* outValue) const
1086 if (mEventCode == TEXT) {
1087 outValue->copyFrom_dtoh(((const ResXMLTree_cdataExt*)mCurExt)->typedData);
1088 return sizeof(Res_value);
1093 int32_t ResXMLParser::getNamespacePrefixID() const
1095 if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) {
1096 return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->prefix.index);
1101 const char16_t* ResXMLParser::getNamespacePrefix(size_t* outLen) const
1103 int32_t id = getNamespacePrefixID();
1104 //printf("prefix=%d event=%p\n", id, mEventCode);
1105 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1108 int32_t ResXMLParser::getNamespaceUriID() const
1110 if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) {
1111 return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->uri.index);
1116 const char16_t* ResXMLParser::getNamespaceUri(size_t* outLen) const
1118 int32_t id = getNamespaceUriID();
1119 //printf("uri=%d event=%p\n", id, mEventCode);
1120 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1123 int32_t ResXMLParser::getElementNamespaceID() const
1125 if (mEventCode == START_TAG) {
1126 return dtohl(((const ResXMLTree_attrExt*)mCurExt)->ns.index);
1128 if (mEventCode == END_TAG) {
1129 return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->ns.index);
1134 const char16_t* ResXMLParser::getElementNamespace(size_t* outLen) const
1136 int32_t id = getElementNamespaceID();
1137 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1140 int32_t ResXMLParser::getElementNameID() const
1142 if (mEventCode == START_TAG) {
1143 return dtohl(((const ResXMLTree_attrExt*)mCurExt)->name.index);
1145 if (mEventCode == END_TAG) {
1146 return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->name.index);
1151 const char16_t* ResXMLParser::getElementName(size_t* outLen) const
1153 int32_t id = getElementNameID();
1154 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1157 size_t ResXMLParser::getAttributeCount() const
1159 if (mEventCode == START_TAG) {
1160 return dtohs(((const ResXMLTree_attrExt*)mCurExt)->attributeCount);
1165 int32_t ResXMLParser::getAttributeNamespaceID(size_t idx) const
1167 if (mEventCode == START_TAG) {
1168 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1169 if (idx < dtohs(tag->attributeCount)) {
1170 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1171 (((const uint8_t*)tag)
1172 + dtohs(tag->attributeStart)
1173 + (dtohs(tag->attributeSize)*idx));
1174 return dtohl(attr->ns.index);
1180 const char16_t* ResXMLParser::getAttributeNamespace(size_t idx, size_t* outLen) const
1182 int32_t id = getAttributeNamespaceID(idx);
1183 //printf("attribute namespace=%d idx=%d event=%p\n", id, idx, mEventCode);
1184 if (kDebugXMLNoisy) {
1185 printf("getAttributeNamespace 0x%zx=0x%x\n", idx, id);
1187 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1190 const char* ResXMLParser::getAttributeNamespace8(size_t idx, size_t* outLen) const
1192 int32_t id = getAttributeNamespaceID(idx);
1193 //printf("attribute namespace=%d idx=%d event=%p\n", id, idx, mEventCode);
1194 if (kDebugXMLNoisy) {
1195 printf("getAttributeNamespace 0x%zx=0x%x\n", idx, id);
1197 return id >= 0 ? mTree.mStrings.string8At(id, outLen) : NULL;
1200 int32_t ResXMLParser::getAttributeNameID(size_t idx) const
1202 if (mEventCode == START_TAG) {
1203 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1204 if (idx < dtohs(tag->attributeCount)) {
1205 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1206 (((const uint8_t*)tag)
1207 + dtohs(tag->attributeStart)
1208 + (dtohs(tag->attributeSize)*idx));
1209 return dtohl(attr->name.index);
1215 const char16_t* ResXMLParser::getAttributeName(size_t idx, size_t* outLen) const
1217 int32_t id = getAttributeNameID(idx);
1218 //printf("attribute name=%d idx=%d event=%p\n", id, idx, mEventCode);
1219 if (kDebugXMLNoisy) {
1220 printf("getAttributeName 0x%zx=0x%x\n", idx, id);
1222 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1225 const char* ResXMLParser::getAttributeName8(size_t idx, size_t* outLen) const
1227 int32_t id = getAttributeNameID(idx);
1228 //printf("attribute name=%d idx=%d event=%p\n", id, idx, mEventCode);
1229 if (kDebugXMLNoisy) {
1230 printf("getAttributeName 0x%zx=0x%x\n", idx, id);
1232 return id >= 0 ? mTree.mStrings.string8At(id, outLen) : NULL;
1235 uint32_t ResXMLParser::getAttributeNameResID(size_t idx) const
1237 int32_t id = getAttributeNameID(idx);
1238 if (id >= 0 && (size_t)id < mTree.mNumResIds) {
1239 uint32_t resId = dtohl(mTree.mResIds[id]);
1240 if (mTree.mDynamicRefTable != NULL) {
1241 mTree.mDynamicRefTable->lookupResourceId(&resId);
1248 int32_t ResXMLParser::getAttributeValueStringID(size_t idx) const
1250 if (mEventCode == START_TAG) {
1251 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1252 if (idx < dtohs(tag->attributeCount)) {
1253 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1254 (((const uint8_t*)tag)
1255 + dtohs(tag->attributeStart)
1256 + (dtohs(tag->attributeSize)*idx));
1257 return dtohl(attr->rawValue.index);
1263 const char16_t* ResXMLParser::getAttributeStringValue(size_t idx, size_t* outLen) const
1265 int32_t id = getAttributeValueStringID(idx);
1266 if (kDebugXMLNoisy) {
1267 printf("getAttributeValue 0x%zx=0x%x\n", idx, id);
1269 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1272 int32_t ResXMLParser::getAttributeDataType(size_t idx) const
1274 if (mEventCode == START_TAG) {
1275 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1276 if (idx < dtohs(tag->attributeCount)) {
1277 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1278 (((const uint8_t*)tag)
1279 + dtohs(tag->attributeStart)
1280 + (dtohs(tag->attributeSize)*idx));
1281 uint8_t type = attr->typedValue.dataType;
1282 if (type != Res_value::TYPE_DYNAMIC_REFERENCE) {
1286 // This is a dynamic reference. We adjust those references
1287 // to regular references at this level, so lie to the caller.
1288 return Res_value::TYPE_REFERENCE;
1291 return Res_value::TYPE_NULL;
1294 int32_t ResXMLParser::getAttributeData(size_t idx) const
1296 if (mEventCode == START_TAG) {
1297 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1298 if (idx < dtohs(tag->attributeCount)) {
1299 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1300 (((const uint8_t*)tag)
1301 + dtohs(tag->attributeStart)
1302 + (dtohs(tag->attributeSize)*idx));
1303 if (attr->typedValue.dataType != Res_value::TYPE_DYNAMIC_REFERENCE ||
1304 mTree.mDynamicRefTable == NULL) {
1305 return dtohl(attr->typedValue.data);
1308 uint32_t data = dtohl(attr->typedValue.data);
1309 if (mTree.mDynamicRefTable->lookupResourceId(&data) == NO_ERROR) {
1317 ssize_t ResXMLParser::getAttributeValue(size_t idx, Res_value* outValue) const
1319 if (mEventCode == START_TAG) {
1320 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1321 if (idx < dtohs(tag->attributeCount)) {
1322 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1323 (((const uint8_t*)tag)
1324 + dtohs(tag->attributeStart)
1325 + (dtohs(tag->attributeSize)*idx));
1326 outValue->copyFrom_dtoh(attr->typedValue);
1327 if (mTree.mDynamicRefTable != NULL &&
1328 mTree.mDynamicRefTable->lookupResourceValue(outValue) != NO_ERROR) {
1331 return sizeof(Res_value);
1337 ssize_t ResXMLParser::indexOfAttribute(const char* ns, const char* attr) const
1339 String16 nsStr(ns != NULL ? ns : "");
1340 String16 attrStr(attr);
1341 return indexOfAttribute(ns ? nsStr.string() : NULL, ns ? nsStr.size() : 0,
1342 attrStr.string(), attrStr.size());
1345 ssize_t ResXMLParser::indexOfAttribute(const char16_t* ns, size_t nsLen,
1346 const char16_t* attr, size_t attrLen) const
1348 if (mEventCode == START_TAG) {
1350 return NAME_NOT_FOUND;
1352 const size_t N = getAttributeCount();
1353 if (mTree.mStrings.isUTF8()) {
1356 ns8 = String8(ns, nsLen);
1358 attr8 = String8(attr, attrLen);
1359 if (kDebugStringPoolNoisy) {
1360 ALOGI("indexOfAttribute UTF8 %s (%zu) / %s (%zu)", ns8.string(), nsLen,
1361 attr8.string(), attrLen);
1363 for (size_t i=0; i<N; i++) {
1364 size_t curNsLen = 0, curAttrLen = 0;
1365 const char* curNs = getAttributeNamespace8(i, &curNsLen);
1366 const char* curAttr = getAttributeName8(i, &curAttrLen);
1367 if (kDebugStringPoolNoisy) {
1368 ALOGI(" curNs=%s (%zu), curAttr=%s (%zu)", curNs, curNsLen, curAttr, curAttrLen);
1370 if (curAttr != NULL && curNsLen == nsLen && curAttrLen == attrLen
1371 && memcmp(attr8.string(), curAttr, attrLen) == 0) {
1373 if (curNs == NULL) {
1374 if (kDebugStringPoolNoisy) {
1379 } else if (curNs != NULL) {
1380 //printf(" --> ns=%s, curNs=%s\n",
1381 // String8(ns).string(), String8(curNs).string());
1382 if (memcmp(ns8.string(), curNs, nsLen) == 0) {
1383 if (kDebugStringPoolNoisy) {
1392 if (kDebugStringPoolNoisy) {
1393 ALOGI("indexOfAttribute UTF16 %s (%zu) / %s (%zu)",
1394 String8(ns, nsLen).string(), nsLen,
1395 String8(attr, attrLen).string(), attrLen);
1397 for (size_t i=0; i<N; i++) {
1398 size_t curNsLen = 0, curAttrLen = 0;
1399 const char16_t* curNs = getAttributeNamespace(i, &curNsLen);
1400 const char16_t* curAttr = getAttributeName(i, &curAttrLen);
1401 if (kDebugStringPoolNoisy) {
1402 ALOGI(" curNs=%s (%zu), curAttr=%s (%zu)",
1403 String8(curNs, curNsLen).string(), curNsLen,
1404 String8(curAttr, curAttrLen).string(), curAttrLen);
1406 if (curAttr != NULL && curNsLen == nsLen && curAttrLen == attrLen
1407 && (memcmp(attr, curAttr, attrLen*sizeof(char16_t)) == 0)) {
1409 if (curNs == NULL) {
1410 if (kDebugStringPoolNoisy) {
1415 } else if (curNs != NULL) {
1416 //printf(" --> ns=%s, curNs=%s\n",
1417 // String8(ns).string(), String8(curNs).string());
1418 if (memcmp(ns, curNs, nsLen*sizeof(char16_t)) == 0) {
1419 if (kDebugStringPoolNoisy) {
1430 return NAME_NOT_FOUND;
1433 ssize_t ResXMLParser::indexOfID() const
1435 if (mEventCode == START_TAG) {
1436 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->idIndex);
1437 if (idx > 0) return (idx-1);
1439 return NAME_NOT_FOUND;
1442 ssize_t ResXMLParser::indexOfClass() const
1444 if (mEventCode == START_TAG) {
1445 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->classIndex);
1446 if (idx > 0) return (idx-1);
1448 return NAME_NOT_FOUND;
1451 ssize_t ResXMLParser::indexOfStyle() const
1453 if (mEventCode == START_TAG) {
1454 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->styleIndex);
1455 if (idx > 0) return (idx-1);
1457 return NAME_NOT_FOUND;
1460 ResXMLParser::event_code_t ResXMLParser::nextNode()
1462 if (mEventCode < 0) {
1467 const ResXMLTree_node* next = (const ResXMLTree_node*)
1468 (((const uint8_t*)mCurNode) + dtohl(mCurNode->header.size));
1469 if (kDebugXMLNoisy) {
1470 ALOGI("Next node: prev=%p, next=%p\n", mCurNode, next);
1473 if (((const uint8_t*)next) >= mTree.mDataEnd) {
1475 return (mEventCode=END_DOCUMENT);
1478 if (mTree.validateNode(next) != NO_ERROR) {
1480 return (mEventCode=BAD_DOCUMENT);
1484 const uint16_t headerSize = dtohs(next->header.headerSize);
1485 const uint32_t totalSize = dtohl(next->header.size);
1486 mCurExt = ((const uint8_t*)next) + headerSize;
1487 size_t minExtSize = 0;
1488 event_code_t eventCode = (event_code_t)dtohs(next->header.type);
1489 switch ((mEventCode=eventCode)) {
1490 case RES_XML_START_NAMESPACE_TYPE:
1491 case RES_XML_END_NAMESPACE_TYPE:
1492 minExtSize = sizeof(ResXMLTree_namespaceExt);
1494 case RES_XML_START_ELEMENT_TYPE:
1495 minExtSize = sizeof(ResXMLTree_attrExt);
1497 case RES_XML_END_ELEMENT_TYPE:
1498 minExtSize = sizeof(ResXMLTree_endElementExt);
1500 case RES_XML_CDATA_TYPE:
1501 minExtSize = sizeof(ResXMLTree_cdataExt);
1504 ALOGW("Unknown XML block: header type %d in node at %d\n",
1505 (int)dtohs(next->header.type),
1506 (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)));
1510 if ((totalSize-headerSize) < minExtSize) {
1511 ALOGW("Bad XML block: header type 0x%x in node at 0x%x has size %d, need %d\n",
1512 (int)dtohs(next->header.type),
1513 (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)),
1514 (int)(totalSize-headerSize), (int)minExtSize);
1515 return (mEventCode=BAD_DOCUMENT);
1518 //printf("CurNode=%p, CurExt=%p, headerSize=%d, minExtSize=%d\n",
1519 // mCurNode, mCurExt, headerSize, minExtSize);
1525 void ResXMLParser::getPosition(ResXMLParser::ResXMLPosition* pos) const
1527 pos->eventCode = mEventCode;
1528 pos->curNode = mCurNode;
1529 pos->curExt = mCurExt;
1532 void ResXMLParser::setPosition(const ResXMLParser::ResXMLPosition& pos)
1534 mEventCode = pos.eventCode;
1535 mCurNode = pos.curNode;
1536 mCurExt = pos.curExt;
1539 // --------------------------------------------------------------------
1541 static volatile int32_t gCount = 0;
1543 ResXMLTree::ResXMLTree(const DynamicRefTable* dynamicRefTable)
1544 : ResXMLParser(*this)
1545 , mDynamicRefTable(dynamicRefTable)
1546 , mError(NO_INIT), mOwnedData(NULL)
1548 if (kDebugResXMLTree) {
1549 ALOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1);
1554 ResXMLTree::ResXMLTree()
1555 : ResXMLParser(*this)
1556 , mDynamicRefTable(NULL)
1557 , mError(NO_INIT), mOwnedData(NULL)
1559 if (kDebugResXMLTree) {
1560 ALOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1);
1565 ResXMLTree::~ResXMLTree()
1567 if (kDebugResXMLTree) {
1568 ALOGI("Destroying ResXMLTree in %p #%d\n", this, android_atomic_dec(&gCount)-1);
1573 status_t ResXMLTree::setTo(const void* data, size_t size, bool copyData)
1576 mEventCode = START_DOCUMENT;
1578 if (!data || !size) {
1579 return (mError=BAD_TYPE);
1583 mOwnedData = malloc(size);
1584 if (mOwnedData == NULL) {
1585 return (mError=NO_MEMORY);
1587 memcpy(mOwnedData, data, size);
1591 mHeader = (const ResXMLTree_header*)data;
1592 mSize = dtohl(mHeader->header.size);
1593 if (dtohs(mHeader->header.headerSize) > mSize || mSize > size) {
1594 ALOGW("Bad XML block: header size %d or total size %d is larger than data size %d\n",
1595 (int)dtohs(mHeader->header.headerSize),
1596 (int)dtohl(mHeader->header.size), (int)size);
1601 mDataEnd = ((const uint8_t*)mHeader) + mSize;
1608 // First look for a couple interesting chunks: the string block
1609 // and first XML node.
1610 const ResChunk_header* chunk =
1611 (const ResChunk_header*)(((const uint8_t*)mHeader) + dtohs(mHeader->header.headerSize));
1612 const ResChunk_header* lastChunk = chunk;
1613 while (((const uint8_t*)chunk) < (mDataEnd-sizeof(ResChunk_header)) &&
1614 ((const uint8_t*)chunk) < (mDataEnd-dtohl(chunk->size))) {
1615 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), mDataEnd, "XML");
1616 if (err != NO_ERROR) {
1620 const uint16_t type = dtohs(chunk->type);
1621 const size_t size = dtohl(chunk->size);
1622 if (kDebugXMLNoisy) {
1623 printf("Scanning @ %p: type=0x%x, size=0x%zx\n",
1624 (void*)(((uintptr_t)chunk)-((uintptr_t)mHeader)), type, size);
1626 if (type == RES_STRING_POOL_TYPE) {
1627 mStrings.setTo(chunk, size);
1628 } else if (type == RES_XML_RESOURCE_MAP_TYPE) {
1629 mResIds = (const uint32_t*)
1630 (((const uint8_t*)chunk)+dtohs(chunk->headerSize));
1631 mNumResIds = (dtohl(chunk->size)-dtohs(chunk->headerSize))/sizeof(uint32_t);
1632 } else if (type >= RES_XML_FIRST_CHUNK_TYPE
1633 && type <= RES_XML_LAST_CHUNK_TYPE) {
1634 if (validateNode((const ResXMLTree_node*)chunk) != NO_ERROR) {
1638 mCurNode = (const ResXMLTree_node*)lastChunk;
1639 if (nextNode() == BAD_DOCUMENT) {
1643 mRootNode = mCurNode;
1645 mRootCode = mEventCode;
1648 if (kDebugXMLNoisy) {
1649 printf("Skipping unknown chunk!\n");
1653 chunk = (const ResChunk_header*)
1654 (((const uint8_t*)chunk) + size);
1657 if (mRootNode == NULL) {
1658 ALOGW("Bad XML block: no root element node found\n");
1663 mError = mStrings.getError();
1670 status_t ResXMLTree::getError() const
1675 void ResXMLTree::uninit()
1686 status_t ResXMLTree::validateNode(const ResXMLTree_node* node) const
1688 const uint16_t eventCode = dtohs(node->header.type);
1690 status_t err = validate_chunk(
1691 &node->header, sizeof(ResXMLTree_node),
1692 mDataEnd, "ResXMLTree_node");
1694 if (err >= NO_ERROR) {
1695 // Only perform additional validation on START nodes
1696 if (eventCode != RES_XML_START_ELEMENT_TYPE) {
1700 const uint16_t headerSize = dtohs(node->header.headerSize);
1701 const uint32_t size = dtohl(node->header.size);
1702 const ResXMLTree_attrExt* attrExt = (const ResXMLTree_attrExt*)
1703 (((const uint8_t*)node) + headerSize);
1704 // check for sensical values pulled out of the stream so far...
1705 if ((size >= headerSize + sizeof(ResXMLTree_attrExt))
1706 && ((void*)attrExt > (void*)node)) {
1707 const size_t attrSize = ((size_t)dtohs(attrExt->attributeSize))
1708 * dtohs(attrExt->attributeCount);
1709 if ((dtohs(attrExt->attributeStart)+attrSize) <= (size-headerSize)) {
1712 ALOGW("Bad XML block: node attributes use 0x%x bytes, only have 0x%x bytes\n",
1713 (unsigned int)(dtohs(attrExt->attributeStart)+attrSize),
1714 (unsigned int)(size-headerSize));
1717 ALOGW("Bad XML start block: node header size 0x%x, size 0x%x\n",
1718 (unsigned int)headerSize, (unsigned int)size);
1726 const bool isStart = dtohs(node->header.type) == RES_XML_START_ELEMENT_TYPE;
1728 const uint16_t headerSize = dtohs(node->header.headerSize);
1729 const uint32_t size = dtohl(node->header.size);
1731 if (headerSize >= (isStart ? sizeof(ResXMLTree_attrNode) : sizeof(ResXMLTree_node))) {
1732 if (size >= headerSize) {
1733 if (((const uint8_t*)node) <= (mDataEnd-size)) {
1737 if ((((size_t)dtohs(node->attributeSize))*dtohs(node->attributeCount))
1738 <= (size-headerSize)) {
1741 ALOGW("Bad XML block: node attributes use 0x%x bytes, only have 0x%x bytes\n",
1742 ((int)dtohs(node->attributeSize))*dtohs(node->attributeCount),
1743 (int)(size-headerSize));
1746 ALOGW("Bad XML block: node at 0x%x extends beyond data end 0x%x\n",
1747 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)), (int)mSize);
1750 ALOGW("Bad XML block: node at 0x%x header size 0x%x smaller than total size 0x%x\n",
1751 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)),
1752 (int)headerSize, (int)size);
1755 ALOGW("Bad XML block: node at 0x%x header size 0x%x too small\n",
1756 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)),
1762 // --------------------------------------------------------------------
1763 // --------------------------------------------------------------------
1764 // --------------------------------------------------------------------
1766 void ResTable_config::copyFromDeviceNoSwap(const ResTable_config& o) {
1767 const size_t size = dtohl(o.size);
1768 if (size >= sizeof(ResTable_config)) {
1771 memcpy(this, &o, size);
1772 memset(((uint8_t*)this)+size, 0, sizeof(ResTable_config)-size);
1776 /* static */ size_t unpackLanguageOrRegion(const char in[2], const char base,
1779 // The high bit is "1", which means this is a packed three letter
1782 // The smallest 5 bits of the second char are the first alphabet.
1783 const uint8_t first = in[1] & 0x1f;
1784 // The last three bits of the second char and the first two bits
1785 // of the first char are the second alphabet.
1786 const uint8_t second = ((in[1] & 0xe0) >> 5) + ((in[0] & 0x03) << 3);
1787 // Bits 3 to 7 (inclusive) of the first char are the third alphabet.
1788 const uint8_t third = (in[0] & 0x7c) >> 2;
1790 out[0] = first + base;
1791 out[1] = second + base;
1792 out[2] = third + base;
1800 memset(out + 2, 0, 2);
1808 /* static */ void packLanguageOrRegion(const char* in, const char base,
1810 if (in[2] == 0 || in[2] == '-') {
1814 uint8_t first = (in[0] - base) & 0x007f;
1815 uint8_t second = (in[1] - base) & 0x007f;
1816 uint8_t third = (in[2] - base) & 0x007f;
1818 out[0] = (0x80 | (third << 2) | (second >> 3));
1819 out[1] = ((second << 5) | first);
1824 void ResTable_config::packLanguage(const char* language) {
1825 packLanguageOrRegion(language, 'a', this->language);
1828 void ResTable_config::packRegion(const char* region) {
1829 packLanguageOrRegion(region, '0', this->country);
1832 size_t ResTable_config::unpackLanguage(char language[4]) const {
1833 return unpackLanguageOrRegion(this->language, 'a', language);
1836 size_t ResTable_config::unpackRegion(char region[4]) const {
1837 return unpackLanguageOrRegion(this->country, '0', region);
1841 void ResTable_config::copyFromDtoH(const ResTable_config& o) {
1842 copyFromDeviceNoSwap(o);
1843 size = sizeof(ResTable_config);
1846 density = dtohs(density);
1847 screenWidth = dtohs(screenWidth);
1848 screenHeight = dtohs(screenHeight);
1849 sdkVersion = dtohs(sdkVersion);
1850 minorVersion = dtohs(minorVersion);
1851 smallestScreenWidthDp = dtohs(smallestScreenWidthDp);
1852 screenWidthDp = dtohs(screenWidthDp);
1853 screenHeightDp = dtohs(screenHeightDp);
1856 void ResTable_config::swapHtoD() {
1860 density = htods(density);
1861 screenWidth = htods(screenWidth);
1862 screenHeight = htods(screenHeight);
1863 sdkVersion = htods(sdkVersion);
1864 minorVersion = htods(minorVersion);
1865 smallestScreenWidthDp = htods(smallestScreenWidthDp);
1866 screenWidthDp = htods(screenWidthDp);
1867 screenHeightDp = htods(screenHeightDp);
1870 /* static */ inline int compareLocales(const ResTable_config &l, const ResTable_config &r) {
1871 if (l.locale != r.locale) {
1872 // NOTE: This is the old behaviour with respect to comparison orders.
1873 // The diff value here doesn't make much sense (given our bit packing scheme)
1874 // but it's stable, and that's all we need.
1875 return l.locale - r.locale;
1878 // The language & region are equal, so compare the scripts and variants.
1879 const char emptyScript[sizeof(l.localeScript)] = {'\0', '\0', '\0', '\0'};
1880 const char *lScript = l.localeScriptWasComputed ? emptyScript : l.localeScript;
1881 const char *rScript = r.localeScriptWasComputed ? emptyScript : r.localeScript;
1882 int script = memcmp(lScript, rScript, sizeof(l.localeScript));
1887 // The language, region and script are equal, so compare variants.
1889 // This should happen very infrequently (if at all.)
1890 return memcmp(l.localeVariant, r.localeVariant, sizeof(l.localeVariant));
1893 int ResTable_config::compare(const ResTable_config& o) const {
1894 int32_t diff = (int32_t)(imsi - o.imsi);
1895 if (diff != 0) return diff;
1896 diff = compareLocales(*this, o);
1897 if (diff != 0) return diff;
1898 diff = (int32_t)(screenType - o.screenType);
1899 if (diff != 0) return diff;
1900 diff = (int32_t)(input - o.input);
1901 if (diff != 0) return diff;
1902 diff = (int32_t)(screenSize - o.screenSize);
1903 if (diff != 0) return diff;
1904 diff = (int32_t)(version - o.version);
1905 if (diff != 0) return diff;
1906 diff = (int32_t)(screenLayout - o.screenLayout);
1907 if (diff != 0) return diff;
1908 diff = (int32_t)(screenLayout2 - o.screenLayout2);
1909 if (diff != 0) return diff;
1910 diff = (int32_t)(colorMode - o.colorMode);
1911 if (diff != 0) return diff;
1912 diff = (int32_t)(uiMode - o.uiMode);
1913 if (diff != 0) return diff;
1914 diff = (int32_t)(smallestScreenWidthDp - o.smallestScreenWidthDp);
1915 if (diff != 0) return diff;
1916 diff = (int32_t)(screenSizeDp - o.screenSizeDp);
1920 int ResTable_config::compareLogical(const ResTable_config& o) const {
1922 return mcc < o.mcc ? -1 : 1;
1925 return mnc < o.mnc ? -1 : 1;
1928 int diff = compareLocales(*this, o);
1936 if ((screenLayout & MASK_LAYOUTDIR) != (o.screenLayout & MASK_LAYOUTDIR)) {
1937 return (screenLayout & MASK_LAYOUTDIR) < (o.screenLayout & MASK_LAYOUTDIR) ? -1 : 1;
1939 if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
1940 return smallestScreenWidthDp < o.smallestScreenWidthDp ? -1 : 1;
1942 if (screenWidthDp != o.screenWidthDp) {
1943 return screenWidthDp < o.screenWidthDp ? -1 : 1;
1945 if (screenHeightDp != o.screenHeightDp) {
1946 return screenHeightDp < o.screenHeightDp ? -1 : 1;
1948 if (screenWidth != o.screenWidth) {
1949 return screenWidth < o.screenWidth ? -1 : 1;
1951 if (screenHeight != o.screenHeight) {
1952 return screenHeight < o.screenHeight ? -1 : 1;
1954 if (density != o.density) {
1955 return density < o.density ? -1 : 1;
1957 if (orientation != o.orientation) {
1958 return orientation < o.orientation ? -1 : 1;
1960 if (touchscreen != o.touchscreen) {
1961 return touchscreen < o.touchscreen ? -1 : 1;
1963 if (input != o.input) {
1964 return input < o.input ? -1 : 1;
1966 if (screenLayout != o.screenLayout) {
1967 return screenLayout < o.screenLayout ? -1 : 1;
1969 if (screenLayout2 != o.screenLayout2) {
1970 return screenLayout2 < o.screenLayout2 ? -1 : 1;
1972 if (colorMode != o.colorMode) {
1973 return colorMode < o.colorMode ? -1 : 1;
1975 if (uiMode != o.uiMode) {
1976 return uiMode < o.uiMode ? -1 : 1;
1978 if (version != o.version) {
1979 return version < o.version ? -1 : 1;
1984 int ResTable_config::diff(const ResTable_config& o) const {
1986 if (mcc != o.mcc) diffs |= CONFIG_MCC;
1987 if (mnc != o.mnc) diffs |= CONFIG_MNC;
1988 if (orientation != o.orientation) diffs |= CONFIG_ORIENTATION;
1989 if (density != o.density) diffs |= CONFIG_DENSITY;
1990 if (touchscreen != o.touchscreen) diffs |= CONFIG_TOUCHSCREEN;
1991 if (((inputFlags^o.inputFlags)&(MASK_KEYSHIDDEN|MASK_NAVHIDDEN)) != 0)
1992 diffs |= CONFIG_KEYBOARD_HIDDEN;
1993 if (keyboard != o.keyboard) diffs |= CONFIG_KEYBOARD;
1994 if (navigation != o.navigation) diffs |= CONFIG_NAVIGATION;
1995 if (screenSize != o.screenSize) diffs |= CONFIG_SCREEN_SIZE;
1996 if (version != o.version) diffs |= CONFIG_VERSION;
1997 if ((screenLayout & MASK_LAYOUTDIR) != (o.screenLayout & MASK_LAYOUTDIR)) diffs |= CONFIG_LAYOUTDIR;
1998 if ((screenLayout & ~MASK_LAYOUTDIR) != (o.screenLayout & ~MASK_LAYOUTDIR)) diffs |= CONFIG_SCREEN_LAYOUT;
1999 if ((screenLayout2 & MASK_SCREENROUND) != (o.screenLayout2 & MASK_SCREENROUND)) diffs |= CONFIG_SCREEN_ROUND;
2000 if ((colorMode & MASK_WIDE_COLOR_GAMUT) != (o.colorMode & MASK_WIDE_COLOR_GAMUT)) diffs |= CONFIG_COLOR_MODE;
2001 if ((colorMode & MASK_HDR) != (o.colorMode & MASK_HDR)) diffs |= CONFIG_COLOR_MODE;
2002 if (uiMode != o.uiMode) diffs |= CONFIG_UI_MODE;
2003 if (smallestScreenWidthDp != o.smallestScreenWidthDp) diffs |= CONFIG_SMALLEST_SCREEN_SIZE;
2004 if (screenSizeDp != o.screenSizeDp) diffs |= CONFIG_SCREEN_SIZE;
2006 const int diff = compareLocales(*this, o);
2007 if (diff) diffs |= CONFIG_LOCALE;
2012 int ResTable_config::isLocaleMoreSpecificThan(const ResTable_config& o) const {
2013 if (locale || o.locale) {
2014 if (language[0] != o.language[0]) {
2015 if (!language[0]) return -1;
2016 if (!o.language[0]) return 1;
2019 if (country[0] != o.country[0]) {
2020 if (!country[0]) return -1;
2021 if (!o.country[0]) return 1;
2025 // There isn't a well specified "importance" order between variants and
2026 // scripts. We can't easily tell whether, say "en-Latn-US" is more or less
2027 // specific than "en-US-POSIX".
2029 // We therefore arbitrarily decide to give priority to variants over
2030 // scripts since it seems more useful to do so. We will consider
2031 // "en-US-POSIX" to be more specific than "en-Latn-US".
2033 const int score = ((localeScript[0] != '\0' && !localeScriptWasComputed) ? 1 : 0) +
2034 ((localeVariant[0] != '\0') ? 2 : 0);
2036 const int oScore = (o.localeScript[0] != '\0' && !o.localeScriptWasComputed ? 1 : 0) +
2037 ((o.localeVariant[0] != '\0') ? 2 : 0);
2039 return score - oScore;
2042 bool ResTable_config::isMoreSpecificThan(const ResTable_config& o) const {
2043 // The order of the following tests defines the importance of one
2044 // configuration parameter over another. Those tests first are more
2045 // important, trumping any values in those following them.
2046 if (imsi || o.imsi) {
2048 if (!mcc) return false;
2049 if (!o.mcc) return true;
2053 if (!mnc) return false;
2054 if (!o.mnc) return true;
2058 if (locale || o.locale) {
2059 const int diff = isLocaleMoreSpecificThan(o);
2069 if (screenLayout || o.screenLayout) {
2070 if (((screenLayout^o.screenLayout) & MASK_LAYOUTDIR) != 0) {
2071 if (!(screenLayout & MASK_LAYOUTDIR)) return false;
2072 if (!(o.screenLayout & MASK_LAYOUTDIR)) return true;
2076 if (smallestScreenWidthDp || o.smallestScreenWidthDp) {
2077 if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
2078 if (!smallestScreenWidthDp) return false;
2079 if (!o.smallestScreenWidthDp) return true;
2083 if (screenSizeDp || o.screenSizeDp) {
2084 if (screenWidthDp != o.screenWidthDp) {
2085 if (!screenWidthDp) return false;
2086 if (!o.screenWidthDp) return true;
2089 if (screenHeightDp != o.screenHeightDp) {
2090 if (!screenHeightDp) return false;
2091 if (!o.screenHeightDp) return true;
2095 if (screenLayout || o.screenLayout) {
2096 if (((screenLayout^o.screenLayout) & MASK_SCREENSIZE) != 0) {
2097 if (!(screenLayout & MASK_SCREENSIZE)) return false;
2098 if (!(o.screenLayout & MASK_SCREENSIZE)) return true;
2100 if (((screenLayout^o.screenLayout) & MASK_SCREENLONG) != 0) {
2101 if (!(screenLayout & MASK_SCREENLONG)) return false;
2102 if (!(o.screenLayout & MASK_SCREENLONG)) return true;
2106 if (screenLayout2 || o.screenLayout2) {
2107 if (((screenLayout2^o.screenLayout2) & MASK_SCREENROUND) != 0) {
2108 if (!(screenLayout2 & MASK_SCREENROUND)) return false;
2109 if (!(o.screenLayout2 & MASK_SCREENROUND)) return true;
2113 if (colorMode || o.colorMode) {
2114 if (((colorMode^o.colorMode) & MASK_HDR) != 0) {
2115 if (!(colorMode & MASK_HDR)) return false;
2116 if (!(o.colorMode & MASK_HDR)) return true;
2118 if (((colorMode^o.colorMode) & MASK_WIDE_COLOR_GAMUT) != 0) {
2119 if (!(colorMode & MASK_WIDE_COLOR_GAMUT)) return false;
2120 if (!(o.colorMode & MASK_WIDE_COLOR_GAMUT)) return true;
2124 if (orientation != o.orientation) {
2125 if (!orientation) return false;
2126 if (!o.orientation) return true;
2129 if (uiMode || o.uiMode) {
2130 if (((uiMode^o.uiMode) & MASK_UI_MODE_TYPE) != 0) {
2131 if (!(uiMode & MASK_UI_MODE_TYPE)) return false;
2132 if (!(o.uiMode & MASK_UI_MODE_TYPE)) return true;
2134 if (((uiMode^o.uiMode) & MASK_UI_MODE_NIGHT) != 0) {
2135 if (!(uiMode & MASK_UI_MODE_NIGHT)) return false;
2136 if (!(o.uiMode & MASK_UI_MODE_NIGHT)) return true;
2140 // density is never 'more specific'
2141 // as the default just equals 160
2143 if (touchscreen != o.touchscreen) {
2144 if (!touchscreen) return false;
2145 if (!o.touchscreen) return true;
2148 if (input || o.input) {
2149 if (((inputFlags^o.inputFlags) & MASK_KEYSHIDDEN) != 0) {
2150 if (!(inputFlags & MASK_KEYSHIDDEN)) return false;
2151 if (!(o.inputFlags & MASK_KEYSHIDDEN)) return true;
2154 if (((inputFlags^o.inputFlags) & MASK_NAVHIDDEN) != 0) {
2155 if (!(inputFlags & MASK_NAVHIDDEN)) return false;
2156 if (!(o.inputFlags & MASK_NAVHIDDEN)) return true;
2159 if (keyboard != o.keyboard) {
2160 if (!keyboard) return false;
2161 if (!o.keyboard) return true;
2164 if (navigation != o.navigation) {
2165 if (!navigation) return false;
2166 if (!o.navigation) return true;
2170 if (screenSize || o.screenSize) {
2171 if (screenWidth != o.screenWidth) {
2172 if (!screenWidth) return false;
2173 if (!o.screenWidth) return true;
2176 if (screenHeight != o.screenHeight) {
2177 if (!screenHeight) return false;
2178 if (!o.screenHeight) return true;
2182 if (version || o.version) {
2183 if (sdkVersion != o.sdkVersion) {
2184 if (!sdkVersion) return false;
2185 if (!o.sdkVersion) return true;
2188 if (minorVersion != o.minorVersion) {
2189 if (!minorVersion) return false;
2190 if (!o.minorVersion) return true;
2196 // Codes for specially handled languages and regions
2197 static const char kEnglish[2] = {'e', 'n'}; // packed version of "en"
2198 static const char kUnitedStates[2] = {'U', 'S'}; // packed version of "US"
2199 static const char kFilipino[2] = {'\xAD', '\x05'}; // packed version of "fil"
2200 static const char kTagalog[2] = {'t', 'l'}; // packed version of "tl"
2202 // Checks if two language or region codes are identical
2203 inline bool areIdentical(const char code1[2], const char code2[2]) {
2204 return code1[0] == code2[0] && code1[1] == code2[1];
2207 inline bool langsAreEquivalent(const char lang1[2], const char lang2[2]) {
2208 return areIdentical(lang1, lang2) ||
2209 (areIdentical(lang1, kTagalog) && areIdentical(lang2, kFilipino)) ||
2210 (areIdentical(lang1, kFilipino) && areIdentical(lang2, kTagalog));
2213 bool ResTable_config::isLocaleBetterThan(const ResTable_config& o,
2214 const ResTable_config* requested) const {
2215 if (requested->locale == 0) {
2216 // The request doesn't have a locale, so no resource is better
2221 if (locale == 0 && o.locale == 0) {
2222 // The locale part of both resources is empty, so none is better
2227 // Non-matching locales have been filtered out, so both resources
2228 // match the requested locale.
2230 // Because of the locale-related checks in match() and the checks, we know
2232 // 1) The resource languages are either empty or match the request;
2234 // 2) If the request's script is known, the resource scripts are either
2235 // unknown or match the request.
2237 if (!langsAreEquivalent(language, o.language)) {
2238 // The languages of the two resources are not equivalent. If we are
2239 // here, we can only assume that the two resources matched the request
2240 // because one doesn't have a language and the other has a matching
2243 // We consider the one that has the language specified a better match.
2245 // The exception is that we consider no-language resources a better match
2246 // for US English and similar locales than locales that are a descendant
2247 // of Internatinal English (en-001), since no-language resources are
2248 // where the US English resource have traditionally lived for most apps.
2249 if (areIdentical(requested->language, kEnglish)) {
2250 if (areIdentical(requested->country, kUnitedStates)) {
2251 // For US English itself, we consider a no-locale resource a
2252 // better match if the other resource has a country other than
2254 if (language[0] != '\0') {
2255 return country[0] == '\0' || areIdentical(country, kUnitedStates);
2257 return !(o.country[0] == '\0' || areIdentical(o.country, kUnitedStates));
2259 } else if (localeDataIsCloseToUsEnglish(requested->country)) {
2260 if (language[0] != '\0') {
2261 return localeDataIsCloseToUsEnglish(country);
2263 return !localeDataIsCloseToUsEnglish(o.country);
2267 return (language[0] != '\0');
2270 // If we are here, both the resources have an equivalent non-empty language
2273 // Because the languages are equivalent, computeScript() always returns a
2274 // non-empty script for languages it knows about, and we have passed the
2275 // script checks in match(), the scripts are either all unknown or are all
2276 // the same. So we can't gain anything by checking the scripts. We need to
2277 // check the region and variant.
2279 // See if any of the regions is better than the other.
2280 const int region_comparison = localeDataCompareRegions(
2282 requested->language, requested->localeScript, requested->country);
2283 if (region_comparison != 0) {
2284 return (region_comparison > 0);
2287 // The regions are the same. Try the variant.
2288 const bool localeMatches = strncmp(
2289 localeVariant, requested->localeVariant, sizeof(localeVariant)) == 0;
2290 const bool otherMatches = strncmp(
2291 o.localeVariant, requested->localeVariant, sizeof(localeVariant)) == 0;
2292 if (localeMatches != otherMatches) {
2293 return localeMatches;
2296 // Finally, the languages, although equivalent, may still be different
2297 // (like for Tagalog and Filipino). Identical is better than just
2299 if (areIdentical(language, requested->language)
2300 && !areIdentical(o.language, requested->language)) {
2307 bool ResTable_config::isBetterThan(const ResTable_config& o,
2308 const ResTable_config* requested) const {
2310 if (imsi || o.imsi) {
2311 if ((mcc != o.mcc) && requested->mcc) {
2315 if ((mnc != o.mnc) && requested->mnc) {
2320 if (isLocaleBetterThan(o, requested)) {
2324 if (screenLayout || o.screenLayout) {
2325 if (((screenLayout^o.screenLayout) & MASK_LAYOUTDIR) != 0
2326 && (requested->screenLayout & MASK_LAYOUTDIR)) {
2327 int myLayoutDir = screenLayout & MASK_LAYOUTDIR;
2328 int oLayoutDir = o.screenLayout & MASK_LAYOUTDIR;
2329 return (myLayoutDir > oLayoutDir);
2333 if (smallestScreenWidthDp || o.smallestScreenWidthDp) {
2334 // The configuration closest to the actual size is best.
2335 // We assume that larger configs have already been filtered
2336 // out at this point. That means we just want the largest one.
2337 if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
2338 return smallestScreenWidthDp > o.smallestScreenWidthDp;
2342 if (screenSizeDp || o.screenSizeDp) {
2343 // "Better" is based on the sum of the difference between both
2344 // width and height from the requested dimensions. We are
2345 // assuming the invalid configs (with smaller dimens) have
2346 // already been filtered. Note that if a particular dimension
2347 // is unspecified, we will end up with a large value (the
2348 // difference between 0 and the requested dimension), which is
2349 // good since we will prefer a config that has specified a
2351 int myDelta = 0, otherDelta = 0;
2352 if (requested->screenWidthDp) {
2353 myDelta += requested->screenWidthDp - screenWidthDp;
2354 otherDelta += requested->screenWidthDp - o.screenWidthDp;
2356 if (requested->screenHeightDp) {
2357 myDelta += requested->screenHeightDp - screenHeightDp;
2358 otherDelta += requested->screenHeightDp - o.screenHeightDp;
2360 if (kDebugTableSuperNoisy) {
2361 ALOGI("Comparing this %dx%d to other %dx%d in %dx%d: myDelta=%d otherDelta=%d",
2362 screenWidthDp, screenHeightDp, o.screenWidthDp, o.screenHeightDp,
2363 requested->screenWidthDp, requested->screenHeightDp, myDelta, otherDelta);
2365 if (myDelta != otherDelta) {
2366 return myDelta < otherDelta;
2370 if (screenLayout || o.screenLayout) {
2371 if (((screenLayout^o.screenLayout) & MASK_SCREENSIZE) != 0
2372 && (requested->screenLayout & MASK_SCREENSIZE)) {
2373 // A little backwards compatibility here: undefined is
2374 // considered equivalent to normal. But only if the
2375 // requested size is at least normal; otherwise, small
2376 // is better than the default.
2377 int mySL = (screenLayout & MASK_SCREENSIZE);
2378 int oSL = (o.screenLayout & MASK_SCREENSIZE);
2379 int fixedMySL = mySL;
2381 if ((requested->screenLayout & MASK_SCREENSIZE) >= SCREENSIZE_NORMAL) {
2382 if (fixedMySL == 0) fixedMySL = SCREENSIZE_NORMAL;
2383 if (fixedOSL == 0) fixedOSL = SCREENSIZE_NORMAL;
2385 // For screen size, the best match is the one that is
2386 // closest to the requested screen size, but not over
2387 // (the not over part is dealt with in match() below).
2388 if (fixedMySL == fixedOSL) {
2389 // If the two are the same, but 'this' is actually
2390 // undefined, then the other is really a better match.
2391 if (mySL == 0) return false;
2394 if (fixedMySL != fixedOSL) {
2395 return fixedMySL > fixedOSL;
2398 if (((screenLayout^o.screenLayout) & MASK_SCREENLONG) != 0
2399 && (requested->screenLayout & MASK_SCREENLONG)) {
2400 return (screenLayout & MASK_SCREENLONG);
2404 if (screenLayout2 || o.screenLayout2) {
2405 if (((screenLayout2^o.screenLayout2) & MASK_SCREENROUND) != 0 &&
2406 (requested->screenLayout2 & MASK_SCREENROUND)) {
2407 return screenLayout2 & MASK_SCREENROUND;
2411 if (colorMode || o.colorMode) {
2412 if (((colorMode^o.colorMode) & MASK_WIDE_COLOR_GAMUT) != 0 &&
2413 (requested->colorMode & MASK_WIDE_COLOR_GAMUT)) {
2414 return colorMode & MASK_WIDE_COLOR_GAMUT;
2416 if (((colorMode^o.colorMode) & MASK_HDR) != 0 &&
2417 (requested->colorMode & MASK_HDR)) {
2418 return colorMode & MASK_HDR;
2422 if ((orientation != o.orientation) && requested->orientation) {
2423 return (orientation);
2426 if (uiMode || o.uiMode) {
2427 if (((uiMode^o.uiMode) & MASK_UI_MODE_TYPE) != 0
2428 && (requested->uiMode & MASK_UI_MODE_TYPE)) {
2429 return (uiMode & MASK_UI_MODE_TYPE);
2431 if (((uiMode^o.uiMode) & MASK_UI_MODE_NIGHT) != 0
2432 && (requested->uiMode & MASK_UI_MODE_NIGHT)) {
2433 return (uiMode & MASK_UI_MODE_NIGHT);
2437 if (screenType || o.screenType) {
2438 if (density != o.density) {
2439 // Use the system default density (DENSITY_MEDIUM, 160dpi) if none specified.
2440 const int thisDensity = density ? density : int(ResTable_config::DENSITY_MEDIUM);
2441 const int otherDensity = o.density ? o.density : int(ResTable_config::DENSITY_MEDIUM);
2443 // We always prefer DENSITY_ANY over scaling a density bucket.
2444 if (thisDensity == ResTable_config::DENSITY_ANY) {
2446 } else if (otherDensity == ResTable_config::DENSITY_ANY) {
2450 int requestedDensity = requested->density;
2451 if (requested->density == 0 ||
2452 requested->density == ResTable_config::DENSITY_ANY) {
2453 requestedDensity = ResTable_config::DENSITY_MEDIUM;
2456 // DENSITY_ANY is now dealt with. We should look to
2457 // pick a density bucket and potentially scale it.
2458 // Any density is potentially useful
2459 // because the system will scale it. Scaling down
2460 // is generally better than scaling up.
2461 int h = thisDensity;
2462 int l = otherDensity;
2463 bool bImBigger = true;
2471 if (requestedDensity >= h) {
2472 // requested value higher than both l and h, give h
2475 if (l >= requestedDensity) {
2476 // requested value lower than both l and h, give l
2479 // saying that scaling down is 2x better than up
2480 if (((2 * l) - requestedDensity) * h > requestedDensity * requestedDensity) {
2487 if ((touchscreen != o.touchscreen) && requested->touchscreen) {
2488 return (touchscreen);
2492 if (input || o.input) {
2493 const int keysHidden = inputFlags & MASK_KEYSHIDDEN;
2494 const int oKeysHidden = o.inputFlags & MASK_KEYSHIDDEN;
2495 if (keysHidden != oKeysHidden) {
2496 const int reqKeysHidden =
2497 requested->inputFlags & MASK_KEYSHIDDEN;
2498 if (reqKeysHidden) {
2500 if (!keysHidden) return false;
2501 if (!oKeysHidden) return true;
2502 // For compatibility, we count KEYSHIDDEN_NO as being
2503 // the same as KEYSHIDDEN_SOFT. Here we disambiguate
2504 // these by making an exact match more specific.
2505 if (reqKeysHidden == keysHidden) return true;
2506 if (reqKeysHidden == oKeysHidden) return false;
2510 const int navHidden = inputFlags & MASK_NAVHIDDEN;
2511 const int oNavHidden = o.inputFlags & MASK_NAVHIDDEN;
2512 if (navHidden != oNavHidden) {
2513 const int reqNavHidden =
2514 requested->inputFlags & MASK_NAVHIDDEN;
2517 if (!navHidden) return false;
2518 if (!oNavHidden) return true;
2522 if ((keyboard != o.keyboard) && requested->keyboard) {
2526 if ((navigation != o.navigation) && requested->navigation) {
2527 return (navigation);
2531 if (screenSize || o.screenSize) {
2532 // "Better" is based on the sum of the difference between both
2533 // width and height from the requested dimensions. We are
2534 // assuming the invalid configs (with smaller sizes) have
2535 // already been filtered. Note that if a particular dimension
2536 // is unspecified, we will end up with a large value (the
2537 // difference between 0 and the requested dimension), which is
2538 // good since we will prefer a config that has specified a
2540 int myDelta = 0, otherDelta = 0;
2541 if (requested->screenWidth) {
2542 myDelta += requested->screenWidth - screenWidth;
2543 otherDelta += requested->screenWidth - o.screenWidth;
2545 if (requested->screenHeight) {
2546 myDelta += requested->screenHeight - screenHeight;
2547 otherDelta += requested->screenHeight - o.screenHeight;
2549 if (myDelta != otherDelta) {
2550 return myDelta < otherDelta;
2554 if (version || o.version) {
2555 if ((sdkVersion != o.sdkVersion) && requested->sdkVersion) {
2556 return (sdkVersion > o.sdkVersion);
2559 if ((minorVersion != o.minorVersion) &&
2560 requested->minorVersion) {
2561 return (minorVersion);
2567 return isMoreSpecificThan(o);
2570 bool ResTable_config::match(const ResTable_config& settings) const {
2572 if (mcc != 0 && mcc != settings.mcc) {
2575 if (mnc != 0 && mnc != settings.mnc) {
2580 // Don't consider country and variants when deciding matches.
2581 // (Theoretically, the variant can also affect the script. For
2582 // example, "ar-alalc97" probably implies the Latin script, but since
2583 // CLDR doesn't support getting likely scripts for that, we'll assume
2584 // the variant doesn't change the script.)
2586 // If two configs differ only in their country and variant,
2587 // they can be weeded out in the isMoreSpecificThan test.
2588 if (!langsAreEquivalent(language, settings.language)) {
2592 // For backward compatibility and supporting private-use locales, we
2593 // fall back to old behavior if we couldn't determine the script for
2594 // either of the desired locale or the provided locale. But if we could determine
2595 // the scripts, they should be the same for the locales to match.
2596 bool countriesMustMatch = false;
2597 char computed_script[4];
2599 if (settings.localeScript[0] == '\0') { // could not determine the request's script
2600 countriesMustMatch = true;
2602 if (localeScript[0] == '\0' && !localeScriptWasComputed) {
2603 // script was not provided or computed, so we try to compute it
2604 localeDataComputeScript(computed_script, language, country);
2605 if (computed_script[0] == '\0') { // we could not compute the script
2606 countriesMustMatch = true;
2608 script = computed_script;
2610 } else { // script was provided, so just use it
2611 script = localeScript;
2615 if (countriesMustMatch) {
2616 if (country[0] != '\0' && !areIdentical(country, settings.country)) {
2620 if (memcmp(script, settings.localeScript, sizeof(settings.localeScript)) != 0) {
2626 if (screenConfig != 0) {
2627 const int layoutDir = screenLayout&MASK_LAYOUTDIR;
2628 const int setLayoutDir = settings.screenLayout&MASK_LAYOUTDIR;
2629 if (layoutDir != 0 && layoutDir != setLayoutDir) {
2633 const int screenSize = screenLayout&MASK_SCREENSIZE;
2634 const int setScreenSize = settings.screenLayout&MASK_SCREENSIZE;
2635 // Any screen sizes for larger screens than the setting do not
2637 if (screenSize != 0 && screenSize > setScreenSize) {
2641 const int screenLong = screenLayout&MASK_SCREENLONG;
2642 const int setScreenLong = settings.screenLayout&MASK_SCREENLONG;
2643 if (screenLong != 0 && screenLong != setScreenLong) {
2647 const int uiModeType = uiMode&MASK_UI_MODE_TYPE;
2648 const int setUiModeType = settings.uiMode&MASK_UI_MODE_TYPE;
2649 if (uiModeType != 0 && uiModeType != setUiModeType) {
2653 const int uiModeNight = uiMode&MASK_UI_MODE_NIGHT;
2654 const int setUiModeNight = settings.uiMode&MASK_UI_MODE_NIGHT;
2655 if (uiModeNight != 0 && uiModeNight != setUiModeNight) {
2659 if (smallestScreenWidthDp != 0
2660 && smallestScreenWidthDp > settings.smallestScreenWidthDp) {
2665 if (screenConfig2 != 0) {
2666 const int screenRound = screenLayout2 & MASK_SCREENROUND;
2667 const int setScreenRound = settings.screenLayout2 & MASK_SCREENROUND;
2668 if (screenRound != 0 && screenRound != setScreenRound) {
2672 const int hdr = colorMode & MASK_HDR;
2673 const int setHdr = settings.colorMode & MASK_HDR;
2674 if (hdr != 0 && hdr != setHdr) {
2678 const int wideColorGamut = colorMode & MASK_WIDE_COLOR_GAMUT;
2679 const int setWideColorGamut = settings.colorMode & MASK_WIDE_COLOR_GAMUT;
2680 if (wideColorGamut != 0 && wideColorGamut != setWideColorGamut) {
2685 if (screenSizeDp != 0) {
2686 if (screenWidthDp != 0 && screenWidthDp > settings.screenWidthDp) {
2687 if (kDebugTableSuperNoisy) {
2688 ALOGI("Filtering out width %d in requested %d", screenWidthDp,
2689 settings.screenWidthDp);
2693 if (screenHeightDp != 0 && screenHeightDp > settings.screenHeightDp) {
2694 if (kDebugTableSuperNoisy) {
2695 ALOGI("Filtering out height %d in requested %d", screenHeightDp,
2696 settings.screenHeightDp);
2701 if (screenType != 0) {
2702 if (orientation != 0 && orientation != settings.orientation) {
2705 // density always matches - we can scale it. See isBetterThan
2706 if (touchscreen != 0 && touchscreen != settings.touchscreen) {
2711 const int keysHidden = inputFlags&MASK_KEYSHIDDEN;
2712 const int setKeysHidden = settings.inputFlags&MASK_KEYSHIDDEN;
2713 if (keysHidden != 0 && keysHidden != setKeysHidden) {
2714 // For compatibility, we count a request for KEYSHIDDEN_NO as also
2715 // matching the more recent KEYSHIDDEN_SOFT. Basically
2716 // KEYSHIDDEN_NO means there is some kind of keyboard available.
2717 if (kDebugTableSuperNoisy) {
2718 ALOGI("Matching keysHidden: have=%d, config=%d\n", keysHidden, setKeysHidden);
2720 if (keysHidden != KEYSHIDDEN_NO || setKeysHidden != KEYSHIDDEN_SOFT) {
2721 if (kDebugTableSuperNoisy) {
2727 const int navHidden = inputFlags&MASK_NAVHIDDEN;
2728 const int setNavHidden = settings.inputFlags&MASK_NAVHIDDEN;
2729 if (navHidden != 0 && navHidden != setNavHidden) {
2732 if (keyboard != 0 && keyboard != settings.keyboard) {
2735 if (navigation != 0 && navigation != settings.navigation) {
2739 if (screenSize != 0) {
2740 if (screenWidth != 0 && screenWidth > settings.screenWidth) {
2743 if (screenHeight != 0 && screenHeight > settings.screenHeight) {
2748 if (sdkVersion != 0 && sdkVersion > settings.sdkVersion) {
2751 if (minorVersion != 0 && minorVersion != settings.minorVersion) {
2758 void ResTable_config::appendDirLocale(String8& out) const {
2762 const bool scriptWasProvided = localeScript[0] != '\0' && !localeScriptWasComputed;
2763 if (!scriptWasProvided && !localeVariant[0]) {
2765 if (out.size() > 0) {
2770 size_t len = unpackLanguage(buf);
2771 out.append(buf, len);
2775 len = unpackRegion(buf);
2776 out.append(buf, len);
2781 // We are writing the modified BCP 47 tag.
2782 // It starts with 'b+' and uses '+' as a separator.
2784 if (out.size() > 0) {
2790 size_t len = unpackLanguage(buf);
2791 out.append(buf, len);
2793 if (scriptWasProvided) {
2795 out.append(localeScript, sizeof(localeScript));
2800 len = unpackRegion(buf);
2801 out.append(buf, len);
2804 if (localeVariant[0]) {
2806 out.append(localeVariant, strnlen(localeVariant, sizeof(localeVariant)));
2810 void ResTable_config::getBcp47Locale(char str[RESTABLE_MAX_LOCALE_LEN], bool canonicalize) const {
2811 memset(str, 0, RESTABLE_MAX_LOCALE_LEN);
2813 // This represents the "any" locale value, which has traditionally been
2814 // represented by the empty string.
2815 if (language[0] == '\0' && country[0] == '\0') {
2819 size_t charsWritten = 0;
2820 if (language[0] != '\0') {
2821 if (canonicalize && areIdentical(language, kTagalog)) {
2822 // Replace Tagalog with Filipino if we are canonicalizing
2823 str[0] = 'f'; str[1] = 'i'; str[2] = 'l'; str[3] = '\0'; // 3-letter code for Filipino
2826 charsWritten += unpackLanguage(str);
2830 if (localeScript[0] != '\0' && !localeScriptWasComputed) {
2831 if (charsWritten > 0) {
2832 str[charsWritten++] = '-';
2834 memcpy(str + charsWritten, localeScript, sizeof(localeScript));
2835 charsWritten += sizeof(localeScript);
2838 if (country[0] != '\0') {
2839 if (charsWritten > 0) {
2840 str[charsWritten++] = '-';
2842 charsWritten += unpackRegion(str + charsWritten);
2845 if (localeVariant[0] != '\0') {
2846 if (charsWritten > 0) {
2847 str[charsWritten++] = '-';
2849 memcpy(str + charsWritten, localeVariant, sizeof(localeVariant));
2853 /* static */ inline bool assignLocaleComponent(ResTable_config* config,
2854 const char* start, size_t size) {
2861 config->language[0] ? config->packRegion(start) : config->packLanguage(start);
2864 if ('0' <= start[0] && start[0] <= '9') {
2865 // this is a variant, so fall through
2867 config->localeScript[0] = toupper(start[0]);
2868 for (size_t i = 1; i < 4; ++i) {
2869 config->localeScript[i] = tolower(start[i]);
2877 for (size_t i = 0; i < size; ++i) {
2878 config->localeVariant[i] = tolower(start[i]);
2888 void ResTable_config::setBcp47Locale(const char* in) {
2890 memset(localeScript, 0, sizeof(localeScript));
2891 memset(localeVariant, 0, sizeof(localeVariant));
2893 const char* separator = in;
2894 const char* start = in;
2895 while ((separator = strchr(start, '-')) != NULL) {
2896 const size_t size = separator - start;
2897 if (!assignLocaleComponent(this, start, size)) {
2898 fprintf(stderr, "Invalid BCP-47 locale string: %s", in);
2901 start = (separator + 1);
2904 const size_t size = in + strlen(in) - start;
2905 assignLocaleComponent(this, start, size);
2906 localeScriptWasComputed = (localeScript[0] == '\0');
2907 if (localeScriptWasComputed) {
2912 String8 ResTable_config::toString() const {
2916 if (res.size() > 0) res.append("-");
2917 res.appendFormat("mcc%d", dtohs(mcc));
2920 if (res.size() > 0) res.append("-");
2921 res.appendFormat("mnc%d", dtohs(mnc));
2924 appendDirLocale(res);
2926 if ((screenLayout&MASK_LAYOUTDIR) != 0) {
2927 if (res.size() > 0) res.append("-");
2928 switch (screenLayout&ResTable_config::MASK_LAYOUTDIR) {
2929 case ResTable_config::LAYOUTDIR_LTR:
2930 res.append("ldltr");
2932 case ResTable_config::LAYOUTDIR_RTL:
2933 res.append("ldrtl");
2936 res.appendFormat("layoutDir=%d",
2937 dtohs(screenLayout&ResTable_config::MASK_LAYOUTDIR));
2941 if (smallestScreenWidthDp != 0) {
2942 if (res.size() > 0) res.append("-");
2943 res.appendFormat("sw%ddp", dtohs(smallestScreenWidthDp));
2945 if (screenWidthDp != 0) {
2946 if (res.size() > 0) res.append("-");
2947 res.appendFormat("w%ddp", dtohs(screenWidthDp));
2949 if (screenHeightDp != 0) {
2950 if (res.size() > 0) res.append("-");
2951 res.appendFormat("h%ddp", dtohs(screenHeightDp));
2953 if ((screenLayout&MASK_SCREENSIZE) != SCREENSIZE_ANY) {
2954 if (res.size() > 0) res.append("-");
2955 switch (screenLayout&ResTable_config::MASK_SCREENSIZE) {
2956 case ResTable_config::SCREENSIZE_SMALL:
2957 res.append("small");
2959 case ResTable_config::SCREENSIZE_NORMAL:
2960 res.append("normal");
2962 case ResTable_config::SCREENSIZE_LARGE:
2963 res.append("large");
2965 case ResTable_config::SCREENSIZE_XLARGE:
2966 res.append("xlarge");
2969 res.appendFormat("screenLayoutSize=%d",
2970 dtohs(screenLayout&ResTable_config::MASK_SCREENSIZE));
2974 if ((screenLayout&MASK_SCREENLONG) != 0) {
2975 if (res.size() > 0) res.append("-");
2976 switch (screenLayout&ResTable_config::MASK_SCREENLONG) {
2977 case ResTable_config::SCREENLONG_NO:
2978 res.append("notlong");
2980 case ResTable_config::SCREENLONG_YES:
2984 res.appendFormat("screenLayoutLong=%d",
2985 dtohs(screenLayout&ResTable_config::MASK_SCREENLONG));
2989 if ((screenLayout2&MASK_SCREENROUND) != 0) {
2990 if (res.size() > 0) res.append("-");
2991 switch (screenLayout2&MASK_SCREENROUND) {
2992 case SCREENROUND_NO:
2993 res.append("notround");
2995 case SCREENROUND_YES:
2996 res.append("round");
2999 res.appendFormat("screenRound=%d", dtohs(screenLayout2&MASK_SCREENROUND));
3003 if ((colorMode&MASK_HDR) != 0) {
3004 if (res.size() > 0) res.append("-");
3005 switch (colorMode&MASK_HDR) {
3006 case ResTable_config::HDR_NO:
3007 res.append("lowdr");
3009 case ResTable_config::HDR_YES:
3010 res.append("highdr");
3013 res.appendFormat("hdr=%d", dtohs(colorMode&MASK_HDR));
3017 if ((colorMode&MASK_WIDE_COLOR_GAMUT) != 0) {
3018 if (res.size() > 0) res.append("-");
3019 switch (colorMode&MASK_WIDE_COLOR_GAMUT) {
3020 case ResTable_config::WIDE_COLOR_GAMUT_NO:
3021 res.append("nowidecg");
3023 case ResTable_config::WIDE_COLOR_GAMUT_YES:
3024 res.append("widecg");
3027 res.appendFormat("wideColorGamut=%d", dtohs(colorMode&MASK_WIDE_COLOR_GAMUT));
3031 if (orientation != ORIENTATION_ANY) {
3032 if (res.size() > 0) res.append("-");
3033 switch (orientation) {
3034 case ResTable_config::ORIENTATION_PORT:
3037 case ResTable_config::ORIENTATION_LAND:
3040 case ResTable_config::ORIENTATION_SQUARE:
3041 res.append("square");
3044 res.appendFormat("orientation=%d", dtohs(orientation));
3048 if ((uiMode&MASK_UI_MODE_TYPE) != UI_MODE_TYPE_ANY) {
3049 if (res.size() > 0) res.append("-");
3050 switch (uiMode&ResTable_config::MASK_UI_MODE_TYPE) {
3051 case ResTable_config::UI_MODE_TYPE_DESK:
3054 case ResTable_config::UI_MODE_TYPE_CAR:
3057 case ResTable_config::UI_MODE_TYPE_TELEVISION:
3058 res.append("television");
3060 case ResTable_config::UI_MODE_TYPE_APPLIANCE:
3061 res.append("appliance");
3063 case ResTable_config::UI_MODE_TYPE_WATCH:
3064 res.append("watch");
3066 case ResTable_config::UI_MODE_TYPE_VR_HEADSET:
3067 res.append("vrheadset");
3070 res.appendFormat("uiModeType=%d",
3071 dtohs(screenLayout&ResTable_config::MASK_UI_MODE_TYPE));
3075 if ((uiMode&MASK_UI_MODE_NIGHT) != 0) {
3076 if (res.size() > 0) res.append("-");
3077 switch (uiMode&ResTable_config::MASK_UI_MODE_NIGHT) {
3078 case ResTable_config::UI_MODE_NIGHT_NO:
3079 res.append("notnight");
3081 case ResTable_config::UI_MODE_NIGHT_YES:
3082 res.append("night");
3085 res.appendFormat("uiModeNight=%d",
3086 dtohs(uiMode&MASK_UI_MODE_NIGHT));
3090 if (density != DENSITY_DEFAULT) {
3091 if (res.size() > 0) res.append("-");
3093 case ResTable_config::DENSITY_LOW:
3096 case ResTable_config::DENSITY_MEDIUM:
3099 case ResTable_config::DENSITY_TV:
3100 res.append("tvdpi");
3102 case ResTable_config::DENSITY_HIGH:
3105 case ResTable_config::DENSITY_XHIGH:
3106 res.append("xhdpi");
3108 case ResTable_config::DENSITY_XXHIGH:
3109 res.append("xxhdpi");
3111 case ResTable_config::DENSITY_XXXHIGH:
3112 res.append("xxxhdpi");
3114 case ResTable_config::DENSITY_NONE:
3115 res.append("nodpi");
3117 case ResTable_config::DENSITY_ANY:
3118 res.append("anydpi");
3121 res.appendFormat("%ddpi", dtohs(density));
3125 if (touchscreen != TOUCHSCREEN_ANY) {
3126 if (res.size() > 0) res.append("-");
3127 switch (touchscreen) {
3128 case ResTable_config::TOUCHSCREEN_NOTOUCH:
3129 res.append("notouch");
3131 case ResTable_config::TOUCHSCREEN_FINGER:
3132 res.append("finger");
3134 case ResTable_config::TOUCHSCREEN_STYLUS:
3135 res.append("stylus");
3138 res.appendFormat("touchscreen=%d", dtohs(touchscreen));
3142 if ((inputFlags&MASK_KEYSHIDDEN) != 0) {
3143 if (res.size() > 0) res.append("-");
3144 switch (inputFlags&MASK_KEYSHIDDEN) {
3145 case ResTable_config::KEYSHIDDEN_NO:
3146 res.append("keysexposed");
3148 case ResTable_config::KEYSHIDDEN_YES:
3149 res.append("keyshidden");
3151 case ResTable_config::KEYSHIDDEN_SOFT:
3152 res.append("keyssoft");
3156 if (keyboard != KEYBOARD_ANY) {
3157 if (res.size() > 0) res.append("-");
3159 case ResTable_config::KEYBOARD_NOKEYS:
3160 res.append("nokeys");
3162 case ResTable_config::KEYBOARD_QWERTY:
3163 res.append("qwerty");
3165 case ResTable_config::KEYBOARD_12KEY:
3166 res.append("12key");
3169 res.appendFormat("keyboard=%d", dtohs(keyboard));
3173 if ((inputFlags&MASK_NAVHIDDEN) != 0) {
3174 if (res.size() > 0) res.append("-");
3175 switch (inputFlags&MASK_NAVHIDDEN) {
3176 case ResTable_config::NAVHIDDEN_NO:
3177 res.append("navexposed");
3179 case ResTable_config::NAVHIDDEN_YES:
3180 res.append("navhidden");
3183 res.appendFormat("inputFlagsNavHidden=%d",
3184 dtohs(inputFlags&MASK_NAVHIDDEN));
3188 if (navigation != NAVIGATION_ANY) {
3189 if (res.size() > 0) res.append("-");
3190 switch (navigation) {
3191 case ResTable_config::NAVIGATION_NONAV:
3192 res.append("nonav");
3194 case ResTable_config::NAVIGATION_DPAD:
3197 case ResTable_config::NAVIGATION_TRACKBALL:
3198 res.append("trackball");
3200 case ResTable_config::NAVIGATION_WHEEL:
3201 res.append("wheel");
3204 res.appendFormat("navigation=%d", dtohs(navigation));
3208 if (screenSize != 0) {
3209 if (res.size() > 0) res.append("-");
3210 res.appendFormat("%dx%d", dtohs(screenWidth), dtohs(screenHeight));
3213 if (res.size() > 0) res.append("-");
3214 res.appendFormat("v%d", dtohs(sdkVersion));
3215 if (minorVersion != 0) {
3216 res.appendFormat(".%d", dtohs(minorVersion));
3223 // --------------------------------------------------------------------
3224 // --------------------------------------------------------------------
3225 // --------------------------------------------------------------------
3227 struct ResTable::Header
3229 explicit Header(ResTable* _owner) : owner(_owner), ownedData(NULL), header(NULL),
3230 resourceIDMap(NULL), resourceIDMapSize(0) { }
3234 free(resourceIDMap);
3237 const ResTable* const owner;
3239 const ResTable_header* header;
3241 const uint8_t* dataEnd;
3245 ResStringPool values;
3246 uint32_t* resourceIDMap;
3247 size_t resourceIDMapSize;
3250 struct ResTable::Entry {
3251 ResTable_config config;
3252 const ResTable_entry* entry;
3253 const ResTable_type* type;
3255 const Package* package;
3257 StringPoolRef typeStr;
3258 StringPoolRef keyStr;
3261 struct ResTable::Type
3263 Type(const Header* _header, const Package* _package, size_t count)
3264 : header(_header), package(_package), entryCount(count),
3265 typeSpec(NULL), typeSpecFlags(NULL) { }
3266 const Header* const header;
3267 const Package* const package;
3268 const size_t entryCount;
3269 const ResTable_typeSpec* typeSpec;
3270 const uint32_t* typeSpecFlags;
3271 IdmapEntries idmapEntries;
3272 Vector<const ResTable_type*> configs;
3275 struct ResTable::Package
3277 Package(ResTable* _owner, const Header* _header, const ResTable_package* _package)
3278 : owner(_owner), header(_header), package(_package), typeIdOffset(0) {
3279 if (dtohs(package->header.headerSize) == sizeof(*package)) {
3280 // The package structure is the same size as the definition.
3281 // This means it contains the typeIdOffset field.
3282 typeIdOffset = package->typeIdOffset;
3286 const ResTable* const owner;
3287 const Header* const header;
3288 const ResTable_package* const package;
3290 ResStringPool typeStrings;
3291 ResStringPool keyStrings;
3293 size_t typeIdOffset;
3296 // A group of objects describing a particular resource package.
3297 // The first in 'package' is always the root object (from the resource
3298 // table that defined the package); the ones after are skins on top of it.
3299 struct ResTable::PackageGroup
3302 ResTable* _owner, const String16& _name, uint32_t _id,
3303 bool appAsLib, bool _isSystemAsset)
3308 , dynamicRefTable(static_cast<uint8_t>(_id), appAsLib)
3309 , isSystemAsset(_isSystemAsset)
3314 const size_t numTypes = types.size();
3315 for (size_t i = 0; i < numTypes; i++) {
3316 const TypeList& typeList = types[i];
3317 const size_t numInnerTypes = typeList.size();
3318 for (size_t j = 0; j < numInnerTypes; j++) {
3319 if (typeList[j]->package->owner == owner) {
3325 const size_t N = packages.size();
3326 for (size_t i=0; i<N; i++) {
3327 Package* pkg = packages[i];
3328 if (pkg->owner == owner) {
3335 * Clear all cache related data that depends on parameters/configuration.
3336 * This includes the bag caches and filtered types.
3338 void clearBagCache() {
3339 for (size_t i = 0; i < typeCacheEntries.size(); i++) {
3340 if (kDebugTableNoisy) {
3341 printf("type=%zu\n", i);
3343 const TypeList& typeList = types[i];
3344 if (!typeList.isEmpty()) {
3345 TypeCacheEntry& cacheEntry = typeCacheEntries.editItemAt(i);
3347 // Reset the filtered configurations.
3348 cacheEntry.filteredConfigs.clear();
3350 bag_set** typeBags = cacheEntry.cachedBags;
3351 if (kDebugTableNoisy) {
3352 printf("typeBags=%p\n", typeBags);
3356 const size_t N = typeList[0]->entryCount;
3357 if (kDebugTableNoisy) {
3358 printf("type->entryCount=%zu\n", N);
3360 for (size_t j = 0; j < N; j++) {
3361 if (typeBags[j] && typeBags[j] != (bag_set*)0xFFFFFFFF) {
3366 cacheEntry.cachedBags = NULL;
3372 ssize_t findType16(const char16_t* type, size_t len) const {
3373 const size_t N = packages.size();
3374 for (size_t i = 0; i < N; i++) {
3375 ssize_t index = packages[i]->typeStrings.indexOfString(type, len);
3377 return index + packages[i]->typeIdOffset;
3383 const ResTable* const owner;
3384 String16 const name;
3387 // This is mainly used to keep track of the loaded packages
3388 // and to clean them up properly. Accessing resources happens from
3389 // the 'types' array.
3390 Vector<Package*> packages;
3392 ByteBucketArray<TypeList> types;
3394 uint8_t largestTypeId;
3396 // Cached objects dependent on the parameters/configuration of this ResTable.
3397 // Gets cleared whenever the parameters/configuration changes.
3398 // These are stored here in a parallel structure because the data in `types` may
3399 // be shared by other ResTable's (framework resources are shared this way).
3400 ByteBucketArray<TypeCacheEntry> typeCacheEntries;
3402 // The table mapping dynamic references to resolved references for
3403 // this package group.
3404 // TODO: We may be able to support dynamic references in overlays
3405 // by having these tables in a per-package scope rather than
3406 // per-package-group.
3407 DynamicRefTable dynamicRefTable;
3409 // If the package group comes from a system asset. Used in
3410 // determining non-system locales.
3411 const bool isSystemAsset;
3414 ResTable::Theme::Theme(const ResTable& table)
3418 memset(mPackages, 0, sizeof(mPackages));
3421 ResTable::Theme::~Theme()
3423 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3424 package_info* pi = mPackages[i];
3431 void ResTable::Theme::free_package(package_info* pi)
3433 for (size_t j = 0; j <= Res_MAXTYPE; j++) {
3434 theme_entry* te = pi->types[j].entries;
3442 ResTable::Theme::package_info* ResTable::Theme::copy_package(package_info* pi)
3444 package_info* newpi = (package_info*)malloc(sizeof(package_info));
3445 for (size_t j = 0; j <= Res_MAXTYPE; j++) {
3446 size_t cnt = pi->types[j].numEntries;
3447 newpi->types[j].numEntries = cnt;
3448 theme_entry* te = pi->types[j].entries;
3449 size_t cnt_max = SIZE_MAX / sizeof(theme_entry);
3450 if (te != NULL && (cnt < 0xFFFFFFFF-1) && (cnt < cnt_max)) {
3451 theme_entry* newte = (theme_entry*)malloc(cnt*sizeof(theme_entry));
3452 newpi->types[j].entries = newte;
3453 memcpy(newte, te, cnt*sizeof(theme_entry));
3455 newpi->types[j].entries = NULL;
3461 status_t ResTable::Theme::applyStyle(uint32_t resID, bool force)
3463 const bag_entry* bag;
3464 uint32_t bagTypeSpecFlags = 0;
3466 const ssize_t N = mTable.getBagLocked(resID, &bag, &bagTypeSpecFlags);
3467 if (kDebugTableNoisy) {
3468 ALOGV("Applying style 0x%08x to theme %p, count=%zu", resID, this, N);
3475 mTypeSpecFlags |= bagTypeSpecFlags;
3477 uint32_t curPackage = 0xffffffff;
3478 ssize_t curPackageIndex = 0;
3479 package_info* curPI = NULL;
3480 uint32_t curType = 0xffffffff;
3481 size_t numEntries = 0;
3482 theme_entry* curEntries = NULL;
3484 const bag_entry* end = bag + N;
3486 const uint32_t attrRes = bag->map.name.ident;
3487 const uint32_t p = Res_GETPACKAGE(attrRes);
3488 const uint32_t t = Res_GETTYPE(attrRes);
3489 const uint32_t e = Res_GETENTRY(attrRes);
3491 if (curPackage != p) {
3492 const ssize_t pidx = mTable.getResourcePackageIndex(attrRes);
3494 ALOGE("Style contains key with bad package: 0x%08x\n", attrRes);
3499 curPackageIndex = pidx;
3500 curPI = mPackages[pidx];
3501 if (curPI == NULL) {
3502 curPI = (package_info*)malloc(sizeof(package_info));
3503 memset(curPI, 0, sizeof(*curPI));
3504 mPackages[pidx] = curPI;
3506 curType = 0xffffffff;
3509 if (t > Res_MAXTYPE) {
3510 ALOGE("Style contains key with bad type: 0x%08x\n", attrRes);
3515 curEntries = curPI->types[t].entries;
3516 if (curEntries == NULL) {
3517 PackageGroup* const grp = mTable.mPackageGroups[curPackageIndex];
3518 const TypeList& typeList = grp->types[t];
3519 size_t cnt = typeList.isEmpty() ? 0 : typeList[0]->entryCount;
3520 size_t cnt_max = SIZE_MAX / sizeof(theme_entry);
3521 size_t buff_size = (cnt < cnt_max && cnt < 0xFFFFFFFF-1) ?
3522 cnt*sizeof(theme_entry) : 0;
3523 curEntries = (theme_entry*)malloc(buff_size);
3524 memset(curEntries, Res_value::TYPE_NULL, buff_size);
3525 curPI->types[t].numEntries = cnt;
3526 curPI->types[t].entries = curEntries;
3528 numEntries = curPI->types[t].numEntries;
3530 if (e >= numEntries) {
3531 ALOGE("Style contains key with bad entry: 0x%08x\n", attrRes);
3535 theme_entry* curEntry = curEntries + e;
3536 if (kDebugTableNoisy) {
3537 ALOGV("Attr 0x%08x: type=0x%x, data=0x%08x; curType=0x%x",
3538 attrRes, bag->map.value.dataType, bag->map.value.data,
3539 curEntry->value.dataType);
3541 if (force || (curEntry->value.dataType == Res_value::TYPE_NULL
3542 && curEntry->value.data != Res_value::DATA_NULL_EMPTY)) {
3543 curEntry->stringBlock = bag->stringBlock;
3544 curEntry->typeSpecFlags |= bagTypeSpecFlags;
3545 curEntry->value = bag->map.value;
3553 if (kDebugTableTheme) {
3554 ALOGI("Applying style 0x%08x (force=%d) theme %p...\n", resID, force, this);
3561 status_t ResTable::Theme::setTo(const Theme& other)
3563 if (kDebugTableTheme) {
3564 ALOGI("Setting theme %p from theme %p...\n", this, &other);
3569 if (&mTable == &other.mTable) {
3570 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3571 if (mPackages[i] != NULL) {
3572 free_package(mPackages[i]);
3574 if (other.mPackages[i] != NULL) {
3575 mPackages[i] = copy_package(other.mPackages[i]);
3577 mPackages[i] = NULL;
3581 // @todo: need to really implement this, not just copy
3582 // the system package (which is still wrong because it isn't
3583 // fixing up resource references).
3584 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3585 if (mPackages[i] != NULL) {
3586 free_package(mPackages[i]);
3588 if (i == 0 && other.mPackages[i] != NULL) {
3589 mPackages[i] = copy_package(other.mPackages[i]);
3591 mPackages[i] = NULL;
3596 mTypeSpecFlags = other.mTypeSpecFlags;
3598 if (kDebugTableTheme) {
3599 ALOGI("Final theme:");
3606 status_t ResTable::Theme::clear()
3608 if (kDebugTableTheme) {
3609 ALOGI("Clearing theme %p...\n", this);
3613 for (size_t i = 0; i < Res_MAXPACKAGE; i++) {
3614 if (mPackages[i] != NULL) {
3615 free_package(mPackages[i]);
3616 mPackages[i] = NULL;
3622 if (kDebugTableTheme) {
3623 ALOGI("Final theme:");
3630 ssize_t ResTable::Theme::getAttribute(uint32_t resID, Res_value* outValue,
3631 uint32_t* outTypeSpecFlags) const
3635 if (outTypeSpecFlags != NULL) *outTypeSpecFlags = 0;
3638 const ssize_t p = mTable.getResourcePackageIndex(resID);
3639 const uint32_t t = Res_GETTYPE(resID);
3640 const uint32_t e = Res_GETENTRY(resID);
3642 if (kDebugTableTheme) {
3643 ALOGI("Looking up attr 0x%08x in theme %p", resID, this);
3647 const package_info* const pi = mPackages[p];
3648 if (kDebugTableTheme) {
3649 ALOGI("Found package: %p", pi);
3652 if (kDebugTableTheme) {
3653 ALOGI("Desired type index is %u in avail %zu", t, Res_MAXTYPE + 1);
3655 if (t <= Res_MAXTYPE) {
3656 const type_info& ti = pi->types[t];
3657 if (kDebugTableTheme) {
3658 ALOGI("Desired entry index is %u in avail %zu", e, ti.numEntries);
3660 if (e < ti.numEntries) {
3661 const theme_entry& te = ti.entries[e];
3662 if (outTypeSpecFlags != NULL) {
3663 *outTypeSpecFlags |= te.typeSpecFlags;
3665 if (kDebugTableTheme) {
3666 ALOGI("Theme value: type=0x%x, data=0x%08x",
3667 te.value.dataType, te.value.data);
3669 const uint8_t type = te.value.dataType;
3670 if (type == Res_value::TYPE_ATTRIBUTE) {
3673 resID = te.value.data;
3676 ALOGW("Too many attribute references, stopped at: 0x%08x\n", resID);
3678 } else if (type != Res_value::TYPE_NULL
3679 || te.value.data == Res_value::DATA_NULL_EMPTY) {
3680 *outValue = te.value;
3681 return te.stringBlock;
3695 ssize_t ResTable::Theme::resolveAttributeReference(Res_value* inOutValue,
3696 ssize_t blockIndex, uint32_t* outLastRef,
3697 uint32_t* inoutTypeSpecFlags, ResTable_config* inoutConfig) const
3699 //printf("Resolving type=0x%x\n", inOutValue->dataType);
3700 if (inOutValue->dataType == Res_value::TYPE_ATTRIBUTE) {
3701 uint32_t newTypeSpecFlags;
3702 blockIndex = getAttribute(inOutValue->data, inOutValue, &newTypeSpecFlags);
3703 if (kDebugTableTheme) {
3704 ALOGI("Resolving attr reference: blockIndex=%d, type=0x%x, data=0x%x\n",
3705 (int)blockIndex, (int)inOutValue->dataType, inOutValue->data);
3707 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newTypeSpecFlags;
3708 //printf("Retrieved attribute new type=0x%x\n", inOutValue->dataType);
3709 if (blockIndex < 0) {
3713 return mTable.resolveReference(inOutValue, blockIndex, outLastRef,
3714 inoutTypeSpecFlags, inoutConfig);
3717 uint32_t ResTable::Theme::getChangingConfigurations() const
3719 return mTypeSpecFlags;
3722 void ResTable::Theme::dumpToLog() const
3724 ALOGI("Theme %p:\n", this);
3725 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3726 package_info* pi = mPackages[i];
3727 if (pi == NULL) continue;
3729 ALOGI(" Package #0x%02x:\n", (int)(i + 1));
3730 for (size_t j = 0; j <= Res_MAXTYPE; j++) {
3731 type_info& ti = pi->types[j];
3732 if (ti.numEntries == 0) continue;
3733 ALOGI(" Type #0x%02x:\n", (int)(j + 1));
3734 for (size_t k = 0; k < ti.numEntries; k++) {
3735 const theme_entry& te = ti.entries[k];
3736 if (te.value.dataType == Res_value::TYPE_NULL) continue;
3737 ALOGI(" 0x%08x: t=0x%x, d=0x%08x (block=%d)\n",
3738 (int)Res_MAKEID(i, j, k),
3739 te.value.dataType, (int)te.value.data, (int)te.stringBlock);
3745 ResTable::ResTable()
3746 : mError(NO_INIT), mNextPackageId(2)
3748 memset(&mParams, 0, sizeof(mParams));
3749 memset(mPackageMap, 0, sizeof(mPackageMap));
3750 if (kDebugTableSuperNoisy) {
3751 ALOGI("Creating ResTable %p\n", this);
3755 ResTable::ResTable(const void* data, size_t size, const int32_t cookie, bool copyData)
3756 : mError(NO_INIT), mNextPackageId(2)
3758 memset(&mParams, 0, sizeof(mParams));
3759 memset(mPackageMap, 0, sizeof(mPackageMap));
3760 addInternal(data, size, NULL, 0, false, cookie, copyData);
3761 LOG_FATAL_IF(mError != NO_ERROR, "Error parsing resource table");
3762 if (kDebugTableSuperNoisy) {
3763 ALOGI("Creating ResTable %p\n", this);
3767 ResTable::~ResTable()
3769 if (kDebugTableSuperNoisy) {
3770 ALOGI("Destroying ResTable in %p\n", this);
3775 inline ssize_t ResTable::getResourcePackageIndex(uint32_t resID) const
3777 return ((ssize_t)mPackageMap[Res_GETPACKAGE(resID)+1])-1;
3780 status_t ResTable::add(const void* data, size_t size, const int32_t cookie, bool copyData) {
3781 return addInternal(data, size, NULL, 0, false, cookie, copyData);
3784 status_t ResTable::add(const void* data, size_t size, const void* idmapData, size_t idmapDataSize,
3785 const int32_t cookie, bool copyData, bool appAsLib) {
3786 return addInternal(data, size, idmapData, idmapDataSize, appAsLib, cookie, copyData);
3789 status_t ResTable::add(Asset* asset, const int32_t cookie, bool copyData) {
3790 const void* data = asset->getBuffer(true);
3792 ALOGW("Unable to get buffer of resource asset file");
3793 return UNKNOWN_ERROR;
3796 return addInternal(data, static_cast<size_t>(asset->getLength()), NULL, false, 0, cookie,
3800 status_t ResTable::add(
3801 Asset* asset, Asset* idmapAsset, const int32_t cookie, bool copyData,
3802 bool appAsLib, bool isSystemAsset) {
3803 const void* data = asset->getBuffer(true);
3805 ALOGW("Unable to get buffer of resource asset file");
3806 return UNKNOWN_ERROR;
3809 size_t idmapSize = 0;
3810 const void* idmapData = NULL;
3811 if (idmapAsset != NULL) {
3812 idmapData = idmapAsset->getBuffer(true);
3813 if (idmapData == NULL) {
3814 ALOGW("Unable to get buffer of idmap asset file");
3815 return UNKNOWN_ERROR;
3817 idmapSize = static_cast<size_t>(idmapAsset->getLength());
3820 return addInternal(data, static_cast<size_t>(asset->getLength()),
3821 idmapData, idmapSize, appAsLib, cookie, copyData, isSystemAsset);
3824 status_t ResTable::add(ResTable* src, bool isSystemAsset)
3826 mError = src->mError;
3828 for (size_t i=0; i < src->mHeaders.size(); i++) {
3829 mHeaders.add(src->mHeaders[i]);
3832 for (size_t i=0; i < src->mPackageGroups.size(); i++) {
3833 PackageGroup* srcPg = src->mPackageGroups[i];
3834 PackageGroup* pg = new PackageGroup(this, srcPg->name, srcPg->id,
3835 false /* appAsLib */, isSystemAsset || srcPg->isSystemAsset);
3836 for (size_t j=0; j<srcPg->packages.size(); j++) {
3837 pg->packages.add(srcPg->packages[j]);
3840 for (size_t j = 0; j < srcPg->types.size(); j++) {
3841 if (srcPg->types[j].isEmpty()) {
3845 TypeList& typeList = pg->types.editItemAt(j);
3846 typeList.appendVector(srcPg->types[j]);
3848 pg->dynamicRefTable.addMappings(srcPg->dynamicRefTable);
3849 pg->largestTypeId = max(pg->largestTypeId, srcPg->largestTypeId);
3850 mPackageGroups.add(pg);
3853 memcpy(mPackageMap, src->mPackageMap, sizeof(mPackageMap));
3858 status_t ResTable::addEmpty(const int32_t cookie) {
3859 Header* header = new Header(this);
3860 header->index = mHeaders.size();
3861 header->cookie = cookie;
3862 header->values.setToEmpty();
3863 header->ownedData = calloc(1, sizeof(ResTable_header));
3865 ResTable_header* resHeader = (ResTable_header*) header->ownedData;
3866 resHeader->header.type = RES_TABLE_TYPE;
3867 resHeader->header.headerSize = sizeof(ResTable_header);
3868 resHeader->header.size = sizeof(ResTable_header);
3870 header->header = (const ResTable_header*) resHeader;
3871 mHeaders.add(header);
3872 return (mError=NO_ERROR);
3875 status_t ResTable::addInternal(const void* data, size_t dataSize, const void* idmapData, size_t idmapDataSize,
3876 bool appAsLib, const int32_t cookie, bool copyData, bool isSystemAsset)
3882 if (dataSize < sizeof(ResTable_header)) {
3883 ALOGE("Invalid data. Size(%d) is smaller than a ResTable_header(%d).",
3884 (int) dataSize, (int) sizeof(ResTable_header));
3885 return UNKNOWN_ERROR;
3888 Header* header = new Header(this);
3889 header->index = mHeaders.size();
3890 header->cookie = cookie;
3891 if (idmapData != NULL) {
3892 header->resourceIDMap = (uint32_t*) malloc(idmapDataSize);
3893 if (header->resourceIDMap == NULL) {
3895 return (mError = NO_MEMORY);
3897 memcpy(header->resourceIDMap, idmapData, idmapDataSize);
3898 header->resourceIDMapSize = idmapDataSize;
3900 mHeaders.add(header);
3902 const bool notDeviceEndian = htods(0xf0) != 0xf0;
3904 if (kDebugLoadTableNoisy) {
3905 ALOGV("Adding resources to ResTable: data=%p, size=%zu, cookie=%d, copy=%d "
3906 "idmap=%p\n", data, dataSize, cookie, copyData, idmapData);
3909 if (copyData || notDeviceEndian) {
3910 header->ownedData = malloc(dataSize);
3911 if (header->ownedData == NULL) {
3912 return (mError=NO_MEMORY);
3914 memcpy(header->ownedData, data, dataSize);
3915 data = header->ownedData;
3918 header->header = (const ResTable_header*)data;
3919 header->size = dtohl(header->header->header.size);
3920 if (kDebugLoadTableSuperNoisy) {
3921 ALOGI("Got size %zu, again size 0x%x, raw size 0x%x\n", header->size,
3922 dtohl(header->header->header.size), header->header->header.size);
3924 if (kDebugLoadTableNoisy) {
3925 ALOGV("Loading ResTable @%p:\n", header->header);
3927 if (dtohs(header->header->header.headerSize) > header->size
3928 || header->size > dataSize) {
3929 ALOGW("Bad resource table: header size 0x%x or total size 0x%x is larger than data size 0x%x\n",
3930 (int)dtohs(header->header->header.headerSize),
3931 (int)header->size, (int)dataSize);
3932 return (mError=BAD_TYPE);
3934 if (((dtohs(header->header->header.headerSize)|header->size)&0x3) != 0) {
3935 ALOGW("Bad resource table: header size 0x%x or total size 0x%x is not on an integer boundary\n",
3936 (int)dtohs(header->header->header.headerSize),
3938 return (mError=BAD_TYPE);
3940 header->dataEnd = ((const uint8_t*)header->header) + header->size;
3942 // Iterate through all chunks.
3943 size_t curPackage = 0;
3945 const ResChunk_header* chunk =
3946 (const ResChunk_header*)(((const uint8_t*)header->header)
3947 + dtohs(header->header->header.headerSize));
3948 while (((const uint8_t*)chunk) <= (header->dataEnd-sizeof(ResChunk_header)) &&
3949 ((const uint8_t*)chunk) <= (header->dataEnd-dtohl(chunk->size))) {
3950 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), header->dataEnd, "ResTable");
3951 if (err != NO_ERROR) {
3952 return (mError=err);
3954 if (kDebugTableNoisy) {
3955 ALOGV("Chunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n",
3956 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
3957 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)));
3959 const size_t csize = dtohl(chunk->size);
3960 const uint16_t ctype = dtohs(chunk->type);
3961 if (ctype == RES_STRING_POOL_TYPE) {
3962 if (header->values.getError() != NO_ERROR) {
3963 // Only use the first string chunk; ignore any others that
3965 status_t err = header->values.setTo(chunk, csize);
3966 if (err != NO_ERROR) {
3967 return (mError=err);
3970 ALOGW("Multiple string chunks found in resource table.");
3972 } else if (ctype == RES_TABLE_PACKAGE_TYPE) {
3973 if (curPackage >= dtohl(header->header->packageCount)) {
3974 ALOGW("More package chunks were found than the %d declared in the header.",
3975 dtohl(header->header->packageCount));
3976 return (mError=BAD_TYPE);
3980 (ResTable_package*)chunk, header, appAsLib, isSystemAsset) != NO_ERROR) {
3985 ALOGW("Unknown chunk type 0x%x in table at %p.\n",
3987 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)));
3989 chunk = (const ResChunk_header*)
3990 (((const uint8_t*)chunk) + csize);
3993 if (curPackage < dtohl(header->header->packageCount)) {
3994 ALOGW("Fewer package chunks (%d) were found than the %d declared in the header.",
3995 (int)curPackage, dtohl(header->header->packageCount));
3996 return (mError=BAD_TYPE);
3998 mError = header->values.getError();
3999 if (mError != NO_ERROR) {
4000 ALOGW("No string values found in resource table!");
4003 if (kDebugTableNoisy) {
4004 ALOGV("Returning from add with mError=%d\n", mError);
4009 status_t ResTable::getError() const
4014 void ResTable::uninit()
4017 size_t N = mPackageGroups.size();
4018 for (size_t i=0; i<N; i++) {
4019 PackageGroup* g = mPackageGroups[i];
4022 N = mHeaders.size();
4023 for (size_t i=0; i<N; i++) {
4024 Header* header = mHeaders[i];
4025 if (header->owner == this) {
4026 if (header->ownedData) {
4027 free(header->ownedData);
4033 mPackageGroups.clear();
4037 bool ResTable::getResourceName(uint32_t resID, bool allowUtf8, resource_name* outName) const
4039 if (mError != NO_ERROR) {
4043 const ssize_t p = getResourcePackageIndex(resID);
4044 const int t = Res_GETTYPE(resID);
4045 const int e = Res_GETENTRY(resID);
4048 if (Res_GETPACKAGE(resID)+1 == 0) {
4049 ALOGW("No package identifier when getting name for resource number 0x%08x", resID);
4051 #ifndef STATIC_ANDROIDFW_FOR_TOOLS
4052 ALOGW("No known package when getting name for resource number 0x%08x", resID);
4058 ALOGW("No type identifier when getting name for resource number 0x%08x", resID);
4062 const PackageGroup* const grp = mPackageGroups[p];
4064 ALOGW("Bad identifier when getting name for resource number 0x%08x", resID);
4069 status_t err = getEntry(grp, t, e, NULL, &entry);
4070 if (err != NO_ERROR) {
4074 outName->package = grp->name.string();
4075 outName->packageLen = grp->name.size();
4077 outName->type8 = entry.typeStr.string8(&outName->typeLen);
4078 outName->name8 = entry.keyStr.string8(&outName->nameLen);
4080 outName->type8 = NULL;
4081 outName->name8 = NULL;
4083 if (outName->type8 == NULL) {
4084 outName->type = entry.typeStr.string16(&outName->typeLen);
4085 // If we have a bad index for some reason, we should abort.
4086 if (outName->type == NULL) {
4090 if (outName->name8 == NULL) {
4091 outName->name = entry.keyStr.string16(&outName->nameLen);
4092 // If we have a bad index for some reason, we should abort.
4093 if (outName->name == NULL) {
4101 ssize_t ResTable::getResource(uint32_t resID, Res_value* outValue, bool mayBeBag, uint16_t density,
4102 uint32_t* outSpecFlags, ResTable_config* outConfig) const
4104 if (mError != NO_ERROR) {
4108 const ssize_t p = getResourcePackageIndex(resID);
4109 const int t = Res_GETTYPE(resID);
4110 const int e = Res_GETENTRY(resID);
4113 if (Res_GETPACKAGE(resID)+1 == 0) {
4114 ALOGW("No package identifier when getting value for resource number 0x%08x", resID);
4116 ALOGW("No known package when getting value for resource number 0x%08x", resID);
4121 ALOGW("No type identifier when getting value for resource number 0x%08x", resID);
4125 const PackageGroup* const grp = mPackageGroups[p];
4127 ALOGW("Bad identifier when getting value for resource number 0x%08x", resID);
4131 // Allow overriding density
4132 ResTable_config desiredConfig = mParams;
4134 desiredConfig.density = density;
4138 status_t err = getEntry(grp, t, e, &desiredConfig, &entry);
4139 if (err != NO_ERROR) {
4140 // Only log the failure when we're not running on the host as
4141 // part of a tool. The caller will do its own logging.
4142 #ifndef STATIC_ANDROIDFW_FOR_TOOLS
4143 ALOGW("Failure getting entry for 0x%08x (t=%d e=%d) (error %d)\n",
4149 if ((dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) != 0) {
4151 ALOGW("Requesting resource 0x%08x failed because it is complex\n", resID);
4156 const Res_value* value = reinterpret_cast<const Res_value*>(
4157 reinterpret_cast<const uint8_t*>(entry.entry) + entry.entry->size);
4159 outValue->size = dtohs(value->size);
4160 outValue->res0 = value->res0;
4161 outValue->dataType = value->dataType;
4162 outValue->data = dtohl(value->data);
4164 // The reference may be pointing to a resource in a shared library. These
4165 // references have build-time generated package IDs. These ids may not match
4166 // the actual package IDs of the corresponding packages in this ResTable.
4167 // We need to fix the package ID based on a mapping.
4168 if (grp->dynamicRefTable.lookupResourceValue(outValue) != NO_ERROR) {
4169 ALOGW("Failed to resolve referenced package: 0x%08x", outValue->data);
4173 if (kDebugTableNoisy) {
4175 printf("Found value: pkg=%zu, type=%d, str=%s, int=%d\n",
4176 entry.package->header->index,
4178 outValue->dataType == Res_value::TYPE_STRING ?
4179 String8(entry.package->header->values.stringAt(outValue->data, &len)).string() :
4184 if (outSpecFlags != NULL) {
4185 *outSpecFlags = entry.specFlags;
4188 if (outConfig != NULL) {
4189 *outConfig = entry.config;
4192 return entry.package->header->index;
4195 ssize_t ResTable::resolveReference(Res_value* value, ssize_t blockIndex,
4196 uint32_t* outLastRef, uint32_t* inoutTypeSpecFlags,
4197 ResTable_config* outConfig) const
4200 while (blockIndex >= 0 && value->dataType == Res_value::TYPE_REFERENCE
4201 && value->data != 0 && count < 20) {
4202 if (outLastRef) *outLastRef = value->data;
4203 uint32_t newFlags = 0;
4204 const ssize_t newIndex = getResource(value->data, value, true, 0, &newFlags,
4206 if (newIndex == BAD_INDEX) {
4209 if (kDebugTableTheme) {
4210 ALOGI("Resolving reference 0x%x: newIndex=%d, type=0x%x, data=0x%x\n",
4211 value->data, (int)newIndex, (int)value->dataType, value->data);
4213 //printf("Getting reference 0x%08x: newIndex=%d\n", value->data, newIndex);
4214 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newFlags;
4216 // This can fail if the resource being referenced is a style...
4217 // in this case, just return the reference, and expect the
4218 // caller to deal with.
4221 blockIndex = newIndex;
4227 const char16_t* ResTable::valueToString(
4228 const Res_value* value, size_t stringBlock,
4229 char16_t /*tmpBuffer*/ [TMP_BUFFER_SIZE], size_t* outLen) const
4234 if (value->dataType == value->TYPE_STRING) {
4235 return getTableStringBlock(stringBlock)->stringAt(value->data, outLen);
4237 // XXX do int to string conversions.
4241 ssize_t ResTable::lockBag(uint32_t resID, const bag_entry** outBag) const
4244 ssize_t err = getBagLocked(resID, outBag);
4245 if (err < NO_ERROR) {
4246 //printf("*** get failed! unlocking\n");
4252 void ResTable::unlockBag(const bag_entry* /*bag*/) const
4254 //printf("<<< unlockBag %p\n", this);
4258 void ResTable::lock() const
4263 void ResTable::unlock() const
4268 ssize_t ResTable::getBagLocked(uint32_t resID, const bag_entry** outBag,
4269 uint32_t* outTypeSpecFlags) const
4271 if (mError != NO_ERROR) {
4275 const ssize_t p = getResourcePackageIndex(resID);
4276 const int t = Res_GETTYPE(resID);
4277 const int e = Res_GETENTRY(resID);
4280 ALOGW("Invalid package identifier when getting bag for resource number 0x%08x", resID);
4284 ALOGW("No type identifier when getting bag for resource number 0x%08x", resID);
4288 //printf("Get bag: id=0x%08x, p=%d, t=%d\n", resID, p, t);
4289 PackageGroup* const grp = mPackageGroups[p];
4291 ALOGW("Bad identifier when getting bag for resource number 0x%08x", resID);
4295 const TypeList& typeConfigs = grp->types[t];
4296 if (typeConfigs.isEmpty()) {
4297 ALOGW("Type identifier 0x%x does not exist.", t+1);
4301 const size_t NENTRY = typeConfigs[0]->entryCount;
4302 if (e >= (int)NENTRY) {
4303 ALOGW("Entry identifier 0x%x is larger than entry count 0x%x",
4304 e, (int)typeConfigs[0]->entryCount);
4308 // First see if we've already computed this bag...
4309 TypeCacheEntry& cacheEntry = grp->typeCacheEntries.editItemAt(t);
4310 bag_set** typeSet = cacheEntry.cachedBags;
4312 bag_set* set = typeSet[e];
4314 if (set != (bag_set*)0xFFFFFFFF) {
4315 if (outTypeSpecFlags != NULL) {
4316 *outTypeSpecFlags = set->typeSpecFlags;
4318 *outBag = (bag_entry*)(set+1);
4319 if (kDebugTableSuperNoisy) {
4320 ALOGI("Found existing bag for: 0x%x\n", resID);
4322 return set->numAttrs;
4324 ALOGW("Attempt to retrieve bag 0x%08x which is invalid or in a cycle.",
4330 // Bag not found, we need to compute it!
4332 typeSet = (bag_set**)calloc(NENTRY, sizeof(bag_set*));
4333 if (!typeSet) return NO_MEMORY;
4334 cacheEntry.cachedBags = typeSet;
4337 // Mark that we are currently working on this one.
4338 typeSet[e] = (bag_set*)0xFFFFFFFF;
4340 if (kDebugTableNoisy) {
4341 ALOGI("Building bag: %x\n", resID);
4344 // Now collect all bag attributes
4346 status_t err = getEntry(grp, t, e, &mParams, &entry);
4347 if (err != NO_ERROR) {
4351 const uint16_t entrySize = dtohs(entry.entry->size);
4352 const uint32_t parent = entrySize >= sizeof(ResTable_map_entry)
4353 ? dtohl(((const ResTable_map_entry*)entry.entry)->parent.ident) : 0;
4354 const uint32_t count = entrySize >= sizeof(ResTable_map_entry)
4355 ? dtohl(((const ResTable_map_entry*)entry.entry)->count) : 0;
4359 if (kDebugTableNoisy) {
4360 ALOGI("Found map: size=%x parent=%x count=%d\n", entrySize, parent, count);
4362 // If this map inherits from another, we need to start
4363 // with its parent's values. Otherwise start out empty.
4364 ALOGI("Creating new bag, entrySize=0x%08x, parent=0x%08x\n", entrySize, parent);
4367 // This is what we are building.
4368 bag_set* set = NULL;
4371 uint32_t resolvedParent = parent;
4373 // Bags encode a parent reference without using the standard
4374 // Res_value structure. That means we must always try to
4375 // resolve a parent reference in case it is actually a
4376 // TYPE_DYNAMIC_REFERENCE.
4377 status_t err = grp->dynamicRefTable.lookupResourceId(&resolvedParent);
4378 if (err != NO_ERROR) {
4379 ALOGE("Failed resolving bag parent id 0x%08x", parent);
4380 return UNKNOWN_ERROR;
4383 const bag_entry* parentBag;
4384 uint32_t parentTypeSpecFlags = 0;
4385 const ssize_t NP = getBagLocked(resolvedParent, &parentBag, &parentTypeSpecFlags);
4386 const size_t NT = ((NP >= 0) ? NP : 0) + N;
4387 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*NT);
4392 memcpy(set+1, parentBag, NP*sizeof(bag_entry));
4394 if (kDebugTableNoisy) {
4395 ALOGI("Initialized new bag with %zd inherited attributes.\n", NP);
4398 if (kDebugTableNoisy) {
4399 ALOGI("Initialized new bag with no inherited attributes.\n");
4403 set->availAttrs = NT;
4404 set->typeSpecFlags = parentTypeSpecFlags;
4406 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*N);
4411 set->availAttrs = N;
4412 set->typeSpecFlags = 0;
4415 set->typeSpecFlags |= entry.specFlags;
4417 // Now merge in the new attributes...
4418 size_t curOff = (reinterpret_cast<uintptr_t>(entry.entry) - reinterpret_cast<uintptr_t>(entry.type))
4419 + dtohs(entry.entry->size);
4420 const ResTable_map* map;
4421 bag_entry* entries = (bag_entry*)(set+1);
4422 size_t curEntry = 0;
4424 if (kDebugTableNoisy) {
4425 ALOGI("Starting with set %p, entries=%p, avail=%zu\n", set, entries, set->availAttrs);
4427 while (pos < count) {
4428 if (kDebugTableNoisy) {
4429 ALOGI("Now at %p\n", (void*)curOff);
4432 if (curOff > (dtohl(entry.type->header.size)-sizeof(ResTable_map))) {
4433 ALOGW("ResTable_map at %d is beyond type chunk data %d",
4434 (int)curOff, dtohl(entry.type->header.size));
4438 map = (const ResTable_map*)(((const uint8_t*)entry.type) + curOff);
4441 uint32_t newName = htodl(map->name.ident);
4442 if (!Res_INTERNALID(newName)) {
4443 // Attributes don't have a resource id as the name. They specify
4444 // other data, which would be wrong to change via a lookup.
4445 if (grp->dynamicRefTable.lookupResourceId(&newName) != NO_ERROR) {
4446 ALOGE("Failed resolving ResTable_map name at %d with ident 0x%08x",
4447 (int) curOff, (int) newName);
4449 return UNKNOWN_ERROR;
4454 uint32_t oldName = 0;
4455 while ((isInside=(curEntry < set->numAttrs))
4456 && (oldName=entries[curEntry].map.name.ident) < newName) {
4457 if (kDebugTableNoisy) {
4458 ALOGI("#%zu: Keeping existing attribute: 0x%08x\n",
4459 curEntry, entries[curEntry].map.name.ident);
4464 if ((!isInside) || oldName != newName) {
4465 // This is a new attribute... figure out what to do with it.
4466 if (set->numAttrs >= set->availAttrs) {
4467 // Need to alloc more memory...
4468 const size_t newAvail = set->availAttrs+N;
4470 set = (bag_set*)realloc(set,
4472 + sizeof(bag_entry)*newAvail);
4477 set->availAttrs = newAvail;
4478 entries = (bag_entry*)(set+1);
4479 if (kDebugTableNoisy) {
4480 ALOGI("Reallocated set %p, entries=%p, avail=%zu\n",
4481 set, entries, set->availAttrs);
4485 // Going in the middle, need to make space.
4486 memmove(entries+curEntry+1, entries+curEntry,
4487 sizeof(bag_entry)*(set->numAttrs-curEntry));
4490 if (kDebugTableNoisy) {
4491 ALOGI("#%zu: Inserting new attribute: 0x%08x\n", curEntry, newName);
4494 if (kDebugTableNoisy) {
4495 ALOGI("#%zu: Replacing existing attribute: 0x%08x\n", curEntry, oldName);
4499 bag_entry* cur = entries+curEntry;
4501 cur->stringBlock = entry.package->header->index;
4502 cur->map.name.ident = newName;
4503 cur->map.value.copyFrom_dtoh(map->value);
4504 status_t err = grp->dynamicRefTable.lookupResourceValue(&cur->map.value);
4505 if (err != NO_ERROR) {
4506 ALOGE("Reference item(0x%08x) in bag could not be resolved.", cur->map.value.data);
4507 return UNKNOWN_ERROR;
4510 if (kDebugTableNoisy) {
4511 ALOGI("Setting entry #%zu %p: block=%zd, name=0x%08d, type=%d, data=0x%08x\n",
4512 curEntry, cur, cur->stringBlock, cur->map.name.ident,
4513 cur->map.value.dataType, cur->map.value.data);
4519 const size_t size = dtohs(map->value.size);
4520 curOff += size + sizeof(*map)-sizeof(map->value);
4523 if (curEntry > set->numAttrs) {
4524 set->numAttrs = curEntry;
4527 // And this is it...
4530 if (outTypeSpecFlags != NULL) {
4531 *outTypeSpecFlags = set->typeSpecFlags;
4533 *outBag = (bag_entry*)(set+1);
4534 if (kDebugTableNoisy) {
4535 ALOGI("Returning %zu attrs\n", set->numAttrs);
4537 return set->numAttrs;
4542 void ResTable::setParameters(const ResTable_config* params)
4544 AutoMutex _lock(mLock);
4545 AutoMutex _lock2(mFilteredConfigLock);
4547 if (kDebugTableGetEntry) {
4548 ALOGI("Setting parameters: %s\n", params->toString().string());
4551 for (size_t p = 0; p < mPackageGroups.size(); p++) {
4552 PackageGroup* packageGroup = mPackageGroups.editItemAt(p);
4553 if (kDebugTableNoisy) {
4554 ALOGI("CLEARING BAGS FOR GROUP %zu!", p);
4556 packageGroup->clearBagCache();
4558 // Find which configurations match the set of parameters. This allows for a much
4559 // faster lookup in getEntry() if the set of values is narrowed down.
4560 for (size_t t = 0; t < packageGroup->types.size(); t++) {
4561 if (packageGroup->types[t].isEmpty()) {
4565 TypeList& typeList = packageGroup->types.editItemAt(t);
4567 // Retrieve the cache entry for this type.
4568 TypeCacheEntry& cacheEntry = packageGroup->typeCacheEntries.editItemAt(t);
4570 for (size_t ts = 0; ts < typeList.size(); ts++) {
4571 Type* type = typeList.editItemAt(ts);
4573 std::shared_ptr<Vector<const ResTable_type*>> newFilteredConfigs =
4574 std::make_shared<Vector<const ResTable_type*>>();
4576 for (size_t ti = 0; ti < type->configs.size(); ti++) {
4577 ResTable_config config;
4578 config.copyFromDtoH(type->configs[ti]->config);
4580 if (config.match(mParams)) {
4581 newFilteredConfigs->add(type->configs[ti]);
4585 if (kDebugTableNoisy) {
4586 ALOGD("Updating pkg=%zu type=%zu with %zu filtered configs",
4587 p, t, newFilteredConfigs->size());
4590 cacheEntry.filteredConfigs.add(newFilteredConfigs);
4596 void ResTable::getParameters(ResTable_config* params) const
4603 struct id_name_map {
4609 const static id_name_map ID_NAMES[] = {
4610 { ResTable_map::ATTR_TYPE, 5, { '^', 't', 'y', 'p', 'e' } },
4611 { ResTable_map::ATTR_L10N, 5, { '^', 'l', '1', '0', 'n' } },
4612 { ResTable_map::ATTR_MIN, 4, { '^', 'm', 'i', 'n' } },
4613 { ResTable_map::ATTR_MAX, 4, { '^', 'm', 'a', 'x' } },
4614 { ResTable_map::ATTR_OTHER, 6, { '^', 'o', 't', 'h', 'e', 'r' } },
4615 { ResTable_map::ATTR_ZERO, 5, { '^', 'z', 'e', 'r', 'o' } },
4616 { ResTable_map::ATTR_ONE, 4, { '^', 'o', 'n', 'e' } },
4617 { ResTable_map::ATTR_TWO, 4, { '^', 't', 'w', 'o' } },
4618 { ResTable_map::ATTR_FEW, 4, { '^', 'f', 'e', 'w' } },
4619 { ResTable_map::ATTR_MANY, 5, { '^', 'm', 'a', 'n', 'y' } },
4622 uint32_t ResTable::identifierForName(const char16_t* name, size_t nameLen,
4623 const char16_t* type, size_t typeLen,
4624 const char16_t* package,
4626 uint32_t* outTypeSpecFlags) const
4628 if (kDebugTableSuperNoisy) {
4629 printf("Identifier for name: error=%d\n", mError);
4632 // Check for internal resource identifier as the very first thing, so
4633 // that we will always find them even when there are no resources.
4634 if (name[0] == '^') {
4635 const int N = (sizeof(ID_NAMES)/sizeof(ID_NAMES[0]));
4637 for (int i=0; i<N; i++) {
4638 const id_name_map* m = ID_NAMES + i;
4640 if (len != nameLen) {
4643 for (size_t j=1; j<len; j++) {
4644 if (m->name[j] != name[j]) {
4648 if (outTypeSpecFlags) {
4649 *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC;
4656 if (name[1] == 'i' && name[2] == 'n'
4657 && name[3] == 'd' && name[4] == 'e' && name[5] == 'x'
4658 && name[6] == '_') {
4659 int index = atoi(String8(name + 7, nameLen - 7).string());
4660 if (Res_CHECKID(index)) {
4661 ALOGW("Array resource index: %d is too large.",
4665 if (outTypeSpecFlags) {
4666 *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC;
4668 return Res_MAKEARRAY(index);
4674 if (mError != NO_ERROR) {
4678 bool fakePublic = false;
4680 // Figure out the package and type we are looking in...
4682 const char16_t* packageEnd = NULL;
4683 const char16_t* typeEnd = NULL;
4684 const char16_t* const nameEnd = name+nameLen;
4685 const char16_t* p = name;
4686 while (p < nameEnd) {
4687 if (*p == ':') packageEnd = p;
4688 else if (*p == '/') typeEnd = p;
4698 if (name >= nameEnd) {
4704 packageLen = packageEnd-name;
4705 name = packageEnd+1;
4706 } else if (!package) {
4712 typeLen = typeEnd-name;
4718 if (name >= nameEnd) {
4721 nameLen = nameEnd-name;
4723 if (kDebugTableNoisy) {
4724 printf("Looking for identifier: type=%s, name=%s, package=%s\n",
4725 String8(type, typeLen).string(),
4726 String8(name, nameLen).string(),
4727 String8(package, packageLen).string());
4730 const String16 attr("attr");
4731 const String16 attrPrivate("^attr-private");
4733 const size_t NG = mPackageGroups.size();
4734 for (size_t ig=0; ig<NG; ig++) {
4735 const PackageGroup* group = mPackageGroups[ig];
4737 if (strzcmp16(package, packageLen,
4738 group->name.string(), group->name.size())) {
4739 if (kDebugTableNoisy) {
4740 printf("Skipping package group: %s\n", String8(group->name).string());
4745 const size_t packageCount = group->packages.size();
4746 for (size_t pi = 0; pi < packageCount; pi++) {
4747 const char16_t* targetType = type;
4748 size_t targetTypeLen = typeLen;
4751 ssize_t ti = group->packages[pi]->typeStrings.indexOfString(
4752 targetType, targetTypeLen);
4757 ti += group->packages[pi]->typeIdOffset;
4759 const uint32_t identifier = findEntry(group, ti, name, nameLen,
4761 if (identifier != 0) {
4762 if (fakePublic && outTypeSpecFlags) {
4763 *outTypeSpecFlags |= ResTable_typeSpec::SPEC_PUBLIC;
4767 } while (strzcmp16(attr.string(), attr.size(), targetType, targetTypeLen) == 0
4768 && (targetType = attrPrivate.string())
4769 && (targetTypeLen = attrPrivate.size())
4776 uint32_t ResTable::findEntry(const PackageGroup* group, ssize_t typeIndex, const char16_t* name,
4777 size_t nameLen, uint32_t* outTypeSpecFlags) const {
4778 const TypeList& typeList = group->types[typeIndex];
4779 const size_t typeCount = typeList.size();
4780 for (size_t i = 0; i < typeCount; i++) {
4781 const Type* t = typeList[i];
4782 const ssize_t ei = t->package->keyStrings.indexOfString(name, nameLen);
4787 const size_t configCount = t->configs.size();
4788 for (size_t j = 0; j < configCount; j++) {
4789 const TypeVariant tv(t->configs[j]);
4790 for (TypeVariant::iterator iter = tv.beginEntries();
4791 iter != tv.endEntries();
4793 const ResTable_entry* entry = *iter;
4794 if (entry == NULL) {
4798 if (dtohl(entry->key.index) == (size_t) ei) {
4799 uint32_t resId = Res_MAKEID(group->id - 1, typeIndex, iter.index());
4800 if (outTypeSpecFlags) {
4802 if (getEntry(group, typeIndex, iter.index(), NULL, &result) != NO_ERROR) {
4803 ALOGW("Failed to find spec flags for 0x%08x", resId);
4806 *outTypeSpecFlags = result.specFlags;
4816 bool ResTable::expandResourceRef(const char16_t* refStr, size_t refLen,
4817 String16* outPackage,
4820 const String16* defType,
4821 const String16* defPackage,
4822 const char** outErrorMsg,
4823 bool* outPublicOnly)
4825 const char16_t* packageEnd = NULL;
4826 const char16_t* typeEnd = NULL;
4827 const char16_t* p = refStr;
4828 const char16_t* const end = p + refLen;
4830 if (*p == ':') packageEnd = p;
4831 else if (*p == '/') {
4840 if (outPublicOnly != NULL) {
4841 *outPublicOnly = true;
4845 if (outPublicOnly != NULL) {
4846 *outPublicOnly = false;
4851 *outPackage = String16(p, packageEnd-p);
4856 *outErrorMsg = "No resource package specified";
4860 *outPackage = *defPackage;
4863 *outType = String16(p, typeEnd-p);
4868 *outErrorMsg = "No resource type specified";
4872 *outType = *defType;
4874 *outName = String16(p, end-p);
4875 if(**outPackage == 0) {
4877 *outErrorMsg = "Resource package cannot be an empty string";
4881 if(**outType == 0) {
4883 *outErrorMsg = "Resource type cannot be an empty string";
4887 if(**outName == 0) {
4889 *outErrorMsg = "Resource id cannot be an empty string";
4896 static uint32_t get_hex(char c, bool* outError)
4898 if (c >= '0' && c <= '9') {
4900 } else if (c >= 'a' && c <= 'f') {
4901 return c - 'a' + 0xa;
4902 } else if (c >= 'A' && c <= 'F') {
4903 return c - 'A' + 0xa;
4918 static const unit_entry unitNames[] = {
4919 { "px", strlen("px"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PX, 1.0f },
4920 { "dip", strlen("dip"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
4921 { "dp", strlen("dp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
4922 { "sp", strlen("sp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_SP, 1.0f },
4923 { "pt", strlen("pt"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PT, 1.0f },
4924 { "in", strlen("in"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_IN, 1.0f },
4925 { "mm", strlen("mm"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_MM, 1.0f },
4926 { "%", strlen("%"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION, 1.0f/100 },
4927 { "%p", strlen("%p"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION_PARENT, 1.0f/100 },
4928 { NULL, 0, 0, 0, 0 }
4931 static bool parse_unit(const char* str, Res_value* outValue,
4932 float* outScale, const char** outEnd)
4934 const char* end = str;
4935 while (*end != 0 && !isspace((unsigned char)*end)) {
4938 const size_t len = end-str;
4940 const char* realEnd = end;
4941 while (*realEnd != 0 && isspace((unsigned char)*realEnd)) {
4944 if (*realEnd != 0) {
4948 const unit_entry* cur = unitNames;
4950 if (len == cur->len && strncmp(cur->name, str, len) == 0) {
4951 outValue->dataType = cur->type;
4952 outValue->data = cur->unit << Res_value::COMPLEX_UNIT_SHIFT;
4953 *outScale = cur->scale;
4955 //printf("Found unit %s for %s\n", cur->name, str);
4964 bool U16StringToInt(const char16_t* s, size_t len, Res_value* outValue)
4966 while (len > 0 && isspace16(*s)) {
4984 if (s[i] < '0' || s[i] > '9') {
4988 static_assert(std::is_same<uint32_t, Res_value::data_type>::value,
4989 "Res_value::data_type has changed. The range checks in this "
4990 "function are no longer correct.");
4994 if (len > 1 && s[i] == '0' && s[i+1] == 'x') {
5008 while (i < len && !error) {
5009 val = (val*16) + get_hex(s[i], &error);
5012 if (val > std::numeric_limits<uint32_t>::max()) {
5022 if (s[i] < '0' || s[i] > '9') {
5025 val = (val*10) + s[i]-'0';
5028 if ((neg && -val < std::numeric_limits<int32_t>::min()) ||
5029 (!neg && val > std::numeric_limits<int32_t>::max())) {
5035 if (neg) val = -val;
5037 while (i < len && isspace16(s[i])) {
5046 outValue->dataType =
5047 isHex ? outValue->TYPE_INT_HEX : outValue->TYPE_INT_DEC;
5048 outValue->data = static_cast<Res_value::data_type>(val);
5053 bool ResTable::stringToInt(const char16_t* s, size_t len, Res_value* outValue)
5055 return U16StringToInt(s, len, outValue);
5058 bool ResTable::stringToFloat(const char16_t* s, size_t len, Res_value* outValue)
5060 while (len > 0 && isspace16(*s)) {
5071 while (len > 0 && *s != 0 && i < 126) {
5082 if ((buf[0] < '0' || buf[0] > '9') && buf[0] != '.' && buf[0] != '-' && buf[0] != '+') {
5088 float f = strtof(buf, (char**)&end);
5090 if (*end != 0 && !isspace((unsigned char)*end)) {
5091 // Might be a unit...
5093 if (parse_unit(end, outValue, &scale, &end)) {
5095 const bool neg = f < 0;
5097 uint64_t bits = (uint64_t)(f*(1<<23)+.5f);
5100 if ((bits&0x7fffff) == 0) {
5101 // Always use 23p0 if there is no fraction, just to make
5102 // things easier to read.
5103 radix = Res_value::COMPLEX_RADIX_23p0;
5105 } else if ((bits&0xffffffffff800000LL) == 0) {
5106 // Magnitude is zero -- can fit in 0 bits of precision.
5107 radix = Res_value::COMPLEX_RADIX_0p23;
5109 } else if ((bits&0xffffffff80000000LL) == 0) {
5110 // Magnitude can fit in 8 bits of precision.
5111 radix = Res_value::COMPLEX_RADIX_8p15;
5113 } else if ((bits&0xffffff8000000000LL) == 0) {
5114 // Magnitude can fit in 16 bits of precision.
5115 radix = Res_value::COMPLEX_RADIX_16p7;
5118 // Magnitude needs entire range, so no fractional part.
5119 radix = Res_value::COMPLEX_RADIX_23p0;
5122 int32_t mantissa = (int32_t)(
5123 (bits>>shift) & Res_value::COMPLEX_MANTISSA_MASK);
5125 mantissa = (-mantissa) & Res_value::COMPLEX_MANTISSA_MASK;
5128 (radix<<Res_value::COMPLEX_RADIX_SHIFT)
5129 | (mantissa<<Res_value::COMPLEX_MANTISSA_SHIFT);
5130 //printf("Input value: %f 0x%016Lx, mult: %f, radix: %d, shift: %d, final: 0x%08x\n",
5131 // f * (neg ? -1 : 1), bits, f*(1<<23),
5132 // radix, shift, outValue->data);
5138 while (*end != 0 && isspace((unsigned char)*end)) {
5144 outValue->dataType = outValue->TYPE_FLOAT;
5145 *(float*)(&outValue->data) = f;
5153 bool ResTable::stringToValue(Res_value* outValue, String16* outString,
5154 const char16_t* s, size_t len,
5155 bool preserveSpaces, bool coerceType,
5157 const String16* defType,
5158 const String16* defPackage,
5160 void* accessorCookie,
5162 bool enforcePrivate) const
5164 bool localizationSetting = accessor != NULL && accessor->getLocalizationSetting();
5165 const char* errorMsg = NULL;
5167 outValue->size = sizeof(Res_value);
5170 // First strip leading/trailing whitespace. Do this before handling
5171 // escapes, so they can be used to force whitespace into the string.
5172 if (!preserveSpaces) {
5173 while (len > 0 && isspace16(*s)) {
5177 while (len > 0 && isspace16(s[len-1])) {
5180 // If the string ends with '\', then we keep the space after it.
5181 if (len > 0 && s[len-1] == '\\' && s[len] != 0) {
5186 //printf("Value for: %s\n", String8(s, len).string());
5188 uint32_t l10nReq = ResTable_map::L10N_NOT_REQUIRED;
5189 uint32_t attrMin = 0x80000000, attrMax = 0x7fffffff;
5190 bool fromAccessor = false;
5191 if (attrID != 0 && !Res_INTERNALID(attrID)) {
5192 const ssize_t p = getResourcePackageIndex(attrID);
5193 const bag_entry* bag;
5194 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
5195 //printf("For attr 0x%08x got bag of %d\n", attrID, cnt);
5198 //printf("Entry 0x%08x = 0x%08x\n", bag->map.name.ident, bag->map.value.data);
5199 switch (bag->map.name.ident) {
5200 case ResTable_map::ATTR_TYPE:
5201 attrType = bag->map.value.data;
5203 case ResTable_map::ATTR_MIN:
5204 attrMin = bag->map.value.data;
5206 case ResTable_map::ATTR_MAX:
5207 attrMax = bag->map.value.data;
5209 case ResTable_map::ATTR_L10N:
5210 l10nReq = bag->map.value.data;
5217 } else if (accessor && accessor->getAttributeType(attrID, &attrType)) {
5218 fromAccessor = true;
5219 if (attrType == ResTable_map::TYPE_ENUM
5220 || attrType == ResTable_map::TYPE_FLAGS
5221 || attrType == ResTable_map::TYPE_INTEGER) {
5222 accessor->getAttributeMin(attrID, &attrMin);
5223 accessor->getAttributeMax(attrID, &attrMax);
5225 if (localizationSetting) {
5226 l10nReq = accessor->getAttributeL10N(attrID);
5231 const bool canStringCoerce =
5232 coerceType && (attrType&ResTable_map::TYPE_STRING) != 0;
5235 outValue->dataType = outValue->TYPE_REFERENCE;
5237 // Note: we don't check attrType here because the reference can
5238 // be to any other type; we just need to count on the client making
5239 // sure the referenced type is correct.
5241 //printf("Looking up ref: %s\n", String8(s, len).string());
5243 // It's a reference!
5244 if (len == 5 && s[1]=='n' && s[2]=='u' && s[3]=='l' && s[4]=='l') {
5245 // Special case @null as undefined. This will be converted by
5246 // AssetManager to TYPE_NULL with data DATA_NULL_UNDEFINED.
5249 } else if (len == 6 && s[1]=='e' && s[2]=='m' && s[3]=='p' && s[4]=='t' && s[5]=='y') {
5250 // Special case @empty as explicitly defined empty value.
5251 outValue->dataType = Res_value::TYPE_NULL;
5252 outValue->data = Res_value::DATA_NULL_EMPTY;
5255 bool createIfNotFound = false;
5256 const char16_t* resourceRefName;
5257 int resourceNameLen;
5258 if (len > 2 && s[1] == '+') {
5259 createIfNotFound = true;
5260 resourceRefName = s + 2;
5261 resourceNameLen = len - 2;
5262 } else if (len > 2 && s[1] == '*') {
5263 enforcePrivate = false;
5264 resourceRefName = s + 2;
5265 resourceNameLen = len - 2;
5267 createIfNotFound = false;
5268 resourceRefName = s + 1;
5269 resourceNameLen = len - 1;
5271 String16 package, type, name;
5272 if (!expandResourceRef(resourceRefName,resourceNameLen, &package, &type, &name,
5273 defType, defPackage, &errorMsg)) {
5274 if (accessor != NULL) {
5275 accessor->reportError(accessorCookie, errorMsg);
5280 uint32_t specFlags = 0;
5281 uint32_t rid = identifierForName(name.string(), name.size(), type.string(),
5282 type.size(), package.string(), package.size(), &specFlags);
5284 if (enforcePrivate) {
5285 if (accessor == NULL || accessor->getAssetsPackage() != package) {
5286 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
5287 if (accessor != NULL) {
5288 accessor->reportError(accessorCookie, "Resource is not public.");
5297 accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
5298 Res_GETTYPE(rid), Res_GETENTRY(rid));
5299 if (kDebugTableNoisy) {
5300 ALOGI("Incl %s:%s/%s: 0x%08x\n",
5301 String8(package).string(), String8(type).string(),
5302 String8(name).string(), rid);
5306 uint32_t packageId = Res_GETPACKAGE(rid) + 1;
5307 if (packageId != APP_PACKAGE_ID && packageId != SYS_PACKAGE_ID) {
5308 outValue->dataType = Res_value::TYPE_DYNAMIC_REFERENCE;
5310 outValue->data = rid;
5315 uint32_t rid = accessor->getCustomResourceWithCreation(package, type, name,
5318 if (kDebugTableNoisy) {
5319 ALOGI("Pckg %s:%s/%s: 0x%08x\n",
5320 String8(package).string(), String8(type).string(),
5321 String8(name).string(), rid);
5323 uint32_t packageId = Res_GETPACKAGE(rid) + 1;
5324 if (packageId == 0x00) {
5325 outValue->data = rid;
5326 outValue->dataType = Res_value::TYPE_DYNAMIC_REFERENCE;
5328 } else if (packageId == APP_PACKAGE_ID || packageId == SYS_PACKAGE_ID) {
5329 // We accept packageId's generated as 0x01 in order to support
5330 // building the android system resources
5331 outValue->data = rid;
5338 if (accessor != NULL) {
5339 accessor->reportError(accessorCookie, "No resource found that matches the given name");
5344 // if we got to here, and localization is required and it's not a reference,
5345 // complain and bail.
5346 if (l10nReq == ResTable_map::L10N_SUGGESTED) {
5347 if (localizationSetting) {
5348 if (accessor != NULL) {
5349 accessor->reportError(accessorCookie, "This attribute must be localized.");
5355 // It's a color! Convert to an integer of the form 0xaarrggbb.
5359 outValue->dataType = outValue->TYPE_INT_COLOR_RGB4;
5360 color |= 0xFF000000;
5361 color |= get_hex(s[1], &error) << 20;
5362 color |= get_hex(s[1], &error) << 16;
5363 color |= get_hex(s[2], &error) << 12;
5364 color |= get_hex(s[2], &error) << 8;
5365 color |= get_hex(s[3], &error) << 4;
5366 color |= get_hex(s[3], &error);
5367 } else if (len == 5) {
5368 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB4;
5369 color |= get_hex(s[1], &error) << 28;
5370 color |= get_hex(s[1], &error) << 24;
5371 color |= get_hex(s[2], &error) << 20;
5372 color |= get_hex(s[2], &error) << 16;
5373 color |= get_hex(s[3], &error) << 12;
5374 color |= get_hex(s[3], &error) << 8;
5375 color |= get_hex(s[4], &error) << 4;
5376 color |= get_hex(s[4], &error);
5377 } else if (len == 7) {
5378 outValue->dataType = outValue->TYPE_INT_COLOR_RGB8;
5379 color |= 0xFF000000;
5380 color |= get_hex(s[1], &error) << 20;
5381 color |= get_hex(s[2], &error) << 16;
5382 color |= get_hex(s[3], &error) << 12;
5383 color |= get_hex(s[4], &error) << 8;
5384 color |= get_hex(s[5], &error) << 4;
5385 color |= get_hex(s[6], &error);
5386 } else if (len == 9) {
5387 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB8;
5388 color |= get_hex(s[1], &error) << 28;
5389 color |= get_hex(s[2], &error) << 24;
5390 color |= get_hex(s[3], &error) << 20;
5391 color |= get_hex(s[4], &error) << 16;
5392 color |= get_hex(s[5], &error) << 12;
5393 color |= get_hex(s[6], &error) << 8;
5394 color |= get_hex(s[7], &error) << 4;
5395 color |= get_hex(s[8], &error);
5400 if ((attrType&ResTable_map::TYPE_COLOR) == 0) {
5401 if (!canStringCoerce) {
5402 if (accessor != NULL) {
5403 accessor->reportError(accessorCookie,
5404 "Color types not allowed");
5409 outValue->data = color;
5410 //printf("Color input=%s, output=0x%x\n", String8(s, len).string(), color);
5414 if ((attrType&ResTable_map::TYPE_COLOR) != 0) {
5415 if (accessor != NULL) {
5416 accessor->reportError(accessorCookie, "Color value not valid --"
5417 " must be #rgb, #argb, #rrggbb, or #aarrggbb");
5420 fprintf(stderr, "%s: Color ID %s value %s is not valid\n",
5421 "Resource File", //(const char*)in->getPrintableSource(),
5422 String8(*curTag).string(),
5423 String8(s, len).string());
5431 outValue->dataType = outValue->TYPE_ATTRIBUTE;
5433 // Note: we don't check attrType here because the reference can
5434 // be to any other type; we just need to count on the client making
5435 // sure the referenced type is correct.
5437 //printf("Looking up attr: %s\n", String8(s, len).string());
5439 static const String16 attr16("attr");
5440 String16 package, type, name;
5441 if (!expandResourceRef(s+1, len-1, &package, &type, &name,
5442 &attr16, defPackage, &errorMsg)) {
5443 if (accessor != NULL) {
5444 accessor->reportError(accessorCookie, errorMsg);
5449 //printf("Pkg: %s, Type: %s, Name: %s\n",
5450 // String8(package).string(), String8(type).string(),
5451 // String8(name).string());
5452 uint32_t specFlags = 0;
5454 identifierForName(name.string(), name.size(),
5455 type.string(), type.size(),
5456 package.string(), package.size(), &specFlags);
5458 if (enforcePrivate) {
5459 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
5460 if (accessor != NULL) {
5461 accessor->reportError(accessorCookie, "Attribute is not public.");
5469 accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
5470 Res_GETTYPE(rid), Res_GETENTRY(rid));
5473 uint32_t packageId = Res_GETPACKAGE(rid) + 1;
5474 if (packageId != APP_PACKAGE_ID && packageId != SYS_PACKAGE_ID) {
5475 outValue->dataType = Res_value::TYPE_DYNAMIC_ATTRIBUTE;
5477 outValue->data = rid;
5482 uint32_t rid = accessor->getCustomResource(package, type, name);
5484 uint32_t packageId = Res_GETPACKAGE(rid) + 1;
5485 if (packageId == 0x00) {
5486 outValue->data = rid;
5487 outValue->dataType = Res_value::TYPE_DYNAMIC_ATTRIBUTE;
5489 } else if (packageId == APP_PACKAGE_ID || packageId == SYS_PACKAGE_ID) {
5490 // We accept packageId's generated as 0x01 in order to support
5491 // building the android system resources
5492 outValue->data = rid;
5498 if (accessor != NULL) {
5499 accessor->reportError(accessorCookie, "No resource found that matches the given name");
5504 if (stringToInt(s, len, outValue)) {
5505 if ((attrType&ResTable_map::TYPE_INTEGER) == 0) {
5506 // If this type does not allow integers, but does allow floats,
5507 // fall through on this error case because the float type should
5508 // be able to accept any integer value.
5509 if (!canStringCoerce && (attrType&ResTable_map::TYPE_FLOAT) == 0) {
5510 if (accessor != NULL) {
5511 accessor->reportError(accessorCookie, "Integer types not allowed");
5516 if (((int32_t)outValue->data) < ((int32_t)attrMin)
5517 || ((int32_t)outValue->data) > ((int32_t)attrMax)) {
5518 if (accessor != NULL) {
5519 accessor->reportError(accessorCookie, "Integer value out of range");
5527 if (stringToFloat(s, len, outValue)) {
5528 if (outValue->dataType == Res_value::TYPE_DIMENSION) {
5529 if ((attrType&ResTable_map::TYPE_DIMENSION) != 0) {
5532 if (!canStringCoerce) {
5533 if (accessor != NULL) {
5534 accessor->reportError(accessorCookie, "Dimension types not allowed");
5538 } else if (outValue->dataType == Res_value::TYPE_FRACTION) {
5539 if ((attrType&ResTable_map::TYPE_FRACTION) != 0) {
5542 if (!canStringCoerce) {
5543 if (accessor != NULL) {
5544 accessor->reportError(accessorCookie, "Fraction types not allowed");
5548 } else if ((attrType&ResTable_map::TYPE_FLOAT) == 0) {
5549 if (!canStringCoerce) {
5550 if (accessor != NULL) {
5551 accessor->reportError(accessorCookie, "Float types not allowed");
5561 if ((s[0] == 't' || s[0] == 'T') &&
5562 (s[1] == 'r' || s[1] == 'R') &&
5563 (s[2] == 'u' || s[2] == 'U') &&
5564 (s[3] == 'e' || s[3] == 'E')) {
5565 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
5566 if (!canStringCoerce) {
5567 if (accessor != NULL) {
5568 accessor->reportError(accessorCookie, "Boolean types not allowed");
5573 outValue->dataType = outValue->TYPE_INT_BOOLEAN;
5574 outValue->data = (uint32_t)-1;
5581 if ((s[0] == 'f' || s[0] == 'F') &&
5582 (s[1] == 'a' || s[1] == 'A') &&
5583 (s[2] == 'l' || s[2] == 'L') &&
5584 (s[3] == 's' || s[3] == 'S') &&
5585 (s[4] == 'e' || s[4] == 'E')) {
5586 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
5587 if (!canStringCoerce) {
5588 if (accessor != NULL) {
5589 accessor->reportError(accessorCookie, "Boolean types not allowed");
5594 outValue->dataType = outValue->TYPE_INT_BOOLEAN;
5601 if ((attrType&ResTable_map::TYPE_ENUM) != 0) {
5602 const ssize_t p = getResourcePackageIndex(attrID);
5603 const bag_entry* bag;
5604 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
5605 //printf("Got %d for enum\n", cnt);
5607 resource_name rname;
5609 if (!Res_INTERNALID(bag->map.name.ident)) {
5610 //printf("Trying attr #%08x\n", bag->map.name.ident);
5611 if (getResourceName(bag->map.name.ident, false, &rname)) {
5613 printf("Matching %s against %s (0x%08x)\n",
5614 String8(s, len).string(),
5615 String8(rname.name, rname.nameLen).string(),
5616 bag->map.name.ident);
5618 if (strzcmp16(s, len, rname.name, rname.nameLen) == 0) {
5619 outValue->dataType = bag->map.value.dataType;
5620 outValue->data = bag->map.value.data;
5634 if (accessor->getAttributeEnum(attrID, s, len, outValue)) {
5640 if ((attrType&ResTable_map::TYPE_FLAGS) != 0) {
5641 const ssize_t p = getResourcePackageIndex(attrID);
5642 const bag_entry* bag;
5643 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
5644 //printf("Got %d for flags\n", cnt);
5646 bool failed = false;
5647 resource_name rname;
5648 outValue->dataType = Res_value::TYPE_INT_HEX;
5650 const char16_t* end = s + len;
5651 const char16_t* pos = s;
5652 while (pos < end && !failed) {
5653 const char16_t* start = pos;
5655 while (pos < end && *pos != '|') {
5658 //printf("Looking for: %s\n", String8(start, pos-start).string());
5659 const bag_entry* bagi = bag;
5661 for (i=0; i<cnt; i++, bagi++) {
5662 if (!Res_INTERNALID(bagi->map.name.ident)) {
5663 //printf("Trying attr #%08x\n", bagi->map.name.ident);
5664 if (getResourceName(bagi->map.name.ident, false, &rname)) {
5666 printf("Matching %s against %s (0x%08x)\n",
5667 String8(start,pos-start).string(),
5668 String8(rname.name, rname.nameLen).string(),
5669 bagi->map.name.ident);
5671 if (strzcmp16(start, pos-start, rname.name, rname.nameLen) == 0) {
5672 outValue->data |= bagi->map.value.data;
5679 // Didn't find this flag identifier.
5688 //printf("Final flag value: 0x%lx\n", outValue->data);
5695 if (accessor->getAttributeFlags(attrID, s, len, outValue)) {
5696 //printf("Final flag value: 0x%lx\n", outValue->data);
5702 if ((attrType&ResTable_map::TYPE_STRING) == 0) {
5703 if (accessor != NULL) {
5704 accessor->reportError(accessorCookie, "String types not allowed");
5709 // Generic string handling...
5710 outValue->dataType = outValue->TYPE_STRING;
5712 bool failed = collectString(outString, s, len, preserveSpaces, &errorMsg);
5713 if (accessor != NULL) {
5714 accessor->reportError(accessorCookie, errorMsg);
5722 bool ResTable::collectString(String16* outString,
5723 const char16_t* s, size_t len,
5724 bool preserveSpaces,
5725 const char** outErrorMsg,
5731 const char16_t* p = s;
5732 while (p < (s+len)) {
5733 while (p < (s+len)) {
5734 const char16_t c = *p;
5738 if (!preserveSpaces) {
5739 if (quoted == 0 && isspace16(c)
5740 && (c != ' ' || isspace16(*(p+1)))) {
5743 if (c == '"' && (quoted == 0 || quoted == '"')) {
5746 if (c == '\'' && (quoted == 0 || quoted == '\'')) {
5748 * In practice, when people write ' instead of \'
5749 * in a string, they are doing it by accident
5750 * instead of really meaning to use ' as a quoting
5751 * character. Warn them so they don't lose it.
5754 *outErrorMsg = "Apostrophe not preceded by \\";
5763 tmp.append(String16(s, p-s));
5765 if (!preserveSpaces && (*p == '"' || *p == '\'')) {
5772 } else if (!preserveSpaces && isspace16(*p)) {
5773 // Space outside of a quote -- consume all spaces and
5774 // leave a single plain space char.
5775 tmp.append(String16(" "));
5777 while (p < (s+len) && isspace16(*p)) {
5780 } else if (*p == '\\') {
5785 tmp.append(String16("\t"));
5788 tmp.append(String16("\n"));
5791 tmp.append(String16("#"));
5794 tmp.append(String16("@"));
5797 tmp.append(String16("?"));
5800 tmp.append(String16("\""));
5803 tmp.append(String16("'"));
5806 tmp.append(String16("\\"));
5812 while (i < 4 && p[1] != 0) {
5816 if (*p >= '0' && *p <= '9') {
5818 } else if (*p >= 'a' && *p <= 'f') {
5820 } else if (*p >= 'A' && *p <= 'F') {
5824 *outErrorMsg = "Bad character in \\u unicode escape sequence";
5830 tmp.append(String16(&chr, 1));
5833 // ignore unknown escape chars.
5844 if (tmp.size() != 0) {
5846 tmp.append(String16(s, len));
5849 outString->append(tmp);
5851 outString->setTo(tmp);
5855 outString->append(String16(s, len));
5857 outString->setTo(s, len);
5864 size_t ResTable::getBasePackageCount() const
5866 if (mError != NO_ERROR) {
5869 return mPackageGroups.size();
5872 const String16 ResTable::getBasePackageName(size_t idx) const
5874 if (mError != NO_ERROR) {
5877 LOG_FATAL_IF(idx >= mPackageGroups.size(),
5878 "Requested package index %d past package count %d",
5879 (int)idx, (int)mPackageGroups.size());
5880 return mPackageGroups[idx]->name;
5883 uint32_t ResTable::getBasePackageId(size_t idx) const
5885 if (mError != NO_ERROR) {
5888 LOG_FATAL_IF(idx >= mPackageGroups.size(),
5889 "Requested package index %d past package count %d",
5890 (int)idx, (int)mPackageGroups.size());
5891 return mPackageGroups[idx]->id;
5894 uint32_t ResTable::getLastTypeIdForPackage(size_t idx) const
5896 if (mError != NO_ERROR) {
5899 LOG_FATAL_IF(idx >= mPackageGroups.size(),
5900 "Requested package index %d past package count %d",
5901 (int)idx, (int)mPackageGroups.size());
5902 const PackageGroup* const group = mPackageGroups[idx];
5903 return group->largestTypeId;
5906 size_t ResTable::getTableCount() const
5908 return mHeaders.size();
5911 const ResStringPool* ResTable::getTableStringBlock(size_t index) const
5913 return &mHeaders[index]->values;
5916 int32_t ResTable::getTableCookie(size_t index) const
5918 return mHeaders[index]->cookie;
5921 const DynamicRefTable* ResTable::getDynamicRefTableForCookie(int32_t cookie) const
5923 const size_t N = mPackageGroups.size();
5924 for (size_t i = 0; i < N; i++) {
5925 const PackageGroup* pg = mPackageGroups[i];
5926 size_t M = pg->packages.size();
5927 for (size_t j = 0; j < M; j++) {
5928 if (pg->packages[j]->header->cookie == cookie) {
5929 return &pg->dynamicRefTable;
5936 static bool compareResTableConfig(const ResTable_config& a, const ResTable_config& b) {
5937 return a.compare(b) < 0;
5940 template <typename Func>
5941 void ResTable::forEachConfiguration(bool ignoreMipmap, bool ignoreAndroidPackage,
5942 bool includeSystemConfigs, const Func& f) const {
5943 const size_t packageCount = mPackageGroups.size();
5944 const String16 android("android");
5945 for (size_t i = 0; i < packageCount; i++) {
5946 const PackageGroup* packageGroup = mPackageGroups[i];
5947 if (ignoreAndroidPackage && android == packageGroup->name) {
5950 if (!includeSystemConfigs && packageGroup->isSystemAsset) {
5953 const size_t typeCount = packageGroup->types.size();
5954 for (size_t j = 0; j < typeCount; j++) {
5955 const TypeList& typeList = packageGroup->types[j];
5956 const size_t numTypes = typeList.size();
5957 for (size_t k = 0; k < numTypes; k++) {
5958 const Type* type = typeList[k];
5959 const ResStringPool& typeStrings = type->package->typeStrings;
5960 if (ignoreMipmap && typeStrings.string8ObjectAt(
5961 type->typeSpec->id - 1) == "mipmap") {
5965 const size_t numConfigs = type->configs.size();
5966 for (size_t m = 0; m < numConfigs; m++) {
5967 const ResTable_type* config = type->configs[m];
5968 ResTable_config cfg;
5969 memset(&cfg, 0, sizeof(ResTable_config));
5970 cfg.copyFromDtoH(config->config);
5979 void ResTable::getConfigurations(Vector<ResTable_config>* configs, bool ignoreMipmap,
5980 bool ignoreAndroidPackage, bool includeSystemConfigs) const {
5981 auto func = [&](const ResTable_config& cfg) {
5982 const auto beginIter = configs->begin();
5983 const auto endIter = configs->end();
5985 auto iter = std::lower_bound(beginIter, endIter, cfg, compareResTableConfig);
5986 if (iter == endIter || iter->compare(cfg) != 0) {
5987 configs->insertAt(cfg, std::distance(beginIter, iter));
5990 forEachConfiguration(ignoreMipmap, ignoreAndroidPackage, includeSystemConfigs, func);
5993 static bool compareString8AndCString(const String8& str, const char* cStr) {
5994 return strcmp(str.string(), cStr) < 0;
5997 void ResTable::getLocales(Vector<String8>* locales, bool includeSystemLocales,
5998 bool mergeEquivalentLangs) const {
5999 char locale[RESTABLE_MAX_LOCALE_LEN];
6001 forEachConfiguration(false, false, includeSystemLocales, [&](const ResTable_config& cfg) {
6002 cfg.getBcp47Locale(locale, mergeEquivalentLangs /* canonicalize if merging */);
6004 const auto beginIter = locales->begin();
6005 const auto endIter = locales->end();
6007 auto iter = std::lower_bound(beginIter, endIter, locale, compareString8AndCString);
6008 if (iter == endIter || strcmp(iter->string(), locale) != 0) {
6009 locales->insertAt(String8(locale), std::distance(beginIter, iter));
6014 StringPoolRef::StringPoolRef(const ResStringPool* pool, uint32_t index)
6015 : mPool(pool), mIndex(index) {}
6017 StringPoolRef::StringPoolRef()
6018 : mPool(NULL), mIndex(0) {}
6020 const char* StringPoolRef::string8(size_t* outLen) const {
6021 if (mPool != NULL) {
6022 return mPool->string8At(mIndex, outLen);
6024 if (outLen != NULL) {
6030 const char16_t* StringPoolRef::string16(size_t* outLen) const {
6031 if (mPool != NULL) {
6032 return mPool->stringAt(mIndex, outLen);
6034 if (outLen != NULL) {
6040 bool ResTable::getResourceFlags(uint32_t resID, uint32_t* outFlags) const {
6041 if (mError != NO_ERROR) {
6045 const ssize_t p = getResourcePackageIndex(resID);
6046 const int t = Res_GETTYPE(resID);
6047 const int e = Res_GETENTRY(resID);
6050 if (Res_GETPACKAGE(resID)+1 == 0) {
6051 ALOGW("No package identifier when getting flags for resource number 0x%08x", resID);
6053 ALOGW("No known package when getting flags for resource number 0x%08x", resID);
6058 ALOGW("No type identifier when getting flags for resource number 0x%08x", resID);
6062 const PackageGroup* const grp = mPackageGroups[p];
6064 ALOGW("Bad identifier when getting flags for resource number 0x%08x", resID);
6069 status_t err = getEntry(grp, t, e, NULL, &entry);
6070 if (err != NO_ERROR) {
6074 *outFlags = entry.specFlags;
6078 static bool keyCompare(const ResTable_sparseTypeEntry& entry , uint16_t entryIdx) {
6079 return dtohs(entry.idx) < entryIdx;
6082 status_t ResTable::getEntry(
6083 const PackageGroup* packageGroup, int typeIndex, int entryIndex,
6084 const ResTable_config* config,
6085 Entry* outEntry) const
6087 const TypeList& typeList = packageGroup->types[typeIndex];
6088 if (typeList.isEmpty()) {
6089 ALOGV("Skipping entry type index 0x%02x because type is NULL!\n", typeIndex);
6093 const ResTable_type* bestType = NULL;
6094 uint32_t bestOffset = ResTable_type::NO_ENTRY;
6095 const Package* bestPackage = NULL;
6096 uint32_t specFlags = 0;
6097 uint8_t actualTypeIndex = typeIndex;
6098 ResTable_config bestConfig;
6099 memset(&bestConfig, 0, sizeof(bestConfig));
6101 // Iterate over the Types of each package.
6102 const size_t typeCount = typeList.size();
6103 for (size_t i = 0; i < typeCount; i++) {
6104 const Type* const typeSpec = typeList[i];
6106 int realEntryIndex = entryIndex;
6107 int realTypeIndex = typeIndex;
6108 bool currentTypeIsOverlay = false;
6110 // Runtime overlay packages provide a mapping of app resource
6111 // ID to package resource ID.
6112 if (typeSpec->idmapEntries.hasEntries()) {
6113 uint16_t overlayEntryIndex;
6114 if (typeSpec->idmapEntries.lookup(entryIndex, &overlayEntryIndex) != NO_ERROR) {
6115 // No such mapping exists
6118 realEntryIndex = overlayEntryIndex;
6119 realTypeIndex = typeSpec->idmapEntries.overlayTypeId() - 1;
6120 currentTypeIsOverlay = true;
6123 // Check that the entry idx is within range of the declared entry count (ResTable_typeSpec).
6124 // Particular types (ResTable_type) may be encoded with sparse entries, and so their
6125 // entryCount do not need to match.
6126 if (static_cast<size_t>(realEntryIndex) >= typeSpec->entryCount) {
6127 ALOGW("For resource 0x%08x, entry index(%d) is beyond type entryCount(%d)",
6128 Res_MAKEID(packageGroup->id - 1, typeIndex, entryIndex),
6129 entryIndex, static_cast<int>(typeSpec->entryCount));
6130 // We should normally abort here, but some legacy apps declare
6131 // resources in the 'android' package (old bug in AAPT).
6135 // Aggregate all the flags for each package that defines this entry.
6136 if (typeSpec->typeSpecFlags != NULL) {
6137 specFlags |= dtohl(typeSpec->typeSpecFlags[realEntryIndex]);
6142 const Vector<const ResTable_type*>* candidateConfigs = &typeSpec->configs;
6144 std::shared_ptr<Vector<const ResTable_type*>> filteredConfigs;
6145 if (config && memcmp(&mParams, config, sizeof(mParams)) == 0) {
6146 // Grab the lock first so we can safely get the current filtered list.
6147 AutoMutex _lock(mFilteredConfigLock);
6149 // This configuration is equal to the one we have previously cached for,
6150 // so use the filtered configs.
6152 const TypeCacheEntry& cacheEntry = packageGroup->typeCacheEntries[typeIndex];
6153 if (i < cacheEntry.filteredConfigs.size()) {
6154 if (cacheEntry.filteredConfigs[i]) {
6155 // Grab a reference to the shared_ptr so it doesn't get destroyed while
6156 // going through this list.
6157 filteredConfigs = cacheEntry.filteredConfigs[i];
6159 // Use this filtered list.
6160 candidateConfigs = filteredConfigs.get();
6165 const size_t numConfigs = candidateConfigs->size();
6166 for (size_t c = 0; c < numConfigs; c++) {
6167 const ResTable_type* const thisType = candidateConfigs->itemAt(c);
6168 if (thisType == NULL) {
6172 ResTable_config thisConfig;
6173 thisConfig.copyFromDtoH(thisType->config);
6175 // Check to make sure this one is valid for the current parameters.
6176 if (config != NULL && !thisConfig.match(*config)) {
6180 const uint32_t* const eindex = reinterpret_cast<const uint32_t*>(
6181 reinterpret_cast<const uint8_t*>(thisType) + dtohs(thisType->header.headerSize));
6183 uint32_t thisOffset;
6185 // Check if there is the desired entry in this type.
6186 if (thisType->flags & ResTable_type::FLAG_SPARSE) {
6187 // This is encoded as a sparse map, so perform a binary search.
6188 const ResTable_sparseTypeEntry* sparseIndices =
6189 reinterpret_cast<const ResTable_sparseTypeEntry*>(eindex);
6190 const ResTable_sparseTypeEntry* result = std::lower_bound(
6191 sparseIndices, sparseIndices + dtohl(thisType->entryCount), realEntryIndex,
6193 if (result == sparseIndices + dtohl(thisType->entryCount)
6194 || dtohs(result->idx) != realEntryIndex) {
6199 // Extract the offset from the entry. Each offset must be a multiple of 4
6200 // so we store it as the real offset divided by 4.
6201 thisOffset = dtohs(result->offset) * 4u;
6203 if (static_cast<uint32_t>(realEntryIndex) >= dtohl(thisType->entryCount)) {
6204 // Entry does not exist.
6208 thisOffset = dtohl(eindex[realEntryIndex]);
6211 if (thisOffset == ResTable_type::NO_ENTRY) {
6212 // There is no entry for this index and configuration.
6216 if (bestType != NULL) {
6217 // Check if this one is less specific than the last found. If so,
6218 // we will skip it. We check starting with things we most care
6219 // about to those we least care about.
6220 if (!thisConfig.isBetterThan(bestConfig, config)) {
6221 if (!currentTypeIsOverlay || thisConfig.compare(bestConfig) != 0) {
6227 bestType = thisType;
6228 bestOffset = thisOffset;
6229 bestConfig = thisConfig;
6230 bestPackage = typeSpec->package;
6231 actualTypeIndex = realTypeIndex;
6233 // If no config was specified, any type will do, so skip
6234 if (config == NULL) {
6240 if (bestType == NULL) {
6244 bestOffset += dtohl(bestType->entriesStart);
6246 if (bestOffset > (dtohl(bestType->header.size)-sizeof(ResTable_entry))) {
6247 ALOGW("ResTable_entry at 0x%x is beyond type chunk data 0x%x",
6248 bestOffset, dtohl(bestType->header.size));
6251 if ((bestOffset & 0x3) != 0) {
6252 ALOGW("ResTable_entry at 0x%x is not on an integer boundary", bestOffset);
6256 const ResTable_entry* const entry = reinterpret_cast<const ResTable_entry*>(
6257 reinterpret_cast<const uint8_t*>(bestType) + bestOffset);
6258 if (dtohs(entry->size) < sizeof(*entry)) {
6259 ALOGW("ResTable_entry size 0x%x is too small", dtohs(entry->size));
6263 if (outEntry != NULL) {
6264 outEntry->entry = entry;
6265 outEntry->config = bestConfig;
6266 outEntry->type = bestType;
6267 outEntry->specFlags = specFlags;
6268 outEntry->package = bestPackage;
6269 outEntry->typeStr = StringPoolRef(&bestPackage->typeStrings, actualTypeIndex - bestPackage->typeIdOffset);
6270 outEntry->keyStr = StringPoolRef(&bestPackage->keyStrings, dtohl(entry->key.index));
6275 status_t ResTable::parsePackage(const ResTable_package* const pkg,
6276 const Header* const header, bool appAsLib, bool isSystemAsset)
6278 const uint8_t* base = (const uint8_t*)pkg;
6279 status_t err = validate_chunk(&pkg->header, sizeof(*pkg) - sizeof(pkg->typeIdOffset),
6280 header->dataEnd, "ResTable_package");
6281 if (err != NO_ERROR) {
6282 return (mError=err);
6285 const uint32_t pkgSize = dtohl(pkg->header.size);
6287 if (dtohl(pkg->typeStrings) >= pkgSize) {
6288 ALOGW("ResTable_package type strings at 0x%x are past chunk size 0x%x.",
6289 dtohl(pkg->typeStrings), pkgSize);
6290 return (mError=BAD_TYPE);
6292 if ((dtohl(pkg->typeStrings)&0x3) != 0) {
6293 ALOGW("ResTable_package type strings at 0x%x is not on an integer boundary.",
6294 dtohl(pkg->typeStrings));
6295 return (mError=BAD_TYPE);
6297 if (dtohl(pkg->keyStrings) >= pkgSize) {
6298 ALOGW("ResTable_package key strings at 0x%x are past chunk size 0x%x.",
6299 dtohl(pkg->keyStrings), pkgSize);
6300 return (mError=BAD_TYPE);
6302 if ((dtohl(pkg->keyStrings)&0x3) != 0) {
6303 ALOGW("ResTable_package key strings at 0x%x is not on an integer boundary.",
6304 dtohl(pkg->keyStrings));
6305 return (mError=BAD_TYPE);
6308 uint32_t id = dtohl(pkg->id);
6309 KeyedVector<uint8_t, IdmapEntries> idmapEntries;
6311 if (header->resourceIDMap != NULL) {
6312 uint8_t targetPackageId = 0;
6313 status_t err = parseIdmap(header->resourceIDMap, header->resourceIDMapSize, &targetPackageId, &idmapEntries);
6314 if (err != NO_ERROR) {
6315 ALOGW("Overlay is broken");
6316 return (mError=err);
6318 id = targetPackageId;
6322 LOG_ALWAYS_FATAL("Package id out of range");
6324 } else if (id == 0 || (id == 0x7f && appAsLib) || isSystemAsset) {
6325 // This is a library or a system asset, so assign an ID
6326 id = mNextPackageId++;
6329 PackageGroup* group = NULL;
6330 Package* package = new Package(this, header, pkg);
6331 if (package == NULL) {
6332 return (mError=NO_MEMORY);
6335 err = package->typeStrings.setTo(base+dtohl(pkg->typeStrings),
6336 header->dataEnd-(base+dtohl(pkg->typeStrings)));
6337 if (err != NO_ERROR) {
6340 return (mError=err);
6343 err = package->keyStrings.setTo(base+dtohl(pkg->keyStrings),
6344 header->dataEnd-(base+dtohl(pkg->keyStrings)));
6345 if (err != NO_ERROR) {
6348 return (mError=err);
6351 size_t idx = mPackageMap[id];
6353 idx = mPackageGroups.size() + 1;
6355 char16_t tmpName[sizeof(pkg->name)/sizeof(pkg->name[0])];
6356 strcpy16_dtoh(tmpName, pkg->name, sizeof(pkg->name)/sizeof(pkg->name[0]));
6357 group = new PackageGroup(this, String16(tmpName), id, appAsLib, isSystemAsset);
6358 if (group == NULL) {
6360 return (mError=NO_MEMORY);
6363 err = mPackageGroups.add(group);
6364 if (err < NO_ERROR) {
6365 return (mError=err);
6368 mPackageMap[id] = static_cast<uint8_t>(idx);
6370 // Find all packages that reference this package
6371 size_t N = mPackageGroups.size();
6372 for (size_t i = 0; i < N; i++) {
6373 mPackageGroups[i]->dynamicRefTable.addMapping(
6374 group->name, static_cast<uint8_t>(group->id));
6377 group = mPackageGroups.itemAt(idx - 1);
6378 if (group == NULL) {
6379 return (mError=UNKNOWN_ERROR);
6383 err = group->packages.add(package);
6384 if (err < NO_ERROR) {
6385 return (mError=err);
6388 // Iterate through all chunks.
6389 const ResChunk_header* chunk =
6390 (const ResChunk_header*)(((const uint8_t*)pkg)
6391 + dtohs(pkg->header.headerSize));
6392 const uint8_t* endPos = ((const uint8_t*)pkg) + dtohs(pkg->header.size);
6393 while (((const uint8_t*)chunk) <= (endPos-sizeof(ResChunk_header)) &&
6394 ((const uint8_t*)chunk) <= (endPos-dtohl(chunk->size))) {
6395 if (kDebugTableNoisy) {
6396 ALOGV("PackageChunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n",
6397 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
6398 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)));
6400 const size_t csize = dtohl(chunk->size);
6401 const uint16_t ctype = dtohs(chunk->type);
6402 if (ctype == RES_TABLE_TYPE_SPEC_TYPE) {
6403 const ResTable_typeSpec* typeSpec = (const ResTable_typeSpec*)(chunk);
6404 err = validate_chunk(&typeSpec->header, sizeof(*typeSpec),
6405 endPos, "ResTable_typeSpec");
6406 if (err != NO_ERROR) {
6407 return (mError=err);
6410 const size_t typeSpecSize = dtohl(typeSpec->header.size);
6411 const size_t newEntryCount = dtohl(typeSpec->entryCount);
6413 if (kDebugLoadTableNoisy) {
6414 ALOGI("TypeSpec off %p: type=0x%x, headerSize=0x%x, size=%p\n",
6415 (void*)(base-(const uint8_t*)chunk),
6416 dtohs(typeSpec->header.type),
6417 dtohs(typeSpec->header.headerSize),
6418 (void*)typeSpecSize);
6420 // look for block overrun or int overflow when multiplying by 4
6421 if ((dtohl(typeSpec->entryCount) > (INT32_MAX/sizeof(uint32_t))
6422 || dtohs(typeSpec->header.headerSize)+(sizeof(uint32_t)*newEntryCount)
6424 ALOGW("ResTable_typeSpec entry index to %p extends beyond chunk end %p.",
6425 (void*)(dtohs(typeSpec->header.headerSize) + (sizeof(uint32_t)*newEntryCount)),
6426 (void*)typeSpecSize);
6427 return (mError=BAD_TYPE);
6430 if (typeSpec->id == 0) {
6431 ALOGW("ResTable_type has an id of 0.");
6432 return (mError=BAD_TYPE);
6435 if (newEntryCount > 0) {
6436 bool addToType = true;
6437 uint8_t typeIndex = typeSpec->id - 1;
6438 ssize_t idmapIndex = idmapEntries.indexOfKey(typeSpec->id);
6439 if (idmapIndex >= 0) {
6440 typeIndex = idmapEntries[idmapIndex].targetTypeId() - 1;
6441 } else if (header->resourceIDMap != NULL) {
6442 // This is an overlay, but the types in this overlay are not
6443 // overlaying anything according to the idmap. We can skip these
6444 // as they will otherwise conflict with the other resources in the package
6445 // without a mapping.
6450 TypeList& typeList = group->types.editItemAt(typeIndex);
6451 if (!typeList.isEmpty()) {
6452 const Type* existingType = typeList[0];
6453 if (existingType->entryCount != newEntryCount && idmapIndex < 0) {
6454 ALOGW("ResTable_typeSpec entry count inconsistent: "
6455 "given %d, previously %d",
6456 (int) newEntryCount, (int) existingType->entryCount);
6457 // We should normally abort here, but some legacy apps declare
6458 // resources in the 'android' package (old bug in AAPT).
6462 Type* t = new Type(header, package, newEntryCount);
6463 t->typeSpec = typeSpec;
6464 t->typeSpecFlags = (const uint32_t*)(
6465 ((const uint8_t*)typeSpec) + dtohs(typeSpec->header.headerSize));
6466 if (idmapIndex >= 0) {
6467 t->idmapEntries = idmapEntries[idmapIndex];
6470 group->largestTypeId = max(group->largestTypeId, typeSpec->id);
6473 ALOGV("Skipping empty ResTable_typeSpec for type %d", typeSpec->id);
6476 } else if (ctype == RES_TABLE_TYPE_TYPE) {
6477 const ResTable_type* type = (const ResTable_type*)(chunk);
6478 err = validate_chunk(&type->header, sizeof(*type)-sizeof(ResTable_config)+4,
6479 endPos, "ResTable_type");
6480 if (err != NO_ERROR) {
6481 return (mError=err);
6484 const uint32_t typeSize = dtohl(type->header.size);
6485 const size_t newEntryCount = dtohl(type->entryCount);
6487 if (kDebugLoadTableNoisy) {
6488 printf("Type off %p: type=0x%x, headerSize=0x%x, size=%u\n",
6489 (void*)(base-(const uint8_t*)chunk),
6490 dtohs(type->header.type),
6491 dtohs(type->header.headerSize),
6494 if (dtohs(type->header.headerSize)+(sizeof(uint32_t)*newEntryCount) > typeSize) {
6495 ALOGW("ResTable_type entry index to %p extends beyond chunk end 0x%x.",
6496 (void*)(dtohs(type->header.headerSize) + (sizeof(uint32_t)*newEntryCount)),
6498 return (mError=BAD_TYPE);
6501 if (newEntryCount != 0
6502 && dtohl(type->entriesStart) > (typeSize-sizeof(ResTable_entry))) {
6503 ALOGW("ResTable_type entriesStart at 0x%x extends beyond chunk end 0x%x.",
6504 dtohl(type->entriesStart), typeSize);
6505 return (mError=BAD_TYPE);
6508 if (type->id == 0) {
6509 ALOGW("ResTable_type has an id of 0.");
6510 return (mError=BAD_TYPE);
6513 if (newEntryCount > 0) {
6514 bool addToType = true;
6515 uint8_t typeIndex = type->id - 1;
6516 ssize_t idmapIndex = idmapEntries.indexOfKey(type->id);
6517 if (idmapIndex >= 0) {
6518 typeIndex = idmapEntries[idmapIndex].targetTypeId() - 1;
6519 } else if (header->resourceIDMap != NULL) {
6520 // This is an overlay, but the types in this overlay are not
6521 // overlaying anything according to the idmap. We can skip these
6522 // as they will otherwise conflict with the other resources in the package
6523 // without a mapping.
6528 TypeList& typeList = group->types.editItemAt(typeIndex);
6529 if (typeList.isEmpty()) {
6530 ALOGE("No TypeSpec for type %d", type->id);
6531 return (mError=BAD_TYPE);
6534 Type* t = typeList.editItemAt(typeList.size() - 1);
6535 if (t->package != package) {
6536 ALOGE("No TypeSpec for type %d", type->id);
6537 return (mError=BAD_TYPE);
6540 t->configs.add(type);
6542 if (kDebugTableGetEntry) {
6543 ResTable_config thisConfig;
6544 thisConfig.copyFromDtoH(type->config);
6545 ALOGI("Adding config to type %d: %s\n", type->id,
6546 thisConfig.toString().string());
6550 ALOGV("Skipping empty ResTable_type for type %d", type->id);
6553 } else if (ctype == RES_TABLE_LIBRARY_TYPE) {
6554 if (group->dynamicRefTable.entries().size() == 0) {
6555 status_t err = group->dynamicRefTable.load((const ResTable_lib_header*) chunk);
6556 if (err != NO_ERROR) {
6557 return (mError=err);
6560 // Fill in the reference table with the entries we already know about.
6561 size_t N = mPackageGroups.size();
6562 for (size_t i = 0; i < N; i++) {
6563 group->dynamicRefTable.addMapping(mPackageGroups[i]->name, mPackageGroups[i]->id);
6566 ALOGW("Found multiple library tables, ignoring...");
6569 status_t err = validate_chunk(chunk, sizeof(ResChunk_header),
6570 endPos, "ResTable_package:unknown");
6571 if (err != NO_ERROR) {
6572 return (mError=err);
6575 chunk = (const ResChunk_header*)
6576 (((const uint8_t*)chunk) + csize);
6582 DynamicRefTable::DynamicRefTable() : DynamicRefTable(0, false) {}
6584 DynamicRefTable::DynamicRefTable(uint8_t packageId, bool appAsLib)
6585 : mAssignedPackageId(packageId)
6586 , mAppAsLib(appAsLib)
6588 memset(mLookupTable, 0, sizeof(mLookupTable));
6590 // Reserved package ids
6591 mLookupTable[APP_PACKAGE_ID] = APP_PACKAGE_ID;
6592 mLookupTable[SYS_PACKAGE_ID] = SYS_PACKAGE_ID;
6595 status_t DynamicRefTable::load(const ResTable_lib_header* const header)
6597 const uint32_t entryCount = dtohl(header->count);
6598 const uint32_t sizeOfEntries = sizeof(ResTable_lib_entry) * entryCount;
6599 const uint32_t expectedSize = dtohl(header->header.size) - dtohl(header->header.headerSize);
6600 if (sizeOfEntries > expectedSize) {
6601 ALOGE("ResTable_lib_header size %u is too small to fit %u entries (x %u).",
6602 expectedSize, entryCount, (uint32_t)sizeof(ResTable_lib_entry));
6603 return UNKNOWN_ERROR;
6606 const ResTable_lib_entry* entry = (const ResTable_lib_entry*)(((uint8_t*) header) +
6607 dtohl(header->header.headerSize));
6608 for (uint32_t entryIndex = 0; entryIndex < entryCount; entryIndex++) {
6609 uint32_t packageId = dtohl(entry->packageId);
6610 char16_t tmpName[sizeof(entry->packageName) / sizeof(char16_t)];
6611 strcpy16_dtoh(tmpName, entry->packageName, sizeof(entry->packageName) / sizeof(char16_t));
6612 if (kDebugLibNoisy) {
6613 ALOGV("Found lib entry %s with id %d\n", String8(tmpName).string(),
6614 dtohl(entry->packageId));
6616 if (packageId >= 256) {
6617 ALOGE("Bad package id 0x%08x", packageId);
6618 return UNKNOWN_ERROR;
6620 mEntries.replaceValueFor(String16(tmpName), (uint8_t) packageId);
6626 status_t DynamicRefTable::addMappings(const DynamicRefTable& other) {
6627 if (mAssignedPackageId != other.mAssignedPackageId) {
6628 return UNKNOWN_ERROR;
6631 const size_t entryCount = other.mEntries.size();
6632 for (size_t i = 0; i < entryCount; i++) {
6633 ssize_t index = mEntries.indexOfKey(other.mEntries.keyAt(i));
6635 mEntries.add(other.mEntries.keyAt(i), other.mEntries[i]);
6637 if (other.mEntries[i] != mEntries[index]) {
6638 return UNKNOWN_ERROR;
6643 // Merge the lookup table. No entry can conflict
6644 // (value of 0 means not set).
6645 for (size_t i = 0; i < 256; i++) {
6646 if (mLookupTable[i] != other.mLookupTable[i]) {
6647 if (mLookupTable[i] == 0) {
6648 mLookupTable[i] = other.mLookupTable[i];
6649 } else if (other.mLookupTable[i] != 0) {
6650 return UNKNOWN_ERROR;
6657 status_t DynamicRefTable::addMapping(const String16& packageName, uint8_t packageId)
6659 ssize_t index = mEntries.indexOfKey(packageName);
6661 return UNKNOWN_ERROR;
6663 mLookupTable[mEntries.valueAt(index)] = packageId;
6667 void DynamicRefTable::addMapping(uint8_t buildPackageId, uint8_t runtimePackageId) {
6668 mLookupTable[buildPackageId] = runtimePackageId;
6671 status_t DynamicRefTable::lookupResourceId(uint32_t* resId) const {
6672 uint32_t res = *resId;
6673 size_t packageId = Res_GETPACKAGE(res) + 1;
6675 if (packageId == APP_PACKAGE_ID && !mAppAsLib) {
6676 // No lookup needs to be done, app package IDs are absolute.
6680 if (packageId == 0 || (packageId == APP_PACKAGE_ID && mAppAsLib)) {
6681 // The package ID is 0x00. That means that a shared library is accessing
6682 // its own local resource.
6683 // Or if app resource is loaded as shared library, the resource which has
6684 // app package Id is local resources.
6685 // so we fix up those resources with the calling package ID.
6686 *resId = (0xFFFFFF & (*resId)) | (((uint32_t) mAssignedPackageId) << 24);
6690 // Do a proper lookup.
6691 uint8_t translatedId = mLookupTable[packageId];
6692 if (translatedId == 0) {
6693 ALOGW("DynamicRefTable(0x%02x): No mapping for build-time package ID 0x%02x.",
6694 (uint8_t)mAssignedPackageId, (uint8_t)packageId);
6695 for (size_t i = 0; i < 256; i++) {
6696 if (mLookupTable[i] != 0) {
6697 ALOGW("e[0x%02x] -> 0x%02x", (uint8_t)i, mLookupTable[i]);
6700 return UNKNOWN_ERROR;
6703 *resId = (res & 0x00ffffff) | (((uint32_t) translatedId) << 24);
6707 status_t DynamicRefTable::lookupResourceValue(Res_value* value) const {
6708 uint8_t resolvedType = Res_value::TYPE_REFERENCE;
6709 switch (value->dataType) {
6710 case Res_value::TYPE_ATTRIBUTE:
6711 resolvedType = Res_value::TYPE_ATTRIBUTE;
6713 case Res_value::TYPE_REFERENCE:
6718 // If the package is loaded as shared library, the resource reference
6719 // also need to be fixed.
6721 case Res_value::TYPE_DYNAMIC_ATTRIBUTE:
6722 resolvedType = Res_value::TYPE_ATTRIBUTE;
6724 case Res_value::TYPE_DYNAMIC_REFERENCE:
6730 status_t err = lookupResourceId(&value->data);
6731 if (err != NO_ERROR) {
6735 value->dataType = resolvedType;
6739 struct IdmapTypeMap {
6740 ssize_t overlayTypeId;
6742 Vector<uint32_t> entryMap;
6745 status_t ResTable::createIdmap(const ResTable& overlay,
6746 uint32_t targetCrc, uint32_t overlayCrc,
6747 const char* targetPath, const char* overlayPath,
6748 void** outData, size_t* outSize) const
6750 // see README for details on the format of map
6751 if (mPackageGroups.size() == 0) {
6752 ALOGW("idmap: target package has no package groups, cannot create idmap\n");
6753 return UNKNOWN_ERROR;
6756 if (mPackageGroups[0]->packages.size() == 0) {
6757 ALOGW("idmap: target package has no packages in its first package group, "
6758 "cannot create idmap\n");
6759 return UNKNOWN_ERROR;
6762 KeyedVector<uint8_t, IdmapTypeMap> map;
6764 // overlaid packages are assumed to contain only one package group
6765 const PackageGroup* pg = mPackageGroups[0];
6767 // starting size is header
6768 *outSize = ResTable::IDMAP_HEADER_SIZE_BYTES;
6770 // target package id and number of types in map
6771 *outSize += 2 * sizeof(uint16_t);
6773 // overlay packages are assumed to contain only one package group
6774 const ResTable_package* overlayPackageStruct = overlay.mPackageGroups[0]->packages[0]->package;
6775 char16_t tmpName[sizeof(overlayPackageStruct->name)/sizeof(overlayPackageStruct->name[0])];
6776 strcpy16_dtoh(tmpName, overlayPackageStruct->name, sizeof(overlayPackageStruct->name)/sizeof(overlayPackageStruct->name[0]));
6777 const String16 overlayPackage(tmpName);
6779 for (size_t typeIndex = 0; typeIndex < pg->types.size(); ++typeIndex) {
6780 const TypeList& typeList = pg->types[typeIndex];
6781 if (typeList.isEmpty()) {
6785 const Type* typeConfigs = typeList[0];
6787 IdmapTypeMap typeMap;
6788 typeMap.overlayTypeId = -1;
6789 typeMap.entryOffset = 0;
6791 for (size_t entryIndex = 0; entryIndex < typeConfigs->entryCount; ++entryIndex) {
6792 uint32_t resID = Res_MAKEID(pg->id - 1, typeIndex, entryIndex);
6793 resource_name resName;
6794 if (!this->getResourceName(resID, false, &resName)) {
6795 if (typeMap.entryMap.isEmpty()) {
6796 typeMap.entryOffset++;
6801 const String16 overlayType(resName.type, resName.typeLen);
6802 const String16 overlayName(resName.name, resName.nameLen);
6803 uint32_t overlayResID = overlay.identifierForName(overlayName.string(),
6805 overlayType.string(),
6807 overlayPackage.string(),
6808 overlayPackage.size());
6809 if (overlayResID == 0) {
6810 if (typeMap.entryMap.isEmpty()) {
6811 typeMap.entryOffset++;
6816 if (typeMap.overlayTypeId == -1) {
6817 typeMap.overlayTypeId = Res_GETTYPE(overlayResID) + 1;
6820 if (Res_GETTYPE(overlayResID) + 1 != static_cast<size_t>(typeMap.overlayTypeId)) {
6821 ALOGE("idmap: can't mix type ids in entry map. Resource 0x%08x maps to 0x%08x"
6822 " but entries should map to resources of type %02zx",
6823 resID, overlayResID, typeMap.overlayTypeId);
6827 if (typeMap.entryOffset + typeMap.entryMap.size() < entryIndex) {
6828 // pad with 0xffffffff's (indicating non-existing entries) before adding this entry
6829 size_t index = typeMap.entryMap.size();
6830 size_t numItems = entryIndex - (typeMap.entryOffset + index);
6831 if (typeMap.entryMap.insertAt(0xffffffff, index, numItems) < 0) {
6835 typeMap.entryMap.add(Res_GETENTRY(overlayResID));
6838 if (!typeMap.entryMap.isEmpty()) {
6839 if (map.add(static_cast<uint8_t>(typeIndex), typeMap) < 0) {
6842 *outSize += (4 * sizeof(uint16_t)) + (typeMap.entryMap.size() * sizeof(uint32_t));
6846 if (map.isEmpty()) {
6847 ALOGW("idmap: no resources in overlay package present in base package");
6848 return UNKNOWN_ERROR;
6851 if ((*outData = malloc(*outSize)) == NULL) {
6855 uint32_t* data = (uint32_t*)*outData;
6856 *data++ = htodl(IDMAP_MAGIC);
6857 *data++ = htodl(IDMAP_CURRENT_VERSION);
6858 *data++ = htodl(targetCrc);
6859 *data++ = htodl(overlayCrc);
6860 const char* paths[] = { targetPath, overlayPath };
6861 for (int j = 0; j < 2; ++j) {
6862 char* p = (char*)data;
6863 const char* path = paths[j];
6864 const size_t I = strlen(path);
6866 ALOGV("path exceeds expected 255 characters: %s\n", path);
6867 return UNKNOWN_ERROR;
6869 for (size_t i = 0; i < 256; ++i) {
6870 *p++ = i < I ? path[i] : '\0';
6872 data += 256 / sizeof(uint32_t);
6874 const size_t mapSize = map.size();
6875 uint16_t* typeData = reinterpret_cast<uint16_t*>(data);
6876 *typeData++ = htods(pg->id);
6877 *typeData++ = htods(mapSize);
6878 for (size_t i = 0; i < mapSize; ++i) {
6879 uint8_t targetTypeId = map.keyAt(i);
6880 const IdmapTypeMap& typeMap = map[i];
6881 *typeData++ = htods(targetTypeId + 1);
6882 *typeData++ = htods(typeMap.overlayTypeId);
6883 *typeData++ = htods(typeMap.entryMap.size());
6884 *typeData++ = htods(typeMap.entryOffset);
6886 const size_t entryCount = typeMap.entryMap.size();
6887 uint32_t* entries = reinterpret_cast<uint32_t*>(typeData);
6888 for (size_t j = 0; j < entryCount; j++) {
6889 entries[j] = htodl(typeMap.entryMap[j]);
6891 typeData += entryCount * 2;
6897 bool ResTable::getIdmapInfo(const void* idmap, size_t sizeBytes,
6899 uint32_t* pTargetCrc, uint32_t* pOverlayCrc,
6900 String8* pTargetPath, String8* pOverlayPath)
6902 const uint32_t* map = (const uint32_t*)idmap;
6903 if (!assertIdmapHeader(map, sizeBytes)) {
6907 *pVersion = dtohl(map[1]);
6910 *pTargetCrc = dtohl(map[2]);
6913 *pOverlayCrc = dtohl(map[3]);
6916 pTargetPath->setTo(reinterpret_cast<const char*>(map + 4));
6919 pOverlayPath->setTo(reinterpret_cast<const char*>(map + 4 + 256 / sizeof(uint32_t)));
6925 #define CHAR16_TO_CSTR(c16, len) (String8(String16(c16,len)).string())
6927 #define CHAR16_ARRAY_EQ(constant, var, len) \
6928 (((len) == (sizeof(constant)/sizeof((constant)[0]))) && (0 == memcmp((var), (constant), (len))))
6930 static void print_complex(uint32_t complex, bool isFraction)
6932 const float MANTISSA_MULT =
6933 1.0f / (1<<Res_value::COMPLEX_MANTISSA_SHIFT);
6934 const float RADIX_MULTS[] = {
6935 1.0f*MANTISSA_MULT, 1.0f/(1<<7)*MANTISSA_MULT,
6936 1.0f/(1<<15)*MANTISSA_MULT, 1.0f/(1<<23)*MANTISSA_MULT
6939 float value = (complex&(Res_value::COMPLEX_MANTISSA_MASK
6940 <<Res_value::COMPLEX_MANTISSA_SHIFT))
6941 * RADIX_MULTS[(complex>>Res_value::COMPLEX_RADIX_SHIFT)
6942 & Res_value::COMPLEX_RADIX_MASK];
6943 printf("%f", value);
6946 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
6947 case Res_value::COMPLEX_UNIT_PX: printf("px"); break;
6948 case Res_value::COMPLEX_UNIT_DIP: printf("dp"); break;
6949 case Res_value::COMPLEX_UNIT_SP: printf("sp"); break;
6950 case Res_value::COMPLEX_UNIT_PT: printf("pt"); break;
6951 case Res_value::COMPLEX_UNIT_IN: printf("in"); break;
6952 case Res_value::COMPLEX_UNIT_MM: printf("mm"); break;
6953 default: printf(" (unknown unit)"); break;
6956 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
6957 case Res_value::COMPLEX_UNIT_FRACTION: printf("%%"); break;
6958 case Res_value::COMPLEX_UNIT_FRACTION_PARENT: printf("%%p"); break;
6959 default: printf(" (unknown unit)"); break;
6964 // Normalize a string for output
6965 String8 ResTable::normalizeForOutput( const char *input )
6971 while (*input != '\0') {
6973 // All interesting characters are in the ASCII zone, so we are making our own lives
6974 // easier by scanning the string one byte at a time.
6996 void ResTable::print_value(const Package* pkg, const Res_value& value) const
6998 if (value.dataType == Res_value::TYPE_NULL) {
6999 if (value.data == Res_value::DATA_NULL_UNDEFINED) {
7001 } else if (value.data == Res_value::DATA_NULL_EMPTY) {
7002 printf("(null empty)\n");
7004 // This should never happen.
7005 printf("(null) 0x%08x\n", value.data);
7007 } else if (value.dataType == Res_value::TYPE_REFERENCE) {
7008 printf("(reference) 0x%08x\n", value.data);
7009 } else if (value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE) {
7010 printf("(dynamic reference) 0x%08x\n", value.data);
7011 } else if (value.dataType == Res_value::TYPE_ATTRIBUTE) {
7012 printf("(attribute) 0x%08x\n", value.data);
7013 } else if (value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE) {
7014 printf("(dynamic attribute) 0x%08x\n", value.data);
7015 } else if (value.dataType == Res_value::TYPE_STRING) {
7017 const char* str8 = pkg->header->values.string8At(
7020 printf("(string8) \"%s\"\n", normalizeForOutput(str8).string());
7022 const char16_t* str16 = pkg->header->values.stringAt(
7024 if (str16 != NULL) {
7025 printf("(string16) \"%s\"\n",
7026 normalizeForOutput(String8(str16, len).string()).string());
7028 printf("(string) null\n");
7031 } else if (value.dataType == Res_value::TYPE_FLOAT) {
7032 printf("(float) %g\n", *(const float*)&value.data);
7033 } else if (value.dataType == Res_value::TYPE_DIMENSION) {
7034 printf("(dimension) ");
7035 print_complex(value.data, false);
7037 } else if (value.dataType == Res_value::TYPE_FRACTION) {
7038 printf("(fraction) ");
7039 print_complex(value.data, true);
7041 } else if (value.dataType >= Res_value::TYPE_FIRST_COLOR_INT
7042 || value.dataType <= Res_value::TYPE_LAST_COLOR_INT) {
7043 printf("(color) #%08x\n", value.data);
7044 } else if (value.dataType == Res_value::TYPE_INT_BOOLEAN) {
7045 printf("(boolean) %s\n", value.data ? "true" : "false");
7046 } else if (value.dataType >= Res_value::TYPE_FIRST_INT
7047 || value.dataType <= Res_value::TYPE_LAST_INT) {
7048 printf("(int) 0x%08x or %d\n", value.data, value.data);
7050 printf("(unknown type) t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)\n",
7051 (int)value.dataType, (int)value.data,
7052 (int)value.size, (int)value.res0);
7056 void ResTable::print(bool inclValues) const
7059 printf("mError=0x%x (%s)\n", mError, strerror(mError));
7061 size_t pgCount = mPackageGroups.size();
7062 printf("Package Groups (%d)\n", (int)pgCount);
7063 for (size_t pgIndex=0; pgIndex<pgCount; pgIndex++) {
7064 const PackageGroup* pg = mPackageGroups[pgIndex];
7065 printf("Package Group %d id=0x%02x packageCount=%d name=%s\n",
7066 (int)pgIndex, pg->id, (int)pg->packages.size(),
7067 String8(pg->name).string());
7069 const KeyedVector<String16, uint8_t>& refEntries = pg->dynamicRefTable.entries();
7070 const size_t refEntryCount = refEntries.size();
7071 if (refEntryCount > 0) {
7072 printf(" DynamicRefTable entryCount=%d:\n", (int) refEntryCount);
7073 for (size_t refIndex = 0; refIndex < refEntryCount; refIndex++) {
7074 printf(" 0x%02x -> %s\n",
7075 refEntries.valueAt(refIndex),
7076 String8(refEntries.keyAt(refIndex)).string());
7081 int packageId = pg->id;
7082 size_t pkgCount = pg->packages.size();
7083 for (size_t pkgIndex=0; pkgIndex<pkgCount; pkgIndex++) {
7084 const Package* pkg = pg->packages[pkgIndex];
7085 // Use a package's real ID, since the ID may have been assigned
7086 // if this package is a shared library.
7087 packageId = pkg->package->id;
7088 char16_t tmpName[sizeof(pkg->package->name)/sizeof(pkg->package->name[0])];
7089 strcpy16_dtoh(tmpName, pkg->package->name, sizeof(pkg->package->name)/sizeof(pkg->package->name[0]));
7090 printf(" Package %d id=0x%02x name=%s\n", (int)pkgIndex,
7091 pkg->package->id, String8(tmpName).string());
7094 for (size_t typeIndex=0; typeIndex < pg->types.size(); typeIndex++) {
7095 const TypeList& typeList = pg->types[typeIndex];
7096 if (typeList.isEmpty()) {
7099 const Type* typeConfigs = typeList[0];
7100 const size_t NTC = typeConfigs->configs.size();
7101 printf(" type %d configCount=%d entryCount=%d\n",
7102 (int)typeIndex, (int)NTC, (int)typeConfigs->entryCount);
7103 if (typeConfigs->typeSpecFlags != NULL) {
7104 for (size_t entryIndex=0; entryIndex<typeConfigs->entryCount; entryIndex++) {
7105 uint32_t resID = (0xff000000 & ((packageId)<<24))
7106 | (0x00ff0000 & ((typeIndex+1)<<16))
7107 | (0x0000ffff & (entryIndex));
7108 // Since we are creating resID without actually
7109 // iterating over them, we have no idea which is a
7110 // dynamic reference. We must check.
7111 if (packageId == 0) {
7112 pg->dynamicRefTable.lookupResourceId(&resID);
7115 resource_name resName;
7116 if (this->getResourceName(resID, true, &resName)) {
7119 if (resName.type8 != NULL) {
7120 type8 = String8(resName.type8, resName.typeLen);
7122 type8 = String8(resName.type, resName.typeLen);
7124 if (resName.name8 != NULL) {
7125 name8 = String8(resName.name8, resName.nameLen);
7127 name8 = String8(resName.name, resName.nameLen);
7129 printf(" spec resource 0x%08x %s:%s/%s: flags=0x%08x\n",
7131 CHAR16_TO_CSTR(resName.package, resName.packageLen),
7132 type8.string(), name8.string(),
7133 dtohl(typeConfigs->typeSpecFlags[entryIndex]));
7135 printf(" INVALID TYPE CONFIG FOR RESOURCE 0x%08x\n", resID);
7139 for (size_t configIndex=0; configIndex<NTC; configIndex++) {
7140 const ResTable_type* type = typeConfigs->configs[configIndex];
7141 if ((((uint64_t)type)&0x3) != 0) {
7142 printf(" NON-INTEGER ResTable_type ADDRESS: %p\n", type);
7146 // Always copy the config, as fields get added and we need to
7147 // set the defaults.
7148 ResTable_config thisConfig;
7149 thisConfig.copyFromDtoH(type->config);
7151 String8 configStr = thisConfig.toString();
7152 printf(" config %s", configStr.size() > 0
7153 ? configStr.string() : "(default)");
7154 if (type->flags != 0u) {
7155 printf(" flags=0x%02x", type->flags);
7156 if (type->flags & ResTable_type::FLAG_SPARSE) {
7157 printf(" [sparse]");
7163 size_t entryCount = dtohl(type->entryCount);
7164 uint32_t entriesStart = dtohl(type->entriesStart);
7165 if ((entriesStart&0x3) != 0) {
7166 printf(" NON-INTEGER ResTable_type entriesStart OFFSET: 0x%x\n", entriesStart);
7169 uint32_t typeSize = dtohl(type->header.size);
7170 if ((typeSize&0x3) != 0) {
7171 printf(" NON-INTEGER ResTable_type header.size: 0x%x\n", typeSize);
7175 const uint32_t* const eindex = (const uint32_t*)
7176 (((const uint8_t*)type) + dtohs(type->header.headerSize));
7177 for (size_t entryIndex=0; entryIndex<entryCount; entryIndex++) {
7179 uint32_t thisOffset;
7180 if (type->flags & ResTable_type::FLAG_SPARSE) {
7181 const ResTable_sparseTypeEntry* entry =
7182 reinterpret_cast<const ResTable_sparseTypeEntry*>(
7183 eindex + entryIndex);
7184 entryId = dtohs(entry->idx);
7185 // Offsets are encoded as divided by 4.
7186 thisOffset = static_cast<uint32_t>(dtohs(entry->offset)) * 4u;
7188 entryId = entryIndex;
7189 thisOffset = dtohl(eindex[entryIndex]);
7190 if (thisOffset == ResTable_type::NO_ENTRY) {
7195 uint32_t resID = (0xff000000 & ((packageId)<<24))
7196 | (0x00ff0000 & ((typeIndex+1)<<16))
7197 | (0x0000ffff & (entryId));
7198 if (packageId == 0) {
7199 pg->dynamicRefTable.lookupResourceId(&resID);
7201 resource_name resName;
7202 if (this->getResourceName(resID, true, &resName)) {
7205 if (resName.type8 != NULL) {
7206 type8 = String8(resName.type8, resName.typeLen);
7208 type8 = String8(resName.type, resName.typeLen);
7210 if (resName.name8 != NULL) {
7211 name8 = String8(resName.name8, resName.nameLen);
7213 name8 = String8(resName.name, resName.nameLen);
7215 printf(" resource 0x%08x %s:%s/%s: ", resID,
7216 CHAR16_TO_CSTR(resName.package, resName.packageLen),
7217 type8.string(), name8.string());
7219 printf(" INVALID RESOURCE 0x%08x: ", resID);
7221 if ((thisOffset&0x3) != 0) {
7222 printf("NON-INTEGER OFFSET: 0x%x\n", thisOffset);
7225 if ((thisOffset+sizeof(ResTable_entry)) > typeSize) {
7226 printf("OFFSET OUT OF BOUNDS: 0x%x+0x%x (size is 0x%x)\n",
7227 entriesStart, thisOffset, typeSize);
7231 const ResTable_entry* ent = (const ResTable_entry*)
7232 (((const uint8_t*)type) + entriesStart + thisOffset);
7233 if (((entriesStart + thisOffset)&0x3) != 0) {
7234 printf("NON-INTEGER ResTable_entry OFFSET: 0x%x\n",
7235 (entriesStart + thisOffset));
7239 uintptr_t esize = dtohs(ent->size);
7240 if ((esize&0x3) != 0) {
7241 printf("NON-INTEGER ResTable_entry SIZE: %p\n", (void *)esize);
7244 if ((thisOffset+esize) > typeSize) {
7245 printf("ResTable_entry OUT OF BOUNDS: 0x%x+0x%x+%p (size is 0x%x)\n",
7246 entriesStart, thisOffset, (void *)esize, typeSize);
7250 const Res_value* valuePtr = NULL;
7251 const ResTable_map_entry* bagPtr = NULL;
7253 if ((dtohs(ent->flags)&ResTable_entry::FLAG_COMPLEX) != 0) {
7255 bagPtr = (const ResTable_map_entry*)ent;
7257 valuePtr = (const Res_value*)
7258 (((const uint8_t*)ent) + esize);
7259 value.copyFrom_dtoh(*valuePtr);
7260 printf("t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)",
7261 (int)value.dataType, (int)value.data,
7262 (int)value.size, (int)value.res0);
7265 if ((dtohs(ent->flags)&ResTable_entry::FLAG_PUBLIC) != 0) {
7266 printf(" (PUBLIC)");
7271 if (valuePtr != NULL) {
7273 print_value(typeConfigs->package, value);
7274 } else if (bagPtr != NULL) {
7275 const int N = dtohl(bagPtr->count);
7276 const uint8_t* baseMapPtr = (const uint8_t*)ent;
7277 size_t mapOffset = esize;
7278 const ResTable_map* mapPtr = (ResTable_map*)(baseMapPtr+mapOffset);
7279 const uint32_t parent = dtohl(bagPtr->parent.ident);
7280 uint32_t resolvedParent = parent;
7281 if (Res_GETPACKAGE(resolvedParent) + 1 == 0) {
7282 status_t err = pg->dynamicRefTable.lookupResourceId(&resolvedParent);
7283 if (err != NO_ERROR) {
7287 printf(" Parent=0x%08x(Resolved=0x%08x), Count=%d\n",
7288 parent, resolvedParent, N);
7289 for (int i=0; i<N && mapOffset < (typeSize-sizeof(ResTable_map)); i++) {
7290 printf(" #%i (Key=0x%08x): ",
7291 i, dtohl(mapPtr->name.ident));
7292 value.copyFrom_dtoh(mapPtr->value);
7293 print_value(typeConfigs->package, value);
7294 const size_t size = dtohs(mapPtr->value.size);
7295 mapOffset += size + sizeof(*mapPtr)-sizeof(mapPtr->value);
7296 mapPtr = (ResTable_map*)(baseMapPtr+mapOffset);
7306 } // namespace android