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