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