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