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