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