Home | History | Annotate | Download | only in utils
      1 /*
      2  * Copyright (C) 2008 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #define LOG_TAG "ResourceType"
     18 //#define LOG_NDEBUG 0
     19 
     20 #include <utils/Atomic.h>
     21 #include <utils/ByteOrder.h>
     22 #include <utils/Debug.h>
     23 #include <utils/ResourceTypes.h>
     24 #include <utils/String16.h>
     25 #include <utils/String8.h>
     26 #include <utils/TextOutput.h>
     27 #include <utils/Log.h>
     28 
     29 #include <stdlib.h>
     30 #include <string.h>
     31 #include <memory.h>
     32 #include <ctype.h>
     33 #include <stdint.h>
     34 
     35 #ifndef INT32_MAX
     36 #define INT32_MAX ((int32_t)(2147483647))
     37 #endif
     38 
     39 #define POOL_NOISY(x) //x
     40 #define XML_NOISY(x) //x
     41 #define TABLE_NOISY(x) //x
     42 #define TABLE_GETENTRY(x) //x
     43 #define TABLE_SUPER_NOISY(x) //x
     44 #define LOAD_TABLE_NOISY(x) //x
     45 #define TABLE_THEME(x) //x
     46 
     47 namespace android {
     48 
     49 #ifdef HAVE_WINSOCK
     50 #undef  nhtol
     51 #undef  htonl
     52 
     53 #ifdef HAVE_LITTLE_ENDIAN
     54 #define ntohl(x)    ( ((x) << 24) | (((x) >> 24) & 255) | (((x) << 8) & 0xff0000) | (((x) >> 8) & 0xff00) )
     55 #define htonl(x)    ntohl(x)
     56 #define ntohs(x)    ( (((x) << 8) & 0xff00) | (((x) >> 8) & 255) )
     57 #define htons(x)    ntohs(x)
     58 #else
     59 #define ntohl(x)    (x)
     60 #define htonl(x)    (x)
     61 #define ntohs(x)    (x)
     62 #define htons(x)    (x)
     63 #endif
     64 #endif
     65 
     66 static void printToLogFunc(void* cookie, const char* txt)
     67 {
     68     LOGV("%s", txt);
     69 }
     70 
     71 // Standard C isspace() is only required to look at the low byte of its input, so
     72 // produces incorrect results for UTF-16 characters.  For safety's sake, assume that
     73 // any high-byte UTF-16 code point is not whitespace.
     74 inline int isspace16(char16_t c) {
     75     return (c < 0x0080 && isspace(c));
     76 }
     77 
     78 // range checked; guaranteed to NUL-terminate within the stated number of available slots
     79 // NOTE: if this truncates the dst string due to running out of space, no attempt is
     80 // made to avoid splitting surrogate pairs.
     81 static void strcpy16_dtoh(uint16_t* dst, const uint16_t* src, size_t avail)
     82 {
     83     uint16_t* last = dst + avail - 1;
     84     while (*src && (dst < last)) {
     85         char16_t s = dtohs(*src);
     86         *dst++ = s;
     87         src++;
     88     }
     89     *dst = 0;
     90 }
     91 
     92 static status_t validate_chunk(const ResChunk_header* chunk,
     93                                size_t minSize,
     94                                const uint8_t* dataEnd,
     95                                const char* name)
     96 {
     97     const uint16_t headerSize = dtohs(chunk->headerSize);
     98     const uint32_t size = dtohl(chunk->size);
     99 
    100     if (headerSize >= minSize) {
    101         if (headerSize <= size) {
    102             if (((headerSize|size)&0x3) == 0) {
    103                 if ((ssize_t)size <= (dataEnd-((const uint8_t*)chunk))) {
    104                     return NO_ERROR;
    105                 }
    106                 LOGW("%s data size %p extends beyond resource end %p.",
    107                      name, (void*)size,
    108                      (void*)(dataEnd-((const uint8_t*)chunk)));
    109                 return BAD_TYPE;
    110             }
    111             LOGW("%s size 0x%x or headerSize 0x%x is not on an integer boundary.",
    112                  name, (int)size, (int)headerSize);
    113             return BAD_TYPE;
    114         }
    115         LOGW("%s size %p is smaller than header size %p.",
    116              name, (void*)size, (void*)(int)headerSize);
    117         return BAD_TYPE;
    118     }
    119     LOGW("%s header size %p is too small.",
    120          name, (void*)(int)headerSize);
    121     return BAD_TYPE;
    122 }
    123 
    124 inline void Res_value::copyFrom_dtoh(const Res_value& src)
    125 {
    126     size = dtohs(src.size);
    127     res0 = src.res0;
    128     dataType = src.dataType;
    129     data = dtohl(src.data);
    130 }
    131 
    132 void Res_png_9patch::deviceToFile()
    133 {
    134     for (int i = 0; i < numXDivs; i++) {
    135         xDivs[i] = htonl(xDivs[i]);
    136     }
    137     for (int i = 0; i < numYDivs; i++) {
    138         yDivs[i] = htonl(yDivs[i]);
    139     }
    140     paddingLeft = htonl(paddingLeft);
    141     paddingRight = htonl(paddingRight);
    142     paddingTop = htonl(paddingTop);
    143     paddingBottom = htonl(paddingBottom);
    144     for (int i=0; i<numColors; i++) {
    145         colors[i] = htonl(colors[i]);
    146     }
    147 }
    148 
    149 void Res_png_9patch::fileToDevice()
    150 {
    151     for (int i = 0; i < numXDivs; i++) {
    152         xDivs[i] = ntohl(xDivs[i]);
    153     }
    154     for (int i = 0; i < numYDivs; i++) {
    155         yDivs[i] = ntohl(yDivs[i]);
    156     }
    157     paddingLeft = ntohl(paddingLeft);
    158     paddingRight = ntohl(paddingRight);
    159     paddingTop = ntohl(paddingTop);
    160     paddingBottom = ntohl(paddingBottom);
    161     for (int i=0; i<numColors; i++) {
    162         colors[i] = ntohl(colors[i]);
    163     }
    164 }
    165 
    166 size_t Res_png_9patch::serializedSize()
    167 {
    168     // The size of this struct is 32 bytes on the 32-bit target system
    169     // 4 * int8_t
    170     // 4 * int32_t
    171     // 3 * pointer
    172     return 32
    173             + numXDivs * sizeof(int32_t)
    174             + numYDivs * sizeof(int32_t)
    175             + numColors * sizeof(uint32_t);
    176 }
    177 
    178 void* Res_png_9patch::serialize()
    179 {
    180     // Use calloc since we're going to leave a few holes in the data
    181     // and want this to run cleanly under valgrind
    182     void* newData = calloc(1, serializedSize());
    183     serialize(newData);
    184     return newData;
    185 }
    186 
    187 void Res_png_9patch::serialize(void * outData)
    188 {
    189     char* data = (char*) outData;
    190     memmove(data, &wasDeserialized, 4);     // copy  wasDeserialized, numXDivs, numYDivs, numColors
    191     memmove(data + 12, &paddingLeft, 16);   // copy paddingXXXX
    192     data += 32;
    193 
    194     memmove(data, this->xDivs, numXDivs * sizeof(int32_t));
    195     data +=  numXDivs * sizeof(int32_t);
    196     memmove(data, this->yDivs, numYDivs * sizeof(int32_t));
    197     data +=  numYDivs * sizeof(int32_t);
    198     memmove(data, this->colors, numColors * sizeof(uint32_t));
    199 }
    200 
    201 static void deserializeInternal(const void* inData, Res_png_9patch* outData) {
    202     char* patch = (char*) inData;
    203     if (inData != outData) {
    204         memmove(&outData->wasDeserialized, patch, 4);     // copy  wasDeserialized, numXDivs, numYDivs, numColors
    205         memmove(&outData->paddingLeft, patch + 12, 4);     // copy  wasDeserialized, numXDivs, numYDivs, numColors
    206     }
    207     outData->wasDeserialized = true;
    208     char* data = (char*)outData;
    209     data +=  sizeof(Res_png_9patch);
    210     outData->xDivs = (int32_t*) data;
    211     data +=  outData->numXDivs * sizeof(int32_t);
    212     outData->yDivs = (int32_t*) data;
    213     data +=  outData->numYDivs * sizeof(int32_t);
    214     outData->colors = (uint32_t*) data;
    215 }
    216 
    217 Res_png_9patch* Res_png_9patch::deserialize(const void* inData)
    218 {
    219     if (sizeof(void*) != sizeof(int32_t)) {
    220         LOGE("Cannot deserialize on non 32-bit system\n");
    221         return NULL;
    222     }
    223     deserializeInternal(inData, (Res_png_9patch*) inData);
    224     return (Res_png_9patch*) inData;
    225 }
    226 
    227 // --------------------------------------------------------------------
    228 // --------------------------------------------------------------------
    229 // --------------------------------------------------------------------
    230 
    231 ResStringPool::ResStringPool()
    232     : mError(NO_INIT), mOwnedData(NULL), mHeader(NULL), mCache(NULL)
    233 {
    234 }
    235 
    236 ResStringPool::ResStringPool(const void* data, size_t size, bool copyData)
    237     : mError(NO_INIT), mOwnedData(NULL), mHeader(NULL), mCache(NULL)
    238 {
    239     setTo(data, size, copyData);
    240 }
    241 
    242 ResStringPool::~ResStringPool()
    243 {
    244     uninit();
    245 }
    246 
    247 status_t ResStringPool::setTo(const void* data, size_t size, bool copyData)
    248 {
    249     if (!data || !size) {
    250         return (mError=BAD_TYPE);
    251     }
    252 
    253     uninit();
    254 
    255     const bool notDeviceEndian = htods(0xf0) != 0xf0;
    256 
    257     if (copyData || notDeviceEndian) {
    258         mOwnedData = malloc(size);
    259         if (mOwnedData == NULL) {
    260             return (mError=NO_MEMORY);
    261         }
    262         memcpy(mOwnedData, data, size);
    263         data = mOwnedData;
    264     }
    265 
    266     mHeader = (const ResStringPool_header*)data;
    267 
    268     if (notDeviceEndian) {
    269         ResStringPool_header* h = const_cast<ResStringPool_header*>(mHeader);
    270         h->header.headerSize = dtohs(mHeader->header.headerSize);
    271         h->header.type = dtohs(mHeader->header.type);
    272         h->header.size = dtohl(mHeader->header.size);
    273         h->stringCount = dtohl(mHeader->stringCount);
    274         h->styleCount = dtohl(mHeader->styleCount);
    275         h->flags = dtohl(mHeader->flags);
    276         h->stringsStart = dtohl(mHeader->stringsStart);
    277         h->stylesStart = dtohl(mHeader->stylesStart);
    278     }
    279 
    280     if (mHeader->header.headerSize > mHeader->header.size
    281             || mHeader->header.size > size) {
    282         LOGW("Bad string block: header size %d or total size %d is larger than data size %d\n",
    283                 (int)mHeader->header.headerSize, (int)mHeader->header.size, (int)size);
    284         return (mError=BAD_TYPE);
    285     }
    286     mSize = mHeader->header.size;
    287     mEntries = (const uint32_t*)
    288         (((const uint8_t*)data)+mHeader->header.headerSize);
    289 
    290     if (mHeader->stringCount > 0) {
    291         if ((mHeader->stringCount*sizeof(uint32_t) < mHeader->stringCount)  // uint32 overflow?
    292             || (mHeader->header.headerSize+(mHeader->stringCount*sizeof(uint32_t)))
    293                 > size) {
    294             LOGW("Bad string block: entry of %d items extends past data size %d\n",
    295                     (int)(mHeader->header.headerSize+(mHeader->stringCount*sizeof(uint32_t))),
    296                     (int)size);
    297             return (mError=BAD_TYPE);
    298         }
    299 
    300         size_t charSize;
    301         if (mHeader->flags&ResStringPool_header::UTF8_FLAG) {
    302             charSize = sizeof(uint8_t);
    303             mCache = (char16_t**)malloc(sizeof(char16_t**)*mHeader->stringCount);
    304             memset(mCache, 0, sizeof(char16_t**)*mHeader->stringCount);
    305         } else {
    306             charSize = sizeof(char16_t);
    307         }
    308 
    309         mStrings = (const void*)
    310             (((const uint8_t*)data)+mHeader->stringsStart);
    311         if (mHeader->stringsStart >= (mHeader->header.size-sizeof(uint16_t))) {
    312             LOGW("Bad string block: string pool starts at %d, after total size %d\n",
    313                     (int)mHeader->stringsStart, (int)mHeader->header.size);
    314             return (mError=BAD_TYPE);
    315         }
    316         if (mHeader->styleCount == 0) {
    317             mStringPoolSize =
    318                 (mHeader->header.size-mHeader->stringsStart)/charSize;
    319         } else {
    320             // check invariant: styles follow the strings
    321             if (mHeader->stylesStart <= mHeader->stringsStart) {
    322                 LOGW("Bad style block: style block starts at %d, before strings at %d\n",
    323                     (int)mHeader->stylesStart, (int)mHeader->stringsStart);
    324                 return (mError=BAD_TYPE);
    325             }
    326             mStringPoolSize =
    327                 (mHeader->stylesStart-mHeader->stringsStart)/charSize;
    328         }
    329 
    330         // check invariant: stringCount > 0 requires a string pool to exist
    331         if (mStringPoolSize == 0) {
    332             LOGW("Bad string block: stringCount is %d but pool size is 0\n", (int)mHeader->stringCount);
    333             return (mError=BAD_TYPE);
    334         }
    335 
    336         if (notDeviceEndian) {
    337             size_t i;
    338             uint32_t* e = const_cast<uint32_t*>(mEntries);
    339             for (i=0; i<mHeader->stringCount; i++) {
    340                 e[i] = dtohl(mEntries[i]);
    341             }
    342             if (!(mHeader->flags&ResStringPool_header::UTF8_FLAG)) {
    343                 const char16_t* strings = (const char16_t*)mStrings;
    344                 char16_t* s = const_cast<char16_t*>(strings);
    345                 for (i=0; i<mStringPoolSize; i++) {
    346                     s[i] = dtohs(strings[i]);
    347                 }
    348             }
    349         }
    350 
    351         if ((mHeader->flags&ResStringPool_header::UTF8_FLAG &&
    352                 ((uint8_t*)mStrings)[mStringPoolSize-1] != 0) ||
    353                 (!mHeader->flags&ResStringPool_header::UTF8_FLAG &&
    354                 ((char16_t*)mStrings)[mStringPoolSize-1] != 0)) {
    355             LOGW("Bad string block: last string is not 0-terminated\n");
    356             return (mError=BAD_TYPE);
    357         }
    358     } else {
    359         mStrings = NULL;
    360         mStringPoolSize = 0;
    361     }
    362 
    363     if (mHeader->styleCount > 0) {
    364         mEntryStyles = mEntries + mHeader->stringCount;
    365         // invariant: integer overflow in calculating mEntryStyles
    366         if (mEntryStyles < mEntries) {
    367             LOGW("Bad string block: integer overflow finding styles\n");
    368             return (mError=BAD_TYPE);
    369         }
    370 
    371         if (((const uint8_t*)mEntryStyles-(const uint8_t*)mHeader) > (int)size) {
    372             LOGW("Bad string block: entry of %d styles extends past data size %d\n",
    373                     (int)((const uint8_t*)mEntryStyles-(const uint8_t*)mHeader),
    374                     (int)size);
    375             return (mError=BAD_TYPE);
    376         }
    377         mStyles = (const uint32_t*)
    378             (((const uint8_t*)data)+mHeader->stylesStart);
    379         if (mHeader->stylesStart >= mHeader->header.size) {
    380             LOGW("Bad string block: style pool starts %d, after total size %d\n",
    381                     (int)mHeader->stylesStart, (int)mHeader->header.size);
    382             return (mError=BAD_TYPE);
    383         }
    384         mStylePoolSize =
    385             (mHeader->header.size-mHeader->stylesStart)/sizeof(uint32_t);
    386 
    387         if (notDeviceEndian) {
    388             size_t i;
    389             uint32_t* e = const_cast<uint32_t*>(mEntryStyles);
    390             for (i=0; i<mHeader->styleCount; i++) {
    391                 e[i] = dtohl(mEntryStyles[i]);
    392             }
    393             uint32_t* s = const_cast<uint32_t*>(mStyles);
    394             for (i=0; i<mStylePoolSize; i++) {
    395                 s[i] = dtohl(mStyles[i]);
    396             }
    397         }
    398 
    399         const ResStringPool_span endSpan = {
    400             { htodl(ResStringPool_span::END) },
    401             htodl(ResStringPool_span::END), htodl(ResStringPool_span::END)
    402         };
    403         if (memcmp(&mStyles[mStylePoolSize-(sizeof(endSpan)/sizeof(uint32_t))],
    404                    &endSpan, sizeof(endSpan)) != 0) {
    405             LOGW("Bad string block: last style is not 0xFFFFFFFF-terminated\n");
    406             return (mError=BAD_TYPE);
    407         }
    408     } else {
    409         mEntryStyles = NULL;
    410         mStyles = NULL;
    411         mStylePoolSize = 0;
    412     }
    413 
    414     return (mError=NO_ERROR);
    415 }
    416 
    417 status_t ResStringPool::getError() const
    418 {
    419     return mError;
    420 }
    421 
    422 void ResStringPool::uninit()
    423 {
    424     mError = NO_INIT;
    425     if (mOwnedData) {
    426         free(mOwnedData);
    427         mOwnedData = NULL;
    428     }
    429     if (mHeader != NULL && mCache != NULL) {
    430         for (size_t x = 0; x < mHeader->stringCount; x++) {
    431             if (mCache[x] != NULL) {
    432                 free(mCache[x]);
    433                 mCache[x] = NULL;
    434             }
    435         }
    436         free(mCache);
    437         mCache = NULL;
    438     }
    439 }
    440 
    441 #define DECODE_LENGTH(str, chrsz, len) \
    442     len = *(str); \
    443     if (*(str)&(1<<(chrsz*8-1))) { \
    444         (str)++; \
    445         len = (((len)&((1<<(chrsz*8-1))-1))<<(chrsz*8)) + *(str); \
    446     } \
    447     (str)++;
    448 
    449 const uint16_t* ResStringPool::stringAt(size_t idx, size_t* outLen) const
    450 {
    451     if (mError == NO_ERROR && idx < mHeader->stringCount) {
    452         const bool isUTF8 = (mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0;
    453         const uint32_t off = mEntries[idx]/(isUTF8?sizeof(char):sizeof(char16_t));
    454         if (off < (mStringPoolSize-1)) {
    455             if (!isUTF8) {
    456                 const char16_t* strings = (char16_t*)mStrings;
    457                 const char16_t* str = strings+off;
    458                 DECODE_LENGTH(str, sizeof(char16_t), *outLen)
    459                 if ((uint32_t)(str+*outLen-strings) < mStringPoolSize) {
    460                     return str;
    461                 } else {
    462                     LOGW("Bad string block: string #%d extends to %d, past end at %d\n",
    463                             (int)idx, (int)(str+*outLen-strings), (int)mStringPoolSize);
    464                 }
    465             } else {
    466                 const uint8_t* strings = (uint8_t*)mStrings;
    467                 const uint8_t* str = strings+off;
    468                 DECODE_LENGTH(str, sizeof(uint8_t), *outLen)
    469                 size_t encLen;
    470                 DECODE_LENGTH(str, sizeof(uint8_t), encLen)
    471                 if ((uint32_t)(str+encLen-strings) < mStringPoolSize) {
    472                     AutoMutex lock(mDecodeLock);
    473                     if (mCache[idx] != NULL) {
    474                         return mCache[idx];
    475                     }
    476                     char16_t *u16str = (char16_t *)calloc(*outLen+1, sizeof(char16_t));
    477                     if (!u16str) {
    478                         LOGW("No memory when trying to allocate decode cache for string #%d\n",
    479                                 (int)idx);
    480                         return NULL;
    481                     }
    482                     const unsigned char *u8src = reinterpret_cast<const unsigned char *>(str);
    483                     utf8_to_utf16(u8src, encLen, u16str, *outLen);
    484                     mCache[idx] = u16str;
    485                     return u16str;
    486                 } else {
    487                     LOGW("Bad string block: string #%d extends to %d, past end at %d\n",
    488                             (int)idx, (int)(str+encLen-strings), (int)mStringPoolSize);
    489                 }
    490             }
    491         } else {
    492             LOGW("Bad string block: string #%d entry is at %d, past end at %d\n",
    493                     (int)idx, (int)(off*sizeof(uint16_t)),
    494                     (int)(mStringPoolSize*sizeof(uint16_t)));
    495         }
    496     }
    497     return NULL;
    498 }
    499 
    500 const char* ResStringPool::string8At(size_t idx, size_t* outLen) const
    501 {
    502     if (mError == NO_ERROR && idx < mHeader->stringCount) {
    503         const bool isUTF8 = (mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0;
    504         const uint32_t off = mEntries[idx]/(isUTF8?sizeof(char):sizeof(char16_t));
    505         if (off < (mStringPoolSize-1)) {
    506             if (isUTF8) {
    507                 const uint8_t* strings = (uint8_t*)mStrings;
    508                 const uint8_t* str = strings+off;
    509                 DECODE_LENGTH(str, sizeof(uint8_t), *outLen)
    510                 size_t encLen;
    511                 DECODE_LENGTH(str, sizeof(uint8_t), encLen)
    512                 if ((uint32_t)(str+encLen-strings) < mStringPoolSize) {
    513                     return (const char*)str;
    514                 } else {
    515                     LOGW("Bad string block: string #%d extends to %d, past end at %d\n",
    516                             (int)idx, (int)(str+encLen-strings), (int)mStringPoolSize);
    517                 }
    518             }
    519         } else {
    520             LOGW("Bad string block: string #%d entry is at %d, past end at %d\n",
    521                     (int)idx, (int)(off*sizeof(uint16_t)),
    522                     (int)(mStringPoolSize*sizeof(uint16_t)));
    523         }
    524     }
    525     return NULL;
    526 }
    527 
    528 const ResStringPool_span* ResStringPool::styleAt(const ResStringPool_ref& ref) const
    529 {
    530     return styleAt(ref.index);
    531 }
    532 
    533 const ResStringPool_span* ResStringPool::styleAt(size_t idx) const
    534 {
    535     if (mError == NO_ERROR && idx < mHeader->styleCount) {
    536         const uint32_t off = (mEntryStyles[idx]/sizeof(uint32_t));
    537         if (off < mStylePoolSize) {
    538             return (const ResStringPool_span*)(mStyles+off);
    539         } else {
    540             LOGW("Bad string block: style #%d entry is at %d, past end at %d\n",
    541                     (int)idx, (int)(off*sizeof(uint32_t)),
    542                     (int)(mStylePoolSize*sizeof(uint32_t)));
    543         }
    544     }
    545     return NULL;
    546 }
    547 
    548 ssize_t ResStringPool::indexOfString(const char16_t* str, size_t strLen) const
    549 {
    550     if (mError != NO_ERROR) {
    551         return mError;
    552     }
    553 
    554     size_t len;
    555 
    556     // TODO optimize searching for UTF-8 strings taking into account
    557     // the cache fill to determine when to convert the searched-for
    558     // string key to UTF-8.
    559 
    560     if (mHeader->flags&ResStringPool_header::SORTED_FLAG) {
    561         // Do a binary search for the string...
    562         ssize_t l = 0;
    563         ssize_t h = mHeader->stringCount-1;
    564 
    565         ssize_t mid;
    566         while (l <= h) {
    567             mid = l + (h - l)/2;
    568             const char16_t* s = stringAt(mid, &len);
    569             int c = s ? strzcmp16(s, len, str, strLen) : -1;
    570             POOL_NOISY(printf("Looking for %s, at %s, cmp=%d, l/mid/h=%d/%d/%d\n",
    571                          String8(str).string(),
    572                          String8(s).string(),
    573                          c, (int)l, (int)mid, (int)h));
    574             if (c == 0) {
    575                 return mid;
    576             } else if (c < 0) {
    577                 l = mid + 1;
    578             } else {
    579                 h = mid - 1;
    580             }
    581         }
    582     } else {
    583         // It is unusual to get the ID from an unsorted string block...
    584         // most often this happens because we want to get IDs for style
    585         // span tags; since those always appear at the end of the string
    586         // block, start searching at the back.
    587         for (int i=mHeader->stringCount-1; i>=0; i--) {
    588             const char16_t* s = stringAt(i, &len);
    589             POOL_NOISY(printf("Looking for %s, at %s, i=%d\n",
    590                          String8(str, strLen).string(),
    591                          String8(s).string(),
    592                          i));
    593             if (s && strzcmp16(s, len, str, strLen) == 0) {
    594                 return i;
    595             }
    596         }
    597     }
    598 
    599     return NAME_NOT_FOUND;
    600 }
    601 
    602 size_t ResStringPool::size() const
    603 {
    604     return (mError == NO_ERROR) ? mHeader->stringCount : 0;
    605 }
    606 
    607 #ifndef HAVE_ANDROID_OS
    608 bool ResStringPool::isUTF8() const
    609 {
    610     return (mHeader->flags&ResStringPool_header::UTF8_FLAG)!=0;
    611 }
    612 #endif
    613 
    614 // --------------------------------------------------------------------
    615 // --------------------------------------------------------------------
    616 // --------------------------------------------------------------------
    617 
    618 ResXMLParser::ResXMLParser(const ResXMLTree& tree)
    619     : mTree(tree), mEventCode(BAD_DOCUMENT)
    620 {
    621 }
    622 
    623 void ResXMLParser::restart()
    624 {
    625     mCurNode = NULL;
    626     mEventCode = mTree.mError == NO_ERROR ? START_DOCUMENT : BAD_DOCUMENT;
    627 }
    628 const ResStringPool& ResXMLParser::getStrings() const
    629 {
    630     return mTree.mStrings;
    631 }
    632 
    633 ResXMLParser::event_code_t ResXMLParser::getEventType() const
    634 {
    635     return mEventCode;
    636 }
    637 
    638 ResXMLParser::event_code_t ResXMLParser::next()
    639 {
    640     if (mEventCode == START_DOCUMENT) {
    641         mCurNode = mTree.mRootNode;
    642         mCurExt = mTree.mRootExt;
    643         return (mEventCode=mTree.mRootCode);
    644     } else if (mEventCode >= FIRST_CHUNK_CODE) {
    645         return nextNode();
    646     }
    647     return mEventCode;
    648 }
    649 
    650 int32_t ResXMLParser::getCommentID() const
    651 {
    652     return mCurNode != NULL ? dtohl(mCurNode->comment.index) : -1;
    653 }
    654 
    655 const uint16_t* ResXMLParser::getComment(size_t* outLen) const
    656 {
    657     int32_t id = getCommentID();
    658     return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
    659 }
    660 
    661 uint32_t ResXMLParser::getLineNumber() const
    662 {
    663     return mCurNode != NULL ? dtohl(mCurNode->lineNumber) : -1;
    664 }
    665 
    666 int32_t ResXMLParser::getTextID() const
    667 {
    668     if (mEventCode == TEXT) {
    669         return dtohl(((const ResXMLTree_cdataExt*)mCurExt)->data.index);
    670     }
    671     return -1;
    672 }
    673 
    674 const uint16_t* ResXMLParser::getText(size_t* outLen) const
    675 {
    676     int32_t id = getTextID();
    677     return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
    678 }
    679 
    680 ssize_t ResXMLParser::getTextValue(Res_value* outValue) const
    681 {
    682     if (mEventCode == TEXT) {
    683         outValue->copyFrom_dtoh(((const ResXMLTree_cdataExt*)mCurExt)->typedData);
    684         return sizeof(Res_value);
    685     }
    686     return BAD_TYPE;
    687 }
    688 
    689 int32_t ResXMLParser::getNamespacePrefixID() const
    690 {
    691     if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) {
    692         return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->prefix.index);
    693     }
    694     return -1;
    695 }
    696 
    697 const uint16_t* ResXMLParser::getNamespacePrefix(size_t* outLen) const
    698 {
    699     int32_t id = getNamespacePrefixID();
    700     //printf("prefix=%d  event=%p\n", id, mEventCode);
    701     return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
    702 }
    703 
    704 int32_t ResXMLParser::getNamespaceUriID() const
    705 {
    706     if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) {
    707         return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->uri.index);
    708     }
    709     return -1;
    710 }
    711 
    712 const uint16_t* ResXMLParser::getNamespaceUri(size_t* outLen) const
    713 {
    714     int32_t id = getNamespaceUriID();
    715     //printf("uri=%d  event=%p\n", id, mEventCode);
    716     return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
    717 }
    718 
    719 int32_t ResXMLParser::getElementNamespaceID() const
    720 {
    721     if (mEventCode == START_TAG) {
    722         return dtohl(((const ResXMLTree_attrExt*)mCurExt)->ns.index);
    723     }
    724     if (mEventCode == END_TAG) {
    725         return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->ns.index);
    726     }
    727     return -1;
    728 }
    729 
    730 const uint16_t* ResXMLParser::getElementNamespace(size_t* outLen) const
    731 {
    732     int32_t id = getElementNamespaceID();
    733     return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
    734 }
    735 
    736 int32_t ResXMLParser::getElementNameID() const
    737 {
    738     if (mEventCode == START_TAG) {
    739         return dtohl(((const ResXMLTree_attrExt*)mCurExt)->name.index);
    740     }
    741     if (mEventCode == END_TAG) {
    742         return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->name.index);
    743     }
    744     return -1;
    745 }
    746 
    747 const uint16_t* ResXMLParser::getElementName(size_t* outLen) const
    748 {
    749     int32_t id = getElementNameID();
    750     return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
    751 }
    752 
    753 size_t ResXMLParser::getAttributeCount() const
    754 {
    755     if (mEventCode == START_TAG) {
    756         return dtohs(((const ResXMLTree_attrExt*)mCurExt)->attributeCount);
    757     }
    758     return 0;
    759 }
    760 
    761 int32_t ResXMLParser::getAttributeNamespaceID(size_t idx) const
    762 {
    763     if (mEventCode == START_TAG) {
    764         const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
    765         if (idx < dtohs(tag->attributeCount)) {
    766             const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
    767                 (((const uint8_t*)tag)
    768                  + dtohs(tag->attributeStart)
    769                  + (dtohs(tag->attributeSize)*idx));
    770             return dtohl(attr->ns.index);
    771         }
    772     }
    773     return -2;
    774 }
    775 
    776 const uint16_t* ResXMLParser::getAttributeNamespace(size_t idx, size_t* outLen) const
    777 {
    778     int32_t id = getAttributeNamespaceID(idx);
    779     //printf("attribute namespace=%d  idx=%d  event=%p\n", id, idx, mEventCode);
    780     //XML_NOISY(printf("getAttributeNamespace 0x%x=0x%x\n", idx, id));
    781     return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
    782 }
    783 
    784 int32_t ResXMLParser::getAttributeNameID(size_t idx) const
    785 {
    786     if (mEventCode == START_TAG) {
    787         const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
    788         if (idx < dtohs(tag->attributeCount)) {
    789             const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
    790                 (((const uint8_t*)tag)
    791                  + dtohs(tag->attributeStart)
    792                  + (dtohs(tag->attributeSize)*idx));
    793             return dtohl(attr->name.index);
    794         }
    795     }
    796     return -1;
    797 }
    798 
    799 const uint16_t* ResXMLParser::getAttributeName(size_t idx, size_t* outLen) const
    800 {
    801     int32_t id = getAttributeNameID(idx);
    802     //printf("attribute name=%d  idx=%d  event=%p\n", id, idx, mEventCode);
    803     //XML_NOISY(printf("getAttributeName 0x%x=0x%x\n", idx, id));
    804     return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
    805 }
    806 
    807 uint32_t ResXMLParser::getAttributeNameResID(size_t idx) const
    808 {
    809     int32_t id = getAttributeNameID(idx);
    810     if (id >= 0 && (size_t)id < mTree.mNumResIds) {
    811         return dtohl(mTree.mResIds[id]);
    812     }
    813     return 0;
    814 }
    815 
    816 int32_t ResXMLParser::getAttributeValueStringID(size_t idx) const
    817 {
    818     if (mEventCode == START_TAG) {
    819         const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
    820         if (idx < dtohs(tag->attributeCount)) {
    821             const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
    822                 (((const uint8_t*)tag)
    823                  + dtohs(tag->attributeStart)
    824                  + (dtohs(tag->attributeSize)*idx));
    825             return dtohl(attr->rawValue.index);
    826         }
    827     }
    828     return -1;
    829 }
    830 
    831 const uint16_t* ResXMLParser::getAttributeStringValue(size_t idx, size_t* outLen) const
    832 {
    833     int32_t id = getAttributeValueStringID(idx);
    834     //XML_NOISY(printf("getAttributeValue 0x%x=0x%x\n", idx, id));
    835     return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
    836 }
    837 
    838 int32_t ResXMLParser::getAttributeDataType(size_t idx) const
    839 {
    840     if (mEventCode == START_TAG) {
    841         const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
    842         if (idx < dtohs(tag->attributeCount)) {
    843             const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
    844                 (((const uint8_t*)tag)
    845                  + dtohs(tag->attributeStart)
    846                  + (dtohs(tag->attributeSize)*idx));
    847             return attr->typedValue.dataType;
    848         }
    849     }
    850     return Res_value::TYPE_NULL;
    851 }
    852 
    853 int32_t ResXMLParser::getAttributeData(size_t idx) const
    854 {
    855     if (mEventCode == START_TAG) {
    856         const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
    857         if (idx < dtohs(tag->attributeCount)) {
    858             const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
    859                 (((const uint8_t*)tag)
    860                  + dtohs(tag->attributeStart)
    861                  + (dtohs(tag->attributeSize)*idx));
    862             return dtohl(attr->typedValue.data);
    863         }
    864     }
    865     return 0;
    866 }
    867 
    868 ssize_t ResXMLParser::getAttributeValue(size_t idx, Res_value* outValue) const
    869 {
    870     if (mEventCode == START_TAG) {
    871         const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
    872         if (idx < dtohs(tag->attributeCount)) {
    873             const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
    874                 (((const uint8_t*)tag)
    875                  + dtohs(tag->attributeStart)
    876                  + (dtohs(tag->attributeSize)*idx));
    877             outValue->copyFrom_dtoh(attr->typedValue);
    878             return sizeof(Res_value);
    879         }
    880     }
    881     return BAD_TYPE;
    882 }
    883 
    884 ssize_t ResXMLParser::indexOfAttribute(const char* ns, const char* attr) const
    885 {
    886     String16 nsStr(ns != NULL ? ns : "");
    887     String16 attrStr(attr);
    888     return indexOfAttribute(ns ? nsStr.string() : NULL, ns ? nsStr.size() : 0,
    889                             attrStr.string(), attrStr.size());
    890 }
    891 
    892 ssize_t ResXMLParser::indexOfAttribute(const char16_t* ns, size_t nsLen,
    893                                        const char16_t* attr, size_t attrLen) const
    894 {
    895     if (mEventCode == START_TAG) {
    896         const size_t N = getAttributeCount();
    897         for (size_t i=0; i<N; i++) {
    898             size_t curNsLen, curAttrLen;
    899             const char16_t* curNs = getAttributeNamespace(i, &curNsLen);
    900             const char16_t* curAttr = getAttributeName(i, &curAttrLen);
    901             //printf("%d: ns=%p attr=%p curNs=%p curAttr=%p\n",
    902             //       i, ns, attr, curNs, curAttr);
    903             //printf(" --> attr=%s, curAttr=%s\n",
    904             //       String8(attr).string(), String8(curAttr).string());
    905             if (attr && curAttr && (strzcmp16(attr, attrLen, curAttr, curAttrLen) == 0)) {
    906                 if (ns == NULL) {
    907                     if (curNs == NULL) return i;
    908                 } else if (curNs != NULL) {
    909                     //printf(" --> ns=%s, curNs=%s\n",
    910                     //       String8(ns).string(), String8(curNs).string());
    911                     if (strzcmp16(ns, nsLen, curNs, curNsLen) == 0) return i;
    912                 }
    913             }
    914         }
    915     }
    916 
    917     return NAME_NOT_FOUND;
    918 }
    919 
    920 ssize_t ResXMLParser::indexOfID() const
    921 {
    922     if (mEventCode == START_TAG) {
    923         const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->idIndex);
    924         if (idx > 0) return (idx-1);
    925     }
    926     return NAME_NOT_FOUND;
    927 }
    928 
    929 ssize_t ResXMLParser::indexOfClass() const
    930 {
    931     if (mEventCode == START_TAG) {
    932         const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->classIndex);
    933         if (idx > 0) return (idx-1);
    934     }
    935     return NAME_NOT_FOUND;
    936 }
    937 
    938 ssize_t ResXMLParser::indexOfStyle() const
    939 {
    940     if (mEventCode == START_TAG) {
    941         const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->styleIndex);
    942         if (idx > 0) return (idx-1);
    943     }
    944     return NAME_NOT_FOUND;
    945 }
    946 
    947 ResXMLParser::event_code_t ResXMLParser::nextNode()
    948 {
    949     if (mEventCode < 0) {
    950         return mEventCode;
    951     }
    952 
    953     do {
    954         const ResXMLTree_node* next = (const ResXMLTree_node*)
    955             (((const uint8_t*)mCurNode) + dtohl(mCurNode->header.size));
    956         //LOGW("Next node: prev=%p, next=%p\n", mCurNode, next);
    957 
    958         if (((const uint8_t*)next) >= mTree.mDataEnd) {
    959             mCurNode = NULL;
    960             return (mEventCode=END_DOCUMENT);
    961         }
    962 
    963         if (mTree.validateNode(next) != NO_ERROR) {
    964             mCurNode = NULL;
    965             return (mEventCode=BAD_DOCUMENT);
    966         }
    967 
    968         mCurNode = next;
    969         const uint16_t headerSize = dtohs(next->header.headerSize);
    970         const uint32_t totalSize = dtohl(next->header.size);
    971         mCurExt = ((const uint8_t*)next) + headerSize;
    972         size_t minExtSize = 0;
    973         event_code_t eventCode = (event_code_t)dtohs(next->header.type);
    974         switch ((mEventCode=eventCode)) {
    975             case RES_XML_START_NAMESPACE_TYPE:
    976             case RES_XML_END_NAMESPACE_TYPE:
    977                 minExtSize = sizeof(ResXMLTree_namespaceExt);
    978                 break;
    979             case RES_XML_START_ELEMENT_TYPE:
    980                 minExtSize = sizeof(ResXMLTree_attrExt);
    981                 break;
    982             case RES_XML_END_ELEMENT_TYPE:
    983                 minExtSize = sizeof(ResXMLTree_endElementExt);
    984                 break;
    985             case RES_XML_CDATA_TYPE:
    986                 minExtSize = sizeof(ResXMLTree_cdataExt);
    987                 break;
    988             default:
    989                 LOGW("Unknown XML block: header type %d in node at %d\n",
    990                      (int)dtohs(next->header.type),
    991                      (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)));
    992                 continue;
    993         }
    994 
    995         if ((totalSize-headerSize) < minExtSize) {
    996             LOGW("Bad XML block: header type 0x%x in node at 0x%x has size %d, need %d\n",
    997                  (int)dtohs(next->header.type),
    998                  (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)),
    999                  (int)(totalSize-headerSize), (int)minExtSize);
   1000             return (mEventCode=BAD_DOCUMENT);
   1001         }
   1002 
   1003         //printf("CurNode=%p, CurExt=%p, headerSize=%d, minExtSize=%d\n",
   1004         //       mCurNode, mCurExt, headerSize, minExtSize);
   1005 
   1006         return eventCode;
   1007     } while (true);
   1008 }
   1009 
   1010 void ResXMLParser::getPosition(ResXMLParser::ResXMLPosition* pos) const
   1011 {
   1012     pos->eventCode = mEventCode;
   1013     pos->curNode = mCurNode;
   1014     pos->curExt = mCurExt;
   1015 }
   1016 
   1017 void ResXMLParser::setPosition(const ResXMLParser::ResXMLPosition& pos)
   1018 {
   1019     mEventCode = pos.eventCode;
   1020     mCurNode = pos.curNode;
   1021     mCurExt = pos.curExt;
   1022 }
   1023 
   1024 
   1025 // --------------------------------------------------------------------
   1026 
   1027 static volatile int32_t gCount = 0;
   1028 
   1029 ResXMLTree::ResXMLTree()
   1030     : ResXMLParser(*this)
   1031     , mError(NO_INIT), mOwnedData(NULL)
   1032 {
   1033     //LOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1);
   1034     restart();
   1035 }
   1036 
   1037 ResXMLTree::ResXMLTree(const void* data, size_t size, bool copyData)
   1038     : ResXMLParser(*this)
   1039     , mError(NO_INIT), mOwnedData(NULL)
   1040 {
   1041     //LOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1);
   1042     setTo(data, size, copyData);
   1043 }
   1044 
   1045 ResXMLTree::~ResXMLTree()
   1046 {
   1047     //LOGI("Destroying ResXMLTree in %p #%d\n", this, android_atomic_dec(&gCount)-1);
   1048     uninit();
   1049 }
   1050 
   1051 status_t ResXMLTree::setTo(const void* data, size_t size, bool copyData)
   1052 {
   1053     uninit();
   1054     mEventCode = START_DOCUMENT;
   1055 
   1056     if (copyData) {
   1057         mOwnedData = malloc(size);
   1058         if (mOwnedData == NULL) {
   1059             return (mError=NO_MEMORY);
   1060         }
   1061         memcpy(mOwnedData, data, size);
   1062         data = mOwnedData;
   1063     }
   1064 
   1065     mHeader = (const ResXMLTree_header*)data;
   1066     mSize = dtohl(mHeader->header.size);
   1067     if (dtohs(mHeader->header.headerSize) > mSize || mSize > size) {
   1068         LOGW("Bad XML block: header size %d or total size %d is larger than data size %d\n",
   1069              (int)dtohs(mHeader->header.headerSize),
   1070              (int)dtohl(mHeader->header.size), (int)size);
   1071         mError = BAD_TYPE;
   1072         restart();
   1073         return mError;
   1074     }
   1075     mDataEnd = ((const uint8_t*)mHeader) + mSize;
   1076 
   1077     mStrings.uninit();
   1078     mRootNode = NULL;
   1079     mResIds = NULL;
   1080     mNumResIds = 0;
   1081 
   1082     // First look for a couple interesting chunks: the string block
   1083     // and first XML node.
   1084     const ResChunk_header* chunk =
   1085         (const ResChunk_header*)(((const uint8_t*)mHeader) + dtohs(mHeader->header.headerSize));
   1086     const ResChunk_header* lastChunk = chunk;
   1087     while (((const uint8_t*)chunk) < (mDataEnd-sizeof(ResChunk_header)) &&
   1088            ((const uint8_t*)chunk) < (mDataEnd-dtohl(chunk->size))) {
   1089         status_t err = validate_chunk(chunk, sizeof(ResChunk_header), mDataEnd, "XML");
   1090         if (err != NO_ERROR) {
   1091             mError = err;
   1092             goto done;
   1093         }
   1094         const uint16_t type = dtohs(chunk->type);
   1095         const size_t size = dtohl(chunk->size);
   1096         XML_NOISY(printf("Scanning @ %p: type=0x%x, size=0x%x\n",
   1097                      (void*)(((uint32_t)chunk)-((uint32_t)mHeader)), type, size));
   1098         if (type == RES_STRING_POOL_TYPE) {
   1099             mStrings.setTo(chunk, size);
   1100         } else if (type == RES_XML_RESOURCE_MAP_TYPE) {
   1101             mResIds = (const uint32_t*)
   1102                 (((const uint8_t*)chunk)+dtohs(chunk->headerSize));
   1103             mNumResIds = (dtohl(chunk->size)-dtohs(chunk->headerSize))/sizeof(uint32_t);
   1104         } else if (type >= RES_XML_FIRST_CHUNK_TYPE
   1105                    && type <= RES_XML_LAST_CHUNK_TYPE) {
   1106             if (validateNode((const ResXMLTree_node*)chunk) != NO_ERROR) {
   1107                 mError = BAD_TYPE;
   1108                 goto done;
   1109             }
   1110             mCurNode = (const ResXMLTree_node*)lastChunk;
   1111             if (nextNode() == BAD_DOCUMENT) {
   1112                 mError = BAD_TYPE;
   1113                 goto done;
   1114             }
   1115             mRootNode = mCurNode;
   1116             mRootExt = mCurExt;
   1117             mRootCode = mEventCode;
   1118             break;
   1119         } else {
   1120             XML_NOISY(printf("Skipping unknown chunk!\n"));
   1121         }
   1122         lastChunk = chunk;
   1123         chunk = (const ResChunk_header*)
   1124             (((const uint8_t*)chunk) + size);
   1125     }
   1126 
   1127     if (mRootNode == NULL) {
   1128         LOGW("Bad XML block: no root element node found\n");
   1129         mError = BAD_TYPE;
   1130         goto done;
   1131     }
   1132 
   1133     mError = mStrings.getError();
   1134 
   1135 done:
   1136     restart();
   1137     return mError;
   1138 }
   1139 
   1140 status_t ResXMLTree::getError() const
   1141 {
   1142     return mError;
   1143 }
   1144 
   1145 void ResXMLTree::uninit()
   1146 {
   1147     mError = NO_INIT;
   1148     mStrings.uninit();
   1149     if (mOwnedData) {
   1150         free(mOwnedData);
   1151         mOwnedData = NULL;
   1152     }
   1153     restart();
   1154 }
   1155 
   1156 status_t ResXMLTree::validateNode(const ResXMLTree_node* node) const
   1157 {
   1158     const uint16_t eventCode = dtohs(node->header.type);
   1159 
   1160     status_t err = validate_chunk(
   1161         &node->header, sizeof(ResXMLTree_node),
   1162         mDataEnd, "ResXMLTree_node");
   1163 
   1164     if (err >= NO_ERROR) {
   1165         // Only perform additional validation on START nodes
   1166         if (eventCode != RES_XML_START_ELEMENT_TYPE) {
   1167             return NO_ERROR;
   1168         }
   1169 
   1170         const uint16_t headerSize = dtohs(node->header.headerSize);
   1171         const uint32_t size = dtohl(node->header.size);
   1172         const ResXMLTree_attrExt* attrExt = (const ResXMLTree_attrExt*)
   1173             (((const uint8_t*)node) + headerSize);
   1174         // check for sensical values pulled out of the stream so far...
   1175         if ((size >= headerSize + sizeof(ResXMLTree_attrExt))
   1176                 && ((void*)attrExt > (void*)node)) {
   1177             const size_t attrSize = ((size_t)dtohs(attrExt->attributeSize))
   1178                 * dtohs(attrExt->attributeCount);
   1179             if ((dtohs(attrExt->attributeStart)+attrSize) <= (size-headerSize)) {
   1180                 return NO_ERROR;
   1181             }
   1182             LOGW("Bad XML block: node attributes use 0x%x bytes, only have 0x%x bytes\n",
   1183                     (unsigned int)(dtohs(attrExt->attributeStart)+attrSize),
   1184                     (unsigned int)(size-headerSize));
   1185         }
   1186         else {
   1187             LOGW("Bad XML start block: node header size 0x%x, size 0x%x\n",
   1188                 (unsigned int)headerSize, (unsigned int)size);
   1189         }
   1190         return BAD_TYPE;
   1191     }
   1192 
   1193     return err;
   1194 
   1195 #if 0
   1196     const bool isStart = dtohs(node->header.type) == RES_XML_START_ELEMENT_TYPE;
   1197 
   1198     const uint16_t headerSize = dtohs(node->header.headerSize);
   1199     const uint32_t size = dtohl(node->header.size);
   1200 
   1201     if (headerSize >= (isStart ? sizeof(ResXMLTree_attrNode) : sizeof(ResXMLTree_node))) {
   1202         if (size >= headerSize) {
   1203             if (((const uint8_t*)node) <= (mDataEnd-size)) {
   1204                 if (!isStart) {
   1205                     return NO_ERROR;
   1206                 }
   1207                 if ((((size_t)dtohs(node->attributeSize))*dtohs(node->attributeCount))
   1208                         <= (size-headerSize)) {
   1209                     return NO_ERROR;
   1210                 }
   1211                 LOGW("Bad XML block: node attributes use 0x%x bytes, only have 0x%x bytes\n",
   1212                         ((int)dtohs(node->attributeSize))*dtohs(node->attributeCount),
   1213                         (int)(size-headerSize));
   1214                 return BAD_TYPE;
   1215             }
   1216             LOGW("Bad XML block: node at 0x%x extends beyond data end 0x%x\n",
   1217                     (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)), (int)mSize);
   1218             return BAD_TYPE;
   1219         }
   1220         LOGW("Bad XML block: node at 0x%x header size 0x%x smaller than total size 0x%x\n",
   1221                 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)),
   1222                 (int)headerSize, (int)size);
   1223         return BAD_TYPE;
   1224     }
   1225     LOGW("Bad XML block: node at 0x%x header size 0x%x too small\n",
   1226             (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)),
   1227             (int)headerSize);
   1228     return BAD_TYPE;
   1229 #endif
   1230 }
   1231 
   1232 // --------------------------------------------------------------------
   1233 // --------------------------------------------------------------------
   1234 // --------------------------------------------------------------------
   1235 
   1236 struct ResTable::Header
   1237 {
   1238     Header(ResTable* _owner) : owner(_owner), ownedData(NULL), header(NULL) { }
   1239 
   1240     ResTable* const                 owner;
   1241     void*                           ownedData;
   1242     const ResTable_header*          header;
   1243     size_t                          size;
   1244     const uint8_t*                  dataEnd;
   1245     size_t                          index;
   1246     void*                           cookie;
   1247 
   1248     ResStringPool                   values;
   1249 };
   1250 
   1251 struct ResTable::Type
   1252 {
   1253     Type(const Header* _header, const Package* _package, size_t count)
   1254         : header(_header), package(_package), entryCount(count),
   1255           typeSpec(NULL), typeSpecFlags(NULL) { }
   1256     const Header* const             header;
   1257     const Package* const            package;
   1258     const size_t                    entryCount;
   1259     const ResTable_typeSpec*        typeSpec;
   1260     const uint32_t*                 typeSpecFlags;
   1261     Vector<const ResTable_type*>    configs;
   1262 };
   1263 
   1264 struct ResTable::Package
   1265 {
   1266     Package(ResTable* _owner, const Header* _header, const ResTable_package* _package)
   1267         : owner(_owner), header(_header), package(_package) { }
   1268     ~Package()
   1269     {
   1270         size_t i = types.size();
   1271         while (i > 0) {
   1272             i--;
   1273             delete types[i];
   1274         }
   1275     }
   1276 
   1277     ResTable* const                 owner;
   1278     const Header* const             header;
   1279     const ResTable_package* const   package;
   1280     Vector<Type*>                   types;
   1281 
   1282     ResStringPool                   typeStrings;
   1283     ResStringPool                   keyStrings;
   1284 
   1285     const Type* getType(size_t idx) const {
   1286         return idx < types.size() ? types[idx] : NULL;
   1287     }
   1288 };
   1289 
   1290 // A group of objects describing a particular resource package.
   1291 // The first in 'package' is always the root object (from the resource
   1292 // table that defined the package); the ones after are skins on top of it.
   1293 struct ResTable::PackageGroup
   1294 {
   1295     PackageGroup(ResTable* _owner, const String16& _name, uint32_t _id)
   1296         : owner(_owner), name(_name), id(_id), typeCount(0), bags(NULL) { }
   1297     ~PackageGroup() {
   1298         clearBagCache();
   1299         const size_t N = packages.size();
   1300         for (size_t i=0; i<N; i++) {
   1301             Package* pkg = packages[i];
   1302             if (pkg->owner == owner) {
   1303                 delete pkg;
   1304             }
   1305         }
   1306     }
   1307 
   1308     void clearBagCache() {
   1309         if (bags) {
   1310             TABLE_NOISY(printf("bags=%p\n", bags));
   1311             Package* pkg = packages[0];
   1312             TABLE_NOISY(printf("typeCount=%x\n", typeCount));
   1313             for (size_t i=0; i<typeCount; i++) {
   1314                 TABLE_NOISY(printf("type=%d\n", i));
   1315                 const Type* type = pkg->getType(i);
   1316                 if (type != NULL) {
   1317                     bag_set** typeBags = bags[i];
   1318                     TABLE_NOISY(printf("typeBags=%p\n", typeBags));
   1319                     if (typeBags) {
   1320                         TABLE_NOISY(printf("type->entryCount=%x\n", type->entryCount));
   1321                         const size_t N = type->entryCount;
   1322                         for (size_t j=0; j<N; j++) {
   1323                             if (typeBags[j] && typeBags[j] != (bag_set*)0xFFFFFFFF)
   1324                                 free(typeBags[j]);
   1325                         }
   1326                         free(typeBags);
   1327                     }
   1328                 }
   1329             }
   1330             free(bags);
   1331             bags = NULL;
   1332         }
   1333     }
   1334 
   1335     ResTable* const                 owner;
   1336     String16 const                  name;
   1337     uint32_t const                  id;
   1338     Vector<Package*>                packages;
   1339 
   1340     // This is for finding typeStrings and other common package stuff.
   1341     Package*                        basePackage;
   1342 
   1343     // For quick access.
   1344     size_t                          typeCount;
   1345 
   1346     // Computed attribute bags, first indexed by the type and second
   1347     // by the entry in that type.
   1348     bag_set***                      bags;
   1349 };
   1350 
   1351 struct ResTable::bag_set
   1352 {
   1353     size_t numAttrs;    // number in array
   1354     size_t availAttrs;  // total space in array
   1355     uint32_t typeSpecFlags;
   1356     // Followed by 'numAttr' bag_entry structures.
   1357 };
   1358 
   1359 ResTable::Theme::Theme(const ResTable& table)
   1360     : mTable(table)
   1361 {
   1362     memset(mPackages, 0, sizeof(mPackages));
   1363 }
   1364 
   1365 ResTable::Theme::~Theme()
   1366 {
   1367     for (size_t i=0; i<Res_MAXPACKAGE; i++) {
   1368         package_info* pi = mPackages[i];
   1369         if (pi != NULL) {
   1370             free_package(pi);
   1371         }
   1372     }
   1373 }
   1374 
   1375 void ResTable::Theme::free_package(package_info* pi)
   1376 {
   1377     for (size_t j=0; j<pi->numTypes; j++) {
   1378         theme_entry* te = pi->types[j].entries;
   1379         if (te != NULL) {
   1380             free(te);
   1381         }
   1382     }
   1383     free(pi);
   1384 }
   1385 
   1386 ResTable::Theme::package_info* ResTable::Theme::copy_package(package_info* pi)
   1387 {
   1388     package_info* newpi = (package_info*)malloc(
   1389         sizeof(package_info) + (pi->numTypes*sizeof(type_info)));
   1390     newpi->numTypes = pi->numTypes;
   1391     for (size_t j=0; j<newpi->numTypes; j++) {
   1392         size_t cnt = pi->types[j].numEntries;
   1393         newpi->types[j].numEntries = cnt;
   1394         theme_entry* te = pi->types[j].entries;
   1395         if (te != NULL) {
   1396             theme_entry* newte = (theme_entry*)malloc(cnt*sizeof(theme_entry));
   1397             newpi->types[j].entries = newte;
   1398             memcpy(newte, te, cnt*sizeof(theme_entry));
   1399         } else {
   1400             newpi->types[j].entries = NULL;
   1401         }
   1402     }
   1403     return newpi;
   1404 }
   1405 
   1406 status_t ResTable::Theme::applyStyle(uint32_t resID, bool force)
   1407 {
   1408     const bag_entry* bag;
   1409     uint32_t bagTypeSpecFlags = 0;
   1410     mTable.lock();
   1411     const ssize_t N = mTable.getBagLocked(resID, &bag, &bagTypeSpecFlags);
   1412     TABLE_NOISY(LOGV("Applying style 0x%08x to theme %p, count=%d", resID, this, N));
   1413     if (N < 0) {
   1414         mTable.unlock();
   1415         return N;
   1416     }
   1417 
   1418     uint32_t curPackage = 0xffffffff;
   1419     ssize_t curPackageIndex = 0;
   1420     package_info* curPI = NULL;
   1421     uint32_t curType = 0xffffffff;
   1422     size_t numEntries = 0;
   1423     theme_entry* curEntries = NULL;
   1424 
   1425     const bag_entry* end = bag + N;
   1426     while (bag < end) {
   1427         const uint32_t attrRes = bag->map.name.ident;
   1428         const uint32_t p = Res_GETPACKAGE(attrRes);
   1429         const uint32_t t = Res_GETTYPE(attrRes);
   1430         const uint32_t e = Res_GETENTRY(attrRes);
   1431 
   1432         if (curPackage != p) {
   1433             const ssize_t pidx = mTable.getResourcePackageIndex(attrRes);
   1434             if (pidx < 0) {
   1435                 LOGE("Style contains key with bad package: 0x%08x\n", attrRes);
   1436                 bag++;
   1437                 continue;
   1438             }
   1439             curPackage = p;
   1440             curPackageIndex = pidx;
   1441             curPI = mPackages[pidx];
   1442             if (curPI == NULL) {
   1443                 PackageGroup* const grp = mTable.mPackageGroups[pidx];
   1444                 int cnt = grp->typeCount;
   1445                 curPI = (package_info*)malloc(
   1446                     sizeof(package_info) + (cnt*sizeof(type_info)));
   1447                 curPI->numTypes = cnt;
   1448                 memset(curPI->types, 0, cnt*sizeof(type_info));
   1449                 mPackages[pidx] = curPI;
   1450             }
   1451             curType = 0xffffffff;
   1452         }
   1453         if (curType != t) {
   1454             if (t >= curPI->numTypes) {
   1455                 LOGE("Style contains key with bad type: 0x%08x\n", attrRes);
   1456                 bag++;
   1457                 continue;
   1458             }
   1459             curType = t;
   1460             curEntries = curPI->types[t].entries;
   1461             if (curEntries == NULL) {
   1462                 PackageGroup* const grp = mTable.mPackageGroups[curPackageIndex];
   1463                 const Type* type = grp->packages[0]->getType(t);
   1464                 int cnt = type != NULL ? type->entryCount : 0;
   1465                 curEntries = (theme_entry*)malloc(cnt*sizeof(theme_entry));
   1466                 memset(curEntries, Res_value::TYPE_NULL, cnt*sizeof(theme_entry));
   1467                 curPI->types[t].numEntries = cnt;
   1468                 curPI->types[t].entries = curEntries;
   1469             }
   1470             numEntries = curPI->types[t].numEntries;
   1471         }
   1472         if (e >= numEntries) {
   1473             LOGE("Style contains key with bad entry: 0x%08x\n", attrRes);
   1474             bag++;
   1475             continue;
   1476         }
   1477         theme_entry* curEntry = curEntries + e;
   1478         TABLE_NOISY(LOGV("Attr 0x%08x: type=0x%x, data=0x%08x; curType=0x%x",
   1479                    attrRes, bag->map.value.dataType, bag->map.value.data,
   1480              curEntry->value.dataType));
   1481         if (force || curEntry->value.dataType == Res_value::TYPE_NULL) {
   1482             curEntry->stringBlock = bag->stringBlock;
   1483             curEntry->typeSpecFlags |= bagTypeSpecFlags;
   1484             curEntry->value = bag->map.value;
   1485         }
   1486 
   1487         bag++;
   1488     }
   1489 
   1490     mTable.unlock();
   1491 
   1492     //LOGI("Applying style 0x%08x (force=%d)  theme %p...\n", resID, force, this);
   1493     //dumpToLog();
   1494 
   1495     return NO_ERROR;
   1496 }
   1497 
   1498 status_t ResTable::Theme::setTo(const Theme& other)
   1499 {
   1500     //LOGI("Setting theme %p from theme %p...\n", this, &other);
   1501     //dumpToLog();
   1502     //other.dumpToLog();
   1503 
   1504     if (&mTable == &other.mTable) {
   1505         for (size_t i=0; i<Res_MAXPACKAGE; i++) {
   1506             if (mPackages[i] != NULL) {
   1507                 free_package(mPackages[i]);
   1508             }
   1509             if (other.mPackages[i] != NULL) {
   1510                 mPackages[i] = copy_package(other.mPackages[i]);
   1511             } else {
   1512                 mPackages[i] = NULL;
   1513             }
   1514         }
   1515     } else {
   1516         // @todo: need to really implement this, not just copy
   1517         // the system package (which is still wrong because it isn't
   1518         // fixing up resource references).
   1519         for (size_t i=0; i<Res_MAXPACKAGE; i++) {
   1520             if (mPackages[i] != NULL) {
   1521                 free_package(mPackages[i]);
   1522             }
   1523             if (i == 0 && other.mPackages[i] != NULL) {
   1524                 mPackages[i] = copy_package(other.mPackages[i]);
   1525             } else {
   1526                 mPackages[i] = NULL;
   1527             }
   1528         }
   1529     }
   1530 
   1531     //LOGI("Final theme:");
   1532     //dumpToLog();
   1533 
   1534     return NO_ERROR;
   1535 }
   1536 
   1537 ssize_t ResTable::Theme::getAttribute(uint32_t resID, Res_value* outValue,
   1538         uint32_t* outTypeSpecFlags) const
   1539 {
   1540     int cnt = 20;
   1541 
   1542     if (outTypeSpecFlags != NULL) *outTypeSpecFlags = 0;
   1543 
   1544     do {
   1545         const ssize_t p = mTable.getResourcePackageIndex(resID);
   1546         const uint32_t t = Res_GETTYPE(resID);
   1547         const uint32_t e = Res_GETENTRY(resID);
   1548 
   1549         TABLE_THEME(LOGI("Looking up attr 0x%08x in theme %p", resID, this));
   1550 
   1551         if (p >= 0) {
   1552             const package_info* const pi = mPackages[p];
   1553             TABLE_THEME(LOGI("Found package: %p", pi));
   1554             if (pi != NULL) {
   1555                 TABLE_THEME(LOGI("Desired type index is %ld in avail %d", t, pi->numTypes));
   1556                 if (t < pi->numTypes) {
   1557                     const type_info& ti = pi->types[t];
   1558                     TABLE_THEME(LOGI("Desired entry index is %ld in avail %d", e, ti.numEntries));
   1559                     if (e < ti.numEntries) {
   1560                         const theme_entry& te = ti.entries[e];
   1561                         if (outTypeSpecFlags != NULL) {
   1562                             *outTypeSpecFlags |= te.typeSpecFlags;
   1563                         }
   1564                         TABLE_THEME(LOGI("Theme value: type=0x%x, data=0x%08x",
   1565                                 te.value.dataType, te.value.data));
   1566                         const uint8_t type = te.value.dataType;
   1567                         if (type == Res_value::TYPE_ATTRIBUTE) {
   1568                             if (cnt > 0) {
   1569                                 cnt--;
   1570                                 resID = te.value.data;
   1571                                 continue;
   1572                             }
   1573                             LOGW("Too many attribute references, stopped at: 0x%08x\n", resID);
   1574                             return BAD_INDEX;
   1575                         } else if (type != Res_value::TYPE_NULL) {
   1576                             *outValue = te.value;
   1577                             return te.stringBlock;
   1578                         }
   1579                         return BAD_INDEX;
   1580                     }
   1581                 }
   1582             }
   1583         }
   1584         break;
   1585 
   1586     } while (true);
   1587 
   1588     return BAD_INDEX;
   1589 }
   1590 
   1591 ssize_t ResTable::Theme::resolveAttributeReference(Res_value* inOutValue,
   1592         ssize_t blockIndex, uint32_t* outLastRef,
   1593         uint32_t* inoutTypeSpecFlags, ResTable_config* inoutConfig) const
   1594 {
   1595     //printf("Resolving type=0x%x\n", inOutValue->dataType);
   1596     if (inOutValue->dataType == Res_value::TYPE_ATTRIBUTE) {
   1597         uint32_t newTypeSpecFlags;
   1598         blockIndex = getAttribute(inOutValue->data, inOutValue, &newTypeSpecFlags);
   1599         TABLE_THEME(LOGI("Resolving attr reference: blockIndex=%d, type=0x%x, data=%p\n",
   1600              (int)blockIndex, (int)inOutValue->dataType, (void*)inOutValue->data));
   1601         if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newTypeSpecFlags;
   1602         //printf("Retrieved attribute new type=0x%x\n", inOutValue->dataType);
   1603         if (blockIndex < 0) {
   1604             return blockIndex;
   1605         }
   1606     }
   1607     return mTable.resolveReference(inOutValue, blockIndex, outLastRef,
   1608             inoutTypeSpecFlags, inoutConfig);
   1609 }
   1610 
   1611 void ResTable::Theme::dumpToLog() const
   1612 {
   1613     LOGI("Theme %p:\n", this);
   1614     for (size_t i=0; i<Res_MAXPACKAGE; i++) {
   1615         package_info* pi = mPackages[i];
   1616         if (pi == NULL) continue;
   1617 
   1618         LOGI("  Package #0x%02x:\n", (int)(i+1));
   1619         for (size_t j=0; j<pi->numTypes; j++) {
   1620             type_info& ti = pi->types[j];
   1621             if (ti.numEntries == 0) continue;
   1622 
   1623             LOGI("    Type #0x%02x:\n", (int)(j+1));
   1624             for (size_t k=0; k<ti.numEntries; k++) {
   1625                 theme_entry& te = ti.entries[k];
   1626                 if (te.value.dataType == Res_value::TYPE_NULL) continue;
   1627                 LOGI("      0x%08x: t=0x%x, d=0x%08x (block=%d)\n",
   1628                      (int)Res_MAKEID(i, j, k),
   1629                      te.value.dataType, (int)te.value.data, (int)te.stringBlock);
   1630             }
   1631         }
   1632     }
   1633 }
   1634 
   1635 ResTable::ResTable()
   1636     : mError(NO_INIT)
   1637 {
   1638     memset(&mParams, 0, sizeof(mParams));
   1639     memset(mPackageMap, 0, sizeof(mPackageMap));
   1640     //LOGI("Creating ResTable %p\n", this);
   1641 }
   1642 
   1643 ResTable::ResTable(const void* data, size_t size, void* cookie, bool copyData)
   1644     : mError(NO_INIT)
   1645 {
   1646     memset(&mParams, 0, sizeof(mParams));
   1647     memset(mPackageMap, 0, sizeof(mPackageMap));
   1648     add(data, size, cookie, copyData);
   1649     LOG_FATAL_IF(mError != NO_ERROR, "Error parsing resource table");
   1650     //LOGI("Creating ResTable %p\n", this);
   1651 }
   1652 
   1653 ResTable::~ResTable()
   1654 {
   1655     //LOGI("Destroying ResTable in %p\n", this);
   1656     uninit();
   1657 }
   1658 
   1659 inline ssize_t ResTable::getResourcePackageIndex(uint32_t resID) const
   1660 {
   1661     return ((ssize_t)mPackageMap[Res_GETPACKAGE(resID)+1])-1;
   1662 }
   1663 
   1664 status_t ResTable::add(const void* data, size_t size, void* cookie, bool copyData)
   1665 {
   1666     return add(data, size, cookie, NULL, copyData);
   1667 }
   1668 
   1669 status_t ResTable::add(Asset* asset, void* cookie, bool copyData)
   1670 {
   1671     const void* data = asset->getBuffer(true);
   1672     if (data == NULL) {
   1673         LOGW("Unable to get buffer of resource asset file");
   1674         return UNKNOWN_ERROR;
   1675     }
   1676     size_t size = (size_t)asset->getLength();
   1677     return add(data, size, cookie, asset, copyData);
   1678 }
   1679 
   1680 status_t ResTable::add(ResTable* src)
   1681 {
   1682     mError = src->mError;
   1683 
   1684     for (size_t i=0; i<src->mHeaders.size(); i++) {
   1685         mHeaders.add(src->mHeaders[i]);
   1686     }
   1687 
   1688     for (size_t i=0; i<src->mPackageGroups.size(); i++) {
   1689         PackageGroup* srcPg = src->mPackageGroups[i];
   1690         PackageGroup* pg = new PackageGroup(this, srcPg->name, srcPg->id);
   1691         for (size_t j=0; j<srcPg->packages.size(); j++) {
   1692             pg->packages.add(srcPg->packages[j]);
   1693         }
   1694         pg->basePackage = srcPg->basePackage;
   1695         pg->typeCount = srcPg->typeCount;
   1696         mPackageGroups.add(pg);
   1697     }
   1698 
   1699     memcpy(mPackageMap, src->mPackageMap, sizeof(mPackageMap));
   1700 
   1701     return mError;
   1702 }
   1703 
   1704 status_t ResTable::add(const void* data, size_t size, void* cookie,
   1705                        Asset* asset, bool copyData)
   1706 {
   1707     if (!data) return NO_ERROR;
   1708     Header* header = new Header(this);
   1709     header->index = mHeaders.size();
   1710     header->cookie = cookie;
   1711     mHeaders.add(header);
   1712 
   1713     const bool notDeviceEndian = htods(0xf0) != 0xf0;
   1714 
   1715     LOAD_TABLE_NOISY(
   1716         LOGV("Adding resources to ResTable: data=%p, size=0x%x, cookie=%p, asset=%p, copy=%d\n",
   1717              data, size, cookie, asset, copyData));
   1718 
   1719     if (copyData || notDeviceEndian) {
   1720         header->ownedData = malloc(size);
   1721         if (header->ownedData == NULL) {
   1722             return (mError=NO_MEMORY);
   1723         }
   1724         memcpy(header->ownedData, data, size);
   1725         data = header->ownedData;
   1726     }
   1727 
   1728     header->header = (const ResTable_header*)data;
   1729     header->size = dtohl(header->header->header.size);
   1730     //LOGI("Got size 0x%x, again size 0x%x, raw size 0x%x\n", header->size,
   1731     //     dtohl(header->header->header.size), header->header->header.size);
   1732     LOAD_TABLE_NOISY(LOGV("Loading ResTable @%p:\n", header->header));
   1733     LOAD_TABLE_NOISY(printHexData(2, header->header, header->size < 256 ? header->size : 256,
   1734                                   16, 16, 0, false, printToLogFunc));
   1735     if (dtohs(header->header->header.headerSize) > header->size
   1736             || header->size > size) {
   1737         LOGW("Bad resource table: header size 0x%x or total size 0x%x is larger than data size 0x%x\n",
   1738              (int)dtohs(header->header->header.headerSize),
   1739              (int)header->size, (int)size);
   1740         return (mError=BAD_TYPE);
   1741     }
   1742     if (((dtohs(header->header->header.headerSize)|header->size)&0x3) != 0) {
   1743         LOGW("Bad resource table: header size 0x%x or total size 0x%x is not on an integer boundary\n",
   1744              (int)dtohs(header->header->header.headerSize),
   1745              (int)header->size);
   1746         return (mError=BAD_TYPE);
   1747     }
   1748     header->dataEnd = ((const uint8_t*)header->header) + header->size;
   1749 
   1750     // Iterate through all chunks.
   1751     size_t curPackage = 0;
   1752 
   1753     const ResChunk_header* chunk =
   1754         (const ResChunk_header*)(((const uint8_t*)header->header)
   1755                                  + dtohs(header->header->header.headerSize));
   1756     while (((const uint8_t*)chunk) <= (header->dataEnd-sizeof(ResChunk_header)) &&
   1757            ((const uint8_t*)chunk) <= (header->dataEnd-dtohl(chunk->size))) {
   1758         status_t err = validate_chunk(chunk, sizeof(ResChunk_header), header->dataEnd, "ResTable");
   1759         if (err != NO_ERROR) {
   1760             return (mError=err);
   1761         }
   1762         TABLE_NOISY(LOGV("Chunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n",
   1763                      dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
   1764                      (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header))));
   1765         const size_t csize = dtohl(chunk->size);
   1766         const uint16_t ctype = dtohs(chunk->type);
   1767         if (ctype == RES_STRING_POOL_TYPE) {
   1768             if (header->values.getError() != NO_ERROR) {
   1769                 // Only use the first string chunk; ignore any others that
   1770                 // may appear.
   1771                 status_t err = header->values.setTo(chunk, csize);
   1772                 if (err != NO_ERROR) {
   1773                     return (mError=err);
   1774                 }
   1775             } else {
   1776                 LOGW("Multiple string chunks found in resource table.");
   1777             }
   1778         } else if (ctype == RES_TABLE_PACKAGE_TYPE) {
   1779             if (curPackage >= dtohl(header->header->packageCount)) {
   1780                 LOGW("More package chunks were found than the %d declared in the header.",
   1781                      dtohl(header->header->packageCount));
   1782                 return (mError=BAD_TYPE);
   1783             }
   1784             if (parsePackage((ResTable_package*)chunk, header) != NO_ERROR) {
   1785                 return mError;
   1786             }
   1787             curPackage++;
   1788         } else {
   1789             LOGW("Unknown chunk type %p in table at %p.\n",
   1790                  (void*)(int)(ctype),
   1791                  (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)));
   1792         }
   1793         chunk = (const ResChunk_header*)
   1794             (((const uint8_t*)chunk) + csize);
   1795     }
   1796 
   1797     if (curPackage < dtohl(header->header->packageCount)) {
   1798         LOGW("Fewer package chunks (%d) were found than the %d declared in the header.",
   1799              (int)curPackage, dtohl(header->header->packageCount));
   1800         return (mError=BAD_TYPE);
   1801     }
   1802     mError = header->values.getError();
   1803     if (mError != NO_ERROR) {
   1804         LOGW("No string values found in resource table!");
   1805     }
   1806     TABLE_NOISY(LOGV("Returning from add with mError=%d\n", mError));
   1807     return mError;
   1808 }
   1809 
   1810 status_t ResTable::getError() const
   1811 {
   1812     return mError;
   1813 }
   1814 
   1815 void ResTable::uninit()
   1816 {
   1817     mError = NO_INIT;
   1818     size_t N = mPackageGroups.size();
   1819     for (size_t i=0; i<N; i++) {
   1820         PackageGroup* g = mPackageGroups[i];
   1821         delete g;
   1822     }
   1823     N = mHeaders.size();
   1824     for (size_t i=0; i<N; i++) {
   1825         Header* header = mHeaders[i];
   1826         if (header->owner == this) {
   1827             if (header->ownedData) {
   1828                 free(header->ownedData);
   1829             }
   1830             delete header;
   1831         }
   1832     }
   1833 
   1834     mPackageGroups.clear();
   1835     mHeaders.clear();
   1836 }
   1837 
   1838 bool ResTable::getResourceName(uint32_t resID, resource_name* outName) const
   1839 {
   1840     if (mError != NO_ERROR) {
   1841         return false;
   1842     }
   1843 
   1844     const ssize_t p = getResourcePackageIndex(resID);
   1845     const int t = Res_GETTYPE(resID);
   1846     const int e = Res_GETENTRY(resID);
   1847 
   1848     if (p < 0) {
   1849         if (Res_GETPACKAGE(resID)+1 == 0) {
   1850             LOGW("No package identifier when getting name for resource number 0x%08x", resID);
   1851         } else {
   1852             LOGW("No known package when getting name for resource number 0x%08x", resID);
   1853         }
   1854         return false;
   1855     }
   1856     if (t < 0) {
   1857         LOGW("No type identifier when getting name for resource number 0x%08x", resID);
   1858         return false;
   1859     }
   1860 
   1861     const PackageGroup* const grp = mPackageGroups[p];
   1862     if (grp == NULL) {
   1863         LOGW("Bad identifier when getting name for resource number 0x%08x", resID);
   1864         return false;
   1865     }
   1866     if (grp->packages.size() > 0) {
   1867         const Package* const package = grp->packages[0];
   1868 
   1869         const ResTable_type* type;
   1870         const ResTable_entry* entry;
   1871         ssize_t offset = getEntry(package, t, e, NULL, &type, &entry, NULL);
   1872         if (offset <= 0) {
   1873             return false;
   1874         }
   1875 
   1876         outName->package = grp->name.string();
   1877         outName->packageLen = grp->name.size();
   1878         outName->type = grp->basePackage->typeStrings.stringAt(t, &outName->typeLen);
   1879         outName->name = grp->basePackage->keyStrings.stringAt(
   1880             dtohl(entry->key.index), &outName->nameLen);
   1881         return true;
   1882     }
   1883 
   1884     return false;
   1885 }
   1886 
   1887 ssize_t ResTable::getResource(uint32_t resID, Res_value* outValue, bool mayBeBag,
   1888         uint32_t* outSpecFlags, ResTable_config* outConfig) const
   1889 {
   1890     if (mError != NO_ERROR) {
   1891         return mError;
   1892     }
   1893 
   1894     const ssize_t p = getResourcePackageIndex(resID);
   1895     const int t = Res_GETTYPE(resID);
   1896     const int e = Res_GETENTRY(resID);
   1897 
   1898     if (p < 0) {
   1899         if (Res_GETPACKAGE(resID)+1 == 0) {
   1900             LOGW("No package identifier when getting value for resource number 0x%08x", resID);
   1901         } else {
   1902             LOGW("No known package when getting value for resource number 0x%08x", resID);
   1903         }
   1904         return BAD_INDEX;
   1905     }
   1906     if (t < 0) {
   1907         LOGW("No type identifier when getting value for resource number 0x%08x", resID);
   1908         return BAD_INDEX;
   1909     }
   1910 
   1911     const Res_value* bestValue = NULL;
   1912     const Package* bestPackage = NULL;
   1913     ResTable_config bestItem;
   1914     memset(&bestItem, 0, sizeof(bestItem)); // make the compiler shut up
   1915 
   1916     if (outSpecFlags != NULL) *outSpecFlags = 0;
   1917 
   1918     // Look through all resource packages, starting with the most
   1919     // recently added.
   1920     const PackageGroup* const grp = mPackageGroups[p];
   1921     if (grp == NULL) {
   1922         LOGW("Bad identifier when getting value for resource number 0x%08x", resID);
   1923         return BAD_INDEX;
   1924     }
   1925     size_t ip = grp->packages.size();
   1926     while (ip > 0) {
   1927         ip--;
   1928 
   1929         const Package* const package = grp->packages[ip];
   1930 
   1931         const ResTable_type* type;
   1932         const ResTable_entry* entry;
   1933         const Type* typeClass;
   1934         ssize_t offset = getEntry(package, t, e, &mParams, &type, &entry, &typeClass);
   1935         if (offset <= 0) {
   1936             if (offset < 0) {
   1937                 LOGW("Failure getting entry for 0x%08x (t=%d e=%d) in package %zd (error %d)\n",
   1938                         resID, t, e, ip, (int)offset);
   1939                 return offset;
   1940             }
   1941             continue;
   1942         }
   1943 
   1944         if ((dtohs(entry->flags)&entry->FLAG_COMPLEX) != 0) {
   1945             if (!mayBeBag) {
   1946                 LOGW("Requesting resource %p failed because it is complex\n",
   1947                      (void*)resID);
   1948             }
   1949             continue;
   1950         }
   1951 
   1952         TABLE_NOISY(aout << "Resource type data: "
   1953               << HexDump(type, dtohl(type->header.size)) << endl);
   1954 
   1955         if ((size_t)offset > (dtohl(type->header.size)-sizeof(Res_value))) {
   1956             LOGW("ResTable_item at %d is beyond type chunk data %d",
   1957                  (int)offset, dtohl(type->header.size));
   1958             return BAD_TYPE;
   1959         }
   1960 
   1961         const Res_value* item =
   1962             (const Res_value*)(((const uint8_t*)type) + offset);
   1963         ResTable_config thisConfig;
   1964         thisConfig.copyFromDtoH(type->config);
   1965 
   1966         if (outSpecFlags != NULL) {
   1967             if (typeClass->typeSpecFlags != NULL) {
   1968                 *outSpecFlags |= dtohl(typeClass->typeSpecFlags[e]);
   1969             } else {
   1970                 *outSpecFlags = -1;
   1971             }
   1972         }
   1973 
   1974         if (bestPackage != NULL && bestItem.isMoreSpecificThan(thisConfig)) {
   1975             continue;
   1976         }
   1977 
   1978         bestItem = thisConfig;
   1979         bestValue = item;
   1980         bestPackage = package;
   1981     }
   1982 
   1983     TABLE_NOISY(printf("Found result: package %p\n", bestPackage));
   1984 
   1985     if (bestValue) {
   1986         outValue->size = dtohs(bestValue->size);
   1987         outValue->res0 = bestValue->res0;
   1988         outValue->dataType = bestValue->dataType;
   1989         outValue->data = dtohl(bestValue->data);
   1990         if (outConfig != NULL) {
   1991             *outConfig = bestItem;
   1992         }
   1993         TABLE_NOISY(size_t len;
   1994               printf("Found value: pkg=%d, type=%d, str=%s, int=%d\n",
   1995                      bestPackage->header->index,
   1996                      outValue->dataType,
   1997                      outValue->dataType == bestValue->TYPE_STRING
   1998                      ? String8(bestPackage->header->values.stringAt(
   1999                          outValue->data, &len)).string()
   2000                      : "",
   2001                      outValue->data));
   2002         return bestPackage->header->index;
   2003     }
   2004 
   2005     return BAD_VALUE;
   2006 }
   2007 
   2008 ssize_t ResTable::resolveReference(Res_value* value, ssize_t blockIndex,
   2009         uint32_t* outLastRef, uint32_t* inoutTypeSpecFlags,
   2010         ResTable_config* outConfig) const
   2011 {
   2012     int count=0;
   2013     while (blockIndex >= 0 && value->dataType == value->TYPE_REFERENCE
   2014            && value->data != 0 && count < 20) {
   2015         if (outLastRef) *outLastRef = value->data;
   2016         uint32_t lastRef = value->data;
   2017         uint32_t newFlags = 0;
   2018         const ssize_t newIndex = getResource(value->data, value, true, &newFlags,
   2019                 outConfig);
   2020         if (newIndex == BAD_INDEX) {
   2021             return BAD_INDEX;
   2022         }
   2023         TABLE_THEME(LOGI("Resolving reference %p: newIndex=%d, type=0x%x, data=%p\n",
   2024              (void*)lastRef, (int)newIndex, (int)value->dataType, (void*)value->data));
   2025         //printf("Getting reference 0x%08x: newIndex=%d\n", value->data, newIndex);
   2026         if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newFlags;
   2027         if (newIndex < 0) {
   2028             // This can fail if the resource being referenced is a style...
   2029             // in this case, just return the reference, and expect the
   2030             // caller to deal with.
   2031             return blockIndex;
   2032         }
   2033         blockIndex = newIndex;
   2034         count++;
   2035     }
   2036     return blockIndex;
   2037 }
   2038 
   2039 const char16_t* ResTable::valueToString(
   2040     const Res_value* value, size_t stringBlock,
   2041     char16_t tmpBuffer[TMP_BUFFER_SIZE], size_t* outLen)
   2042 {
   2043     if (!value) {
   2044         return NULL;
   2045     }
   2046     if (value->dataType == value->TYPE_STRING) {
   2047         return getTableStringBlock(stringBlock)->stringAt(value->data, outLen);
   2048     }
   2049     // XXX do int to string conversions.
   2050     return NULL;
   2051 }
   2052 
   2053 ssize_t ResTable::lockBag(uint32_t resID, const bag_entry** outBag) const
   2054 {
   2055     mLock.lock();
   2056     ssize_t err = getBagLocked(resID, outBag);
   2057     if (err < NO_ERROR) {
   2058         //printf("*** get failed!  unlocking\n");
   2059         mLock.unlock();
   2060     }
   2061     return err;
   2062 }
   2063 
   2064 void ResTable::unlockBag(const bag_entry* bag) const
   2065 {
   2066     //printf("<<< unlockBag %p\n", this);
   2067     mLock.unlock();
   2068 }
   2069 
   2070 void ResTable::lock() const
   2071 {
   2072     mLock.lock();
   2073 }
   2074 
   2075 void ResTable::unlock() const
   2076 {
   2077     mLock.unlock();
   2078 }
   2079 
   2080 ssize_t ResTable::getBagLocked(uint32_t resID, const bag_entry** outBag,
   2081         uint32_t* outTypeSpecFlags) const
   2082 {
   2083     if (mError != NO_ERROR) {
   2084         return mError;
   2085     }
   2086 
   2087     const ssize_t p = getResourcePackageIndex(resID);
   2088     const int t = Res_GETTYPE(resID);
   2089     const int e = Res_GETENTRY(resID);
   2090 
   2091     if (p < 0) {
   2092         LOGW("Invalid package identifier when getting bag for resource number 0x%08x", resID);
   2093         return BAD_INDEX;
   2094     }
   2095     if (t < 0) {
   2096         LOGW("No type identifier when getting bag for resource number 0x%08x", resID);
   2097         return BAD_INDEX;
   2098     }
   2099 
   2100     //printf("Get bag: id=0x%08x, p=%d, t=%d\n", resID, p, t);
   2101     PackageGroup* const grp = mPackageGroups[p];
   2102     if (grp == NULL) {
   2103         LOGW("Bad identifier when getting bag for resource number 0x%08x", resID);
   2104         return false;
   2105     }
   2106 
   2107     if (t >= (int)grp->typeCount) {
   2108         LOGW("Type identifier 0x%x is larger than type count 0x%x",
   2109              t+1, (int)grp->typeCount);
   2110         return BAD_INDEX;
   2111     }
   2112 
   2113     const Package* const basePackage = grp->packages[0];
   2114 
   2115     const Type* const typeConfigs = basePackage->getType(t);
   2116 
   2117     const size_t NENTRY = typeConfigs->entryCount;
   2118     if (e >= (int)NENTRY) {
   2119         LOGW("Entry identifier 0x%x is larger than entry count 0x%x",
   2120              e, (int)typeConfigs->entryCount);
   2121         return BAD_INDEX;
   2122     }
   2123 
   2124     // First see if we've already computed this bag...
   2125     if (grp->bags) {
   2126         bag_set** typeSet = grp->bags[t];
   2127         if (typeSet) {
   2128             bag_set* set = typeSet[e];
   2129             if (set) {
   2130                 if (set != (bag_set*)0xFFFFFFFF) {
   2131                     if (outTypeSpecFlags != NULL) {
   2132                         *outTypeSpecFlags = set->typeSpecFlags;
   2133                     }
   2134                     *outBag = (bag_entry*)(set+1);
   2135                     //LOGI("Found existing bag for: %p\n", (void*)resID);
   2136                     return set->numAttrs;
   2137                 }
   2138                 LOGW("Attempt to retrieve bag 0x%08x which is invalid or in a cycle.",
   2139                      resID);
   2140                 return BAD_INDEX;
   2141             }
   2142         }
   2143     }
   2144 
   2145     // Bag not found, we need to compute it!
   2146     if (!grp->bags) {
   2147         grp->bags = (bag_set***)malloc(sizeof(bag_set*)*grp->typeCount);
   2148         if (!grp->bags) return NO_MEMORY;
   2149         memset(grp->bags, 0, sizeof(bag_set*)*grp->typeCount);
   2150     }
   2151 
   2152     bag_set** typeSet = grp->bags[t];
   2153     if (!typeSet) {
   2154         typeSet = (bag_set**)malloc(sizeof(bag_set*)*NENTRY);
   2155         if (!typeSet) return NO_MEMORY;
   2156         memset(typeSet, 0, sizeof(bag_set*)*NENTRY);
   2157         grp->bags[t] = typeSet;
   2158     }
   2159 
   2160     // Mark that we are currently working on this one.
   2161     typeSet[e] = (bag_set*)0xFFFFFFFF;
   2162 
   2163     // This is what we are building.
   2164     bag_set* set = NULL;
   2165 
   2166     TABLE_NOISY(LOGI("Building bag: %p\n", (void*)resID));
   2167 
   2168     // Now collect all bag attributes from all packages.
   2169     size_t ip = grp->packages.size();
   2170     while (ip > 0) {
   2171         ip--;
   2172 
   2173         const Package* const package = grp->packages[ip];
   2174 
   2175         const ResTable_type* type;
   2176         const ResTable_entry* entry;
   2177         const Type* typeClass;
   2178         LOGV("Getting entry pkg=%p, t=%d, e=%d\n", package, t, e);
   2179         ssize_t offset = getEntry(package, t, e, &mParams, &type, &entry, &typeClass);
   2180         LOGV("Resulting offset=%d\n", offset);
   2181         if (offset <= 0) {
   2182             if (offset < 0) {
   2183                 if (set) free(set);
   2184                 return offset;
   2185             }
   2186             continue;
   2187         }
   2188 
   2189         if ((dtohs(entry->flags)&entry->FLAG_COMPLEX) == 0) {
   2190             LOGW("Skipping entry %p in package table %d because it is not complex!\n",
   2191                  (void*)resID, (int)ip);
   2192             continue;
   2193         }
   2194 
   2195         const uint16_t entrySize = dtohs(entry->size);
   2196         const uint32_t parent = entrySize >= sizeof(ResTable_map_entry)
   2197             ? dtohl(((const ResTable_map_entry*)entry)->parent.ident) : 0;
   2198         const uint32_t count = entrySize >= sizeof(ResTable_map_entry)
   2199             ? dtohl(((const ResTable_map_entry*)entry)->count) : 0;
   2200 
   2201         size_t N = count;
   2202 
   2203         TABLE_NOISY(LOGI("Found map: size=%p parent=%p count=%d\n",
   2204                          entrySize, parent, count));
   2205 
   2206         if (set == NULL) {
   2207             // If this map inherits from another, we need to start
   2208             // with its parent's values.  Otherwise start out empty.
   2209             TABLE_NOISY(printf("Creating new bag, entrySize=0x%08x, parent=0x%08x\n",
   2210                          entrySize, parent));
   2211             if (parent) {
   2212                 const bag_entry* parentBag;
   2213                 uint32_t parentTypeSpecFlags = 0;
   2214                 const ssize_t NP = getBagLocked(parent, &parentBag, &parentTypeSpecFlags);
   2215                 const size_t NT = ((NP >= 0) ? NP : 0) + N;
   2216                 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*NT);
   2217                 if (set == NULL) {
   2218                     return NO_MEMORY;
   2219                 }
   2220                 if (NP > 0) {
   2221                     memcpy(set+1, parentBag, NP*sizeof(bag_entry));
   2222                     set->numAttrs = NP;
   2223                     TABLE_NOISY(LOGI("Initialized new bag with %d inherited attributes.\n", NP));
   2224                 } else {
   2225                     TABLE_NOISY(LOGI("Initialized new bag with no inherited attributes.\n"));
   2226                     set->numAttrs = 0;
   2227                 }
   2228                 set->availAttrs = NT;
   2229                 set->typeSpecFlags = parentTypeSpecFlags;
   2230             } else {
   2231                 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*N);
   2232                 if (set == NULL) {
   2233                     return NO_MEMORY;
   2234                 }
   2235                 set->numAttrs = 0;
   2236                 set->availAttrs = N;
   2237                 set->typeSpecFlags = 0;
   2238             }
   2239         }
   2240 
   2241         if (typeClass->typeSpecFlags != NULL) {
   2242             set->typeSpecFlags |= dtohl(typeClass->typeSpecFlags[e]);
   2243         } else {
   2244             set->typeSpecFlags = -1;
   2245         }
   2246 
   2247         // Now merge in the new attributes...
   2248         ssize_t curOff = offset;
   2249         const ResTable_map* map;
   2250         bag_entry* entries = (bag_entry*)(set+1);
   2251         size_t curEntry = 0;
   2252         uint32_t pos = 0;
   2253         TABLE_NOISY(LOGI("Starting with set %p, entries=%p, avail=%d\n",
   2254                      set, entries, set->availAttrs));
   2255         while (pos < count) {
   2256             TABLE_NOISY(printf("Now at %p\n", (void*)curOff));
   2257 
   2258             if ((size_t)curOff > (dtohl(type->header.size)-sizeof(ResTable_map))) {
   2259                 LOGW("ResTable_map at %d is beyond type chunk data %d",
   2260                      (int)curOff, dtohl(type->header.size));
   2261                 return BAD_TYPE;
   2262             }
   2263             map = (const ResTable_map*)(((const uint8_t*)type) + curOff);
   2264             N++;
   2265 
   2266             const uint32_t newName = htodl(map->name.ident);
   2267             bool isInside;
   2268             uint32_t oldName = 0;
   2269             while ((isInside=(curEntry < set->numAttrs))
   2270                     && (oldName=entries[curEntry].map.name.ident) < newName) {
   2271                 TABLE_NOISY(printf("#%d: Keeping existing attribute: 0x%08x\n",
   2272                              curEntry, entries[curEntry].map.name.ident));
   2273                 curEntry++;
   2274             }
   2275 
   2276             if ((!isInside) || oldName != newName) {
   2277                 // This is a new attribute...  figure out what to do with it.
   2278                 if (set->numAttrs >= set->availAttrs) {
   2279                     // Need to alloc more memory...
   2280                     const size_t newAvail = set->availAttrs+N;
   2281                     set = (bag_set*)realloc(set,
   2282                                             sizeof(bag_set)
   2283                                             + sizeof(bag_entry)*newAvail);
   2284                     if (set == NULL) {
   2285                         return NO_MEMORY;
   2286                     }
   2287                     set->availAttrs = newAvail;
   2288                     entries = (bag_entry*)(set+1);
   2289                     TABLE_NOISY(printf("Reallocated set %p, entries=%p, avail=%d\n",
   2290                                  set, entries, set->availAttrs));
   2291                 }
   2292                 if (isInside) {
   2293                     // Going in the middle, need to make space.
   2294                     memmove(entries+curEntry+1, entries+curEntry,
   2295                             sizeof(bag_entry)*(set->numAttrs-curEntry));
   2296                     set->numAttrs++;
   2297                 }
   2298                 TABLE_NOISY(printf("#%d: Inserting new attribute: 0x%08x\n",
   2299                              curEntry, newName));
   2300             } else {
   2301                 TABLE_NOISY(printf("#%d: Replacing existing attribute: 0x%08x\n",
   2302                              curEntry, oldName));
   2303             }
   2304 
   2305             bag_entry* cur = entries+curEntry;
   2306 
   2307             cur->stringBlock = package->header->index;
   2308             cur->map.name.ident = newName;
   2309             cur->map.value.copyFrom_dtoh(map->value);
   2310             TABLE_NOISY(printf("Setting entry #%d %p: block=%d, name=0x%08x, type=%d, data=0x%08x\n",
   2311                          curEntry, cur, cur->stringBlock, cur->map.name.ident,
   2312                          cur->map.value.dataType, cur->map.value.data));
   2313 
   2314             // On to the next!
   2315             curEntry++;
   2316             pos++;
   2317             const size_t size = dtohs(map->value.size);
   2318             curOff += size + sizeof(*map)-sizeof(map->value);
   2319         };
   2320         if (curEntry > set->numAttrs) {
   2321             set->numAttrs = curEntry;
   2322         }
   2323     }
   2324 
   2325     // And this is it...
   2326     typeSet[e] = set;
   2327     if (set) {
   2328         if (outTypeSpecFlags != NULL) {
   2329             *outTypeSpecFlags = set->typeSpecFlags;
   2330         }
   2331         *outBag = (bag_entry*)(set+1);
   2332         TABLE_NOISY(LOGI("Returning %d attrs\n", set->numAttrs));
   2333         return set->numAttrs;
   2334     }
   2335     return BAD_INDEX;
   2336 }
   2337 
   2338 void ResTable::setParameters(const ResTable_config* params)
   2339 {
   2340     mLock.lock();
   2341     TABLE_GETENTRY(LOGI("Setting parameters: imsi:%d/%d lang:%c%c cnt:%c%c "
   2342                         "orien:%d touch:%d density:%d key:%d inp:%d nav:%d w:%d h:%d\n",
   2343                        params->mcc, params->mnc,
   2344                        params->language[0] ? params->language[0] : '-',
   2345                        params->language[1] ? params->language[1] : '-',
   2346                        params->country[0] ? params->country[0] : '-',
   2347                        params->country[1] ? params->country[1] : '-',
   2348                        params->orientation,
   2349                        params->touchscreen,
   2350                        params->density,
   2351                        params->keyboard,
   2352                        params->inputFlags,
   2353                        params->navigation,
   2354                        params->screenWidth,
   2355                        params->screenHeight));
   2356     mParams = *params;
   2357     for (size_t i=0; i<mPackageGroups.size(); i++) {
   2358         TABLE_NOISY(LOGI("CLEARING BAGS FOR GROUP %d!", i));
   2359         mPackageGroups[i]->clearBagCache();
   2360     }
   2361     mLock.unlock();
   2362 }
   2363 
   2364 void ResTable::getParameters(ResTable_config* params) const
   2365 {
   2366     mLock.lock();
   2367     *params = mParams;
   2368     mLock.unlock();
   2369 }
   2370 
   2371 struct id_name_map {
   2372     uint32_t id;
   2373     size_t len;
   2374     char16_t name[6];
   2375 };
   2376 
   2377 const static id_name_map ID_NAMES[] = {
   2378     { ResTable_map::ATTR_TYPE,  5, { '^', 't', 'y', 'p', 'e' } },
   2379     { ResTable_map::ATTR_L10N,  5, { '^', 'l', '1', '0', 'n' } },
   2380     { ResTable_map::ATTR_MIN,   4, { '^', 'm', 'i', 'n' } },
   2381     { ResTable_map::ATTR_MAX,   4, { '^', 'm', 'a', 'x' } },
   2382     { ResTable_map::ATTR_OTHER, 6, { '^', 'o', 't', 'h', 'e', 'r' } },
   2383     { ResTable_map::ATTR_ZERO,  5, { '^', 'z', 'e', 'r', 'o' } },
   2384     { ResTable_map::ATTR_ONE,   4, { '^', 'o', 'n', 'e' } },
   2385     { ResTable_map::ATTR_TWO,   4, { '^', 't', 'w', 'o' } },
   2386     { ResTable_map::ATTR_FEW,   4, { '^', 'f', 'e', 'w' } },
   2387     { ResTable_map::ATTR_MANY,  5, { '^', 'm', 'a', 'n', 'y' } },
   2388 };
   2389 
   2390 uint32_t ResTable::identifierForName(const char16_t* name, size_t nameLen,
   2391                                      const char16_t* type, size_t typeLen,
   2392                                      const char16_t* package,
   2393                                      size_t packageLen,
   2394                                      uint32_t* outTypeSpecFlags) const
   2395 {
   2396     TABLE_SUPER_NOISY(printf("Identifier for name: error=%d\n", mError));
   2397 
   2398     // Check for internal resource identifier as the very first thing, so
   2399     // that we will always find them even when there are no resources.
   2400     if (name[0] == '^') {
   2401         const int N = (sizeof(ID_NAMES)/sizeof(ID_NAMES[0]));
   2402         size_t len;
   2403         for (int i=0; i<N; i++) {
   2404             const id_name_map* m = ID_NAMES + i;
   2405             len = m->len;
   2406             if (len != nameLen) {
   2407                 continue;
   2408             }
   2409             for (size_t j=1; j<len; j++) {
   2410                 if (m->name[j] != name[j]) {
   2411                     goto nope;
   2412                 }
   2413             }
   2414             return m->id;
   2415 nope:
   2416             ;
   2417         }
   2418         if (nameLen > 7) {
   2419             if (name[1] == 'i' && name[2] == 'n'
   2420                 && name[3] == 'd' && name[4] == 'e' && name[5] == 'x'
   2421                 && name[6] == '_') {
   2422                 int index = atoi(String8(name + 7, nameLen - 7).string());
   2423                 if (Res_CHECKID(index)) {
   2424                     LOGW("Array resource index: %d is too large.",
   2425                          index);
   2426                     return 0;
   2427                 }
   2428                 return  Res_MAKEARRAY(index);
   2429             }
   2430         }
   2431         return 0;
   2432     }
   2433 
   2434     if (mError != NO_ERROR) {
   2435         return 0;
   2436     }
   2437 
   2438     // Figure out the package and type we are looking in...
   2439 
   2440     const char16_t* packageEnd = NULL;
   2441     const char16_t* typeEnd = NULL;
   2442     const char16_t* const nameEnd = name+nameLen;
   2443     const char16_t* p = name;
   2444     while (p < nameEnd) {
   2445         if (*p == ':') packageEnd = p;
   2446         else if (*p == '/') typeEnd = p;
   2447         p++;
   2448     }
   2449     if (*name == '@') name++;
   2450     if (name >= nameEnd) {
   2451         return 0;
   2452     }
   2453 
   2454     if (packageEnd) {
   2455         package = name;
   2456         packageLen = packageEnd-name;
   2457         name = packageEnd+1;
   2458     } else if (!package) {
   2459         return 0;
   2460     }
   2461 
   2462     if (typeEnd) {
   2463         type = name;
   2464         typeLen = typeEnd-name;
   2465         name = typeEnd+1;
   2466     } else if (!type) {
   2467         return 0;
   2468     }
   2469 
   2470     if (name >= nameEnd) {
   2471         return 0;
   2472     }
   2473     nameLen = nameEnd-name;
   2474 
   2475     TABLE_NOISY(printf("Looking for identifier: type=%s, name=%s, package=%s\n",
   2476                  String8(type, typeLen).string(),
   2477                  String8(name, nameLen).string(),
   2478                  String8(package, packageLen).string()));
   2479 
   2480     const size_t NG = mPackageGroups.size();
   2481     for (size_t ig=0; ig<NG; ig++) {
   2482         const PackageGroup* group = mPackageGroups[ig];
   2483 
   2484         if (strzcmp16(package, packageLen,
   2485                       group->name.string(), group->name.size())) {
   2486             TABLE_NOISY(printf("Skipping package group: %s\n", String8(group->name).string()));
   2487             continue;
   2488         }
   2489 
   2490         const ssize_t ti = group->basePackage->typeStrings.indexOfString(type, typeLen);
   2491         if (ti < 0) {
   2492             TABLE_NOISY(printf("Type not found in package %s\n", String8(group->name).string()));
   2493             continue;
   2494         }
   2495 
   2496         const ssize_t ei = group->basePackage->keyStrings.indexOfString(name, nameLen);
   2497         if (ei < 0) {
   2498             TABLE_NOISY(printf("Name not found in package %s\n", String8(group->name).string()));
   2499             continue;
   2500         }
   2501 
   2502         TABLE_NOISY(printf("Search indices: type=%d, name=%d\n", ti, ei));
   2503 
   2504         const Type* const typeConfigs = group->packages[0]->getType(ti);
   2505         if (typeConfigs == NULL || typeConfigs->configs.size() <= 0) {
   2506             TABLE_NOISY(printf("Expected type structure not found in package %s for idnex %d\n",
   2507                                String8(group->name).string(), ti));
   2508         }
   2509 
   2510         size_t NTC = typeConfigs->configs.size();
   2511         for (size_t tci=0; tci<NTC; tci++) {
   2512             const ResTable_type* const ty = typeConfigs->configs[tci];
   2513             const uint32_t typeOffset = dtohl(ty->entriesStart);
   2514 
   2515             const uint8_t* const end = ((const uint8_t*)ty) + dtohl(ty->header.size);
   2516             const uint32_t* const eindex = (const uint32_t*)
   2517                 (((const uint8_t*)ty) + dtohs(ty->header.headerSize));
   2518 
   2519             const size_t NE = dtohl(ty->entryCount);
   2520             for (size_t i=0; i<NE; i++) {
   2521                 uint32_t offset = dtohl(eindex[i]);
   2522                 if (offset == ResTable_type::NO_ENTRY) {
   2523                     continue;
   2524                 }
   2525 
   2526                 offset += typeOffset;
   2527 
   2528                 if (offset > (dtohl(ty->header.size)-sizeof(ResTable_entry))) {
   2529                     LOGW("ResTable_entry at %d is beyond type chunk data %d",
   2530                          offset, dtohl(ty->header.size));
   2531                     return 0;
   2532                 }
   2533                 if ((offset&0x3) != 0) {
   2534                     LOGW("ResTable_entry at %d (pkg=%d type=%d ent=%d) is not on an integer boundary when looking for %s:%s/%s",
   2535                          (int)offset, (int)group->id, (int)ti+1, (int)i,
   2536                          String8(package, packageLen).string(),
   2537                          String8(type, typeLen).string(),
   2538                          String8(name, nameLen).string());
   2539                     return 0;
   2540                 }
   2541 
   2542                 const ResTable_entry* const entry = (const ResTable_entry*)
   2543                     (((const uint8_t*)ty) + offset);
   2544                 if (dtohs(entry->size) < sizeof(*entry)) {
   2545                     LOGW("ResTable_entry size %d is too small", dtohs(entry->size));
   2546                     return BAD_TYPE;
   2547                 }
   2548 
   2549                 TABLE_SUPER_NOISY(printf("Looking at entry #%d: want str %d, have %d\n",
   2550                                          i, ei, dtohl(entry->key.index)));
   2551                 if (dtohl(entry->key.index) == (size_t)ei) {
   2552                     if (outTypeSpecFlags) {
   2553                         *outTypeSpecFlags = typeConfigs->typeSpecFlags[i];
   2554                     }
   2555                     return Res_MAKEID(group->id-1, ti, i);
   2556                 }
   2557             }
   2558         }
   2559     }
   2560 
   2561     return 0;
   2562 }
   2563 
   2564 bool ResTable::expandResourceRef(const uint16_t* refStr, size_t refLen,
   2565                                  String16* outPackage,
   2566                                  String16* outType,
   2567                                  String16* outName,
   2568                                  const String16* defType,
   2569                                  const String16* defPackage,
   2570                                  const char** outErrorMsg)
   2571 {
   2572     const char16_t* packageEnd = NULL;
   2573     const char16_t* typeEnd = NULL;
   2574     const char16_t* p = refStr;
   2575     const char16_t* const end = p + refLen;
   2576     while (p < end) {
   2577         if (*p == ':') packageEnd = p;
   2578         else if (*p == '/') {
   2579             typeEnd = p;
   2580             break;
   2581         }
   2582         p++;
   2583     }
   2584     p = refStr;
   2585     if (*p == '@') p++;
   2586 
   2587     if (packageEnd) {
   2588         *outPackage = String16(p, packageEnd-p);
   2589         p = packageEnd+1;
   2590     } else {
   2591         if (!defPackage) {
   2592             if (outErrorMsg) {
   2593                 *outErrorMsg = "No resource package specified";
   2594             }
   2595             return false;
   2596         }
   2597         *outPackage = *defPackage;
   2598     }
   2599     if (typeEnd) {
   2600         *outType = String16(p, typeEnd-p);
   2601         p = typeEnd+1;
   2602     } else {
   2603         if (!defType) {
   2604             if (outErrorMsg) {
   2605                 *outErrorMsg = "No resource type specified";
   2606             }
   2607             return false;
   2608         }
   2609         *outType = *defType;
   2610     }
   2611     *outName = String16(p, end-p);
   2612     return true;
   2613 }
   2614 
   2615 static uint32_t get_hex(char c, bool* outError)
   2616 {
   2617     if (c >= '0' && c <= '9') {
   2618         return c - '0';
   2619     } else if (c >= 'a' && c <= 'f') {
   2620         return c - 'a' + 0xa;
   2621     } else if (c >= 'A' && c <= 'F') {
   2622         return c - 'A' + 0xa;
   2623     }
   2624     *outError = true;
   2625     return 0;
   2626 }
   2627 
   2628 struct unit_entry
   2629 {
   2630     const char* name;
   2631     size_t len;
   2632     uint8_t type;
   2633     uint32_t unit;
   2634     float scale;
   2635 };
   2636 
   2637 static const unit_entry unitNames[] = {
   2638     { "px", strlen("px"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PX, 1.0f },
   2639     { "dip", strlen("dip"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
   2640     { "dp", strlen("dp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
   2641     { "sp", strlen("sp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_SP, 1.0f },
   2642     { "pt", strlen("pt"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PT, 1.0f },
   2643     { "in", strlen("in"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_IN, 1.0f },
   2644     { "mm", strlen("mm"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_MM, 1.0f },
   2645     { "%", strlen("%"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION, 1.0f/100 },
   2646     { "%p", strlen("%p"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION_PARENT, 1.0f/100 },
   2647     { NULL, 0, 0, 0, 0 }
   2648 };
   2649 
   2650 static bool parse_unit(const char* str, Res_value* outValue,
   2651                        float* outScale, const char** outEnd)
   2652 {
   2653     const char* end = str;
   2654     while (*end != 0 && !isspace((unsigned char)*end)) {
   2655         end++;
   2656     }
   2657     const size_t len = end-str;
   2658 
   2659     const char* realEnd = end;
   2660     while (*realEnd != 0 && isspace((unsigned char)*realEnd)) {
   2661         realEnd++;
   2662     }
   2663     if (*realEnd != 0) {
   2664         return false;
   2665     }
   2666 
   2667     const unit_entry* cur = unitNames;
   2668     while (cur->name) {
   2669         if (len == cur->len && strncmp(cur->name, str, len) == 0) {
   2670             outValue->dataType = cur->type;
   2671             outValue->data = cur->unit << Res_value::COMPLEX_UNIT_SHIFT;
   2672             *outScale = cur->scale;
   2673             *outEnd = end;
   2674             //printf("Found unit %s for %s\n", cur->name, str);
   2675             return true;
   2676         }
   2677         cur++;
   2678     }
   2679 
   2680     return false;
   2681 }
   2682 
   2683 
   2684 bool ResTable::stringToInt(const char16_t* s, size_t len, Res_value* outValue)
   2685 {
   2686     while (len > 0 && isspace16(*s)) {
   2687         s++;
   2688         len--;
   2689     }
   2690 
   2691     if (len <= 0) {
   2692         return false;
   2693     }
   2694 
   2695     size_t i = 0;
   2696     int32_t val = 0;
   2697     bool neg = false;
   2698 
   2699     if (*s == '-') {
   2700         neg = true;
   2701         i++;
   2702     }
   2703 
   2704     if (s[i] < '0' || s[i] > '9') {
   2705         return false;
   2706     }
   2707 
   2708     // Decimal or hex?
   2709     if (s[i] == '0' && s[i+1] == 'x') {
   2710         if (outValue)
   2711             outValue->dataType = outValue->TYPE_INT_HEX;
   2712         i += 2;
   2713         bool error = false;
   2714         while (i < len && !error) {
   2715             val = (val*16) + get_hex(s[i], &error);
   2716             i++;
   2717         }
   2718         if (error) {
   2719             return false;
   2720         }
   2721     } else {
   2722         if (outValue)
   2723             outValue->dataType = outValue->TYPE_INT_DEC;
   2724         while (i < len) {
   2725             if (s[i] < '0' || s[i] > '9') {
   2726                 return false;
   2727             }
   2728             val = (val*10) + s[i]-'0';
   2729             i++;
   2730         }
   2731     }
   2732 
   2733     if (neg) val = -val;
   2734 
   2735     while (i < len && isspace16(s[i])) {
   2736         i++;
   2737     }
   2738 
   2739     if (i == len) {
   2740         if (outValue)
   2741             outValue->data = val;
   2742         return true;
   2743     }
   2744 
   2745     return false;
   2746 }
   2747 
   2748 bool ResTable::stringToFloat(const char16_t* s, size_t len, Res_value* outValue)
   2749 {
   2750     while (len > 0 && isspace16(*s)) {
   2751         s++;
   2752         len--;
   2753     }
   2754 
   2755     if (len <= 0) {
   2756         return false;
   2757     }
   2758 
   2759     char buf[128];
   2760     int i=0;
   2761     while (len > 0 && *s != 0 && i < 126) {
   2762         if (*s > 255) {
   2763             return false;
   2764         }
   2765         buf[i++] = *s++;
   2766         len--;
   2767     }
   2768 
   2769     if (len > 0) {
   2770         return false;
   2771     }
   2772     if (buf[0] < '0' && buf[0] > '9' && buf[0] != '.') {
   2773         return false;
   2774     }
   2775 
   2776     buf[i] = 0;
   2777     const char* end;
   2778     float f = strtof(buf, (char**)&end);
   2779 
   2780     if (*end != 0 && !isspace((unsigned char)*end)) {
   2781         // Might be a unit...
   2782         float scale;
   2783         if (parse_unit(end, outValue, &scale, &end)) {
   2784             f *= scale;
   2785             const bool neg = f < 0;
   2786             if (neg) f = -f;
   2787             uint64_t bits = (uint64_t)(f*(1<<23)+.5f);
   2788             uint32_t radix;
   2789             uint32_t shift;
   2790             if ((bits&0x7fffff) == 0) {
   2791                 // Always use 23p0 if there is no fraction, just to make
   2792                 // things easier to read.
   2793                 radix = Res_value::COMPLEX_RADIX_23p0;
   2794                 shift = 23;
   2795             } else if ((bits&0xffffffffff800000LL) == 0) {
   2796                 // Magnitude is zero -- can fit in 0 bits of precision.
   2797                 radix = Res_value::COMPLEX_RADIX_0p23;
   2798                 shift = 0;
   2799             } else if ((bits&0xffffffff80000000LL) == 0) {
   2800                 // Magnitude can fit in 8 bits of precision.
   2801                 radix = Res_value::COMPLEX_RADIX_8p15;
   2802                 shift = 8;
   2803             } else if ((bits&0xffffff8000000000LL) == 0) {
   2804                 // Magnitude can fit in 16 bits of precision.
   2805                 radix = Res_value::COMPLEX_RADIX_16p7;
   2806                 shift = 16;
   2807             } else {
   2808                 // Magnitude needs entire range, so no fractional part.
   2809                 radix = Res_value::COMPLEX_RADIX_23p0;
   2810                 shift = 23;
   2811             }
   2812             int32_t mantissa = (int32_t)(
   2813                 (bits>>shift) & Res_value::COMPLEX_MANTISSA_MASK);
   2814             if (neg) {
   2815                 mantissa = (-mantissa) & Res_value::COMPLEX_MANTISSA_MASK;
   2816             }
   2817             outValue->data |=
   2818                 (radix<<Res_value::COMPLEX_RADIX_SHIFT)
   2819                 | (mantissa<<Res_value::COMPLEX_MANTISSA_SHIFT);
   2820             //printf("Input value: %f 0x%016Lx, mult: %f, radix: %d, shift: %d, final: 0x%08x\n",
   2821             //       f * (neg ? -1 : 1), bits, f*(1<<23),
   2822             //       radix, shift, outValue->data);
   2823             return true;
   2824         }
   2825         return false;
   2826     }
   2827 
   2828     while (*end != 0 && isspace((unsigned char)*end)) {
   2829         end++;
   2830     }
   2831 
   2832     if (*end == 0) {
   2833         if (outValue) {
   2834             outValue->dataType = outValue->TYPE_FLOAT;
   2835             *(float*)(&outValue->data) = f;
   2836             return true;
   2837         }
   2838     }
   2839 
   2840     return false;
   2841 }
   2842 
   2843 bool ResTable::stringToValue(Res_value* outValue, String16* outString,
   2844                              const char16_t* s, size_t len,
   2845                              bool preserveSpaces, bool coerceType,
   2846                              uint32_t attrID,
   2847                              const String16* defType,
   2848                              const String16* defPackage,
   2849                              Accessor* accessor,
   2850                              void* accessorCookie,
   2851                              uint32_t attrType,
   2852                              bool enforcePrivate) const
   2853 {
   2854     bool localizationSetting = accessor != NULL && accessor->getLocalizationSetting();
   2855     const char* errorMsg = NULL;
   2856 
   2857     outValue->size = sizeof(Res_value);
   2858     outValue->res0 = 0;
   2859 
   2860     // First strip leading/trailing whitespace.  Do this before handling
   2861     // escapes, so they can be used to force whitespace into the string.
   2862     if (!preserveSpaces) {
   2863         while (len > 0 && isspace16(*s)) {
   2864             s++;
   2865             len--;
   2866         }
   2867         while (len > 0 && isspace16(s[len-1])) {
   2868             len--;
   2869         }
   2870         // If the string ends with '\', then we keep the space after it.
   2871         if (len > 0 && s[len-1] == '\\' && s[len] != 0) {
   2872             len++;
   2873         }
   2874     }
   2875 
   2876     //printf("Value for: %s\n", String8(s, len).string());
   2877 
   2878     uint32_t l10nReq = ResTable_map::L10N_NOT_REQUIRED;
   2879     uint32_t attrMin = 0x80000000, attrMax = 0x7fffffff;
   2880     bool fromAccessor = false;
   2881     if (attrID != 0 && !Res_INTERNALID(attrID)) {
   2882         const ssize_t p = getResourcePackageIndex(attrID);
   2883         const bag_entry* bag;
   2884         ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
   2885         //printf("For attr 0x%08x got bag of %d\n", attrID, cnt);
   2886         if (cnt >= 0) {
   2887             while (cnt > 0) {
   2888                 //printf("Entry 0x%08x = 0x%08x\n", bag->map.name.ident, bag->map.value.data);
   2889                 switch (bag->map.name.ident) {
   2890                 case ResTable_map::ATTR_TYPE:
   2891                     attrType = bag->map.value.data;
   2892                     break;
   2893                 case ResTable_map::ATTR_MIN:
   2894                     attrMin = bag->map.value.data;
   2895                     break;
   2896                 case ResTable_map::ATTR_MAX:
   2897                     attrMax = bag->map.value.data;
   2898                     break;
   2899                 case ResTable_map::ATTR_L10N:
   2900                     l10nReq = bag->map.value.data;
   2901                     break;
   2902                 }
   2903                 bag++;
   2904                 cnt--;
   2905             }
   2906             unlockBag(bag);
   2907         } else if (accessor && accessor->getAttributeType(attrID, &attrType)) {
   2908             fromAccessor = true;
   2909             if (attrType == ResTable_map::TYPE_ENUM
   2910                     || attrType == ResTable_map::TYPE_FLAGS
   2911                     || attrType == ResTable_map::TYPE_INTEGER) {
   2912                 accessor->getAttributeMin(attrID, &attrMin);
   2913                 accessor->getAttributeMax(attrID, &attrMax);
   2914             }
   2915             if (localizationSetting) {
   2916                 l10nReq = accessor->getAttributeL10N(attrID);
   2917             }
   2918         }
   2919     }
   2920 
   2921     const bool canStringCoerce =
   2922         coerceType && (attrType&ResTable_map::TYPE_STRING) != 0;
   2923 
   2924     if (*s == '@') {
   2925         outValue->dataType = outValue->TYPE_REFERENCE;
   2926 
   2927         // Note: we don't check attrType here because the reference can
   2928         // be to any other type; we just need to count on the client making
   2929         // sure the referenced type is correct.
   2930 
   2931         //printf("Looking up ref: %s\n", String8(s, len).string());
   2932 
   2933         // It's a reference!
   2934         if (len == 5 && s[1]=='n' && s[2]=='u' && s[3]=='l' && s[4]=='l') {
   2935             outValue->data = 0;
   2936             return true;
   2937         } else {
   2938             bool createIfNotFound = false;
   2939             const char16_t* resourceRefName;
   2940             int resourceNameLen;
   2941             if (len > 2 && s[1] == '+') {
   2942                 createIfNotFound = true;
   2943                 resourceRefName = s + 2;
   2944                 resourceNameLen = len - 2;
   2945             } else if (len > 2 && s[1] == '*') {
   2946                 enforcePrivate = false;
   2947                 resourceRefName = s + 2;
   2948                 resourceNameLen = len - 2;
   2949             } else {
   2950                 createIfNotFound = false;
   2951                 resourceRefName = s + 1;
   2952                 resourceNameLen = len - 1;
   2953             }
   2954             String16 package, type, name;
   2955             if (!expandResourceRef(resourceRefName,resourceNameLen, &package, &type, &name,
   2956                                    defType, defPackage, &errorMsg)) {
   2957                 if (accessor != NULL) {
   2958                     accessor->reportError(accessorCookie, errorMsg);
   2959                 }
   2960                 return false;
   2961             }
   2962 
   2963             uint32_t specFlags = 0;
   2964             uint32_t rid = identifierForName(name.string(), name.size(), type.string(),
   2965                     type.size(), package.string(), package.size(), &specFlags);
   2966             if (rid != 0) {
   2967                 if (enforcePrivate) {
   2968                     if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
   2969                         if (accessor != NULL) {
   2970                             accessor->reportError(accessorCookie, "Resource is not public.");
   2971                         }
   2972                         return false;
   2973                     }
   2974                 }
   2975                 if (!accessor) {
   2976                     outValue->data = rid;
   2977                     return true;
   2978                 }
   2979                 rid = Res_MAKEID(
   2980                     accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
   2981                     Res_GETTYPE(rid), Res_GETENTRY(rid));
   2982                 TABLE_NOISY(printf("Incl %s:%s/%s: 0x%08x\n",
   2983                        String8(package).string(), String8(type).string(),
   2984                        String8(name).string(), rid));
   2985                 outValue->data = rid;
   2986                 return true;
   2987             }
   2988 
   2989             if (accessor) {
   2990                 uint32_t rid = accessor->getCustomResourceWithCreation(package, type, name,
   2991                                                                        createIfNotFound);
   2992                 if (rid != 0) {
   2993                     TABLE_NOISY(printf("Pckg %s:%s/%s: 0x%08x\n",
   2994                            String8(package).string(), String8(type).string(),
   2995                            String8(name).string(), rid));
   2996                     outValue->data = rid;
   2997                     return true;
   2998                 }
   2999             }
   3000         }
   3001 
   3002         if (accessor != NULL) {
   3003             accessor->reportError(accessorCookie, "No resource found that matches the given name");
   3004         }
   3005         return false;
   3006     }
   3007 
   3008     // if we got to here, and localization is required and it's not a reference,
   3009     // complain and bail.
   3010     if (l10nReq == ResTable_map::L10N_SUGGESTED) {
   3011         if (localizationSetting) {
   3012             if (accessor != NULL) {
   3013                 accessor->reportError(accessorCookie, "This attribute must be localized.");
   3014             }
   3015         }
   3016     }
   3017 
   3018     if (*s == '#') {
   3019         // It's a color!  Convert to an integer of the form 0xaarrggbb.
   3020         uint32_t color = 0;
   3021         bool error = false;
   3022         if (len == 4) {
   3023             outValue->dataType = outValue->TYPE_INT_COLOR_RGB4;
   3024             color |= 0xFF000000;
   3025             color |= get_hex(s[1], &error) << 20;
   3026             color |= get_hex(s[1], &error) << 16;
   3027             color |= get_hex(s[2], &error) << 12;
   3028             color |= get_hex(s[2], &error) << 8;
   3029             color |= get_hex(s[3], &error) << 4;
   3030             color |= get_hex(s[3], &error);
   3031         } else if (len == 5) {
   3032             outValue->dataType = outValue->TYPE_INT_COLOR_ARGB4;
   3033             color |= get_hex(s[1], &error) << 28;
   3034             color |= get_hex(s[1], &error) << 24;
   3035             color |= get_hex(s[2], &error) << 20;
   3036             color |= get_hex(s[2], &error) << 16;
   3037             color |= get_hex(s[3], &error) << 12;
   3038             color |= get_hex(s[3], &error) << 8;
   3039             color |= get_hex(s[4], &error) << 4;
   3040             color |= get_hex(s[4], &error);
   3041         } else if (len == 7) {
   3042             outValue->dataType = outValue->TYPE_INT_COLOR_RGB8;
   3043             color |= 0xFF000000;
   3044             color |= get_hex(s[1], &error) << 20;
   3045             color |= get_hex(s[2], &error) << 16;
   3046             color |= get_hex(s[3], &error) << 12;
   3047             color |= get_hex(s[4], &error) << 8;
   3048             color |= get_hex(s[5], &error) << 4;
   3049             color |= get_hex(s[6], &error);
   3050         } else if (len == 9) {
   3051             outValue->dataType = outValue->TYPE_INT_COLOR_ARGB8;
   3052             color |= get_hex(s[1], &error) << 28;
   3053             color |= get_hex(s[2], &error) << 24;
   3054             color |= get_hex(s[3], &error) << 20;
   3055             color |= get_hex(s[4], &error) << 16;
   3056             color |= get_hex(s[5], &error) << 12;
   3057             color |= get_hex(s[6], &error) << 8;
   3058             color |= get_hex(s[7], &error) << 4;
   3059             color |= get_hex(s[8], &error);
   3060         } else {
   3061             error = true;
   3062         }
   3063         if (!error) {
   3064             if ((attrType&ResTable_map::TYPE_COLOR) == 0) {
   3065                 if (!canStringCoerce) {
   3066                     if (accessor != NULL) {
   3067                         accessor->reportError(accessorCookie,
   3068                                 "Color types not allowed");
   3069                     }
   3070                     return false;
   3071                 }
   3072             } else {
   3073                 outValue->data = color;
   3074                 //printf("Color input=%s, output=0x%x\n", String8(s, len).string(), color);
   3075                 return true;
   3076             }
   3077         } else {
   3078             if ((attrType&ResTable_map::TYPE_COLOR) != 0) {
   3079                 if (accessor != NULL) {
   3080                     accessor->reportError(accessorCookie, "Color value not valid --"
   3081                             " must be #rgb, #argb, #rrggbb, or #aarrggbb");
   3082                 }
   3083                 #if 0
   3084                 fprintf(stderr, "%s: Color ID %s value %s is not valid\n",
   3085                         "Resource File", //(const char*)in->getPrintableSource(),
   3086                         String8(*curTag).string(),
   3087                         String8(s, len).string());
   3088                 #endif
   3089                 return false;
   3090             }
   3091         }
   3092     }
   3093 
   3094     if (*s == '?') {
   3095         outValue->dataType = outValue->TYPE_ATTRIBUTE;
   3096 
   3097         // Note: we don't check attrType here because the reference can
   3098         // be to any other type; we just need to count on the client making
   3099         // sure the referenced type is correct.
   3100 
   3101         //printf("Looking up attr: %s\n", String8(s, len).string());
   3102 
   3103         static const String16 attr16("attr");
   3104         String16 package, type, name;
   3105         if (!expandResourceRef(s+1, len-1, &package, &type, &name,
   3106                                &attr16, defPackage, &errorMsg)) {
   3107             if (accessor != NULL) {
   3108                 accessor->reportError(accessorCookie, errorMsg);
   3109             }
   3110             return false;
   3111         }
   3112 
   3113         //printf("Pkg: %s, Type: %s, Name: %s\n",
   3114         //       String8(package).string(), String8(type).string(),
   3115         //       String8(name).string());
   3116         uint32_t specFlags = 0;
   3117         uint32_t rid =
   3118             identifierForName(name.string(), name.size(),
   3119                               type.string(), type.size(),
   3120                               package.string(), package.size(), &specFlags);
   3121         if (rid != 0) {
   3122             if (enforcePrivate) {
   3123                 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
   3124                     if (accessor != NULL) {
   3125                         accessor->reportError(accessorCookie, "Attribute is not public.");
   3126                     }
   3127                     return false;
   3128                 }
   3129             }
   3130             if (!accessor) {
   3131                 outValue->data = rid;
   3132                 return true;
   3133             }
   3134             rid = Res_MAKEID(
   3135                 accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
   3136                 Res_GETTYPE(rid), Res_GETENTRY(rid));
   3137             //printf("Incl %s:%s/%s: 0x%08x\n",
   3138             //       String8(package).string(), String8(type).string(),
   3139             //       String8(name).string(), rid);
   3140             outValue->data = rid;
   3141             return true;
   3142         }
   3143 
   3144         if (accessor) {
   3145             uint32_t rid = accessor->getCustomResource(package, type, name);
   3146             if (rid != 0) {
   3147                 //printf("Mine %s:%s/%s: 0x%08x\n",
   3148                 //       String8(package).string(), String8(type).string(),
   3149                 //       String8(name).string(), rid);
   3150                 outValue->data = rid;
   3151                 return true;
   3152             }
   3153         }
   3154 
   3155         if (accessor != NULL) {
   3156             accessor->reportError(accessorCookie, "No resource found that matches the given name");
   3157         }
   3158         return false;
   3159     }
   3160 
   3161     if (stringToInt(s, len, outValue)) {
   3162         if ((attrType&ResTable_map::TYPE_INTEGER) == 0) {
   3163             // If this type does not allow integers, but does allow floats,
   3164             // fall through on this error case because the float type should
   3165             // be able to accept any integer value.
   3166             if (!canStringCoerce && (attrType&ResTable_map::TYPE_FLOAT) == 0) {
   3167                 if (accessor != NULL) {
   3168                     accessor->reportError(accessorCookie, "Integer types not allowed");
   3169                 }
   3170                 return false;
   3171             }
   3172         } else {
   3173             if (((int32_t)outValue->data) < ((int32_t)attrMin)
   3174                     || ((int32_t)outValue->data) > ((int32_t)attrMax)) {
   3175                 if (accessor != NULL) {
   3176                     accessor->reportError(accessorCookie, "Integer value out of range");
   3177                 }
   3178                 return false;
   3179             }
   3180             return true;
   3181         }
   3182     }
   3183 
   3184     if (stringToFloat(s, len, outValue)) {
   3185         if (outValue->dataType == Res_value::TYPE_DIMENSION) {
   3186             if ((attrType&ResTable_map::TYPE_DIMENSION) != 0) {
   3187                 return true;
   3188             }
   3189             if (!canStringCoerce) {
   3190                 if (accessor != NULL) {
   3191                     accessor->reportError(accessorCookie, "Dimension types not allowed");
   3192                 }
   3193                 return false;
   3194             }
   3195         } else if (outValue->dataType == Res_value::TYPE_FRACTION) {
   3196             if ((attrType&ResTable_map::TYPE_FRACTION) != 0) {
   3197                 return true;
   3198             }
   3199             if (!canStringCoerce) {
   3200                 if (accessor != NULL) {
   3201                     accessor->reportError(accessorCookie, "Fraction types not allowed");
   3202                 }
   3203                 return false;
   3204             }
   3205         } else if ((attrType&ResTable_map::TYPE_FLOAT) == 0) {
   3206             if (!canStringCoerce) {
   3207                 if (accessor != NULL) {
   3208                     accessor->reportError(accessorCookie, "Float types not allowed");
   3209                 }
   3210                 return false;
   3211             }
   3212         } else {
   3213             return true;
   3214         }
   3215     }
   3216 
   3217     if (len == 4) {
   3218         if ((s[0] == 't' || s[0] == 'T') &&
   3219             (s[1] == 'r' || s[1] == 'R') &&
   3220             (s[2] == 'u' || s[2] == 'U') &&
   3221             (s[3] == 'e' || s[3] == 'E')) {
   3222             if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
   3223                 if (!canStringCoerce) {
   3224                     if (accessor != NULL) {
   3225                         accessor->reportError(accessorCookie, "Boolean types not allowed");
   3226                     }
   3227                     return false;
   3228                 }
   3229             } else {
   3230                 outValue->dataType = outValue->TYPE_INT_BOOLEAN;
   3231                 outValue->data = (uint32_t)-1;
   3232                 return true;
   3233             }
   3234         }
   3235     }
   3236 
   3237     if (len == 5) {
   3238         if ((s[0] == 'f' || s[0] == 'F') &&
   3239             (s[1] == 'a' || s[1] == 'A') &&
   3240             (s[2] == 'l' || s[2] == 'L') &&
   3241             (s[3] == 's' || s[3] == 'S') &&
   3242             (s[4] == 'e' || s[4] == 'E')) {
   3243             if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
   3244                 if (!canStringCoerce) {
   3245                     if (accessor != NULL) {
   3246                         accessor->reportError(accessorCookie, "Boolean types not allowed");
   3247                     }
   3248                     return false;
   3249                 }
   3250             } else {
   3251                 outValue->dataType = outValue->TYPE_INT_BOOLEAN;
   3252                 outValue->data = 0;
   3253                 return true;
   3254             }
   3255         }
   3256     }
   3257 
   3258     if ((attrType&ResTable_map::TYPE_ENUM) != 0) {
   3259         const ssize_t p = getResourcePackageIndex(attrID);
   3260         const bag_entry* bag;
   3261         ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
   3262         //printf("Got %d for enum\n", cnt);
   3263         if (cnt >= 0) {
   3264             resource_name rname;
   3265             while (cnt > 0) {
   3266                 if (!Res_INTERNALID(bag->map.name.ident)) {
   3267                     //printf("Trying attr #%08x\n", bag->map.name.ident);
   3268                     if (getResourceName(bag->map.name.ident, &rname)) {
   3269                         #if 0
   3270                         printf("Matching %s against %s (0x%08x)\n",
   3271                                String8(s, len).string(),
   3272                                String8(rname.name, rname.nameLen).string(),
   3273                                bag->map.name.ident);
   3274                         #endif
   3275                         if (strzcmp16(s, len, rname.name, rname.nameLen) == 0) {
   3276                             outValue->dataType = bag->map.value.dataType;
   3277                             outValue->data = bag->map.value.data;
   3278                             unlockBag(bag);
   3279                             return true;
   3280                         }
   3281                     }
   3282 
   3283                 }
   3284                 bag++;
   3285                 cnt--;
   3286             }
   3287             unlockBag(bag);
   3288         }
   3289 
   3290         if (fromAccessor) {
   3291             if (accessor->getAttributeEnum(attrID, s, len, outValue)) {
   3292                 return true;
   3293             }
   3294         }
   3295     }
   3296 
   3297     if ((attrType&ResTable_map::TYPE_FLAGS) != 0) {
   3298         const ssize_t p = getResourcePackageIndex(attrID);
   3299         const bag_entry* bag;
   3300         ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
   3301         //printf("Got %d for flags\n", cnt);
   3302         if (cnt >= 0) {
   3303             bool failed = false;
   3304             resource_name rname;
   3305             outValue->dataType = Res_value::TYPE_INT_HEX;
   3306             outValue->data = 0;
   3307             const char16_t* end = s + len;
   3308             const char16_t* pos = s;
   3309             while (pos < end && !failed) {
   3310                 const char16_t* start = pos;
   3311                 pos++;
   3312                 while (pos < end && *pos != '|') {
   3313                     pos++;
   3314                 }
   3315                 //printf("Looking for: %s\n", String8(start, pos-start).string());
   3316                 const bag_entry* bagi = bag;
   3317                 ssize_t i;
   3318                 for (i=0; i<cnt; i++, bagi++) {
   3319                     if (!Res_INTERNALID(bagi->map.name.ident)) {
   3320                         //printf("Trying attr #%08x\n", bagi->map.name.ident);
   3321                         if (getResourceName(bagi->map.name.ident, &rname)) {
   3322                             #if 0
   3323                             printf("Matching %s against %s (0x%08x)\n",
   3324                                    String8(start,pos-start).string(),
   3325                                    String8(rname.name, rname.nameLen).string(),
   3326                                    bagi->map.name.ident);
   3327                             #endif
   3328                             if (strzcmp16(start, pos-start, rname.name, rname.nameLen) == 0) {
   3329                                 outValue->data |= bagi->map.value.data;
   3330                                 break;
   3331                             }
   3332                         }
   3333                     }
   3334                 }
   3335                 if (i >= cnt) {
   3336                     // Didn't find this flag identifier.
   3337                     failed = true;
   3338                 }
   3339                 if (pos < end) {
   3340                     pos++;
   3341                 }
   3342             }
   3343             unlockBag(bag);
   3344             if (!failed) {
   3345                 //printf("Final flag value: 0x%lx\n", outValue->data);
   3346                 return true;
   3347             }
   3348         }
   3349 
   3350 
   3351         if (fromAccessor) {
   3352             if (accessor->getAttributeFlags(attrID, s, len, outValue)) {
   3353                 //printf("Final flag value: 0x%lx\n", outValue->data);
   3354                 return true;
   3355             }
   3356         }
   3357     }
   3358 
   3359     if ((attrType&ResTable_map::TYPE_STRING) == 0) {
   3360         if (accessor != NULL) {
   3361             accessor->reportError(accessorCookie, "String types not allowed");
   3362         }
   3363         return false;
   3364     }
   3365 
   3366     // Generic string handling...
   3367     outValue->dataType = outValue->TYPE_STRING;
   3368     if (outString) {
   3369         bool failed = collectString(outString, s, len, preserveSpaces, &errorMsg);
   3370         if (accessor != NULL) {
   3371             accessor->reportError(accessorCookie, errorMsg);
   3372         }
   3373         return failed;
   3374     }
   3375 
   3376     return true;
   3377 }
   3378 
   3379 bool ResTable::collectString(String16* outString,
   3380                              const char16_t* s, size_t len,
   3381                              bool preserveSpaces,
   3382                              const char** outErrorMsg,
   3383                              bool append)
   3384 {
   3385     String16 tmp;
   3386 
   3387     char quoted = 0;
   3388     const char16_t* p = s;
   3389     while (p < (s+len)) {
   3390         while (p < (s+len)) {
   3391             const char16_t c = *p;
   3392             if (c == '\\') {
   3393                 break;
   3394             }
   3395             if (!preserveSpaces) {
   3396                 if (quoted == 0 && isspace16(c)
   3397                     && (c != ' ' || isspace16(*(p+1)))) {
   3398                     break;
   3399                 }
   3400                 if (c == '"' && (quoted == 0 || quoted == '"')) {
   3401                     break;
   3402                 }
   3403                 if (c == '\'' && (quoted == 0 || quoted == '\'')) {
   3404                     /*
   3405                      * In practice, when people write ' instead of \'
   3406                      * in a string, they are doing it by accident
   3407                      * instead of really meaning to use ' as a quoting
   3408                      * character.  Warn them so they don't lose it.
   3409                      */
   3410                     if (outErrorMsg) {
   3411                         *outErrorMsg = "Apostrophe not preceded by \\";
   3412                     }
   3413                     return false;
   3414                 }
   3415             }
   3416             p++;
   3417         }
   3418         if (p < (s+len)) {
   3419             if (p > s) {
   3420                 tmp.append(String16(s, p-s));
   3421             }
   3422             if (!preserveSpaces && (*p == '"' || *p == '\'')) {
   3423                 if (quoted == 0) {
   3424                     quoted = *p;
   3425                 } else {
   3426                     quoted = 0;
   3427                 }
   3428                 p++;
   3429             } else if (!preserveSpaces && isspace16(*p)) {
   3430                 // Space outside of a quote -- consume all spaces and
   3431                 // leave a single plain space char.
   3432                 tmp.append(String16(" "));
   3433                 p++;
   3434                 while (p < (s+len) && isspace16(*p)) {
   3435                     p++;
   3436                 }
   3437             } else if (*p == '\\') {
   3438                 p++;
   3439                 if (p < (s+len)) {
   3440                     switch (*p) {
   3441                     case 't':
   3442                         tmp.append(String16("\t"));
   3443                         break;
   3444                     case 'n':
   3445                         tmp.append(String16("\n"));
   3446                         break;
   3447                     case '#':
   3448                         tmp.append(String16("#"));
   3449                         break;
   3450                     case '@':
   3451                         tmp.append(String16("@"));
   3452                         break;
   3453                     case '?':
   3454                         tmp.append(String16("?"));
   3455                         break;
   3456                     case '"':
   3457                         tmp.append(String16("\""));
   3458                         break;
   3459                     case '\'':
   3460                         tmp.append(String16("'"));
   3461                         break;
   3462                     case '\\':
   3463                         tmp.append(String16("\\"));
   3464                         break;
   3465                     case 'u':
   3466                     {
   3467                         char16_t chr = 0;
   3468                         int i = 0;
   3469                         while (i < 4 && p[1] != 0) {
   3470                             p++;
   3471                             i++;
   3472                             int c;
   3473                             if (*p >= '0' && *p <= '9') {
   3474                                 c = *p - '0';
   3475                             } else if (*p >= 'a' && *p <= 'f') {
   3476                                 c = *p - 'a' + 10;
   3477                             } else if (*p >= 'A' && *p <= 'F') {
   3478                                 c = *p - 'A' + 10;
   3479                             } else {
   3480                                 if (outErrorMsg) {
   3481                                     *outErrorMsg = "Bad character in \\u unicode escape sequence";
   3482                                 }
   3483                                 return false;
   3484                             }
   3485                             chr = (chr<<4) | c;
   3486                         }
   3487                         tmp.append(String16(&chr, 1));
   3488                     } break;
   3489                     default:
   3490                         // ignore unknown escape chars.
   3491                         break;
   3492                     }
   3493                     p++;
   3494                 }
   3495             }
   3496             len -= (p-s);
   3497             s = p;
   3498         }
   3499     }
   3500 
   3501     if (tmp.size() != 0) {
   3502         if (len > 0) {
   3503             tmp.append(String16(s, len));
   3504         }
   3505         if (append) {
   3506             outString->append(tmp);
   3507         } else {
   3508             outString->setTo(tmp);
   3509         }
   3510     } else {
   3511         if (append) {
   3512             outString->append(String16(s, len));
   3513         } else {
   3514             outString->setTo(s, len);
   3515         }
   3516     }
   3517 
   3518     return true;
   3519 }
   3520 
   3521 size_t ResTable::getBasePackageCount() const
   3522 {
   3523     if (mError != NO_ERROR) {
   3524         return 0;
   3525     }
   3526     return mPackageGroups.size();
   3527 }
   3528 
   3529 const char16_t* ResTable::getBasePackageName(size_t idx) const
   3530 {
   3531     if (mError != NO_ERROR) {
   3532         return 0;
   3533     }
   3534     LOG_FATAL_IF(idx >= mPackageGroups.size(),
   3535                  "Requested package index %d past package count %d",
   3536                  (int)idx, (int)mPackageGroups.size());
   3537     return mPackageGroups[idx]->name.string();
   3538 }
   3539 
   3540 uint32_t ResTable::getBasePackageId(size_t idx) const
   3541 {
   3542     if (mError != NO_ERROR) {
   3543         return 0;
   3544     }
   3545     LOG_FATAL_IF(idx >= mPackageGroups.size(),
   3546                  "Requested package index %d past package count %d",
   3547                  (int)idx, (int)mPackageGroups.size());
   3548     return mPackageGroups[idx]->id;
   3549 }
   3550 
   3551 size_t ResTable::getTableCount() const
   3552 {
   3553     return mHeaders.size();
   3554 }
   3555 
   3556 const ResStringPool* ResTable::getTableStringBlock(size_t index) const
   3557 {
   3558     return &mHeaders[index]->values;
   3559 }
   3560 
   3561 void* ResTable::getTableCookie(size_t index) const
   3562 {
   3563     return mHeaders[index]->cookie;
   3564 }
   3565 
   3566 void ResTable::getConfigurations(Vector<ResTable_config>* configs) const
   3567 {
   3568     const size_t I = mPackageGroups.size();
   3569     for (size_t i=0; i<I; i++) {
   3570         const PackageGroup* packageGroup = mPackageGroups[i];
   3571         const size_t J = packageGroup->packages.size();
   3572         for (size_t j=0; j<J; j++) {
   3573             const Package* package = packageGroup->packages[j];
   3574             const size_t K = package->types.size();
   3575             for (size_t k=0; k<K; k++) {
   3576                 const Type* type = package->types[k];
   3577                 if (type == NULL) continue;
   3578                 const size_t L = type->configs.size();
   3579                 for (size_t l=0; l<L; l++) {
   3580                     const ResTable_type* config = type->configs[l];
   3581                     const ResTable_config* cfg = &config->config;
   3582                     // only insert unique
   3583                     const size_t M = configs->size();
   3584                     size_t m;
   3585                     for (m=0; m<M; m++) {
   3586                         if (0 == (*configs)[m].compare(*cfg)) {
   3587                             break;
   3588                         }
   3589                     }
   3590                     // if we didn't find it
   3591                     if (m == M) {
   3592                         configs->add(*cfg);
   3593                     }
   3594                 }
   3595             }
   3596         }
   3597     }
   3598 }
   3599 
   3600 void ResTable::getLocales(Vector<String8>* locales) const
   3601 {
   3602     Vector<ResTable_config> configs;
   3603     LOGD("calling getConfigurations");
   3604     getConfigurations(&configs);
   3605     LOGD("called getConfigurations size=%d", (int)configs.size());
   3606     const size_t I = configs.size();
   3607     for (size_t i=0; i<I; i++) {
   3608         char locale[6];
   3609         configs[i].getLocale(locale);
   3610         const size_t J = locales->size();
   3611         size_t j;
   3612         for (j=0; j<J; j++) {
   3613             if (0 == strcmp(locale, (*locales)[j].string())) {
   3614                 break;
   3615             }
   3616         }
   3617         if (j == J) {
   3618             locales->add(String8(locale));
   3619         }
   3620     }
   3621 }
   3622 
   3623 ssize_t ResTable::getEntry(
   3624     const Package* package, int typeIndex, int entryIndex,
   3625     const ResTable_config* config,
   3626     const ResTable_type** outType, const ResTable_entry** outEntry,
   3627     const Type** outTypeClass) const
   3628 {
   3629     LOGV("Getting entry from package %p\n", package);
   3630     const ResTable_package* const pkg = package->package;
   3631 
   3632     const Type* allTypes = package->getType(typeIndex);
   3633     LOGV("allTypes=%p\n", allTypes);
   3634     if (allTypes == NULL) {
   3635         LOGV("Skipping entry type index 0x%02x because type is NULL!\n", typeIndex);
   3636         return 0;
   3637     }
   3638 
   3639     if ((size_t)entryIndex >= allTypes->entryCount) {
   3640         LOGW("getEntry failing because entryIndex %d is beyond type entryCount %d",
   3641             entryIndex, (int)allTypes->entryCount);
   3642         return BAD_TYPE;
   3643     }
   3644 
   3645     const ResTable_type* type = NULL;
   3646     uint32_t offset = ResTable_type::NO_ENTRY;
   3647     ResTable_config bestConfig;
   3648     memset(&bestConfig, 0, sizeof(bestConfig)); // make the compiler shut up
   3649 
   3650     const size_t NT = allTypes->configs.size();
   3651     for (size_t i=0; i<NT; i++) {
   3652         const ResTable_type* const thisType = allTypes->configs[i];
   3653         if (thisType == NULL) continue;
   3654 
   3655         ResTable_config thisConfig;
   3656         thisConfig.copyFromDtoH(thisType->config);
   3657 
   3658         TABLE_GETENTRY(LOGI("Match entry 0x%x in type 0x%x (sz 0x%x): imsi:%d/%d=%d/%d lang:%c%c=%c%c cnt:%c%c=%c%c "
   3659                             "orien:%d=%d touch:%d=%d density:%d=%d key:%d=%d inp:%d=%d nav:%d=%d w:%d=%d h:%d=%d\n",
   3660                            entryIndex, typeIndex+1, dtohl(thisType->config.size),
   3661                            thisConfig.mcc, thisConfig.mnc,
   3662                            config ? config->mcc : 0, config ? config->mnc : 0,
   3663                            thisConfig.language[0] ? thisConfig.language[0] : '-',
   3664                            thisConfig.language[1] ? thisConfig.language[1] : '-',
   3665                            config && config->language[0] ? config->language[0] : '-',
   3666                            config && config->language[1] ? config->language[1] : '-',
   3667                            thisConfig.country[0] ? thisConfig.country[0] : '-',
   3668                            thisConfig.country[1] ? thisConfig.country[1] : '-',
   3669                            config && config->country[0] ? config->country[0] : '-',
   3670                            config && config->country[1] ? config->country[1] : '-',
   3671                            thisConfig.orientation,
   3672                            config ? config->orientation : 0,
   3673                            thisConfig.touchscreen,
   3674                            config ? config->touchscreen : 0,
   3675                            thisConfig.density,
   3676                            config ? config->density : 0,
   3677                            thisConfig.keyboard,
   3678                            config ? config->keyboard : 0,
   3679                            thisConfig.inputFlags,
   3680                            config ? config->inputFlags : 0,
   3681                            thisConfig.navigation,
   3682                            config ? config->navigation : 0,
   3683                            thisConfig.screenWidth,
   3684                            config ? config->screenWidth : 0,
   3685                            thisConfig.screenHeight,
   3686                            config ? config->screenHeight : 0));
   3687 
   3688         // Check to make sure this one is valid for the current parameters.
   3689         if (config && !thisConfig.match(*config)) {
   3690             TABLE_GETENTRY(LOGI("Does not match config!\n"));
   3691             continue;
   3692         }
   3693 
   3694         // Check if there is the desired entry in this type.
   3695 
   3696         const uint8_t* const end = ((const uint8_t*)thisType)
   3697             + dtohl(thisType->header.size);
   3698         const uint32_t* const eindex = (const uint32_t*)
   3699             (((const uint8_t*)thisType) + dtohs(thisType->header.headerSize));
   3700 
   3701         uint32_t thisOffset = dtohl(eindex[entryIndex]);
   3702         if (thisOffset == ResTable_type::NO_ENTRY) {
   3703             TABLE_GETENTRY(LOGI("Skipping because it is not defined!\n"));
   3704             continue;
   3705         }
   3706 
   3707         if (type != NULL) {
   3708             // Check if this one is less specific than the last found.  If so,
   3709             // we will skip it.  We check starting with things we most care
   3710             // about to those we least care about.
   3711             if (!thisConfig.isBetterThan(bestConfig, config)) {
   3712                 TABLE_GETENTRY(LOGI("This config is worse than last!\n"));
   3713                 continue;
   3714             }
   3715         }
   3716 
   3717         type = thisType;
   3718         offset = thisOffset;
   3719         bestConfig = thisConfig;
   3720         TABLE_GETENTRY(LOGI("Best entry so far -- using it!\n"));
   3721         if (!config) break;
   3722     }
   3723 
   3724     if (type == NULL) {
   3725         TABLE_GETENTRY(LOGI("No value found for requested entry!\n"));
   3726         return BAD_INDEX;
   3727     }
   3728 
   3729     offset += dtohl(type->entriesStart);
   3730     TABLE_NOISY(aout << "Looking in resource table " << package->header->header
   3731           << ", typeOff="
   3732           << (void*)(((const char*)type)-((const char*)package->header->header))
   3733           << ", offset=" << (void*)offset << endl);
   3734 
   3735     if (offset > (dtohl(type->header.size)-sizeof(ResTable_entry))) {
   3736         LOGW("ResTable_entry at 0x%x is beyond type chunk data 0x%x",
   3737              offset, dtohl(type->header.size));
   3738         return BAD_TYPE;
   3739     }
   3740     if ((offset&0x3) != 0) {
   3741         LOGW("ResTable_entry at 0x%x is not on an integer boundary",
   3742              offset);
   3743         return BAD_TYPE;
   3744     }
   3745 
   3746     const ResTable_entry* const entry = (const ResTable_entry*)
   3747         (((const uint8_t*)type) + offset);
   3748     if (dtohs(entry->size) < sizeof(*entry)) {
   3749         LOGW("ResTable_entry size 0x%x is too small", dtohs(entry->size));
   3750         return BAD_TYPE;
   3751     }
   3752 
   3753     *outType = type;
   3754     *outEntry = entry;
   3755     if (outTypeClass != NULL) {
   3756         *outTypeClass = allTypes;
   3757     }
   3758     return offset + dtohs(entry->size);
   3759 }
   3760 
   3761 status_t ResTable::parsePackage(const ResTable_package* const pkg,
   3762                                 const Header* const header)
   3763 {
   3764     const uint8_t* base = (const uint8_t*)pkg;
   3765     status_t err = validate_chunk(&pkg->header, sizeof(*pkg),
   3766                                   header->dataEnd, "ResTable_package");
   3767     if (err != NO_ERROR) {
   3768         return (mError=err);
   3769     }
   3770 
   3771     const size_t pkgSize = dtohl(pkg->header.size);
   3772 
   3773     if (dtohl(pkg->typeStrings) >= pkgSize) {
   3774         LOGW("ResTable_package type strings at %p are past chunk size %p.",
   3775              (void*)dtohl(pkg->typeStrings), (void*)pkgSize);
   3776         return (mError=BAD_TYPE);
   3777     }
   3778     if ((dtohl(pkg->typeStrings)&0x3) != 0) {
   3779         LOGW("ResTable_package type strings at %p is not on an integer boundary.",
   3780              (void*)dtohl(pkg->typeStrings));
   3781         return (mError=BAD_TYPE);
   3782     }
   3783     if (dtohl(pkg->keyStrings) >= pkgSize) {
   3784         LOGW("ResTable_package key strings at %p are past chunk size %p.",
   3785              (void*)dtohl(pkg->keyStrings), (void*)pkgSize);
   3786         return (mError=BAD_TYPE);
   3787     }
   3788     if ((dtohl(pkg->keyStrings)&0x3) != 0) {
   3789         LOGW("ResTable_package key strings at %p is not on an integer boundary.",
   3790              (void*)dtohl(pkg->keyStrings));
   3791         return (mError=BAD_TYPE);
   3792     }
   3793 
   3794     Package* package = NULL;
   3795     PackageGroup* group = NULL;
   3796     uint32_t id = dtohl(pkg->id);
   3797     if (id != 0 && id < 256) {
   3798 
   3799         package = new Package(this, header, pkg);
   3800         if (package == NULL) {
   3801             return (mError=NO_MEMORY);
   3802         }
   3803 
   3804         size_t idx = mPackageMap[id];
   3805         if (idx == 0) {
   3806             idx = mPackageGroups.size()+1;
   3807 
   3808             char16_t tmpName[sizeof(pkg->name)/sizeof(char16_t)];
   3809             strcpy16_dtoh(tmpName, pkg->name, sizeof(pkg->name)/sizeof(char16_t));
   3810             group = new PackageGroup(this, String16(tmpName), id);
   3811             if (group == NULL) {
   3812                 delete package;
   3813                 return (mError=NO_MEMORY);
   3814             }
   3815 
   3816             err = package->typeStrings.setTo(base+dtohl(pkg->typeStrings),
   3817                                            header->dataEnd-(base+dtohl(pkg->typeStrings)));
   3818             if (err != NO_ERROR) {
   3819                 delete group;
   3820                 delete package;
   3821                 return (mError=err);
   3822             }
   3823             err = package->keyStrings.setTo(base+dtohl(pkg->keyStrings),
   3824                                           header->dataEnd-(base+dtohl(pkg->keyStrings)));
   3825             if (err != NO_ERROR) {
   3826                 delete group;
   3827                 delete package;
   3828                 return (mError=err);
   3829             }
   3830 
   3831             //printf("Adding new package id %d at index %d\n", id, idx);
   3832             err = mPackageGroups.add(group);
   3833             if (err < NO_ERROR) {
   3834                 return (mError=err);
   3835             }
   3836             group->basePackage = package;
   3837 
   3838             mPackageMap[id] = (uint8_t)idx;
   3839         } else {
   3840             group = mPackageGroups.itemAt(idx-1);
   3841             if (group == NULL) {
   3842                 return (mError=UNKNOWN_ERROR);
   3843             }
   3844         }
   3845         err = group->packages.add(package);
   3846         if (err < NO_ERROR) {
   3847             return (mError=err);
   3848         }
   3849     } else {
   3850         LOG_ALWAYS_FATAL("Skins not supported!");
   3851         return NO_ERROR;
   3852     }
   3853 
   3854 
   3855     // Iterate through all chunks.
   3856     size_t curPackage = 0;
   3857 
   3858     const ResChunk_header* chunk =
   3859         (const ResChunk_header*)(((const uint8_t*)pkg)
   3860                                  + dtohs(pkg->header.headerSize));
   3861     const uint8_t* endPos = ((const uint8_t*)pkg) + dtohs(pkg->header.size);
   3862     while (((const uint8_t*)chunk) <= (endPos-sizeof(ResChunk_header)) &&
   3863            ((const uint8_t*)chunk) <= (endPos-dtohl(chunk->size))) {
   3864         TABLE_NOISY(LOGV("PackageChunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n",
   3865                          dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
   3866                          (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header))));
   3867         const size_t csize = dtohl(chunk->size);
   3868         const uint16_t ctype = dtohs(chunk->type);
   3869         if (ctype == RES_TABLE_TYPE_SPEC_TYPE) {
   3870             const ResTable_typeSpec* typeSpec = (const ResTable_typeSpec*)(chunk);
   3871             err = validate_chunk(&typeSpec->header, sizeof(*typeSpec),
   3872                                  endPos, "ResTable_typeSpec");
   3873             if (err != NO_ERROR) {
   3874                 return (mError=err);
   3875             }
   3876 
   3877             const size_t typeSpecSize = dtohl(typeSpec->header.size);
   3878 
   3879             LOAD_TABLE_NOISY(printf("TypeSpec off %p: type=0x%x, headerSize=0x%x, size=%p\n",
   3880                                     (void*)(base-(const uint8_t*)chunk),
   3881                                     dtohs(typeSpec->header.type),
   3882                                     dtohs(typeSpec->header.headerSize),
   3883                                     (void*)typeSize));
   3884             // look for block overrun or int overflow when multiplying by 4
   3885             if ((dtohl(typeSpec->entryCount) > (INT32_MAX/sizeof(uint32_t))
   3886                     || dtohs(typeSpec->header.headerSize)+(sizeof(uint32_t)*dtohl(typeSpec->entryCount))
   3887                     > typeSpecSize)) {
   3888                 LOGW("ResTable_typeSpec entry index to %p extends beyond chunk end %p.",
   3889                      (void*)(dtohs(typeSpec->header.headerSize)
   3890                              +(sizeof(uint32_t)*dtohl(typeSpec->entryCount))),
   3891                      (void*)typeSpecSize);
   3892                 return (mError=BAD_TYPE);
   3893             }
   3894 
   3895             if (typeSpec->id == 0) {
   3896                 LOGW("ResTable_type has an id of 0.");
   3897                 return (mError=BAD_TYPE);
   3898             }
   3899 
   3900             while (package->types.size() < typeSpec->id) {
   3901                 package->types.add(NULL);
   3902             }
   3903             Type* t = package->types[typeSpec->id-1];
   3904             if (t == NULL) {
   3905                 t = new Type(header, package, dtohl(typeSpec->entryCount));
   3906                 package->types.editItemAt(typeSpec->id-1) = t;
   3907             } else if (dtohl(typeSpec->entryCount) != t->entryCount) {
   3908                 LOGW("ResTable_typeSpec entry count inconsistent: given %d, previously %d",
   3909                     (int)dtohl(typeSpec->entryCount), (int)t->entryCount);
   3910                 return (mError=BAD_TYPE);
   3911             }
   3912             t->typeSpecFlags = (const uint32_t*)(
   3913                     ((const uint8_t*)typeSpec) + dtohs(typeSpec->header.headerSize));
   3914             t->typeSpec = typeSpec;
   3915 
   3916         } else if (ctype == RES_TABLE_TYPE_TYPE) {
   3917             const ResTable_type* type = (const ResTable_type*)(chunk);
   3918             err = validate_chunk(&type->header, sizeof(*type)-sizeof(ResTable_config)+4,
   3919                                  endPos, "ResTable_type");
   3920             if (err != NO_ERROR) {
   3921                 return (mError=err);
   3922             }
   3923 
   3924             const size_t typeSize = dtohl(type->header.size);
   3925 
   3926             LOAD_TABLE_NOISY(printf("Type off %p: type=0x%x, headerSize=0x%x, size=%p\n",
   3927                                     (void*)(base-(const uint8_t*)chunk),
   3928                                     dtohs(type->header.type),
   3929                                     dtohs(type->header.headerSize),
   3930                                     (void*)typeSize));
   3931             if (dtohs(type->header.headerSize)+(sizeof(uint32_t)*dtohl(type->entryCount))
   3932                 > typeSize) {
   3933                 LOGW("ResTable_type entry index to %p extends beyond chunk end %p.",
   3934                      (void*)(dtohs(type->header.headerSize)
   3935                              +(sizeof(uint32_t)*dtohl(type->entryCount))),
   3936                      (void*)typeSize);
   3937                 return (mError=BAD_TYPE);
   3938             }
   3939             if (dtohl(type->entryCount) != 0
   3940                 && dtohl(type->entriesStart) > (typeSize-sizeof(ResTable_entry))) {
   3941                 LOGW("ResTable_type entriesStart at %p extends beyond chunk end %p.",
   3942                      (void*)dtohl(type->entriesStart), (void*)typeSize);
   3943                 return (mError=BAD_TYPE);
   3944             }
   3945             if (type->id == 0) {
   3946                 LOGW("ResTable_type has an id of 0.");
   3947                 return (mError=BAD_TYPE);
   3948             }
   3949 
   3950             while (package->types.size() < type->id) {
   3951                 package->types.add(NULL);
   3952             }
   3953             Type* t = package->types[type->id-1];
   3954             if (t == NULL) {
   3955                 t = new Type(header, package, dtohl(type->entryCount));
   3956                 package->types.editItemAt(type->id-1) = t;
   3957             } else if (dtohl(type->entryCount) != t->entryCount) {
   3958                 LOGW("ResTable_type entry count inconsistent: given %d, previously %d",
   3959                     (int)dtohl(type->entryCount), (int)t->entryCount);
   3960                 return (mError=BAD_TYPE);
   3961             }
   3962 
   3963             TABLE_GETENTRY(
   3964                 ResTable_config thisConfig;
   3965                 thisConfig.copyFromDtoH(type->config);
   3966                 LOGI("Adding config to type %d: imsi:%d/%d lang:%c%c cnt:%c%c "
   3967                      "orien:%d touch:%d density:%d key:%d inp:%d nav:%d w:%d h:%d\n",
   3968                       type->id,
   3969                       thisConfig.mcc, thisConfig.mnc,
   3970                       thisConfig.language[0] ? thisConfig.language[0] : '-',
   3971                       thisConfig.language[1] ? thisConfig.language[1] : '-',
   3972                       thisConfig.country[0] ? thisConfig.country[0] : '-',
   3973                       thisConfig.country[1] ? thisConfig.country[1] : '-',
   3974                       thisConfig.orientation,
   3975                       thisConfig.touchscreen,
   3976                       thisConfig.density,
   3977                       thisConfig.keyboard,
   3978                       thisConfig.inputFlags,
   3979                       thisConfig.navigation,
   3980                       thisConfig.screenWidth,
   3981                       thisConfig.screenHeight));
   3982             t->configs.add(type);
   3983         } else {
   3984             status_t err = validate_chunk(chunk, sizeof(ResChunk_header),
   3985                                           endPos, "ResTable_package:unknown");
   3986             if (err != NO_ERROR) {
   3987                 return (mError=err);
   3988             }
   3989         }
   3990         chunk = (const ResChunk_header*)
   3991             (((const uint8_t*)chunk) + csize);
   3992     }
   3993 
   3994     if (group->typeCount == 0) {
   3995         group->typeCount = package->types.size();
   3996     }
   3997 
   3998     return NO_ERROR;
   3999 }
   4000 
   4001 #ifndef HAVE_ANDROID_OS
   4002 #define CHAR16_TO_CSTR(c16, len) (String8(String16(c16,len)).string())
   4003 
   4004 #define CHAR16_ARRAY_EQ(constant, var, len) \
   4005         ((len == (sizeof(constant)/sizeof(constant[0]))) && (0 == memcmp((var), (constant), (len))))
   4006 
   4007 void print_complex(uint32_t complex, bool isFraction)
   4008 {
   4009     const float MANTISSA_MULT =
   4010         1.0f / (1<<Res_value::COMPLEX_MANTISSA_SHIFT);
   4011     const float RADIX_MULTS[] = {
   4012         1.0f*MANTISSA_MULT, 1.0f/(1<<7)*MANTISSA_MULT,
   4013         1.0f/(1<<15)*MANTISSA_MULT, 1.0f/(1<<23)*MANTISSA_MULT
   4014     };
   4015 
   4016     float value = (complex&(Res_value::COMPLEX_MANTISSA_MASK
   4017                    <<Res_value::COMPLEX_MANTISSA_SHIFT))
   4018             * RADIX_MULTS[(complex>>Res_value::COMPLEX_RADIX_SHIFT)
   4019                             & Res_value::COMPLEX_RADIX_MASK];
   4020     printf("%f", value);
   4021 
   4022     if (!isFraction) {
   4023         switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
   4024             case Res_value::COMPLEX_UNIT_PX: printf("px"); break;
   4025             case Res_value::COMPLEX_UNIT_DIP: printf("dp"); break;
   4026             case Res_value::COMPLEX_UNIT_SP: printf("sp"); break;
   4027             case Res_value::COMPLEX_UNIT_PT: printf("pt"); break;
   4028             case Res_value::COMPLEX_UNIT_IN: printf("in"); break;
   4029             case Res_value::COMPLEX_UNIT_MM: printf("mm"); break;
   4030             default: printf(" (unknown unit)"); break;
   4031         }
   4032     } else {
   4033         switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
   4034             case Res_value::COMPLEX_UNIT_FRACTION: printf("%%"); break;
   4035             case Res_value::COMPLEX_UNIT_FRACTION_PARENT: printf("%%p"); break;
   4036             default: printf(" (unknown unit)"); break;
   4037         }
   4038     }
   4039 }
   4040 
   4041 void ResTable::print_value(const Package* pkg, const Res_value& value) const
   4042 {
   4043     if (value.dataType == Res_value::TYPE_NULL) {
   4044         printf("(null)\n");
   4045     } else if (value.dataType == Res_value::TYPE_REFERENCE) {
   4046         printf("(reference) 0x%08x\n", value.data);
   4047     } else if (value.dataType == Res_value::TYPE_ATTRIBUTE) {
   4048         printf("(attribute) 0x%08x\n", value.data);
   4049     } else if (value.dataType == Res_value::TYPE_STRING) {
   4050         size_t len;
   4051         const char* str8 = pkg->header->values.string8At(
   4052                 value.data, &len);
   4053         if (str8 != NULL) {
   4054             printf("(string8) \"%s\"\n", str8);
   4055         } else {
   4056             const char16_t* str16 = pkg->header->values.stringAt(
   4057                     value.data, &len);
   4058             if (str16 != NULL) {
   4059                 printf("(string16) \"%s\"\n",
   4060                     String8(str16, len).string());
   4061             } else {
   4062                 printf("(string) null\n");
   4063             }
   4064         }
   4065     } else if (value.dataType == Res_value::TYPE_FLOAT) {
   4066         printf("(float) %g\n", *(const float*)&value.data);
   4067     } else if (value.dataType == Res_value::TYPE_DIMENSION) {
   4068         printf("(dimension) ");
   4069         print_complex(value.data, false);
   4070         printf("\n");
   4071     } else if (value.dataType == Res_value::TYPE_FRACTION) {
   4072         printf("(fraction) ");
   4073         print_complex(value.data, true);
   4074         printf("\n");
   4075     } else if (value.dataType >= Res_value::TYPE_FIRST_COLOR_INT
   4076             || value.dataType <= Res_value::TYPE_LAST_COLOR_INT) {
   4077         printf("(color) #%08x\n", value.data);
   4078     } else if (value.dataType == Res_value::TYPE_INT_BOOLEAN) {
   4079         printf("(boolean) %s\n", value.data ? "true" : "false");
   4080     } else if (value.dataType >= Res_value::TYPE_FIRST_INT
   4081             || value.dataType <= Res_value::TYPE_LAST_INT) {
   4082         printf("(int) 0x%08x or %d\n", value.data, value.data);
   4083     } else {
   4084         printf("(unknown type) t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)\n",
   4085                (int)value.dataType, (int)value.data,
   4086                (int)value.size, (int)value.res0);
   4087     }
   4088 }
   4089 
   4090 void ResTable::print(bool inclValues) const
   4091 {
   4092     if (mError != 0) {
   4093         printf("mError=0x%x (%s)\n", mError, strerror(mError));
   4094     }
   4095 #if 0
   4096     printf("mParams=%c%c-%c%c,\n",
   4097             mParams.language[0], mParams.language[1],
   4098             mParams.country[0], mParams.country[1]);
   4099 #endif
   4100     size_t pgCount = mPackageGroups.size();
   4101     printf("Package Groups (%d)\n", (int)pgCount);
   4102     for (size_t pgIndex=0; pgIndex<pgCount; pgIndex++) {
   4103         const PackageGroup* pg = mPackageGroups[pgIndex];
   4104         printf("Package Group %d id=%d packageCount=%d name=%s\n",
   4105                 (int)pgIndex, pg->id, (int)pg->packages.size(),
   4106                 String8(pg->name).string());
   4107 
   4108         size_t pkgCount = pg->packages.size();
   4109         for (size_t pkgIndex=0; pkgIndex<pkgCount; pkgIndex++) {
   4110             const Package* pkg = pg->packages[pkgIndex];
   4111             size_t typeCount = pkg->types.size();
   4112             printf("  Package %d id=%d name=%s typeCount=%d\n", (int)pkgIndex,
   4113                     pkg->package->id, String8(String16(pkg->package->name)).string(),
   4114                     (int)typeCount);
   4115             for (size_t typeIndex=0; typeIndex<typeCount; typeIndex++) {
   4116                 const Type* typeConfigs = pkg->getType(typeIndex);
   4117                 if (typeConfigs == NULL) {
   4118                     printf("    type %d NULL\n", (int)typeIndex);
   4119                     continue;
   4120                 }
   4121                 const size_t NTC = typeConfigs->configs.size();
   4122                 printf("    type %d configCount=%d entryCount=%d\n",
   4123                        (int)typeIndex, (int)NTC, (int)typeConfigs->entryCount);
   4124                 if (typeConfigs->typeSpecFlags != NULL) {
   4125                     for (size_t entryIndex=0; entryIndex<typeConfigs->entryCount; entryIndex++) {
   4126                         uint32_t resID = (0xff000000 & ((pkg->package->id)<<24))
   4127                                     | (0x00ff0000 & ((typeIndex+1)<<16))
   4128                                     | (0x0000ffff & (entryIndex));
   4129                         resource_name resName;
   4130                         this->getResourceName(resID, &resName);
   4131                         printf("      spec resource 0x%08x %s:%s/%s: flags=0x%08x\n",
   4132                             resID,
   4133                             CHAR16_TO_CSTR(resName.package, resName.packageLen),
   4134                             CHAR16_TO_CSTR(resName.type, resName.typeLen),
   4135                             CHAR16_TO_CSTR(resName.name, resName.nameLen),
   4136                             dtohl(typeConfigs->typeSpecFlags[entryIndex]));
   4137                     }
   4138                 }
   4139                 for (size_t configIndex=0; configIndex<NTC; configIndex++) {
   4140                     const ResTable_type* type = typeConfigs->configs[configIndex];
   4141                     if ((((uint64_t)type)&0x3) != 0) {
   4142                         printf("      NON-INTEGER ResTable_type ADDRESS: %p\n", type);
   4143                         continue;
   4144                     }
   4145                     char density[16];
   4146                     uint16_t dval = dtohs(type->config.density);
   4147                     if (dval == ResTable_config::DENSITY_DEFAULT) {
   4148                         strcpy(density, "def");
   4149                     } else if (dval == ResTable_config::DENSITY_NONE) {
   4150                         strcpy(density, "no");
   4151                     } else {
   4152                         sprintf(density, "%d", (int)dval);
   4153                     }
   4154                     printf("      config %d", (int)configIndex);
   4155                     if (type->config.mcc != 0) {
   4156                         printf(" mcc=%d", dtohs(type->config.mcc));
   4157                     }
   4158                     if (type->config.mnc != 0) {
   4159                         printf(" mnc=%d", dtohs(type->config.mnc));
   4160                     }
   4161                     if (type->config.locale != 0) {
   4162                         printf(" lang=%c%c cnt=%c%c",
   4163                                type->config.language[0] ? type->config.language[0] : '-',
   4164                                type->config.language[1] ? type->config.language[1] : '-',
   4165                                type->config.country[0] ? type->config.country[0] : '-',
   4166                                type->config.country[1] ? type->config.country[1] : '-');
   4167                     }
   4168                     if (type->config.screenLayout != 0) {
   4169                         printf(" sz=%d",
   4170                                 type->config.screenLayout&ResTable_config::MASK_SCREENSIZE);
   4171                         switch (type->config.screenLayout&ResTable_config::MASK_SCREENSIZE) {
   4172                             case ResTable_config::SCREENSIZE_SMALL:
   4173                                 printf(" (small)");
   4174                                 break;
   4175                             case ResTable_config::SCREENSIZE_NORMAL:
   4176                                 printf(" (normal)");
   4177                                 break;
   4178                             case ResTable_config::SCREENSIZE_LARGE:
   4179                                 printf(" (large)");
   4180                                 break;
   4181                             case ResTable_config::SCREENSIZE_XLARGE:
   4182                                 printf(" (xlarge)");
   4183                                 break;
   4184                         }
   4185                         printf(" lng=%d",
   4186                                 type->config.screenLayout&ResTable_config::MASK_SCREENLONG);
   4187                         switch (type->config.screenLayout&ResTable_config::MASK_SCREENLONG) {
   4188                             case ResTable_config::SCREENLONG_NO:
   4189                                 printf(" (notlong)");
   4190                                 break;
   4191                             case ResTable_config::SCREENLONG_YES:
   4192                                 printf(" (long)");
   4193                                 break;
   4194                         }
   4195                     }
   4196                     if (type->config.orientation != 0) {
   4197                         printf(" orient=%d", type->config.orientation);
   4198                         switch (type->config.orientation) {
   4199                             case ResTable_config::ORIENTATION_PORT:
   4200                                 printf(" (port)");
   4201                                 break;
   4202                             case ResTable_config::ORIENTATION_LAND:
   4203                                 printf(" (land)");
   4204                                 break;
   4205                             case ResTable_config::ORIENTATION_SQUARE:
   4206                                 printf(" (square)");
   4207                                 break;
   4208                         }
   4209                     }
   4210                     if (type->config.uiMode != 0) {
   4211                         printf(" type=%d",
   4212                                 type->config.uiMode&ResTable_config::MASK_UI_MODE_TYPE);
   4213                         switch (type->config.uiMode&ResTable_config::MASK_UI_MODE_TYPE) {
   4214                             case ResTable_config::UI_MODE_TYPE_NORMAL:
   4215                                 printf(" (normal)");
   4216                                 break;
   4217                             case ResTable_config::UI_MODE_TYPE_CAR:
   4218                                 printf(" (car)");
   4219                                 break;
   4220                         }
   4221                         printf(" night=%d",
   4222                                 type->config.uiMode&ResTable_config::MASK_UI_MODE_NIGHT);
   4223                         switch (type->config.uiMode&ResTable_config::MASK_UI_MODE_NIGHT) {
   4224                             case ResTable_config::UI_MODE_NIGHT_NO:
   4225                                 printf(" (no)");
   4226                                 break;
   4227                             case ResTable_config::UI_MODE_NIGHT_YES:
   4228                                 printf(" (yes)");
   4229                                 break;
   4230                         }
   4231                     }
   4232                     if (dval != 0) {
   4233                         printf(" density=%s", density);
   4234                     }
   4235                     if (type->config.touchscreen != 0) {
   4236                         printf(" touch=%d", type->config.touchscreen);
   4237                         switch (type->config.touchscreen) {
   4238                             case ResTable_config::TOUCHSCREEN_NOTOUCH:
   4239                                 printf(" (notouch)");
   4240                                 break;
   4241                             case ResTable_config::TOUCHSCREEN_STYLUS:
   4242                                 printf(" (stylus)");
   4243                                 break;
   4244                             case ResTable_config::TOUCHSCREEN_FINGER:
   4245                                 printf(" (finger)");
   4246                                 break;
   4247                         }
   4248                     }
   4249                     if (type->config.inputFlags != 0) {
   4250                         printf(" keyhid=%d", type->config.inputFlags&ResTable_config::MASK_KEYSHIDDEN);
   4251                         switch (type->config.inputFlags&ResTable_config::MASK_KEYSHIDDEN) {
   4252                             case ResTable_config::KEYSHIDDEN_NO:
   4253                                 printf(" (no)");
   4254                                 break;
   4255                             case ResTable_config::KEYSHIDDEN_YES:
   4256                                 printf(" (yes)");
   4257                                 break;
   4258                             case ResTable_config::KEYSHIDDEN_SOFT:
   4259                                 printf(" (soft)");
   4260                                 break;
   4261                         }
   4262                         printf(" navhid=%d", type->config.inputFlags&ResTable_config::MASK_NAVHIDDEN);
   4263                         switch (type->config.inputFlags&ResTable_config::MASK_NAVHIDDEN) {
   4264                             case ResTable_config::NAVHIDDEN_NO:
   4265                                 printf(" (no)");
   4266                                 break;
   4267                             case ResTable_config::NAVHIDDEN_YES:
   4268                                 printf(" (yes)");
   4269                                 break;
   4270                         }
   4271                     }
   4272                     if (type->config.keyboard != 0) {
   4273                         printf(" kbd=%d", type->config.keyboard);
   4274                         switch (type->config.keyboard) {
   4275                             case ResTable_config::KEYBOARD_NOKEYS:
   4276                                 printf(" (nokeys)");
   4277                                 break;
   4278                             case ResTable_config::KEYBOARD_QWERTY:
   4279                                 printf(" (qwerty)");
   4280                                 break;
   4281                             case ResTable_config::KEYBOARD_12KEY:
   4282                                 printf(" (12key)");
   4283                                 break;
   4284                         }
   4285                     }
   4286                     if (type->config.navigation != 0) {
   4287                         printf(" nav=%d", type->config.navigation);
   4288                         switch (type->config.navigation) {
   4289                             case ResTable_config::NAVIGATION_NONAV:
   4290                                 printf(" (nonav)");
   4291                                 break;
   4292                             case ResTable_config::NAVIGATION_DPAD:
   4293                                 printf(" (dpad)");
   4294                                 break;
   4295                             case ResTable_config::NAVIGATION_TRACKBALL:
   4296                                 printf(" (trackball)");
   4297                                 break;
   4298                             case ResTable_config::NAVIGATION_WHEEL:
   4299                                 printf(" (wheel)");
   4300                                 break;
   4301                         }
   4302                     }
   4303                     if (type->config.screenWidth != 0) {
   4304                         printf(" w=%d", dtohs(type->config.screenWidth));
   4305                     }
   4306                     if (type->config.screenHeight != 0) {
   4307                         printf(" h=%d", dtohs(type->config.screenHeight));
   4308                     }
   4309                     if (type->config.sdkVersion != 0) {
   4310                         printf(" sdk=%d", dtohs(type->config.sdkVersion));
   4311                     }
   4312                     if (type->config.minorVersion != 0) {
   4313                         printf(" mver=%d", dtohs(type->config.minorVersion));
   4314                     }
   4315                     printf("\n");
   4316                     size_t entryCount = dtohl(type->entryCount);
   4317                     uint32_t entriesStart = dtohl(type->entriesStart);
   4318                     if ((entriesStart&0x3) != 0) {
   4319                         printf("      NON-INTEGER ResTable_type entriesStart OFFSET: %p\n", (void*)entriesStart);
   4320                         continue;
   4321                     }
   4322                     uint32_t typeSize = dtohl(type->header.size);
   4323                     if ((typeSize&0x3) != 0) {
   4324                         printf("      NON-INTEGER ResTable_type header.size: %p\n", (void*)typeSize);
   4325                         continue;
   4326                     }
   4327                     for (size_t entryIndex=0; entryIndex<entryCount; entryIndex++) {
   4328 
   4329                         const uint8_t* const end = ((const uint8_t*)type)
   4330                             + dtohl(type->header.size);
   4331                         const uint32_t* const eindex = (const uint32_t*)
   4332                             (((const uint8_t*)type) + dtohs(type->header.headerSize));
   4333 
   4334                         uint32_t thisOffset = dtohl(eindex[entryIndex]);
   4335                         if (thisOffset == ResTable_type::NO_ENTRY) {
   4336                             continue;
   4337                         }
   4338 
   4339                         uint32_t resID = (0xff000000 & ((pkg->package->id)<<24))
   4340                                     | (0x00ff0000 & ((typeIndex+1)<<16))
   4341                                     | (0x0000ffff & (entryIndex));
   4342                         resource_name resName;
   4343                         this->getResourceName(resID, &resName);
   4344                         printf("        resource 0x%08x %s:%s/%s: ", resID,
   4345                                 CHAR16_TO_CSTR(resName.package, resName.packageLen),
   4346                                 CHAR16_TO_CSTR(resName.type, resName.typeLen),
   4347                                 CHAR16_TO_CSTR(resName.name, resName.nameLen));
   4348                         if ((thisOffset&0x3) != 0) {
   4349                             printf("NON-INTEGER OFFSET: %p\n", (void*)thisOffset);
   4350                             continue;
   4351                         }
   4352                         if ((thisOffset+sizeof(ResTable_entry)) > typeSize) {
   4353                             printf("OFFSET OUT OF BOUNDS: %p+%p (size is %p)\n",
   4354                                    (void*)entriesStart, (void*)thisOffset,
   4355                                    (void*)typeSize);
   4356                             continue;
   4357                         }
   4358 
   4359                         const ResTable_entry* ent = (const ResTable_entry*)
   4360                             (((const uint8_t*)type) + entriesStart + thisOffset);
   4361                         if (((entriesStart + thisOffset)&0x3) != 0) {
   4362                             printf("NON-INTEGER ResTable_entry OFFSET: %p\n",
   4363                                  (void*)(entriesStart + thisOffset));
   4364                             continue;
   4365                         }
   4366 
   4367                         uint16_t esize = dtohs(ent->size);
   4368                         if ((esize&0x3) != 0) {
   4369                             printf("NON-INTEGER ResTable_entry SIZE: %p\n", (void*)esize);
   4370                             continue;
   4371                         }
   4372                         if ((thisOffset+esize) > typeSize) {
   4373                             printf("ResTable_entry OUT OF BOUNDS: %p+%p+%p (size is %p)\n",
   4374                                    (void*)entriesStart, (void*)thisOffset,
   4375                                    (void*)esize, (void*)typeSize);
   4376                             continue;
   4377                         }
   4378 
   4379                         const Res_value* valuePtr = NULL;
   4380                         const ResTable_map_entry* bagPtr = NULL;
   4381                         Res_value value;
   4382                         if ((dtohs(ent->flags)&ResTable_entry::FLAG_COMPLEX) != 0) {
   4383                             printf("<bag>");
   4384                             bagPtr = (const ResTable_map_entry*)ent;
   4385                         } else {
   4386                             valuePtr = (const Res_value*)
   4387                                 (((const uint8_t*)ent) + esize);
   4388                             value.copyFrom_dtoh(*valuePtr);
   4389                             printf("t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)",
   4390                                    (int)value.dataType, (int)value.data,
   4391                                    (int)value.size, (int)value.res0);
   4392                         }
   4393 
   4394                         if ((dtohs(ent->flags)&ResTable_entry::FLAG_PUBLIC) != 0) {
   4395                             printf(" (PUBLIC)");
   4396                         }
   4397                         printf("\n");
   4398 
   4399                         if (inclValues) {
   4400                             if (valuePtr != NULL) {
   4401                                 printf("          ");
   4402                                 print_value(pkg, value);
   4403                             } else if (bagPtr != NULL) {
   4404                                 const int N = dtohl(bagPtr->count);
   4405                                 const ResTable_map* mapPtr = (const ResTable_map*)
   4406                                         (((const uint8_t*)ent) + esize);
   4407                                 printf("          Parent=0x%08x, Count=%d\n",
   4408                                     dtohl(bagPtr->parent.ident), N);
   4409                                 for (int i=0; i<N; i++) {
   4410                                     printf("          #%i (Key=0x%08x): ",
   4411                                         i, dtohl(mapPtr->name.ident));
   4412                                     value.copyFrom_dtoh(mapPtr->value);
   4413                                     print_value(pkg, value);
   4414                                     const size_t size = dtohs(mapPtr->value.size);
   4415                                     mapPtr = (ResTable_map*)(((const uint8_t*)mapPtr)
   4416                                             + size + sizeof(*mapPtr)-sizeof(mapPtr->value));
   4417                                 }
   4418                             }
   4419                         }
   4420                     }
   4421                 }
   4422             }
   4423         }
   4424     }
   4425 }
   4426 
   4427 #endif // HAVE_ANDROID_OS
   4428 
   4429 }   // namespace android
   4430