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