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