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