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
20 #include <androidfw/ResourceTypes.h>
21 #include <utils/Atomic.h>
22 #include <utils/ByteOrder.h>
23 #include <utils/Debug.h>
24 #include <utils/Log.h>
25 #include <utils/String16.h>
26 #include <utils/String8.h>
35 #define INT32_MAX ((int32_t)(2147483647))
38 #define STRING_POOL_NOISY(x) //x
39 #define XML_NOISY(x) //x
40 #define TABLE_NOISY(x) //x
41 #define TABLE_GETENTRY(x) //x
42 #define TABLE_SUPER_NOISY(x) //x
43 #define LOAD_TABLE_NOISY(x) //x
44 #define TABLE_THEME(x) //x
52 #ifdef HAVE_LITTLE_ENDIAN
53 #define ntohl(x) ( ((x) << 24) | (((x) >> 24) & 255) | (((x) << 8) & 0xff0000) | (((x) >> 8) & 0xff00) )
54 #define htonl(x) ntohl(x)
55 #define ntohs(x) ( (((x) << 8) & 0xff00) | (((x) >> 8) & 255) )
56 #define htons(x) ntohs(x)
65 #define IDMAP_MAGIC 0x706d6469
66 // size measured in sizeof(uint32_t)
67 #define IDMAP_HEADER_SIZE (ResTable::IDMAP_HEADER_SIZE_BYTES / sizeof(uint32_t))
69 static void printToLogFunc(void* cookie, const char* txt)
74 // Standard C isspace() is only required to look at the low byte of its input, so
75 // produces incorrect results for UTF-16 characters. For safety's sake, assume that
76 // any high-byte UTF-16 code point is not whitespace.
77 inline int isspace16(char16_t c) {
78 return (c < 0x0080 && isspace(c));
81 // range checked; guaranteed to NUL-terminate within the stated number of available slots
82 // NOTE: if this truncates the dst string due to running out of space, no attempt is
83 // made to avoid splitting surrogate pairs.
84 static void strcpy16_dtoh(uint16_t* dst, const uint16_t* src, size_t avail)
86 uint16_t* last = dst + avail - 1;
87 while (*src && (dst < last)) {
88 char16_t s = dtohs(*src);
95 static status_t validate_chunk(const ResChunk_header* chunk,
97 const uint8_t* dataEnd,
100 const uint16_t headerSize = dtohs(chunk->headerSize);
101 const uint32_t size = dtohl(chunk->size);
103 if (headerSize >= minSize) {
104 if (headerSize <= size) {
105 if (((headerSize|size)&0x3) == 0) {
106 if ((ssize_t)size <= (dataEnd-((const uint8_t*)chunk))) {
109 ALOGW("%s data size %p extends beyond resource end %p.",
111 (void*)(dataEnd-((const uint8_t*)chunk)));
114 ALOGW("%s size 0x%x or headerSize 0x%x is not on an integer boundary.",
115 name, (int)size, (int)headerSize);
118 ALOGW("%s size %p is smaller than header size %p.",
119 name, (void*)size, (void*)(int)headerSize);
122 ALOGW("%s header size %p is too small.",
123 name, (void*)(int)headerSize);
127 inline void Res_value::copyFrom_dtoh(const Res_value& src)
129 size = dtohs(src.size);
131 dataType = src.dataType;
132 data = dtohl(src.data);
135 void Res_png_9patch::deviceToFile()
137 for (int i = 0; i < numXDivs; i++) {
138 xDivs[i] = htonl(xDivs[i]);
140 for (int i = 0; i < numYDivs; i++) {
141 yDivs[i] = htonl(yDivs[i]);
143 paddingLeft = htonl(paddingLeft);
144 paddingRight = htonl(paddingRight);
145 paddingTop = htonl(paddingTop);
146 paddingBottom = htonl(paddingBottom);
147 for (int i=0; i<numColors; i++) {
148 colors[i] = htonl(colors[i]);
152 void Res_png_9patch::fileToDevice()
154 for (int i = 0; i < numXDivs; i++) {
155 xDivs[i] = ntohl(xDivs[i]);
157 for (int i = 0; i < numYDivs; i++) {
158 yDivs[i] = ntohl(yDivs[i]);
160 paddingLeft = ntohl(paddingLeft);
161 paddingRight = ntohl(paddingRight);
162 paddingTop = ntohl(paddingTop);
163 paddingBottom = ntohl(paddingBottom);
164 for (int i=0; i<numColors; i++) {
165 colors[i] = ntohl(colors[i]);
169 size_t Res_png_9patch::serializedSize()
171 // The size of this struct is 32 bytes on the 32-bit target system
176 + numXDivs * sizeof(int32_t)
177 + numYDivs * sizeof(int32_t)
178 + numColors * sizeof(uint32_t);
181 void* Res_png_9patch::serialize()
183 // Use calloc since we're going to leave a few holes in the data
184 // and want this to run cleanly under valgrind
185 void* newData = calloc(1, serializedSize());
190 void Res_png_9patch::serialize(void * outData)
192 char* data = (char*) outData;
193 memmove(data, &wasDeserialized, 4); // copy wasDeserialized, numXDivs, numYDivs, numColors
194 memmove(data + 12, &paddingLeft, 16); // copy paddingXXXX
197 memmove(data, this->xDivs, numXDivs * sizeof(int32_t));
198 data += numXDivs * sizeof(int32_t);
199 memmove(data, this->yDivs, numYDivs * sizeof(int32_t));
200 data += numYDivs * sizeof(int32_t);
201 memmove(data, this->colors, numColors * sizeof(uint32_t));
204 static void deserializeInternal(const void* inData, Res_png_9patch* outData) {
205 char* patch = (char*) inData;
206 if (inData != outData) {
207 memmove(&outData->wasDeserialized, patch, 4); // copy wasDeserialized, numXDivs, numYDivs, numColors
208 memmove(&outData->paddingLeft, patch + 12, 4); // copy wasDeserialized, numXDivs, numYDivs, numColors
210 outData->wasDeserialized = true;
211 char* data = (char*)outData;
212 data += sizeof(Res_png_9patch);
213 outData->xDivs = (int32_t*) data;
214 data += outData->numXDivs * sizeof(int32_t);
215 outData->yDivs = (int32_t*) data;
216 data += outData->numYDivs * sizeof(int32_t);
217 outData->colors = (uint32_t*) data;
220 static bool assertIdmapHeader(const uint32_t* map, size_t sizeBytes)
222 if (sizeBytes < ResTable::IDMAP_HEADER_SIZE_BYTES) {
223 ALOGW("idmap assertion failed: size=%d bytes\n", (int)sizeBytes);
226 if (*map != htodl(IDMAP_MAGIC)) { // htodl: map data expected to be in correct endianess
227 ALOGW("idmap assertion failed: invalid magic found (is 0x%08x, expected 0x%08x)\n",
228 *map, htodl(IDMAP_MAGIC));
234 static status_t idmapLookup(const uint32_t* map, size_t sizeBytes, uint32_t key, uint32_t* outValue)
236 // see README for details on the format of map
237 if (!assertIdmapHeader(map, sizeBytes)) {
238 return UNKNOWN_ERROR;
240 map = map + IDMAP_HEADER_SIZE; // skip ahead to data segment
241 // size of data block, in uint32_t
242 const size_t size = (sizeBytes - ResTable::IDMAP_HEADER_SIZE_BYTES) / sizeof(uint32_t);
243 const uint32_t type = Res_GETTYPE(key) + 1; // add one, idmap stores "public" type id
244 const uint32_t entry = Res_GETENTRY(key);
245 const uint32_t typeCount = *map;
247 if (type > typeCount) {
248 ALOGW("Resource ID map: type=%d exceeds number of types=%d\n", type, typeCount);
249 return UNKNOWN_ERROR;
251 if (typeCount > size) {
252 ALOGW("Resource ID map: number of types=%d exceeds size of map=%d\n", typeCount, (int)size);
253 return UNKNOWN_ERROR;
255 const uint32_t typeOffset = map[type];
256 if (typeOffset == 0) {
260 if (typeOffset + 1 > size) {
261 ALOGW("Resource ID map: type offset=%d exceeds reasonable value, size of map=%d\n",
262 typeOffset, (int)size);
263 return UNKNOWN_ERROR;
265 const uint32_t entryCount = map[typeOffset];
266 const uint32_t entryOffset = map[typeOffset + 1];
267 if (entryCount == 0 || entry < entryOffset || entry - entryOffset > entryCount - 1) {
271 const uint32_t index = typeOffset + 2 + entry - entryOffset;
273 ALOGW("Resource ID map: entry index=%d exceeds size of map=%d\n", index, (int)size);
277 *outValue = map[index];
282 static status_t getIdmapPackageId(const uint32_t* map, size_t mapSize, uint32_t *outId)
284 if (!assertIdmapHeader(map, mapSize)) {
285 return UNKNOWN_ERROR;
287 const uint32_t* p = map + IDMAP_HEADER_SIZE + 1;
291 *outId = (map[*p + IDMAP_HEADER_SIZE + 2] >> 24) & 0x000000ff;
295 Res_png_9patch* Res_png_9patch::deserialize(const void* inData)
297 if (sizeof(void*) != sizeof(int32_t)) {
298 ALOGE("Cannot deserialize on non 32-bit system\n");
301 deserializeInternal(inData, (Res_png_9patch*) inData);
302 return (Res_png_9patch*) inData;
305 // --------------------------------------------------------------------
306 // --------------------------------------------------------------------
307 // --------------------------------------------------------------------
309 ResStringPool::ResStringPool()
310 : mError(NO_INIT), mOwnedData(NULL), mHeader(NULL), mCache(NULL)
314 ResStringPool::ResStringPool(const void* data, size_t size, bool copyData)
315 : mError(NO_INIT), mOwnedData(NULL), mHeader(NULL), mCache(NULL)
317 setTo(data, size, copyData);
320 ResStringPool::~ResStringPool()
325 status_t ResStringPool::setTo(const void* data, size_t size, bool copyData)
327 if (!data || !size) {
328 return (mError=BAD_TYPE);
333 const bool notDeviceEndian = htods(0xf0) != 0xf0;
335 if (copyData || notDeviceEndian) {
336 mOwnedData = malloc(size);
337 if (mOwnedData == NULL) {
338 return (mError=NO_MEMORY);
340 memcpy(mOwnedData, data, size);
344 mHeader = (const ResStringPool_header*)data;
346 if (notDeviceEndian) {
347 ResStringPool_header* h = const_cast<ResStringPool_header*>(mHeader);
348 h->header.headerSize = dtohs(mHeader->header.headerSize);
349 h->header.type = dtohs(mHeader->header.type);
350 h->header.size = dtohl(mHeader->header.size);
351 h->stringCount = dtohl(mHeader->stringCount);
352 h->styleCount = dtohl(mHeader->styleCount);
353 h->flags = dtohl(mHeader->flags);
354 h->stringsStart = dtohl(mHeader->stringsStart);
355 h->stylesStart = dtohl(mHeader->stylesStart);
358 if (mHeader->header.headerSize > mHeader->header.size
359 || mHeader->header.size > size) {
360 ALOGW("Bad string block: header size %d or total size %d is larger than data size %d\n",
361 (int)mHeader->header.headerSize, (int)mHeader->header.size, (int)size);
362 return (mError=BAD_TYPE);
364 mSize = mHeader->header.size;
365 mEntries = (const uint32_t*)
366 (((const uint8_t*)data)+mHeader->header.headerSize);
368 if (mHeader->stringCount > 0) {
369 if ((mHeader->stringCount*sizeof(uint32_t) < mHeader->stringCount) // uint32 overflow?
370 || (mHeader->header.headerSize+(mHeader->stringCount*sizeof(uint32_t)))
372 ALOGW("Bad string block: entry of %d items extends past data size %d\n",
373 (int)(mHeader->header.headerSize+(mHeader->stringCount*sizeof(uint32_t))),
375 return (mError=BAD_TYPE);
379 if (mHeader->flags&ResStringPool_header::UTF8_FLAG) {
380 charSize = sizeof(uint8_t);
382 charSize = sizeof(char16_t);
385 mStrings = (const void*)
386 (((const uint8_t*)data)+mHeader->stringsStart);
387 if (mHeader->stringsStart >= (mHeader->header.size-sizeof(uint16_t))) {
388 ALOGW("Bad string block: string pool starts at %d, after total size %d\n",
389 (int)mHeader->stringsStart, (int)mHeader->header.size);
390 return (mError=BAD_TYPE);
392 if (mHeader->styleCount == 0) {
394 (mHeader->header.size-mHeader->stringsStart)/charSize;
396 // check invariant: styles starts before end of data
397 if (mHeader->stylesStart >= (mHeader->header.size-sizeof(uint16_t))) {
398 ALOGW("Bad style block: style block starts at %d past data size of %d\n",
399 (int)mHeader->stylesStart, (int)mHeader->header.size);
400 return (mError=BAD_TYPE);
402 // check invariant: styles follow the strings
403 if (mHeader->stylesStart <= mHeader->stringsStart) {
404 ALOGW("Bad style block: style block starts at %d, before strings at %d\n",
405 (int)mHeader->stylesStart, (int)mHeader->stringsStart);
406 return (mError=BAD_TYPE);
409 (mHeader->stylesStart-mHeader->stringsStart)/charSize;
412 // check invariant: stringCount > 0 requires a string pool to exist
413 if (mStringPoolSize == 0) {
414 ALOGW("Bad string block: stringCount is %d but pool size is 0\n", (int)mHeader->stringCount);
415 return (mError=BAD_TYPE);
418 if (notDeviceEndian) {
420 uint32_t* e = const_cast<uint32_t*>(mEntries);
421 for (i=0; i<mHeader->stringCount; i++) {
422 e[i] = dtohl(mEntries[i]);
424 if (!(mHeader->flags&ResStringPool_header::UTF8_FLAG)) {
425 const char16_t* strings = (const char16_t*)mStrings;
426 char16_t* s = const_cast<char16_t*>(strings);
427 for (i=0; i<mStringPoolSize; i++) {
428 s[i] = dtohs(strings[i]);
433 if ((mHeader->flags&ResStringPool_header::UTF8_FLAG &&
434 ((uint8_t*)mStrings)[mStringPoolSize-1] != 0) ||
435 (!mHeader->flags&ResStringPool_header::UTF8_FLAG &&
436 ((char16_t*)mStrings)[mStringPoolSize-1] != 0)) {
437 ALOGW("Bad string block: last string is not 0-terminated\n");
438 return (mError=BAD_TYPE);
445 if (mHeader->styleCount > 0) {
446 mEntryStyles = mEntries + mHeader->stringCount;
447 // invariant: integer overflow in calculating mEntryStyles
448 if (mEntryStyles < mEntries) {
449 ALOGW("Bad string block: integer overflow finding styles\n");
450 return (mError=BAD_TYPE);
453 if (((const uint8_t*)mEntryStyles-(const uint8_t*)mHeader) > (int)size) {
454 ALOGW("Bad string block: entry of %d styles extends past data size %d\n",
455 (int)((const uint8_t*)mEntryStyles-(const uint8_t*)mHeader),
457 return (mError=BAD_TYPE);
459 mStyles = (const uint32_t*)
460 (((const uint8_t*)data)+mHeader->stylesStart);
461 if (mHeader->stylesStart >= mHeader->header.size) {
462 ALOGW("Bad string block: style pool starts %d, after total size %d\n",
463 (int)mHeader->stylesStart, (int)mHeader->header.size);
464 return (mError=BAD_TYPE);
467 (mHeader->header.size-mHeader->stylesStart)/sizeof(uint32_t);
469 if (notDeviceEndian) {
471 uint32_t* e = const_cast<uint32_t*>(mEntryStyles);
472 for (i=0; i<mHeader->styleCount; i++) {
473 e[i] = dtohl(mEntryStyles[i]);
475 uint32_t* s = const_cast<uint32_t*>(mStyles);
476 for (i=0; i<mStylePoolSize; i++) {
477 s[i] = dtohl(mStyles[i]);
481 const ResStringPool_span endSpan = {
482 { htodl(ResStringPool_span::END) },
483 htodl(ResStringPool_span::END), htodl(ResStringPool_span::END)
485 if (memcmp(&mStyles[mStylePoolSize-(sizeof(endSpan)/sizeof(uint32_t))],
486 &endSpan, sizeof(endSpan)) != 0) {
487 ALOGW("Bad string block: last style is not 0xFFFFFFFF-terminated\n");
488 return (mError=BAD_TYPE);
496 return (mError=NO_ERROR);
499 status_t ResStringPool::getError() const
504 void ResStringPool::uninit()
507 if (mHeader != NULL && mCache != NULL) {
508 for (size_t x = 0; x < mHeader->stringCount; x++) {
509 if (mCache[x] != NULL) {
524 * Strings in UTF-16 format have length indicated by a length encoded in the
525 * stored data. It is either 1 or 2 characters of length data. This allows a
526 * maximum length of 0x7FFFFFF (2147483647 bytes), but if you're storing that
527 * much data in a string, you're abusing them.
529 * If the high bit is set, then there are two characters or 4 bytes of length
530 * data encoded. In that case, drop the high bit of the first character and
531 * add it together with the next character.
534 decodeLength(const char16_t** str)
537 if ((len & 0x8000) != 0) {
539 len = ((len & 0x7FFF) << 16) | **str;
546 * Strings in UTF-8 format have length indicated by a length encoded in the
547 * stored data. It is either 1 or 2 characters of length data. This allows a
548 * maximum length of 0x7FFF (32767 bytes), but you should consider storing
549 * text in another way if you're using that much data in a single string.
551 * If the high bit is set, then there are two characters or 2 bytes of length
552 * data encoded. In that case, drop the high bit of the first character and
553 * add it together with the next character.
556 decodeLength(const uint8_t** str)
559 if ((len & 0x80) != 0) {
561 len = ((len & 0x7F) << 8) | **str;
567 const uint16_t* ResStringPool::stringAt(size_t idx, size_t* u16len) const
569 if (mError == NO_ERROR && idx < mHeader->stringCount) {
570 const bool isUTF8 = (mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0;
571 const uint32_t off = mEntries[idx]/(isUTF8?sizeof(char):sizeof(char16_t));
572 if (off < (mStringPoolSize-1)) {
574 const char16_t* strings = (char16_t*)mStrings;
575 const char16_t* str = strings+off;
577 *u16len = decodeLength(&str);
578 if ((uint32_t)(str+*u16len-strings) < mStringPoolSize) {
581 ALOGW("Bad string block: string #%d extends to %d, past end at %d\n",
582 (int)idx, (int)(str+*u16len-strings), (int)mStringPoolSize);
585 const uint8_t* strings = (uint8_t*)mStrings;
586 const uint8_t* u8str = strings+off;
588 *u16len = decodeLength(&u8str);
589 size_t u8len = decodeLength(&u8str);
591 // encLen must be less than 0x7FFF due to encoding.
592 if ((uint32_t)(u8str+u8len-strings) < mStringPoolSize) {
593 AutoMutex lock(mDecodeLock);
595 if (mCache == NULL) {
596 #ifndef HAVE_ANDROID_OS
597 STRING_POOL_NOISY(ALOGI("CREATING STRING CACHE OF %d bytes",
598 mHeader->stringCount*sizeof(char16_t**)));
600 // We do not want to be in this case when actually running Android.
601 ALOGW("CREATING STRING CACHE OF %d bytes",
602 mHeader->stringCount*sizeof(char16_t**));
604 mCache = (char16_t**)calloc(mHeader->stringCount, sizeof(char16_t**));
605 if (mCache == NULL) {
606 ALOGW("No memory trying to allocate decode cache table of %d bytes\n",
607 (int)(mHeader->stringCount*sizeof(char16_t**)));
612 if (mCache[idx] != NULL) {
616 ssize_t actualLen = utf8_to_utf16_length(u8str, u8len);
617 if (actualLen < 0 || (size_t)actualLen != *u16len) {
618 ALOGW("Bad string block: string #%lld decoded length is not correct "
620 (long long)idx, (long long)actualLen, (long long)*u16len);
624 char16_t *u16str = (char16_t *)calloc(*u16len+1, sizeof(char16_t));
626 ALOGW("No memory when trying to allocate decode cache for string #%d\n",
631 STRING_POOL_NOISY(ALOGI("Caching UTF8 string: %s", u8str));
632 utf8_to_utf16(u8str, u8len, u16str);
633 mCache[idx] = u16str;
636 ALOGW("Bad string block: string #%lld extends to %lld, past end at %lld\n",
637 (long long)idx, (long long)(u8str+u8len-strings),
638 (long long)mStringPoolSize);
642 ALOGW("Bad string block: string #%d entry is at %d, past end at %d\n",
643 (int)idx, (int)(off*sizeof(uint16_t)),
644 (int)(mStringPoolSize*sizeof(uint16_t)));
650 const char* ResStringPool::string8At(size_t idx, size_t* outLen) const
652 if (mError == NO_ERROR && idx < mHeader->stringCount) {
653 if ((mHeader->flags&ResStringPool_header::UTF8_FLAG) == 0) {
656 const uint32_t off = mEntries[idx]/sizeof(char);
657 if (off < (mStringPoolSize-1)) {
658 const uint8_t* strings = (uint8_t*)mStrings;
659 const uint8_t* str = strings+off;
660 *outLen = decodeLength(&str);
661 size_t encLen = decodeLength(&str);
662 if ((uint32_t)(str+encLen-strings) < mStringPoolSize) {
663 return (const char*)str;
665 ALOGW("Bad string block: string #%d extends to %d, past end at %d\n",
666 (int)idx, (int)(str+encLen-strings), (int)mStringPoolSize);
669 ALOGW("Bad string block: string #%d entry is at %d, past end at %d\n",
670 (int)idx, (int)(off*sizeof(uint16_t)),
671 (int)(mStringPoolSize*sizeof(uint16_t)));
677 const String8 ResStringPool::string8ObjectAt(size_t idx) const
680 const char *str = (const char*)string8At(idx, &len);
684 return String8(stringAt(idx, &len));
687 const ResStringPool_span* ResStringPool::styleAt(const ResStringPool_ref& ref) const
689 return styleAt(ref.index);
692 const ResStringPool_span* ResStringPool::styleAt(size_t idx) const
694 if (mError == NO_ERROR && idx < mHeader->styleCount) {
695 const uint32_t off = (mEntryStyles[idx]/sizeof(uint32_t));
696 if (off < mStylePoolSize) {
697 return (const ResStringPool_span*)(mStyles+off);
699 ALOGW("Bad string block: style #%d entry is at %d, past end at %d\n",
700 (int)idx, (int)(off*sizeof(uint32_t)),
701 (int)(mStylePoolSize*sizeof(uint32_t)));
707 ssize_t ResStringPool::indexOfString(const char16_t* str, size_t strLen) const
709 if (mError != NO_ERROR) {
715 if ((mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0) {
716 STRING_POOL_NOISY(ALOGI("indexOfString UTF-8: %s", String8(str, strLen).string()));
718 // The string pool contains UTF 8 strings; we don't want to cause
719 // temporary UTF-16 strings to be created as we search.
720 if (mHeader->flags&ResStringPool_header::SORTED_FLAG) {
721 // Do a binary search for the string... this is a little tricky,
722 // because the strings are sorted with strzcmp16(). So to match
723 // the ordering, we need to convert strings in the pool to UTF-16.
724 // But we don't want to hit the cache, so instead we will have a
725 // local temporary allocation for the conversions.
726 char16_t* convBuffer = (char16_t*)malloc(strLen+4);
728 ssize_t h = mHeader->stringCount-1;
733 const uint8_t* s = (const uint8_t*)string8At(mid, &len);
736 char16_t* end = utf8_to_utf16_n(s, len, convBuffer, strLen+3);
738 c = strzcmp16(convBuffer, end-convBuffer, str, strLen);
742 STRING_POOL_NOISY(ALOGI("Looking at %s, cmp=%d, l/mid/h=%d/%d/%d\n",
743 (const char*)s, c, (int)l, (int)mid, (int)h));
745 STRING_POOL_NOISY(ALOGI("MATCH!"));
756 // It is unusual to get the ID from an unsorted string block...
757 // most often this happens because we want to get IDs for style
758 // span tags; since those always appear at the end of the string
759 // block, start searching at the back.
760 String8 str8(str, strLen);
761 const size_t str8Len = str8.size();
762 for (int i=mHeader->stringCount-1; i>=0; i--) {
763 const char* s = string8At(i, &len);
764 STRING_POOL_NOISY(ALOGI("Looking at %s, i=%d\n",
767 if (s && str8Len == len && memcmp(s, str8.string(), str8Len) == 0) {
768 STRING_POOL_NOISY(ALOGI("MATCH!"));
775 STRING_POOL_NOISY(ALOGI("indexOfString UTF-16: %s", String8(str, strLen).string()));
777 if (mHeader->flags&ResStringPool_header::SORTED_FLAG) {
778 // Do a binary search for the string...
780 ssize_t h = mHeader->stringCount-1;
785 const char16_t* s = stringAt(mid, &len);
786 int c = s ? strzcmp16(s, len, str, strLen) : -1;
787 STRING_POOL_NOISY(ALOGI("Looking at %s, cmp=%d, l/mid/h=%d/%d/%d\n",
789 c, (int)l, (int)mid, (int)h));
791 STRING_POOL_NOISY(ALOGI("MATCH!"));
800 // It is unusual to get the ID from an unsorted string block...
801 // most often this happens because we want to get IDs for style
802 // span tags; since those always appear at the end of the string
803 // block, start searching at the back.
804 for (int i=mHeader->stringCount-1; i>=0; i--) {
805 const char16_t* s = stringAt(i, &len);
806 STRING_POOL_NOISY(ALOGI("Looking at %s, i=%d\n",
809 if (s && strLen == len && strzcmp16(s, len, str, strLen) == 0) {
810 STRING_POOL_NOISY(ALOGI("MATCH!"));
817 return NAME_NOT_FOUND;
820 size_t ResStringPool::size() const
822 return (mError == NO_ERROR) ? mHeader->stringCount : 0;
825 size_t ResStringPool::styleCount() const
827 return (mError == NO_ERROR) ? mHeader->styleCount : 0;
830 size_t ResStringPool::bytes() const
832 return (mError == NO_ERROR) ? mHeader->header.size : 0;
835 bool ResStringPool::isSorted() const
837 return (mHeader->flags&ResStringPool_header::SORTED_FLAG)!=0;
840 bool ResStringPool::isUTF8() const
842 return (mHeader->flags&ResStringPool_header::UTF8_FLAG)!=0;
845 // --------------------------------------------------------------------
846 // --------------------------------------------------------------------
847 // --------------------------------------------------------------------
849 ResXMLParser::ResXMLParser(const ResXMLTree& tree)
850 : mTree(tree), mEventCode(BAD_DOCUMENT)
854 void ResXMLParser::restart()
857 mEventCode = mTree.mError == NO_ERROR ? START_DOCUMENT : BAD_DOCUMENT;
859 const ResStringPool& ResXMLParser::getStrings() const
861 return mTree.mStrings;
864 ResXMLParser::event_code_t ResXMLParser::getEventType() const
869 ResXMLParser::event_code_t ResXMLParser::next()
871 if (mEventCode == START_DOCUMENT) {
872 mCurNode = mTree.mRootNode;
873 mCurExt = mTree.mRootExt;
874 return (mEventCode=mTree.mRootCode);
875 } else if (mEventCode >= FIRST_CHUNK_CODE) {
881 int32_t ResXMLParser::getCommentID() const
883 return mCurNode != NULL ? dtohl(mCurNode->comment.index) : -1;
886 const uint16_t* ResXMLParser::getComment(size_t* outLen) const
888 int32_t id = getCommentID();
889 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
892 uint32_t ResXMLParser::getLineNumber() const
894 return mCurNode != NULL ? dtohl(mCurNode->lineNumber) : -1;
897 int32_t ResXMLParser::getTextID() const
899 if (mEventCode == TEXT) {
900 return dtohl(((const ResXMLTree_cdataExt*)mCurExt)->data.index);
905 const uint16_t* ResXMLParser::getText(size_t* outLen) const
907 int32_t id = getTextID();
908 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
911 ssize_t ResXMLParser::getTextValue(Res_value* outValue) const
913 if (mEventCode == TEXT) {
914 outValue->copyFrom_dtoh(((const ResXMLTree_cdataExt*)mCurExt)->typedData);
915 return sizeof(Res_value);
920 int32_t ResXMLParser::getNamespacePrefixID() const
922 if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) {
923 return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->prefix.index);
928 const uint16_t* ResXMLParser::getNamespacePrefix(size_t* outLen) const
930 int32_t id = getNamespacePrefixID();
931 //printf("prefix=%d event=%p\n", id, mEventCode);
932 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
935 int32_t ResXMLParser::getNamespaceUriID() const
937 if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) {
938 return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->uri.index);
943 const uint16_t* ResXMLParser::getNamespaceUri(size_t* outLen) const
945 int32_t id = getNamespaceUriID();
946 //printf("uri=%d event=%p\n", id, mEventCode);
947 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
950 int32_t ResXMLParser::getElementNamespaceID() const
952 if (mEventCode == START_TAG) {
953 return dtohl(((const ResXMLTree_attrExt*)mCurExt)->ns.index);
955 if (mEventCode == END_TAG) {
956 return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->ns.index);
961 const uint16_t* ResXMLParser::getElementNamespace(size_t* outLen) const
963 int32_t id = getElementNamespaceID();
964 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
967 int32_t ResXMLParser::getElementNameID() const
969 if (mEventCode == START_TAG) {
970 return dtohl(((const ResXMLTree_attrExt*)mCurExt)->name.index);
972 if (mEventCode == END_TAG) {
973 return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->name.index);
978 const uint16_t* ResXMLParser::getElementName(size_t* outLen) const
980 int32_t id = getElementNameID();
981 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
984 size_t ResXMLParser::getAttributeCount() const
986 if (mEventCode == START_TAG) {
987 return dtohs(((const ResXMLTree_attrExt*)mCurExt)->attributeCount);
992 int32_t ResXMLParser::getAttributeNamespaceID(size_t idx) const
994 if (mEventCode == START_TAG) {
995 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
996 if (idx < dtohs(tag->attributeCount)) {
997 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
998 (((const uint8_t*)tag)
999 + dtohs(tag->attributeStart)
1000 + (dtohs(tag->attributeSize)*idx));
1001 return dtohl(attr->ns.index);
1007 const uint16_t* ResXMLParser::getAttributeNamespace(size_t idx, size_t* outLen) const
1009 int32_t id = getAttributeNamespaceID(idx);
1010 //printf("attribute namespace=%d idx=%d event=%p\n", id, idx, mEventCode);
1011 //XML_NOISY(printf("getAttributeNamespace 0x%x=0x%x\n", idx, id));
1012 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1015 const char* ResXMLParser::getAttributeNamespace8(size_t idx, size_t* outLen) const
1017 int32_t id = getAttributeNamespaceID(idx);
1018 //printf("attribute namespace=%d idx=%d event=%p\n", id, idx, mEventCode);
1019 //XML_NOISY(printf("getAttributeNamespace 0x%x=0x%x\n", idx, id));
1020 return id >= 0 ? mTree.mStrings.string8At(id, outLen) : NULL;
1023 int32_t ResXMLParser::getAttributeNameID(size_t idx) const
1025 if (mEventCode == START_TAG) {
1026 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1027 if (idx < dtohs(tag->attributeCount)) {
1028 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1029 (((const uint8_t*)tag)
1030 + dtohs(tag->attributeStart)
1031 + (dtohs(tag->attributeSize)*idx));
1032 return dtohl(attr->name.index);
1038 const uint16_t* ResXMLParser::getAttributeName(size_t idx, size_t* outLen) const
1040 int32_t id = getAttributeNameID(idx);
1041 //printf("attribute name=%d idx=%d event=%p\n", id, idx, mEventCode);
1042 //XML_NOISY(printf("getAttributeName 0x%x=0x%x\n", idx, id));
1043 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1046 const char* ResXMLParser::getAttributeName8(size_t idx, size_t* outLen) const
1048 int32_t id = getAttributeNameID(idx);
1049 //printf("attribute name=%d idx=%d event=%p\n", id, idx, mEventCode);
1050 //XML_NOISY(printf("getAttributeName 0x%x=0x%x\n", idx, id));
1051 return id >= 0 ? mTree.mStrings.string8At(id, outLen) : NULL;
1054 uint32_t ResXMLParser::getAttributeNameResID(size_t idx) const
1056 int32_t id = getAttributeNameID(idx);
1057 if (id >= 0 && (size_t)id < mTree.mNumResIds) {
1058 return dtohl(mTree.mResIds[id]);
1063 int32_t ResXMLParser::getAttributeValueStringID(size_t idx) const
1065 if (mEventCode == START_TAG) {
1066 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1067 if (idx < dtohs(tag->attributeCount)) {
1068 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1069 (((const uint8_t*)tag)
1070 + dtohs(tag->attributeStart)
1071 + (dtohs(tag->attributeSize)*idx));
1072 return dtohl(attr->rawValue.index);
1078 const uint16_t* ResXMLParser::getAttributeStringValue(size_t idx, size_t* outLen) const
1080 int32_t id = getAttributeValueStringID(idx);
1081 //XML_NOISY(printf("getAttributeValue 0x%x=0x%x\n", idx, id));
1082 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1085 int32_t ResXMLParser::getAttributeDataType(size_t idx) const
1087 if (mEventCode == START_TAG) {
1088 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1089 if (idx < dtohs(tag->attributeCount)) {
1090 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1091 (((const uint8_t*)tag)
1092 + dtohs(tag->attributeStart)
1093 + (dtohs(tag->attributeSize)*idx));
1094 return attr->typedValue.dataType;
1097 return Res_value::TYPE_NULL;
1100 int32_t ResXMLParser::getAttributeData(size_t idx) const
1102 if (mEventCode == START_TAG) {
1103 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1104 if (idx < dtohs(tag->attributeCount)) {
1105 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1106 (((const uint8_t*)tag)
1107 + dtohs(tag->attributeStart)
1108 + (dtohs(tag->attributeSize)*idx));
1109 return dtohl(attr->typedValue.data);
1115 ssize_t ResXMLParser::getAttributeValue(size_t idx, Res_value* outValue) const
1117 if (mEventCode == START_TAG) {
1118 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1119 if (idx < dtohs(tag->attributeCount)) {
1120 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1121 (((const uint8_t*)tag)
1122 + dtohs(tag->attributeStart)
1123 + (dtohs(tag->attributeSize)*idx));
1124 outValue->copyFrom_dtoh(attr->typedValue);
1125 return sizeof(Res_value);
1131 ssize_t ResXMLParser::indexOfAttribute(const char* ns, const char* attr) const
1133 String16 nsStr(ns != NULL ? ns : "");
1134 String16 attrStr(attr);
1135 return indexOfAttribute(ns ? nsStr.string() : NULL, ns ? nsStr.size() : 0,
1136 attrStr.string(), attrStr.size());
1139 ssize_t ResXMLParser::indexOfAttribute(const char16_t* ns, size_t nsLen,
1140 const char16_t* attr, size_t attrLen) const
1142 if (mEventCode == START_TAG) {
1144 return NAME_NOT_FOUND;
1146 const size_t N = getAttributeCount();
1147 if (mTree.mStrings.isUTF8()) {
1150 ns8 = String8(ns, nsLen);
1152 attr8 = String8(attr, attrLen);
1153 STRING_POOL_NOISY(ALOGI("indexOfAttribute UTF8 %s (%d) / %s (%d)", ns8.string(), nsLen,
1154 attr8.string(), attrLen));
1155 for (size_t i=0; i<N; i++) {
1156 size_t curNsLen = 0, curAttrLen = 0;
1157 const char* curNs = getAttributeNamespace8(i, &curNsLen);
1158 const char* curAttr = getAttributeName8(i, &curAttrLen);
1159 STRING_POOL_NOISY(ALOGI(" curNs=%s (%d), curAttr=%s (%d)", curNs, curNsLen,
1160 curAttr, curAttrLen));
1161 if (curAttr != NULL && curNsLen == nsLen && curAttrLen == attrLen
1162 && memcmp(attr8.string(), curAttr, attrLen) == 0) {
1164 if (curNs == NULL) {
1165 STRING_POOL_NOISY(ALOGI(" FOUND!"));
1168 } else if (curNs != NULL) {
1169 //printf(" --> ns=%s, curNs=%s\n",
1170 // String8(ns).string(), String8(curNs).string());
1171 if (memcmp(ns8.string(), curNs, nsLen) == 0) {
1172 STRING_POOL_NOISY(ALOGI(" FOUND!"));
1179 STRING_POOL_NOISY(ALOGI("indexOfAttribute UTF16 %s (%d) / %s (%d)",
1180 String8(ns, nsLen).string(), nsLen,
1181 String8(attr, attrLen).string(), attrLen));
1182 for (size_t i=0; i<N; i++) {
1183 size_t curNsLen = 0, curAttrLen = 0;
1184 const char16_t* curNs = getAttributeNamespace(i, &curNsLen);
1185 const char16_t* curAttr = getAttributeName(i, &curAttrLen);
1186 STRING_POOL_NOISY(ALOGI(" curNs=%s (%d), curAttr=%s (%d)",
1187 String8(curNs, curNsLen).string(), curNsLen,
1188 String8(curAttr, curAttrLen).string(), curAttrLen));
1189 if (curAttr != NULL && curNsLen == nsLen && curAttrLen == attrLen
1190 && (memcmp(attr, curAttr, attrLen*sizeof(char16_t)) == 0)) {
1192 if (curNs == NULL) {
1193 STRING_POOL_NOISY(ALOGI(" FOUND!"));
1196 } else if (curNs != NULL) {
1197 //printf(" --> ns=%s, curNs=%s\n",
1198 // String8(ns).string(), String8(curNs).string());
1199 if (memcmp(ns, curNs, nsLen*sizeof(char16_t)) == 0) {
1200 STRING_POOL_NOISY(ALOGI(" FOUND!"));
1209 return NAME_NOT_FOUND;
1212 ssize_t ResXMLParser::indexOfID() const
1214 if (mEventCode == START_TAG) {
1215 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->idIndex);
1216 if (idx > 0) return (idx-1);
1218 return NAME_NOT_FOUND;
1221 ssize_t ResXMLParser::indexOfClass() const
1223 if (mEventCode == START_TAG) {
1224 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->classIndex);
1225 if (idx > 0) return (idx-1);
1227 return NAME_NOT_FOUND;
1230 ssize_t ResXMLParser::indexOfStyle() const
1232 if (mEventCode == START_TAG) {
1233 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->styleIndex);
1234 if (idx > 0) return (idx-1);
1236 return NAME_NOT_FOUND;
1239 ResXMLParser::event_code_t ResXMLParser::nextNode()
1241 if (mEventCode < 0) {
1246 const ResXMLTree_node* next = (const ResXMLTree_node*)
1247 (((const uint8_t*)mCurNode) + dtohl(mCurNode->header.size));
1248 //ALOGW("Next node: prev=%p, next=%p\n", mCurNode, next);
1250 if (((const uint8_t*)next) >= mTree.mDataEnd) {
1252 return (mEventCode=END_DOCUMENT);
1255 if (mTree.validateNode(next) != NO_ERROR) {
1257 return (mEventCode=BAD_DOCUMENT);
1261 const uint16_t headerSize = dtohs(next->header.headerSize);
1262 const uint32_t totalSize = dtohl(next->header.size);
1263 mCurExt = ((const uint8_t*)next) + headerSize;
1264 size_t minExtSize = 0;
1265 event_code_t eventCode = (event_code_t)dtohs(next->header.type);
1266 switch ((mEventCode=eventCode)) {
1267 case RES_XML_START_NAMESPACE_TYPE:
1268 case RES_XML_END_NAMESPACE_TYPE:
1269 minExtSize = sizeof(ResXMLTree_namespaceExt);
1271 case RES_XML_START_ELEMENT_TYPE:
1272 minExtSize = sizeof(ResXMLTree_attrExt);
1274 case RES_XML_END_ELEMENT_TYPE:
1275 minExtSize = sizeof(ResXMLTree_endElementExt);
1277 case RES_XML_CDATA_TYPE:
1278 minExtSize = sizeof(ResXMLTree_cdataExt);
1281 ALOGW("Unknown XML block: header type %d in node at %d\n",
1282 (int)dtohs(next->header.type),
1283 (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)));
1287 if ((totalSize-headerSize) < minExtSize) {
1288 ALOGW("Bad XML block: header type 0x%x in node at 0x%x has size %d, need %d\n",
1289 (int)dtohs(next->header.type),
1290 (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)),
1291 (int)(totalSize-headerSize), (int)minExtSize);
1292 return (mEventCode=BAD_DOCUMENT);
1295 //printf("CurNode=%p, CurExt=%p, headerSize=%d, minExtSize=%d\n",
1296 // mCurNode, mCurExt, headerSize, minExtSize);
1302 void ResXMLParser::getPosition(ResXMLParser::ResXMLPosition* pos) const
1304 pos->eventCode = mEventCode;
1305 pos->curNode = mCurNode;
1306 pos->curExt = mCurExt;
1309 void ResXMLParser::setPosition(const ResXMLParser::ResXMLPosition& pos)
1311 mEventCode = pos.eventCode;
1312 mCurNode = pos.curNode;
1313 mCurExt = pos.curExt;
1317 // --------------------------------------------------------------------
1319 static volatile int32_t gCount = 0;
1321 ResXMLTree::ResXMLTree()
1322 : ResXMLParser(*this)
1323 , mError(NO_INIT), mOwnedData(NULL)
1325 //ALOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1);
1329 ResXMLTree::ResXMLTree(const void* data, size_t size, bool copyData)
1330 : ResXMLParser(*this)
1331 , mError(NO_INIT), mOwnedData(NULL)
1333 //ALOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1);
1334 setTo(data, size, copyData);
1337 ResXMLTree::~ResXMLTree()
1339 //ALOGI("Destroying ResXMLTree in %p #%d\n", this, android_atomic_dec(&gCount)-1);
1343 status_t ResXMLTree::setTo(const void* data, size_t size, bool copyData)
1346 mEventCode = START_DOCUMENT;
1348 if (!data || !size) {
1349 return (mError=BAD_TYPE);
1353 mOwnedData = malloc(size);
1354 if (mOwnedData == NULL) {
1355 return (mError=NO_MEMORY);
1357 memcpy(mOwnedData, data, size);
1361 mHeader = (const ResXMLTree_header*)data;
1362 mSize = dtohl(mHeader->header.size);
1363 if (dtohs(mHeader->header.headerSize) > mSize || mSize > size) {
1364 ALOGW("Bad XML block: header size %d or total size %d is larger than data size %d\n",
1365 (int)dtohs(mHeader->header.headerSize),
1366 (int)dtohl(mHeader->header.size), (int)size);
1371 mDataEnd = ((const uint8_t*)mHeader) + mSize;
1378 // First look for a couple interesting chunks: the string block
1379 // and first XML node.
1380 const ResChunk_header* chunk =
1381 (const ResChunk_header*)(((const uint8_t*)mHeader) + dtohs(mHeader->header.headerSize));
1382 const ResChunk_header* lastChunk = chunk;
1383 while (((const uint8_t*)chunk) < (mDataEnd-sizeof(ResChunk_header)) &&
1384 ((const uint8_t*)chunk) < (mDataEnd-dtohl(chunk->size))) {
1385 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), mDataEnd, "XML");
1386 if (err != NO_ERROR) {
1390 const uint16_t type = dtohs(chunk->type);
1391 const size_t size = dtohl(chunk->size);
1392 XML_NOISY(printf("Scanning @ %p: type=0x%x, size=0x%x\n",
1393 (void*)(((uint32_t)chunk)-((uint32_t)mHeader)), type, size));
1394 if (type == RES_STRING_POOL_TYPE) {
1395 mStrings.setTo(chunk, size);
1396 } else if (type == RES_XML_RESOURCE_MAP_TYPE) {
1397 mResIds = (const uint32_t*)
1398 (((const uint8_t*)chunk)+dtohs(chunk->headerSize));
1399 mNumResIds = (dtohl(chunk->size)-dtohs(chunk->headerSize))/sizeof(uint32_t);
1400 } else if (type >= RES_XML_FIRST_CHUNK_TYPE
1401 && type <= RES_XML_LAST_CHUNK_TYPE) {
1402 if (validateNode((const ResXMLTree_node*)chunk) != NO_ERROR) {
1406 mCurNode = (const ResXMLTree_node*)lastChunk;
1407 if (nextNode() == BAD_DOCUMENT) {
1411 mRootNode = mCurNode;
1413 mRootCode = mEventCode;
1416 XML_NOISY(printf("Skipping unknown chunk!\n"));
1419 chunk = (const ResChunk_header*)
1420 (((const uint8_t*)chunk) + size);
1423 if (mRootNode == NULL) {
1424 ALOGW("Bad XML block: no root element node found\n");
1429 mError = mStrings.getError();
1436 status_t ResXMLTree::getError() const
1441 void ResXMLTree::uninit()
1452 status_t ResXMLTree::validateNode(const ResXMLTree_node* node) const
1454 const uint16_t eventCode = dtohs(node->header.type);
1456 status_t err = validate_chunk(
1457 &node->header, sizeof(ResXMLTree_node),
1458 mDataEnd, "ResXMLTree_node");
1460 if (err >= NO_ERROR) {
1461 // Only perform additional validation on START nodes
1462 if (eventCode != RES_XML_START_ELEMENT_TYPE) {
1466 const uint16_t headerSize = dtohs(node->header.headerSize);
1467 const uint32_t size = dtohl(node->header.size);
1468 const ResXMLTree_attrExt* attrExt = (const ResXMLTree_attrExt*)
1469 (((const uint8_t*)node) + headerSize);
1470 // check for sensical values pulled out of the stream so far...
1471 if ((size >= headerSize + sizeof(ResXMLTree_attrExt))
1472 && ((void*)attrExt > (void*)node)) {
1473 const size_t attrSize = ((size_t)dtohs(attrExt->attributeSize))
1474 * dtohs(attrExt->attributeCount);
1475 if ((dtohs(attrExt->attributeStart)+attrSize) <= (size-headerSize)) {
1478 ALOGW("Bad XML block: node attributes use 0x%x bytes, only have 0x%x bytes\n",
1479 (unsigned int)(dtohs(attrExt->attributeStart)+attrSize),
1480 (unsigned int)(size-headerSize));
1483 ALOGW("Bad XML start block: node header size 0x%x, size 0x%x\n",
1484 (unsigned int)headerSize, (unsigned int)size);
1492 const bool isStart = dtohs(node->header.type) == RES_XML_START_ELEMENT_TYPE;
1494 const uint16_t headerSize = dtohs(node->header.headerSize);
1495 const uint32_t size = dtohl(node->header.size);
1497 if (headerSize >= (isStart ? sizeof(ResXMLTree_attrNode) : sizeof(ResXMLTree_node))) {
1498 if (size >= headerSize) {
1499 if (((const uint8_t*)node) <= (mDataEnd-size)) {
1503 if ((((size_t)dtohs(node->attributeSize))*dtohs(node->attributeCount))
1504 <= (size-headerSize)) {
1507 ALOGW("Bad XML block: node attributes use 0x%x bytes, only have 0x%x bytes\n",
1508 ((int)dtohs(node->attributeSize))*dtohs(node->attributeCount),
1509 (int)(size-headerSize));
1512 ALOGW("Bad XML block: node at 0x%x extends beyond data end 0x%x\n",
1513 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)), (int)mSize);
1516 ALOGW("Bad XML block: node at 0x%x header size 0x%x smaller than total size 0x%x\n",
1517 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)),
1518 (int)headerSize, (int)size);
1521 ALOGW("Bad XML block: node at 0x%x header size 0x%x too small\n",
1522 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)),
1528 // --------------------------------------------------------------------
1529 // --------------------------------------------------------------------
1530 // --------------------------------------------------------------------
1532 void ResTable_config::copyFromDeviceNoSwap(const ResTable_config& o) {
1533 const size_t size = dtohl(o.size);
1534 if (size >= sizeof(ResTable_config)) {
1537 memcpy(this, &o, size);
1538 memset(((uint8_t*)this)+size, 0, sizeof(ResTable_config)-size);
1542 void ResTable_config::copyFromDtoH(const ResTable_config& o) {
1543 copyFromDeviceNoSwap(o);
1544 size = sizeof(ResTable_config);
1547 density = dtohs(density);
1548 screenWidth = dtohs(screenWidth);
1549 screenHeight = dtohs(screenHeight);
1550 sdkVersion = dtohs(sdkVersion);
1551 minorVersion = dtohs(minorVersion);
1552 smallestScreenWidthDp = dtohs(smallestScreenWidthDp);
1553 screenWidthDp = dtohs(screenWidthDp);
1554 screenHeightDp = dtohs(screenHeightDp);
1557 void ResTable_config::swapHtoD() {
1561 density = htods(density);
1562 screenWidth = htods(screenWidth);
1563 screenHeight = htods(screenHeight);
1564 sdkVersion = htods(sdkVersion);
1565 minorVersion = htods(minorVersion);
1566 smallestScreenWidthDp = htods(smallestScreenWidthDp);
1567 screenWidthDp = htods(screenWidthDp);
1568 screenHeightDp = htods(screenHeightDp);
1571 int ResTable_config::compare(const ResTable_config& o) const {
1572 int32_t diff = (int32_t)(imsi - o.imsi);
1573 if (diff != 0) return diff;
1574 diff = (int32_t)(locale - o.locale);
1575 if (diff != 0) return diff;
1576 diff = (int32_t)(screenType - o.screenType);
1577 if (diff != 0) return diff;
1578 diff = (int32_t)(input - o.input);
1579 if (diff != 0) return diff;
1580 diff = (int32_t)(screenSize - o.screenSize);
1581 if (diff != 0) return diff;
1582 diff = (int32_t)(version - o.version);
1583 if (diff != 0) return diff;
1584 diff = (int32_t)(screenLayout - o.screenLayout);
1585 if (diff != 0) return diff;
1586 diff = (int32_t)(uiMode - o.uiMode);
1587 if (diff != 0) return diff;
1588 diff = (int32_t)(smallestScreenWidthDp - o.smallestScreenWidthDp);
1589 if (diff != 0) return diff;
1590 diff = (int32_t)(screenSizeDp - o.screenSizeDp);
1594 int ResTable_config::compareLogical(const ResTable_config& o) const {
1596 return mcc < o.mcc ? -1 : 1;
1599 return mnc < o.mnc ? -1 : 1;
1601 if (language[0] != o.language[0]) {
1602 return language[0] < o.language[0] ? -1 : 1;
1604 if (language[1] != o.language[1]) {
1605 return language[1] < o.language[1] ? -1 : 1;
1607 if (country[0] != o.country[0]) {
1608 return country[0] < o.country[0] ? -1 : 1;
1610 if (country[1] != o.country[1]) {
1611 return country[1] < o.country[1] ? -1 : 1;
1613 if ((screenLayout & MASK_LAYOUTDIR) != (o.screenLayout & MASK_LAYOUTDIR)) {
1614 return (screenLayout & MASK_LAYOUTDIR) < (o.screenLayout & MASK_LAYOUTDIR) ? -1 : 1;
1616 if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
1617 return smallestScreenWidthDp < o.smallestScreenWidthDp ? -1 : 1;
1619 if (screenWidthDp != o.screenWidthDp) {
1620 return screenWidthDp < o.screenWidthDp ? -1 : 1;
1622 if (screenHeightDp != o.screenHeightDp) {
1623 return screenHeightDp < o.screenHeightDp ? -1 : 1;
1625 if (screenWidth != o.screenWidth) {
1626 return screenWidth < o.screenWidth ? -1 : 1;
1628 if (screenHeight != o.screenHeight) {
1629 return screenHeight < o.screenHeight ? -1 : 1;
1631 if (density != o.density) {
1632 return density < o.density ? -1 : 1;
1634 if (orientation != o.orientation) {
1635 return orientation < o.orientation ? -1 : 1;
1637 if (touchscreen != o.touchscreen) {
1638 return touchscreen < o.touchscreen ? -1 : 1;
1640 if (input != o.input) {
1641 return input < o.input ? -1 : 1;
1643 if (screenLayout != o.screenLayout) {
1644 return screenLayout < o.screenLayout ? -1 : 1;
1646 if (uiMode != o.uiMode) {
1647 return uiMode < o.uiMode ? -1 : 1;
1649 if (version != o.version) {
1650 return version < o.version ? -1 : 1;
1655 int ResTable_config::diff(const ResTable_config& o) const {
1657 if (mcc != o.mcc) diffs |= CONFIG_MCC;
1658 if (mnc != o.mnc) diffs |= CONFIG_MNC;
1659 if (locale != o.locale) diffs |= CONFIG_LOCALE;
1660 if (orientation != o.orientation) diffs |= CONFIG_ORIENTATION;
1661 if (density != o.density) diffs |= CONFIG_DENSITY;
1662 if (touchscreen != o.touchscreen) diffs |= CONFIG_TOUCHSCREEN;
1663 if (((inputFlags^o.inputFlags)&(MASK_KEYSHIDDEN|MASK_NAVHIDDEN)) != 0)
1664 diffs |= CONFIG_KEYBOARD_HIDDEN;
1665 if (keyboard != o.keyboard) diffs |= CONFIG_KEYBOARD;
1666 if (navigation != o.navigation) diffs |= CONFIG_NAVIGATION;
1667 if (screenSize != o.screenSize) diffs |= CONFIG_SCREEN_SIZE;
1668 if (version != o.version) diffs |= CONFIG_VERSION;
1669 if ((screenLayout & MASK_LAYOUTDIR) != (o.screenLayout & MASK_LAYOUTDIR)) diffs |= CONFIG_LAYOUTDIR;
1670 if ((screenLayout & ~MASK_LAYOUTDIR) != (o.screenLayout & ~MASK_LAYOUTDIR)) diffs |= CONFIG_SCREEN_LAYOUT;
1671 if (uiMode != o.uiMode) diffs |= CONFIG_UI_MODE;
1672 if (smallestScreenWidthDp != o.smallestScreenWidthDp) diffs |= CONFIG_SMALLEST_SCREEN_SIZE;
1673 if (screenSizeDp != o.screenSizeDp) diffs |= CONFIG_SCREEN_SIZE;
1677 bool ResTable_config::isMoreSpecificThan(const ResTable_config& o) const {
1678 // The order of the following tests defines the importance of one
1679 // configuration parameter over another. Those tests first are more
1680 // important, trumping any values in those following them.
1681 if (imsi || o.imsi) {
1683 if (!mcc) return false;
1684 if (!o.mcc) return true;
1688 if (!mnc) return false;
1689 if (!o.mnc) return true;
1693 if (locale || o.locale) {
1694 if (language[0] != o.language[0]) {
1695 if (!language[0]) return false;
1696 if (!o.language[0]) return true;
1699 if (country[0] != o.country[0]) {
1700 if (!country[0]) return false;
1701 if (!o.country[0]) return true;
1705 if (screenLayout || o.screenLayout) {
1706 if (((screenLayout^o.screenLayout) & MASK_LAYOUTDIR) != 0) {
1707 if (!(screenLayout & MASK_LAYOUTDIR)) return false;
1708 if (!(o.screenLayout & MASK_LAYOUTDIR)) return true;
1712 if (smallestScreenWidthDp || o.smallestScreenWidthDp) {
1713 if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
1714 if (!smallestScreenWidthDp) return false;
1715 if (!o.smallestScreenWidthDp) return true;
1719 if (screenSizeDp || o.screenSizeDp) {
1720 if (screenWidthDp != o.screenWidthDp) {
1721 if (!screenWidthDp) return false;
1722 if (!o.screenWidthDp) return true;
1725 if (screenHeightDp != o.screenHeightDp) {
1726 if (!screenHeightDp) return false;
1727 if (!o.screenHeightDp) return true;
1731 if (screenLayout || o.screenLayout) {
1732 if (((screenLayout^o.screenLayout) & MASK_SCREENSIZE) != 0) {
1733 if (!(screenLayout & MASK_SCREENSIZE)) return false;
1734 if (!(o.screenLayout & MASK_SCREENSIZE)) return true;
1736 if (((screenLayout^o.screenLayout) & MASK_SCREENLONG) != 0) {
1737 if (!(screenLayout & MASK_SCREENLONG)) return false;
1738 if (!(o.screenLayout & MASK_SCREENLONG)) return true;
1742 if (orientation != o.orientation) {
1743 if (!orientation) return false;
1744 if (!o.orientation) return true;
1747 if (uiMode || o.uiMode) {
1748 if (((uiMode^o.uiMode) & MASK_UI_MODE_TYPE) != 0) {
1749 if (!(uiMode & MASK_UI_MODE_TYPE)) return false;
1750 if (!(o.uiMode & MASK_UI_MODE_TYPE)) return true;
1752 if (((uiMode^o.uiMode) & MASK_UI_MODE_NIGHT) != 0) {
1753 if (!(uiMode & MASK_UI_MODE_NIGHT)) return false;
1754 if (!(o.uiMode & MASK_UI_MODE_NIGHT)) return true;
1758 // density is never 'more specific'
1759 // as the default just equals 160
1761 if (touchscreen != o.touchscreen) {
1762 if (!touchscreen) return false;
1763 if (!o.touchscreen) return true;
1766 if (input || o.input) {
1767 if (((inputFlags^o.inputFlags) & MASK_KEYSHIDDEN) != 0) {
1768 if (!(inputFlags & MASK_KEYSHIDDEN)) return false;
1769 if (!(o.inputFlags & MASK_KEYSHIDDEN)) return true;
1772 if (((inputFlags^o.inputFlags) & MASK_NAVHIDDEN) != 0) {
1773 if (!(inputFlags & MASK_NAVHIDDEN)) return false;
1774 if (!(o.inputFlags & MASK_NAVHIDDEN)) return true;
1777 if (keyboard != o.keyboard) {
1778 if (!keyboard) return false;
1779 if (!o.keyboard) return true;
1782 if (navigation != o.navigation) {
1783 if (!navigation) return false;
1784 if (!o.navigation) return true;
1788 if (screenSize || o.screenSize) {
1789 if (screenWidth != o.screenWidth) {
1790 if (!screenWidth) return false;
1791 if (!o.screenWidth) return true;
1794 if (screenHeight != o.screenHeight) {
1795 if (!screenHeight) return false;
1796 if (!o.screenHeight) return true;
1800 if (version || o.version) {
1801 if (sdkVersion != o.sdkVersion) {
1802 if (!sdkVersion) return false;
1803 if (!o.sdkVersion) return true;
1806 if (minorVersion != o.minorVersion) {
1807 if (!minorVersion) return false;
1808 if (!o.minorVersion) return true;
1814 bool ResTable_config::isBetterThan(const ResTable_config& o,
1815 const ResTable_config* requested) const {
1817 if (imsi || o.imsi) {
1818 if ((mcc != o.mcc) && requested->mcc) {
1822 if ((mnc != o.mnc) && requested->mnc) {
1827 if (locale || o.locale) {
1828 if ((language[0] != o.language[0]) && requested->language[0]) {
1829 return (language[0]);
1832 if ((country[0] != o.country[0]) && requested->country[0]) {
1833 return (country[0]);
1837 if (screenLayout || o.screenLayout) {
1838 if (((screenLayout^o.screenLayout) & MASK_LAYOUTDIR) != 0
1839 && (requested->screenLayout & MASK_LAYOUTDIR)) {
1840 int myLayoutDir = screenLayout & MASK_LAYOUTDIR;
1841 int oLayoutDir = o.screenLayout & MASK_LAYOUTDIR;
1842 return (myLayoutDir > oLayoutDir);
1846 if (smallestScreenWidthDp || o.smallestScreenWidthDp) {
1847 // The configuration closest to the actual size is best.
1848 // We assume that larger configs have already been filtered
1849 // out at this point. That means we just want the largest one.
1850 if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
1851 return smallestScreenWidthDp > o.smallestScreenWidthDp;
1855 if (screenSizeDp || o.screenSizeDp) {
1856 // "Better" is based on the sum of the difference between both
1857 // width and height from the requested dimensions. We are
1858 // assuming the invalid configs (with smaller dimens) have
1859 // already been filtered. Note that if a particular dimension
1860 // is unspecified, we will end up with a large value (the
1861 // difference between 0 and the requested dimension), which is
1862 // good since we will prefer a config that has specified a
1864 int myDelta = 0, otherDelta = 0;
1865 if (requested->screenWidthDp) {
1866 myDelta += requested->screenWidthDp - screenWidthDp;
1867 otherDelta += requested->screenWidthDp - o.screenWidthDp;
1869 if (requested->screenHeightDp) {
1870 myDelta += requested->screenHeightDp - screenHeightDp;
1871 otherDelta += requested->screenHeightDp - o.screenHeightDp;
1873 //ALOGI("Comparing this %dx%d to other %dx%d in %dx%d: myDelta=%d otherDelta=%d",
1874 // screenWidthDp, screenHeightDp, o.screenWidthDp, o.screenHeightDp,
1875 // requested->screenWidthDp, requested->screenHeightDp, myDelta, otherDelta);
1876 if (myDelta != otherDelta) {
1877 return myDelta < otherDelta;
1881 if (screenLayout || o.screenLayout) {
1882 if (((screenLayout^o.screenLayout) & MASK_SCREENSIZE) != 0
1883 && (requested->screenLayout & MASK_SCREENSIZE)) {
1884 // A little backwards compatibility here: undefined is
1885 // considered equivalent to normal. But only if the
1886 // requested size is at least normal; otherwise, small
1887 // is better than the default.
1888 int mySL = (screenLayout & MASK_SCREENSIZE);
1889 int oSL = (o.screenLayout & MASK_SCREENSIZE);
1890 int fixedMySL = mySL;
1892 if ((requested->screenLayout & MASK_SCREENSIZE) >= SCREENSIZE_NORMAL) {
1893 if (fixedMySL == 0) fixedMySL = SCREENSIZE_NORMAL;
1894 if (fixedOSL == 0) fixedOSL = SCREENSIZE_NORMAL;
1896 // For screen size, the best match is the one that is
1897 // closest to the requested screen size, but not over
1898 // (the not over part is dealt with in match() below).
1899 if (fixedMySL == fixedOSL) {
1900 // If the two are the same, but 'this' is actually
1901 // undefined, then the other is really a better match.
1902 if (mySL == 0) return false;
1905 if (fixedMySL != fixedOSL) {
1906 return fixedMySL > fixedOSL;
1909 if (((screenLayout^o.screenLayout) & MASK_SCREENLONG) != 0
1910 && (requested->screenLayout & MASK_SCREENLONG)) {
1911 return (screenLayout & MASK_SCREENLONG);
1915 if ((orientation != o.orientation) && requested->orientation) {
1916 return (orientation);
1919 if (uiMode || o.uiMode) {
1920 if (((uiMode^o.uiMode) & MASK_UI_MODE_TYPE) != 0
1921 && (requested->uiMode & MASK_UI_MODE_TYPE)) {
1922 return (uiMode & MASK_UI_MODE_TYPE);
1924 if (((uiMode^o.uiMode) & MASK_UI_MODE_NIGHT) != 0
1925 && (requested->uiMode & MASK_UI_MODE_NIGHT)) {
1926 return (uiMode & MASK_UI_MODE_NIGHT);
1930 if (screenType || o.screenType) {
1931 if (density != o.density) {
1932 // density is tough. Any density is potentially useful
1933 // because the system will scale it. Scaling down
1934 // is generally better than scaling up.
1935 // Default density counts as 160dpi (the system default)
1936 // TODO - remove 160 constants
1937 int h = (density?density:160);
1938 int l = (o.density?o.density:160);
1939 bool bImBigger = true;
1947 int reqValue = (requested->density?requested->density:160);
1948 if (reqValue >= h) {
1949 // requested value higher than both l and h, give h
1952 if (l >= reqValue) {
1953 // requested value lower than both l and h, give l
1956 // saying that scaling down is 2x better than up
1957 if (((2 * l) - reqValue) * h > reqValue * reqValue) {
1964 if ((touchscreen != o.touchscreen) && requested->touchscreen) {
1965 return (touchscreen);
1969 if (input || o.input) {
1970 const int keysHidden = inputFlags & MASK_KEYSHIDDEN;
1971 const int oKeysHidden = o.inputFlags & MASK_KEYSHIDDEN;
1972 if (keysHidden != oKeysHidden) {
1973 const int reqKeysHidden =
1974 requested->inputFlags & MASK_KEYSHIDDEN;
1975 if (reqKeysHidden) {
1977 if (!keysHidden) return false;
1978 if (!oKeysHidden) return true;
1979 // For compatibility, we count KEYSHIDDEN_NO as being
1980 // the same as KEYSHIDDEN_SOFT. Here we disambiguate
1981 // these by making an exact match more specific.
1982 if (reqKeysHidden == keysHidden) return true;
1983 if (reqKeysHidden == oKeysHidden) return false;
1987 const int navHidden = inputFlags & MASK_NAVHIDDEN;
1988 const int oNavHidden = o.inputFlags & MASK_NAVHIDDEN;
1989 if (navHidden != oNavHidden) {
1990 const int reqNavHidden =
1991 requested->inputFlags & MASK_NAVHIDDEN;
1994 if (!navHidden) return false;
1995 if (!oNavHidden) return true;
1999 if ((keyboard != o.keyboard) && requested->keyboard) {
2003 if ((navigation != o.navigation) && requested->navigation) {
2004 return (navigation);
2008 if (screenSize || o.screenSize) {
2009 // "Better" is based on the sum of the difference between both
2010 // width and height from the requested dimensions. We are
2011 // assuming the invalid configs (with smaller sizes) have
2012 // already been filtered. Note that if a particular dimension
2013 // is unspecified, we will end up with a large value (the
2014 // difference between 0 and the requested dimension), which is
2015 // good since we will prefer a config that has specified a
2017 int myDelta = 0, otherDelta = 0;
2018 if (requested->screenWidth) {
2019 myDelta += requested->screenWidth - screenWidth;
2020 otherDelta += requested->screenWidth - o.screenWidth;
2022 if (requested->screenHeight) {
2023 myDelta += requested->screenHeight - screenHeight;
2024 otherDelta += requested->screenHeight - o.screenHeight;
2026 if (myDelta != otherDelta) {
2027 return myDelta < otherDelta;
2031 if (version || o.version) {
2032 if ((sdkVersion != o.sdkVersion) && requested->sdkVersion) {
2033 return (sdkVersion > o.sdkVersion);
2036 if ((minorVersion != o.minorVersion) &&
2037 requested->minorVersion) {
2038 return (minorVersion);
2044 return isMoreSpecificThan(o);
2047 bool ResTable_config::match(const ResTable_config& settings) const {
2049 if (mcc != 0 && mcc != settings.mcc) {
2052 if (mnc != 0 && mnc != settings.mnc) {
2057 if (language[0] != 0
2058 && (language[0] != settings.language[0]
2059 || language[1] != settings.language[1])) {
2063 && (country[0] != settings.country[0]
2064 || country[1] != settings.country[1])) {
2068 if (screenConfig != 0) {
2069 const int layoutDir = screenLayout&MASK_LAYOUTDIR;
2070 const int setLayoutDir = settings.screenLayout&MASK_LAYOUTDIR;
2071 if (layoutDir != 0 && layoutDir != setLayoutDir) {
2075 const int screenSize = screenLayout&MASK_SCREENSIZE;
2076 const int setScreenSize = settings.screenLayout&MASK_SCREENSIZE;
2077 // Any screen sizes for larger screens than the setting do not
2079 if (screenSize != 0 && screenSize > setScreenSize) {
2083 const int screenLong = screenLayout&MASK_SCREENLONG;
2084 const int setScreenLong = settings.screenLayout&MASK_SCREENLONG;
2085 if (screenLong != 0 && screenLong != setScreenLong) {
2089 const int uiModeType = uiMode&MASK_UI_MODE_TYPE;
2090 const int setUiModeType = settings.uiMode&MASK_UI_MODE_TYPE;
2091 if (uiModeType != 0 && uiModeType != setUiModeType) {
2095 const int uiModeNight = uiMode&MASK_UI_MODE_NIGHT;
2096 const int setUiModeNight = settings.uiMode&MASK_UI_MODE_NIGHT;
2097 if (uiModeNight != 0 && uiModeNight != setUiModeNight) {
2101 if (smallestScreenWidthDp != 0
2102 && smallestScreenWidthDp > settings.smallestScreenWidthDp) {
2106 if (screenSizeDp != 0) {
2107 if (screenWidthDp != 0 && screenWidthDp > settings.screenWidthDp) {
2108 //ALOGI("Filtering out width %d in requested %d", screenWidthDp, settings.screenWidthDp);
2111 if (screenHeightDp != 0 && screenHeightDp > settings.screenHeightDp) {
2112 //ALOGI("Filtering out height %d in requested %d", screenHeightDp, settings.screenHeightDp);
2116 if (screenType != 0) {
2117 if (orientation != 0 && orientation != settings.orientation) {
2120 // density always matches - we can scale it. See isBetterThan
2121 if (touchscreen != 0 && touchscreen != settings.touchscreen) {
2126 const int keysHidden = inputFlags&MASK_KEYSHIDDEN;
2127 const int setKeysHidden = settings.inputFlags&MASK_KEYSHIDDEN;
2128 if (keysHidden != 0 && keysHidden != setKeysHidden) {
2129 // For compatibility, we count a request for KEYSHIDDEN_NO as also
2130 // matching the more recent KEYSHIDDEN_SOFT. Basically
2131 // KEYSHIDDEN_NO means there is some kind of keyboard available.
2132 //ALOGI("Matching keysHidden: have=%d, config=%d\n", keysHidden, setKeysHidden);
2133 if (keysHidden != KEYSHIDDEN_NO || setKeysHidden != KEYSHIDDEN_SOFT) {
2134 //ALOGI("No match!");
2138 const int navHidden = inputFlags&MASK_NAVHIDDEN;
2139 const int setNavHidden = settings.inputFlags&MASK_NAVHIDDEN;
2140 if (navHidden != 0 && navHidden != setNavHidden) {
2143 if (keyboard != 0 && keyboard != settings.keyboard) {
2146 if (navigation != 0 && navigation != settings.navigation) {
2150 if (screenSize != 0) {
2151 if (screenWidth != 0 && screenWidth > settings.screenWidth) {
2154 if (screenHeight != 0 && screenHeight > settings.screenHeight) {
2159 if (sdkVersion != 0 && sdkVersion > settings.sdkVersion) {
2162 if (minorVersion != 0 && minorVersion != settings.minorVersion) {
2169 void ResTable_config::getLocale(char str[6]) const {
2172 str[0] = language[0];
2173 str[1] = language[1];
2176 str[3] = country[0];
2177 str[4] = country[1];
2182 String8 ResTable_config::toString() const {
2186 if (res.size() > 0) res.append("-");
2187 res.appendFormat("%dmcc", dtohs(mcc));
2190 if (res.size() > 0) res.append("-");
2191 res.appendFormat("%dmnc", dtohs(mnc));
2193 if (language[0] != 0) {
2194 if (res.size() > 0) res.append("-");
2195 res.append(language, 2);
2197 if (country[0] != 0) {
2198 if (res.size() > 0) res.append("-");
2199 res.append(country, 2);
2201 if ((screenLayout&MASK_LAYOUTDIR) != 0) {
2202 if (res.size() > 0) res.append("-");
2203 switch (screenLayout&ResTable_config::MASK_LAYOUTDIR) {
2204 case ResTable_config::LAYOUTDIR_LTR:
2205 res.append("ldltr");
2207 case ResTable_config::LAYOUTDIR_RTL:
2208 res.append("ldrtl");
2211 res.appendFormat("layoutDir=%d",
2212 dtohs(screenLayout&ResTable_config::MASK_LAYOUTDIR));
2216 if (smallestScreenWidthDp != 0) {
2217 if (res.size() > 0) res.append("-");
2218 res.appendFormat("sw%ddp", dtohs(smallestScreenWidthDp));
2220 if (screenWidthDp != 0) {
2221 if (res.size() > 0) res.append("-");
2222 res.appendFormat("w%ddp", dtohs(screenWidthDp));
2224 if (screenHeightDp != 0) {
2225 if (res.size() > 0) res.append("-");
2226 res.appendFormat("h%ddp", dtohs(screenHeightDp));
2228 if ((screenLayout&MASK_SCREENSIZE) != SCREENSIZE_ANY) {
2229 if (res.size() > 0) res.append("-");
2230 switch (screenLayout&ResTable_config::MASK_SCREENSIZE) {
2231 case ResTable_config::SCREENSIZE_SMALL:
2232 res.append("small");
2234 case ResTable_config::SCREENSIZE_NORMAL:
2235 res.append("normal");
2237 case ResTable_config::SCREENSIZE_LARGE:
2238 res.append("large");
2240 case ResTable_config::SCREENSIZE_XLARGE:
2241 res.append("xlarge");
2244 res.appendFormat("screenLayoutSize=%d",
2245 dtohs(screenLayout&ResTable_config::MASK_SCREENSIZE));
2249 if ((screenLayout&MASK_SCREENLONG) != 0) {
2250 if (res.size() > 0) res.append("-");
2251 switch (screenLayout&ResTable_config::MASK_SCREENLONG) {
2252 case ResTable_config::SCREENLONG_NO:
2253 res.append("notlong");
2255 case ResTable_config::SCREENLONG_YES:
2259 res.appendFormat("screenLayoutLong=%d",
2260 dtohs(screenLayout&ResTable_config::MASK_SCREENLONG));
2264 if (orientation != ORIENTATION_ANY) {
2265 if (res.size() > 0) res.append("-");
2266 switch (orientation) {
2267 case ResTable_config::ORIENTATION_PORT:
2270 case ResTable_config::ORIENTATION_LAND:
2273 case ResTable_config::ORIENTATION_SQUARE:
2274 res.append("square");
2277 res.appendFormat("orientation=%d", dtohs(orientation));
2281 if ((uiMode&MASK_UI_MODE_TYPE) != UI_MODE_TYPE_ANY) {
2282 if (res.size() > 0) res.append("-");
2283 switch (uiMode&ResTable_config::MASK_UI_MODE_TYPE) {
2284 case ResTable_config::UI_MODE_TYPE_DESK:
2287 case ResTable_config::UI_MODE_TYPE_CAR:
2290 case ResTable_config::UI_MODE_TYPE_TELEVISION:
2291 res.append("television");
2293 case ResTable_config::UI_MODE_TYPE_APPLIANCE:
2294 res.append("appliance");
2296 case ResTable_config::UI_MODE_TYPE_WATCH:
2297 res.append("watch");
2300 res.appendFormat("uiModeType=%d",
2301 dtohs(screenLayout&ResTable_config::MASK_UI_MODE_TYPE));
2305 if ((uiMode&MASK_UI_MODE_NIGHT) != 0) {
2306 if (res.size() > 0) res.append("-");
2307 switch (uiMode&ResTable_config::MASK_UI_MODE_NIGHT) {
2308 case ResTable_config::UI_MODE_NIGHT_NO:
2309 res.append("notnight");
2311 case ResTable_config::UI_MODE_NIGHT_YES:
2312 res.append("night");
2315 res.appendFormat("uiModeNight=%d",
2316 dtohs(uiMode&MASK_UI_MODE_NIGHT));
2320 if (density != DENSITY_DEFAULT) {
2321 if (res.size() > 0) res.append("-");
2323 case ResTable_config::DENSITY_LOW:
2326 case ResTable_config::DENSITY_MEDIUM:
2329 case ResTable_config::DENSITY_TV:
2330 res.append("tvdpi");
2332 case ResTable_config::DENSITY_HIGH:
2335 case ResTable_config::DENSITY_XHIGH:
2336 res.append("xhdpi");
2338 case ResTable_config::DENSITY_XXHIGH:
2339 res.append("xxhdpi");
2341 case ResTable_config::DENSITY_NONE:
2342 res.append("nodpi");
2345 res.appendFormat("%ddpi", dtohs(density));
2349 if (touchscreen != TOUCHSCREEN_ANY) {
2350 if (res.size() > 0) res.append("-");
2351 switch (touchscreen) {
2352 case ResTable_config::TOUCHSCREEN_NOTOUCH:
2353 res.append("notouch");
2355 case ResTable_config::TOUCHSCREEN_FINGER:
2356 res.append("finger");
2358 case ResTable_config::TOUCHSCREEN_STYLUS:
2359 res.append("stylus");
2362 res.appendFormat("touchscreen=%d", dtohs(touchscreen));
2366 if (keyboard != KEYBOARD_ANY) {
2367 if (res.size() > 0) res.append("-");
2369 case ResTable_config::KEYBOARD_NOKEYS:
2370 res.append("nokeys");
2372 case ResTable_config::KEYBOARD_QWERTY:
2373 res.append("qwerty");
2375 case ResTable_config::KEYBOARD_12KEY:
2376 res.append("12key");
2379 res.appendFormat("keyboard=%d", dtohs(keyboard));
2383 if ((inputFlags&MASK_KEYSHIDDEN) != 0) {
2384 if (res.size() > 0) res.append("-");
2385 switch (inputFlags&MASK_KEYSHIDDEN) {
2386 case ResTable_config::KEYSHIDDEN_NO:
2387 res.append("keysexposed");
2389 case ResTable_config::KEYSHIDDEN_YES:
2390 res.append("keyshidden");
2392 case ResTable_config::KEYSHIDDEN_SOFT:
2393 res.append("keyssoft");
2397 if (navigation != NAVIGATION_ANY) {
2398 if (res.size() > 0) res.append("-");
2399 switch (navigation) {
2400 case ResTable_config::NAVIGATION_NONAV:
2401 res.append("nonav");
2403 case ResTable_config::NAVIGATION_DPAD:
2406 case ResTable_config::NAVIGATION_TRACKBALL:
2407 res.append("trackball");
2409 case ResTable_config::NAVIGATION_WHEEL:
2410 res.append("wheel");
2413 res.appendFormat("navigation=%d", dtohs(navigation));
2417 if ((inputFlags&MASK_NAVHIDDEN) != 0) {
2418 if (res.size() > 0) res.append("-");
2419 switch (inputFlags&MASK_NAVHIDDEN) {
2420 case ResTable_config::NAVHIDDEN_NO:
2421 res.append("navsexposed");
2423 case ResTable_config::NAVHIDDEN_YES:
2424 res.append("navhidden");
2427 res.appendFormat("inputFlagsNavHidden=%d",
2428 dtohs(inputFlags&MASK_NAVHIDDEN));
2432 if (screenSize != 0) {
2433 if (res.size() > 0) res.append("-");
2434 res.appendFormat("%dx%d", dtohs(screenWidth), dtohs(screenHeight));
2437 if (res.size() > 0) res.append("-");
2438 res.appendFormat("v%d", dtohs(sdkVersion));
2439 if (minorVersion != 0) {
2440 res.appendFormat(".%d", dtohs(minorVersion));
2447 // --------------------------------------------------------------------
2448 // --------------------------------------------------------------------
2449 // --------------------------------------------------------------------
2451 struct ResTable::Header
2453 Header(ResTable* _owner) : owner(_owner), ownedData(NULL), header(NULL),
2454 resourceIDMap(NULL), resourceIDMapSize(0) { }
2458 free(resourceIDMap);
2461 ResTable* const owner;
2463 const ResTable_header* header;
2465 const uint8_t* dataEnd;
2469 ResStringPool values;
2470 uint32_t* resourceIDMap;
2471 size_t resourceIDMapSize;
2474 struct ResTable::Type
2476 Type(const Header* _header, const Package* _package, size_t count)
2477 : header(_header), package(_package), entryCount(count),
2478 typeSpec(NULL), typeSpecFlags(NULL) { }
2479 const Header* const header;
2480 const Package* const package;
2481 const size_t entryCount;
2482 const ResTable_typeSpec* typeSpec;
2483 const uint32_t* typeSpecFlags;
2484 Vector<const ResTable_type*> configs;
2487 struct ResTable::Package
2489 Package(ResTable* _owner, const Header* _header, const ResTable_package* _package)
2490 : owner(_owner), header(_header), package(_package) { }
2493 size_t i = types.size();
2500 ResTable* const owner;
2501 const Header* const header;
2502 const ResTable_package* const package;
2503 Vector<Type*> types;
2505 ResStringPool typeStrings;
2506 ResStringPool keyStrings;
2508 const Type* getType(size_t idx) const {
2509 return idx < types.size() ? types[idx] : NULL;
2513 // A group of objects describing a particular resource package.
2514 // The first in 'package' is always the root object (from the resource
2515 // table that defined the package); the ones after are skins on top of it.
2516 struct ResTable::PackageGroup
2518 PackageGroup(ResTable* _owner, const String16& _name, uint32_t _id)
2519 : owner(_owner), name(_name), id(_id), typeCount(0), bags(NULL) { }
2522 const size_t N = packages.size();
2523 for (size_t i=0; i<N; i++) {
2524 Package* pkg = packages[i];
2525 if (pkg->owner == owner) {
2531 void clearBagCache() {
2533 TABLE_NOISY(printf("bags=%p\n", bags));
2534 Package* pkg = packages[0];
2535 TABLE_NOISY(printf("typeCount=%x\n", typeCount));
2536 for (size_t i=0; i<typeCount; i++) {
2537 TABLE_NOISY(printf("type=%d\n", i));
2538 const Type* type = pkg->getType(i);
2540 bag_set** typeBags = bags[i];
2541 TABLE_NOISY(printf("typeBags=%p\n", typeBags));
2543 TABLE_NOISY(printf("type->entryCount=%x\n", type->entryCount));
2544 const size_t N = type->entryCount;
2545 for (size_t j=0; j<N; j++) {
2546 if (typeBags[j] && typeBags[j] != (bag_set*)0xFFFFFFFF)
2558 ResTable* const owner;
2559 String16 const name;
2561 Vector<Package*> packages;
2563 // This is for finding typeStrings and other common package stuff.
2564 Package* basePackage;
2566 // For quick access.
2569 // Computed attribute bags, first indexed by the type and second
2570 // by the entry in that type.
2574 struct ResTable::bag_set
2576 size_t numAttrs; // number in array
2577 size_t availAttrs; // total space in array
2578 uint32_t typeSpecFlags;
2579 // Followed by 'numAttr' bag_entry structures.
2582 ResTable::Theme::Theme(const ResTable& table)
2585 memset(mPackages, 0, sizeof(mPackages));
2588 ResTable::Theme::~Theme()
2590 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
2591 package_info* pi = mPackages[i];
2598 void ResTable::Theme::free_package(package_info* pi)
2600 for (size_t j=0; j<pi->numTypes; j++) {
2601 theme_entry* te = pi->types[j].entries;
2609 ResTable::Theme::package_info* ResTable::Theme::copy_package(package_info* pi)
2611 package_info* newpi = (package_info*)malloc(
2612 sizeof(package_info) + (pi->numTypes*sizeof(type_info)));
2613 newpi->numTypes = pi->numTypes;
2614 for (size_t j=0; j<newpi->numTypes; j++) {
2615 size_t cnt = pi->types[j].numEntries;
2616 newpi->types[j].numEntries = cnt;
2617 theme_entry* te = pi->types[j].entries;
2619 theme_entry* newte = (theme_entry*)malloc(cnt*sizeof(theme_entry));
2620 newpi->types[j].entries = newte;
2621 memcpy(newte, te, cnt*sizeof(theme_entry));
2623 newpi->types[j].entries = NULL;
2629 status_t ResTable::Theme::applyStyle(uint32_t resID, bool force)
2631 const bag_entry* bag;
2632 uint32_t bagTypeSpecFlags = 0;
2634 const ssize_t N = mTable.getBagLocked(resID, &bag, &bagTypeSpecFlags);
2635 TABLE_NOISY(ALOGV("Applying style 0x%08x to theme %p, count=%d", resID, this, N));
2641 uint32_t curPackage = 0xffffffff;
2642 ssize_t curPackageIndex = 0;
2643 package_info* curPI = NULL;
2644 uint32_t curType = 0xffffffff;
2645 size_t numEntries = 0;
2646 theme_entry* curEntries = NULL;
2648 const bag_entry* end = bag + N;
2650 const uint32_t attrRes = bag->map.name.ident;
2651 const uint32_t p = Res_GETPACKAGE(attrRes);
2652 const uint32_t t = Res_GETTYPE(attrRes);
2653 const uint32_t e = Res_GETENTRY(attrRes);
2655 if (curPackage != p) {
2656 const ssize_t pidx = mTable.getResourcePackageIndex(attrRes);
2658 ALOGE("Style contains key with bad package: 0x%08x\n", attrRes);
2663 curPackageIndex = pidx;
2664 curPI = mPackages[pidx];
2665 if (curPI == NULL) {
2666 PackageGroup* const grp = mTable.mPackageGroups[pidx];
2667 int cnt = grp->typeCount;
2668 curPI = (package_info*)malloc(
2669 sizeof(package_info) + (cnt*sizeof(type_info)));
2670 curPI->numTypes = cnt;
2671 memset(curPI->types, 0, cnt*sizeof(type_info));
2672 mPackages[pidx] = curPI;
2674 curType = 0xffffffff;
2677 if (t >= curPI->numTypes) {
2678 ALOGE("Style contains key with bad type: 0x%08x\n", attrRes);
2683 curEntries = curPI->types[t].entries;
2684 if (curEntries == NULL) {
2685 PackageGroup* const grp = mTable.mPackageGroups[curPackageIndex];
2686 const Type* type = grp->packages[0]->getType(t);
2687 int cnt = type != NULL ? type->entryCount : 0;
2688 curEntries = (theme_entry*)malloc(cnt*sizeof(theme_entry));
2689 memset(curEntries, Res_value::TYPE_NULL, cnt*sizeof(theme_entry));
2690 curPI->types[t].numEntries = cnt;
2691 curPI->types[t].entries = curEntries;
2693 numEntries = curPI->types[t].numEntries;
2695 if (e >= numEntries) {
2696 ALOGE("Style contains key with bad entry: 0x%08x\n", attrRes);
2700 theme_entry* curEntry = curEntries + e;
2701 TABLE_NOISY(ALOGV("Attr 0x%08x: type=0x%x, data=0x%08x; curType=0x%x",
2702 attrRes, bag->map.value.dataType, bag->map.value.data,
2703 curEntry->value.dataType));
2704 if (force || curEntry->value.dataType == Res_value::TYPE_NULL) {
2705 curEntry->stringBlock = bag->stringBlock;
2706 curEntry->typeSpecFlags |= bagTypeSpecFlags;
2707 curEntry->value = bag->map.value;
2715 //ALOGI("Applying style 0x%08x (force=%d) theme %p...\n", resID, force, this);
2721 status_t ResTable::Theme::setTo(const Theme& other)
2723 //ALOGI("Setting theme %p from theme %p...\n", this, &other);
2725 //other.dumpToLog();
2727 if (&mTable == &other.mTable) {
2728 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
2729 if (mPackages[i] != NULL) {
2730 free_package(mPackages[i]);
2732 if (other.mPackages[i] != NULL) {
2733 mPackages[i] = copy_package(other.mPackages[i]);
2735 mPackages[i] = NULL;
2739 // @todo: need to really implement this, not just copy
2740 // the system package (which is still wrong because it isn't
2741 // fixing up resource references).
2742 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
2743 if (mPackages[i] != NULL) {
2744 free_package(mPackages[i]);
2746 if (i == 0 && other.mPackages[i] != NULL) {
2747 mPackages[i] = copy_package(other.mPackages[i]);
2749 mPackages[i] = NULL;
2754 //ALOGI("Final theme:");
2760 ssize_t ResTable::Theme::getAttribute(uint32_t resID, Res_value* outValue,
2761 uint32_t* outTypeSpecFlags) const
2765 if (outTypeSpecFlags != NULL) *outTypeSpecFlags = 0;
2768 const ssize_t p = mTable.getResourcePackageIndex(resID);
2769 const uint32_t t = Res_GETTYPE(resID);
2770 const uint32_t e = Res_GETENTRY(resID);
2772 TABLE_THEME(ALOGI("Looking up attr 0x%08x in theme %p", resID, this));
2775 const package_info* const pi = mPackages[p];
2776 TABLE_THEME(ALOGI("Found package: %p", pi));
2778 TABLE_THEME(ALOGI("Desired type index is %ld in avail %d", t, pi->numTypes));
2779 if (t < pi->numTypes) {
2780 const type_info& ti = pi->types[t];
2781 TABLE_THEME(ALOGI("Desired entry index is %ld in avail %d", e, ti.numEntries));
2782 if (e < ti.numEntries) {
2783 const theme_entry& te = ti.entries[e];
2784 if (outTypeSpecFlags != NULL) {
2785 *outTypeSpecFlags |= te.typeSpecFlags;
2787 TABLE_THEME(ALOGI("Theme value: type=0x%x, data=0x%08x",
2788 te.value.dataType, te.value.data));
2789 const uint8_t type = te.value.dataType;
2790 if (type == Res_value::TYPE_ATTRIBUTE) {
2793 resID = te.value.data;
2796 ALOGW("Too many attribute references, stopped at: 0x%08x\n", resID);
2798 } else if (type != Res_value::TYPE_NULL) {
2799 *outValue = te.value;
2800 return te.stringBlock;
2814 ssize_t ResTable::Theme::resolveAttributeReference(Res_value* inOutValue,
2815 ssize_t blockIndex, uint32_t* outLastRef,
2816 uint32_t* inoutTypeSpecFlags, ResTable_config* inoutConfig) const
2818 //printf("Resolving type=0x%x\n", inOutValue->dataType);
2819 if (inOutValue->dataType == Res_value::TYPE_ATTRIBUTE) {
2820 uint32_t newTypeSpecFlags;
2821 blockIndex = getAttribute(inOutValue->data, inOutValue, &newTypeSpecFlags);
2822 TABLE_THEME(ALOGI("Resolving attr reference: blockIndex=%d, type=0x%x, data=%p\n",
2823 (int)blockIndex, (int)inOutValue->dataType, (void*)inOutValue->data));
2824 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newTypeSpecFlags;
2825 //printf("Retrieved attribute new type=0x%x\n", inOutValue->dataType);
2826 if (blockIndex < 0) {
2830 return mTable.resolveReference(inOutValue, blockIndex, outLastRef,
2831 inoutTypeSpecFlags, inoutConfig);
2834 void ResTable::Theme::dumpToLog() const
2836 ALOGI("Theme %p:\n", this);
2837 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
2838 package_info* pi = mPackages[i];
2839 if (pi == NULL) continue;
2841 ALOGI(" Package #0x%02x:\n", (int)(i+1));
2842 for (size_t j=0; j<pi->numTypes; j++) {
2843 type_info& ti = pi->types[j];
2844 if (ti.numEntries == 0) continue;
2846 ALOGI(" Type #0x%02x:\n", (int)(j+1));
2847 for (size_t k=0; k<ti.numEntries; k++) {
2848 theme_entry& te = ti.entries[k];
2849 if (te.value.dataType == Res_value::TYPE_NULL) continue;
2850 ALOGI(" 0x%08x: t=0x%x, d=0x%08x (block=%d)\n",
2851 (int)Res_MAKEID(i, j, k),
2852 te.value.dataType, (int)te.value.data, (int)te.stringBlock);
2858 ResTable::ResTable()
2861 memset(&mParams, 0, sizeof(mParams));
2862 memset(mPackageMap, 0, sizeof(mPackageMap));
2863 //ALOGI("Creating ResTable %p\n", this);
2866 ResTable::ResTable(const void* data, size_t size, void* cookie, bool copyData)
2869 memset(&mParams, 0, sizeof(mParams));
2870 memset(mPackageMap, 0, sizeof(mPackageMap));
2871 add(data, size, cookie, copyData);
2872 LOG_FATAL_IF(mError != NO_ERROR, "Error parsing resource table");
2873 //ALOGI("Creating ResTable %p\n", this);
2876 ResTable::~ResTable()
2878 //ALOGI("Destroying ResTable in %p\n", this);
2882 inline ssize_t ResTable::getResourcePackageIndex(uint32_t resID) const
2884 return ((ssize_t)mPackageMap[Res_GETPACKAGE(resID)+1])-1;
2887 status_t ResTable::add(const void* data, size_t size, void* cookie, bool copyData,
2890 return add(data, size, cookie, NULL, copyData, reinterpret_cast<const Asset*>(idmap));
2893 status_t ResTable::add(Asset* asset, void* cookie, bool copyData, const void* idmap)
2895 const void* data = asset->getBuffer(true);
2897 ALOGW("Unable to get buffer of resource asset file");
2898 return UNKNOWN_ERROR;
2900 size_t size = (size_t)asset->getLength();
2901 return add(data, size, cookie, asset, copyData, reinterpret_cast<const Asset*>(idmap));
2904 status_t ResTable::add(ResTable* src)
2906 mError = src->mError;
2908 for (size_t i=0; i<src->mHeaders.size(); i++) {
2909 mHeaders.add(src->mHeaders[i]);
2912 for (size_t i=0; i<src->mPackageGroups.size(); i++) {
2913 PackageGroup* srcPg = src->mPackageGroups[i];
2914 PackageGroup* pg = new PackageGroup(this, srcPg->name, srcPg->id);
2915 for (size_t j=0; j<srcPg->packages.size(); j++) {
2916 pg->packages.add(srcPg->packages[j]);
2918 pg->basePackage = srcPg->basePackage;
2919 pg->typeCount = srcPg->typeCount;
2920 mPackageGroups.add(pg);
2923 memcpy(mPackageMap, src->mPackageMap, sizeof(mPackageMap));
2928 status_t ResTable::add(const void* data, size_t size, void* cookie,
2929 Asset* asset, bool copyData, const Asset* idmap)
2931 if (!data) return NO_ERROR;
2932 Header* header = new Header(this);
2933 header->index = mHeaders.size();
2934 header->cookie = cookie;
2935 if (idmap != NULL) {
2936 const size_t idmap_size = idmap->getLength();
2937 const void* idmap_data = const_cast<Asset*>(idmap)->getBuffer(true);
2938 header->resourceIDMap = (uint32_t*)malloc(idmap_size);
2939 if (header->resourceIDMap == NULL) {
2941 return (mError = NO_MEMORY);
2943 memcpy((void*)header->resourceIDMap, idmap_data, idmap_size);
2944 header->resourceIDMapSize = idmap_size;
2946 mHeaders.add(header);
2948 const bool notDeviceEndian = htods(0xf0) != 0xf0;
2951 ALOGV("Adding resources to ResTable: data=%p, size=0x%x, cookie=%p, asset=%p, copy=%d "
2952 "idmap=%p\n", data, size, cookie, asset, copyData, idmap));
2954 if (copyData || notDeviceEndian) {
2955 header->ownedData = malloc(size);
2956 if (header->ownedData == NULL) {
2957 return (mError=NO_MEMORY);
2959 memcpy(header->ownedData, data, size);
2960 data = header->ownedData;
2963 header->header = (const ResTable_header*)data;
2964 header->size = dtohl(header->header->header.size);
2965 //ALOGI("Got size 0x%x, again size 0x%x, raw size 0x%x\n", header->size,
2966 // dtohl(header->header->header.size), header->header->header.size);
2967 LOAD_TABLE_NOISY(ALOGV("Loading ResTable @%p:\n", header->header));
2968 LOAD_TABLE_NOISY(printHexData(2, header->header, header->size < 256 ? header->size : 256,
2969 16, 16, 0, false, printToLogFunc));
2970 if (dtohs(header->header->header.headerSize) > header->size
2971 || header->size > size) {
2972 ALOGW("Bad resource table: header size 0x%x or total size 0x%x is larger than data size 0x%x\n",
2973 (int)dtohs(header->header->header.headerSize),
2974 (int)header->size, (int)size);
2975 return (mError=BAD_TYPE);
2977 if (((dtohs(header->header->header.headerSize)|header->size)&0x3) != 0) {
2978 ALOGW("Bad resource table: header size 0x%x or total size 0x%x is not on an integer boundary\n",
2979 (int)dtohs(header->header->header.headerSize),
2981 return (mError=BAD_TYPE);
2983 header->dataEnd = ((const uint8_t*)header->header) + header->size;
2985 // Iterate through all chunks.
2986 size_t curPackage = 0;
2988 const ResChunk_header* chunk =
2989 (const ResChunk_header*)(((const uint8_t*)header->header)
2990 + dtohs(header->header->header.headerSize));
2991 while (((const uint8_t*)chunk) <= (header->dataEnd-sizeof(ResChunk_header)) &&
2992 ((const uint8_t*)chunk) <= (header->dataEnd-dtohl(chunk->size))) {
2993 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), header->dataEnd, "ResTable");
2994 if (err != NO_ERROR) {
2995 return (mError=err);
2997 TABLE_NOISY(ALOGV("Chunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n",
2998 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
2999 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header))));
3000 const size_t csize = dtohl(chunk->size);
3001 const uint16_t ctype = dtohs(chunk->type);
3002 if (ctype == RES_STRING_POOL_TYPE) {
3003 if (header->values.getError() != NO_ERROR) {
3004 // Only use the first string chunk; ignore any others that
3006 status_t err = header->values.setTo(chunk, csize);
3007 if (err != NO_ERROR) {
3008 return (mError=err);
3011 ALOGW("Multiple string chunks found in resource table.");
3013 } else if (ctype == RES_TABLE_PACKAGE_TYPE) {
3014 if (curPackage >= dtohl(header->header->packageCount)) {
3015 ALOGW("More package chunks were found than the %d declared in the header.",
3016 dtohl(header->header->packageCount));
3017 return (mError=BAD_TYPE);
3019 uint32_t idmap_id = 0;
3020 if (idmap != NULL) {
3022 if (getIdmapPackageId(header->resourceIDMap,
3023 header->resourceIDMapSize,
3024 &tmp) == NO_ERROR) {
3028 if (parsePackage((ResTable_package*)chunk, header, idmap_id) != NO_ERROR) {
3033 ALOGW("Unknown chunk type %p in table at %p.\n",
3034 (void*)(int)(ctype),
3035 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)));
3037 chunk = (const ResChunk_header*)
3038 (((const uint8_t*)chunk) + csize);
3041 if (curPackage < dtohl(header->header->packageCount)) {
3042 ALOGW("Fewer package chunks (%d) were found than the %d declared in the header.",
3043 (int)curPackage, dtohl(header->header->packageCount));
3044 return (mError=BAD_TYPE);
3046 mError = header->values.getError();
3047 if (mError != NO_ERROR) {
3048 ALOGW("No string values found in resource table!");
3051 TABLE_NOISY(ALOGV("Returning from add with mError=%d\n", mError));
3055 status_t ResTable::getError() const
3060 void ResTable::uninit()
3063 size_t N = mPackageGroups.size();
3064 for (size_t i=0; i<N; i++) {
3065 PackageGroup* g = mPackageGroups[i];
3068 N = mHeaders.size();
3069 for (size_t i=0; i<N; i++) {
3070 Header* header = mHeaders[i];
3071 if (header->owner == this) {
3072 if (header->ownedData) {
3073 free(header->ownedData);
3079 mPackageGroups.clear();
3083 bool ResTable::getResourceName(uint32_t resID, bool allowUtf8, resource_name* outName) const
3085 if (mError != NO_ERROR) {
3089 const ssize_t p = getResourcePackageIndex(resID);
3090 const int t = Res_GETTYPE(resID);
3091 const int e = Res_GETENTRY(resID);
3094 if (Res_GETPACKAGE(resID)+1 == 0) {
3095 ALOGW("No package identifier when getting name for resource number 0x%08x", resID);
3097 ALOGW("No known package when getting name for resource number 0x%08x", resID);
3102 ALOGW("No type identifier when getting name for resource number 0x%08x", resID);
3106 const PackageGroup* const grp = mPackageGroups[p];
3108 ALOGW("Bad identifier when getting name for resource number 0x%08x", resID);
3111 if (grp->packages.size() > 0) {
3112 const Package* const package = grp->packages[0];
3114 const ResTable_type* type;
3115 const ResTable_entry* entry;
3116 ssize_t offset = getEntry(package, t, e, NULL, &type, &entry, NULL);
3121 outName->package = grp->name.string();
3122 outName->packageLen = grp->name.size();
3124 outName->type8 = grp->basePackage->typeStrings.string8At(t, &outName->typeLen);
3125 outName->name8 = grp->basePackage->keyStrings.string8At(
3126 dtohl(entry->key.index), &outName->nameLen);
3128 outName->type8 = NULL;
3129 outName->name8 = NULL;
3131 if (outName->type8 == NULL) {
3132 outName->type = grp->basePackage->typeStrings.stringAt(t, &outName->typeLen);
3133 // If we have a bad index for some reason, we should abort.
3134 if (outName->type == NULL) {
3138 if (outName->name8 == NULL) {
3139 outName->name = grp->basePackage->keyStrings.stringAt(
3140 dtohl(entry->key.index), &outName->nameLen);
3141 // If we have a bad index for some reason, we should abort.
3142 if (outName->name == NULL) {
3153 ssize_t ResTable::getResource(uint32_t resID, Res_value* outValue, bool mayBeBag, uint16_t density,
3154 uint32_t* outSpecFlags, ResTable_config* outConfig) const
3156 if (mError != NO_ERROR) {
3160 const ssize_t p = getResourcePackageIndex(resID);
3161 const int t = Res_GETTYPE(resID);
3162 const int e = Res_GETENTRY(resID);
3165 if (Res_GETPACKAGE(resID)+1 == 0) {
3166 ALOGW("No package identifier when getting value for resource number 0x%08x", resID);
3168 ALOGW("No known package when getting value for resource number 0x%08x", resID);
3173 ALOGW("No type identifier when getting value for resource number 0x%08x", resID);
3177 const Res_value* bestValue = NULL;
3178 const Package* bestPackage = NULL;
3179 ResTable_config bestItem;
3180 memset(&bestItem, 0, sizeof(bestItem)); // make the compiler shut up
3182 if (outSpecFlags != NULL) *outSpecFlags = 0;
3184 // Look through all resource packages, starting with the most
3186 const PackageGroup* const grp = mPackageGroups[p];
3188 ALOGW("Bad identifier when getting value for resource number 0x%08x", resID);
3192 // Allow overriding density
3193 const ResTable_config* desiredConfig = &mParams;
3194 ResTable_config* overrideConfig = NULL;
3196 overrideConfig = (ResTable_config*) malloc(sizeof(ResTable_config));
3197 if (overrideConfig == NULL) {
3198 ALOGE("Couldn't malloc ResTable_config for overrides: %s", strerror(errno));
3201 memcpy(overrideConfig, &mParams, sizeof(ResTable_config));
3202 overrideConfig->density = density;
3203 desiredConfig = overrideConfig;
3206 ssize_t rc = BAD_VALUE;
3207 size_t ip = grp->packages.size();
3213 const Package* const package = grp->packages[ip];
3214 if (package->header->resourceIDMap) {
3215 uint32_t overlayResID = 0x0;
3216 status_t retval = idmapLookup(package->header->resourceIDMap,
3217 package->header->resourceIDMapSize,
3218 resID, &overlayResID);
3219 if (retval == NO_ERROR && overlayResID != 0x0) {
3220 // for this loop iteration, this is the type and entry we really want
3221 ALOGV("resource map 0x%08x -> 0x%08x\n", resID, overlayResID);
3222 T = Res_GETTYPE(overlayResID);
3223 E = Res_GETENTRY(overlayResID);
3225 // resource not present in overlay package, continue with the next package
3230 const ResTable_type* type;
3231 const ResTable_entry* entry;
3232 const Type* typeClass;
3233 ssize_t offset = getEntry(package, T, E, desiredConfig, &type, &entry, &typeClass);
3235 // No {entry, appropriate config} pair found in package. If this
3236 // package is an overlay package (ip != 0), this simply means the
3237 // overlay package did not specify a default.
3238 // Non-overlay packages are still required to provide a default.
3239 if (offset < 0 && ip == 0) {
3240 ALOGW("Failure getting entry for 0x%08x (t=%d e=%d) in package %zd (error %d)\n",
3241 resID, T, E, ip, (int)offset);
3248 if ((dtohs(entry->flags)&entry->FLAG_COMPLEX) != 0) {
3250 ALOGW("Requesting resource %p failed because it is complex\n",
3256 TABLE_NOISY(aout << "Resource type data: "
3257 << HexDump(type, dtohl(type->header.size)) << endl);
3259 if ((size_t)offset > (dtohl(type->header.size)-sizeof(Res_value))) {
3260 ALOGW("ResTable_item at %d is beyond type chunk data %d",
3261 (int)offset, dtohl(type->header.size));
3266 const Res_value* item =
3267 (const Res_value*)(((const uint8_t*)type) + offset);
3268 ResTable_config thisConfig;
3269 thisConfig.copyFromDtoH(type->config);
3271 if (outSpecFlags != NULL) {
3272 if (typeClass->typeSpecFlags != NULL) {
3273 *outSpecFlags |= dtohl(typeClass->typeSpecFlags[E]);
3279 if (bestPackage != NULL &&
3280 (bestItem.isMoreSpecificThan(thisConfig) || bestItem.diff(thisConfig) == 0)) {
3281 // Discard thisConfig not only if bestItem is more specific, but also if the two configs
3282 // are identical (diff == 0), or overlay packages will not take effect.
3286 bestItem = thisConfig;
3288 bestPackage = package;
3291 TABLE_NOISY(printf("Found result: package %p\n", bestPackage));
3294 outValue->size = dtohs(bestValue->size);
3295 outValue->res0 = bestValue->res0;
3296 outValue->dataType = bestValue->dataType;
3297 outValue->data = dtohl(bestValue->data);
3298 if (outConfig != NULL) {
3299 *outConfig = bestItem;
3301 TABLE_NOISY(size_t len;
3302 printf("Found value: pkg=%d, type=%d, str=%s, int=%d\n",
3303 bestPackage->header->index,
3305 outValue->dataType == bestValue->TYPE_STRING
3306 ? String8(bestPackage->header->values.stringAt(
3307 outValue->data, &len)).string()
3310 rc = bestPackage->header->index;
3315 if (overrideConfig != NULL) {
3316 free(overrideConfig);
3322 ssize_t ResTable::resolveReference(Res_value* value, ssize_t blockIndex,
3323 uint32_t* outLastRef, uint32_t* inoutTypeSpecFlags,
3324 ResTable_config* outConfig) const
3327 while (blockIndex >= 0 && value->dataType == value->TYPE_REFERENCE
3328 && value->data != 0 && count < 20) {
3329 if (outLastRef) *outLastRef = value->data;
3330 uint32_t lastRef = value->data;
3331 uint32_t newFlags = 0;
3332 const ssize_t newIndex = getResource(value->data, value, true, 0, &newFlags,
3334 if (newIndex == BAD_INDEX) {
3337 TABLE_THEME(ALOGI("Resolving reference %p: newIndex=%d, type=0x%x, data=%p\n",
3338 (void*)lastRef, (int)newIndex, (int)value->dataType, (void*)value->data));
3339 //printf("Getting reference 0x%08x: newIndex=%d\n", value->data, newIndex);
3340 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newFlags;
3342 // This can fail if the resource being referenced is a style...
3343 // in this case, just return the reference, and expect the
3344 // caller to deal with.
3347 blockIndex = newIndex;
3353 const char16_t* ResTable::valueToString(
3354 const Res_value* value, size_t stringBlock,
3355 char16_t tmpBuffer[TMP_BUFFER_SIZE], size_t* outLen)
3360 if (value->dataType == value->TYPE_STRING) {
3361 return getTableStringBlock(stringBlock)->stringAt(value->data, outLen);
3363 // XXX do int to string conversions.
3367 ssize_t ResTable::lockBag(uint32_t resID, const bag_entry** outBag) const
3370 ssize_t err = getBagLocked(resID, outBag);
3371 if (err < NO_ERROR) {
3372 //printf("*** get failed! unlocking\n");
3378 void ResTable::unlockBag(const bag_entry* bag) const
3380 //printf("<<< unlockBag %p\n", this);
3384 void ResTable::lock() const
3389 void ResTable::unlock() const
3394 ssize_t ResTable::getBagLocked(uint32_t resID, const bag_entry** outBag,
3395 uint32_t* outTypeSpecFlags) const
3397 if (mError != NO_ERROR) {
3401 const ssize_t p = getResourcePackageIndex(resID);
3402 const int t = Res_GETTYPE(resID);
3403 const int e = Res_GETENTRY(resID);
3406 ALOGW("Invalid package identifier when getting bag for resource number 0x%08x", resID);
3410 ALOGW("No type identifier when getting bag for resource number 0x%08x", resID);
3414 //printf("Get bag: id=0x%08x, p=%d, t=%d\n", resID, p, t);
3415 PackageGroup* const grp = mPackageGroups[p];
3417 ALOGW("Bad identifier when getting bag for resource number 0x%08x", resID);
3421 if (t >= (int)grp->typeCount) {
3422 ALOGW("Type identifier 0x%x is larger than type count 0x%x",
3423 t+1, (int)grp->typeCount);
3427 const Package* const basePackage = grp->packages[0];
3429 const Type* const typeConfigs = basePackage->getType(t);
3431 const size_t NENTRY = typeConfigs->entryCount;
3432 if (e >= (int)NENTRY) {
3433 ALOGW("Entry identifier 0x%x is larger than entry count 0x%x",
3434 e, (int)typeConfigs->entryCount);
3438 // First see if we've already computed this bag...
3440 bag_set** typeSet = grp->bags[t];
3442 bag_set* set = typeSet[e];
3444 if (set != (bag_set*)0xFFFFFFFF) {
3445 if (outTypeSpecFlags != NULL) {
3446 *outTypeSpecFlags = set->typeSpecFlags;
3448 *outBag = (bag_entry*)(set+1);
3449 //ALOGI("Found existing bag for: %p\n", (void*)resID);
3450 return set->numAttrs;
3452 ALOGW("Attempt to retrieve bag 0x%08x which is invalid or in a cycle.",
3459 // Bag not found, we need to compute it!
3461 grp->bags = (bag_set***)calloc(grp->typeCount, sizeof(bag_set*));
3462 if (!grp->bags) return NO_MEMORY;
3465 bag_set** typeSet = grp->bags[t];
3467 typeSet = (bag_set**)calloc(NENTRY, sizeof(bag_set*));
3468 if (!typeSet) return NO_MEMORY;
3469 grp->bags[t] = typeSet;
3472 // Mark that we are currently working on this one.
3473 typeSet[e] = (bag_set*)0xFFFFFFFF;
3475 // This is what we are building.
3476 bag_set* set = NULL;
3478 TABLE_NOISY(ALOGI("Building bag: %p\n", (void*)resID));
3480 ResTable_config bestConfig;
3481 memset(&bestConfig, 0, sizeof(bestConfig));
3483 // Now collect all bag attributes from all packages.
3484 size_t ip = grp->packages.size();
3490 const Package* const package = grp->packages[ip];
3491 if (package->header->resourceIDMap) {
3492 uint32_t overlayResID = 0x0;
3493 status_t retval = idmapLookup(package->header->resourceIDMap,
3494 package->header->resourceIDMapSize,
3495 resID, &overlayResID);
3496 if (retval == NO_ERROR && overlayResID != 0x0) {
3497 // for this loop iteration, this is the type and entry we really want
3498 ALOGV("resource map 0x%08x -> 0x%08x\n", resID, overlayResID);
3499 T = Res_GETTYPE(overlayResID);
3500 E = Res_GETENTRY(overlayResID);
3502 // resource not present in overlay package, continue with the next package
3507 const ResTable_type* type;
3508 const ResTable_entry* entry;
3509 const Type* typeClass;
3510 ALOGV("Getting entry pkg=%p, t=%d, e=%d\n", package, T, E);
3511 ssize_t offset = getEntry(package, T, E, &mParams, &type, &entry, &typeClass);
3512 ALOGV("Resulting offset=%d\n", offset);
3514 // No {entry, appropriate config} pair found in package. If this
3515 // package is an overlay package (ip != 0), this simply means the
3516 // overlay package did not specify a default.
3517 // Non-overlay packages are still required to provide a default.
3518 if (offset < 0 && ip == 0) {
3525 if ((dtohs(entry->flags)&entry->FLAG_COMPLEX) == 0) {
3526 ALOGW("Skipping entry %p in package table %d because it is not complex!\n",
3527 (void*)resID, (int)ip);
3531 if (set != NULL && !type->config.isBetterThan(bestConfig, NULL)) {
3534 bestConfig = type->config;
3540 const uint16_t entrySize = dtohs(entry->size);
3541 const uint32_t parent = entrySize >= sizeof(ResTable_map_entry)
3542 ? dtohl(((const ResTable_map_entry*)entry)->parent.ident) : 0;
3543 const uint32_t count = entrySize >= sizeof(ResTable_map_entry)
3544 ? dtohl(((const ResTable_map_entry*)entry)->count) : 0;
3548 TABLE_NOISY(ALOGI("Found map: size=%p parent=%p count=%d\n",
3549 entrySize, parent, count));
3551 // If this map inherits from another, we need to start
3552 // with its parent's values. Otherwise start out empty.
3553 TABLE_NOISY(printf("Creating new bag, entrySize=0x%08x, parent=0x%08x\n",
3554 entrySize, parent));
3556 const bag_entry* parentBag;
3557 uint32_t parentTypeSpecFlags = 0;
3558 const ssize_t NP = getBagLocked(parent, &parentBag, &parentTypeSpecFlags);
3559 const size_t NT = ((NP >= 0) ? NP : 0) + N;
3560 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*NT);
3565 memcpy(set+1, parentBag, NP*sizeof(bag_entry));
3567 TABLE_NOISY(ALOGI("Initialized new bag with %d inherited attributes.\n", NP));
3569 TABLE_NOISY(ALOGI("Initialized new bag with no inherited attributes.\n"));
3572 set->availAttrs = NT;
3573 set->typeSpecFlags = parentTypeSpecFlags;
3575 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*N);
3580 set->availAttrs = N;
3581 set->typeSpecFlags = 0;
3584 if (typeClass->typeSpecFlags != NULL) {
3585 set->typeSpecFlags |= dtohl(typeClass->typeSpecFlags[E]);
3587 set->typeSpecFlags = -1;
3590 // Now merge in the new attributes...
3591 ssize_t curOff = offset;
3592 const ResTable_map* map;
3593 bag_entry* entries = (bag_entry*)(set+1);
3594 size_t curEntry = 0;
3596 TABLE_NOISY(ALOGI("Starting with set %p, entries=%p, avail=%d\n",
3597 set, entries, set->availAttrs));
3598 while (pos < count) {
3599 TABLE_NOISY(printf("Now at %p\n", (void*)curOff));
3601 if ((size_t)curOff > (dtohl(type->header.size)-sizeof(ResTable_map))) {
3602 ALOGW("ResTable_map at %d is beyond type chunk data %d",
3603 (int)curOff, dtohl(type->header.size));
3606 map = (const ResTable_map*)(((const uint8_t*)type) + curOff);
3609 const uint32_t newName = htodl(map->name.ident);
3611 uint32_t oldName = 0;
3612 while ((isInside=(curEntry < set->numAttrs))
3613 && (oldName=entries[curEntry].map.name.ident) < newName) {
3614 TABLE_NOISY(printf("#%d: Keeping existing attribute: 0x%08x\n",
3615 curEntry, entries[curEntry].map.name.ident));
3619 if ((!isInside) || oldName != newName) {
3620 // This is a new attribute... figure out what to do with it.
3621 if (set->numAttrs >= set->availAttrs) {
3622 // Need to alloc more memory...
3623 const size_t newAvail = set->availAttrs+N;
3624 set = (bag_set*)realloc(set,
3626 + sizeof(bag_entry)*newAvail);
3630 set->availAttrs = newAvail;
3631 entries = (bag_entry*)(set+1);
3632 TABLE_NOISY(printf("Reallocated set %p, entries=%p, avail=%d\n",
3633 set, entries, set->availAttrs));
3636 // Going in the middle, need to make space.
3637 memmove(entries+curEntry+1, entries+curEntry,
3638 sizeof(bag_entry)*(set->numAttrs-curEntry));
3641 TABLE_NOISY(printf("#%d: Inserting new attribute: 0x%08x\n",
3642 curEntry, newName));
3644 TABLE_NOISY(printf("#%d: Replacing existing attribute: 0x%08x\n",
3645 curEntry, oldName));
3648 bag_entry* cur = entries+curEntry;
3650 cur->stringBlock = package->header->index;
3651 cur->map.name.ident = newName;
3652 cur->map.value.copyFrom_dtoh(map->value);
3653 TABLE_NOISY(printf("Setting entry #%d %p: block=%d, name=0x%08x, type=%d, data=0x%08x\n",
3654 curEntry, cur, cur->stringBlock, cur->map.name.ident,
3655 cur->map.value.dataType, cur->map.value.data));
3660 const size_t size = dtohs(map->value.size);
3661 curOff += size + sizeof(*map)-sizeof(map->value);
3663 if (curEntry > set->numAttrs) {
3664 set->numAttrs = curEntry;
3668 // And this is it...
3671 if (outTypeSpecFlags != NULL) {
3672 *outTypeSpecFlags = set->typeSpecFlags;
3674 *outBag = (bag_entry*)(set+1);
3675 TABLE_NOISY(ALOGI("Returning %d attrs\n", set->numAttrs));
3676 return set->numAttrs;
3681 void ResTable::setParameters(const ResTable_config* params)
3684 TABLE_GETENTRY(ALOGI("Setting parameters: %s\n", params->toString().string()));
3686 for (size_t i=0; i<mPackageGroups.size(); i++) {
3687 TABLE_NOISY(ALOGI("CLEARING BAGS FOR GROUP %d!", i));
3688 mPackageGroups[i]->clearBagCache();
3693 void ResTable::getParameters(ResTable_config* params) const
3700 struct id_name_map {
3706 const static id_name_map ID_NAMES[] = {
3707 { ResTable_map::ATTR_TYPE, 5, { '^', 't', 'y', 'p', 'e' } },
3708 { ResTable_map::ATTR_L10N, 5, { '^', 'l', '1', '0', 'n' } },
3709 { ResTable_map::ATTR_MIN, 4, { '^', 'm', 'i', 'n' } },
3710 { ResTable_map::ATTR_MAX, 4, { '^', 'm', 'a', 'x' } },
3711 { ResTable_map::ATTR_OTHER, 6, { '^', 'o', 't', 'h', 'e', 'r' } },
3712 { ResTable_map::ATTR_ZERO, 5, { '^', 'z', 'e', 'r', 'o' } },
3713 { ResTable_map::ATTR_ONE, 4, { '^', 'o', 'n', 'e' } },
3714 { ResTable_map::ATTR_TWO, 4, { '^', 't', 'w', 'o' } },
3715 { ResTable_map::ATTR_FEW, 4, { '^', 'f', 'e', 'w' } },
3716 { ResTable_map::ATTR_MANY, 5, { '^', 'm', 'a', 'n', 'y' } },
3719 uint32_t ResTable::identifierForName(const char16_t* name, size_t nameLen,
3720 const char16_t* type, size_t typeLen,
3721 const char16_t* package,
3723 uint32_t* outTypeSpecFlags) const
3725 TABLE_SUPER_NOISY(printf("Identifier for name: error=%d\n", mError));
3727 // Check for internal resource identifier as the very first thing, so
3728 // that we will always find them even when there are no resources.
3729 if (name[0] == '^') {
3730 const int N = (sizeof(ID_NAMES)/sizeof(ID_NAMES[0]));
3732 for (int i=0; i<N; i++) {
3733 const id_name_map* m = ID_NAMES + i;
3735 if (len != nameLen) {
3738 for (size_t j=1; j<len; j++) {
3739 if (m->name[j] != name[j]) {
3743 if (outTypeSpecFlags) {
3744 *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC;
3751 if (name[1] == 'i' && name[2] == 'n'
3752 && name[3] == 'd' && name[4] == 'e' && name[5] == 'x'
3753 && name[6] == '_') {
3754 int index = atoi(String8(name + 7, nameLen - 7).string());
3755 if (Res_CHECKID(index)) {
3756 ALOGW("Array resource index: %d is too large.",
3760 if (outTypeSpecFlags) {
3761 *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC;
3763 return Res_MAKEARRAY(index);
3769 if (mError != NO_ERROR) {
3773 bool fakePublic = false;
3775 // Figure out the package and type we are looking in...
3777 const char16_t* packageEnd = NULL;
3778 const char16_t* typeEnd = NULL;
3779 const char16_t* const nameEnd = name+nameLen;
3780 const char16_t* p = name;
3781 while (p < nameEnd) {
3782 if (*p == ':') packageEnd = p;
3783 else if (*p == '/') typeEnd = p;
3793 if (name >= nameEnd) {
3799 packageLen = packageEnd-name;
3800 name = packageEnd+1;
3801 } else if (!package) {
3807 typeLen = typeEnd-name;
3813 if (name >= nameEnd) {
3816 nameLen = nameEnd-name;
3818 TABLE_NOISY(printf("Looking for identifier: type=%s, name=%s, package=%s\n",
3819 String8(type, typeLen).string(),
3820 String8(name, nameLen).string(),
3821 String8(package, packageLen).string()));
3823 const size_t NG = mPackageGroups.size();
3824 for (size_t ig=0; ig<NG; ig++) {
3825 const PackageGroup* group = mPackageGroups[ig];
3827 if (strzcmp16(package, packageLen,
3828 group->name.string(), group->name.size())) {
3829 TABLE_NOISY(printf("Skipping package group: %s\n", String8(group->name).string()));
3833 const ssize_t ti = group->basePackage->typeStrings.indexOfString(type, typeLen);
3835 TABLE_NOISY(printf("Type not found in package %s\n", String8(group->name).string()));
3839 const ssize_t ei = group->basePackage->keyStrings.indexOfString(name, nameLen);
3841 TABLE_NOISY(printf("Name not found in package %s\n", String8(group->name).string()));
3845 TABLE_NOISY(printf("Search indices: type=%d, name=%d\n", ti, ei));
3847 const Type* const typeConfigs = group->packages[0]->getType(ti);
3848 if (typeConfigs == NULL || typeConfigs->configs.size() <= 0) {
3849 TABLE_NOISY(printf("Expected type structure not found in package %s for idnex %d\n",
3850 String8(group->name).string(), ti));
3853 size_t NTC = typeConfigs->configs.size();
3854 for (size_t tci=0; tci<NTC; tci++) {
3855 const ResTable_type* const ty = typeConfigs->configs[tci];
3856 const uint32_t typeOffset = dtohl(ty->entriesStart);
3858 const uint8_t* const end = ((const uint8_t*)ty) + dtohl(ty->header.size);
3859 const uint32_t* const eindex = (const uint32_t*)
3860 (((const uint8_t*)ty) + dtohs(ty->header.headerSize));
3862 const size_t NE = dtohl(ty->entryCount);
3863 for (size_t i=0; i<NE; i++) {
3864 uint32_t offset = dtohl(eindex[i]);
3865 if (offset == ResTable_type::NO_ENTRY) {
3869 offset += typeOffset;
3871 if (offset > (dtohl(ty->header.size)-sizeof(ResTable_entry))) {
3872 ALOGW("ResTable_entry at %d is beyond type chunk data %d",
3873 offset, dtohl(ty->header.size));
3876 if ((offset&0x3) != 0) {
3877 ALOGW("ResTable_entry at %d (pkg=%d type=%d ent=%d) is not on an integer boundary when looking for %s:%s/%s",
3878 (int)offset, (int)group->id, (int)ti+1, (int)i,
3879 String8(package, packageLen).string(),
3880 String8(type, typeLen).string(),
3881 String8(name, nameLen).string());
3885 const ResTable_entry* const entry = (const ResTable_entry*)
3886 (((const uint8_t*)ty) + offset);
3887 if (dtohs(entry->size) < sizeof(*entry)) {
3888 ALOGW("ResTable_entry size %d is too small", dtohs(entry->size));
3892 TABLE_SUPER_NOISY(printf("Looking at entry #%d: want str %d, have %d\n",
3893 i, ei, dtohl(entry->key.index)));
3894 if (dtohl(entry->key.index) == (size_t)ei) {
3895 if (outTypeSpecFlags) {
3896 *outTypeSpecFlags = typeConfigs->typeSpecFlags[i];
3898 *outTypeSpecFlags |= ResTable_typeSpec::SPEC_PUBLIC;
3901 return Res_MAKEID(group->id-1, ti, i);
3910 bool ResTable::expandResourceRef(const uint16_t* refStr, size_t refLen,
3911 String16* outPackage,
3914 const String16* defType,
3915 const String16* defPackage,
3916 const char** outErrorMsg,
3917 bool* outPublicOnly)
3919 const char16_t* packageEnd = NULL;
3920 const char16_t* typeEnd = NULL;
3921 const char16_t* p = refStr;
3922 const char16_t* const end = p + refLen;
3924 if (*p == ':') packageEnd = p;
3925 else if (*p == '/') {
3934 if (outPublicOnly != NULL) {
3935 *outPublicOnly = true;
3939 if (outPublicOnly != NULL) {
3940 *outPublicOnly = false;
3945 *outPackage = String16(p, packageEnd-p);
3950 *outErrorMsg = "No resource package specified";
3954 *outPackage = *defPackage;
3957 *outType = String16(p, typeEnd-p);
3962 *outErrorMsg = "No resource type specified";
3966 *outType = *defType;
3968 *outName = String16(p, end-p);
3969 if(**outPackage == 0) {
3971 *outErrorMsg = "Resource package cannot be an empty string";
3975 if(**outType == 0) {
3977 *outErrorMsg = "Resource type cannot be an empty string";
3981 if(**outName == 0) {
3983 *outErrorMsg = "Resource id cannot be an empty string";
3990 static uint32_t get_hex(char c, bool* outError)
3992 if (c >= '0' && c <= '9') {
3994 } else if (c >= 'a' && c <= 'f') {
3995 return c - 'a' + 0xa;
3996 } else if (c >= 'A' && c <= 'F') {
3997 return c - 'A' + 0xa;
4012 static const unit_entry unitNames[] = {
4013 { "px", strlen("px"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PX, 1.0f },
4014 { "dip", strlen("dip"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
4015 { "dp", strlen("dp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
4016 { "sp", strlen("sp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_SP, 1.0f },
4017 { "pt", strlen("pt"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PT, 1.0f },
4018 { "in", strlen("in"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_IN, 1.0f },
4019 { "mm", strlen("mm"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_MM, 1.0f },
4020 { "%", strlen("%"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION, 1.0f/100 },
4021 { "%p", strlen("%p"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION_PARENT, 1.0f/100 },
4022 { NULL, 0, 0, 0, 0 }
4025 static bool parse_unit(const char* str, Res_value* outValue,
4026 float* outScale, const char** outEnd)
4028 const char* end = str;
4029 while (*end != 0 && !isspace((unsigned char)*end)) {
4032 const size_t len = end-str;
4034 const char* realEnd = end;
4035 while (*realEnd != 0 && isspace((unsigned char)*realEnd)) {
4038 if (*realEnd != 0) {
4042 const unit_entry* cur = unitNames;
4044 if (len == cur->len && strncmp(cur->name, str, len) == 0) {
4045 outValue->dataType = cur->type;
4046 outValue->data = cur->unit << Res_value::COMPLEX_UNIT_SHIFT;
4047 *outScale = cur->scale;
4049 //printf("Found unit %s for %s\n", cur->name, str);
4059 bool ResTable::stringToInt(const char16_t* s, size_t len, Res_value* outValue)
4061 while (len > 0 && isspace16(*s)) {
4079 if (s[i] < '0' || s[i] > '9') {
4084 if (s[i] == '0' && s[i+1] == 'x') {
4086 outValue->dataType = outValue->TYPE_INT_HEX;
4089 while (i < len && !error) {
4090 val = (val*16) + get_hex(s[i], &error);
4098 outValue->dataType = outValue->TYPE_INT_DEC;
4100 if (s[i] < '0' || s[i] > '9') {
4103 val = (val*10) + s[i]-'0';
4108 if (neg) val = -val;
4110 while (i < len && isspace16(s[i])) {
4116 outValue->data = val;
4123 bool ResTable::stringToFloat(const char16_t* s, size_t len, Res_value* outValue)
4125 while (len > 0 && isspace16(*s)) {
4136 while (len > 0 && *s != 0 && i < 126) {
4147 if (buf[0] < '0' && buf[0] > '9' && buf[0] != '.') {
4153 float f = strtof(buf, (char**)&end);
4155 if (*end != 0 && !isspace((unsigned char)*end)) {
4156 // Might be a unit...
4158 if (parse_unit(end, outValue, &scale, &end)) {
4160 const bool neg = f < 0;
4162 uint64_t bits = (uint64_t)(f*(1<<23)+.5f);
4165 if ((bits&0x7fffff) == 0) {
4166 // Always use 23p0 if there is no fraction, just to make
4167 // things easier to read.
4168 radix = Res_value::COMPLEX_RADIX_23p0;
4170 } else if ((bits&0xffffffffff800000LL) == 0) {
4171 // Magnitude is zero -- can fit in 0 bits of precision.
4172 radix = Res_value::COMPLEX_RADIX_0p23;
4174 } else if ((bits&0xffffffff80000000LL) == 0) {
4175 // Magnitude can fit in 8 bits of precision.
4176 radix = Res_value::COMPLEX_RADIX_8p15;
4178 } else if ((bits&0xffffff8000000000LL) == 0) {
4179 // Magnitude can fit in 16 bits of precision.
4180 radix = Res_value::COMPLEX_RADIX_16p7;
4183 // Magnitude needs entire range, so no fractional part.
4184 radix = Res_value::COMPLEX_RADIX_23p0;
4187 int32_t mantissa = (int32_t)(
4188 (bits>>shift) & Res_value::COMPLEX_MANTISSA_MASK);
4190 mantissa = (-mantissa) & Res_value::COMPLEX_MANTISSA_MASK;
4193 (radix<<Res_value::COMPLEX_RADIX_SHIFT)
4194 | (mantissa<<Res_value::COMPLEX_MANTISSA_SHIFT);
4195 //printf("Input value: %f 0x%016Lx, mult: %f, radix: %d, shift: %d, final: 0x%08x\n",
4196 // f * (neg ? -1 : 1), bits, f*(1<<23),
4197 // radix, shift, outValue->data);
4203 while (*end != 0 && isspace((unsigned char)*end)) {
4209 outValue->dataType = outValue->TYPE_FLOAT;
4210 *(float*)(&outValue->data) = f;
4218 bool ResTable::stringToValue(Res_value* outValue, String16* outString,
4219 const char16_t* s, size_t len,
4220 bool preserveSpaces, bool coerceType,
4222 const String16* defType,
4223 const String16* defPackage,
4225 void* accessorCookie,
4227 bool enforcePrivate) const
4229 bool localizationSetting = accessor != NULL && accessor->getLocalizationSetting();
4230 const char* errorMsg = NULL;
4232 outValue->size = sizeof(Res_value);
4235 // First strip leading/trailing whitespace. Do this before handling
4236 // escapes, so they can be used to force whitespace into the string.
4237 if (!preserveSpaces) {
4238 while (len > 0 && isspace16(*s)) {
4242 while (len > 0 && isspace16(s[len-1])) {
4245 // If the string ends with '\', then we keep the space after it.
4246 if (len > 0 && s[len-1] == '\\' && s[len] != 0) {
4251 //printf("Value for: %s\n", String8(s, len).string());
4253 uint32_t l10nReq = ResTable_map::L10N_NOT_REQUIRED;
4254 uint32_t attrMin = 0x80000000, attrMax = 0x7fffffff;
4255 bool fromAccessor = false;
4256 if (attrID != 0 && !Res_INTERNALID(attrID)) {
4257 const ssize_t p = getResourcePackageIndex(attrID);
4258 const bag_entry* bag;
4259 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
4260 //printf("For attr 0x%08x got bag of %d\n", attrID, cnt);
4263 //printf("Entry 0x%08x = 0x%08x\n", bag->map.name.ident, bag->map.value.data);
4264 switch (bag->map.name.ident) {
4265 case ResTable_map::ATTR_TYPE:
4266 attrType = bag->map.value.data;
4268 case ResTable_map::ATTR_MIN:
4269 attrMin = bag->map.value.data;
4271 case ResTable_map::ATTR_MAX:
4272 attrMax = bag->map.value.data;
4274 case ResTable_map::ATTR_L10N:
4275 l10nReq = bag->map.value.data;
4282 } else if (accessor && accessor->getAttributeType(attrID, &attrType)) {
4283 fromAccessor = true;
4284 if (attrType == ResTable_map::TYPE_ENUM
4285 || attrType == ResTable_map::TYPE_FLAGS
4286 || attrType == ResTable_map::TYPE_INTEGER) {
4287 accessor->getAttributeMin(attrID, &attrMin);
4288 accessor->getAttributeMax(attrID, &attrMax);
4290 if (localizationSetting) {
4291 l10nReq = accessor->getAttributeL10N(attrID);
4296 const bool canStringCoerce =
4297 coerceType && (attrType&ResTable_map::TYPE_STRING) != 0;
4300 outValue->dataType = outValue->TYPE_REFERENCE;
4302 // Note: we don't check attrType here because the reference can
4303 // be to any other type; we just need to count on the client making
4304 // sure the referenced type is correct.
4306 //printf("Looking up ref: %s\n", String8(s, len).string());
4308 // It's a reference!
4309 if (len == 5 && s[1]=='n' && s[2]=='u' && s[3]=='l' && s[4]=='l') {
4313 bool createIfNotFound = false;
4314 const char16_t* resourceRefName;
4315 int resourceNameLen;
4316 if (len > 2 && s[1] == '+') {
4317 createIfNotFound = true;
4318 resourceRefName = s + 2;
4319 resourceNameLen = len - 2;
4320 } else if (len > 2 && s[1] == '*') {
4321 enforcePrivate = false;
4322 resourceRefName = s + 2;
4323 resourceNameLen = len - 2;
4325 createIfNotFound = false;
4326 resourceRefName = s + 1;
4327 resourceNameLen = len - 1;
4329 String16 package, type, name;
4330 if (!expandResourceRef(resourceRefName,resourceNameLen, &package, &type, &name,
4331 defType, defPackage, &errorMsg)) {
4332 if (accessor != NULL) {
4333 accessor->reportError(accessorCookie, errorMsg);
4338 uint32_t specFlags = 0;
4339 uint32_t rid = identifierForName(name.string(), name.size(), type.string(),
4340 type.size(), package.string(), package.size(), &specFlags);
4342 if (enforcePrivate) {
4343 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
4344 if (accessor != NULL) {
4345 accessor->reportError(accessorCookie, "Resource is not public.");
4351 outValue->data = rid;
4355 accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
4356 Res_GETTYPE(rid), Res_GETENTRY(rid));
4357 TABLE_NOISY(printf("Incl %s:%s/%s: 0x%08x\n",
4358 String8(package).string(), String8(type).string(),
4359 String8(name).string(), rid));
4360 outValue->data = rid;
4365 uint32_t rid = accessor->getCustomResourceWithCreation(package, type, name,
4368 TABLE_NOISY(printf("Pckg %s:%s/%s: 0x%08x\n",
4369 String8(package).string(), String8(type).string(),
4370 String8(name).string(), rid));
4371 outValue->data = rid;
4377 if (accessor != NULL) {
4378 accessor->reportError(accessorCookie, "No resource found that matches the given name");
4383 // if we got to here, and localization is required and it's not a reference,
4384 // complain and bail.
4385 if (l10nReq == ResTable_map::L10N_SUGGESTED) {
4386 if (localizationSetting) {
4387 if (accessor != NULL) {
4388 accessor->reportError(accessorCookie, "This attribute must be localized.");
4394 // It's a color! Convert to an integer of the form 0xaarrggbb.
4398 outValue->dataType = outValue->TYPE_INT_COLOR_RGB4;
4399 color |= 0xFF000000;
4400 color |= get_hex(s[1], &error) << 20;
4401 color |= get_hex(s[1], &error) << 16;
4402 color |= get_hex(s[2], &error) << 12;
4403 color |= get_hex(s[2], &error) << 8;
4404 color |= get_hex(s[3], &error) << 4;
4405 color |= get_hex(s[3], &error);
4406 } else if (len == 5) {
4407 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB4;
4408 color |= get_hex(s[1], &error) << 28;
4409 color |= get_hex(s[1], &error) << 24;
4410 color |= get_hex(s[2], &error) << 20;
4411 color |= get_hex(s[2], &error) << 16;
4412 color |= get_hex(s[3], &error) << 12;
4413 color |= get_hex(s[3], &error) << 8;
4414 color |= get_hex(s[4], &error) << 4;
4415 color |= get_hex(s[4], &error);
4416 } else if (len == 7) {
4417 outValue->dataType = outValue->TYPE_INT_COLOR_RGB8;
4418 color |= 0xFF000000;
4419 color |= get_hex(s[1], &error) << 20;
4420 color |= get_hex(s[2], &error) << 16;
4421 color |= get_hex(s[3], &error) << 12;
4422 color |= get_hex(s[4], &error) << 8;
4423 color |= get_hex(s[5], &error) << 4;
4424 color |= get_hex(s[6], &error);
4425 } else if (len == 9) {
4426 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB8;
4427 color |= get_hex(s[1], &error) << 28;
4428 color |= get_hex(s[2], &error) << 24;
4429 color |= get_hex(s[3], &error) << 20;
4430 color |= get_hex(s[4], &error) << 16;
4431 color |= get_hex(s[5], &error) << 12;
4432 color |= get_hex(s[6], &error) << 8;
4433 color |= get_hex(s[7], &error) << 4;
4434 color |= get_hex(s[8], &error);
4439 if ((attrType&ResTable_map::TYPE_COLOR) == 0) {
4440 if (!canStringCoerce) {
4441 if (accessor != NULL) {
4442 accessor->reportError(accessorCookie,
4443 "Color types not allowed");
4448 outValue->data = color;
4449 //printf("Color input=%s, output=0x%x\n", String8(s, len).string(), color);
4453 if ((attrType&ResTable_map::TYPE_COLOR) != 0) {
4454 if (accessor != NULL) {
4455 accessor->reportError(accessorCookie, "Color value not valid --"
4456 " must be #rgb, #argb, #rrggbb, or #aarrggbb");
4459 fprintf(stderr, "%s: Color ID %s value %s is not valid\n",
4460 "Resource File", //(const char*)in->getPrintableSource(),
4461 String8(*curTag).string(),
4462 String8(s, len).string());
4470 outValue->dataType = outValue->TYPE_ATTRIBUTE;
4472 // Note: we don't check attrType here because the reference can
4473 // be to any other type; we just need to count on the client making
4474 // sure the referenced type is correct.
4476 //printf("Looking up attr: %s\n", String8(s, len).string());
4478 static const String16 attr16("attr");
4479 String16 package, type, name;
4480 if (!expandResourceRef(s+1, len-1, &package, &type, &name,
4481 &attr16, defPackage, &errorMsg)) {
4482 if (accessor != NULL) {
4483 accessor->reportError(accessorCookie, errorMsg);
4488 //printf("Pkg: %s, Type: %s, Name: %s\n",
4489 // String8(package).string(), String8(type).string(),
4490 // String8(name).string());
4491 uint32_t specFlags = 0;
4493 identifierForName(name.string(), name.size(),
4494 type.string(), type.size(),
4495 package.string(), package.size(), &specFlags);
4497 if (enforcePrivate) {
4498 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
4499 if (accessor != NULL) {
4500 accessor->reportError(accessorCookie, "Attribute is not public.");
4506 outValue->data = rid;
4510 accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
4511 Res_GETTYPE(rid), Res_GETENTRY(rid));
4512 //printf("Incl %s:%s/%s: 0x%08x\n",
4513 // String8(package).string(), String8(type).string(),
4514 // String8(name).string(), rid);
4515 outValue->data = rid;
4520 uint32_t rid = accessor->getCustomResource(package, type, name);
4522 //printf("Mine %s:%s/%s: 0x%08x\n",
4523 // String8(package).string(), String8(type).string(),
4524 // String8(name).string(), rid);
4525 outValue->data = rid;
4530 if (accessor != NULL) {
4531 accessor->reportError(accessorCookie, "No resource found that matches the given name");
4536 if (stringToInt(s, len, outValue)) {
4537 if ((attrType&ResTable_map::TYPE_INTEGER) == 0) {
4538 // If this type does not allow integers, but does allow floats,
4539 // fall through on this error case because the float type should
4540 // be able to accept any integer value.
4541 if (!canStringCoerce && (attrType&ResTable_map::TYPE_FLOAT) == 0) {
4542 if (accessor != NULL) {
4543 accessor->reportError(accessorCookie, "Integer types not allowed");
4548 if (((int32_t)outValue->data) < ((int32_t)attrMin)
4549 || ((int32_t)outValue->data) > ((int32_t)attrMax)) {
4550 if (accessor != NULL) {
4551 accessor->reportError(accessorCookie, "Integer value out of range");
4559 if (stringToFloat(s, len, outValue)) {
4560 if (outValue->dataType == Res_value::TYPE_DIMENSION) {
4561 if ((attrType&ResTable_map::TYPE_DIMENSION) != 0) {
4564 if (!canStringCoerce) {
4565 if (accessor != NULL) {
4566 accessor->reportError(accessorCookie, "Dimension types not allowed");
4570 } else if (outValue->dataType == Res_value::TYPE_FRACTION) {
4571 if ((attrType&ResTable_map::TYPE_FRACTION) != 0) {
4574 if (!canStringCoerce) {
4575 if (accessor != NULL) {
4576 accessor->reportError(accessorCookie, "Fraction types not allowed");
4580 } else if ((attrType&ResTable_map::TYPE_FLOAT) == 0) {
4581 if (!canStringCoerce) {
4582 if (accessor != NULL) {
4583 accessor->reportError(accessorCookie, "Float types not allowed");
4593 if ((s[0] == 't' || s[0] == 'T') &&
4594 (s[1] == 'r' || s[1] == 'R') &&
4595 (s[2] == 'u' || s[2] == 'U') &&
4596 (s[3] == 'e' || s[3] == 'E')) {
4597 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
4598 if (!canStringCoerce) {
4599 if (accessor != NULL) {
4600 accessor->reportError(accessorCookie, "Boolean types not allowed");
4605 outValue->dataType = outValue->TYPE_INT_BOOLEAN;
4606 outValue->data = (uint32_t)-1;
4613 if ((s[0] == 'f' || s[0] == 'F') &&
4614 (s[1] == 'a' || s[1] == 'A') &&
4615 (s[2] == 'l' || s[2] == 'L') &&
4616 (s[3] == 's' || s[3] == 'S') &&
4617 (s[4] == 'e' || s[4] == 'E')) {
4618 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
4619 if (!canStringCoerce) {
4620 if (accessor != NULL) {
4621 accessor->reportError(accessorCookie, "Boolean types not allowed");
4626 outValue->dataType = outValue->TYPE_INT_BOOLEAN;
4633 if ((attrType&ResTable_map::TYPE_ENUM) != 0) {
4634 const ssize_t p = getResourcePackageIndex(attrID);
4635 const bag_entry* bag;
4636 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
4637 //printf("Got %d for enum\n", cnt);
4639 resource_name rname;
4641 if (!Res_INTERNALID(bag->map.name.ident)) {
4642 //printf("Trying attr #%08x\n", bag->map.name.ident);
4643 if (getResourceName(bag->map.name.ident, false, &rname)) {
4645 printf("Matching %s against %s (0x%08x)\n",
4646 String8(s, len).string(),
4647 String8(rname.name, rname.nameLen).string(),
4648 bag->map.name.ident);
4650 if (strzcmp16(s, len, rname.name, rname.nameLen) == 0) {
4651 outValue->dataType = bag->map.value.dataType;
4652 outValue->data = bag->map.value.data;
4666 if (accessor->getAttributeEnum(attrID, s, len, outValue)) {
4672 if ((attrType&ResTable_map::TYPE_FLAGS) != 0) {
4673 const ssize_t p = getResourcePackageIndex(attrID);
4674 const bag_entry* bag;
4675 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
4676 //printf("Got %d for flags\n", cnt);
4678 bool failed = false;
4679 resource_name rname;
4680 outValue->dataType = Res_value::TYPE_INT_HEX;
4682 const char16_t* end = s + len;
4683 const char16_t* pos = s;
4684 while (pos < end && !failed) {
4685 const char16_t* start = pos;
4687 while (pos < end && *pos != '|') {
4690 //printf("Looking for: %s\n", String8(start, pos-start).string());
4691 const bag_entry* bagi = bag;
4693 for (i=0; i<cnt; i++, bagi++) {
4694 if (!Res_INTERNALID(bagi->map.name.ident)) {
4695 //printf("Trying attr #%08x\n", bagi->map.name.ident);
4696 if (getResourceName(bagi->map.name.ident, false, &rname)) {
4698 printf("Matching %s against %s (0x%08x)\n",
4699 String8(start,pos-start).string(),
4700 String8(rname.name, rname.nameLen).string(),
4701 bagi->map.name.ident);
4703 if (strzcmp16(start, pos-start, rname.name, rname.nameLen) == 0) {
4704 outValue->data |= bagi->map.value.data;
4711 // Didn't find this flag identifier.
4720 //printf("Final flag value: 0x%lx\n", outValue->data);
4727 if (accessor->getAttributeFlags(attrID, s, len, outValue)) {
4728 //printf("Final flag value: 0x%lx\n", outValue->data);
4734 if ((attrType&ResTable_map::TYPE_STRING) == 0) {
4735 if (accessor != NULL) {
4736 accessor->reportError(accessorCookie, "String types not allowed");
4741 // Generic string handling...
4742 outValue->dataType = outValue->TYPE_STRING;
4744 bool failed = collectString(outString, s, len, preserveSpaces, &errorMsg);
4745 if (accessor != NULL) {
4746 accessor->reportError(accessorCookie, errorMsg);
4754 bool ResTable::collectString(String16* outString,
4755 const char16_t* s, size_t len,
4756 bool preserveSpaces,
4757 const char** outErrorMsg,
4763 const char16_t* p = s;
4764 while (p < (s+len)) {
4765 while (p < (s+len)) {
4766 const char16_t c = *p;
4770 if (!preserveSpaces) {
4771 if (quoted == 0 && isspace16(c)
4772 && (c != ' ' || isspace16(*(p+1)))) {
4775 if (c == '"' && (quoted == 0 || quoted == '"')) {
4778 if (c == '\'' && (quoted == 0 || quoted == '\'')) {
4780 * In practice, when people write ' instead of \'
4781 * in a string, they are doing it by accident
4782 * instead of really meaning to use ' as a quoting
4783 * character. Warn them so they don't lose it.
4786 *outErrorMsg = "Apostrophe not preceded by \\";
4795 tmp.append(String16(s, p-s));
4797 if (!preserveSpaces && (*p == '"' || *p == '\'')) {
4804 } else if (!preserveSpaces && isspace16(*p)) {
4805 // Space outside of a quote -- consume all spaces and
4806 // leave a single plain space char.
4807 tmp.append(String16(" "));
4809 while (p < (s+len) && isspace16(*p)) {
4812 } else if (*p == '\\') {
4817 tmp.append(String16("\t"));
4820 tmp.append(String16("\n"));
4823 tmp.append(String16("#"));
4826 tmp.append(String16("@"));
4829 tmp.append(String16("?"));
4832 tmp.append(String16("\""));
4835 tmp.append(String16("'"));
4838 tmp.append(String16("\\"));
4844 while (i < 4 && p[1] != 0) {
4848 if (*p >= '0' && *p <= '9') {
4850 } else if (*p >= 'a' && *p <= 'f') {
4852 } else if (*p >= 'A' && *p <= 'F') {
4856 *outErrorMsg = "Bad character in \\u unicode escape sequence";
4862 tmp.append(String16(&chr, 1));
4865 // ignore unknown escape chars.
4876 if (tmp.size() != 0) {
4878 tmp.append(String16(s, len));
4881 outString->append(tmp);
4883 outString->setTo(tmp);
4887 outString->append(String16(s, len));
4889 outString->setTo(s, len);
4896 size_t ResTable::getBasePackageCount() const
4898 if (mError != NO_ERROR) {
4901 return mPackageGroups.size();
4904 const char16_t* ResTable::getBasePackageName(size_t idx) const
4906 if (mError != NO_ERROR) {
4909 LOG_FATAL_IF(idx >= mPackageGroups.size(),
4910 "Requested package index %d past package count %d",
4911 (int)idx, (int)mPackageGroups.size());
4912 return mPackageGroups[idx]->name.string();
4915 uint32_t ResTable::getBasePackageId(size_t idx) const
4917 if (mError != NO_ERROR) {
4920 LOG_FATAL_IF(idx >= mPackageGroups.size(),
4921 "Requested package index %d past package count %d",
4922 (int)idx, (int)mPackageGroups.size());
4923 return mPackageGroups[idx]->id;
4926 size_t ResTable::getTableCount() const
4928 return mHeaders.size();
4931 const ResStringPool* ResTable::getTableStringBlock(size_t index) const
4933 return &mHeaders[index]->values;
4936 void* ResTable::getTableCookie(size_t index) const
4938 return mHeaders[index]->cookie;
4941 void ResTable::getConfigurations(Vector<ResTable_config>* configs) const
4943 const size_t I = mPackageGroups.size();
4944 for (size_t i=0; i<I; i++) {
4945 const PackageGroup* packageGroup = mPackageGroups[i];
4946 const size_t J = packageGroup->packages.size();
4947 for (size_t j=0; j<J; j++) {
4948 const Package* package = packageGroup->packages[j];
4949 const size_t K = package->types.size();
4950 for (size_t k=0; k<K; k++) {
4951 const Type* type = package->types[k];
4952 if (type == NULL) continue;
4953 const size_t L = type->configs.size();
4954 for (size_t l=0; l<L; l++) {
4955 const ResTable_type* config = type->configs[l];
4956 const ResTable_config* cfg = &config->config;
4957 // only insert unique
4958 const size_t M = configs->size();
4960 for (m=0; m<M; m++) {
4961 if (0 == (*configs)[m].compare(*cfg)) {
4965 // if we didn't find it
4975 void ResTable::getLocales(Vector<String8>* locales) const
4977 Vector<ResTable_config> configs;
4978 ALOGV("calling getConfigurations");
4979 getConfigurations(&configs);
4980 ALOGV("called getConfigurations size=%d", (int)configs.size());
4981 const size_t I = configs.size();
4982 for (size_t i=0; i<I; i++) {
4984 configs[i].getLocale(locale);
4985 const size_t J = locales->size();
4987 for (j=0; j<J; j++) {
4988 if (0 == strcmp(locale, (*locales)[j].string())) {
4993 locales->add(String8(locale));
4998 ssize_t ResTable::getEntry(
4999 const Package* package, int typeIndex, int entryIndex,
5000 const ResTable_config* config,
5001 const ResTable_type** outType, const ResTable_entry** outEntry,
5002 const Type** outTypeClass) const
5004 ALOGV("Getting entry from package %p\n", package);
5005 const ResTable_package* const pkg = package->package;
5007 const Type* allTypes = package->getType(typeIndex);
5008 ALOGV("allTypes=%p\n", allTypes);
5009 if (allTypes == NULL) {
5010 ALOGV("Skipping entry type index 0x%02x because type is NULL!\n", typeIndex);
5014 if ((size_t)entryIndex >= allTypes->entryCount) {
5015 ALOGW("getEntry failing because entryIndex %d is beyond type entryCount %d",
5016 entryIndex, (int)allTypes->entryCount);
5020 const ResTable_type* type = NULL;
5021 uint32_t offset = ResTable_type::NO_ENTRY;
5022 ResTable_config bestConfig;
5023 memset(&bestConfig, 0, sizeof(bestConfig)); // make the compiler shut up
5025 const size_t NT = allTypes->configs.size();
5026 for (size_t i=0; i<NT; i++) {
5027 const ResTable_type* const thisType = allTypes->configs[i];
5028 if (thisType == NULL) continue;
5030 ResTable_config thisConfig;
5031 thisConfig.copyFromDtoH(thisType->config);
5033 TABLE_GETENTRY(ALOGI("Match entry 0x%x in type 0x%x (sz 0x%x): %s\n",
5034 entryIndex, typeIndex+1, dtohl(thisType->config.size),
5035 thisConfig.toString().string()));
5037 // Check to make sure this one is valid for the current parameters.
5038 if (config && !thisConfig.match(*config)) {
5039 TABLE_GETENTRY(ALOGI("Does not match config!\n"));
5043 // Check if there is the desired entry in this type.
5045 const uint8_t* const end = ((const uint8_t*)thisType)
5046 + dtohl(thisType->header.size);
5047 const uint32_t* const eindex = (const uint32_t*)
5048 (((const uint8_t*)thisType) + dtohs(thisType->header.headerSize));
5050 uint32_t thisOffset = dtohl(eindex[entryIndex]);
5051 if (thisOffset == ResTable_type::NO_ENTRY) {
5052 TABLE_GETENTRY(ALOGI("Skipping because it is not defined!\n"));
5057 // Check if this one is less specific than the last found. If so,
5058 // we will skip it. We check starting with things we most care
5059 // about to those we least care about.
5060 if (!thisConfig.isBetterThan(bestConfig, config)) {
5061 TABLE_GETENTRY(ALOGI("This config is worse than last!\n"));
5067 offset = thisOffset;
5068 bestConfig = thisConfig;
5069 TABLE_GETENTRY(ALOGI("Best entry so far -- using it!\n"));
5074 TABLE_GETENTRY(ALOGI("No value found for requested entry!\n"));
5078 offset += dtohl(type->entriesStart);
5079 TABLE_NOISY(aout << "Looking in resource table " << package->header->header
5081 << (void*)(((const char*)type)-((const char*)package->header->header))
5082 << ", offset=" << (void*)offset << endl);
5084 if (offset > (dtohl(type->header.size)-sizeof(ResTable_entry))) {
5085 ALOGW("ResTable_entry at 0x%x is beyond type chunk data 0x%x",
5086 offset, dtohl(type->header.size));
5089 if ((offset&0x3) != 0) {
5090 ALOGW("ResTable_entry at 0x%x is not on an integer boundary",
5095 const ResTable_entry* const entry = (const ResTable_entry*)
5096 (((const uint8_t*)type) + offset);
5097 if (dtohs(entry->size) < sizeof(*entry)) {
5098 ALOGW("ResTable_entry size 0x%x is too small", dtohs(entry->size));
5104 if (outTypeClass != NULL) {
5105 *outTypeClass = allTypes;
5107 return offset + dtohs(entry->size);
5110 status_t ResTable::parsePackage(const ResTable_package* const pkg,
5111 const Header* const header, uint32_t idmap_id)
5113 const uint8_t* base = (const uint8_t*)pkg;
5114 status_t err = validate_chunk(&pkg->header, sizeof(*pkg),
5115 header->dataEnd, "ResTable_package");
5116 if (err != NO_ERROR) {
5117 return (mError=err);
5120 const size_t pkgSize = dtohl(pkg->header.size);
5122 if (dtohl(pkg->typeStrings) >= pkgSize) {
5123 ALOGW("ResTable_package type strings at %p are past chunk size %p.",
5124 (void*)dtohl(pkg->typeStrings), (void*)pkgSize);
5125 return (mError=BAD_TYPE);
5127 if ((dtohl(pkg->typeStrings)&0x3) != 0) {
5128 ALOGW("ResTable_package type strings at %p is not on an integer boundary.",
5129 (void*)dtohl(pkg->typeStrings));
5130 return (mError=BAD_TYPE);
5132 if (dtohl(pkg->keyStrings) >= pkgSize) {
5133 ALOGW("ResTable_package key strings at %p are past chunk size %p.",
5134 (void*)dtohl(pkg->keyStrings), (void*)pkgSize);
5135 return (mError=BAD_TYPE);
5137 if ((dtohl(pkg->keyStrings)&0x3) != 0) {
5138 ALOGW("ResTable_package key strings at %p is not on an integer boundary.",
5139 (void*)dtohl(pkg->keyStrings));
5140 return (mError=BAD_TYPE);
5143 Package* package = NULL;
5144 PackageGroup* group = NULL;
5145 uint32_t id = idmap_id != 0 ? idmap_id : dtohl(pkg->id);
5146 // If at this point id == 0, pkg is an overlay package without a
5147 // corresponding idmap. During regular usage, overlay packages are
5148 // always loaded alongside their idmaps, but during idmap creation
5149 // the package is temporarily loaded by itself.
5152 package = new Package(this, header, pkg);
5153 if (package == NULL) {
5154 return (mError=NO_MEMORY);
5157 size_t idx = mPackageMap[id];
5159 idx = mPackageGroups.size()+1;
5161 char16_t tmpName[sizeof(pkg->name)/sizeof(char16_t)];
5162 strcpy16_dtoh(tmpName, pkg->name, sizeof(pkg->name)/sizeof(char16_t));
5163 group = new PackageGroup(this, String16(tmpName), id);
5164 if (group == NULL) {
5166 return (mError=NO_MEMORY);
5169 err = package->typeStrings.setTo(base+dtohl(pkg->typeStrings),
5170 header->dataEnd-(base+dtohl(pkg->typeStrings)));
5171 if (err != NO_ERROR) {
5174 return (mError=err);
5176 err = package->keyStrings.setTo(base+dtohl(pkg->keyStrings),
5177 header->dataEnd-(base+dtohl(pkg->keyStrings)));
5178 if (err != NO_ERROR) {
5181 return (mError=err);
5184 //printf("Adding new package id %d at index %d\n", id, idx);
5185 err = mPackageGroups.add(group);
5186 if (err < NO_ERROR) {
5187 return (mError=err);
5189 group->basePackage = package;
5191 mPackageMap[id] = (uint8_t)idx;
5193 group = mPackageGroups.itemAt(idx-1);
5194 if (group == NULL) {
5195 return (mError=UNKNOWN_ERROR);
5198 err = group->packages.add(package);
5199 if (err < NO_ERROR) {
5200 return (mError=err);
5203 LOG_ALWAYS_FATAL("Package id out of range");
5208 // Iterate through all chunks.
5209 size_t curPackage = 0;
5211 const ResChunk_header* chunk =
5212 (const ResChunk_header*)(((const uint8_t*)pkg)
5213 + dtohs(pkg->header.headerSize));
5214 const uint8_t* endPos = ((const uint8_t*)pkg) + dtohs(pkg->header.size);
5215 while (((const uint8_t*)chunk) <= (endPos-sizeof(ResChunk_header)) &&
5216 ((const uint8_t*)chunk) <= (endPos-dtohl(chunk->size))) {
5217 TABLE_NOISY(ALOGV("PackageChunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n",
5218 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
5219 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header))));
5220 const size_t csize = dtohl(chunk->size);
5221 const uint16_t ctype = dtohs(chunk->type);
5222 if (ctype == RES_TABLE_TYPE_SPEC_TYPE) {
5223 const ResTable_typeSpec* typeSpec = (const ResTable_typeSpec*)(chunk);
5224 err = validate_chunk(&typeSpec->header, sizeof(*typeSpec),
5225 endPos, "ResTable_typeSpec");
5226 if (err != NO_ERROR) {
5227 return (mError=err);
5230 const size_t typeSpecSize = dtohl(typeSpec->header.size);
5232 LOAD_TABLE_NOISY(printf("TypeSpec off %p: type=0x%x, headerSize=0x%x, size=%p\n",
5233 (void*)(base-(const uint8_t*)chunk),
5234 dtohs(typeSpec->header.type),
5235 dtohs(typeSpec->header.headerSize),
5237 // look for block overrun or int overflow when multiplying by 4
5238 if ((dtohl(typeSpec->entryCount) > (INT32_MAX/sizeof(uint32_t))
5239 || dtohs(typeSpec->header.headerSize)+(sizeof(uint32_t)*dtohl(typeSpec->entryCount))
5241 ALOGW("ResTable_typeSpec entry index to %p extends beyond chunk end %p.",
5242 (void*)(dtohs(typeSpec->header.headerSize)
5243 +(sizeof(uint32_t)*dtohl(typeSpec->entryCount))),
5244 (void*)typeSpecSize);
5245 return (mError=BAD_TYPE);
5248 if (typeSpec->id == 0) {
5249 ALOGW("ResTable_type has an id of 0.");
5250 return (mError=BAD_TYPE);
5253 while (package->types.size() < typeSpec->id) {
5254 package->types.add(NULL);
5256 Type* t = package->types[typeSpec->id-1];
5258 t = new Type(header, package, dtohl(typeSpec->entryCount));
5259 package->types.editItemAt(typeSpec->id-1) = t;
5260 } else if (dtohl(typeSpec->entryCount) != t->entryCount) {
5261 ALOGW("ResTable_typeSpec entry count inconsistent: given %d, previously %d",
5262 (int)dtohl(typeSpec->entryCount), (int)t->entryCount);
5263 return (mError=BAD_TYPE);
5265 t->typeSpecFlags = (const uint32_t*)(
5266 ((const uint8_t*)typeSpec) + dtohs(typeSpec->header.headerSize));
5267 t->typeSpec = typeSpec;
5269 } else if (ctype == RES_TABLE_TYPE_TYPE) {
5270 const ResTable_type* type = (const ResTable_type*)(chunk);
5271 err = validate_chunk(&type->header, sizeof(*type)-sizeof(ResTable_config)+4,
5272 endPos, "ResTable_type");
5273 if (err != NO_ERROR) {
5274 return (mError=err);
5277 const size_t typeSize = dtohl(type->header.size);
5279 LOAD_TABLE_NOISY(printf("Type off %p: type=0x%x, headerSize=0x%x, size=%p\n",
5280 (void*)(base-(const uint8_t*)chunk),
5281 dtohs(type->header.type),
5282 dtohs(type->header.headerSize),
5284 if (dtohs(type->header.headerSize)+(sizeof(uint32_t)*dtohl(type->entryCount))
5286 ALOGW("ResTable_type entry index to %p extends beyond chunk end %p.",
5287 (void*)(dtohs(type->header.headerSize)
5288 +(sizeof(uint32_t)*dtohl(type->entryCount))),
5290 return (mError=BAD_TYPE);
5292 if (dtohl(type->entryCount) != 0
5293 && dtohl(type->entriesStart) > (typeSize-sizeof(ResTable_entry))) {
5294 ALOGW("ResTable_type entriesStart at %p extends beyond chunk end %p.",
5295 (void*)dtohl(type->entriesStart), (void*)typeSize);
5296 return (mError=BAD_TYPE);
5298 if (type->id == 0) {
5299 ALOGW("ResTable_type has an id of 0.");
5300 return (mError=BAD_TYPE);
5303 while (package->types.size() < type->id) {
5304 package->types.add(NULL);
5306 Type* t = package->types[type->id-1];
5308 t = new Type(header, package, dtohl(type->entryCount));
5309 package->types.editItemAt(type->id-1) = t;
5310 } else if (dtohl(type->entryCount) != t->entryCount) {
5311 ALOGW("ResTable_type entry count inconsistent: given %d, previously %d",
5312 (int)dtohl(type->entryCount), (int)t->entryCount);
5313 return (mError=BAD_TYPE);
5317 ResTable_config thisConfig;
5318 thisConfig.copyFromDtoH(type->config);
5319 ALOGI("Adding config to type %d: %s\n",
5320 type->id, thisConfig.toString().string()));
5321 t->configs.add(type);
5323 status_t err = validate_chunk(chunk, sizeof(ResChunk_header),
5324 endPos, "ResTable_package:unknown");
5325 if (err != NO_ERROR) {
5326 return (mError=err);
5329 chunk = (const ResChunk_header*)
5330 (((const uint8_t*)chunk) + csize);
5333 if (group->typeCount == 0) {
5334 group->typeCount = package->types.size();
5340 status_t ResTable::createIdmap(const ResTable& overlay, uint32_t originalCrc, uint32_t overlayCrc,
5341 void** outData, size_t* outSize) const
5343 // see README for details on the format of map
5344 if (mPackageGroups.size() == 0) {
5345 return UNKNOWN_ERROR;
5347 if (mPackageGroups[0]->packages.size() == 0) {
5348 return UNKNOWN_ERROR;
5351 Vector<Vector<uint32_t> > map;
5352 const PackageGroup* pg = mPackageGroups[0];
5353 const Package* pkg = pg->packages[0];
5354 size_t typeCount = pkg->types.size();
5355 // starting size is header + first item (number of types in map)
5356 *outSize = (IDMAP_HEADER_SIZE + 1) * sizeof(uint32_t);
5357 const String16 overlayPackage(overlay.mPackageGroups[0]->packages[0]->package->name);
5358 const uint32_t pkg_id = pkg->package->id << 24;
5360 for (size_t typeIndex = 0; typeIndex < typeCount; ++typeIndex) {
5363 const Type* typeConfigs = pkg->getType(typeIndex);
5364 ssize_t mapIndex = map.add();
5368 Vector<uint32_t>& vector = map.editItemAt(mapIndex);
5369 for (size_t entryIndex = 0; entryIndex < typeConfigs->entryCount; ++entryIndex) {
5370 uint32_t resID = pkg_id
5371 | (0x00ff0000 & ((typeIndex+1)<<16))
5372 | (0x0000ffff & (entryIndex));
5373 resource_name resName;
5374 if (!this->getResourceName(resID, true, &resName)) {
5375 ALOGW("idmap: resource 0x%08x has spec but lacks values, skipping\n", resID);
5376 // add dummy value, or trimming leading/trailing zeroes later will fail
5381 const String16 overlayType(resName.type, resName.typeLen);
5382 const String16 overlayName(resName.name, resName.nameLen);
5383 uint32_t overlayResID = overlay.identifierForName(overlayName.string(),
5385 overlayType.string(),
5387 overlayPackage.string(),
5388 overlayPackage.size());
5389 if (overlayResID != 0) {
5390 overlayResID = pkg_id | (0x00ffffff & overlayResID);
5391 last = Res_GETENTRY(resID);
5393 first = Res_GETENTRY(resID);
5396 vector.push(overlayResID);
5398 if (overlayResID != 0) {
5399 ALOGD("%s/%s 0x%08x -> 0x%08x\n",
5400 String8(String16(resName.type)).string(),
5401 String8(String16(resName.name)).string(),
5402 resID, overlayResID);
5408 // shave off trailing entries which lack overlay values
5409 const size_t last_past_one = last + 1;
5410 if (last_past_one < vector.size()) {
5411 vector.removeItemsAt(last_past_one, vector.size() - last_past_one);
5413 // shave off leading entries which lack overlay values
5414 vector.removeItemsAt(0, first);
5415 // store offset to first overlaid resource ID of this type
5416 vector.insertAt((uint32_t)first, 0, 1);
5417 // reserve space for number and offset of entries, and the actual entries
5418 *outSize += (2 + vector.size()) * sizeof(uint32_t);
5420 // no entries of current type defined in overlay package
5422 // reserve space for type offset
5423 *outSize += 1 * sizeof(uint32_t);
5427 if ((*outData = malloc(*outSize)) == NULL) {
5430 uint32_t* data = (uint32_t*)*outData;
5431 *data++ = htodl(IDMAP_MAGIC);
5432 *data++ = htodl(originalCrc);
5433 *data++ = htodl(overlayCrc);
5434 const size_t mapSize = map.size();
5435 *data++ = htodl(mapSize);
5436 size_t offset = mapSize;
5437 for (size_t i = 0; i < mapSize; ++i) {
5438 const Vector<uint32_t>& vector = map.itemAt(i);
5439 const size_t N = vector.size();
5444 *data++ = htodl(offset);
5448 for (size_t i = 0; i < mapSize; ++i) {
5449 const Vector<uint32_t>& vector = map.itemAt(i);
5450 const size_t N = vector.size();
5454 if (N == 1) { // vector expected to hold (offset) + (N > 0 entries)
5455 ALOGW("idmap: type %d supposedly has entries, but no entries found\n", i);
5456 return UNKNOWN_ERROR;
5458 *data++ = htodl(N - 1); // do not count the offset (which is vector's first element)
5459 for (size_t j = 0; j < N; ++j) {
5460 const uint32_t& overlayResID = vector.itemAt(j);
5461 *data++ = htodl(overlayResID);
5468 bool ResTable::getIdmapInfo(const void* idmap, size_t sizeBytes,
5469 uint32_t* pOriginalCrc, uint32_t* pOverlayCrc)
5471 const uint32_t* map = (const uint32_t*)idmap;
5472 if (!assertIdmapHeader(map, sizeBytes)) {
5475 *pOriginalCrc = map[1];
5476 *pOverlayCrc = map[2];
5481 #define CHAR16_TO_CSTR(c16, len) (String8(String16(c16,len)).string())
5483 #define CHAR16_ARRAY_EQ(constant, var, len) \
5484 ((len == (sizeof(constant)/sizeof(constant[0]))) && (0 == memcmp((var), (constant), (len))))
5486 static void print_complex(uint32_t complex, bool isFraction)
5488 const float MANTISSA_MULT =
5489 1.0f / (1<<Res_value::COMPLEX_MANTISSA_SHIFT);
5490 const float RADIX_MULTS[] = {
5491 1.0f*MANTISSA_MULT, 1.0f/(1<<7)*MANTISSA_MULT,
5492 1.0f/(1<<15)*MANTISSA_MULT, 1.0f/(1<<23)*MANTISSA_MULT
5495 float value = (complex&(Res_value::COMPLEX_MANTISSA_MASK
5496 <<Res_value::COMPLEX_MANTISSA_SHIFT))
5497 * RADIX_MULTS[(complex>>Res_value::COMPLEX_RADIX_SHIFT)
5498 & Res_value::COMPLEX_RADIX_MASK];
5499 printf("%f", value);
5502 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
5503 case Res_value::COMPLEX_UNIT_PX: printf("px"); break;
5504 case Res_value::COMPLEX_UNIT_DIP: printf("dp"); break;
5505 case Res_value::COMPLEX_UNIT_SP: printf("sp"); break;
5506 case Res_value::COMPLEX_UNIT_PT: printf("pt"); break;
5507 case Res_value::COMPLEX_UNIT_IN: printf("in"); break;
5508 case Res_value::COMPLEX_UNIT_MM: printf("mm"); break;
5509 default: printf(" (unknown unit)"); break;
5512 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
5513 case Res_value::COMPLEX_UNIT_FRACTION: printf("%%"); break;
5514 case Res_value::COMPLEX_UNIT_FRACTION_PARENT: printf("%%p"); break;
5515 default: printf(" (unknown unit)"); break;
5520 // Normalize a string for output
5521 String8 ResTable::normalizeForOutput( const char *input )
5527 while (*input != '\0') {
5529 // All interesting characters are in the ASCII zone, so we are making our own lives
5530 // easier by scanning the string one byte at a time.
5552 void ResTable::print_value(const Package* pkg, const Res_value& value) const
5554 if (value.dataType == Res_value::TYPE_NULL) {
5556 } else if (value.dataType == Res_value::TYPE_REFERENCE) {
5557 printf("(reference) 0x%08x\n", value.data);
5558 } else if (value.dataType == Res_value::TYPE_ATTRIBUTE) {
5559 printf("(attribute) 0x%08x\n", value.data);
5560 } else if (value.dataType == Res_value::TYPE_STRING) {
5562 const char* str8 = pkg->header->values.string8At(
5565 printf("(string8) \"%s\"\n", normalizeForOutput(str8).string());
5567 const char16_t* str16 = pkg->header->values.stringAt(
5569 if (str16 != NULL) {
5570 printf("(string16) \"%s\"\n",
5571 normalizeForOutput(String8(str16, len).string()).string());
5573 printf("(string) null\n");
5576 } else if (value.dataType == Res_value::TYPE_FLOAT) {
5577 printf("(float) %g\n", *(const float*)&value.data);
5578 } else if (value.dataType == Res_value::TYPE_DIMENSION) {
5579 printf("(dimension) ");
5580 print_complex(value.data, false);
5582 } else if (value.dataType == Res_value::TYPE_FRACTION) {
5583 printf("(fraction) ");
5584 print_complex(value.data, true);
5586 } else if (value.dataType >= Res_value::TYPE_FIRST_COLOR_INT
5587 || value.dataType <= Res_value::TYPE_LAST_COLOR_INT) {
5588 printf("(color) #%08x\n", value.data);
5589 } else if (value.dataType == Res_value::TYPE_INT_BOOLEAN) {
5590 printf("(boolean) %s\n", value.data ? "true" : "false");
5591 } else if (value.dataType >= Res_value::TYPE_FIRST_INT
5592 || value.dataType <= Res_value::TYPE_LAST_INT) {
5593 printf("(int) 0x%08x or %d\n", value.data, value.data);
5595 printf("(unknown type) t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)\n",
5596 (int)value.dataType, (int)value.data,
5597 (int)value.size, (int)value.res0);
5601 void ResTable::print(bool inclValues) const
5604 printf("mError=0x%x (%s)\n", mError, strerror(mError));
5607 printf("mParams=%c%c-%c%c,\n",
5608 mParams.language[0], mParams.language[1],
5609 mParams.country[0], mParams.country[1]);
5611 size_t pgCount = mPackageGroups.size();
5612 printf("Package Groups (%d)\n", (int)pgCount);
5613 for (size_t pgIndex=0; pgIndex<pgCount; pgIndex++) {
5614 const PackageGroup* pg = mPackageGroups[pgIndex];
5615 printf("Package Group %d id=%d packageCount=%d name=%s\n",
5616 (int)pgIndex, pg->id, (int)pg->packages.size(),
5617 String8(pg->name).string());
5619 size_t pkgCount = pg->packages.size();
5620 for (size_t pkgIndex=0; pkgIndex<pkgCount; pkgIndex++) {
5621 const Package* pkg = pg->packages[pkgIndex];
5622 size_t typeCount = pkg->types.size();
5623 printf(" Package %d id=%d name=%s typeCount=%d\n", (int)pkgIndex,
5624 pkg->package->id, String8(String16(pkg->package->name)).string(),
5626 for (size_t typeIndex=0; typeIndex<typeCount; typeIndex++) {
5627 const Type* typeConfigs = pkg->getType(typeIndex);
5628 if (typeConfigs == NULL) {
5629 printf(" type %d NULL\n", (int)typeIndex);
5632 const size_t NTC = typeConfigs->configs.size();
5633 printf(" type %d configCount=%d entryCount=%d\n",
5634 (int)typeIndex, (int)NTC, (int)typeConfigs->entryCount);
5635 if (typeConfigs->typeSpecFlags != NULL) {
5636 for (size_t entryIndex=0; entryIndex<typeConfigs->entryCount; entryIndex++) {
5637 uint32_t resID = (0xff000000 & ((pkg->package->id)<<24))
5638 | (0x00ff0000 & ((typeIndex+1)<<16))
5639 | (0x0000ffff & (entryIndex));
5640 resource_name resName;
5641 if (this->getResourceName(resID, true, &resName)) {
5644 if (resName.type8 != NULL) {
5645 type8 = String8(resName.type8, resName.typeLen);
5647 type8 = String8(resName.type, resName.typeLen);
5649 if (resName.name8 != NULL) {
5650 name8 = String8(resName.name8, resName.nameLen);
5652 name8 = String8(resName.name, resName.nameLen);
5654 printf(" spec resource 0x%08x %s:%s/%s: flags=0x%08x\n",
5656 CHAR16_TO_CSTR(resName.package, resName.packageLen),
5657 type8.string(), name8.string(),
5658 dtohl(typeConfigs->typeSpecFlags[entryIndex]));
5660 printf(" INVALID TYPE CONFIG FOR RESOURCE 0x%08x\n", resID);
5664 for (size_t configIndex=0; configIndex<NTC; configIndex++) {
5665 const ResTable_type* type = typeConfigs->configs[configIndex];
5666 if ((((uint64_t)type)&0x3) != 0) {
5667 printf(" NON-INTEGER ResTable_type ADDRESS: %p\n", type);
5670 String8 configStr = type->config.toString();
5671 printf(" config %s:\n", configStr.size() > 0
5672 ? configStr.string() : "(default)");
5673 size_t entryCount = dtohl(type->entryCount);
5674 uint32_t entriesStart = dtohl(type->entriesStart);
5675 if ((entriesStart&0x3) != 0) {
5676 printf(" NON-INTEGER ResTable_type entriesStart OFFSET: %p\n", (void*)entriesStart);
5679 uint32_t typeSize = dtohl(type->header.size);
5680 if ((typeSize&0x3) != 0) {
5681 printf(" NON-INTEGER ResTable_type header.size: %p\n", (void*)typeSize);
5684 for (size_t entryIndex=0; entryIndex<entryCount; entryIndex++) {
5686 const uint8_t* const end = ((const uint8_t*)type)
5687 + dtohl(type->header.size);
5688 const uint32_t* const eindex = (const uint32_t*)
5689 (((const uint8_t*)type) + dtohs(type->header.headerSize));
5691 uint32_t thisOffset = dtohl(eindex[entryIndex]);
5692 if (thisOffset == ResTable_type::NO_ENTRY) {
5696 uint32_t resID = (0xff000000 & ((pkg->package->id)<<24))
5697 | (0x00ff0000 & ((typeIndex+1)<<16))
5698 | (0x0000ffff & (entryIndex));
5699 resource_name resName;
5700 if (this->getResourceName(resID, true, &resName)) {
5703 if (resName.type8 != NULL) {
5704 type8 = String8(resName.type8, resName.typeLen);
5706 type8 = String8(resName.type, resName.typeLen);
5708 if (resName.name8 != NULL) {
5709 name8 = String8(resName.name8, resName.nameLen);
5711 name8 = String8(resName.name, resName.nameLen);
5713 printf(" resource 0x%08x %s:%s/%s: ", resID,
5714 CHAR16_TO_CSTR(resName.package, resName.packageLen),
5715 type8.string(), name8.string());
5717 printf(" INVALID RESOURCE 0x%08x: ", resID);
5719 if ((thisOffset&0x3) != 0) {
5720 printf("NON-INTEGER OFFSET: %p\n", (void*)thisOffset);
5723 if ((thisOffset+sizeof(ResTable_entry)) > typeSize) {
5724 printf("OFFSET OUT OF BOUNDS: %p+%p (size is %p)\n",
5725 (void*)entriesStart, (void*)thisOffset,
5730 const ResTable_entry* ent = (const ResTable_entry*)
5731 (((const uint8_t*)type) + entriesStart + thisOffset);
5732 if (((entriesStart + thisOffset)&0x3) != 0) {
5733 printf("NON-INTEGER ResTable_entry OFFSET: %p\n",
5734 (void*)(entriesStart + thisOffset));
5738 uint16_t esize = dtohs(ent->size);
5739 if ((esize&0x3) != 0) {
5740 printf("NON-INTEGER ResTable_entry SIZE: %p\n", (void*)esize);
5743 if ((thisOffset+esize) > typeSize) {
5744 printf("ResTable_entry OUT OF BOUNDS: %p+%p+%p (size is %p)\n",
5745 (void*)entriesStart, (void*)thisOffset,
5746 (void*)esize, (void*)typeSize);
5750 const Res_value* valuePtr = NULL;
5751 const ResTable_map_entry* bagPtr = NULL;
5753 if ((dtohs(ent->flags)&ResTable_entry::FLAG_COMPLEX) != 0) {
5755 bagPtr = (const ResTable_map_entry*)ent;
5757 valuePtr = (const Res_value*)
5758 (((const uint8_t*)ent) + esize);
5759 value.copyFrom_dtoh(*valuePtr);
5760 printf("t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)",
5761 (int)value.dataType, (int)value.data,
5762 (int)value.size, (int)value.res0);
5765 if ((dtohs(ent->flags)&ResTable_entry::FLAG_PUBLIC) != 0) {
5766 printf(" (PUBLIC)");
5771 if (valuePtr != NULL) {
5773 print_value(pkg, value);
5774 } else if (bagPtr != NULL) {
5775 const int N = dtohl(bagPtr->count);
5776 const uint8_t* baseMapPtr = (const uint8_t*)ent;
5777 size_t mapOffset = esize;
5778 const ResTable_map* mapPtr = (ResTable_map*)(baseMapPtr+mapOffset);
5779 printf(" Parent=0x%08x, Count=%d\n",
5780 dtohl(bagPtr->parent.ident), N);
5781 for (int i=0; i<N && mapOffset < (typeSize-sizeof(ResTable_map)); i++) {
5782 printf(" #%i (Key=0x%08x): ",
5783 i, dtohl(mapPtr->name.ident));
5784 value.copyFrom_dtoh(mapPtr->value);
5785 print_value(pkg, value);
5786 const size_t size = dtohs(mapPtr->value.size);
5787 mapOffset += size + sizeof(*mapPtr)-sizeof(mapPtr->value);
5788 mapPtr = (ResTable_map*)(baseMapPtr+mapOffset);
5799 } // namespace android