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