Home | History | Annotate | Download | only in androidfw
      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 <androidfw/ResourceTypes.h>
     21 #include <utils/Atomic.h>
     22 #include <utils/ByteOrder.h>
     23 #include <utils/Debug.h>
     24 #include <utils/Log.h>
     25 #include <utils/String16.h>
     26 #include <utils/String8.h>
     27 #include <utils/TextOutput.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 #define IDMAP_MAGIC         0x706d6469
     67 // size measured in sizeof(uint32_t)
     68 #define IDMAP_HEADER_SIZE (ResTable::IDMAP_HEADER_SIZE_BYTES / sizeof(uint32_t))
     69 
     70 static void printToLogFunc(void* cookie, const char* txt)
     71 {
     72     ALOGV("%s", txt);
     73 }
     74 
     75 // Standard C isspace() is only required to look at the low byte of its input, so
     76 // produces incorrect results for UTF-16 characters.  For safety's sake, assume that
     77 // any high-byte UTF-16 code point is not whitespace.
     78 inline int isspace16(char16_t c) {
     79     return (c < 0x0080 && isspace(c));
     80 }
     81 
     82 // range checked; guaranteed to NUL-terminate within the stated number of available slots
     83 // NOTE: if this truncates the dst string due to running out of space, no attempt is
     84 // made to avoid splitting surrogate pairs.
     85 static void strcpy16_dtoh(uint16_t* dst, const uint16_t* src, size_t avail)
     86 {
     87     uint16_t* last = dst + avail - 1;
     88     while (*src && (dst < last)) {
     89         char16_t s = dtohs(*src);
     90         *dst++ = s;
     91         src++;
     92     }
     93     *dst = 0;
     94 }
     95 
     96 static status_t validate_chunk(const ResChunk_header* chunk,
     97                                size_t minSize,
     98                                const uint8_t* dataEnd,
     99                                const char* name)
    100 {
    101     const uint16_t headerSize = dtohs(chunk->headerSize);
    102     const uint32_t size = dtohl(chunk->size);
    103 
    104     if (headerSize >= minSize) {
    105         if (headerSize <= size) {
    106             if (((headerSize|size)&0x3) == 0) {
    107                 if ((ssize_t)size <= (dataEnd-((const uint8_t*)chunk))) {
    108                     return NO_ERROR;
    109                 }
    110                 ALOGW("%s data size %p extends beyond resource end %p.",
    111                      name, (void*)size,
    112                      (void*)(dataEnd-((const uint8_t*)chunk)));
    113                 return BAD_TYPE;
    114             }
    115             ALOGW("%s size 0x%x or headerSize 0x%x is not on an integer boundary.",
    116                  name, (int)size, (int)headerSize);
    117             return BAD_TYPE;
    118         }
    119         ALOGW("%s size %p is smaller than header size %p.",
    120              name, (void*)size, (void*)(int)headerSize);
    121         return BAD_TYPE;
    122     }
    123     ALOGW("%s header size %p is too small.",
    124          name, (void*)(int)headerSize);
    125     return BAD_TYPE;
    126 }
    127 
    128 inline void Res_value::copyFrom_dtoh(const Res_value& src)
    129 {
    130     size = dtohs(src.size);
    131     res0 = src.res0;
    132     dataType = src.dataType;
    133     data = dtohl(src.data);
    134 }
    135 
    136 void Res_png_9patch::deviceToFile()
    137 {
    138     for (int i = 0; i < numXDivs; i++) {
    139         xDivs[i] = htonl(xDivs[i]);
    140     }
    141     for (int i = 0; i < numYDivs; i++) {
    142         yDivs[i] = htonl(yDivs[i]);
    143     }
    144     paddingLeft = htonl(paddingLeft);
    145     paddingRight = htonl(paddingRight);
    146     paddingTop = htonl(paddingTop);
    147     paddingBottom = htonl(paddingBottom);
    148     for (int i=0; i<numColors; i++) {
    149         colors[i] = htonl(colors[i]);
    150     }
    151 }
    152 
    153 void Res_png_9patch::fileToDevice()
    154 {
    155     for (int i = 0; i < numXDivs; i++) {
    156         xDivs[i] = ntohl(xDivs[i]);
    157     }
    158     for (int i = 0; i < numYDivs; i++) {
    159         yDivs[i] = ntohl(yDivs[i]);
    160     }
    161     paddingLeft = ntohl(paddingLeft);
    162     paddingRight = ntohl(paddingRight);
    163     paddingTop = ntohl(paddingTop);
    164     paddingBottom = ntohl(paddingBottom);
    165     for (int i=0; i<numColors; i++) {
    166         colors[i] = ntohl(colors[i]);
    167     }
    168 }
    169 
    170 size_t Res_png_9patch::serializedSize()
    171 {
    172     // The size of this struct is 32 bytes on the 32-bit target system
    173     // 4 * int8_t
    174     // 4 * int32_t
    175     // 3 * pointer
    176     return 32
    177             + numXDivs * sizeof(int32_t)
    178             + numYDivs * sizeof(int32_t)
    179             + numColors * sizeof(uint32_t);
    180 }
    181 
    182 void* Res_png_9patch::serialize()
    183 {
    184     // Use calloc since we're going to leave a few holes in the data
    185     // and want this to run cleanly under valgrind
    186     void* newData = calloc(1, serializedSize());
    187     serialize(newData);
    188     return newData;
    189 }
    190 
    191 void Res_png_9patch::serialize(void * outData)
    192 {
    193     char* data = (char*) outData;
    194     memmove(data, &wasDeserialized, 4);     // copy  wasDeserialized, numXDivs, numYDivs, numColors
    195     memmove(data + 12, &paddingLeft, 16);   // copy paddingXXXX
    196     data += 32;
    197 
    198     memmove(data, this->xDivs, numXDivs * sizeof(int32_t));
    199     data +=  numXDivs * sizeof(int32_t);
    200     memmove(data, this->yDivs, numYDivs * sizeof(int32_t));
    201     data +=  numYDivs * sizeof(int32_t);
    202     memmove(data, this->colors, numColors * sizeof(uint32_t));
    203 }
    204 
    205 static void deserializeInternal(const void* inData, Res_png_9patch* outData) {
    206     char* patch = (char*) inData;
    207     if (inData != outData) {
    208         memmove(&outData->wasDeserialized, patch, 4);     // copy  wasDeserialized, numXDivs, numYDivs, numColors
    209         memmove(&outData->paddingLeft, patch + 12, 4);     // copy  wasDeserialized, numXDivs, numYDivs, numColors
    210     }
    211     outData->wasDeserialized = true;
    212     char* data = (char*)outData;
    213     data +=  sizeof(Res_png_9patch);
    214     outData->xDivs = (int32_t*) data;
    215     data +=  outData->numXDivs * sizeof(int32_t);
    216     outData->yDivs = (int32_t*) data;
    217     data +=  outData->numYDivs * sizeof(int32_t);
    218     outData->colors = (uint32_t*) data;
    219 }
    220 
    221 static bool assertIdmapHeader(const uint32_t* map, size_t sizeBytes)
    222 {
    223     if (sizeBytes < ResTable::IDMAP_HEADER_SIZE_BYTES) {
    224         ALOGW("idmap assertion failed: size=%d bytes\n", (int)sizeBytes);
    225         return false;
    226     }
    227     if (*map != htodl(IDMAP_MAGIC)) { // htodl: map data expected to be in correct endianess
    228         ALOGW("idmap assertion failed: invalid magic found (is 0x%08x, expected 0x%08x)\n",
    229              *map, htodl(IDMAP_MAGIC));
    230         return false;
    231     }
    232     return true;
    233 }
    234 
    235 static status_t idmapLookup(const uint32_t* map, size_t sizeBytes, uint32_t key, uint32_t* outValue)
    236 {
    237     // see README for details on the format of map
    238     if (!assertIdmapHeader(map, sizeBytes)) {
    239         return UNKNOWN_ERROR;
    240     }
    241     map = map + IDMAP_HEADER_SIZE; // skip ahead to data segment
    242     // size of data block, in uint32_t
    243     const size_t size = (sizeBytes - ResTable::IDMAP_HEADER_SIZE_BYTES) / sizeof(uint32_t);
    244     const uint32_t type = Res_GETTYPE(key) + 1; // add one, idmap stores "public" type id
    245     const uint32_t entry = Res_GETENTRY(key);
    246     const uint32_t typeCount = *map;
    247 
    248     if (type > typeCount) {
    249         ALOGW("Resource ID map: type=%d exceeds number of types=%d\n", type, typeCount);
    250         return UNKNOWN_ERROR;
    251     }
    252     if (typeCount > size) {
    253         ALOGW("Resource ID map: number of types=%d exceeds size of map=%d\n", typeCount, (int)size);
    254         return UNKNOWN_ERROR;
    255     }
    256     const uint32_t typeOffset = map[type];
    257     if (typeOffset == 0) {
    258         *outValue = 0;
    259         return NO_ERROR;
    260     }
    261     if (typeOffset + 1 > size) {
    262         ALOGW("Resource ID map: type offset=%d exceeds reasonable value, size of map=%d\n",
    263              typeOffset, (int)size);
    264         return UNKNOWN_ERROR;
    265     }
    266     const uint32_t entryCount = map[typeOffset];
    267     const uint32_t entryOffset = map[typeOffset + 1];
    268     if (entryCount == 0 || entry < entryOffset || entry - entryOffset > entryCount - 1) {
    269         *outValue = 0;
    270         return NO_ERROR;
    271     }
    272     const uint32_t index = typeOffset + 2 + entry - entryOffset;
    273     if (index > size) {
    274         ALOGW("Resource ID map: entry index=%d exceeds size of map=%d\n", index, (int)size);
    275         *outValue = 0;
    276         return NO_ERROR;
    277     }
    278     *outValue = map[index];
    279 
    280     return NO_ERROR;
    281 }
    282 
    283 static status_t getIdmapPackageId(const uint32_t* map, size_t mapSize, uint32_t *outId)
    284 {
    285     if (!assertIdmapHeader(map, mapSize)) {
    286         return UNKNOWN_ERROR;
    287     }
    288     const uint32_t* p = map + IDMAP_HEADER_SIZE + 1;
    289     while (*p == 0) {
    290         ++p;
    291     }
    292     *outId = (map[*p + IDMAP_HEADER_SIZE + 2] >> 24) & 0x000000ff;
    293     return NO_ERROR;
    294 }
    295 
    296 Res_png_9patch* Res_png_9patch::deserialize(const void* inData)
    297 {
    298     if (sizeof(void*) != sizeof(int32_t)) {
    299         ALOGE("Cannot deserialize on non 32-bit system\n");
    300         return NULL;
    301     }
    302     deserializeInternal(inData, (Res_png_9patch*) inData);
    303     return (Res_png_9patch*) inData;
    304 }
    305 
    306 // --------------------------------------------------------------------
    307 // --------------------------------------------------------------------
    308 // --------------------------------------------------------------------
    309 
    310 ResStringPool::ResStringPool()
    311     : mError(NO_INIT), mOwnedData(NULL), mHeader(NULL), mCache(NULL)
    312 {
    313 }
    314 
    315 ResStringPool::ResStringPool(const void* data, size_t size, bool copyData)
    316     : mError(NO_INIT), mOwnedData(NULL), mHeader(NULL), mCache(NULL)
    317 {
    318     setTo(data, size, copyData);
    319 }
    320 
    321 ResStringPool::~ResStringPool()
    322 {
    323     uninit();
    324 }
    325 
    326 status_t ResStringPool::setTo(const void* data, size_t size, bool copyData)
    327 {
    328     if (!data || !size) {
    329         return (mError=BAD_TYPE);
    330     }
    331 
    332     uninit();
    333 
    334     const bool notDeviceEndian = htods(0xf0) != 0xf0;
    335 
    336     if (copyData || notDeviceEndian) {
    337         mOwnedData = malloc(size);
    338         if (mOwnedData == NULL) {
    339             return (mError=NO_MEMORY);
    340         }
    341         memcpy(mOwnedData, data, size);
    342         data = mOwnedData;
    343     }
    344 
    345     mHeader = (const ResStringPool_header*)data;
    346 
    347     if (notDeviceEndian) {
    348         ResStringPool_header* h = const_cast<ResStringPool_header*>(mHeader);
    349         h->header.headerSize = dtohs(mHeader->header.headerSize);
    350         h->header.type = dtohs(mHeader->header.type);
    351         h->header.size = dtohl(mHeader->header.size);
    352         h->stringCount = dtohl(mHeader->stringCount);
    353         h->styleCount = dtohl(mHeader->styleCount);
    354         h->flags = dtohl(mHeader->flags);
    355         h->stringsStart = dtohl(mHeader->stringsStart);
    356         h->stylesStart = dtohl(mHeader->stylesStart);
    357     }
    358 
    359     if (mHeader->header.headerSize > mHeader->header.size
    360             || mHeader->header.size > size) {
    361         ALOGW("Bad string block: header size %d or total size %d is larger than data size %d\n",
    362                 (int)mHeader->header.headerSize, (int)mHeader->header.size, (int)size);
    363         return (mError=BAD_TYPE);
    364     }
    365     mSize = mHeader->header.size;
    366     mEntries = (const uint32_t*)
    367         (((const uint8_t*)data)+mHeader->header.headerSize);
    368 
    369     if (mHeader->stringCount > 0) {
    370         if ((mHeader->stringCount*sizeof(uint32_t) < mHeader->stringCount)  // uint32 overflow?
    371             || (mHeader->header.headerSize+(mHeader->stringCount*sizeof(uint32_t)))
    372                 > size) {
    373             ALOGW("Bad string block: entry of %d items extends past data size %d\n",
    374                     (int)(mHeader->header.headerSize+(mHeader->stringCount*sizeof(uint32_t))),
    375                     (int)size);
    376             return (mError=BAD_TYPE);
    377         }
    378 
    379         size_t charSize;
    380         if (mHeader->flags&ResStringPool_header::UTF8_FLAG) {
    381             charSize = sizeof(uint8_t);
    382             mCache = (char16_t**)calloc(mHeader->stringCount, sizeof(char16_t**));
    383         } else {
    384             charSize = sizeof(char16_t);
    385         }
    386 
    387         mStrings = (const void*)
    388             (((const uint8_t*)data)+mHeader->stringsStart);
    389         if (mHeader->stringsStart >= (mHeader->header.size-sizeof(uint16_t))) {
    390             ALOGW("Bad string block: string pool starts at %d, after total size %d\n",
    391                     (int)mHeader->stringsStart, (int)mHeader->header.size);
    392             return (mError=BAD_TYPE);
    393         }
    394         if (mHeader->styleCount == 0) {
    395             mStringPoolSize =
    396                 (mHeader->header.size-mHeader->stringsStart)/charSize;
    397         } else {
    398             // check invariant: styles starts before end of data
    399             if (mHeader->stylesStart >= (mHeader->header.size-sizeof(uint16_t))) {
    400                 ALOGW("Bad style block: style block starts at %d past data size of %d\n",
    401                     (int)mHeader->stylesStart, (int)mHeader->header.size);
    402                 return (mError=BAD_TYPE);
    403             }
    404             // check invariant: styles follow the strings
    405             if (mHeader->stylesStart <= mHeader->stringsStart) {
    406                 ALOGW("Bad style block: style block starts at %d, before strings at %d\n",
    407                     (int)mHeader->stylesStart, (int)mHeader->stringsStart);
    408                 return (mError=BAD_TYPE);
    409             }
    410             mStringPoolSize =
    411                 (mHeader->stylesStart-mHeader->stringsStart)/charSize;
    412         }
    413 
    414         // check invariant: stringCount > 0 requires a string pool to exist
    415         if (mStringPoolSize == 0) {
    416             ALOGW("Bad string block: stringCount is %d but pool size is 0\n", (int)mHeader->stringCount);
    417             return (mError=BAD_TYPE);
    418         }
    419 
    420         if (notDeviceEndian) {
    421             size_t i;
    422             uint32_t* e = const_cast<uint32_t*>(mEntries);
    423             for (i=0; i<mHeader->stringCount; i++) {
    424                 e[i] = dtohl(mEntries[i]);
    425             }
    426             if (!(mHeader->flags&ResStringPool_header::UTF8_FLAG)) {
    427                 const char16_t* strings = (const char16_t*)mStrings;
    428                 char16_t* s = const_cast<char16_t*>(strings);
    429                 for (i=0; i<mStringPoolSize; i++) {
    430                     s[i] = dtohs(strings[i]);
    431                 }
    432             }
    433         }
    434 
    435         if ((mHeader->flags&ResStringPool_header::UTF8_FLAG &&
    436                 ((uint8_t*)mStrings)[mStringPoolSize-1] != 0) ||
    437                 (!mHeader->flags&ResStringPool_header::UTF8_FLAG &&
    438                 ((char16_t*)mStrings)[mStringPoolSize-1] != 0)) {
    439             ALOGW("Bad string block: last string is not 0-terminated\n");
    440             return (mError=BAD_TYPE);
    441         }
    442     } else {
    443         mStrings = NULL;
    444         mStringPoolSize = 0;
    445     }
    446 
    447     if (mHeader->styleCount > 0) {
    448         mEntryStyles = mEntries + mHeader->stringCount;
    449         // invariant: integer overflow in calculating mEntryStyles
    450         if (mEntryStyles < mEntries) {
    451             ALOGW("Bad string block: integer overflow finding styles\n");
    452             return (mError=BAD_TYPE);
    453         }
    454 
    455         if (((const uint8_t*)mEntryStyles-(const uint8_t*)mHeader) > (int)size) {
    456             ALOGW("Bad string block: entry of %d styles extends past data size %d\n",
    457                     (int)((const uint8_t*)mEntryStyles-(const uint8_t*)mHeader),
    458                     (int)size);
    459             return (mError=BAD_TYPE);
    460         }
    461         mStyles = (const uint32_t*)
    462             (((const uint8_t*)data)+mHeader->stylesStart);
    463         if (mHeader->stylesStart >= mHeader->header.size) {
    464             ALOGW("Bad string block: style pool starts %d, after total size %d\n",
    465                     (int)mHeader->stylesStart, (int)mHeader->header.size);
    466             return (mError=BAD_TYPE);
    467         }
    468         mStylePoolSize =
    469             (mHeader->header.size-mHeader->stylesStart)/sizeof(uint32_t);
    470 
    471         if (notDeviceEndian) {
    472             size_t i;
    473             uint32_t* e = const_cast<uint32_t*>(mEntryStyles);
    474             for (i=0; i<mHeader->styleCount; i++) {
    475                 e[i] = dtohl(mEntryStyles[i]);
    476             }
    477             uint32_t* s = const_cast<uint32_t*>(mStyles);
    478             for (i=0; i<mStylePoolSize; i++) {
    479                 s[i] = dtohl(mStyles[i]);
    480             }
    481         }
    482 
    483         const ResStringPool_span endSpan = {
    484             { htodl(ResStringPool_span::END) },
    485             htodl(ResStringPool_span::END), htodl(ResStringPool_span::END)
    486         };
    487         if (memcmp(&mStyles[mStylePoolSize-(sizeof(endSpan)/sizeof(uint32_t))],
    488                    &endSpan, sizeof(endSpan)) != 0) {
    489             ALOGW("Bad string block: last style is not 0xFFFFFFFF-terminated\n");
    490             return (mError=BAD_TYPE);
    491         }
    492     } else {
    493         mEntryStyles = NULL;
    494         mStyles = NULL;
    495         mStylePoolSize = 0;
    496     }
    497 
    498     return (mError=NO_ERROR);
    499 }
    500 
    501 status_t ResStringPool::getError() const
    502 {
    503     return mError;
    504 }
    505 
    506 void ResStringPool::uninit()
    507 {
    508     mError = NO_INIT;
    509     if (mOwnedData) {
    510         free(mOwnedData);
    511         mOwnedData = NULL;
    512     }
    513     if (mHeader != NULL && mCache != NULL) {
    514         for (size_t x = 0; x < mHeader->stringCount; x++) {
    515             if (mCache[x] != NULL) {
    516                 free(mCache[x]);
    517                 mCache[x] = NULL;
    518             }
    519         }
    520         free(mCache);
    521         mCache = NULL;
    522     }
    523 }
    524 
    525 /**
    526  * Strings in UTF-16 format have length indicated by a length encoded in the
    527  * stored data. It is either 1 or 2 characters of length data. This allows a
    528  * maximum length of 0x7FFFFFF (2147483647 bytes), but if you're storing that
    529  * much data in a string, you're abusing them.
    530  *
    531  * If the high bit is set, then there are two characters or 4 bytes of length
    532  * data encoded. In that case, drop the high bit of the first character and
    533  * add it together with the next character.
    534  */
    535 static inline size_t
    536 decodeLength(const char16_t** str)
    537 {
    538     size_t len = **str;
    539     if ((len & 0x8000) != 0) {
    540         (*str)++;
    541         len = ((len & 0x7FFF) << 16) | **str;
    542     }
    543     (*str)++;
    544     return len;
    545 }
    546 
    547 /**
    548  * Strings in UTF-8 format have length indicated by a length encoded in the
    549  * stored data. It is either 1 or 2 characters of length data. This allows a
    550  * maximum length of 0x7FFF (32767 bytes), but you should consider storing
    551  * text in another way if you're using that much data in a single string.
    552  *
    553  * If the high bit is set, then there are two characters or 2 bytes of length
    554  * data encoded. In that case, drop the high bit of the first character and
    555  * add it together with the next character.
    556  */
    557 static inline size_t
    558 decodeLength(const uint8_t** str)
    559 {
    560     size_t len = **str;
    561     if ((len & 0x80) != 0) {
    562         (*str)++;
    563         len = ((len & 0x7F) << 8) | **str;
    564     }
    565     (*str)++;
    566     return len;
    567 }
    568 
    569 const uint16_t* ResStringPool::stringAt(size_t idx, size_t* u16len) const
    570 {
    571     if (mError == NO_ERROR && idx < mHeader->stringCount) {
    572         const bool isUTF8 = (mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0;
    573         const uint32_t off = mEntries[idx]/(isUTF8?sizeof(char):sizeof(char16_t));
    574         if (off < (mStringPoolSize-1)) {
    575             if (!isUTF8) {
    576                 const char16_t* strings = (char16_t*)mStrings;
    577                 const char16_t* str = strings+off;
    578 
    579                 *u16len = decodeLength(&str);
    580                 if ((uint32_t)(str+*u16len-strings) < mStringPoolSize) {
    581                     return str;
    582                 } else {
    583                     ALOGW("Bad string block: string #%d extends to %d, past end at %d\n",
    584                             (int)idx, (int)(str+*u16len-strings), (int)mStringPoolSize);
    585                 }
    586             } else {
    587                 const uint8_t* strings = (uint8_t*)mStrings;
    588                 const uint8_t* u8str = strings+off;
    589 
    590                 *u16len = decodeLength(&u8str);
    591                 size_t u8len = decodeLength(&u8str);
    592 
    593                 // encLen must be less than 0x7FFF due to encoding.
    594                 if ((uint32_t)(u8str+u8len-strings) < mStringPoolSize) {
    595                     AutoMutex lock(mDecodeLock);
    596 
    597                     if (mCache[idx] != NULL) {
    598                         return mCache[idx];
    599                     }
    600 
    601                     ssize_t actualLen = utf8_to_utf16_length(u8str, u8len);
    602                     if (actualLen < 0 || (size_t)actualLen != *u16len) {
    603                         ALOGW("Bad string block: string #%lld decoded length is not correct "
    604                                 "%lld vs %llu\n",
    605                                 (long long)idx, (long long)actualLen, (long long)*u16len);
    606                         return NULL;
    607                     }
    608 
    609                     char16_t *u16str = (char16_t *)calloc(*u16len+1, sizeof(char16_t));
    610                     if (!u16str) {
    611                         ALOGW("No memory when trying to allocate decode cache for string #%d\n",
    612                                 (int)idx);
    613                         return NULL;
    614                     }
    615 
    616                     utf8_to_utf16(u8str, u8len, u16str);
    617                     mCache[idx] = u16str;
    618                     return u16str;
    619                 } else {
    620                     ALOGW("Bad string block: string #%lld extends to %lld, past end at %lld\n",
    621                             (long long)idx, (long long)(u8str+u8len-strings),
    622                             (long long)mStringPoolSize);
    623                 }
    624             }
    625         } else {
    626             ALOGW("Bad string block: string #%d entry is at %d, past end at %d\n",
    627                     (int)idx, (int)(off*sizeof(uint16_t)),
    628                     (int)(mStringPoolSize*sizeof(uint16_t)));
    629         }
    630     }
    631     return NULL;
    632 }
    633 
    634 const char* ResStringPool::string8At(size_t idx, size_t* outLen) const
    635 {
    636     if (mError == NO_ERROR && idx < mHeader->stringCount) {
    637         const bool isUTF8 = (mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0;
    638         const uint32_t off = mEntries[idx]/(isUTF8?sizeof(char):sizeof(char16_t));
    639         if (off < (mStringPoolSize-1)) {
    640             if (isUTF8) {
    641                 const uint8_t* strings = (uint8_t*)mStrings;
    642                 const uint8_t* str = strings+off;
    643                 *outLen = decodeLength(&str);
    644                 size_t encLen = decodeLength(&str);
    645                 if ((uint32_t)(str+encLen-strings) < mStringPoolSize) {
    646                     return (const char*)str;
    647                 } else {
    648                     ALOGW("Bad string block: string #%d extends to %d, past end at %d\n",
    649                             (int)idx, (int)(str+encLen-strings), (int)mStringPoolSize);
    650                 }
    651             }
    652         } else {
    653             ALOGW("Bad string block: string #%d entry is at %d, past end at %d\n",
    654                     (int)idx, (int)(off*sizeof(uint16_t)),
    655                     (int)(mStringPoolSize*sizeof(uint16_t)));
    656         }
    657     }
    658     return NULL;
    659 }
    660 
    661 const String8 ResStringPool::string8ObjectAt(size_t idx) const
    662 {
    663     size_t len;
    664     const char *str = (const char*)string8At(idx, &len);
    665     if (str != NULL) {
    666         return String8(str);
    667     }
    668     return String8(stringAt(idx, &len));
    669 }
    670 
    671 const ResStringPool_span* ResStringPool::styleAt(const ResStringPool_ref& ref) const
    672 {
    673     return styleAt(ref.index);
    674 }
    675 
    676 const ResStringPool_span* ResStringPool::styleAt(size_t idx) const
    677 {
    678     if (mError == NO_ERROR && idx < mHeader->styleCount) {
    679         const uint32_t off = (mEntryStyles[idx]/sizeof(uint32_t));
    680         if (off < mStylePoolSize) {
    681             return (const ResStringPool_span*)(mStyles+off);
    682         } else {
    683             ALOGW("Bad string block: style #%d entry is at %d, past end at %d\n",
    684                     (int)idx, (int)(off*sizeof(uint32_t)),
    685                     (int)(mStylePoolSize*sizeof(uint32_t)));
    686         }
    687     }
    688     return NULL;
    689 }
    690 
    691 ssize_t ResStringPool::indexOfString(const char16_t* str, size_t strLen) const
    692 {
    693     if (mError != NO_ERROR) {
    694         return mError;
    695     }
    696 
    697     size_t len;
    698 
    699     // TODO optimize searching for UTF-8 strings taking into account
    700     // the cache fill to determine when to convert the searched-for
    701     // string key to UTF-8.
    702 
    703     if (mHeader->flags&ResStringPool_header::SORTED_FLAG) {
    704         // Do a binary search for the string...
    705         ssize_t l = 0;
    706         ssize_t h = mHeader->stringCount-1;
    707 
    708         ssize_t mid;
    709         while (l <= h) {
    710             mid = l + (h - l)/2;
    711             const char16_t* s = stringAt(mid, &len);
    712             int c = s ? strzcmp16(s, len, str, strLen) : -1;
    713             POOL_NOISY(printf("Looking for %s, at %s, cmp=%d, l/mid/h=%d/%d/%d\n",
    714                          String8(str).string(),
    715                          String8(s).string(),
    716                          c, (int)l, (int)mid, (int)h));
    717             if (c == 0) {
    718                 return mid;
    719             } else if (c < 0) {
    720                 l = mid + 1;
    721             } else {
    722                 h = mid - 1;
    723             }
    724         }
    725     } else {
    726         // It is unusual to get the ID from an unsorted string block...
    727         // most often this happens because we want to get IDs for style
    728         // span tags; since those always appear at the end of the string
    729         // block, start searching at the back.
    730         for (int i=mHeader->stringCount-1; i>=0; i--) {
    731             const char16_t* s = stringAt(i, &len);
    732             POOL_NOISY(printf("Looking for %s, at %s, i=%d\n",
    733                          String8(str, strLen).string(),
    734                          String8(s).string(),
    735                          i));
    736             if (s && strzcmp16(s, len, str, strLen) == 0) {
    737                 return i;
    738             }
    739         }
    740     }
    741 
    742     return NAME_NOT_FOUND;
    743 }
    744 
    745 size_t ResStringPool::size() const
    746 {
    747     return (mError == NO_ERROR) ? mHeader->stringCount : 0;
    748 }
    749 
    750 size_t ResStringPool::styleCount() const
    751 {
    752     return (mError == NO_ERROR) ? mHeader->styleCount : 0;
    753 }
    754 
    755 size_t ResStringPool::bytes() const
    756 {
    757     return (mError == NO_ERROR) ? mHeader->header.size : 0;
    758 }
    759 
    760 bool ResStringPool::isSorted() const
    761 {
    762     return (mHeader->flags&ResStringPool_header::SORTED_FLAG)!=0;
    763 }
    764 
    765 bool ResStringPool::isUTF8() const
    766 {
    767     return (mHeader->flags&ResStringPool_header::UTF8_FLAG)!=0;
    768 }
    769 
    770 // --------------------------------------------------------------------
    771 // --------------------------------------------------------------------
    772 // --------------------------------------------------------------------
    773 
    774 ResXMLParser::ResXMLParser(const ResXMLTree& tree)
    775     : mTree(tree), mEventCode(BAD_DOCUMENT)
    776 {
    777 }
    778 
    779 void ResXMLParser::restart()
    780 {
    781     mCurNode = NULL;
    782     mEventCode = mTree.mError == NO_ERROR ? START_DOCUMENT : BAD_DOCUMENT;
    783 }
    784 const ResStringPool& ResXMLParser::getStrings() const
    785 {
    786     return mTree.mStrings;
    787 }
    788 
    789 ResXMLParser::event_code_t ResXMLParser::getEventType() const
    790 {
    791     return mEventCode;
    792 }
    793 
    794 ResXMLParser::event_code_t ResXMLParser::next()
    795 {
    796     if (mEventCode == START_DOCUMENT) {
    797         mCurNode = mTree.mRootNode;
    798         mCurExt = mTree.mRootExt;
    799         return (mEventCode=mTree.mRootCode);
    800     } else if (mEventCode >= FIRST_CHUNK_CODE) {
    801         return nextNode();
    802     }
    803     return mEventCode;
    804 }
    805 
    806 int32_t ResXMLParser::getCommentID() const
    807 {
    808     return mCurNode != NULL ? dtohl(mCurNode->comment.index) : -1;
    809 }
    810 
    811 const uint16_t* ResXMLParser::getComment(size_t* outLen) const
    812 {
    813     int32_t id = getCommentID();
    814     return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
    815 }
    816 
    817 uint32_t ResXMLParser::getLineNumber() const
    818 {
    819     return mCurNode != NULL ? dtohl(mCurNode->lineNumber) : -1;
    820 }
    821 
    822 int32_t ResXMLParser::getTextID() const
    823 {
    824     if (mEventCode == TEXT) {
    825         return dtohl(((const ResXMLTree_cdataExt*)mCurExt)->data.index);
    826     }
    827     return -1;
    828 }
    829 
    830 const uint16_t* ResXMLParser::getText(size_t* outLen) const
    831 {
    832     int32_t id = getTextID();
    833     return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
    834 }
    835 
    836 ssize_t ResXMLParser::getTextValue(Res_value* outValue) const
    837 {
    838     if (mEventCode == TEXT) {
    839         outValue->copyFrom_dtoh(((const ResXMLTree_cdataExt*)mCurExt)->typedData);
    840         return sizeof(Res_value);
    841     }
    842     return BAD_TYPE;
    843 }
    844 
    845 int32_t ResXMLParser::getNamespacePrefixID() const
    846 {
    847     if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) {
    848         return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->prefix.index);
    849     }
    850     return -1;
    851 }
    852 
    853 const uint16_t* ResXMLParser::getNamespacePrefix(size_t* outLen) const
    854 {
    855     int32_t id = getNamespacePrefixID();
    856     //printf("prefix=%d  event=%p\n", id, mEventCode);
    857     return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
    858 }
    859 
    860 int32_t ResXMLParser::getNamespaceUriID() const
    861 {
    862     if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) {
    863         return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->uri.index);
    864     }
    865     return -1;
    866 }
    867 
    868 const uint16_t* ResXMLParser::getNamespaceUri(size_t* outLen) const
    869 {
    870     int32_t id = getNamespaceUriID();
    871     //printf("uri=%d  event=%p\n", id, mEventCode);
    872     return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
    873 }
    874 
    875 int32_t ResXMLParser::getElementNamespaceID() const
    876 {
    877     if (mEventCode == START_TAG) {
    878         return dtohl(((const ResXMLTree_attrExt*)mCurExt)->ns.index);
    879     }
    880     if (mEventCode == END_TAG) {
    881         return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->ns.index);
    882     }
    883     return -1;
    884 }
    885 
    886 const uint16_t* ResXMLParser::getElementNamespace(size_t* outLen) const
    887 {
    888     int32_t id = getElementNamespaceID();
    889     return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
    890 }
    891 
    892 int32_t ResXMLParser::getElementNameID() const
    893 {
    894     if (mEventCode == START_TAG) {
    895         return dtohl(((const ResXMLTree_attrExt*)mCurExt)->name.index);
    896     }
    897     if (mEventCode == END_TAG) {
    898         return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->name.index);
    899     }
    900     return -1;
    901 }
    902 
    903 const uint16_t* ResXMLParser::getElementName(size_t* outLen) const
    904 {
    905     int32_t id = getElementNameID();
    906     return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
    907 }
    908 
    909 size_t ResXMLParser::getAttributeCount() const
    910 {
    911     if (mEventCode == START_TAG) {
    912         return dtohs(((const ResXMLTree_attrExt*)mCurExt)->attributeCount);
    913     }
    914     return 0;
    915 }
    916 
    917 int32_t ResXMLParser::getAttributeNamespaceID(size_t idx) const
    918 {
    919     if (mEventCode == START_TAG) {
    920         const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
    921         if (idx < dtohs(tag->attributeCount)) {
    922             const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
    923                 (((const uint8_t*)tag)
    924                  + dtohs(tag->attributeStart)
    925                  + (dtohs(tag->attributeSize)*idx));
    926             return dtohl(attr->ns.index);
    927         }
    928     }
    929     return -2;
    930 }
    931 
    932 const uint16_t* ResXMLParser::getAttributeNamespace(size_t idx, size_t* outLen) const
    933 {
    934     int32_t id = getAttributeNamespaceID(idx);
    935     //printf("attribute namespace=%d  idx=%d  event=%p\n", id, idx, mEventCode);
    936     //XML_NOISY(printf("getAttributeNamespace 0x%x=0x%x\n", idx, id));
    937     return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
    938 }
    939 
    940 int32_t ResXMLParser::getAttributeNameID(size_t idx) const
    941 {
    942     if (mEventCode == START_TAG) {
    943         const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
    944         if (idx < dtohs(tag->attributeCount)) {
    945             const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
    946                 (((const uint8_t*)tag)
    947                  + dtohs(tag->attributeStart)
    948                  + (dtohs(tag->attributeSize)*idx));
    949             return dtohl(attr->name.index);
    950         }
    951     }
    952     return -1;
    953 }
    954 
    955 const uint16_t* ResXMLParser::getAttributeName(size_t idx, size_t* outLen) const
    956 {
    957     int32_t id = getAttributeNameID(idx);
    958     //printf("attribute name=%d  idx=%d  event=%p\n", id, idx, mEventCode);
    959     //XML_NOISY(printf("getAttributeName 0x%x=0x%x\n", idx, id));
    960     return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
    961 }
    962 
    963 uint32_t ResXMLParser::getAttributeNameResID(size_t idx) const
    964 {
    965     int32_t id = getAttributeNameID(idx);
    966     if (id >= 0 && (size_t)id < mTree.mNumResIds) {
    967         return dtohl(mTree.mResIds[id]);
    968     }
    969     return 0;
    970 }
    971 
    972 int32_t ResXMLParser::getAttributeValueStringID(size_t idx) const
    973 {
    974     if (mEventCode == START_TAG) {
    975         const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
    976         if (idx < dtohs(tag->attributeCount)) {
    977             const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
    978                 (((const uint8_t*)tag)
    979                  + dtohs(tag->attributeStart)
    980                  + (dtohs(tag->attributeSize)*idx));
    981             return dtohl(attr->rawValue.index);
    982         }
    983     }
    984     return -1;
    985 }
    986 
    987 const uint16_t* ResXMLParser::getAttributeStringValue(size_t idx, size_t* outLen) const
    988 {
    989     int32_t id = getAttributeValueStringID(idx);
    990     //XML_NOISY(printf("getAttributeValue 0x%x=0x%x\n", idx, id));
    991     return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
    992 }
    993 
    994 int32_t ResXMLParser::getAttributeDataType(size_t idx) const
    995 {
    996     if (mEventCode == START_TAG) {
    997         const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
    998         if (idx < dtohs(tag->attributeCount)) {
    999             const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
   1000                 (((const uint8_t*)tag)
   1001                  + dtohs(tag->attributeStart)
   1002                  + (dtohs(tag->attributeSize)*idx));
   1003             return attr->typedValue.dataType;
   1004         }
   1005     }
   1006     return Res_value::TYPE_NULL;
   1007 }
   1008 
   1009 int32_t ResXMLParser::getAttributeData(size_t idx) const
   1010 {
   1011     if (mEventCode == START_TAG) {
   1012         const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
   1013         if (idx < dtohs(tag->attributeCount)) {
   1014             const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
   1015                 (((const uint8_t*)tag)
   1016                  + dtohs(tag->attributeStart)
   1017                  + (dtohs(tag->attributeSize)*idx));
   1018             return dtohl(attr->typedValue.data);
   1019         }
   1020     }
   1021     return 0;
   1022 }
   1023 
   1024 ssize_t ResXMLParser::getAttributeValue(size_t idx, Res_value* outValue) const
   1025 {
   1026     if (mEventCode == START_TAG) {
   1027         const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
   1028         if (idx < dtohs(tag->attributeCount)) {
   1029             const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
   1030                 (((const uint8_t*)tag)
   1031                  + dtohs(tag->attributeStart)
   1032                  + (dtohs(tag->attributeSize)*idx));
   1033             outValue->copyFrom_dtoh(attr->typedValue);
   1034             return sizeof(Res_value);
   1035         }
   1036     }
   1037     return BAD_TYPE;
   1038 }
   1039 
   1040 ssize_t ResXMLParser::indexOfAttribute(const char* ns, const char* attr) const
   1041 {
   1042     String16 nsStr(ns != NULL ? ns : "");
   1043     String16 attrStr(attr);
   1044     return indexOfAttribute(ns ? nsStr.string() : NULL, ns ? nsStr.size() : 0,
   1045                             attrStr.string(), attrStr.size());
   1046 }
   1047 
   1048 ssize_t ResXMLParser::indexOfAttribute(const char16_t* ns, size_t nsLen,
   1049                                        const char16_t* attr, size_t attrLen) const
   1050 {
   1051     if (mEventCode == START_TAG) {
   1052         const size_t N = getAttributeCount();
   1053         for (size_t i=0; i<N; i++) {
   1054             size_t curNsLen, curAttrLen;
   1055             const char16_t* curNs = getAttributeNamespace(i, &curNsLen);
   1056             const char16_t* curAttr = getAttributeName(i, &curAttrLen);
   1057             //printf("%d: ns=%p attr=%p curNs=%p curAttr=%p\n",
   1058             //       i, ns, attr, curNs, curAttr);
   1059             //printf(" --> attr=%s, curAttr=%s\n",
   1060             //       String8(attr).string(), String8(curAttr).string());
   1061             if (attr && curAttr && (strzcmp16(attr, attrLen, curAttr, curAttrLen) == 0)) {
   1062                 if (ns == NULL) {
   1063                     if (curNs == NULL) return i;
   1064                 } else if (curNs != NULL) {
   1065                     //printf(" --> ns=%s, curNs=%s\n",
   1066                     //       String8(ns).string(), String8(curNs).string());
   1067                     if (strzcmp16(ns, nsLen, curNs, curNsLen) == 0) return i;
   1068                 }
   1069             }
   1070         }
   1071     }
   1072 
   1073     return NAME_NOT_FOUND;
   1074 }
   1075 
   1076 ssize_t ResXMLParser::indexOfID() const
   1077 {
   1078     if (mEventCode == START_TAG) {
   1079         const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->idIndex);
   1080         if (idx > 0) return (idx-1);
   1081     }
   1082     return NAME_NOT_FOUND;
   1083 }
   1084 
   1085 ssize_t ResXMLParser::indexOfClass() const
   1086 {
   1087     if (mEventCode == START_TAG) {
   1088         const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->classIndex);
   1089         if (idx > 0) return (idx-1);
   1090     }
   1091     return NAME_NOT_FOUND;
   1092 }
   1093 
   1094 ssize_t ResXMLParser::indexOfStyle() const
   1095 {
   1096     if (mEventCode == START_TAG) {
   1097         const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->styleIndex);
   1098         if (idx > 0) return (idx-1);
   1099     }
   1100     return NAME_NOT_FOUND;
   1101 }
   1102 
   1103 ResXMLParser::event_code_t ResXMLParser::nextNode()
   1104 {
   1105     if (mEventCode < 0) {
   1106         return mEventCode;
   1107     }
   1108 
   1109     do {
   1110         const ResXMLTree_node* next = (const ResXMLTree_node*)
   1111             (((const uint8_t*)mCurNode) + dtohl(mCurNode->header.size));
   1112         //ALOGW("Next node: prev=%p, next=%p\n", mCurNode, next);
   1113 
   1114         if (((const uint8_t*)next) >= mTree.mDataEnd) {
   1115             mCurNode = NULL;
   1116             return (mEventCode=END_DOCUMENT);
   1117         }
   1118 
   1119         if (mTree.validateNode(next) != NO_ERROR) {
   1120             mCurNode = NULL;
   1121             return (mEventCode=BAD_DOCUMENT);
   1122         }
   1123 
   1124         mCurNode = next;
   1125         const uint16_t headerSize = dtohs(next->header.headerSize);
   1126         const uint32_t totalSize = dtohl(next->header.size);
   1127         mCurExt = ((const uint8_t*)next) + headerSize;
   1128         size_t minExtSize = 0;
   1129         event_code_t eventCode = (event_code_t)dtohs(next->header.type);
   1130         switch ((mEventCode=eventCode)) {
   1131             case RES_XML_START_NAMESPACE_TYPE:
   1132             case RES_XML_END_NAMESPACE_TYPE:
   1133                 minExtSize = sizeof(ResXMLTree_namespaceExt);
   1134                 break;
   1135             case RES_XML_START_ELEMENT_TYPE:
   1136                 minExtSize = sizeof(ResXMLTree_attrExt);
   1137                 break;
   1138             case RES_XML_END_ELEMENT_TYPE:
   1139                 minExtSize = sizeof(ResXMLTree_endElementExt);
   1140                 break;
   1141             case RES_XML_CDATA_TYPE:
   1142                 minExtSize = sizeof(ResXMLTree_cdataExt);
   1143                 break;
   1144             default:
   1145                 ALOGW("Unknown XML block: header type %d in node at %d\n",
   1146                      (int)dtohs(next->header.type),
   1147                      (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)));
   1148                 continue;
   1149         }
   1150 
   1151         if ((totalSize-headerSize) < minExtSize) {
   1152             ALOGW("Bad XML block: header type 0x%x in node at 0x%x has size %d, need %d\n",
   1153                  (int)dtohs(next->header.type),
   1154                  (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)),
   1155                  (int)(totalSize-headerSize), (int)minExtSize);
   1156             return (mEventCode=BAD_DOCUMENT);
   1157         }
   1158 
   1159         //printf("CurNode=%p, CurExt=%p, headerSize=%d, minExtSize=%d\n",
   1160         //       mCurNode, mCurExt, headerSize, minExtSize);
   1161 
   1162         return eventCode;
   1163     } while (true);
   1164 }
   1165 
   1166 void ResXMLParser::getPosition(ResXMLParser::ResXMLPosition* pos) const
   1167 {
   1168     pos->eventCode = mEventCode;
   1169     pos->curNode = mCurNode;
   1170     pos->curExt = mCurExt;
   1171 }
   1172 
   1173 void ResXMLParser::setPosition(const ResXMLParser::ResXMLPosition& pos)
   1174 {
   1175     mEventCode = pos.eventCode;
   1176     mCurNode = pos.curNode;
   1177     mCurExt = pos.curExt;
   1178 }
   1179 
   1180 
   1181 // --------------------------------------------------------------------
   1182 
   1183 static volatile int32_t gCount = 0;
   1184 
   1185 ResXMLTree::ResXMLTree()
   1186     : ResXMLParser(*this)
   1187     , mError(NO_INIT), mOwnedData(NULL)
   1188 {
   1189     //ALOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1);
   1190     restart();
   1191 }
   1192 
   1193 ResXMLTree::ResXMLTree(const void* data, size_t size, bool copyData)
   1194     : ResXMLParser(*this)
   1195     , mError(NO_INIT), mOwnedData(NULL)
   1196 {
   1197     //ALOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1);
   1198     setTo(data, size, copyData);
   1199 }
   1200 
   1201 ResXMLTree::~ResXMLTree()
   1202 {
   1203     //ALOGI("Destroying ResXMLTree in %p #%d\n", this, android_atomic_dec(&gCount)-1);
   1204     uninit();
   1205 }
   1206 
   1207 status_t ResXMLTree::setTo(const void* data, size_t size, bool copyData)
   1208 {
   1209     uninit();
   1210     mEventCode = START_DOCUMENT;
   1211 
   1212     if (copyData) {
   1213         mOwnedData = malloc(size);
   1214         if (mOwnedData == NULL) {
   1215             return (mError=NO_MEMORY);
   1216         }
   1217         memcpy(mOwnedData, data, size);
   1218         data = mOwnedData;
   1219     }
   1220 
   1221     mHeader = (const ResXMLTree_header*)data;
   1222     mSize = dtohl(mHeader->header.size);
   1223     if (dtohs(mHeader->header.headerSize) > mSize || mSize > size) {
   1224         ALOGW("Bad XML block: header size %d or total size %d is larger than data size %d\n",
   1225              (int)dtohs(mHeader->header.headerSize),
   1226              (int)dtohl(mHeader->header.size), (int)size);
   1227         mError = BAD_TYPE;
   1228         restart();
   1229         return mError;
   1230     }
   1231     mDataEnd = ((const uint8_t*)mHeader) + mSize;
   1232 
   1233     mStrings.uninit();
   1234     mRootNode = NULL;
   1235     mResIds = NULL;
   1236     mNumResIds = 0;
   1237 
   1238     // First look for a couple interesting chunks: the string block
   1239     // and first XML node.
   1240     const ResChunk_header* chunk =
   1241         (const ResChunk_header*)(((const uint8_t*)mHeader) + dtohs(mHeader->header.headerSize));
   1242     const ResChunk_header* lastChunk = chunk;
   1243     while (((const uint8_t*)chunk) < (mDataEnd-sizeof(ResChunk_header)) &&
   1244            ((const uint8_t*)chunk) < (mDataEnd-dtohl(chunk->size))) {
   1245         status_t err = validate_chunk(chunk, sizeof(ResChunk_header), mDataEnd, "XML");
   1246         if (err != NO_ERROR) {
   1247             mError = err;
   1248             goto done;
   1249         }
   1250         const uint16_t type = dtohs(chunk->type);
   1251         const size_t size = dtohl(chunk->size);
   1252         XML_NOISY(printf("Scanning @ %p: type=0x%x, size=0x%x\n",
   1253                      (void*)(((uint32_t)chunk)-((uint32_t)mHeader)), type, size));
   1254         if (type == RES_STRING_POOL_TYPE) {
   1255             mStrings.setTo(chunk, size);
   1256         } else if (type == RES_XML_RESOURCE_MAP_TYPE) {
   1257             mResIds = (const uint32_t*)
   1258                 (((const uint8_t*)chunk)+dtohs(chunk->headerSize));
   1259             mNumResIds = (dtohl(chunk->size)-dtohs(chunk->headerSize))/sizeof(uint32_t);
   1260         } else if (type >= RES_XML_FIRST_CHUNK_TYPE
   1261                    && type <= RES_XML_LAST_CHUNK_TYPE) {
   1262             if (validateNode((const ResXMLTree_node*)chunk) != NO_ERROR) {
   1263                 mError = BAD_TYPE;
   1264                 goto done;
   1265             }
   1266             mCurNode = (const ResXMLTree_node*)lastChunk;
   1267             if (nextNode() == BAD_DOCUMENT) {
   1268                 mError = BAD_TYPE;
   1269                 goto done;
   1270             }
   1271             mRootNode = mCurNode;
   1272             mRootExt = mCurExt;
   1273             mRootCode = mEventCode;
   1274             break;
   1275         } else {
   1276             XML_NOISY(printf("Skipping unknown chunk!\n"));
   1277         }
   1278         lastChunk = chunk;
   1279         chunk = (const ResChunk_header*)
   1280             (((const uint8_t*)chunk) + size);
   1281     }
   1282 
   1283     if (mRootNode == NULL) {
   1284         ALOGW("Bad XML block: no root element node found\n");
   1285         mError = BAD_TYPE;
   1286         goto done;
   1287     }
   1288 
   1289     mError = mStrings.getError();
   1290 
   1291 done:
   1292     restart();
   1293     return mError;
   1294 }
   1295 
   1296 status_t ResXMLTree::getError() const
   1297 {
   1298     return mError;
   1299 }
   1300 
   1301 void ResXMLTree::uninit()
   1302 {
   1303     mError = NO_INIT;
   1304     mStrings.uninit();
   1305     if (mOwnedData) {
   1306         free(mOwnedData);
   1307         mOwnedData = NULL;
   1308     }
   1309     restart();
   1310 }
   1311 
   1312 status_t ResXMLTree::validateNode(const ResXMLTree_node* node) const
   1313 {
   1314     const uint16_t eventCode = dtohs(node->header.type);
   1315 
   1316     status_t err = validate_chunk(
   1317         &node->header, sizeof(ResXMLTree_node),
   1318         mDataEnd, "ResXMLTree_node");
   1319 
   1320     if (err >= NO_ERROR) {
   1321         // Only perform additional validation on START nodes
   1322         if (eventCode != RES_XML_START_ELEMENT_TYPE) {
   1323             return NO_ERROR;
   1324         }
   1325 
   1326         const uint16_t headerSize = dtohs(node->header.headerSize);
   1327         const uint32_t size = dtohl(node->header.size);
   1328         const ResXMLTree_attrExt* attrExt = (const ResXMLTree_attrExt*)
   1329             (((const uint8_t*)node) + headerSize);
   1330         // check for sensical values pulled out of the stream so far...
   1331         if ((size >= headerSize + sizeof(ResXMLTree_attrExt))
   1332                 && ((void*)attrExt > (void*)node)) {
   1333             const size_t attrSize = ((size_t)dtohs(attrExt->attributeSize))
   1334                 * dtohs(attrExt->attributeCount);
   1335             if ((dtohs(attrExt->attributeStart)+attrSize) <= (size-headerSize)) {
   1336                 return NO_ERROR;
   1337             }
   1338             ALOGW("Bad XML block: node attributes use 0x%x bytes, only have 0x%x bytes\n",
   1339                     (unsigned int)(dtohs(attrExt->attributeStart)+attrSize),
   1340                     (unsigned int)(size-headerSize));
   1341         }
   1342         else {
   1343             ALOGW("Bad XML start block: node header size 0x%x, size 0x%x\n",
   1344                 (unsigned int)headerSize, (unsigned int)size);
   1345         }
   1346         return BAD_TYPE;
   1347     }
   1348 
   1349     return err;
   1350 
   1351 #if 0
   1352     const bool isStart = dtohs(node->header.type) == RES_XML_START_ELEMENT_TYPE;
   1353 
   1354     const uint16_t headerSize = dtohs(node->header.headerSize);
   1355     const uint32_t size = dtohl(node->header.size);
   1356 
   1357     if (headerSize >= (isStart ? sizeof(ResXMLTree_attrNode) : sizeof(ResXMLTree_node))) {
   1358         if (size >= headerSize) {
   1359             if (((const uint8_t*)node) <= (mDataEnd-size)) {
   1360                 if (!isStart) {
   1361                     return NO_ERROR;
   1362                 }
   1363                 if ((((size_t)dtohs(node->attributeSize))*dtohs(node->attributeCount))
   1364                         <= (size-headerSize)) {
   1365                     return NO_ERROR;
   1366                 }
   1367                 ALOGW("Bad XML block: node attributes use 0x%x bytes, only have 0x%x bytes\n",
   1368                         ((int)dtohs(node->attributeSize))*dtohs(node->attributeCount),
   1369                         (int)(size-headerSize));
   1370                 return BAD_TYPE;
   1371             }
   1372             ALOGW("Bad XML block: node at 0x%x extends beyond data end 0x%x\n",
   1373                     (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)), (int)mSize);
   1374             return BAD_TYPE;
   1375         }
   1376         ALOGW("Bad XML block: node at 0x%x header size 0x%x smaller than total size 0x%x\n",
   1377                 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)),
   1378                 (int)headerSize, (int)size);
   1379         return BAD_TYPE;
   1380     }
   1381     ALOGW("Bad XML block: node at 0x%x header size 0x%x too small\n",
   1382             (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)),
   1383             (int)headerSize);
   1384     return BAD_TYPE;
   1385 #endif
   1386 }
   1387 
   1388 // --------------------------------------------------------------------
   1389 // --------------------------------------------------------------------
   1390 // --------------------------------------------------------------------
   1391 
   1392 void ResTable_config::copyFromDeviceNoSwap(const ResTable_config& o) {
   1393     const size_t size = dtohl(o.size);
   1394     if (size >= sizeof(ResTable_config)) {
   1395         *this = o;
   1396     } else {
   1397         memcpy(this, &o, size);
   1398         memset(((uint8_t*)this)+size, 0, sizeof(ResTable_config)-size);
   1399     }
   1400 }
   1401 
   1402 void ResTable_config::copyFromDtoH(const ResTable_config& o) {
   1403     copyFromDeviceNoSwap(o);
   1404     size = sizeof(ResTable_config);
   1405     mcc = dtohs(mcc);
   1406     mnc = dtohs(mnc);
   1407     density = dtohs(density);
   1408     screenWidth = dtohs(screenWidth);
   1409     screenHeight = dtohs(screenHeight);
   1410     sdkVersion = dtohs(sdkVersion);
   1411     minorVersion = dtohs(minorVersion);
   1412     smallestScreenWidthDp = dtohs(smallestScreenWidthDp);
   1413     screenWidthDp = dtohs(screenWidthDp);
   1414     screenHeightDp = dtohs(screenHeightDp);
   1415 }
   1416 
   1417 void ResTable_config::swapHtoD() {
   1418     size = htodl(size);
   1419     mcc = htods(mcc);
   1420     mnc = htods(mnc);
   1421     density = htods(density);
   1422     screenWidth = htods(screenWidth);
   1423     screenHeight = htods(screenHeight);
   1424     sdkVersion = htods(sdkVersion);
   1425     minorVersion = htods(minorVersion);
   1426     smallestScreenWidthDp = htods(smallestScreenWidthDp);
   1427     screenWidthDp = htods(screenWidthDp);
   1428     screenHeightDp = htods(screenHeightDp);
   1429 }
   1430 
   1431 int ResTable_config::compare(const ResTable_config& o) const {
   1432     int32_t diff = (int32_t)(imsi - o.imsi);
   1433     if (diff != 0) return diff;
   1434     diff = (int32_t)(locale - o.locale);
   1435     if (diff != 0) return diff;
   1436     diff = (int32_t)(screenType - o.screenType);
   1437     if (diff != 0) return diff;
   1438     diff = (int32_t)(input - o.input);
   1439     if (diff != 0) return diff;
   1440     diff = (int32_t)(screenSize - o.screenSize);
   1441     if (diff != 0) return diff;
   1442     diff = (int32_t)(version - o.version);
   1443     if (diff != 0) return diff;
   1444     diff = (int32_t)(screenLayout - o.screenLayout);
   1445     if (diff != 0) return diff;
   1446     diff = (int32_t)(uiMode - o.uiMode);
   1447     if (diff != 0) return diff;
   1448     diff = (int32_t)(smallestScreenWidthDp - o.smallestScreenWidthDp);
   1449     if (diff != 0) return diff;
   1450     diff = (int32_t)(screenSizeDp - o.screenSizeDp);
   1451     return (int)diff;
   1452 }
   1453 
   1454 int ResTable_config::compareLogical(const ResTable_config& o) const {
   1455     if (mcc != o.mcc) {
   1456         return mcc < o.mcc ? -1 : 1;
   1457     }
   1458     if (mnc != o.mnc) {
   1459         return mnc < o.mnc ? -1 : 1;
   1460     }
   1461     if (language[0] != o.language[0]) {
   1462         return language[0] < o.language[0] ? -1 : 1;
   1463     }
   1464     if (language[1] != o.language[1]) {
   1465         return language[1] < o.language[1] ? -1 : 1;
   1466     }
   1467     if (country[0] != o.country[0]) {
   1468         return country[0] < o.country[0] ? -1 : 1;
   1469     }
   1470     if (country[1] != o.country[1]) {
   1471         return country[1] < o.country[1] ? -1 : 1;
   1472     }
   1473     if ((screenLayout & MASK_LAYOUTDIR) != (o.screenLayout & MASK_LAYOUTDIR)) {
   1474         return (screenLayout & MASK_LAYOUTDIR) < (o.screenLayout & MASK_LAYOUTDIR) ? -1 : 1;
   1475     }
   1476     if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
   1477         return smallestScreenWidthDp < o.smallestScreenWidthDp ? -1 : 1;
   1478     }
   1479     if (screenWidthDp != o.screenWidthDp) {
   1480         return screenWidthDp < o.screenWidthDp ? -1 : 1;
   1481     }
   1482     if (screenHeightDp != o.screenHeightDp) {
   1483         return screenHeightDp < o.screenHeightDp ? -1 : 1;
   1484     }
   1485     if (screenWidth != o.screenWidth) {
   1486         return screenWidth < o.screenWidth ? -1 : 1;
   1487     }
   1488     if (screenHeight != o.screenHeight) {
   1489         return screenHeight < o.screenHeight ? -1 : 1;
   1490     }
   1491     if (density != o.density) {
   1492         return density < o.density ? -1 : 1;
   1493     }
   1494     if (orientation != o.orientation) {
   1495         return orientation < o.orientation ? -1 : 1;
   1496     }
   1497     if (touchscreen != o.touchscreen) {
   1498         return touchscreen < o.touchscreen ? -1 : 1;
   1499     }
   1500     if (input != o.input) {
   1501         return input < o.input ? -1 : 1;
   1502     }
   1503     if (screenLayout != o.screenLayout) {
   1504         return screenLayout < o.screenLayout ? -1 : 1;
   1505     }
   1506     if (uiMode != o.uiMode) {
   1507         return uiMode < o.uiMode ? -1 : 1;
   1508     }
   1509     if (version != o.version) {
   1510         return version < o.version ? -1 : 1;
   1511     }
   1512     return 0;
   1513 }
   1514 
   1515 int ResTable_config::diff(const ResTable_config& o) const {
   1516     int diffs = 0;
   1517     if (mcc != o.mcc) diffs |= CONFIG_MCC;
   1518     if (mnc != o.mnc) diffs |= CONFIG_MNC;
   1519     if (locale != o.locale) diffs |= CONFIG_LOCALE;
   1520     if (orientation != o.orientation) diffs |= CONFIG_ORIENTATION;
   1521     if (density != o.density) diffs |= CONFIG_DENSITY;
   1522     if (touchscreen != o.touchscreen) diffs |= CONFIG_TOUCHSCREEN;
   1523     if (((inputFlags^o.inputFlags)&(MASK_KEYSHIDDEN|MASK_NAVHIDDEN)) != 0)
   1524             diffs |= CONFIG_KEYBOARD_HIDDEN;
   1525     if (keyboard != o.keyboard) diffs |= CONFIG_KEYBOARD;
   1526     if (navigation != o.navigation) diffs |= CONFIG_NAVIGATION;
   1527     if (screenSize != o.screenSize) diffs |= CONFIG_SCREEN_SIZE;
   1528     if (version != o.version) diffs |= CONFIG_VERSION;
   1529     if (screenLayout != o.screenLayout) diffs |= CONFIG_SCREEN_LAYOUT;
   1530     if (uiMode != o.uiMode) diffs |= CONFIG_UI_MODE;
   1531     if (smallestScreenWidthDp != o.smallestScreenWidthDp) diffs |= CONFIG_SMALLEST_SCREEN_SIZE;
   1532     if (screenSizeDp != o.screenSizeDp) diffs |= CONFIG_SCREEN_SIZE;
   1533     return diffs;
   1534 }
   1535 
   1536 bool ResTable_config::isMoreSpecificThan(const ResTable_config& o) const {
   1537     // The order of the following tests defines the importance of one
   1538     // configuration parameter over another.  Those tests first are more
   1539     // important, trumping any values in those following them.
   1540     if (imsi || o.imsi) {
   1541         if (mcc != o.mcc) {
   1542             if (!mcc) return false;
   1543             if (!o.mcc) return true;
   1544         }
   1545 
   1546         if (mnc != o.mnc) {
   1547             if (!mnc) return false;
   1548             if (!o.mnc) return true;
   1549         }
   1550     }
   1551 
   1552     if (locale || o.locale) {
   1553         if (language[0] != o.language[0]) {
   1554             if (!language[0]) return false;
   1555             if (!o.language[0]) return true;
   1556         }
   1557 
   1558         if (country[0] != o.country[0]) {
   1559             if (!country[0]) return false;
   1560             if (!o.country[0]) return true;
   1561         }
   1562     }
   1563 
   1564     if (screenLayout || o.screenLayout) {
   1565         if (((screenLayout^o.screenLayout) & MASK_LAYOUTDIR) != 0) {
   1566             if (!(screenLayout & MASK_LAYOUTDIR)) return false;
   1567             if (!(o.screenLayout & MASK_LAYOUTDIR)) return true;
   1568         }
   1569     }
   1570 
   1571     if (smallestScreenWidthDp || o.smallestScreenWidthDp) {
   1572         if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
   1573             if (!smallestScreenWidthDp) return false;
   1574             if (!o.smallestScreenWidthDp) return true;
   1575         }
   1576     }
   1577 
   1578     if (screenSizeDp || o.screenSizeDp) {
   1579         if (screenWidthDp != o.screenWidthDp) {
   1580             if (!screenWidthDp) return false;
   1581             if (!o.screenWidthDp) return true;
   1582         }
   1583 
   1584         if (screenHeightDp != o.screenHeightDp) {
   1585             if (!screenHeightDp) return false;
   1586             if (!o.screenHeightDp) return true;
   1587         }
   1588     }
   1589 
   1590     if (screenLayout || o.screenLayout) {
   1591         if (((screenLayout^o.screenLayout) & MASK_SCREENSIZE) != 0) {
   1592             if (!(screenLayout & MASK_SCREENSIZE)) return false;
   1593             if (!(o.screenLayout & MASK_SCREENSIZE)) return true;
   1594         }
   1595         if (((screenLayout^o.screenLayout) & MASK_SCREENLONG) != 0) {
   1596             if (!(screenLayout & MASK_SCREENLONG)) return false;
   1597             if (!(o.screenLayout & MASK_SCREENLONG)) return true;
   1598         }
   1599     }
   1600 
   1601     if (orientation != o.orientation) {
   1602         if (!orientation) return false;
   1603         if (!o.orientation) return true;
   1604     }
   1605 
   1606     if (uiMode || o.uiMode) {
   1607         if (((uiMode^o.uiMode) & MASK_UI_MODE_TYPE) != 0) {
   1608             if (!(uiMode & MASK_UI_MODE_TYPE)) return false;
   1609             if (!(o.uiMode & MASK_UI_MODE_TYPE)) return true;
   1610         }
   1611         if (((uiMode^o.uiMode) & MASK_UI_MODE_NIGHT) != 0) {
   1612             if (!(uiMode & MASK_UI_MODE_NIGHT)) return false;
   1613             if (!(o.uiMode & MASK_UI_MODE_NIGHT)) return true;
   1614         }
   1615     }
   1616 
   1617     // density is never 'more specific'
   1618     // as the default just equals 160
   1619 
   1620     if (touchscreen != o.touchscreen) {
   1621         if (!touchscreen) return false;
   1622         if (!o.touchscreen) return true;
   1623     }
   1624 
   1625     if (input || o.input) {
   1626         if (((inputFlags^o.inputFlags) & MASK_KEYSHIDDEN) != 0) {
   1627             if (!(inputFlags & MASK_KEYSHIDDEN)) return false;
   1628             if (!(o.inputFlags & MASK_KEYSHIDDEN)) return true;
   1629         }
   1630 
   1631         if (((inputFlags^o.inputFlags) & MASK_NAVHIDDEN) != 0) {
   1632             if (!(inputFlags & MASK_NAVHIDDEN)) return false;
   1633             if (!(o.inputFlags & MASK_NAVHIDDEN)) return true;
   1634         }
   1635 
   1636         if (keyboard != o.keyboard) {
   1637             if (!keyboard) return false;
   1638             if (!o.keyboard) return true;
   1639         }
   1640 
   1641         if (navigation != o.navigation) {
   1642             if (!navigation) return false;
   1643             if (!o.navigation) return true;
   1644         }
   1645     }
   1646 
   1647     if (screenSize || o.screenSize) {
   1648         if (screenWidth != o.screenWidth) {
   1649             if (!screenWidth) return false;
   1650             if (!o.screenWidth) return true;
   1651         }
   1652 
   1653         if (screenHeight != o.screenHeight) {
   1654             if (!screenHeight) return false;
   1655             if (!o.screenHeight) return true;
   1656         }
   1657     }
   1658 
   1659     if (version || o.version) {
   1660         if (sdkVersion != o.sdkVersion) {
   1661             if (!sdkVersion) return false;
   1662             if (!o.sdkVersion) return true;
   1663         }
   1664 
   1665         if (minorVersion != o.minorVersion) {
   1666             if (!minorVersion) return false;
   1667             if (!o.minorVersion) return true;
   1668         }
   1669     }
   1670     return false;
   1671 }
   1672 
   1673 bool ResTable_config::isBetterThan(const ResTable_config& o,
   1674         const ResTable_config* requested) const {
   1675     if (requested) {
   1676         if (imsi || o.imsi) {
   1677             if ((mcc != o.mcc) && requested->mcc) {
   1678                 return (mcc);
   1679             }
   1680 
   1681             if ((mnc != o.mnc) && requested->mnc) {
   1682                 return (mnc);
   1683             }
   1684         }
   1685 
   1686         if (locale || o.locale) {
   1687             if ((language[0] != o.language[0]) && requested->language[0]) {
   1688                 return (language[0]);
   1689             }
   1690 
   1691             if ((country[0] != o.country[0]) && requested->country[0]) {
   1692                 return (country[0]);
   1693             }
   1694         }
   1695 
   1696         if (screenLayout || o.screenLayout) {
   1697             if (((screenLayout^o.screenLayout) & MASK_LAYOUTDIR) != 0
   1698                     && (requested->screenLayout & MASK_LAYOUTDIR)) {
   1699                 int myLayoutDir = screenLayout & MASK_LAYOUTDIR;
   1700                 int oLayoutDir = o.screenLayout & MASK_LAYOUTDIR;
   1701                 return (myLayoutDir > oLayoutDir);
   1702             }
   1703         }
   1704 
   1705         if (smallestScreenWidthDp || o.smallestScreenWidthDp) {
   1706             // The configuration closest to the actual size is best.
   1707             // We assume that larger configs have already been filtered
   1708             // out at this point.  That means we just want the largest one.
   1709             if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
   1710                 return smallestScreenWidthDp > o.smallestScreenWidthDp;
   1711             }
   1712         }
   1713 
   1714         if (screenSizeDp || o.screenSizeDp) {
   1715             // "Better" is based on the sum of the difference between both
   1716             // width and height from the requested dimensions.  We are
   1717             // assuming the invalid configs (with smaller dimens) have
   1718             // already been filtered.  Note that if a particular dimension
   1719             // is unspecified, we will end up with a large value (the
   1720             // difference between 0 and the requested dimension), which is
   1721             // good since we will prefer a config that has specified a
   1722             // dimension value.
   1723             int myDelta = 0, otherDelta = 0;
   1724             if (requested->screenWidthDp) {
   1725                 myDelta += requested->screenWidthDp - screenWidthDp;
   1726                 otherDelta += requested->screenWidthDp - o.screenWidthDp;
   1727             }
   1728             if (requested->screenHeightDp) {
   1729                 myDelta += requested->screenHeightDp - screenHeightDp;
   1730                 otherDelta += requested->screenHeightDp - o.screenHeightDp;
   1731             }
   1732             //ALOGI("Comparing this %dx%d to other %dx%d in %dx%d: myDelta=%d otherDelta=%d",
   1733             //    screenWidthDp, screenHeightDp, o.screenWidthDp, o.screenHeightDp,
   1734             //    requested->screenWidthDp, requested->screenHeightDp, myDelta, otherDelta);
   1735             if (myDelta != otherDelta) {
   1736                 return myDelta < otherDelta;
   1737             }
   1738         }
   1739 
   1740         if (screenLayout || o.screenLayout) {
   1741             if (((screenLayout^o.screenLayout) & MASK_SCREENSIZE) != 0
   1742                     && (requested->screenLayout & MASK_SCREENSIZE)) {
   1743                 // A little backwards compatibility here: undefined is
   1744                 // considered equivalent to normal.  But only if the
   1745                 // requested size is at least normal; otherwise, small
   1746                 // is better than the default.
   1747                 int mySL = (screenLayout & MASK_SCREENSIZE);
   1748                 int oSL = (o.screenLayout & MASK_SCREENSIZE);
   1749                 int fixedMySL = mySL;
   1750                 int fixedOSL = oSL;
   1751                 if ((requested->screenLayout & MASK_SCREENSIZE) >= SCREENSIZE_NORMAL) {
   1752                     if (fixedMySL == 0) fixedMySL = SCREENSIZE_NORMAL;
   1753                     if (fixedOSL == 0) fixedOSL = SCREENSIZE_NORMAL;
   1754                 }
   1755                 // For screen size, the best match is the one that is
   1756                 // closest to the requested screen size, but not over
   1757                 // (the not over part is dealt with in match() below).
   1758                 if (fixedMySL == fixedOSL) {
   1759                     // If the two are the same, but 'this' is actually
   1760                     // undefined, then the other is really a better match.
   1761                     if (mySL == 0) return false;
   1762                     return true;
   1763                 }
   1764                 if (fixedMySL != fixedOSL) {
   1765                     return fixedMySL > fixedOSL;
   1766                 }
   1767             }
   1768             if (((screenLayout^o.screenLayout) & MASK_SCREENLONG) != 0
   1769                     && (requested->screenLayout & MASK_SCREENLONG)) {
   1770                 return (screenLayout & MASK_SCREENLONG);
   1771             }
   1772         }
   1773 
   1774         if ((orientation != o.orientation) && requested->orientation) {
   1775             return (orientation);
   1776         }
   1777 
   1778         if (uiMode || o.uiMode) {
   1779             if (((uiMode^o.uiMode) & MASK_UI_MODE_TYPE) != 0
   1780                     && (requested->uiMode & MASK_UI_MODE_TYPE)) {
   1781                 return (uiMode & MASK_UI_MODE_TYPE);
   1782             }
   1783             if (((uiMode^o.uiMode) & MASK_UI_MODE_NIGHT) != 0
   1784                     && (requested->uiMode & MASK_UI_MODE_NIGHT)) {
   1785                 return (uiMode & MASK_UI_MODE_NIGHT);
   1786             }
   1787         }
   1788 
   1789         if (screenType || o.screenType) {
   1790             if (density != o.density) {
   1791                 // density is tough.  Any density is potentially useful
   1792                 // because the system will scale it.  Scaling down
   1793                 // is generally better than scaling up.
   1794                 // Default density counts as 160dpi (the system default)
   1795                 // TODO - remove 160 constants
   1796                 int h = (density?density:160);
   1797                 int l = (o.density?o.density:160);
   1798                 bool bImBigger = true;
   1799                 if (l > h) {
   1800                     int t = h;
   1801                     h = l;
   1802                     l = t;
   1803                     bImBigger = false;
   1804                 }
   1805 
   1806                 int reqValue = (requested->density?requested->density:160);
   1807                 if (reqValue >= h) {
   1808                     // requested value higher than both l and h, give h
   1809                     return bImBigger;
   1810                 }
   1811                 if (l >= reqValue) {
   1812                     // requested value lower than both l and h, give l
   1813                     return !bImBigger;
   1814                 }
   1815                 // saying that scaling down is 2x better than up
   1816                 if (((2 * l) - reqValue) * h > reqValue * reqValue) {
   1817                     return !bImBigger;
   1818                 } else {
   1819                     return bImBigger;
   1820                 }
   1821             }
   1822 
   1823             if ((touchscreen != o.touchscreen) && requested->touchscreen) {
   1824                 return (touchscreen);
   1825             }
   1826         }
   1827 
   1828         if (input || o.input) {
   1829             const int keysHidden = inputFlags & MASK_KEYSHIDDEN;
   1830             const int oKeysHidden = o.inputFlags & MASK_KEYSHIDDEN;
   1831             if (keysHidden != oKeysHidden) {
   1832                 const int reqKeysHidden =
   1833                         requested->inputFlags & MASK_KEYSHIDDEN;
   1834                 if (reqKeysHidden) {
   1835 
   1836                     if (!keysHidden) return false;
   1837                     if (!oKeysHidden) return true;
   1838                     // For compatibility, we count KEYSHIDDEN_NO as being
   1839                     // the same as KEYSHIDDEN_SOFT.  Here we disambiguate
   1840                     // these by making an exact match more specific.
   1841                     if (reqKeysHidden == keysHidden) return true;
   1842                     if (reqKeysHidden == oKeysHidden) return false;
   1843                 }
   1844             }
   1845 
   1846             const int navHidden = inputFlags & MASK_NAVHIDDEN;
   1847             const int oNavHidden = o.inputFlags & MASK_NAVHIDDEN;
   1848             if (navHidden != oNavHidden) {
   1849                 const int reqNavHidden =
   1850                         requested->inputFlags & MASK_NAVHIDDEN;
   1851                 if (reqNavHidden) {
   1852 
   1853                     if (!navHidden) return false;
   1854                     if (!oNavHidden) return true;
   1855                 }
   1856             }
   1857 
   1858             if ((keyboard != o.keyboard) && requested->keyboard) {
   1859                 return (keyboard);
   1860             }
   1861 
   1862             if ((navigation != o.navigation) && requested->navigation) {
   1863                 return (navigation);
   1864             }
   1865         }
   1866 
   1867         if (screenSize || o.screenSize) {
   1868             // "Better" is based on the sum of the difference between both
   1869             // width and height from the requested dimensions.  We are
   1870             // assuming the invalid configs (with smaller sizes) have
   1871             // already been filtered.  Note that if a particular dimension
   1872             // is unspecified, we will end up with a large value (the
   1873             // difference between 0 and the requested dimension), which is
   1874             // good since we will prefer a config that has specified a
   1875             // size value.
   1876             int myDelta = 0, otherDelta = 0;
   1877             if (requested->screenWidth) {
   1878                 myDelta += requested->screenWidth - screenWidth;
   1879                 otherDelta += requested->screenWidth - o.screenWidth;
   1880             }
   1881             if (requested->screenHeight) {
   1882                 myDelta += requested->screenHeight - screenHeight;
   1883                 otherDelta += requested->screenHeight - o.screenHeight;
   1884             }
   1885             if (myDelta != otherDelta) {
   1886                 return myDelta < otherDelta;
   1887             }
   1888         }
   1889 
   1890         if (version || o.version) {
   1891             if ((sdkVersion != o.sdkVersion) && requested->sdkVersion) {
   1892                 return (sdkVersion > o.sdkVersion);
   1893             }
   1894 
   1895             if ((minorVersion != o.minorVersion) &&
   1896                     requested->minorVersion) {
   1897                 return (minorVersion);
   1898             }
   1899         }
   1900 
   1901         return false;
   1902     }
   1903     return isMoreSpecificThan(o);
   1904 }
   1905 
   1906 bool ResTable_config::match(const ResTable_config& settings) const {
   1907     if (imsi != 0) {
   1908         if (mcc != 0 && mcc != settings.mcc) {
   1909             return false;
   1910         }
   1911         if (mnc != 0 && mnc != settings.mnc) {
   1912             return false;
   1913         }
   1914     }
   1915     if (locale != 0) {
   1916         if (language[0] != 0
   1917             && (language[0] != settings.language[0]
   1918                 || language[1] != settings.language[1])) {
   1919             return false;
   1920         }
   1921         if (country[0] != 0
   1922             && (country[0] != settings.country[0]
   1923                 || country[1] != settings.country[1])) {
   1924             return false;
   1925         }
   1926     }
   1927     if (screenConfig != 0) {
   1928         const int layoutDir = screenLayout&MASK_LAYOUTDIR;
   1929         const int setLayoutDir = settings.screenLayout&MASK_LAYOUTDIR;
   1930         if (layoutDir != 0 && layoutDir != setLayoutDir) {
   1931             return false;
   1932         }
   1933 
   1934         const int screenSize = screenLayout&MASK_SCREENSIZE;
   1935         const int setScreenSize = settings.screenLayout&MASK_SCREENSIZE;
   1936         // Any screen sizes for larger screens than the setting do not
   1937         // match.
   1938         if (screenSize != 0 && screenSize > setScreenSize) {
   1939             return false;
   1940         }
   1941 
   1942         const int screenLong = screenLayout&MASK_SCREENLONG;
   1943         const int setScreenLong = settings.screenLayout&MASK_SCREENLONG;
   1944         if (screenLong != 0 && screenLong != setScreenLong) {
   1945             return false;
   1946         }
   1947 
   1948         const int uiModeType = uiMode&MASK_UI_MODE_TYPE;
   1949         const int setUiModeType = settings.uiMode&MASK_UI_MODE_TYPE;
   1950         if (uiModeType != 0 && uiModeType != setUiModeType) {
   1951             return false;
   1952         }
   1953 
   1954         const int uiModeNight = uiMode&MASK_UI_MODE_NIGHT;
   1955         const int setUiModeNight = settings.uiMode&MASK_UI_MODE_NIGHT;
   1956         if (uiModeNight != 0 && uiModeNight != setUiModeNight) {
   1957             return false;
   1958         }
   1959 
   1960         if (smallestScreenWidthDp != 0
   1961                 && smallestScreenWidthDp > settings.smallestScreenWidthDp) {
   1962             return false;
   1963         }
   1964     }
   1965     if (screenSizeDp != 0) {
   1966         if (screenWidthDp != 0 && screenWidthDp > settings.screenWidthDp) {
   1967             //ALOGI("Filtering out width %d in requested %d", screenWidthDp, settings.screenWidthDp);
   1968             return false;
   1969         }
   1970         if (screenHeightDp != 0 && screenHeightDp > settings.screenHeightDp) {
   1971             //ALOGI("Filtering out height %d in requested %d", screenHeightDp, settings.screenHeightDp);
   1972             return false;
   1973         }
   1974     }
   1975     if (screenType != 0) {
   1976         if (orientation != 0 && orientation != settings.orientation) {
   1977             return false;
   1978         }
   1979         // density always matches - we can scale it.  See isBetterThan
   1980         if (touchscreen != 0 && touchscreen != settings.touchscreen) {
   1981             return false;
   1982         }
   1983     }
   1984     if (input != 0) {
   1985         const int keysHidden = inputFlags&MASK_KEYSHIDDEN;
   1986         const int setKeysHidden = settings.inputFlags&MASK_KEYSHIDDEN;
   1987         if (keysHidden != 0 && keysHidden != setKeysHidden) {
   1988             // For compatibility, we count a request for KEYSHIDDEN_NO as also
   1989             // matching the more recent KEYSHIDDEN_SOFT.  Basically
   1990             // KEYSHIDDEN_NO means there is some kind of keyboard available.
   1991             //ALOGI("Matching keysHidden: have=%d, config=%d\n", keysHidden, setKeysHidden);
   1992             if (keysHidden != KEYSHIDDEN_NO || setKeysHidden != KEYSHIDDEN_SOFT) {
   1993                 //ALOGI("No match!");
   1994                 return false;
   1995             }
   1996         }
   1997         const int navHidden = inputFlags&MASK_NAVHIDDEN;
   1998         const int setNavHidden = settings.inputFlags&MASK_NAVHIDDEN;
   1999         if (navHidden != 0 && navHidden != setNavHidden) {
   2000             return false;
   2001         }
   2002         if (keyboard != 0 && keyboard != settings.keyboard) {
   2003             return false;
   2004         }
   2005         if (navigation != 0 && navigation != settings.navigation) {
   2006             return false;
   2007         }
   2008     }
   2009     if (screenSize != 0) {
   2010         if (screenWidth != 0 && screenWidth > settings.screenWidth) {
   2011             return false;
   2012         }
   2013         if (screenHeight != 0 && screenHeight > settings.screenHeight) {
   2014             return false;
   2015         }
   2016     }
   2017     if (version != 0) {
   2018         if (sdkVersion != 0 && sdkVersion > settings.sdkVersion) {
   2019             return false;
   2020         }
   2021         if (minorVersion != 0 && minorVersion != settings.minorVersion) {
   2022             return false;
   2023         }
   2024     }
   2025     return true;
   2026 }
   2027 
   2028 void ResTable_config::getLocale(char str[6]) const {
   2029     memset(str, 0, 6);
   2030     if (language[0]) {
   2031         str[0] = language[0];
   2032         str[1] = language[1];
   2033         if (country[0]) {
   2034             str[2] = '_';
   2035             str[3] = country[0];
   2036             str[4] = country[1];
   2037         }
   2038     }
   2039 }
   2040 
   2041 String8 ResTable_config::toString() const {
   2042     String8 res;
   2043 
   2044     if (mcc != 0) {
   2045         if (res.size() > 0) res.append("-");
   2046         res.appendFormat("%dmcc", dtohs(mcc));
   2047     }
   2048     if (mnc != 0) {
   2049         if (res.size() > 0) res.append("-");
   2050         res.appendFormat("%dmnc", dtohs(mnc));
   2051     }
   2052     if (language[0] != 0) {
   2053         if (res.size() > 0) res.append("-");
   2054         res.append(language, 2);
   2055     }
   2056     if (country[0] != 0) {
   2057         if (res.size() > 0) res.append("-");
   2058         res.append(country, 2);
   2059     }
   2060     if ((screenLayout&MASK_LAYOUTDIR) != 0) {
   2061         if (res.size() > 0) res.append("-");
   2062         switch (screenLayout&ResTable_config::MASK_LAYOUTDIR) {
   2063             case ResTable_config::LAYOUTDIR_LTR:
   2064                 res.append("ldltr");
   2065                 break;
   2066             case ResTable_config::LAYOUTDIR_RTL:
   2067                 res.append("ldrtl");
   2068                 break;
   2069             default:
   2070                 res.appendFormat("layoutDir=%d",
   2071                         dtohs(screenLayout&ResTable_config::MASK_LAYOUTDIR));
   2072                 break;
   2073         }
   2074     }
   2075     if (smallestScreenWidthDp != 0) {
   2076         if (res.size() > 0) res.append("-");
   2077         res.appendFormat("sw%ddp", dtohs(smallestScreenWidthDp));
   2078     }
   2079     if (screenWidthDp != 0) {
   2080         if (res.size() > 0) res.append("-");
   2081         res.appendFormat("w%ddp", dtohs(screenWidthDp));
   2082     }
   2083     if (screenHeightDp != 0) {
   2084         if (res.size() > 0) res.append("-");
   2085         res.appendFormat("h%ddp", dtohs(screenHeightDp));
   2086     }
   2087     if ((screenLayout&MASK_SCREENSIZE) != SCREENSIZE_ANY) {
   2088         if (res.size() > 0) res.append("-");
   2089         switch (screenLayout&ResTable_config::MASK_SCREENSIZE) {
   2090             case ResTable_config::SCREENSIZE_SMALL:
   2091                 res.append("small");
   2092                 break;
   2093             case ResTable_config::SCREENSIZE_NORMAL:
   2094                 res.append("normal");
   2095                 break;
   2096             case ResTable_config::SCREENSIZE_LARGE:
   2097                 res.append("large");
   2098                 break;
   2099             case ResTable_config::SCREENSIZE_XLARGE:
   2100                 res.append("xlarge");
   2101                 break;
   2102             default:
   2103                 res.appendFormat("screenLayoutSize=%d",
   2104                         dtohs(screenLayout&ResTable_config::MASK_SCREENSIZE));
   2105                 break;
   2106         }
   2107     }
   2108     if ((screenLayout&MASK_SCREENLONG) != 0) {
   2109         if (res.size() > 0) res.append("-");
   2110         switch (screenLayout&ResTable_config::MASK_SCREENLONG) {
   2111             case ResTable_config::SCREENLONG_NO:
   2112                 res.append("notlong");
   2113                 break;
   2114             case ResTable_config::SCREENLONG_YES:
   2115                 res.append("long");
   2116                 break;
   2117             default:
   2118                 res.appendFormat("screenLayoutLong=%d",
   2119                         dtohs(screenLayout&ResTable_config::MASK_SCREENLONG));
   2120                 break;
   2121         }
   2122     }
   2123     if (orientation != ORIENTATION_ANY) {
   2124         if (res.size() > 0) res.append("-");
   2125         switch (orientation) {
   2126             case ResTable_config::ORIENTATION_PORT:
   2127                 res.append("port");
   2128                 break;
   2129             case ResTable_config::ORIENTATION_LAND:
   2130                 res.append("land");
   2131                 break;
   2132             case ResTable_config::ORIENTATION_SQUARE:
   2133                 res.append("square");
   2134                 break;
   2135             default:
   2136                 res.appendFormat("orientation=%d", dtohs(orientation));
   2137                 break;
   2138         }
   2139     }
   2140     if ((uiMode&MASK_UI_MODE_TYPE) != UI_MODE_TYPE_ANY) {
   2141         if (res.size() > 0) res.append("-");
   2142         switch (uiMode&ResTable_config::MASK_UI_MODE_TYPE) {
   2143             case ResTable_config::UI_MODE_TYPE_DESK:
   2144                 res.append("desk");
   2145                 break;
   2146             case ResTable_config::UI_MODE_TYPE_CAR:
   2147                 res.append("car");
   2148                 break;
   2149             case ResTable_config::UI_MODE_TYPE_TELEVISION:
   2150                 res.append("television");
   2151                 break;
   2152             case ResTable_config::UI_MODE_TYPE_APPLIANCE:
   2153                 res.append("appliance");
   2154                 break;
   2155             default:
   2156                 res.appendFormat("uiModeType=%d",
   2157                         dtohs(screenLayout&ResTable_config::MASK_UI_MODE_TYPE));
   2158                 break;
   2159         }
   2160     }
   2161     if ((uiMode&MASK_UI_MODE_NIGHT) != 0) {
   2162         if (res.size() > 0) res.append("-");
   2163         switch (uiMode&ResTable_config::MASK_UI_MODE_NIGHT) {
   2164             case ResTable_config::UI_MODE_NIGHT_NO:
   2165                 res.append("notnight");
   2166                 break;
   2167             case ResTable_config::UI_MODE_NIGHT_YES:
   2168                 res.append("night");
   2169                 break;
   2170             default:
   2171                 res.appendFormat("uiModeNight=%d",
   2172                         dtohs(uiMode&MASK_UI_MODE_NIGHT));
   2173                 break;
   2174         }
   2175     }
   2176     if (density != DENSITY_DEFAULT) {
   2177         if (res.size() > 0) res.append("-");
   2178         switch (density) {
   2179             case ResTable_config::DENSITY_LOW:
   2180                 res.append("ldpi");
   2181                 break;
   2182             case ResTable_config::DENSITY_MEDIUM:
   2183                 res.append("mdpi");
   2184                 break;
   2185             case ResTable_config::DENSITY_TV:
   2186                 res.append("tvdpi");
   2187                 break;
   2188             case ResTable_config::DENSITY_HIGH:
   2189                 res.append("hdpi");
   2190                 break;
   2191             case ResTable_config::DENSITY_XHIGH:
   2192                 res.append("xhdpi");
   2193                 break;
   2194             case ResTable_config::DENSITY_XXHIGH:
   2195                 res.append("xxhdpi");
   2196                 break;
   2197             case ResTable_config::DENSITY_NONE:
   2198                 res.append("nodpi");
   2199                 break;
   2200             default:
   2201                 res.appendFormat("%ddpi", dtohs(density));
   2202                 break;
   2203         }
   2204     }
   2205     if (touchscreen != TOUCHSCREEN_ANY) {
   2206         if (res.size() > 0) res.append("-");
   2207         switch (touchscreen) {
   2208             case ResTable_config::TOUCHSCREEN_NOTOUCH:
   2209                 res.append("notouch");
   2210                 break;
   2211             case ResTable_config::TOUCHSCREEN_FINGER:
   2212                 res.append("finger");
   2213                 break;
   2214             case ResTable_config::TOUCHSCREEN_STYLUS:
   2215                 res.append("stylus");
   2216                 break;
   2217             default:
   2218                 res.appendFormat("touchscreen=%d", dtohs(touchscreen));
   2219                 break;
   2220         }
   2221     }
   2222     if (keyboard != KEYBOARD_ANY) {
   2223         if (res.size() > 0) res.append("-");
   2224         switch (keyboard) {
   2225             case ResTable_config::KEYBOARD_NOKEYS:
   2226                 res.append("nokeys");
   2227                 break;
   2228             case ResTable_config::KEYBOARD_QWERTY:
   2229                 res.append("qwerty");
   2230                 break;
   2231             case ResTable_config::KEYBOARD_12KEY:
   2232                 res.append("12key");
   2233                 break;
   2234             default:
   2235                 res.appendFormat("keyboard=%d", dtohs(keyboard));
   2236                 break;
   2237         }
   2238     }
   2239     if ((inputFlags&MASK_KEYSHIDDEN) != 0) {
   2240         if (res.size() > 0) res.append("-");
   2241         switch (inputFlags&MASK_KEYSHIDDEN) {
   2242             case ResTable_config::KEYSHIDDEN_NO:
   2243                 res.append("keysexposed");
   2244                 break;
   2245             case ResTable_config::KEYSHIDDEN_YES:
   2246                 res.append("keyshidden");
   2247                 break;
   2248             case ResTable_config::KEYSHIDDEN_SOFT:
   2249                 res.append("keyssoft");
   2250                 break;
   2251         }
   2252     }
   2253     if (navigation != NAVIGATION_ANY) {
   2254         if (res.size() > 0) res.append("-");
   2255         switch (navigation) {
   2256             case ResTable_config::NAVIGATION_NONAV:
   2257                 res.append("nonav");
   2258                 break;
   2259             case ResTable_config::NAVIGATION_DPAD:
   2260                 res.append("dpad");
   2261                 break;
   2262             case ResTable_config::NAVIGATION_TRACKBALL:
   2263                 res.append("trackball");
   2264                 break;
   2265             case ResTable_config::NAVIGATION_WHEEL:
   2266                 res.append("wheel");
   2267                 break;
   2268             default:
   2269                 res.appendFormat("navigation=%d", dtohs(navigation));
   2270                 break;
   2271         }
   2272     }
   2273     if ((inputFlags&MASK_NAVHIDDEN) != 0) {
   2274         if (res.size() > 0) res.append("-");
   2275         switch (inputFlags&MASK_NAVHIDDEN) {
   2276             case ResTable_config::NAVHIDDEN_NO:
   2277                 res.append("navsexposed");
   2278                 break;
   2279             case ResTable_config::NAVHIDDEN_YES:
   2280                 res.append("navhidden");
   2281                 break;
   2282             default:
   2283                 res.appendFormat("inputFlagsNavHidden=%d",
   2284                         dtohs(inputFlags&MASK_NAVHIDDEN));
   2285                 break;
   2286         }
   2287     }
   2288     if (screenSize != 0) {
   2289         if (res.size() > 0) res.append("-");
   2290         res.appendFormat("%dx%d", dtohs(screenWidth), dtohs(screenHeight));
   2291     }
   2292     if (version != 0) {
   2293         if (res.size() > 0) res.append("-");
   2294         res.appendFormat("v%d", dtohs(sdkVersion));
   2295         if (minorVersion != 0) {
   2296             res.appendFormat(".%d", dtohs(minorVersion));
   2297         }
   2298     }
   2299 
   2300     return res;
   2301 }
   2302 
   2303 // --------------------------------------------------------------------
   2304 // --------------------------------------------------------------------
   2305 // --------------------------------------------------------------------
   2306 
   2307 struct ResTable::Header
   2308 {
   2309     Header(ResTable* _owner) : owner(_owner), ownedData(NULL), header(NULL),
   2310         resourceIDMap(NULL), resourceIDMapSize(0) { }
   2311 
   2312     ~Header()
   2313     {
   2314         free(resourceIDMap);
   2315     }
   2316 
   2317     ResTable* const                 owner;
   2318     void*                           ownedData;
   2319     const ResTable_header*          header;
   2320     size_t                          size;
   2321     const uint8_t*                  dataEnd;
   2322     size_t                          index;
   2323     void*                           cookie;
   2324 
   2325     ResStringPool                   values;
   2326     uint32_t*                       resourceIDMap;
   2327     size_t                          resourceIDMapSize;
   2328 };
   2329 
   2330 struct ResTable::Type
   2331 {
   2332     Type(const Header* _header, const Package* _package, size_t count)
   2333         : header(_header), package(_package), entryCount(count),
   2334           typeSpec(NULL), typeSpecFlags(NULL) { }
   2335     const Header* const             header;
   2336     const Package* const            package;
   2337     const size_t                    entryCount;
   2338     const ResTable_typeSpec*        typeSpec;
   2339     const uint32_t*                 typeSpecFlags;
   2340     Vector<const ResTable_type*>    configs;
   2341 };
   2342 
   2343 struct ResTable::Package
   2344 {
   2345     Package(ResTable* _owner, const Header* _header, const ResTable_package* _package)
   2346         : owner(_owner), header(_header), package(_package) { }
   2347     ~Package()
   2348     {
   2349         size_t i = types.size();
   2350         while (i > 0) {
   2351             i--;
   2352             delete types[i];
   2353         }
   2354     }
   2355 
   2356     ResTable* const                 owner;
   2357     const Header* const             header;
   2358     const ResTable_package* const   package;
   2359     Vector<Type*>                   types;
   2360 
   2361     ResStringPool                   typeStrings;
   2362     ResStringPool                   keyStrings;
   2363 
   2364     const Type* getType(size_t idx) const {
   2365         return idx < types.size() ? types[idx] : NULL;
   2366     }
   2367 };
   2368 
   2369 // A group of objects describing a particular resource package.
   2370 // The first in 'package' is always the root object (from the resource
   2371 // table that defined the package); the ones after are skins on top of it.
   2372 struct ResTable::PackageGroup
   2373 {
   2374     PackageGroup(ResTable* _owner, const String16& _name, uint32_t _id)
   2375         : owner(_owner), name(_name), id(_id), typeCount(0), bags(NULL) { }
   2376     ~PackageGroup() {
   2377         clearBagCache();
   2378         const size_t N = packages.size();
   2379         for (size_t i=0; i<N; i++) {
   2380             Package* pkg = packages[i];
   2381             if (pkg->owner == owner) {
   2382                 delete pkg;
   2383             }
   2384         }
   2385     }
   2386 
   2387     void clearBagCache() {
   2388         if (bags) {
   2389             TABLE_NOISY(printf("bags=%p\n", bags));
   2390             Package* pkg = packages[0];
   2391             TABLE_NOISY(printf("typeCount=%x\n", typeCount));
   2392             for (size_t i=0; i<typeCount; i++) {
   2393                 TABLE_NOISY(printf("type=%d\n", i));
   2394                 const Type* type = pkg->getType(i);
   2395                 if (type != NULL) {
   2396                     bag_set** typeBags = bags[i];
   2397                     TABLE_NOISY(printf("typeBags=%p\n", typeBags));
   2398                     if (typeBags) {
   2399                         TABLE_NOISY(printf("type->entryCount=%x\n", type->entryCount));
   2400                         const size_t N = type->entryCount;
   2401                         for (size_t j=0; j<N; j++) {
   2402                             if (typeBags[j] && typeBags[j] != (bag_set*)0xFFFFFFFF)
   2403                                 free(typeBags[j]);
   2404                         }
   2405                         free(typeBags);
   2406                     }
   2407                 }
   2408             }
   2409             free(bags);
   2410             bags = NULL;
   2411         }
   2412     }
   2413 
   2414     ResTable* const                 owner;
   2415     String16 const                  name;
   2416     uint32_t const                  id;
   2417     Vector<Package*>                packages;
   2418 
   2419     // This is for finding typeStrings and other common package stuff.
   2420     Package*                        basePackage;
   2421 
   2422     // For quick access.
   2423     size_t                          typeCount;
   2424 
   2425     // Computed attribute bags, first indexed by the type and second
   2426     // by the entry in that type.
   2427     bag_set***                      bags;
   2428 };
   2429 
   2430 struct ResTable::bag_set
   2431 {
   2432     size_t numAttrs;    // number in array
   2433     size_t availAttrs;  // total space in array
   2434     uint32_t typeSpecFlags;
   2435     // Followed by 'numAttr' bag_entry structures.
   2436 };
   2437 
   2438 ResTable::Theme::Theme(const ResTable& table)
   2439     : mTable(table)
   2440 {
   2441     memset(mPackages, 0, sizeof(mPackages));
   2442 }
   2443 
   2444 ResTable::Theme::~Theme()
   2445 {
   2446     for (size_t i=0; i<Res_MAXPACKAGE; i++) {
   2447         package_info* pi = mPackages[i];
   2448         if (pi != NULL) {
   2449             free_package(pi);
   2450         }
   2451     }
   2452 }
   2453 
   2454 void ResTable::Theme::free_package(package_info* pi)
   2455 {
   2456     for (size_t j=0; j<pi->numTypes; j++) {
   2457         theme_entry* te = pi->types[j].entries;
   2458         if (te != NULL) {
   2459             free(te);
   2460         }
   2461     }
   2462     free(pi);
   2463 }
   2464 
   2465 ResTable::Theme::package_info* ResTable::Theme::copy_package(package_info* pi)
   2466 {
   2467     package_info* newpi = (package_info*)malloc(
   2468         sizeof(package_info) + (pi->numTypes*sizeof(type_info)));
   2469     newpi->numTypes = pi->numTypes;
   2470     for (size_t j=0; j<newpi->numTypes; j++) {
   2471         size_t cnt = pi->types[j].numEntries;
   2472         newpi->types[j].numEntries = cnt;
   2473         theme_entry* te = pi->types[j].entries;
   2474         if (te != NULL) {
   2475             theme_entry* newte = (theme_entry*)malloc(cnt*sizeof(theme_entry));
   2476             newpi->types[j].entries = newte;
   2477             memcpy(newte, te, cnt*sizeof(theme_entry));
   2478         } else {
   2479             newpi->types[j].entries = NULL;
   2480         }
   2481     }
   2482     return newpi;
   2483 }
   2484 
   2485 status_t ResTable::Theme::applyStyle(uint32_t resID, bool force)
   2486 {
   2487     const bag_entry* bag;
   2488     uint32_t bagTypeSpecFlags = 0;
   2489     mTable.lock();
   2490     const ssize_t N = mTable.getBagLocked(resID, &bag, &bagTypeSpecFlags);
   2491     TABLE_NOISY(ALOGV("Applying style 0x%08x to theme %p, count=%d", resID, this, N));
   2492     if (N < 0) {
   2493         mTable.unlock();
   2494         return N;
   2495     }
   2496 
   2497     uint32_t curPackage = 0xffffffff;
   2498     ssize_t curPackageIndex = 0;
   2499     package_info* curPI = NULL;
   2500     uint32_t curType = 0xffffffff;
   2501     size_t numEntries = 0;
   2502     theme_entry* curEntries = NULL;
   2503 
   2504     const bag_entry* end = bag + N;
   2505     while (bag < end) {
   2506         const uint32_t attrRes = bag->map.name.ident;
   2507         const uint32_t p = Res_GETPACKAGE(attrRes);
   2508         const uint32_t t = Res_GETTYPE(attrRes);
   2509         const uint32_t e = Res_GETENTRY(attrRes);
   2510 
   2511         if (curPackage != p) {
   2512             const ssize_t pidx = mTable.getResourcePackageIndex(attrRes);
   2513             if (pidx < 0) {
   2514                 ALOGE("Style contains key with bad package: 0x%08x\n", attrRes);
   2515                 bag++;
   2516                 continue;
   2517             }
   2518             curPackage = p;
   2519             curPackageIndex = pidx;
   2520             curPI = mPackages[pidx];
   2521             if (curPI == NULL) {
   2522                 PackageGroup* const grp = mTable.mPackageGroups[pidx];
   2523                 int cnt = grp->typeCount;
   2524                 curPI = (package_info*)malloc(
   2525                     sizeof(package_info) + (cnt*sizeof(type_info)));
   2526                 curPI->numTypes = cnt;
   2527                 memset(curPI->types, 0, cnt*sizeof(type_info));
   2528                 mPackages[pidx] = curPI;
   2529             }
   2530             curType = 0xffffffff;
   2531         }
   2532         if (curType != t) {
   2533             if (t >= curPI->numTypes) {
   2534                 ALOGE("Style contains key with bad type: 0x%08x\n", attrRes);
   2535                 bag++;
   2536                 continue;
   2537             }
   2538             curType = t;
   2539             curEntries = curPI->types[t].entries;
   2540             if (curEntries == NULL) {
   2541                 PackageGroup* const grp = mTable.mPackageGroups[curPackageIndex];
   2542                 const Type* type = grp->packages[0]->getType(t);
   2543                 int cnt = type != NULL ? type->entryCount : 0;
   2544                 curEntries = (theme_entry*)malloc(cnt*sizeof(theme_entry));
   2545                 memset(curEntries, Res_value::TYPE_NULL, cnt*sizeof(theme_entry));
   2546                 curPI->types[t].numEntries = cnt;
   2547                 curPI->types[t].entries = curEntries;
   2548             }
   2549             numEntries = curPI->types[t].numEntries;
   2550         }
   2551         if (e >= numEntries) {
   2552             ALOGE("Style contains key with bad entry: 0x%08x\n", attrRes);
   2553             bag++;
   2554             continue;
   2555         }
   2556         theme_entry* curEntry = curEntries + e;
   2557         TABLE_NOISY(ALOGV("Attr 0x%08x: type=0x%x, data=0x%08x; curType=0x%x",
   2558                    attrRes, bag->map.value.dataType, bag->map.value.data,
   2559              curEntry->value.dataType));
   2560         if (force || curEntry->value.dataType == Res_value::TYPE_NULL) {
   2561             curEntry->stringBlock = bag->stringBlock;
   2562             curEntry->typeSpecFlags |= bagTypeSpecFlags;
   2563             curEntry->value = bag->map.value;
   2564         }
   2565 
   2566         bag++;
   2567     }
   2568 
   2569     mTable.unlock();
   2570 
   2571     //ALOGI("Applying style 0x%08x (force=%d)  theme %p...\n", resID, force, this);
   2572     //dumpToLog();
   2573 
   2574     return NO_ERROR;
   2575 }
   2576 
   2577 status_t ResTable::Theme::setTo(const Theme& other)
   2578 {
   2579     //ALOGI("Setting theme %p from theme %p...\n", this, &other);
   2580     //dumpToLog();
   2581     //other.dumpToLog();
   2582 
   2583     if (&mTable == &other.mTable) {
   2584         for (size_t i=0; i<Res_MAXPACKAGE; i++) {
   2585             if (mPackages[i] != NULL) {
   2586                 free_package(mPackages[i]);
   2587             }
   2588             if (other.mPackages[i] != NULL) {
   2589                 mPackages[i] = copy_package(other.mPackages[i]);
   2590             } else {
   2591                 mPackages[i] = NULL;
   2592             }
   2593         }
   2594     } else {
   2595         // @todo: need to really implement this, not just copy
   2596         // the system package (which is still wrong because it isn't
   2597         // fixing up resource references).
   2598         for (size_t i=0; i<Res_MAXPACKAGE; i++) {
   2599             if (mPackages[i] != NULL) {
   2600                 free_package(mPackages[i]);
   2601             }
   2602             if (i == 0 && other.mPackages[i] != NULL) {
   2603                 mPackages[i] = copy_package(other.mPackages[i]);
   2604             } else {
   2605                 mPackages[i] = NULL;
   2606             }
   2607         }
   2608     }
   2609 
   2610     //ALOGI("Final theme:");
   2611     //dumpToLog();
   2612 
   2613     return NO_ERROR;
   2614 }
   2615 
   2616 ssize_t ResTable::Theme::getAttribute(uint32_t resID, Res_value* outValue,
   2617         uint32_t* outTypeSpecFlags) const
   2618 {
   2619     int cnt = 20;
   2620 
   2621     if (outTypeSpecFlags != NULL) *outTypeSpecFlags = 0;
   2622 
   2623     do {
   2624         const ssize_t p = mTable.getResourcePackageIndex(resID);
   2625         const uint32_t t = Res_GETTYPE(resID);
   2626         const uint32_t e = Res_GETENTRY(resID);
   2627 
   2628         TABLE_THEME(ALOGI("Looking up attr 0x%08x in theme %p", resID, this));
   2629 
   2630         if (p >= 0) {
   2631             const package_info* const pi = mPackages[p];
   2632             TABLE_THEME(ALOGI("Found package: %p", pi));
   2633             if (pi != NULL) {
   2634                 TABLE_THEME(ALOGI("Desired type index is %ld in avail %d", t, pi->numTypes));
   2635                 if (t < pi->numTypes) {
   2636                     const type_info& ti = pi->types[t];
   2637                     TABLE_THEME(ALOGI("Desired entry index is %ld in avail %d", e, ti.numEntries));
   2638                     if (e < ti.numEntries) {
   2639                         const theme_entry& te = ti.entries[e];
   2640                         if (outTypeSpecFlags != NULL) {
   2641                             *outTypeSpecFlags |= te.typeSpecFlags;
   2642                         }
   2643                         TABLE_THEME(ALOGI("Theme value: type=0x%x, data=0x%08x",
   2644                                 te.value.dataType, te.value.data));
   2645                         const uint8_t type = te.value.dataType;
   2646                         if (type == Res_value::TYPE_ATTRIBUTE) {
   2647                             if (cnt > 0) {
   2648                                 cnt--;
   2649                                 resID = te.value.data;
   2650                                 continue;
   2651                             }
   2652                             ALOGW("Too many attribute references, stopped at: 0x%08x\n", resID);
   2653                             return BAD_INDEX;
   2654                         } else if (type != Res_value::TYPE_NULL) {
   2655                             *outValue = te.value;
   2656                             return te.stringBlock;
   2657                         }
   2658                         return BAD_INDEX;
   2659                     }
   2660                 }
   2661             }
   2662         }
   2663         break;
   2664 
   2665     } while (true);
   2666 
   2667     return BAD_INDEX;
   2668 }
   2669 
   2670 ssize_t ResTable::Theme::resolveAttributeReference(Res_value* inOutValue,
   2671         ssize_t blockIndex, uint32_t* outLastRef,
   2672         uint32_t* inoutTypeSpecFlags, ResTable_config* inoutConfig) const
   2673 {
   2674     //printf("Resolving type=0x%x\n", inOutValue->dataType);
   2675     if (inOutValue->dataType == Res_value::TYPE_ATTRIBUTE) {
   2676         uint32_t newTypeSpecFlags;
   2677         blockIndex = getAttribute(inOutValue->data, inOutValue, &newTypeSpecFlags);
   2678         TABLE_THEME(ALOGI("Resolving attr reference: blockIndex=%d, type=0x%x, data=%p\n",
   2679              (int)blockIndex, (int)inOutValue->dataType, (void*)inOutValue->data));
   2680         if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newTypeSpecFlags;
   2681         //printf("Retrieved attribute new type=0x%x\n", inOutValue->dataType);
   2682         if (blockIndex < 0) {
   2683             return blockIndex;
   2684         }
   2685     }
   2686     return mTable.resolveReference(inOutValue, blockIndex, outLastRef,
   2687             inoutTypeSpecFlags, inoutConfig);
   2688 }
   2689 
   2690 void ResTable::Theme::dumpToLog() const
   2691 {
   2692     ALOGI("Theme %p:\n", this);
   2693     for (size_t i=0; i<Res_MAXPACKAGE; i++) {
   2694         package_info* pi = mPackages[i];
   2695         if (pi == NULL) continue;
   2696 
   2697         ALOGI("  Package #0x%02x:\n", (int)(i+1));
   2698         for (size_t j=0; j<pi->numTypes; j++) {
   2699             type_info& ti = pi->types[j];
   2700             if (ti.numEntries == 0) continue;
   2701 
   2702             ALOGI("    Type #0x%02x:\n", (int)(j+1));
   2703             for (size_t k=0; k<ti.numEntries; k++) {
   2704                 theme_entry& te = ti.entries[k];
   2705                 if (te.value.dataType == Res_value::TYPE_NULL) continue;
   2706                 ALOGI("      0x%08x: t=0x%x, d=0x%08x (block=%d)\n",
   2707                      (int)Res_MAKEID(i, j, k),
   2708                      te.value.dataType, (int)te.value.data, (int)te.stringBlock);
   2709             }
   2710         }
   2711     }
   2712 }
   2713 
   2714 ResTable::ResTable()
   2715     : mError(NO_INIT)
   2716 {
   2717     memset(&mParams, 0, sizeof(mParams));
   2718     memset(mPackageMap, 0, sizeof(mPackageMap));
   2719     //ALOGI("Creating ResTable %p\n", this);
   2720 }
   2721 
   2722 ResTable::ResTable(const void* data, size_t size, void* cookie, bool copyData)
   2723     : mError(NO_INIT)
   2724 {
   2725     memset(&mParams, 0, sizeof(mParams));
   2726     memset(mPackageMap, 0, sizeof(mPackageMap));
   2727     add(data, size, cookie, copyData);
   2728     LOG_FATAL_IF(mError != NO_ERROR, "Error parsing resource table");
   2729     //ALOGI("Creating ResTable %p\n", this);
   2730 }
   2731 
   2732 ResTable::~ResTable()
   2733 {
   2734     //ALOGI("Destroying ResTable in %p\n", this);
   2735     uninit();
   2736 }
   2737 
   2738 inline ssize_t ResTable::getResourcePackageIndex(uint32_t resID) const
   2739 {
   2740     return ((ssize_t)mPackageMap[Res_GETPACKAGE(resID)+1])-1;
   2741 }
   2742 
   2743 status_t ResTable::add(const void* data, size_t size, void* cookie, bool copyData,
   2744                        const void* idmap)
   2745 {
   2746     return add(data, size, cookie, NULL, copyData, reinterpret_cast<const Asset*>(idmap));
   2747 }
   2748 
   2749 status_t ResTable::add(Asset* asset, void* cookie, bool copyData, const void* idmap)
   2750 {
   2751     const void* data = asset->getBuffer(true);
   2752     if (data == NULL) {
   2753         ALOGW("Unable to get buffer of resource asset file");
   2754         return UNKNOWN_ERROR;
   2755     }
   2756     size_t size = (size_t)asset->getLength();
   2757     return add(data, size, cookie, asset, copyData, reinterpret_cast<const Asset*>(idmap));
   2758 }
   2759 
   2760 status_t ResTable::add(ResTable* src)
   2761 {
   2762     mError = src->mError;
   2763 
   2764     for (size_t i=0; i<src->mHeaders.size(); i++) {
   2765         mHeaders.add(src->mHeaders[i]);
   2766     }
   2767 
   2768     for (size_t i=0; i<src->mPackageGroups.size(); i++) {
   2769         PackageGroup* srcPg = src->mPackageGroups[i];
   2770         PackageGroup* pg = new PackageGroup(this, srcPg->name, srcPg->id);
   2771         for (size_t j=0; j<srcPg->packages.size(); j++) {
   2772             pg->packages.add(srcPg->packages[j]);
   2773         }
   2774         pg->basePackage = srcPg->basePackage;
   2775         pg->typeCount = srcPg->typeCount;
   2776         mPackageGroups.add(pg);
   2777     }
   2778 
   2779     memcpy(mPackageMap, src->mPackageMap, sizeof(mPackageMap));
   2780 
   2781     return mError;
   2782 }
   2783 
   2784 status_t ResTable::add(const void* data, size_t size, void* cookie,
   2785                        Asset* asset, bool copyData, const Asset* idmap)
   2786 {
   2787     if (!data) return NO_ERROR;
   2788     Header* header = new Header(this);
   2789     header->index = mHeaders.size();
   2790     header->cookie = cookie;
   2791     if (idmap != NULL) {
   2792         const size_t idmap_size = idmap->getLength();
   2793         const void* idmap_data = const_cast<Asset*>(idmap)->getBuffer(true);
   2794         header->resourceIDMap = (uint32_t*)malloc(idmap_size);
   2795         if (header->resourceIDMap == NULL) {
   2796             delete header;
   2797             return (mError = NO_MEMORY);
   2798         }
   2799         memcpy((void*)header->resourceIDMap, idmap_data, idmap_size);
   2800         header->resourceIDMapSize = idmap_size;
   2801     }
   2802     mHeaders.add(header);
   2803 
   2804     const bool notDeviceEndian = htods(0xf0) != 0xf0;
   2805 
   2806     LOAD_TABLE_NOISY(
   2807         ALOGV("Adding resources to ResTable: data=%p, size=0x%x, cookie=%p, asset=%p, copy=%d "
   2808              "idmap=%p\n", data, size, cookie, asset, copyData, idmap));
   2809 
   2810     if (copyData || notDeviceEndian) {
   2811         header->ownedData = malloc(size);
   2812         if (header->ownedData == NULL) {
   2813             return (mError=NO_MEMORY);
   2814         }
   2815         memcpy(header->ownedData, data, size);
   2816         data = header->ownedData;
   2817     }
   2818 
   2819     header->header = (const ResTable_header*)data;
   2820     header->size = dtohl(header->header->header.size);
   2821     //ALOGI("Got size 0x%x, again size 0x%x, raw size 0x%x\n", header->size,
   2822     //     dtohl(header->header->header.size), header->header->header.size);
   2823     LOAD_TABLE_NOISY(ALOGV("Loading ResTable @%p:\n", header->header));
   2824     LOAD_TABLE_NOISY(printHexData(2, header->header, header->size < 256 ? header->size : 256,
   2825                                   16, 16, 0, false, printToLogFunc));
   2826     if (dtohs(header->header->header.headerSize) > header->size
   2827             || header->size > size) {
   2828         ALOGW("Bad resource table: header size 0x%x or total size 0x%x is larger than data size 0x%x\n",
   2829              (int)dtohs(header->header->header.headerSize),
   2830              (int)header->size, (int)size);
   2831         return (mError=BAD_TYPE);
   2832     }
   2833     if (((dtohs(header->header->header.headerSize)|header->size)&0x3) != 0) {
   2834         ALOGW("Bad resource table: header size 0x%x or total size 0x%x is not on an integer boundary\n",
   2835              (int)dtohs(header->header->header.headerSize),
   2836              (int)header->size);
   2837         return (mError=BAD_TYPE);
   2838     }
   2839     header->dataEnd = ((const uint8_t*)header->header) + header->size;
   2840 
   2841     // Iterate through all chunks.
   2842     size_t curPackage = 0;
   2843 
   2844     const ResChunk_header* chunk =
   2845         (const ResChunk_header*)(((const uint8_t*)header->header)
   2846                                  + dtohs(header->header->header.headerSize));
   2847     while (((const uint8_t*)chunk) <= (header->dataEnd-sizeof(ResChunk_header)) &&
   2848            ((const uint8_t*)chunk) <= (header->dataEnd-dtohl(chunk->size))) {
   2849         status_t err = validate_chunk(chunk, sizeof(ResChunk_header), header->dataEnd, "ResTable");
   2850         if (err != NO_ERROR) {
   2851             return (mError=err);
   2852         }
   2853         TABLE_NOISY(ALOGV("Chunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n",
   2854                      dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
   2855                      (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header))));
   2856         const size_t csize = dtohl(chunk->size);
   2857         const uint16_t ctype = dtohs(chunk->type);
   2858         if (ctype == RES_STRING_POOL_TYPE) {
   2859             if (header->values.getError() != NO_ERROR) {
   2860                 // Only use the first string chunk; ignore any others that
   2861                 // may appear.
   2862                 status_t err = header->values.setTo(chunk, csize);
   2863                 if (err != NO_ERROR) {
   2864                     return (mError=err);
   2865                 }
   2866             } else {
   2867                 ALOGW("Multiple string chunks found in resource table.");
   2868             }
   2869         } else if (ctype == RES_TABLE_PACKAGE_TYPE) {
   2870             if (curPackage >= dtohl(header->header->packageCount)) {
   2871                 ALOGW("More package chunks were found than the %d declared in the header.",
   2872                      dtohl(header->header->packageCount));
   2873                 return (mError=BAD_TYPE);
   2874             }
   2875             uint32_t idmap_id = 0;
   2876             if (idmap != NULL) {
   2877                 uint32_t tmp;
   2878                 if (getIdmapPackageId(header->resourceIDMap,
   2879                                       header->resourceIDMapSize,
   2880                                       &tmp) == NO_ERROR) {
   2881                     idmap_id = tmp;
   2882                 }
   2883             }
   2884             if (parsePackage((ResTable_package*)chunk, header, idmap_id) != NO_ERROR) {
   2885                 return mError;
   2886             }
   2887             curPackage++;
   2888         } else {
   2889             ALOGW("Unknown chunk type %p in table at %p.\n",
   2890                  (void*)(int)(ctype),
   2891                  (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)));
   2892         }
   2893         chunk = (const ResChunk_header*)
   2894             (((const uint8_t*)chunk) + csize);
   2895     }
   2896 
   2897     if (curPackage < dtohl(header->header->packageCount)) {
   2898         ALOGW("Fewer package chunks (%d) were found than the %d declared in the header.",
   2899              (int)curPackage, dtohl(header->header->packageCount));
   2900         return (mError=BAD_TYPE);
   2901     }
   2902     mError = header->values.getError();
   2903     if (mError != NO_ERROR) {
   2904         ALOGW("No string values found in resource table!");
   2905     }
   2906 
   2907     TABLE_NOISY(ALOGV("Returning from add with mError=%d\n", mError));
   2908     return mError;
   2909 }
   2910 
   2911 status_t ResTable::getError() const
   2912 {
   2913     return mError;
   2914 }
   2915 
   2916 void ResTable::uninit()
   2917 {
   2918     mError = NO_INIT;
   2919     size_t N = mPackageGroups.size();
   2920     for (size_t i=0; i<N; i++) {
   2921         PackageGroup* g = mPackageGroups[i];
   2922         delete g;
   2923     }
   2924     N = mHeaders.size();
   2925     for (size_t i=0; i<N; i++) {
   2926         Header* header = mHeaders[i];
   2927         if (header->owner == this) {
   2928             if (header->ownedData) {
   2929                 free(header->ownedData);
   2930             }
   2931             delete header;
   2932         }
   2933     }
   2934 
   2935     mPackageGroups.clear();
   2936     mHeaders.clear();
   2937 }
   2938 
   2939 bool ResTable::getResourceName(uint32_t resID, resource_name* outName) const
   2940 {
   2941     if (mError != NO_ERROR) {
   2942         return false;
   2943     }
   2944 
   2945     const ssize_t p = getResourcePackageIndex(resID);
   2946     const int t = Res_GETTYPE(resID);
   2947     const int e = Res_GETENTRY(resID);
   2948 
   2949     if (p < 0) {
   2950         if (Res_GETPACKAGE(resID)+1 == 0) {
   2951             ALOGW("No package identifier when getting name for resource number 0x%08x", resID);
   2952         } else {
   2953             ALOGW("No known package when getting name for resource number 0x%08x", resID);
   2954         }
   2955         return false;
   2956     }
   2957     if (t < 0) {
   2958         ALOGW("No type identifier when getting name for resource number 0x%08x", resID);
   2959         return false;
   2960     }
   2961 
   2962     const PackageGroup* const grp = mPackageGroups[p];
   2963     if (grp == NULL) {
   2964         ALOGW("Bad identifier when getting name for resource number 0x%08x", resID);
   2965         return false;
   2966     }
   2967     if (grp->packages.size() > 0) {
   2968         const Package* const package = grp->packages[0];
   2969 
   2970         const ResTable_type* type;
   2971         const ResTable_entry* entry;
   2972         ssize_t offset = getEntry(package, t, e, NULL, &type, &entry, NULL);
   2973         if (offset <= 0) {
   2974             return false;
   2975         }
   2976 
   2977         outName->package = grp->name.string();
   2978         outName->packageLen = grp->name.size();
   2979         outName->type = grp->basePackage->typeStrings.stringAt(t, &outName->typeLen);
   2980         outName->name = grp->basePackage->keyStrings.stringAt(
   2981             dtohl(entry->key.index), &outName->nameLen);
   2982 
   2983         // If we have a bad index for some reason, we should abort.
   2984         if (outName->type == NULL || outName->name == NULL) {
   2985             return false;
   2986         }
   2987 
   2988         return true;
   2989     }
   2990 
   2991     return false;
   2992 }
   2993 
   2994 ssize_t ResTable::getResource(uint32_t resID, Res_value* outValue, bool mayBeBag, uint16_t density,
   2995         uint32_t* outSpecFlags, ResTable_config* outConfig) const
   2996 {
   2997     if (mError != NO_ERROR) {
   2998         return mError;
   2999     }
   3000 
   3001     const ssize_t p = getResourcePackageIndex(resID);
   3002     const int t = Res_GETTYPE(resID);
   3003     const int e = Res_GETENTRY(resID);
   3004 
   3005     if (p < 0) {
   3006         if (Res_GETPACKAGE(resID)+1 == 0) {
   3007             ALOGW("No package identifier when getting value for resource number 0x%08x", resID);
   3008         } else {
   3009             ALOGW("No known package when getting value for resource number 0x%08x", resID);
   3010         }
   3011         return BAD_INDEX;
   3012     }
   3013     if (t < 0) {
   3014         ALOGW("No type identifier when getting value for resource number 0x%08x", resID);
   3015         return BAD_INDEX;
   3016     }
   3017 
   3018     const Res_value* bestValue = NULL;
   3019     const Package* bestPackage = NULL;
   3020     ResTable_config bestItem;
   3021     memset(&bestItem, 0, sizeof(bestItem)); // make the compiler shut up
   3022 
   3023     if (outSpecFlags != NULL) *outSpecFlags = 0;
   3024 
   3025     // Look through all resource packages, starting with the most
   3026     // recently added.
   3027     const PackageGroup* const grp = mPackageGroups[p];
   3028     if (grp == NULL) {
   3029         ALOGW("Bad identifier when getting value for resource number 0x%08x", resID);
   3030         return BAD_INDEX;
   3031     }
   3032 
   3033     // Allow overriding density
   3034     const ResTable_config* desiredConfig = &mParams;
   3035     ResTable_config* overrideConfig = NULL;
   3036     if (density > 0) {
   3037         overrideConfig = (ResTable_config*) malloc(sizeof(ResTable_config));
   3038         if (overrideConfig == NULL) {
   3039             ALOGE("Couldn't malloc ResTable_config for overrides: %s", strerror(errno));
   3040             return BAD_INDEX;
   3041         }
   3042         memcpy(overrideConfig, &mParams, sizeof(ResTable_config));
   3043         overrideConfig->density = density;
   3044         desiredConfig = overrideConfig;
   3045     }
   3046 
   3047     ssize_t rc = BAD_VALUE;
   3048     size_t ip = grp->packages.size();
   3049     while (ip > 0) {
   3050         ip--;
   3051         int T = t;
   3052         int E = e;
   3053 
   3054         const Package* const package = grp->packages[ip];
   3055         if (package->header->resourceIDMap) {
   3056             uint32_t overlayResID = 0x0;
   3057             status_t retval = idmapLookup(package->header->resourceIDMap,
   3058                                           package->header->resourceIDMapSize,
   3059                                           resID, &overlayResID);
   3060             if (retval == NO_ERROR && overlayResID != 0x0) {
   3061                 // for this loop iteration, this is the type and entry we really want
   3062                 ALOGV("resource map 0x%08x -> 0x%08x\n", resID, overlayResID);
   3063                 T = Res_GETTYPE(overlayResID);
   3064                 E = Res_GETENTRY(overlayResID);
   3065             } else {
   3066                 // resource not present in overlay package, continue with the next package
   3067                 continue;
   3068             }
   3069         }
   3070 
   3071         const ResTable_type* type;
   3072         const ResTable_entry* entry;
   3073         const Type* typeClass;
   3074         ssize_t offset = getEntry(package, T, E, desiredConfig, &type, &entry, &typeClass);
   3075         if (offset <= 0) {
   3076             // No {entry, appropriate config} pair found in package. If this
   3077             // package is an overlay package (ip != 0), this simply means the
   3078             // overlay package did not specify a default.
   3079             // Non-overlay packages are still required to provide a default.
   3080             if (offset < 0 && ip == 0) {
   3081                 ALOGW("Failure getting entry for 0x%08x (t=%d e=%d) in package %zd (error %d)\n",
   3082                         resID, T, E, ip, (int)offset);
   3083                 rc = offset;
   3084                 goto out;
   3085             }
   3086             continue;
   3087         }
   3088 
   3089         if ((dtohs(entry->flags)&entry->FLAG_COMPLEX) != 0) {
   3090             if (!mayBeBag) {
   3091                 ALOGW("Requesting resource %p failed because it is complex\n",
   3092                      (void*)resID);
   3093             }
   3094             continue;
   3095         }
   3096 
   3097         TABLE_NOISY(aout << "Resource type data: "
   3098               << HexDump(type, dtohl(type->header.size)) << endl);
   3099 
   3100         if ((size_t)offset > (dtohl(type->header.size)-sizeof(Res_value))) {
   3101             ALOGW("ResTable_item at %d is beyond type chunk data %d",
   3102                  (int)offset, dtohl(type->header.size));
   3103             rc = BAD_TYPE;
   3104             goto out;
   3105         }
   3106 
   3107         const Res_value* item =
   3108             (const Res_value*)(((const uint8_t*)type) + offset);
   3109         ResTable_config thisConfig;
   3110         thisConfig.copyFromDtoH(type->config);
   3111 
   3112         if (outSpecFlags != NULL) {
   3113             if (typeClass->typeSpecFlags != NULL) {
   3114                 *outSpecFlags |= dtohl(typeClass->typeSpecFlags[E]);
   3115             } else {
   3116                 *outSpecFlags = -1;
   3117             }
   3118         }
   3119 
   3120         if (bestPackage != NULL &&
   3121             (bestItem.isMoreSpecificThan(thisConfig) || bestItem.diff(thisConfig) == 0)) {
   3122             // Discard thisConfig not only if bestItem is more specific, but also if the two configs
   3123             // are identical (diff == 0), or overlay packages will not take effect.
   3124             continue;
   3125         }
   3126 
   3127         bestItem = thisConfig;
   3128         bestValue = item;
   3129         bestPackage = package;
   3130     }
   3131 
   3132     TABLE_NOISY(printf("Found result: package %p\n", bestPackage));
   3133 
   3134     if (bestValue) {
   3135         outValue->size = dtohs(bestValue->size);
   3136         outValue->res0 = bestValue->res0;
   3137         outValue->dataType = bestValue->dataType;
   3138         outValue->data = dtohl(bestValue->data);
   3139         if (outConfig != NULL) {
   3140             *outConfig = bestItem;
   3141         }
   3142         TABLE_NOISY(size_t len;
   3143               printf("Found value: pkg=%d, type=%d, str=%s, int=%d\n",
   3144                      bestPackage->header->index,
   3145                      outValue->dataType,
   3146                      outValue->dataType == bestValue->TYPE_STRING
   3147                      ? String8(bestPackage->header->values.stringAt(
   3148                          outValue->data, &len)).string()
   3149                      : "",
   3150                      outValue->data));
   3151         rc = bestPackage->header->index;
   3152         goto out;
   3153     }
   3154 
   3155 out:
   3156     if (overrideConfig != NULL) {
   3157         free(overrideConfig);
   3158     }
   3159 
   3160     return rc;
   3161 }
   3162 
   3163 ssize_t ResTable::resolveReference(Res_value* value, ssize_t blockIndex,
   3164         uint32_t* outLastRef, uint32_t* inoutTypeSpecFlags,
   3165         ResTable_config* outConfig) const
   3166 {
   3167     int count=0;
   3168     while (blockIndex >= 0 && value->dataType == value->TYPE_REFERENCE
   3169            && value->data != 0 && count < 20) {
   3170         if (outLastRef) *outLastRef = value->data;
   3171         uint32_t lastRef = value->data;
   3172         uint32_t newFlags = 0;
   3173         const ssize_t newIndex = getResource(value->data, value, true, 0, &newFlags,
   3174                 outConfig);
   3175         if (newIndex == BAD_INDEX) {
   3176             return BAD_INDEX;
   3177         }
   3178         TABLE_THEME(ALOGI("Resolving reference %p: newIndex=%d, type=0x%x, data=%p\n",
   3179              (void*)lastRef, (int)newIndex, (int)value->dataType, (void*)value->data));
   3180         //printf("Getting reference 0x%08x: newIndex=%d\n", value->data, newIndex);
   3181         if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newFlags;
   3182         if (newIndex < 0) {
   3183             // This can fail if the resource being referenced is a style...
   3184             // in this case, just return the reference, and expect the
   3185             // caller to deal with.
   3186             return blockIndex;
   3187         }
   3188         blockIndex = newIndex;
   3189         count++;
   3190     }
   3191     return blockIndex;
   3192 }
   3193 
   3194 const char16_t* ResTable::valueToString(
   3195     const Res_value* value, size_t stringBlock,
   3196     char16_t tmpBuffer[TMP_BUFFER_SIZE], size_t* outLen)
   3197 {
   3198     if (!value) {
   3199         return NULL;
   3200     }
   3201     if (value->dataType == value->TYPE_STRING) {
   3202         return getTableStringBlock(stringBlock)->stringAt(value->data, outLen);
   3203     }
   3204     // XXX do int to string conversions.
   3205     return NULL;
   3206 }
   3207 
   3208 ssize_t ResTable::lockBag(uint32_t resID, const bag_entry** outBag) const
   3209 {
   3210     mLock.lock();
   3211     ssize_t err = getBagLocked(resID, outBag);
   3212     if (err < NO_ERROR) {
   3213         //printf("*** get failed!  unlocking\n");
   3214         mLock.unlock();
   3215     }
   3216     return err;
   3217 }
   3218 
   3219 void ResTable::unlockBag(const bag_entry* bag) const
   3220 {
   3221     //printf("<<< unlockBag %p\n", this);
   3222     mLock.unlock();
   3223 }
   3224 
   3225 void ResTable::lock() const
   3226 {
   3227     mLock.lock();
   3228 }
   3229 
   3230 void ResTable::unlock() const
   3231 {
   3232     mLock.unlock();
   3233 }
   3234 
   3235 ssize_t ResTable::getBagLocked(uint32_t resID, const bag_entry** outBag,
   3236         uint32_t* outTypeSpecFlags) const
   3237 {
   3238     if (mError != NO_ERROR) {
   3239         return mError;
   3240     }
   3241 
   3242     const ssize_t p = getResourcePackageIndex(resID);
   3243     const int t = Res_GETTYPE(resID);
   3244     const int e = Res_GETENTRY(resID);
   3245 
   3246     if (p < 0) {
   3247         ALOGW("Invalid package identifier when getting bag for resource number 0x%08x", resID);
   3248         return BAD_INDEX;
   3249     }
   3250     if (t < 0) {
   3251         ALOGW("No type identifier when getting bag for resource number 0x%08x", resID);
   3252         return BAD_INDEX;
   3253     }
   3254 
   3255     //printf("Get bag: id=0x%08x, p=%d, t=%d\n", resID, p, t);
   3256     PackageGroup* const grp = mPackageGroups[p];
   3257     if (grp == NULL) {
   3258         ALOGW("Bad identifier when getting bag for resource number 0x%08x", resID);
   3259         return false;
   3260     }
   3261 
   3262     if (t >= (int)grp->typeCount) {
   3263         ALOGW("Type identifier 0x%x is larger than type count 0x%x",
   3264              t+1, (int)grp->typeCount);
   3265         return BAD_INDEX;
   3266     }
   3267 
   3268     const Package* const basePackage = grp->packages[0];
   3269 
   3270     const Type* const typeConfigs = basePackage->getType(t);
   3271 
   3272     const size_t NENTRY = typeConfigs->entryCount;
   3273     if (e >= (int)NENTRY) {
   3274         ALOGW("Entry identifier 0x%x is larger than entry count 0x%x",
   3275              e, (int)typeConfigs->entryCount);
   3276         return BAD_INDEX;
   3277     }
   3278 
   3279     // First see if we've already computed this bag...
   3280     if (grp->bags) {
   3281         bag_set** typeSet = grp->bags[t];
   3282         if (typeSet) {
   3283             bag_set* set = typeSet[e];
   3284             if (set) {
   3285                 if (set != (bag_set*)0xFFFFFFFF) {
   3286                     if (outTypeSpecFlags != NULL) {
   3287                         *outTypeSpecFlags = set->typeSpecFlags;
   3288                     }
   3289                     *outBag = (bag_entry*)(set+1);
   3290                     //ALOGI("Found existing bag for: %p\n", (void*)resID);
   3291                     return set->numAttrs;
   3292                 }
   3293                 ALOGW("Attempt to retrieve bag 0x%08x which is invalid or in a cycle.",
   3294                      resID);
   3295                 return BAD_INDEX;
   3296             }
   3297         }
   3298     }
   3299 
   3300     // Bag not found, we need to compute it!
   3301     if (!grp->bags) {
   3302         grp->bags = (bag_set***)calloc(grp->typeCount, sizeof(bag_set*));
   3303         if (!grp->bags) return NO_MEMORY;
   3304     }
   3305 
   3306     bag_set** typeSet = grp->bags[t];
   3307     if (!typeSet) {
   3308         typeSet = (bag_set**)calloc(NENTRY, sizeof(bag_set*));
   3309         if (!typeSet) return NO_MEMORY;
   3310         grp->bags[t] = typeSet;
   3311     }
   3312 
   3313     // Mark that we are currently working on this one.
   3314     typeSet[e] = (bag_set*)0xFFFFFFFF;
   3315 
   3316     // This is what we are building.
   3317     bag_set* set = NULL;
   3318 
   3319     TABLE_NOISY(ALOGI("Building bag: %p\n", (void*)resID));
   3320 
   3321     ResTable_config bestConfig;
   3322     memset(&bestConfig, 0, sizeof(bestConfig));
   3323 
   3324     // Now collect all bag attributes from all packages.
   3325     size_t ip = grp->packages.size();
   3326     while (ip > 0) {
   3327         ip--;
   3328         int T = t;
   3329         int E = e;
   3330 
   3331         const Package* const package = grp->packages[ip];
   3332         if (package->header->resourceIDMap) {
   3333             uint32_t overlayResID = 0x0;
   3334             status_t retval = idmapLookup(package->header->resourceIDMap,
   3335                                           package->header->resourceIDMapSize,
   3336                                           resID, &overlayResID);
   3337             if (retval == NO_ERROR && overlayResID != 0x0) {
   3338                 // for this loop iteration, this is the type and entry we really want
   3339                 ALOGV("resource map 0x%08x -> 0x%08x\n", resID, overlayResID);
   3340                 T = Res_GETTYPE(overlayResID);
   3341                 E = Res_GETENTRY(overlayResID);
   3342             } else {
   3343                 // resource not present in overlay package, continue with the next package
   3344                 continue;
   3345             }
   3346         }
   3347 
   3348         const ResTable_type* type;
   3349         const ResTable_entry* entry;
   3350         const Type* typeClass;
   3351         ALOGV("Getting entry pkg=%p, t=%d, e=%d\n", package, T, E);
   3352         ssize_t offset = getEntry(package, T, E, &mParams, &type, &entry, &typeClass);
   3353         ALOGV("Resulting offset=%d\n", offset);
   3354         if (offset <= 0) {
   3355             // No {entry, appropriate config} pair found in package. If this
   3356             // package is an overlay package (ip != 0), this simply means the
   3357             // overlay package did not specify a default.
   3358             // Non-overlay packages are still required to provide a default.
   3359             if (offset < 0 && ip == 0) {
   3360                 if (set) free(set);
   3361                 return offset;
   3362             }
   3363             continue;
   3364         }
   3365 
   3366         if ((dtohs(entry->flags)&entry->FLAG_COMPLEX) == 0) {
   3367             ALOGW("Skipping entry %p in package table %d because it is not complex!\n",
   3368                  (void*)resID, (int)ip);
   3369             continue;
   3370         }
   3371 
   3372         if (set != NULL && !type->config.isBetterThan(bestConfig, NULL)) {
   3373             continue;
   3374         }
   3375         bestConfig = type->config;
   3376         if (set) {
   3377             free(set);
   3378             set = NULL;
   3379         }
   3380 
   3381         const uint16_t entrySize = dtohs(entry->size);
   3382         const uint32_t parent = entrySize >= sizeof(ResTable_map_entry)
   3383             ? dtohl(((const ResTable_map_entry*)entry)->parent.ident) : 0;
   3384         const uint32_t count = entrySize >= sizeof(ResTable_map_entry)
   3385             ? dtohl(((const ResTable_map_entry*)entry)->count) : 0;
   3386 
   3387         size_t N = count;
   3388 
   3389         TABLE_NOISY(ALOGI("Found map: size=%p parent=%p count=%d\n",
   3390                          entrySize, parent, count));
   3391 
   3392         // If this map inherits from another, we need to start
   3393         // with its parent's values.  Otherwise start out empty.
   3394         TABLE_NOISY(printf("Creating new bag, entrySize=0x%08x, parent=0x%08x\n",
   3395                            entrySize, parent));
   3396         if (parent) {
   3397             const bag_entry* parentBag;
   3398             uint32_t parentTypeSpecFlags = 0;
   3399             const ssize_t NP = getBagLocked(parent, &parentBag, &parentTypeSpecFlags);
   3400             const size_t NT = ((NP >= 0) ? NP : 0) + N;
   3401             set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*NT);
   3402             if (set == NULL) {
   3403                 return NO_MEMORY;
   3404             }
   3405             if (NP > 0) {
   3406                 memcpy(set+1, parentBag, NP*sizeof(bag_entry));
   3407                 set->numAttrs = NP;
   3408                 TABLE_NOISY(ALOGI("Initialized new bag with %d inherited attributes.\n", NP));
   3409             } else {
   3410                 TABLE_NOISY(ALOGI("Initialized new bag with no inherited attributes.\n"));
   3411                 set->numAttrs = 0;
   3412             }
   3413             set->availAttrs = NT;
   3414             set->typeSpecFlags = parentTypeSpecFlags;
   3415         } else {
   3416             set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*N);
   3417             if (set == NULL) {
   3418                 return NO_MEMORY;
   3419             }
   3420             set->numAttrs = 0;
   3421             set->availAttrs = N;
   3422             set->typeSpecFlags = 0;
   3423         }
   3424 
   3425         if (typeClass->typeSpecFlags != NULL) {
   3426             set->typeSpecFlags |= dtohl(typeClass->typeSpecFlags[E]);
   3427         } else {
   3428             set->typeSpecFlags = -1;
   3429         }
   3430 
   3431         // Now merge in the new attributes...
   3432         ssize_t curOff = offset;
   3433         const ResTable_map* map;
   3434         bag_entry* entries = (bag_entry*)(set+1);
   3435         size_t curEntry = 0;
   3436         uint32_t pos = 0;
   3437         TABLE_NOISY(ALOGI("Starting with set %p, entries=%p, avail=%d\n",
   3438                      set, entries, set->availAttrs));
   3439         while (pos < count) {
   3440             TABLE_NOISY(printf("Now at %p\n", (void*)curOff));
   3441 
   3442             if ((size_t)curOff > (dtohl(type->header.size)-sizeof(ResTable_map))) {
   3443                 ALOGW("ResTable_map at %d is beyond type chunk data %d",
   3444                      (int)curOff, dtohl(type->header.size));
   3445                 return BAD_TYPE;
   3446             }
   3447             map = (const ResTable_map*)(((const uint8_t*)type) + curOff);
   3448             N++;
   3449 
   3450             const uint32_t newName = htodl(map->name.ident);
   3451             bool isInside;
   3452             uint32_t oldName = 0;
   3453             while ((isInside=(curEntry < set->numAttrs))
   3454                     && (oldName=entries[curEntry].map.name.ident) < newName) {
   3455                 TABLE_NOISY(printf("#%d: Keeping existing attribute: 0x%08x\n",
   3456                              curEntry, entries[curEntry].map.name.ident));
   3457                 curEntry++;
   3458             }
   3459 
   3460             if ((!isInside) || oldName != newName) {
   3461                 // This is a new attribute...  figure out what to do with it.
   3462                 if (set->numAttrs >= set->availAttrs) {
   3463                     // Need to alloc more memory...
   3464                     const size_t newAvail = set->availAttrs+N;
   3465                     set = (bag_set*)realloc(set,
   3466                                             sizeof(bag_set)
   3467                                             + sizeof(bag_entry)*newAvail);
   3468                     if (set == NULL) {
   3469                         return NO_MEMORY;
   3470                     }
   3471                     set->availAttrs = newAvail;
   3472                     entries = (bag_entry*)(set+1);
   3473                     TABLE_NOISY(printf("Reallocated set %p, entries=%p, avail=%d\n",
   3474                                  set, entries, set->availAttrs));
   3475                 }
   3476                 if (isInside) {
   3477                     // Going in the middle, need to make space.
   3478                     memmove(entries+curEntry+1, entries+curEntry,
   3479                             sizeof(bag_entry)*(set->numAttrs-curEntry));
   3480                     set->numAttrs++;
   3481                 }
   3482                 TABLE_NOISY(printf("#%d: Inserting new attribute: 0x%08x\n",
   3483                              curEntry, newName));
   3484             } else {
   3485                 TABLE_NOISY(printf("#%d: Replacing existing attribute: 0x%08x\n",
   3486                              curEntry, oldName));
   3487             }
   3488 
   3489             bag_entry* cur = entries+curEntry;
   3490 
   3491             cur->stringBlock = package->header->index;
   3492             cur->map.name.ident = newName;
   3493             cur->map.value.copyFrom_dtoh(map->value);
   3494             TABLE_NOISY(printf("Setting entry #%d %p: block=%d, name=0x%08x, type=%d, data=0x%08x\n",
   3495                          curEntry, cur, cur->stringBlock, cur->map.name.ident,
   3496                          cur->map.value.dataType, cur->map.value.data));
   3497 
   3498             // On to the next!
   3499             curEntry++;
   3500             pos++;
   3501             const size_t size = dtohs(map->value.size);
   3502             curOff += size + sizeof(*map)-sizeof(map->value);
   3503         };
   3504         if (curEntry > set->numAttrs) {
   3505             set->numAttrs = curEntry;
   3506         }
   3507     }
   3508 
   3509     // And this is it...
   3510     typeSet[e] = set;
   3511     if (set) {
   3512         if (outTypeSpecFlags != NULL) {
   3513             *outTypeSpecFlags = set->typeSpecFlags;
   3514         }
   3515         *outBag = (bag_entry*)(set+1);
   3516         TABLE_NOISY(ALOGI("Returning %d attrs\n", set->numAttrs));
   3517         return set->numAttrs;
   3518     }
   3519     return BAD_INDEX;
   3520 }
   3521 
   3522 void ResTable::setParameters(const ResTable_config* params)
   3523 {
   3524     mLock.lock();
   3525     TABLE_GETENTRY(ALOGI("Setting parameters: %s\n", params->toString().string()));
   3526     mParams = *params;
   3527     for (size_t i=0; i<mPackageGroups.size(); i++) {
   3528         TABLE_NOISY(ALOGI("CLEARING BAGS FOR GROUP %d!", i));
   3529         mPackageGroups[i]->clearBagCache();
   3530     }
   3531     mLock.unlock();
   3532 }
   3533 
   3534 void ResTable::getParameters(ResTable_config* params) const
   3535 {
   3536     mLock.lock();
   3537     *params = mParams;
   3538     mLock.unlock();
   3539 }
   3540 
   3541 struct id_name_map {
   3542     uint32_t id;
   3543     size_t len;
   3544     char16_t name[6];
   3545 };
   3546 
   3547 const static id_name_map ID_NAMES[] = {
   3548     { ResTable_map::ATTR_TYPE,  5, { '^', 't', 'y', 'p', 'e' } },
   3549     { ResTable_map::ATTR_L10N,  5, { '^', 'l', '1', '0', 'n' } },
   3550     { ResTable_map::ATTR_MIN,   4, { '^', 'm', 'i', 'n' } },
   3551     { ResTable_map::ATTR_MAX,   4, { '^', 'm', 'a', 'x' } },
   3552     { ResTable_map::ATTR_OTHER, 6, { '^', 'o', 't', 'h', 'e', 'r' } },
   3553     { ResTable_map::ATTR_ZERO,  5, { '^', 'z', 'e', 'r', 'o' } },
   3554     { ResTable_map::ATTR_ONE,   4, { '^', 'o', 'n', 'e' } },
   3555     { ResTable_map::ATTR_TWO,   4, { '^', 't', 'w', 'o' } },
   3556     { ResTable_map::ATTR_FEW,   4, { '^', 'f', 'e', 'w' } },
   3557     { ResTable_map::ATTR_MANY,  5, { '^', 'm', 'a', 'n', 'y' } },
   3558 };
   3559 
   3560 uint32_t ResTable::identifierForName(const char16_t* name, size_t nameLen,
   3561                                      const char16_t* type, size_t typeLen,
   3562                                      const char16_t* package,
   3563                                      size_t packageLen,
   3564                                      uint32_t* outTypeSpecFlags) const
   3565 {
   3566     TABLE_SUPER_NOISY(printf("Identifier for name: error=%d\n", mError));
   3567 
   3568     // Check for internal resource identifier as the very first thing, so
   3569     // that we will always find them even when there are no resources.
   3570     if (name[0] == '^') {
   3571         const int N = (sizeof(ID_NAMES)/sizeof(ID_NAMES[0]));
   3572         size_t len;
   3573         for (int i=0; i<N; i++) {
   3574             const id_name_map* m = ID_NAMES + i;
   3575             len = m->len;
   3576             if (len != nameLen) {
   3577                 continue;
   3578             }
   3579             for (size_t j=1; j<len; j++) {
   3580                 if (m->name[j] != name[j]) {
   3581                     goto nope;
   3582                 }
   3583             }
   3584             if (outTypeSpecFlags) {
   3585                 *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC;
   3586             }
   3587             return m->id;
   3588 nope:
   3589             ;
   3590         }
   3591         if (nameLen > 7) {
   3592             if (name[1] == 'i' && name[2] == 'n'
   3593                 && name[3] == 'd' && name[4] == 'e' && name[5] == 'x'
   3594                 && name[6] == '_') {
   3595                 int index = atoi(String8(name + 7, nameLen - 7).string());
   3596                 if (Res_CHECKID(index)) {
   3597                     ALOGW("Array resource index: %d is too large.",
   3598                          index);
   3599                     return 0;
   3600                 }
   3601                 if (outTypeSpecFlags) {
   3602                     *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC;
   3603                 }
   3604                 return  Res_MAKEARRAY(index);
   3605             }
   3606         }
   3607         return 0;
   3608     }
   3609 
   3610     if (mError != NO_ERROR) {
   3611         return 0;
   3612     }
   3613 
   3614     bool fakePublic = false;
   3615 
   3616     // Figure out the package and type we are looking in...
   3617 
   3618     const char16_t* packageEnd = NULL;
   3619     const char16_t* typeEnd = NULL;
   3620     const char16_t* const nameEnd = name+nameLen;
   3621     const char16_t* p = name;
   3622     while (p < nameEnd) {
   3623         if (*p == ':') packageEnd = p;
   3624         else if (*p == '/') typeEnd = p;
   3625         p++;
   3626     }
   3627     if (*name == '@') {
   3628         name++;
   3629         if (*name == '*') {
   3630             fakePublic = true;
   3631             name++;
   3632         }
   3633     }
   3634     if (name >= nameEnd) {
   3635         return 0;
   3636     }
   3637 
   3638     if (packageEnd) {
   3639         package = name;
   3640         packageLen = packageEnd-name;
   3641         name = packageEnd+1;
   3642     } else if (!package) {
   3643         return 0;
   3644     }
   3645 
   3646     if (typeEnd) {
   3647         type = name;
   3648         typeLen = typeEnd-name;
   3649         name = typeEnd+1;
   3650     } else if (!type) {
   3651         return 0;
   3652     }
   3653 
   3654     if (name >= nameEnd) {
   3655         return 0;
   3656     }
   3657     nameLen = nameEnd-name;
   3658 
   3659     TABLE_NOISY(printf("Looking for identifier: type=%s, name=%s, package=%s\n",
   3660                  String8(type, typeLen).string(),
   3661                  String8(name, nameLen).string(),
   3662                  String8(package, packageLen).string()));
   3663 
   3664     const size_t NG = mPackageGroups.size();
   3665     for (size_t ig=0; ig<NG; ig++) {
   3666         const PackageGroup* group = mPackageGroups[ig];
   3667 
   3668         if (strzcmp16(package, packageLen,
   3669                       group->name.string(), group->name.size())) {
   3670             TABLE_NOISY(printf("Skipping package group: %s\n", String8(group->name).string()));
   3671             continue;
   3672         }
   3673 
   3674         const ssize_t ti = group->basePackage->typeStrings.indexOfString(type, typeLen);
   3675         if (ti < 0) {
   3676             TABLE_NOISY(printf("Type not found in package %s\n", String8(group->name).string()));
   3677             continue;
   3678         }
   3679 
   3680         const ssize_t ei = group->basePackage->keyStrings.indexOfString(name, nameLen);
   3681         if (ei < 0) {
   3682             TABLE_NOISY(printf("Name not found in package %s\n", String8(group->name).string()));
   3683             continue;
   3684         }
   3685 
   3686         TABLE_NOISY(printf("Search indices: type=%d, name=%d\n", ti, ei));
   3687 
   3688         const Type* const typeConfigs = group->packages[0]->getType(ti);
   3689         if (typeConfigs == NULL || typeConfigs->configs.size() <= 0) {
   3690             TABLE_NOISY(printf("Expected type structure not found in package %s for idnex %d\n",
   3691                                String8(group->name).string(), ti));
   3692         }
   3693 
   3694         size_t NTC = typeConfigs->configs.size();
   3695         for (size_t tci=0; tci<NTC; tci++) {
   3696             const ResTable_type* const ty = typeConfigs->configs[tci];
   3697             const uint32_t typeOffset = dtohl(ty->entriesStart);
   3698 
   3699             const uint8_t* const end = ((const uint8_t*)ty) + dtohl(ty->header.size);
   3700             const uint32_t* const eindex = (const uint32_t*)
   3701                 (((const uint8_t*)ty) + dtohs(ty->header.headerSize));
   3702 
   3703             const size_t NE = dtohl(ty->entryCount);
   3704             for (size_t i=0; i<NE; i++) {
   3705                 uint32_t offset = dtohl(eindex[i]);
   3706                 if (offset == ResTable_type::NO_ENTRY) {
   3707                     continue;
   3708                 }
   3709 
   3710                 offset += typeOffset;
   3711 
   3712                 if (offset > (dtohl(ty->header.size)-sizeof(ResTable_entry))) {
   3713                     ALOGW("ResTable_entry at %d is beyond type chunk data %d",
   3714                          offset, dtohl(ty->header.size));
   3715                     return 0;
   3716                 }
   3717                 if ((offset&0x3) != 0) {
   3718                     ALOGW("ResTable_entry at %d (pkg=%d type=%d ent=%d) is not on an integer boundary when looking for %s:%s/%s",
   3719                          (int)offset, (int)group->id, (int)ti+1, (int)i,
   3720                          String8(package, packageLen).string(),
   3721                          String8(type, typeLen).string(),
   3722                          String8(name, nameLen).string());
   3723                     return 0;
   3724                 }
   3725 
   3726                 const ResTable_entry* const entry = (const ResTable_entry*)
   3727                     (((const uint8_t*)ty) + offset);
   3728                 if (dtohs(entry->size) < sizeof(*entry)) {
   3729                     ALOGW("ResTable_entry size %d is too small", dtohs(entry->size));
   3730                     return BAD_TYPE;
   3731                 }
   3732 
   3733                 TABLE_SUPER_NOISY(printf("Looking at entry #%d: want str %d, have %d\n",
   3734                                          i, ei, dtohl(entry->key.index)));
   3735                 if (dtohl(entry->key.index) == (size_t)ei) {
   3736                     if (outTypeSpecFlags) {
   3737                         *outTypeSpecFlags = typeConfigs->typeSpecFlags[i];
   3738                         if (fakePublic) {
   3739                             *outTypeSpecFlags |= ResTable_typeSpec::SPEC_PUBLIC;
   3740                         }
   3741                     }
   3742                     return Res_MAKEID(group->id-1, ti, i);
   3743                 }
   3744             }
   3745         }
   3746     }
   3747 
   3748     return 0;
   3749 }
   3750 
   3751 bool ResTable::expandResourceRef(const uint16_t* refStr, size_t refLen,
   3752                                  String16* outPackage,
   3753                                  String16* outType,
   3754                                  String16* outName,
   3755                                  const String16* defType,
   3756                                  const String16* defPackage,
   3757                                  const char** outErrorMsg,
   3758                                  bool* outPublicOnly)
   3759 {
   3760     const char16_t* packageEnd = NULL;
   3761     const char16_t* typeEnd = NULL;
   3762     const char16_t* p = refStr;
   3763     const char16_t* const end = p + refLen;
   3764     while (p < end) {
   3765         if (*p == ':') packageEnd = p;
   3766         else if (*p == '/') {
   3767             typeEnd = p;
   3768             break;
   3769         }
   3770         p++;
   3771     }
   3772     p = refStr;
   3773     if (*p == '@') p++;
   3774 
   3775     if (outPublicOnly != NULL) {
   3776         *outPublicOnly = true;
   3777     }
   3778     if (*p == '*') {
   3779         p++;
   3780         if (outPublicOnly != NULL) {
   3781             *outPublicOnly = false;
   3782         }
   3783     }
   3784 
   3785     if (packageEnd) {
   3786         *outPackage = String16(p, packageEnd-p);
   3787         p = packageEnd+1;
   3788     } else {
   3789         if (!defPackage) {
   3790             if (outErrorMsg) {
   3791                 *outErrorMsg = "No resource package specified";
   3792             }
   3793             return false;
   3794         }
   3795         *outPackage = *defPackage;
   3796     }
   3797     if (typeEnd) {
   3798         *outType = String16(p, typeEnd-p);
   3799         p = typeEnd+1;
   3800     } else {
   3801         if (!defType) {
   3802             if (outErrorMsg) {
   3803                 *outErrorMsg = "No resource type specified";
   3804             }
   3805             return false;
   3806         }
   3807         *outType = *defType;
   3808     }
   3809     *outName = String16(p, end-p);
   3810     if(**outPackage == 0) {
   3811         if(outErrorMsg) {
   3812             *outErrorMsg = "Resource package cannot be an empty string";
   3813         }
   3814         return false;
   3815     }
   3816     if(**outType == 0) {
   3817         if(outErrorMsg) {
   3818             *outErrorMsg = "Resource type cannot be an empty string";
   3819         }
   3820         return false;
   3821     }
   3822     if(**outName == 0) {
   3823         if(outErrorMsg) {
   3824             *outErrorMsg = "Resource id cannot be an empty string";
   3825         }
   3826         return false;
   3827     }
   3828     return true;
   3829 }
   3830 
   3831 static uint32_t get_hex(char c, bool* outError)
   3832 {
   3833     if (c >= '0' && c <= '9') {
   3834         return c - '0';
   3835     } else if (c >= 'a' && c <= 'f') {
   3836         return c - 'a' + 0xa;
   3837     } else if (c >= 'A' && c <= 'F') {
   3838         return c - 'A' + 0xa;
   3839     }
   3840     *outError = true;
   3841     return 0;
   3842 }
   3843 
   3844 struct unit_entry
   3845 {
   3846     const char* name;
   3847     size_t len;
   3848     uint8_t type;
   3849     uint32_t unit;
   3850     float scale;
   3851 };
   3852 
   3853 static const unit_entry unitNames[] = {
   3854     { "px", strlen("px"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PX, 1.0f },
   3855     { "dip", strlen("dip"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
   3856     { "dp", strlen("dp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
   3857     { "sp", strlen("sp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_SP, 1.0f },
   3858     { "pt", strlen("pt"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PT, 1.0f },
   3859     { "in", strlen("in"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_IN, 1.0f },
   3860     { "mm", strlen("mm"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_MM, 1.0f },
   3861     { "%", strlen("%"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION, 1.0f/100 },
   3862     { "%p", strlen("%p"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION_PARENT, 1.0f/100 },
   3863     { NULL, 0, 0, 0, 0 }
   3864 };
   3865 
   3866 static bool parse_unit(const char* str, Res_value* outValue,
   3867                        float* outScale, const char** outEnd)
   3868 {
   3869     const char* end = str;
   3870     while (*end != 0 && !isspace((unsigned char)*end)) {
   3871         end++;
   3872     }
   3873     const size_t len = end-str;
   3874 
   3875     const char* realEnd = end;
   3876     while (*realEnd != 0 && isspace((unsigned char)*realEnd)) {
   3877         realEnd++;
   3878     }
   3879     if (*realEnd != 0) {
   3880         return false;
   3881     }
   3882 
   3883     const unit_entry* cur = unitNames;
   3884     while (cur->name) {
   3885         if (len == cur->len && strncmp(cur->name, str, len) == 0) {
   3886             outValue->dataType = cur->type;
   3887             outValue->data = cur->unit << Res_value::COMPLEX_UNIT_SHIFT;
   3888             *outScale = cur->scale;
   3889             *outEnd = end;
   3890             //printf("Found unit %s for %s\n", cur->name, str);
   3891             return true;
   3892         }
   3893         cur++;
   3894     }
   3895 
   3896     return false;
   3897 }
   3898 
   3899 
   3900 bool ResTable::stringToInt(const char16_t* s, size_t len, Res_value* outValue)
   3901 {
   3902     while (len > 0 && isspace16(*s)) {
   3903         s++;
   3904         len--;
   3905     }
   3906 
   3907     if (len <= 0) {
   3908         return false;
   3909     }
   3910 
   3911     size_t i = 0;
   3912     int32_t val = 0;
   3913     bool neg = false;
   3914 
   3915     if (*s == '-') {
   3916         neg = true;
   3917         i++;
   3918     }
   3919 
   3920     if (s[i] < '0' || s[i] > '9') {
   3921         return false;
   3922     }
   3923 
   3924     // Decimal or hex?
   3925     if (s[i] == '0' && s[i+1] == 'x') {
   3926         if (outValue)
   3927             outValue->dataType = outValue->TYPE_INT_HEX;
   3928         i += 2;
   3929         bool error = false;
   3930         while (i < len && !error) {
   3931             val = (val*16) + get_hex(s[i], &error);
   3932             i++;
   3933         }
   3934         if (error) {
   3935             return false;
   3936         }
   3937     } else {
   3938         if (outValue)
   3939             outValue->dataType = outValue->TYPE_INT_DEC;
   3940         while (i < len) {
   3941             if (s[i] < '0' || s[i] > '9') {
   3942                 return false;
   3943             }
   3944             val = (val*10) + s[i]-'0';
   3945             i++;
   3946         }
   3947     }
   3948 
   3949     if (neg) val = -val;
   3950 
   3951     while (i < len && isspace16(s[i])) {
   3952         i++;
   3953     }
   3954 
   3955     if (i == len) {
   3956         if (outValue)
   3957             outValue->data = val;
   3958         return true;
   3959     }
   3960 
   3961     return false;
   3962 }
   3963 
   3964 bool ResTable::stringToFloat(const char16_t* s, size_t len, Res_value* outValue)
   3965 {
   3966     while (len > 0 && isspace16(*s)) {
   3967         s++;
   3968         len--;
   3969     }
   3970 
   3971     if (len <= 0) {
   3972         return false;
   3973     }
   3974 
   3975     char buf[128];
   3976     int i=0;
   3977     while (len > 0 && *s != 0 && i < 126) {
   3978         if (*s > 255) {
   3979             return false;
   3980         }
   3981         buf[i++] = *s++;
   3982         len--;
   3983     }
   3984 
   3985     if (len > 0) {
   3986         return false;
   3987     }
   3988     if (buf[0] < '0' && buf[0] > '9' && buf[0] != '.') {
   3989         return false;
   3990     }
   3991 
   3992     buf[i] = 0;
   3993     const char* end;
   3994     float f = strtof(buf, (char**)&end);
   3995 
   3996     if (*end != 0 && !isspace((unsigned char)*end)) {
   3997         // Might be a unit...
   3998         float scale;
   3999         if (parse_unit(end, outValue, &scale, &end)) {
   4000             f *= scale;
   4001             const bool neg = f < 0;
   4002             if (neg) f = -f;
   4003             uint64_t bits = (uint64_t)(f*(1<<23)+.5f);
   4004             uint32_t radix;
   4005             uint32_t shift;
   4006             if ((bits&0x7fffff) == 0) {
   4007                 // Always use 23p0 if there is no fraction, just to make
   4008                 // things easier to read.
   4009                 radix = Res_value::COMPLEX_RADIX_23p0;
   4010                 shift = 23;
   4011             } else if ((bits&0xffffffffff800000LL) == 0) {
   4012                 // Magnitude is zero -- can fit in 0 bits of precision.
   4013                 radix = Res_value::COMPLEX_RADIX_0p23;
   4014                 shift = 0;
   4015             } else if ((bits&0xffffffff80000000LL) == 0) {
   4016                 // Magnitude can fit in 8 bits of precision.
   4017                 radix = Res_value::COMPLEX_RADIX_8p15;
   4018                 shift = 8;
   4019             } else if ((bits&0xffffff8000000000LL) == 0) {
   4020                 // Magnitude can fit in 16 bits of precision.
   4021                 radix = Res_value::COMPLEX_RADIX_16p7;
   4022                 shift = 16;
   4023             } else {
   4024                 // Magnitude needs entire range, so no fractional part.
   4025                 radix = Res_value::COMPLEX_RADIX_23p0;
   4026                 shift = 23;
   4027             }
   4028             int32_t mantissa = (int32_t)(
   4029                 (bits>>shift) & Res_value::COMPLEX_MANTISSA_MASK);
   4030             if (neg) {
   4031                 mantissa = (-mantissa) & Res_value::COMPLEX_MANTISSA_MASK;
   4032             }
   4033             outValue->data |=
   4034                 (radix<<Res_value::COMPLEX_RADIX_SHIFT)
   4035                 | (mantissa<<Res_value::COMPLEX_MANTISSA_SHIFT);
   4036             //printf("Input value: %f 0x%016Lx, mult: %f, radix: %d, shift: %d, final: 0x%08x\n",
   4037             //       f * (neg ? -1 : 1), bits, f*(1<<23),
   4038             //       radix, shift, outValue->data);
   4039             return true;
   4040         }
   4041         return false;
   4042     }
   4043 
   4044     while (*end != 0 && isspace((unsigned char)*end)) {
   4045         end++;
   4046     }
   4047 
   4048     if (*end == 0) {
   4049         if (outValue) {
   4050             outValue->dataType = outValue->TYPE_FLOAT;
   4051             *(float*)(&outValue->data) = f;
   4052             return true;
   4053         }
   4054     }
   4055 
   4056     return false;
   4057 }
   4058 
   4059 bool ResTable::stringToValue(Res_value* outValue, String16* outString,
   4060                              const char16_t* s, size_t len,
   4061                              bool preserveSpaces, bool coerceType,
   4062                              uint32_t attrID,
   4063                              const String16* defType,
   4064                              const String16* defPackage,
   4065                              Accessor* accessor,
   4066                              void* accessorCookie,
   4067                              uint32_t attrType,
   4068                              bool enforcePrivate) const
   4069 {
   4070     bool localizationSetting = accessor != NULL && accessor->getLocalizationSetting();
   4071     const char* errorMsg = NULL;
   4072 
   4073     outValue->size = sizeof(Res_value);
   4074     outValue->res0 = 0;
   4075 
   4076     // First strip leading/trailing whitespace.  Do this before handling
   4077     // escapes, so they can be used to force whitespace into the string.
   4078     if (!preserveSpaces) {
   4079         while (len > 0 && isspace16(*s)) {
   4080             s++;
   4081             len--;
   4082         }
   4083         while (len > 0 && isspace16(s[len-1])) {
   4084             len--;
   4085         }
   4086         // If the string ends with '\', then we keep the space after it.
   4087         if (len > 0 && s[len-1] == '\\' && s[len] != 0) {
   4088             len++;
   4089         }
   4090     }
   4091 
   4092     //printf("Value for: %s\n", String8(s, len).string());
   4093 
   4094     uint32_t l10nReq = ResTable_map::L10N_NOT_REQUIRED;
   4095     uint32_t attrMin = 0x80000000, attrMax = 0x7fffffff;
   4096     bool fromAccessor = false;
   4097     if (attrID != 0 && !Res_INTERNALID(attrID)) {
   4098         const ssize_t p = getResourcePackageIndex(attrID);
   4099         const bag_entry* bag;
   4100         ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
   4101         //printf("For attr 0x%08x got bag of %d\n", attrID, cnt);
   4102         if (cnt >= 0) {
   4103             while (cnt > 0) {
   4104                 //printf("Entry 0x%08x = 0x%08x\n", bag->map.name.ident, bag->map.value.data);
   4105                 switch (bag->map.name.ident) {
   4106                 case ResTable_map::ATTR_TYPE:
   4107                     attrType = bag->map.value.data;
   4108                     break;
   4109                 case ResTable_map::ATTR_MIN:
   4110                     attrMin = bag->map.value.data;
   4111                     break;
   4112                 case ResTable_map::ATTR_MAX:
   4113                     attrMax = bag->map.value.data;
   4114                     break;
   4115                 case ResTable_map::ATTR_L10N:
   4116                     l10nReq = bag->map.value.data;
   4117                     break;
   4118                 }
   4119                 bag++;
   4120                 cnt--;
   4121             }
   4122             unlockBag(bag);
   4123         } else if (accessor && accessor->getAttributeType(attrID, &attrType)) {
   4124             fromAccessor = true;
   4125             if (attrType == ResTable_map::TYPE_ENUM
   4126                     || attrType == ResTable_map::TYPE_FLAGS
   4127                     || attrType == ResTable_map::TYPE_INTEGER) {
   4128                 accessor->getAttributeMin(attrID, &attrMin);
   4129                 accessor->getAttributeMax(attrID, &attrMax);
   4130             }
   4131             if (localizationSetting) {
   4132                 l10nReq = accessor->getAttributeL10N(attrID);
   4133             }
   4134         }
   4135     }
   4136 
   4137     const bool canStringCoerce =
   4138         coerceType && (attrType&ResTable_map::TYPE_STRING) != 0;
   4139 
   4140     if (*s == '@') {
   4141         outValue->dataType = outValue->TYPE_REFERENCE;
   4142 
   4143         // Note: we don't check attrType here because the reference can
   4144         // be to any other type; we just need to count on the client making
   4145         // sure the referenced type is correct.
   4146 
   4147         //printf("Looking up ref: %s\n", String8(s, len).string());
   4148 
   4149         // It's a reference!
   4150         if (len == 5 && s[1]=='n' && s[2]=='u' && s[3]=='l' && s[4]=='l') {
   4151             outValue->data = 0;
   4152             return true;
   4153         } else {
   4154             bool createIfNotFound = false;
   4155             const char16_t* resourceRefName;
   4156             int resourceNameLen;
   4157             if (len > 2 && s[1] == '+') {
   4158                 createIfNotFound = true;
   4159                 resourceRefName = s + 2;
   4160                 resourceNameLen = len - 2;
   4161             } else if (len > 2 && s[1] == '*') {
   4162                 enforcePrivate = false;
   4163                 resourceRefName = s + 2;
   4164                 resourceNameLen = len - 2;
   4165             } else {
   4166                 createIfNotFound = false;
   4167                 resourceRefName = s + 1;
   4168                 resourceNameLen = len - 1;
   4169             }
   4170             String16 package, type, name;
   4171             if (!expandResourceRef(resourceRefName,resourceNameLen, &package, &type, &name,
   4172                                    defType, defPackage, &errorMsg)) {
   4173                 if (accessor != NULL) {
   4174                     accessor->reportError(accessorCookie, errorMsg);
   4175                 }
   4176                 return false;
   4177             }
   4178 
   4179             uint32_t specFlags = 0;
   4180             uint32_t rid = identifierForName(name.string(), name.size(), type.string(),
   4181                     type.size(), package.string(), package.size(), &specFlags);
   4182             if (rid != 0) {
   4183                 if (enforcePrivate) {
   4184                     if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
   4185                         if (accessor != NULL) {
   4186                             accessor->reportError(accessorCookie, "Resource is not public.");
   4187                         }
   4188                         return false;
   4189                     }
   4190                 }
   4191                 if (!accessor) {
   4192                     outValue->data = rid;
   4193                     return true;
   4194                 }
   4195                 rid = Res_MAKEID(
   4196                     accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
   4197                     Res_GETTYPE(rid), Res_GETENTRY(rid));
   4198                 TABLE_NOISY(printf("Incl %s:%s/%s: 0x%08x\n",
   4199                        String8(package).string(), String8(type).string(),
   4200                        String8(name).string(), rid));
   4201                 outValue->data = rid;
   4202                 return true;
   4203             }
   4204 
   4205             if (accessor) {
   4206                 uint32_t rid = accessor->getCustomResourceWithCreation(package, type, name,
   4207                                                                        createIfNotFound);
   4208                 if (rid != 0) {
   4209                     TABLE_NOISY(printf("Pckg %s:%s/%s: 0x%08x\n",
   4210                            String8(package).string(), String8(type).string(),
   4211                            String8(name).string(), rid));
   4212                     outValue->data = rid;
   4213                     return true;
   4214                 }
   4215             }
   4216         }
   4217 
   4218         if (accessor != NULL) {
   4219             accessor->reportError(accessorCookie, "No resource found that matches the given name");
   4220         }
   4221         return false;
   4222     }
   4223 
   4224     // if we got to here, and localization is required and it's not a reference,
   4225     // complain and bail.
   4226     if (l10nReq == ResTable_map::L10N_SUGGESTED) {
   4227         if (localizationSetting) {
   4228             if (accessor != NULL) {
   4229                 accessor->reportError(accessorCookie, "This attribute must be localized.");
   4230             }
   4231         }
   4232     }
   4233 
   4234     if (*s == '#') {
   4235         // It's a color!  Convert to an integer of the form 0xaarrggbb.
   4236         uint32_t color = 0;
   4237         bool error = false;
   4238         if (len == 4) {
   4239             outValue->dataType = outValue->TYPE_INT_COLOR_RGB4;
   4240             color |= 0xFF000000;
   4241             color |= get_hex(s[1], &error) << 20;
   4242             color |= get_hex(s[1], &error) << 16;
   4243             color |= get_hex(s[2], &error) << 12;
   4244             color |= get_hex(s[2], &error) << 8;
   4245             color |= get_hex(s[3], &error) << 4;
   4246             color |= get_hex(s[3], &error);
   4247         } else if (len == 5) {
   4248             outValue->dataType = outValue->TYPE_INT_COLOR_ARGB4;
   4249             color |= get_hex(s[1], &error) << 28;
   4250             color |= get_hex(s[1], &error) << 24;
   4251             color |= get_hex(s[2], &error) << 20;
   4252             color |= get_hex(s[2], &error) << 16;
   4253             color |= get_hex(s[3], &error) << 12;
   4254             color |= get_hex(s[3], &error) << 8;
   4255             color |= get_hex(s[4], &error) << 4;
   4256             color |= get_hex(s[4], &error);
   4257         } else if (len == 7) {
   4258             outValue->dataType = outValue->TYPE_INT_COLOR_RGB8;
   4259             color |= 0xFF000000;
   4260             color |= get_hex(s[1], &error) << 20;
   4261             color |= get_hex(s[2], &error) << 16;
   4262             color |= get_hex(s[3], &error) << 12;
   4263             color |= get_hex(s[4], &error) << 8;
   4264             color |= get_hex(s[5], &error) << 4;
   4265             color |= get_hex(s[6], &error);
   4266         } else if (len == 9) {
   4267             outValue->dataType = outValue->TYPE_INT_COLOR_ARGB8;
   4268             color |= get_hex(s[1], &error) << 28;
   4269             color |= get_hex(s[2], &error) << 24;
   4270             color |= get_hex(s[3], &error) << 20;
   4271             color |= get_hex(s[4], &error) << 16;
   4272             color |= get_hex(s[5], &error) << 12;
   4273             color |= get_hex(s[6], &error) << 8;
   4274             color |= get_hex(s[7], &error) << 4;
   4275             color |= get_hex(s[8], &error);
   4276         } else {
   4277             error = true;
   4278         }
   4279         if (!error) {
   4280             if ((attrType&ResTable_map::TYPE_COLOR) == 0) {
   4281                 if (!canStringCoerce) {
   4282                     if (accessor != NULL) {
   4283                         accessor->reportError(accessorCookie,
   4284                                 "Color types not allowed");
   4285                     }
   4286                     return false;
   4287                 }
   4288             } else {
   4289                 outValue->data = color;
   4290                 //printf("Color input=%s, output=0x%x\n", String8(s, len).string(), color);
   4291                 return true;
   4292             }
   4293         } else {
   4294             if ((attrType&ResTable_map::TYPE_COLOR) != 0) {
   4295                 if (accessor != NULL) {
   4296                     accessor->reportError(accessorCookie, "Color value not valid --"
   4297                             " must be #rgb, #argb, #rrggbb, or #aarrggbb");
   4298                 }
   4299                 #if 0
   4300                 fprintf(stderr, "%s: Color ID %s value %s is not valid\n",
   4301                         "Resource File", //(const char*)in->getPrintableSource(),
   4302                         String8(*curTag).string(),
   4303                         String8(s, len).string());
   4304                 #endif
   4305                 return false;
   4306             }
   4307         }
   4308     }
   4309 
   4310     if (*s == '?') {
   4311         outValue->dataType = outValue->TYPE_ATTRIBUTE;
   4312 
   4313         // Note: we don't check attrType here because the reference can
   4314         // be to any other type; we just need to count on the client making
   4315         // sure the referenced type is correct.
   4316 
   4317         //printf("Looking up attr: %s\n", String8(s, len).string());
   4318 
   4319         static const String16 attr16("attr");
   4320         String16 package, type, name;
   4321         if (!expandResourceRef(s+1, len-1, &package, &type, &name,
   4322                                &attr16, defPackage, &errorMsg)) {
   4323             if (accessor != NULL) {
   4324                 accessor->reportError(accessorCookie, errorMsg);
   4325             }
   4326             return false;
   4327         }
   4328 
   4329         //printf("Pkg: %s, Type: %s, Name: %s\n",
   4330         //       String8(package).string(), String8(type).string(),
   4331         //       String8(name).string());
   4332         uint32_t specFlags = 0;
   4333         uint32_t rid =
   4334             identifierForName(name.string(), name.size(),
   4335                               type.string(), type.size(),
   4336                               package.string(), package.size(), &specFlags);
   4337         if (rid != 0) {
   4338             if (enforcePrivate) {
   4339                 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
   4340                     if (accessor != NULL) {
   4341                         accessor->reportError(accessorCookie, "Attribute is not public.");
   4342                     }
   4343                     return false;
   4344                 }
   4345             }
   4346             if (!accessor) {
   4347                 outValue->data = rid;
   4348                 return true;
   4349             }
   4350             rid = Res_MAKEID(
   4351                 accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
   4352                 Res_GETTYPE(rid), Res_GETENTRY(rid));
   4353             //printf("Incl %s:%s/%s: 0x%08x\n",
   4354             //       String8(package).string(), String8(type).string(),
   4355             //       String8(name).string(), rid);
   4356             outValue->data = rid;
   4357             return true;
   4358         }
   4359 
   4360         if (accessor) {
   4361             uint32_t rid = accessor->getCustomResource(package, type, name);
   4362             if (rid != 0) {
   4363                 //printf("Mine %s:%s/%s: 0x%08x\n",
   4364                 //       String8(package).string(), String8(type).string(),
   4365                 //       String8(name).string(), rid);
   4366                 outValue->data = rid;
   4367                 return true;
   4368             }
   4369         }
   4370 
   4371         if (accessor != NULL) {
   4372             accessor->reportError(accessorCookie, "No resource found that matches the given name");
   4373         }
   4374         return false;
   4375     }
   4376 
   4377     if (stringToInt(s, len, outValue)) {
   4378         if ((attrType&ResTable_map::TYPE_INTEGER) == 0) {
   4379             // If this type does not allow integers, but does allow floats,
   4380             // fall through on this error case because the float type should
   4381             // be able to accept any integer value.
   4382             if (!canStringCoerce && (attrType&ResTable_map::TYPE_FLOAT) == 0) {
   4383                 if (accessor != NULL) {
   4384                     accessor->reportError(accessorCookie, "Integer types not allowed");
   4385                 }
   4386                 return false;
   4387             }
   4388         } else {
   4389             if (((int32_t)outValue->data) < ((int32_t)attrMin)
   4390                     || ((int32_t)outValue->data) > ((int32_t)attrMax)) {
   4391                 if (accessor != NULL) {
   4392                     accessor->reportError(accessorCookie, "Integer value out of range");
   4393                 }
   4394                 return false;
   4395             }
   4396             return true;
   4397         }
   4398     }
   4399 
   4400     if (stringToFloat(s, len, outValue)) {
   4401         if (outValue->dataType == Res_value::TYPE_DIMENSION) {
   4402             if ((attrType&ResTable_map::TYPE_DIMENSION) != 0) {
   4403                 return true;
   4404             }
   4405             if (!canStringCoerce) {
   4406                 if (accessor != NULL) {
   4407                     accessor->reportError(accessorCookie, "Dimension types not allowed");
   4408                 }
   4409                 return false;
   4410             }
   4411         } else if (outValue->dataType == Res_value::TYPE_FRACTION) {
   4412             if ((attrType&ResTable_map::TYPE_FRACTION) != 0) {
   4413                 return true;
   4414             }
   4415             if (!canStringCoerce) {
   4416                 if (accessor != NULL) {
   4417                     accessor->reportError(accessorCookie, "Fraction types not allowed");
   4418                 }
   4419                 return false;
   4420             }
   4421         } else if ((attrType&ResTable_map::TYPE_FLOAT) == 0) {
   4422             if (!canStringCoerce) {
   4423                 if (accessor != NULL) {
   4424                     accessor->reportError(accessorCookie, "Float types not allowed");
   4425                 }
   4426                 return false;
   4427             }
   4428         } else {
   4429             return true;
   4430         }
   4431     }
   4432 
   4433     if (len == 4) {
   4434         if ((s[0] == 't' || s[0] == 'T') &&
   4435             (s[1] == 'r' || s[1] == 'R') &&
   4436             (s[2] == 'u' || s[2] == 'U') &&
   4437             (s[3] == 'e' || s[3] == 'E')) {
   4438             if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
   4439                 if (!canStringCoerce) {
   4440                     if (accessor != NULL) {
   4441                         accessor->reportError(accessorCookie, "Boolean types not allowed");
   4442                     }
   4443                     return false;
   4444                 }
   4445             } else {
   4446                 outValue->dataType = outValue->TYPE_INT_BOOLEAN;
   4447                 outValue->data = (uint32_t)-1;
   4448                 return true;
   4449             }
   4450         }
   4451     }
   4452 
   4453     if (len == 5) {
   4454         if ((s[0] == 'f' || s[0] == 'F') &&
   4455             (s[1] == 'a' || s[1] == 'A') &&
   4456             (s[2] == 'l' || s[2] == 'L') &&
   4457             (s[3] == 's' || s[3] == 'S') &&
   4458             (s[4] == 'e' || s[4] == 'E')) {
   4459             if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
   4460                 if (!canStringCoerce) {
   4461                     if (accessor != NULL) {
   4462                         accessor->reportError(accessorCookie, "Boolean types not allowed");
   4463                     }
   4464                     return false;
   4465                 }
   4466             } else {
   4467                 outValue->dataType = outValue->TYPE_INT_BOOLEAN;
   4468                 outValue->data = 0;
   4469                 return true;
   4470             }
   4471         }
   4472     }
   4473 
   4474     if ((attrType&ResTable_map::TYPE_ENUM) != 0) {
   4475         const ssize_t p = getResourcePackageIndex(attrID);
   4476         const bag_entry* bag;
   4477         ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
   4478         //printf("Got %d for enum\n", cnt);
   4479         if (cnt >= 0) {
   4480             resource_name rname;
   4481             while (cnt > 0) {
   4482                 if (!Res_INTERNALID(bag->map.name.ident)) {
   4483                     //printf("Trying attr #%08x\n", bag->map.name.ident);
   4484                     if (getResourceName(bag->map.name.ident, &rname)) {
   4485                         #if 0
   4486                         printf("Matching %s against %s (0x%08x)\n",
   4487                                String8(s, len).string(),
   4488                                String8(rname.name, rname.nameLen).string(),
   4489                                bag->map.name.ident);
   4490                         #endif
   4491                         if (strzcmp16(s, len, rname.name, rname.nameLen) == 0) {
   4492                             outValue->dataType = bag->map.value.dataType;
   4493                             outValue->data = bag->map.value.data;
   4494                             unlockBag(bag);
   4495                             return true;
   4496                         }
   4497                     }
   4498 
   4499                 }
   4500                 bag++;
   4501                 cnt--;
   4502             }
   4503             unlockBag(bag);
   4504         }
   4505 
   4506         if (fromAccessor) {
   4507             if (accessor->getAttributeEnum(attrID, s, len, outValue)) {
   4508                 return true;
   4509             }
   4510         }
   4511     }
   4512 
   4513     if ((attrType&ResTable_map::TYPE_FLAGS) != 0) {
   4514         const ssize_t p = getResourcePackageIndex(attrID);
   4515         const bag_entry* bag;
   4516         ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
   4517         //printf("Got %d for flags\n", cnt);
   4518         if (cnt >= 0) {
   4519             bool failed = false;
   4520             resource_name rname;
   4521             outValue->dataType = Res_value::TYPE_INT_HEX;
   4522             outValue->data = 0;
   4523             const char16_t* end = s + len;
   4524             const char16_t* pos = s;
   4525             while (pos < end && !failed) {
   4526                 const char16_t* start = pos;
   4527                 pos++;
   4528                 while (pos < end && *pos != '|') {
   4529                     pos++;
   4530                 }
   4531                 //printf("Looking for: %s\n", String8(start, pos-start).string());
   4532                 const bag_entry* bagi = bag;
   4533                 ssize_t i;
   4534                 for (i=0; i<cnt; i++, bagi++) {
   4535                     if (!Res_INTERNALID(bagi->map.name.ident)) {
   4536                         //printf("Trying attr #%08x\n", bagi->map.name.ident);
   4537                         if (getResourceName(bagi->map.name.ident, &rname)) {
   4538                             #if 0
   4539                             printf("Matching %s against %s (0x%08x)\n",
   4540                                    String8(start,pos-start).string(),
   4541                                    String8(rname.name, rname.nameLen).string(),
   4542                                    bagi->map.name.ident);
   4543                             #endif
   4544                             if (strzcmp16(start, pos-start, rname.name, rname.nameLen) == 0) {
   4545                                 outValue->data |= bagi->map.value.data;
   4546                                 break;
   4547                             }
   4548                         }
   4549                     }
   4550                 }
   4551                 if (i >= cnt) {
   4552                     // Didn't find this flag identifier.
   4553                     failed = true;
   4554                 }
   4555                 if (pos < end) {
   4556                     pos++;
   4557                 }
   4558             }
   4559             unlockBag(bag);
   4560             if (!failed) {
   4561                 //printf("Final flag value: 0x%lx\n", outValue->data);
   4562                 return true;
   4563             }
   4564         }
   4565 
   4566 
   4567         if (fromAccessor) {
   4568             if (accessor->getAttributeFlags(attrID, s, len, outValue)) {
   4569                 //printf("Final flag value: 0x%lx\n", outValue->data);
   4570                 return true;
   4571             }
   4572         }
   4573     }
   4574 
   4575     if ((attrType&ResTable_map::TYPE_STRING) == 0) {
   4576         if (accessor != NULL) {
   4577             accessor->reportError(accessorCookie, "String types not allowed");
   4578         }
   4579         return false;
   4580     }
   4581 
   4582     // Generic string handling...
   4583     outValue->dataType = outValue->TYPE_STRING;
   4584     if (outString) {
   4585         bool failed = collectString(outString, s, len, preserveSpaces, &errorMsg);
   4586         if (accessor != NULL) {
   4587             accessor->reportError(accessorCookie, errorMsg);
   4588         }
   4589         return failed;
   4590     }
   4591 
   4592     return true;
   4593 }
   4594 
   4595 bool ResTable::collectString(String16* outString,
   4596                              const char16_t* s, size_t len,
   4597                              bool preserveSpaces,
   4598                              const char** outErrorMsg,
   4599                              bool append)
   4600 {
   4601     String16 tmp;
   4602 
   4603     char quoted = 0;
   4604     const char16_t* p = s;
   4605     while (p < (s+len)) {
   4606         while (p < (s+len)) {
   4607             const char16_t c = *p;
   4608             if (c == '\\') {
   4609                 break;
   4610             }
   4611             if (!preserveSpaces) {
   4612                 if (quoted == 0 && isspace16(c)
   4613                     && (c != ' ' || isspace16(*(p+1)))) {
   4614                     break;
   4615                 }
   4616                 if (c == '"' && (quoted == 0 || quoted == '"')) {
   4617                     break;
   4618                 }
   4619                 if (c == '\'' && (quoted == 0 || quoted == '\'')) {
   4620                     /*
   4621                      * In practice, when people write ' instead of \'
   4622                      * in a string, they are doing it by accident
   4623                      * instead of really meaning to use ' as a quoting
   4624                      * character.  Warn them so they don't lose it.
   4625                      */
   4626                     if (outErrorMsg) {
   4627                         *outErrorMsg = "Apostrophe not preceded by \\";
   4628                     }
   4629                     return false;
   4630                 }
   4631             }
   4632             p++;
   4633         }
   4634         if (p < (s+len)) {
   4635             if (p > s) {
   4636                 tmp.append(String16(s, p-s));
   4637             }
   4638             if (!preserveSpaces && (*p == '"' || *p == '\'')) {
   4639                 if (quoted == 0) {
   4640                     quoted = *p;
   4641                 } else {
   4642                     quoted = 0;
   4643                 }
   4644                 p++;
   4645             } else if (!preserveSpaces && isspace16(*p)) {
   4646                 // Space outside of a quote -- consume all spaces and
   4647                 // leave a single plain space char.
   4648                 tmp.append(String16(" "));
   4649                 p++;
   4650                 while (p < (s+len) && isspace16(*p)) {
   4651                     p++;
   4652                 }
   4653             } else if (*p == '\\') {
   4654                 p++;
   4655                 if (p < (s+len)) {
   4656                     switch (*p) {
   4657                     case 't':
   4658                         tmp.append(String16("\t"));
   4659                         break;
   4660                     case 'n':
   4661                         tmp.append(String16("\n"));
   4662                         break;
   4663                     case '#':
   4664                         tmp.append(String16("#"));
   4665                         break;
   4666                     case '@':
   4667                         tmp.append(String16("@"));
   4668                         break;
   4669                     case '?':
   4670                         tmp.append(String16("?"));
   4671                         break;
   4672                     case '"':
   4673                         tmp.append(String16("\""));
   4674                         break;
   4675                     case '\'':
   4676                         tmp.append(String16("'"));
   4677                         break;
   4678                     case '\\':
   4679                         tmp.append(String16("\\"));
   4680                         break;
   4681                     case 'u':
   4682                     {
   4683                         char16_t chr = 0;
   4684                         int i = 0;
   4685                         while (i < 4 && p[1] != 0) {
   4686                             p++;
   4687                             i++;
   4688                             int c;
   4689                             if (*p >= '0' && *p <= '9') {
   4690                                 c = *p - '0';
   4691                             } else if (*p >= 'a' && *p <= 'f') {
   4692                                 c = *p - 'a' + 10;
   4693                             } else if (*p >= 'A' && *p <= 'F') {
   4694                                 c = *p - 'A' + 10;
   4695                             } else {
   4696                                 if (outErrorMsg) {
   4697                                     *outErrorMsg = "Bad character in \\u unicode escape sequence";
   4698                                 }
   4699                                 return false;
   4700                             }
   4701                             chr = (chr<<4) | c;
   4702                         }
   4703                         tmp.append(String16(&chr, 1));
   4704                     } break;
   4705                     default:
   4706                         // ignore unknown escape chars.
   4707                         break;
   4708                     }
   4709                     p++;
   4710                 }
   4711             }
   4712             len -= (p-s);
   4713             s = p;
   4714         }
   4715     }
   4716 
   4717     if (tmp.size() != 0) {
   4718         if (len > 0) {
   4719             tmp.append(String16(s, len));
   4720         }
   4721         if (append) {
   4722             outString->append(tmp);
   4723         } else {
   4724             outString->setTo(tmp);
   4725         }
   4726     } else {
   4727         if (append) {
   4728             outString->append(String16(s, len));
   4729         } else {
   4730             outString->setTo(s, len);
   4731         }
   4732     }
   4733 
   4734     return true;
   4735 }
   4736 
   4737 size_t ResTable::getBasePackageCount() const
   4738 {
   4739     if (mError != NO_ERROR) {
   4740         return 0;
   4741     }
   4742     return mPackageGroups.size();
   4743 }
   4744 
   4745 const char16_t* ResTable::getBasePackageName(size_t idx) const
   4746 {
   4747     if (mError != NO_ERROR) {
   4748         return 0;
   4749     }
   4750     LOG_FATAL_IF(idx >= mPackageGroups.size(),
   4751                  "Requested package index %d past package count %d",
   4752                  (int)idx, (int)mPackageGroups.size());
   4753     return mPackageGroups[idx]->name.string();
   4754 }
   4755 
   4756 uint32_t ResTable::getBasePackageId(size_t idx) const
   4757 {
   4758     if (mError != NO_ERROR) {
   4759         return 0;
   4760     }
   4761     LOG_FATAL_IF(idx >= mPackageGroups.size(),
   4762                  "Requested package index %d past package count %d",
   4763                  (int)idx, (int)mPackageGroups.size());
   4764     return mPackageGroups[idx]->id;
   4765 }
   4766 
   4767 size_t ResTable::getTableCount() const
   4768 {
   4769     return mHeaders.size();
   4770 }
   4771 
   4772 const ResStringPool* ResTable::getTableStringBlock(size_t index) const
   4773 {
   4774     return &mHeaders[index]->values;
   4775 }
   4776 
   4777 void* ResTable::getTableCookie(size_t index) const
   4778 {
   4779     return mHeaders[index]->cookie;
   4780 }
   4781 
   4782 void ResTable::getConfigurations(Vector<ResTable_config>* configs) const
   4783 {
   4784     const size_t I = mPackageGroups.size();
   4785     for (size_t i=0; i<I; i++) {
   4786         const PackageGroup* packageGroup = mPackageGroups[i];
   4787         const size_t J = packageGroup->packages.size();
   4788         for (size_t j=0; j<J; j++) {
   4789             const Package* package = packageGroup->packages[j];
   4790             const size_t K = package->types.size();
   4791             for (size_t k=0; k<K; k++) {
   4792                 const Type* type = package->types[k];
   4793                 if (type == NULL) continue;
   4794                 const size_t L = type->configs.size();
   4795                 for (size_t l=0; l<L; l++) {
   4796                     const ResTable_type* config = type->configs[l];
   4797                     const ResTable_config* cfg = &config->config;
   4798                     // only insert unique
   4799                     const size_t M = configs->size();
   4800                     size_t m;
   4801                     for (m=0; m<M; m++) {
   4802                         if (0 == (*configs)[m].compare(*cfg)) {
   4803                             break;
   4804                         }
   4805                     }
   4806                     // if we didn't find it
   4807                     if (m == M) {
   4808                         configs->add(*cfg);
   4809                     }
   4810                 }
   4811             }
   4812         }
   4813     }
   4814 }
   4815 
   4816 void ResTable::getLocales(Vector<String8>* locales) const
   4817 {
   4818     Vector<ResTable_config> configs;
   4819     ALOGV("calling getConfigurations");
   4820     getConfigurations(&configs);
   4821     ALOGV("called getConfigurations size=%d", (int)configs.size());
   4822     const size_t I = configs.size();
   4823     for (size_t i=0; i<I; i++) {
   4824         char locale[6];
   4825         configs[i].getLocale(locale);
   4826         const size_t J = locales->size();
   4827         size_t j;
   4828         for (j=0; j<J; j++) {
   4829             if (0 == strcmp(locale, (*locales)[j].string())) {
   4830                 break;
   4831             }
   4832         }
   4833         if (j == J) {
   4834             locales->add(String8(locale));
   4835         }
   4836     }
   4837 }
   4838 
   4839 ssize_t ResTable::getEntry(
   4840     const Package* package, int typeIndex, int entryIndex,
   4841     const ResTable_config* config,
   4842     const ResTable_type** outType, const ResTable_entry** outEntry,
   4843     const Type** outTypeClass) const
   4844 {
   4845     ALOGV("Getting entry from package %p\n", package);
   4846     const ResTable_package* const pkg = package->package;
   4847 
   4848     const Type* allTypes = package->getType(typeIndex);
   4849     ALOGV("allTypes=%p\n", allTypes);
   4850     if (allTypes == NULL) {
   4851         ALOGV("Skipping entry type index 0x%02x because type is NULL!\n", typeIndex);
   4852         return 0;
   4853     }
   4854 
   4855     if ((size_t)entryIndex >= allTypes->entryCount) {
   4856         ALOGW("getEntry failing because entryIndex %d is beyond type entryCount %d",
   4857             entryIndex, (int)allTypes->entryCount);
   4858         return BAD_TYPE;
   4859     }
   4860 
   4861     const ResTable_type* type = NULL;
   4862     uint32_t offset = ResTable_type::NO_ENTRY;
   4863     ResTable_config bestConfig;
   4864     memset(&bestConfig, 0, sizeof(bestConfig)); // make the compiler shut up
   4865 
   4866     const size_t NT = allTypes->configs.size();
   4867     for (size_t i=0; i<NT; i++) {
   4868         const ResTable_type* const thisType = allTypes->configs[i];
   4869         if (thisType == NULL) continue;
   4870 
   4871         ResTable_config thisConfig;
   4872         thisConfig.copyFromDtoH(thisType->config);
   4873 
   4874         TABLE_GETENTRY(ALOGI("Match entry 0x%x in type 0x%x (sz 0x%x): %s\n",
   4875                            entryIndex, typeIndex+1, dtohl(thisType->config.size),
   4876                            thisConfig.toString().string()));
   4877 
   4878         // Check to make sure this one is valid for the current parameters.
   4879         if (config && !thisConfig.match(*config)) {
   4880             TABLE_GETENTRY(ALOGI("Does not match config!\n"));
   4881             continue;
   4882         }
   4883 
   4884         // Check if there is the desired entry in this type.
   4885 
   4886         const uint8_t* const end = ((const uint8_t*)thisType)
   4887             + dtohl(thisType->header.size);
   4888         const uint32_t* const eindex = (const uint32_t*)
   4889             (((const uint8_t*)thisType) + dtohs(thisType->header.headerSize));
   4890 
   4891         uint32_t thisOffset = dtohl(eindex[entryIndex]);
   4892         if (thisOffset == ResTable_type::NO_ENTRY) {
   4893             TABLE_GETENTRY(ALOGI("Skipping because it is not defined!\n"));
   4894             continue;
   4895         }
   4896 
   4897         if (type != NULL) {
   4898             // Check if this one is less specific than the last found.  If so,
   4899             // we will skip it.  We check starting with things we most care
   4900             // about to those we least care about.
   4901             if (!thisConfig.isBetterThan(bestConfig, config)) {
   4902                 TABLE_GETENTRY(ALOGI("This config is worse than last!\n"));
   4903                 continue;
   4904             }
   4905         }
   4906 
   4907         type = thisType;
   4908         offset = thisOffset;
   4909         bestConfig = thisConfig;
   4910         TABLE_GETENTRY(ALOGI("Best entry so far -- using it!\n"));
   4911         if (!config) break;
   4912     }
   4913 
   4914     if (type == NULL) {
   4915         TABLE_GETENTRY(ALOGI("No value found for requested entry!\n"));
   4916         return BAD_INDEX;
   4917     }
   4918 
   4919     offset += dtohl(type->entriesStart);
   4920     TABLE_NOISY(aout << "Looking in resource table " << package->header->header
   4921           << ", typeOff="
   4922           << (void*)(((const char*)type)-((const char*)package->header->header))
   4923           << ", offset=" << (void*)offset << endl);
   4924 
   4925     if (offset > (dtohl(type->header.size)-sizeof(ResTable_entry))) {
   4926         ALOGW("ResTable_entry at 0x%x is beyond type chunk data 0x%x",
   4927              offset, dtohl(type->header.size));
   4928         return BAD_TYPE;
   4929     }
   4930     if ((offset&0x3) != 0) {
   4931         ALOGW("ResTable_entry at 0x%x is not on an integer boundary",
   4932              offset);
   4933         return BAD_TYPE;
   4934     }
   4935 
   4936     const ResTable_entry* const entry = (const ResTable_entry*)
   4937         (((const uint8_t*)type) + offset);
   4938     if (dtohs(entry->size) < sizeof(*entry)) {
   4939         ALOGW("ResTable_entry size 0x%x is too small", dtohs(entry->size));
   4940         return BAD_TYPE;
   4941     }
   4942 
   4943     *outType = type;
   4944     *outEntry = entry;
   4945     if (outTypeClass != NULL) {
   4946         *outTypeClass = allTypes;
   4947     }
   4948     return offset + dtohs(entry->size);
   4949 }
   4950 
   4951 status_t ResTable::parsePackage(const ResTable_package* const pkg,
   4952                                 const Header* const header, uint32_t idmap_id)
   4953 {
   4954     const uint8_t* base = (const uint8_t*)pkg;
   4955     status_t err = validate_chunk(&pkg->header, sizeof(*pkg),
   4956                                   header->dataEnd, "ResTable_package");
   4957     if (err != NO_ERROR) {
   4958         return (mError=err);
   4959     }
   4960 
   4961     const size_t pkgSize = dtohl(pkg->header.size);
   4962 
   4963     if (dtohl(pkg->typeStrings) >= pkgSize) {
   4964         ALOGW("ResTable_package type strings at %p are past chunk size %p.",
   4965              (void*)dtohl(pkg->typeStrings), (void*)pkgSize);
   4966         return (mError=BAD_TYPE);
   4967     }
   4968     if ((dtohl(pkg->typeStrings)&0x3) != 0) {
   4969         ALOGW("ResTable_package type strings at %p is not on an integer boundary.",
   4970              (void*)dtohl(pkg->typeStrings));
   4971         return (mError=BAD_TYPE);
   4972     }
   4973     if (dtohl(pkg->keyStrings) >= pkgSize) {
   4974         ALOGW("ResTable_package key strings at %p are past chunk size %p.",
   4975              (void*)dtohl(pkg->keyStrings), (void*)pkgSize);
   4976         return (mError=BAD_TYPE);
   4977     }
   4978     if ((dtohl(pkg->keyStrings)&0x3) != 0) {
   4979         ALOGW("ResTable_package key strings at %p is not on an integer boundary.",
   4980              (void*)dtohl(pkg->keyStrings));
   4981         return (mError=BAD_TYPE);
   4982     }
   4983 
   4984     Package* package = NULL;
   4985     PackageGroup* group = NULL;
   4986     uint32_t id = idmap_id != 0 ? idmap_id : dtohl(pkg->id);
   4987     // If at this point id == 0, pkg is an overlay package without a
   4988     // corresponding idmap. During regular usage, overlay packages are
   4989     // always loaded alongside their idmaps, but during idmap creation
   4990     // the package is temporarily loaded by itself.
   4991     if (id < 256) {
   4992 
   4993         package = new Package(this, header, pkg);
   4994         if (package == NULL) {
   4995             return (mError=NO_MEMORY);
   4996         }
   4997 
   4998         size_t idx = mPackageMap[id];
   4999         if (idx == 0) {
   5000             idx = mPackageGroups.size()+1;
   5001 
   5002             char16_t tmpName[sizeof(pkg->name)/sizeof(char16_t)];
   5003             strcpy16_dtoh(tmpName, pkg->name, sizeof(pkg->name)/sizeof(char16_t));
   5004             group = new PackageGroup(this, String16(tmpName), id);
   5005             if (group == NULL) {
   5006                 delete package;
   5007                 return (mError=NO_MEMORY);
   5008             }
   5009 
   5010             err = package->typeStrings.setTo(base+dtohl(pkg->typeStrings),
   5011                                            header->dataEnd-(base+dtohl(pkg->typeStrings)));
   5012             if (err != NO_ERROR) {
   5013                 delete group;
   5014                 delete package;
   5015                 return (mError=err);
   5016             }
   5017             err = package->keyStrings.setTo(base+dtohl(pkg->keyStrings),
   5018                                           header->dataEnd-(base+dtohl(pkg->keyStrings)));
   5019             if (err != NO_ERROR) {
   5020                 delete group;
   5021                 delete package;
   5022                 return (mError=err);
   5023             }
   5024 
   5025             //printf("Adding new package id %d at index %d\n", id, idx);
   5026             err = mPackageGroups.add(group);
   5027             if (err < NO_ERROR) {
   5028                 return (mError=err);
   5029             }
   5030             group->basePackage = package;
   5031 
   5032             mPackageMap[id] = (uint8_t)idx;
   5033         } else {
   5034             group = mPackageGroups.itemAt(idx-1);
   5035             if (group == NULL) {
   5036                 return (mError=UNKNOWN_ERROR);
   5037             }
   5038         }
   5039         err = group->packages.add(package);
   5040         if (err < NO_ERROR) {
   5041             return (mError=err);
   5042         }
   5043     } else {
   5044         LOG_ALWAYS_FATAL("Package id out of range");
   5045         return NO_ERROR;
   5046     }
   5047 
   5048 
   5049     // Iterate through all chunks.
   5050     size_t curPackage = 0;
   5051 
   5052     const ResChunk_header* chunk =
   5053         (const ResChunk_header*)(((const uint8_t*)pkg)
   5054                                  + dtohs(pkg->header.headerSize));
   5055     const uint8_t* endPos = ((const uint8_t*)pkg) + dtohs(pkg->header.size);
   5056     while (((const uint8_t*)chunk) <= (endPos-sizeof(ResChunk_header)) &&
   5057            ((const uint8_t*)chunk) <= (endPos-dtohl(chunk->size))) {
   5058         TABLE_NOISY(ALOGV("PackageChunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n",
   5059                          dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
   5060                          (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header))));
   5061         const size_t csize = dtohl(chunk->size);
   5062         const uint16_t ctype = dtohs(chunk->type);
   5063         if (ctype == RES_TABLE_TYPE_SPEC_TYPE) {
   5064             const ResTable_typeSpec* typeSpec = (const ResTable_typeSpec*)(chunk);
   5065             err = validate_chunk(&typeSpec->header, sizeof(*typeSpec),
   5066                                  endPos, "ResTable_typeSpec");
   5067             if (err != NO_ERROR) {
   5068                 return (mError=err);
   5069             }
   5070 
   5071             const size_t typeSpecSize = dtohl(typeSpec->header.size);
   5072 
   5073             LOAD_TABLE_NOISY(printf("TypeSpec off %p: type=0x%x, headerSize=0x%x, size=%p\n",
   5074                                     (void*)(base-(const uint8_t*)chunk),
   5075                                     dtohs(typeSpec->header.type),
   5076                                     dtohs(typeSpec->header.headerSize),
   5077                                     (void*)typeSize));
   5078             // look for block overrun or int overflow when multiplying by 4
   5079             if ((dtohl(typeSpec->entryCount) > (INT32_MAX/sizeof(uint32_t))
   5080                     || dtohs(typeSpec->header.headerSize)+(sizeof(uint32_t)*dtohl(typeSpec->entryCount))
   5081                     > typeSpecSize)) {
   5082                 ALOGW("ResTable_typeSpec entry index to %p extends beyond chunk end %p.",
   5083                      (void*)(dtohs(typeSpec->header.headerSize)
   5084                              +(sizeof(uint32_t)*dtohl(typeSpec->entryCount))),
   5085                      (void*)typeSpecSize);
   5086                 return (mError=BAD_TYPE);
   5087             }
   5088 
   5089             if (typeSpec->id == 0) {
   5090                 ALOGW("ResTable_type has an id of 0.");
   5091                 return (mError=BAD_TYPE);
   5092             }
   5093 
   5094             while (package->types.size() < typeSpec->id) {
   5095                 package->types.add(NULL);
   5096             }
   5097             Type* t = package->types[typeSpec->id-1];
   5098             if (t == NULL) {
   5099                 t = new Type(header, package, dtohl(typeSpec->entryCount));
   5100                 package->types.editItemAt(typeSpec->id-1) = t;
   5101             } else if (dtohl(typeSpec->entryCount) != t->entryCount) {
   5102                 ALOGW("ResTable_typeSpec entry count inconsistent: given %d, previously %d",
   5103                     (int)dtohl(typeSpec->entryCount), (int)t->entryCount);
   5104                 return (mError=BAD_TYPE);
   5105             }
   5106             t->typeSpecFlags = (const uint32_t*)(
   5107                     ((const uint8_t*)typeSpec) + dtohs(typeSpec->header.headerSize));
   5108             t->typeSpec = typeSpec;
   5109 
   5110         } else if (ctype == RES_TABLE_TYPE_TYPE) {
   5111             const ResTable_type* type = (const ResTable_type*)(chunk);
   5112             err = validate_chunk(&type->header, sizeof(*type)-sizeof(ResTable_config)+4,
   5113                                  endPos, "ResTable_type");
   5114             if (err != NO_ERROR) {
   5115                 return (mError=err);
   5116             }
   5117 
   5118             const size_t typeSize = dtohl(type->header.size);
   5119 
   5120             LOAD_TABLE_NOISY(printf("Type off %p: type=0x%x, headerSize=0x%x, size=%p\n",
   5121                                     (void*)(base-(const uint8_t*)chunk),
   5122                                     dtohs(type->header.type),
   5123                                     dtohs(type->header.headerSize),
   5124                                     (void*)typeSize));
   5125             if (dtohs(type->header.headerSize)+(sizeof(uint32_t)*dtohl(type->entryCount))
   5126                 > typeSize) {
   5127                 ALOGW("ResTable_type entry index to %p extends beyond chunk end %p.",
   5128                      (void*)(dtohs(type->header.headerSize)
   5129                              +(sizeof(uint32_t)*dtohl(type->entryCount))),
   5130                      (void*)typeSize);
   5131                 return (mError=BAD_TYPE);
   5132             }
   5133             if (dtohl(type->entryCount) != 0
   5134                 && dtohl(type->entriesStart) > (typeSize-sizeof(ResTable_entry))) {
   5135                 ALOGW("ResTable_type entriesStart at %p extends beyond chunk end %p.",
   5136                      (void*)dtohl(type->entriesStart), (void*)typeSize);
   5137                 return (mError=BAD_TYPE);
   5138             }
   5139             if (type->id == 0) {
   5140                 ALOGW("ResTable_type has an id of 0.");
   5141                 return (mError=BAD_TYPE);
   5142             }
   5143 
   5144             while (package->types.size() < type->id) {
   5145                 package->types.add(NULL);
   5146             }
   5147             Type* t = package->types[type->id-1];
   5148             if (t == NULL) {
   5149                 t = new Type(header, package, dtohl(type->entryCount));
   5150                 package->types.editItemAt(type->id-1) = t;
   5151             } else if (dtohl(type->entryCount) != t->entryCount) {
   5152                 ALOGW("ResTable_type entry count inconsistent: given %d, previously %d",
   5153                     (int)dtohl(type->entryCount), (int)t->entryCount);
   5154                 return (mError=BAD_TYPE);
   5155             }
   5156 
   5157             TABLE_GETENTRY(
   5158                 ResTable_config thisConfig;
   5159                 thisConfig.copyFromDtoH(type->config);
   5160                 ALOGI("Adding config to type %d: %s\n",
   5161                       type->id, thisConfig.toString().string()));
   5162             t->configs.add(type);
   5163         } else {
   5164             status_t err = validate_chunk(chunk, sizeof(ResChunk_header),
   5165                                           endPos, "ResTable_package:unknown");
   5166             if (err != NO_ERROR) {
   5167                 return (mError=err);
   5168             }
   5169         }
   5170         chunk = (const ResChunk_header*)
   5171             (((const uint8_t*)chunk) + csize);
   5172     }
   5173 
   5174     if (group->typeCount == 0) {
   5175         group->typeCount = package->types.size();
   5176     }
   5177 
   5178     return NO_ERROR;
   5179 }
   5180 
   5181 status_t ResTable::createIdmap(const ResTable& overlay, uint32_t originalCrc, uint32_t overlayCrc,
   5182                                void** outData, size_t* outSize) const
   5183 {
   5184     // see README for details on the format of map
   5185     if (mPackageGroups.size() == 0) {
   5186         return UNKNOWN_ERROR;
   5187     }
   5188     if (mPackageGroups[0]->packages.size() == 0) {
   5189         return UNKNOWN_ERROR;
   5190     }
   5191 
   5192     Vector<Vector<uint32_t> > map;
   5193     const PackageGroup* pg = mPackageGroups[0];
   5194     const Package* pkg = pg->packages[0];
   5195     size_t typeCount = pkg->types.size();
   5196     // starting size is header + first item (number of types in map)
   5197     *outSize = (IDMAP_HEADER_SIZE + 1) * sizeof(uint32_t);
   5198     const String16 overlayPackage(overlay.mPackageGroups[0]->packages[0]->package->name);
   5199     const uint32_t pkg_id = pkg->package->id << 24;
   5200 
   5201     for (size_t typeIndex = 0; typeIndex < typeCount; ++typeIndex) {
   5202         ssize_t first = -1;
   5203         ssize_t last = -1;
   5204         const Type* typeConfigs = pkg->getType(typeIndex);
   5205         ssize_t mapIndex = map.add();
   5206         if (mapIndex < 0) {
   5207             return NO_MEMORY;
   5208         }
   5209         Vector<uint32_t>& vector = map.editItemAt(mapIndex);
   5210         for (size_t entryIndex = 0; entryIndex < typeConfigs->entryCount; ++entryIndex) {
   5211             uint32_t resID = pkg_id
   5212                 | (0x00ff0000 & ((typeIndex+1)<<16))
   5213                 | (0x0000ffff & (entryIndex));
   5214             resource_name resName;
   5215             if (!this->getResourceName(resID, &resName)) {
   5216                 ALOGW("idmap: resource 0x%08x has spec but lacks values, skipping\n", resID);
   5217                 // add dummy value, or trimming leading/trailing zeroes later will fail
   5218                 vector.push(0);
   5219                 continue;
   5220             }
   5221 
   5222             const String16 overlayType(resName.type, resName.typeLen);
   5223             const String16 overlayName(resName.name, resName.nameLen);
   5224             uint32_t overlayResID = overlay.identifierForName(overlayName.string(),
   5225                                                               overlayName.size(),
   5226                                                               overlayType.string(),
   5227                                                               overlayType.size(),
   5228                                                               overlayPackage.string(),
   5229                                                               overlayPackage.size());
   5230             if (overlayResID != 0) {
   5231                 overlayResID = pkg_id | (0x00ffffff & overlayResID);
   5232                 last = Res_GETENTRY(resID);
   5233                 if (first == -1) {
   5234                     first = Res_GETENTRY(resID);
   5235                 }
   5236             }
   5237             vector.push(overlayResID);
   5238 #if 0
   5239             if (overlayResID != 0) {
   5240                 ALOGD("%s/%s 0x%08x -> 0x%08x\n",
   5241                      String8(String16(resName.type)).string(),
   5242                      String8(String16(resName.name)).string(),
   5243                      resID, overlayResID);
   5244             }
   5245 #endif
   5246         }
   5247 
   5248         if (first != -1) {
   5249             // shave off trailing entries which lack overlay values
   5250             const size_t last_past_one = last + 1;
   5251             if (last_past_one < vector.size()) {
   5252                 vector.removeItemsAt(last_past_one, vector.size() - last_past_one);
   5253             }
   5254             // shave off leading entries which lack overlay values
   5255             vector.removeItemsAt(0, first);
   5256             // store offset to first overlaid resource ID of this type
   5257             vector.insertAt((uint32_t)first, 0, 1);
   5258             // reserve space for number and offset of entries, and the actual entries
   5259             *outSize += (2 + vector.size()) * sizeof(uint32_t);
   5260         } else {
   5261             // no entries of current type defined in overlay package
   5262             vector.clear();
   5263             // reserve space for type offset
   5264             *outSize += 1 * sizeof(uint32_t);
   5265         }
   5266     }
   5267 
   5268     if ((*outData = malloc(*outSize)) == NULL) {
   5269         return NO_MEMORY;
   5270     }
   5271     uint32_t* data = (uint32_t*)*outData;
   5272     *data++ = htodl(IDMAP_MAGIC);
   5273     *data++ = htodl(originalCrc);
   5274     *data++ = htodl(overlayCrc);
   5275     const size_t mapSize = map.size();
   5276     *data++ = htodl(mapSize);
   5277     size_t offset = mapSize;
   5278     for (size_t i = 0; i < mapSize; ++i) {
   5279         const Vector<uint32_t>& vector = map.itemAt(i);
   5280         const size_t N = vector.size();
   5281         if (N == 0) {
   5282             *data++ = htodl(0);
   5283         } else {
   5284             offset++;
   5285             *data++ = htodl(offset);
   5286             offset += N;
   5287         }
   5288     }
   5289     for (size_t i = 0; i < mapSize; ++i) {
   5290         const Vector<uint32_t>& vector = map.itemAt(i);
   5291         const size_t N = vector.size();
   5292         if (N == 0) {
   5293             continue;
   5294         }
   5295         if (N == 1) { // vector expected to hold (offset) + (N > 0 entries)
   5296             ALOGW("idmap: type %d supposedly has entries, but no entries found\n", i);
   5297             return UNKNOWN_ERROR;
   5298         }
   5299         *data++ = htodl(N - 1); // do not count the offset (which is vector's first element)
   5300         for (size_t j = 0; j < N; ++j) {
   5301             const uint32_t& overlayResID = vector.itemAt(j);
   5302             *data++ = htodl(overlayResID);
   5303         }
   5304     }
   5305 
   5306     return NO_ERROR;
   5307 }
   5308 
   5309 bool ResTable::getIdmapInfo(const void* idmap, size_t sizeBytes,
   5310                             uint32_t* pOriginalCrc, uint32_t* pOverlayCrc)
   5311 {
   5312     const uint32_t* map = (const uint32_t*)idmap;
   5313     if (!assertIdmapHeader(map, sizeBytes)) {
   5314         return false;
   5315     }
   5316     *pOriginalCrc = map[1];
   5317     *pOverlayCrc = map[2];
   5318     return true;
   5319 }
   5320 
   5321 
   5322 #ifndef HAVE_ANDROID_OS
   5323 #define CHAR16_TO_CSTR(c16, len) (String8(String16(c16,len)).string())
   5324 
   5325 #define CHAR16_ARRAY_EQ(constant, var, len) \
   5326         ((len == (sizeof(constant)/sizeof(constant[0]))) && (0 == memcmp((var), (constant), (len))))
   5327 
   5328 void print_complex(uint32_t complex, bool isFraction)
   5329 {
   5330     const float MANTISSA_MULT =
   5331         1.0f / (1<<Res_value::COMPLEX_MANTISSA_SHIFT);
   5332     const float RADIX_MULTS[] = {
   5333         1.0f*MANTISSA_MULT, 1.0f/(1<<7)*MANTISSA_MULT,
   5334         1.0f/(1<<15)*MANTISSA_MULT, 1.0f/(1<<23)*MANTISSA_MULT
   5335     };
   5336 
   5337     float value = (complex&(Res_value::COMPLEX_MANTISSA_MASK
   5338                    <<Res_value::COMPLEX_MANTISSA_SHIFT))
   5339             * RADIX_MULTS[(complex>>Res_value::COMPLEX_RADIX_SHIFT)
   5340                             & Res_value::COMPLEX_RADIX_MASK];
   5341     printf("%f", value);
   5342 
   5343     if (!isFraction) {
   5344         switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
   5345             case Res_value::COMPLEX_UNIT_PX: printf("px"); break;
   5346             case Res_value::COMPLEX_UNIT_DIP: printf("dp"); break;
   5347             case Res_value::COMPLEX_UNIT_SP: printf("sp"); break;
   5348             case Res_value::COMPLEX_UNIT_PT: printf("pt"); break;
   5349             case Res_value::COMPLEX_UNIT_IN: printf("in"); break;
   5350             case Res_value::COMPLEX_UNIT_MM: printf("mm"); break;
   5351             default: printf(" (unknown unit)"); break;
   5352         }
   5353     } else {
   5354         switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
   5355             case Res_value::COMPLEX_UNIT_FRACTION: printf("%%"); break;
   5356             case Res_value::COMPLEX_UNIT_FRACTION_PARENT: printf("%%p"); break;
   5357             default: printf(" (unknown unit)"); break;
   5358         }
   5359     }
   5360 }
   5361 
   5362 // Normalize a string for output
   5363 String8 ResTable::normalizeForOutput( const char *input )
   5364 {
   5365     String8 ret;
   5366     char buff[2];
   5367     buff[1] = '\0';
   5368 
   5369     while (*input != '\0') {
   5370         switch (*input) {
   5371             // All interesting characters are in the ASCII zone, so we are making our own lives
   5372             // easier by scanning the string one byte at a time.
   5373         case '\\':
   5374             ret += "\\\\";
   5375             break;
   5376         case '\n':
   5377             ret += "\\n";
   5378             break;
   5379         case '"':
   5380             ret += "\\\"";
   5381             break;
   5382         default:
   5383             buff[0] = *input;
   5384             ret += buff;
   5385             break;
   5386         }
   5387 
   5388         input++;
   5389     }
   5390 
   5391     return ret;
   5392 }
   5393 
   5394 void ResTable::print_value(const Package* pkg, const Res_value& value) const
   5395 {
   5396     if (value.dataType == Res_value::TYPE_NULL) {
   5397         printf("(null)\n");
   5398     } else if (value.dataType == Res_value::TYPE_REFERENCE) {
   5399         printf("(reference) 0x%08x\n", value.data);
   5400     } else if (value.dataType == Res_value::TYPE_ATTRIBUTE) {
   5401         printf("(attribute) 0x%08x\n", value.data);
   5402     } else if (value.dataType == Res_value::TYPE_STRING) {
   5403         size_t len;
   5404         const char* str8 = pkg->header->values.string8At(
   5405                 value.data, &len);
   5406         if (str8 != NULL) {
   5407             printf("(string8) \"%s\"\n", normalizeForOutput(str8).string());
   5408         } else {
   5409             const char16_t* str16 = pkg->header->values.stringAt(
   5410                     value.data, &len);
   5411             if (str16 != NULL) {
   5412                 printf("(string16) \"%s\"\n",
   5413                     normalizeForOutput(String8(str16, len).string()).string());
   5414             } else {
   5415                 printf("(string) null\n");
   5416             }
   5417         }
   5418     } else if (value.dataType == Res_value::TYPE_FLOAT) {
   5419         printf("(float) %g\n", *(const float*)&value.data);
   5420     } else if (value.dataType == Res_value::TYPE_DIMENSION) {
   5421         printf("(dimension) ");
   5422         print_complex(value.data, false);
   5423         printf("\n");
   5424     } else if (value.dataType == Res_value::TYPE_FRACTION) {
   5425         printf("(fraction) ");
   5426         print_complex(value.data, true);
   5427         printf("\n");
   5428     } else if (value.dataType >= Res_value::TYPE_FIRST_COLOR_INT
   5429             || value.dataType <= Res_value::TYPE_LAST_COLOR_INT) {
   5430         printf("(color) #%08x\n", value.data);
   5431     } else if (value.dataType == Res_value::TYPE_INT_BOOLEAN) {
   5432         printf("(boolean) %s\n", value.data ? "true" : "false");
   5433     } else if (value.dataType >= Res_value::TYPE_FIRST_INT
   5434             || value.dataType <= Res_value::TYPE_LAST_INT) {
   5435         printf("(int) 0x%08x or %d\n", value.data, value.data);
   5436     } else {
   5437         printf("(unknown type) t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)\n",
   5438                (int)value.dataType, (int)value.data,
   5439                (int)value.size, (int)value.res0);
   5440     }
   5441 }
   5442 
   5443 void ResTable::print(bool inclValues) const
   5444 {
   5445     if (mError != 0) {
   5446         printf("mError=0x%x (%s)\n", mError, strerror(mError));
   5447     }
   5448 #if 0
   5449     printf("mParams=%c%c-%c%c,\n",
   5450             mParams.language[0], mParams.language[1],
   5451             mParams.country[0], mParams.country[1]);
   5452 #endif
   5453     size_t pgCount = mPackageGroups.size();
   5454     printf("Package Groups (%d)\n", (int)pgCount);
   5455     for (size_t pgIndex=0; pgIndex<pgCount; pgIndex++) {
   5456         const PackageGroup* pg = mPackageGroups[pgIndex];
   5457         printf("Package Group %d id=%d packageCount=%d name=%s\n",
   5458                 (int)pgIndex, pg->id, (int)pg->packages.size(),
   5459                 String8(pg->name).string());
   5460 
   5461         size_t pkgCount = pg->packages.size();
   5462         for (size_t pkgIndex=0; pkgIndex<pkgCount; pkgIndex++) {
   5463             const Package* pkg = pg->packages[pkgIndex];
   5464             size_t typeCount = pkg->types.size();
   5465             printf("  Package %d id=%d name=%s typeCount=%d\n", (int)pkgIndex,
   5466                     pkg->package->id, String8(String16(pkg->package->name)).string(),
   5467                     (int)typeCount);
   5468             for (size_t typeIndex=0; typeIndex<typeCount; typeIndex++) {
   5469                 const Type* typeConfigs = pkg->getType(typeIndex);
   5470                 if (typeConfigs == NULL) {
   5471                     printf("    type %d NULL\n", (int)typeIndex);
   5472                     continue;
   5473                 }
   5474                 const size_t NTC = typeConfigs->configs.size();
   5475                 printf("    type %d configCount=%d entryCount=%d\n",
   5476                        (int)typeIndex, (int)NTC, (int)typeConfigs->entryCount);
   5477                 if (typeConfigs->typeSpecFlags != NULL) {
   5478                     for (size_t entryIndex=0; entryIndex<typeConfigs->entryCount; entryIndex++) {
   5479                         uint32_t resID = (0xff000000 & ((pkg->package->id)<<24))
   5480                                     | (0x00ff0000 & ((typeIndex+1)<<16))
   5481                                     | (0x0000ffff & (entryIndex));
   5482                         resource_name resName;
   5483                         if (this->getResourceName(resID, &resName)) {
   5484                             printf("      spec resource 0x%08x %s:%s/%s: flags=0x%08x\n",
   5485                                 resID,
   5486                                 CHAR16_TO_CSTR(resName.package, resName.packageLen),
   5487                                 CHAR16_TO_CSTR(resName.type, resName.typeLen),
   5488                                 CHAR16_TO_CSTR(resName.name, resName.nameLen),
   5489                                 dtohl(typeConfigs->typeSpecFlags[entryIndex]));
   5490                         } else {
   5491                             printf("      INVALID TYPE CONFIG FOR RESOURCE 0x%08x\n", resID);
   5492                         }
   5493                     }
   5494                 }
   5495                 for (size_t configIndex=0; configIndex<NTC; configIndex++) {
   5496                     const ResTable_type* type = typeConfigs->configs[configIndex];
   5497                     if ((((uint64_t)type)&0x3) != 0) {
   5498                         printf("      NON-INTEGER ResTable_type ADDRESS: %p\n", type);
   5499                         continue;
   5500                     }
   5501                     String8 configStr = type->config.toString();
   5502                     printf("      config %s:\n", configStr.size() > 0
   5503                             ? configStr.string() : "(default)");
   5504                     size_t entryCount = dtohl(type->entryCount);
   5505                     uint32_t entriesStart = dtohl(type->entriesStart);
   5506                     if ((entriesStart&0x3) != 0) {
   5507                         printf("      NON-INTEGER ResTable_type entriesStart OFFSET: %p\n", (void*)entriesStart);
   5508                         continue;
   5509                     }
   5510                     uint32_t typeSize = dtohl(type->header.size);
   5511                     if ((typeSize&0x3) != 0) {
   5512                         printf("      NON-INTEGER ResTable_type header.size: %p\n", (void*)typeSize);
   5513                         continue;
   5514                     }
   5515                     for (size_t entryIndex=0; entryIndex<entryCount; entryIndex++) {
   5516 
   5517                         const uint8_t* const end = ((const uint8_t*)type)
   5518                             + dtohl(type->header.size);
   5519                         const uint32_t* const eindex = (const uint32_t*)
   5520                             (((const uint8_t*)type) + dtohs(type->header.headerSize));
   5521 
   5522                         uint32_t thisOffset = dtohl(eindex[entryIndex]);
   5523                         if (thisOffset == ResTable_type::NO_ENTRY) {
   5524                             continue;
   5525                         }
   5526 
   5527                         uint32_t resID = (0xff000000 & ((pkg->package->id)<<24))
   5528                                     | (0x00ff0000 & ((typeIndex+1)<<16))
   5529                                     | (0x0000ffff & (entryIndex));
   5530                         resource_name resName;
   5531                         if (this->getResourceName(resID, &resName)) {
   5532                             printf("        resource 0x%08x %s:%s/%s: ", resID,
   5533                                     CHAR16_TO_CSTR(resName.package, resName.packageLen),
   5534                                     CHAR16_TO_CSTR(resName.type, resName.typeLen),
   5535                                     CHAR16_TO_CSTR(resName.name, resName.nameLen));
   5536                         } else {
   5537                             printf("        INVALID RESOURCE 0x%08x: ", resID);
   5538                         }
   5539                         if ((thisOffset&0x3) != 0) {
   5540                             printf("NON-INTEGER OFFSET: %p\n", (void*)thisOffset);
   5541                             continue;
   5542                         }
   5543                         if ((thisOffset+sizeof(ResTable_entry)) > typeSize) {
   5544                             printf("OFFSET OUT OF BOUNDS: %p+%p (size is %p)\n",
   5545                                    (void*)entriesStart, (void*)thisOffset,
   5546                                    (void*)typeSize);
   5547                             continue;
   5548                         }
   5549 
   5550                         const ResTable_entry* ent = (const ResTable_entry*)
   5551                             (((const uint8_t*)type) + entriesStart + thisOffset);
   5552                         if (((entriesStart + thisOffset)&0x3) != 0) {
   5553                             printf("NON-INTEGER ResTable_entry OFFSET: %p\n",
   5554                                  (void*)(entriesStart + thisOffset));
   5555                             continue;
   5556                         }
   5557 
   5558                         uint16_t esize = dtohs(ent->size);
   5559                         if ((esize&0x3) != 0) {
   5560                             printf("NON-INTEGER ResTable_entry SIZE: %p\n", (void*)esize);
   5561                             continue;
   5562                         }
   5563                         if ((thisOffset+esize) > typeSize) {
   5564                             printf("ResTable_entry OUT OF BOUNDS: %p+%p+%p (size is %p)\n",
   5565                                    (void*)entriesStart, (void*)thisOffset,
   5566                                    (void*)esize, (void*)typeSize);
   5567                             continue;
   5568                         }
   5569 
   5570                         const Res_value* valuePtr = NULL;
   5571                         const ResTable_map_entry* bagPtr = NULL;
   5572                         Res_value value;
   5573                         if ((dtohs(ent->flags)&ResTable_entry::FLAG_COMPLEX) != 0) {
   5574                             printf("<bag>");
   5575                             bagPtr = (const ResTable_map_entry*)ent;
   5576                         } else {
   5577                             valuePtr = (const Res_value*)
   5578                                 (((const uint8_t*)ent) + esize);
   5579                             value.copyFrom_dtoh(*valuePtr);
   5580                             printf("t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)",
   5581                                    (int)value.dataType, (int)value.data,
   5582                                    (int)value.size, (int)value.res0);
   5583                         }
   5584 
   5585                         if ((dtohs(ent->flags)&ResTable_entry::FLAG_PUBLIC) != 0) {
   5586                             printf(" (PUBLIC)");
   5587                         }
   5588                         printf("\n");
   5589 
   5590                         if (inclValues) {
   5591                             if (valuePtr != NULL) {
   5592                                 printf("          ");
   5593                                 print_value(pkg, value);
   5594                             } else if (bagPtr != NULL) {
   5595                                 const int N = dtohl(bagPtr->count);
   5596                                 const uint8_t* baseMapPtr = (const uint8_t*)ent;
   5597                                 size_t mapOffset = esize;
   5598                                 const ResTable_map* mapPtr = (ResTable_map*)(baseMapPtr+mapOffset);
   5599                                 printf("          Parent=0x%08x, Count=%d\n",
   5600                                     dtohl(bagPtr->parent.ident), N);
   5601                                 for (int i=0; i<N && mapOffset < (typeSize-sizeof(ResTable_map)); i++) {
   5602                                     printf("          #%i (Key=0x%08x): ",
   5603                                         i, dtohl(mapPtr->name.ident));
   5604                                     value.copyFrom_dtoh(mapPtr->value);
   5605                                     print_value(pkg, value);
   5606                                     const size_t size = dtohs(mapPtr->value.size);
   5607                                     mapOffset += size + sizeof(*mapPtr)-sizeof(mapPtr->value);
   5608                                     mapPtr = (ResTable_map*)(baseMapPtr+mapOffset);
   5609                                 }
   5610                             }
   5611                         }
   5612                     }
   5613                 }
   5614             }
   5615         }
   5616     }
   5617 }
   5618 
   5619 #endif // HAVE_ANDROID_OS
   5620 
   5621 }   // namespace android
   5622