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