ResourceTypes.cpp revision 20cb56e26e91df91bd64d4251222e0d421cdbe47
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 <utils/Atomic.h>
21#include <utils/ByteOrder.h>
22#include <utils/Debug.h>
23#include <utils/ResourceTypes.h>
24#include <utils/String16.h>
25#include <utils/String8.h>
26#include <utils/TextOutput.h>
27#include <utils/Log.h>
28
29#include <stdlib.h>
30#include <string.h>
31#include <memory.h>
32#include <ctype.h>
33#include <stdint.h>
34
35#ifndef INT32_MAX
36#define INT32_MAX ((int32_t)(2147483647))
37#endif
38
39#define POOL_NOISY(x) //x
40#define XML_NOISY(x) //x
41#define TABLE_NOISY(x) //x
42#define TABLE_GETENTRY(x) //x
43#define TABLE_SUPER_NOISY(x) //x
44#define LOAD_TABLE_NOISY(x) //x
45#define TABLE_THEME(x) //x
46
47namespace android {
48
49#ifdef HAVE_WINSOCK
50#undef  nhtol
51#undef  htonl
52
53#ifdef HAVE_LITTLE_ENDIAN
54#define ntohl(x)    ( ((x) << 24) | (((x) >> 24) & 255) | (((x) << 8) & 0xff0000) | (((x) >> 8) & 0xff00) )
55#define htonl(x)    ntohl(x)
56#define ntohs(x)    ( (((x) << 8) & 0xff00) | (((x) >> 8) & 255) )
57#define htons(x)    ntohs(x)
58#else
59#define ntohl(x)    (x)
60#define htonl(x)    (x)
61#define ntohs(x)    (x)
62#define htons(x)    (x)
63#endif
64#endif
65
66static void printToLogFunc(void* cookie, const char* txt)
67{
68    LOGV("%s", txt);
69}
70
71// Standard C isspace() is only required to look at the low byte of its input, so
72// produces incorrect results for UTF-16 characters.  For safety's sake, assume that
73// any high-byte UTF-16 code point is not whitespace.
74inline int isspace16(char16_t c) {
75    return (c < 0x0080 && isspace(c));
76}
77
78// range checked; guaranteed to NUL-terminate within the stated number of available slots
79// NOTE: if this truncates the dst string due to running out of space, no attempt is
80// made to avoid splitting surrogate pairs.
81static void strcpy16_dtoh(uint16_t* dst, const uint16_t* src, size_t avail)
82{
83    uint16_t* last = dst + avail - 1;
84    while (*src && (dst < last)) {
85        char16_t s = dtohs(*src);
86        *dst++ = s;
87        src++;
88    }
89    *dst = 0;
90}
91
92static status_t validate_chunk(const ResChunk_header* chunk,
93                               size_t minSize,
94                               const uint8_t* dataEnd,
95                               const char* name)
96{
97    const uint16_t headerSize = dtohs(chunk->headerSize);
98    const uint32_t size = dtohl(chunk->size);
99
100    if (headerSize >= minSize) {
101        if (headerSize <= size) {
102            if (((headerSize|size)&0x3) == 0) {
103                if ((ssize_t)size <= (dataEnd-((const uint8_t*)chunk))) {
104                    return NO_ERROR;
105                }
106                LOGW("%s data size %p extends beyond resource end %p.",
107                     name, (void*)size,
108                     (void*)(dataEnd-((const uint8_t*)chunk)));
109                return BAD_TYPE;
110            }
111            LOGW("%s size 0x%x or headerSize 0x%x is not on an integer boundary.",
112                 name, (int)size, (int)headerSize);
113            return BAD_TYPE;
114        }
115        LOGW("%s size %p is smaller than header size %p.",
116             name, (void*)size, (void*)(int)headerSize);
117        return BAD_TYPE;
118    }
119    LOGW("%s header size %p is too small.",
120         name, (void*)(int)headerSize);
121    return BAD_TYPE;
122}
123
124inline void Res_value::copyFrom_dtoh(const Res_value& src)
125{
126    size = dtohs(src.size);
127    res0 = src.res0;
128    dataType = src.dataType;
129    data = dtohl(src.data);
130}
131
132void Res_png_9patch::deviceToFile()
133{
134    for (int i = 0; i < numXDivs; i++) {
135        xDivs[i] = htonl(xDivs[i]);
136    }
137    for (int i = 0; i < numYDivs; i++) {
138        yDivs[i] = htonl(yDivs[i]);
139    }
140    paddingLeft = htonl(paddingLeft);
141    paddingRight = htonl(paddingRight);
142    paddingTop = htonl(paddingTop);
143    paddingBottom = htonl(paddingBottom);
144    for (int i=0; i<numColors; i++) {
145        colors[i] = htonl(colors[i]);
146    }
147}
148
149void Res_png_9patch::fileToDevice()
150{
151    for (int i = 0; i < numXDivs; i++) {
152        xDivs[i] = ntohl(xDivs[i]);
153    }
154    for (int i = 0; i < numYDivs; i++) {
155        yDivs[i] = ntohl(yDivs[i]);
156    }
157    paddingLeft = ntohl(paddingLeft);
158    paddingRight = ntohl(paddingRight);
159    paddingTop = ntohl(paddingTop);
160    paddingBottom = ntohl(paddingBottom);
161    for (int i=0; i<numColors; i++) {
162        colors[i] = ntohl(colors[i]);
163    }
164}
165
166size_t Res_png_9patch::serializedSize()
167{
168    // The size of this struct is 32 bytes on the 32-bit target system
169    // 4 * int8_t
170    // 4 * int32_t
171    // 3 * pointer
172    return 32
173            + numXDivs * sizeof(int32_t)
174            + numYDivs * sizeof(int32_t)
175            + numColors * sizeof(uint32_t);
176}
177
178void* Res_png_9patch::serialize()
179{
180    // Use calloc since we're going to leave a few holes in the data
181    // and want this to run cleanly under valgrind
182    void* newData = calloc(1, serializedSize());
183    serialize(newData);
184    return newData;
185}
186
187void Res_png_9patch::serialize(void * outData)
188{
189    char* data = (char*) outData;
190    memmove(data, &wasDeserialized, 4);     // copy  wasDeserialized, numXDivs, numYDivs, numColors
191    memmove(data + 12, &paddingLeft, 16);   // copy paddingXXXX
192    data += 32;
193
194    memmove(data, this->xDivs, numXDivs * sizeof(int32_t));
195    data +=  numXDivs * sizeof(int32_t);
196    memmove(data, this->yDivs, numYDivs * sizeof(int32_t));
197    data +=  numYDivs * sizeof(int32_t);
198    memmove(data, this->colors, numColors * sizeof(uint32_t));
199}
200
201static void deserializeInternal(const void* inData, Res_png_9patch* outData) {
202    char* patch = (char*) inData;
203    if (inData != outData) {
204        memmove(&outData->wasDeserialized, patch, 4);     // copy  wasDeserialized, numXDivs, numYDivs, numColors
205        memmove(&outData->paddingLeft, patch + 12, 4);     // copy  wasDeserialized, numXDivs, numYDivs, numColors
206    }
207    outData->wasDeserialized = true;
208    char* data = (char*)outData;
209    data +=  sizeof(Res_png_9patch);
210    outData->xDivs = (int32_t*) data;
211    data +=  outData->numXDivs * sizeof(int32_t);
212    outData->yDivs = (int32_t*) data;
213    data +=  outData->numYDivs * sizeof(int32_t);
214    outData->colors = (uint32_t*) data;
215}
216
217Res_png_9patch* Res_png_9patch::deserialize(const void* inData)
218{
219    if (sizeof(void*) != sizeof(int32_t)) {
220        LOGE("Cannot deserialize on non 32-bit system\n");
221        return NULL;
222    }
223    deserializeInternal(inData, (Res_png_9patch*) inData);
224    return (Res_png_9patch*) inData;
225}
226
227// --------------------------------------------------------------------
228// --------------------------------------------------------------------
229// --------------------------------------------------------------------
230
231ResStringPool::ResStringPool()
232    : mError(NO_INIT), mOwnedData(NULL), mHeader(NULL), mCache(NULL)
233{
234}
235
236ResStringPool::ResStringPool(const void* data, size_t size, bool copyData)
237    : mError(NO_INIT), mOwnedData(NULL), mHeader(NULL), mCache(NULL)
238{
239    setTo(data, size, copyData);
240}
241
242ResStringPool::~ResStringPool()
243{
244    uninit();
245}
246
247status_t ResStringPool::setTo(const void* data, size_t size, bool copyData)
248{
249    if (!data || !size) {
250        return (mError=BAD_TYPE);
251    }
252
253    uninit();
254
255    const bool notDeviceEndian = htods(0xf0) != 0xf0;
256
257    if (copyData || notDeviceEndian) {
258        mOwnedData = malloc(size);
259        if (mOwnedData == NULL) {
260            return (mError=NO_MEMORY);
261        }
262        memcpy(mOwnedData, data, size);
263        data = mOwnedData;
264    }
265
266    mHeader = (const ResStringPool_header*)data;
267
268    if (notDeviceEndian) {
269        ResStringPool_header* h = const_cast<ResStringPool_header*>(mHeader);
270        h->header.headerSize = dtohs(mHeader->header.headerSize);
271        h->header.type = dtohs(mHeader->header.type);
272        h->header.size = dtohl(mHeader->header.size);
273        h->stringCount = dtohl(mHeader->stringCount);
274        h->styleCount = dtohl(mHeader->styleCount);
275        h->flags = dtohl(mHeader->flags);
276        h->stringsStart = dtohl(mHeader->stringsStart);
277        h->stylesStart = dtohl(mHeader->stylesStart);
278    }
279
280    if (mHeader->header.headerSize > mHeader->header.size
281            || mHeader->header.size > size) {
282        LOGW("Bad string block: header size %d or total size %d is larger than data size %d\n",
283                (int)mHeader->header.headerSize, (int)mHeader->header.size, (int)size);
284        return (mError=BAD_TYPE);
285    }
286    mSize = mHeader->header.size;
287    mEntries = (const uint32_t*)
288        (((const uint8_t*)data)+mHeader->header.headerSize);
289
290    if (mHeader->stringCount > 0) {
291        if ((mHeader->stringCount*sizeof(uint32_t) < mHeader->stringCount)  // uint32 overflow?
292            || (mHeader->header.headerSize+(mHeader->stringCount*sizeof(uint32_t)))
293                > size) {
294            LOGW("Bad string block: entry of %d items extends past data size %d\n",
295                    (int)(mHeader->header.headerSize+(mHeader->stringCount*sizeof(uint32_t))),
296                    (int)size);
297            return (mError=BAD_TYPE);
298        }
299
300        size_t charSize;
301        if (mHeader->flags&ResStringPool_header::UTF8_FLAG) {
302            charSize = sizeof(uint8_t);
303            mCache = (char16_t**)malloc(sizeof(char16_t**)*mHeader->stringCount);
304            memset(mCache, 0, sizeof(char16_t**)*mHeader->stringCount);
305        } else {
306            charSize = sizeof(char16_t);
307        }
308
309        mStrings = (const void*)
310            (((const uint8_t*)data)+mHeader->stringsStart);
311        if (mHeader->stringsStart >= (mHeader->header.size-sizeof(uint16_t))) {
312            LOGW("Bad string block: string pool starts at %d, after total size %d\n",
313                    (int)mHeader->stringsStart, (int)mHeader->header.size);
314            return (mError=BAD_TYPE);
315        }
316        if (mHeader->styleCount == 0) {
317            mStringPoolSize =
318                (mHeader->header.size-mHeader->stringsStart)/charSize;
319        } else {
320            // check invariant: styles follow the strings
321            if (mHeader->stylesStart <= mHeader->stringsStart) {
322                LOGW("Bad style block: style block starts at %d, before strings at %d\n",
323                    (int)mHeader->stylesStart, (int)mHeader->stringsStart);
324                return (mError=BAD_TYPE);
325            }
326            mStringPoolSize =
327                (mHeader->stylesStart-mHeader->stringsStart)/charSize;
328        }
329
330        // check invariant: stringCount > 0 requires a string pool to exist
331        if (mStringPoolSize == 0) {
332            LOGW("Bad string block: stringCount is %d but pool size is 0\n", (int)mHeader->stringCount);
333            return (mError=BAD_TYPE);
334        }
335
336        if (notDeviceEndian) {
337            size_t i;
338            uint32_t* e = const_cast<uint32_t*>(mEntries);
339            for (i=0; i<mHeader->stringCount; i++) {
340                e[i] = dtohl(mEntries[i]);
341            }
342            if (!(mHeader->flags&ResStringPool_header::UTF8_FLAG)) {
343                const char16_t* strings = (const char16_t*)mStrings;
344                char16_t* s = const_cast<char16_t*>(strings);
345                for (i=0; i<mStringPoolSize; i++) {
346                    s[i] = dtohs(strings[i]);
347                }
348            }
349        }
350
351        if ((mHeader->flags&ResStringPool_header::UTF8_FLAG &&
352                ((uint8_t*)mStrings)[mStringPoolSize-1] != 0) ||
353                (!mHeader->flags&ResStringPool_header::UTF8_FLAG &&
354                ((char16_t*)mStrings)[mStringPoolSize-1] != 0)) {
355            LOGW("Bad string block: last string is not 0-terminated\n");
356            return (mError=BAD_TYPE);
357        }
358    } else {
359        mStrings = NULL;
360        mStringPoolSize = 0;
361    }
362
363    if (mHeader->styleCount > 0) {
364        mEntryStyles = mEntries + mHeader->stringCount;
365        // invariant: integer overflow in calculating mEntryStyles
366        if (mEntryStyles < mEntries) {
367            LOGW("Bad string block: integer overflow finding styles\n");
368            return (mError=BAD_TYPE);
369        }
370
371        if (((const uint8_t*)mEntryStyles-(const uint8_t*)mHeader) > (int)size) {
372            LOGW("Bad string block: entry of %d styles extends past data size %d\n",
373                    (int)((const uint8_t*)mEntryStyles-(const uint8_t*)mHeader),
374                    (int)size);
375            return (mError=BAD_TYPE);
376        }
377        mStyles = (const uint32_t*)
378            (((const uint8_t*)data)+mHeader->stylesStart);
379        if (mHeader->stylesStart >= mHeader->header.size) {
380            LOGW("Bad string block: style pool starts %d, after total size %d\n",
381                    (int)mHeader->stylesStart, (int)mHeader->header.size);
382            return (mError=BAD_TYPE);
383        }
384        mStylePoolSize =
385            (mHeader->header.size-mHeader->stylesStart)/sizeof(uint32_t);
386
387        if (notDeviceEndian) {
388            size_t i;
389            uint32_t* e = const_cast<uint32_t*>(mEntryStyles);
390            for (i=0; i<mHeader->styleCount; i++) {
391                e[i] = dtohl(mEntryStyles[i]);
392            }
393            uint32_t* s = const_cast<uint32_t*>(mStyles);
394            for (i=0; i<mStylePoolSize; i++) {
395                s[i] = dtohl(mStyles[i]);
396            }
397        }
398
399        const ResStringPool_span endSpan = {
400            { htodl(ResStringPool_span::END) },
401            htodl(ResStringPool_span::END), htodl(ResStringPool_span::END)
402        };
403        if (memcmp(&mStyles[mStylePoolSize-(sizeof(endSpan)/sizeof(uint32_t))],
404                   &endSpan, sizeof(endSpan)) != 0) {
405            LOGW("Bad string block: last style is not 0xFFFFFFFF-terminated\n");
406            return (mError=BAD_TYPE);
407        }
408    } else {
409        mEntryStyles = NULL;
410        mStyles = NULL;
411        mStylePoolSize = 0;
412    }
413
414    return (mError=NO_ERROR);
415}
416
417status_t ResStringPool::getError() const
418{
419    return mError;
420}
421
422void ResStringPool::uninit()
423{
424    mError = NO_INIT;
425    if (mOwnedData) {
426        free(mOwnedData);
427        mOwnedData = NULL;
428    }
429    if (mHeader != NULL && mCache != NULL) {
430        for (size_t x = 0; x < mHeader->stringCount; x++) {
431            if (mCache[x] != NULL) {
432                free(mCache[x]);
433                mCache[x] = NULL;
434            }
435        }
436        free(mCache);
437        mCache = NULL;
438    }
439}
440
441#define DECODE_LENGTH(str, chrsz, len) \
442    len = *(str); \
443    if (*(str)&(1<<(chrsz*8-1))) { \
444        (str)++; \
445        len = (((len)&((1<<(chrsz*8-1))-1))<<(chrsz*8)) + *(str); \
446    } \
447    (str)++;
448
449const uint16_t* ResStringPool::stringAt(size_t idx, size_t* outLen) const
450{
451    if (mError == NO_ERROR && idx < mHeader->stringCount) {
452        const bool isUTF8 = (mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0;
453        const uint32_t off = mEntries[idx]/(isUTF8?sizeof(char):sizeof(char16_t));
454        if (off < (mStringPoolSize-1)) {
455            if (!isUTF8) {
456                const char16_t* strings = (char16_t*)mStrings;
457                const char16_t* str = strings+off;
458                DECODE_LENGTH(str, sizeof(char16_t), *outLen)
459                if ((uint32_t)(str+*outLen-strings) < mStringPoolSize) {
460                    return str;
461                } else {
462                    LOGW("Bad string block: string #%d extends to %d, past end at %d\n",
463                            (int)idx, (int)(str+*outLen-strings), (int)mStringPoolSize);
464                }
465            } else {
466                const uint8_t* strings = (uint8_t*)mStrings;
467                const uint8_t* str = strings+off;
468                DECODE_LENGTH(str, sizeof(uint8_t), *outLen)
469                size_t encLen;
470                DECODE_LENGTH(str, sizeof(uint8_t), encLen)
471                if ((uint32_t)(str+encLen-strings) < mStringPoolSize) {
472                    AutoMutex lock(mDecodeLock);
473                    if (mCache[idx] != NULL) {
474                        return mCache[idx];
475                    }
476                    char16_t *u16str = (char16_t *)calloc(*outLen+1, sizeof(char16_t));
477                    if (!u16str) {
478                        LOGW("No memory when trying to allocate decode cache for string #%d\n",
479                                (int)idx);
480                        return NULL;
481                    }
482                    const unsigned char *u8src = reinterpret_cast<const unsigned char *>(str);
483                    utf8_to_utf16(u8src, encLen, u16str, *outLen);
484                    mCache[idx] = u16str;
485                    return u16str;
486                } else {
487                    LOGW("Bad string block: string #%d extends to %d, past end at %d\n",
488                            (int)idx, (int)(str+encLen-strings), (int)mStringPoolSize);
489                }
490            }
491        } else {
492            LOGW("Bad string block: string #%d entry is at %d, past end at %d\n",
493                    (int)idx, (int)(off*sizeof(uint16_t)),
494                    (int)(mStringPoolSize*sizeof(uint16_t)));
495        }
496    }
497    return NULL;
498}
499
500const char* ResStringPool::string8At(size_t idx, size_t* outLen) const
501{
502    if (mError == NO_ERROR && idx < mHeader->stringCount) {
503        const bool isUTF8 = (mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0;
504        const uint32_t off = mEntries[idx]/(isUTF8?sizeof(char):sizeof(char16_t));
505        if (off < (mStringPoolSize-1)) {
506            if (isUTF8) {
507                const uint8_t* strings = (uint8_t*)mStrings;
508                const uint8_t* str = strings+off;
509                DECODE_LENGTH(str, sizeof(uint8_t), *outLen)
510                size_t encLen;
511                DECODE_LENGTH(str, sizeof(uint8_t), encLen)
512                if ((uint32_t)(str+encLen-strings) < mStringPoolSize) {
513                    return (const char*)str;
514                } else {
515                    LOGW("Bad string block: string #%d extends to %d, past end at %d\n",
516                            (int)idx, (int)(str+encLen-strings), (int)mStringPoolSize);
517                }
518            }
519        } else {
520            LOGW("Bad string block: string #%d entry is at %d, past end at %d\n",
521                    (int)idx, (int)(off*sizeof(uint16_t)),
522                    (int)(mStringPoolSize*sizeof(uint16_t)));
523        }
524    }
525    return NULL;
526}
527
528const ResStringPool_span* ResStringPool::styleAt(const ResStringPool_ref& ref) const
529{
530    return styleAt(ref.index);
531}
532
533const ResStringPool_span* ResStringPool::styleAt(size_t idx) const
534{
535    if (mError == NO_ERROR && idx < mHeader->styleCount) {
536        const uint32_t off = (mEntryStyles[idx]/sizeof(uint32_t));
537        if (off < mStylePoolSize) {
538            return (const ResStringPool_span*)(mStyles+off);
539        } else {
540            LOGW("Bad string block: style #%d entry is at %d, past end at %d\n",
541                    (int)idx, (int)(off*sizeof(uint32_t)),
542                    (int)(mStylePoolSize*sizeof(uint32_t)));
543        }
544    }
545    return NULL;
546}
547
548ssize_t ResStringPool::indexOfString(const char16_t* str, size_t strLen) const
549{
550    if (mError != NO_ERROR) {
551        return mError;
552    }
553
554    size_t len;
555
556    // TODO optimize searching for UTF-8 strings taking into account
557    // the cache fill to determine when to convert the searched-for
558    // string key to UTF-8.
559
560    if (mHeader->flags&ResStringPool_header::SORTED_FLAG) {
561        // Do a binary search for the string...
562        ssize_t l = 0;
563        ssize_t h = mHeader->stringCount-1;
564
565        ssize_t mid;
566        while (l <= h) {
567            mid = l + (h - l)/2;
568            const char16_t* s = stringAt(mid, &len);
569            int c = s ? strzcmp16(s, len, str, strLen) : -1;
570            POOL_NOISY(printf("Looking for %s, at %s, cmp=%d, l/mid/h=%d/%d/%d\n",
571                         String8(str).string(),
572                         String8(s).string(),
573                         c, (int)l, (int)mid, (int)h));
574            if (c == 0) {
575                return mid;
576            } else if (c < 0) {
577                l = mid + 1;
578            } else {
579                h = mid - 1;
580            }
581        }
582    } else {
583        // It is unusual to get the ID from an unsorted string block...
584        // most often this happens because we want to get IDs for style
585        // span tags; since those always appear at the end of the string
586        // block, start searching at the back.
587        for (int i=mHeader->stringCount-1; i>=0; i--) {
588            const char16_t* s = stringAt(i, &len);
589            POOL_NOISY(printf("Looking for %s, at %s, i=%d\n",
590                         String8(str, strLen).string(),
591                         String8(s).string(),
592                         i));
593            if (s && strzcmp16(s, len, str, strLen) == 0) {
594                return i;
595            }
596        }
597    }
598
599    return NAME_NOT_FOUND;
600}
601
602size_t ResStringPool::size() const
603{
604    return (mError == NO_ERROR) ? mHeader->stringCount : 0;
605}
606
607#ifndef HAVE_ANDROID_OS
608bool ResStringPool::isUTF8() const
609{
610    return (mHeader->flags&ResStringPool_header::UTF8_FLAG)!=0;
611}
612#endif
613
614// --------------------------------------------------------------------
615// --------------------------------------------------------------------
616// --------------------------------------------------------------------
617
618ResXMLParser::ResXMLParser(const ResXMLTree& tree)
619    : mTree(tree), mEventCode(BAD_DOCUMENT)
620{
621}
622
623void ResXMLParser::restart()
624{
625    mCurNode = NULL;
626    mEventCode = mTree.mError == NO_ERROR ? START_DOCUMENT : BAD_DOCUMENT;
627}
628
629ResXMLParser::event_code_t ResXMLParser::getEventType() const
630{
631    return mEventCode;
632}
633
634ResXMLParser::event_code_t ResXMLParser::next()
635{
636    if (mEventCode == START_DOCUMENT) {
637        mCurNode = mTree.mRootNode;
638        mCurExt = mTree.mRootExt;
639        return (mEventCode=mTree.mRootCode);
640    } else if (mEventCode >= FIRST_CHUNK_CODE) {
641        return nextNode();
642    }
643    return mEventCode;
644}
645
646int32_t ResXMLParser::getCommentID() const
647{
648    return mCurNode != NULL ? dtohl(mCurNode->comment.index) : -1;
649}
650
651const uint16_t* ResXMLParser::getComment(size_t* outLen) const
652{
653    int32_t id = getCommentID();
654    return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
655}
656
657uint32_t ResXMLParser::getLineNumber() const
658{
659    return mCurNode != NULL ? dtohl(mCurNode->lineNumber) : -1;
660}
661
662int32_t ResXMLParser::getTextID() const
663{
664    if (mEventCode == TEXT) {
665        return dtohl(((const ResXMLTree_cdataExt*)mCurExt)->data.index);
666    }
667    return -1;
668}
669
670const uint16_t* ResXMLParser::getText(size_t* outLen) const
671{
672    int32_t id = getTextID();
673    return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
674}
675
676ssize_t ResXMLParser::getTextValue(Res_value* outValue) const
677{
678    if (mEventCode == TEXT) {
679        outValue->copyFrom_dtoh(((const ResXMLTree_cdataExt*)mCurExt)->typedData);
680        return sizeof(Res_value);
681    }
682    return BAD_TYPE;
683}
684
685int32_t ResXMLParser::getNamespacePrefixID() const
686{
687    if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) {
688        return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->prefix.index);
689    }
690    return -1;
691}
692
693const uint16_t* ResXMLParser::getNamespacePrefix(size_t* outLen) const
694{
695    int32_t id = getNamespacePrefixID();
696    //printf("prefix=%d  event=%p\n", id, mEventCode);
697    return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
698}
699
700int32_t ResXMLParser::getNamespaceUriID() const
701{
702    if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) {
703        return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->uri.index);
704    }
705    return -1;
706}
707
708const uint16_t* ResXMLParser::getNamespaceUri(size_t* outLen) const
709{
710    int32_t id = getNamespaceUriID();
711    //printf("uri=%d  event=%p\n", id, mEventCode);
712    return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
713}
714
715int32_t ResXMLParser::getElementNamespaceID() const
716{
717    if (mEventCode == START_TAG) {
718        return dtohl(((const ResXMLTree_attrExt*)mCurExt)->ns.index);
719    }
720    if (mEventCode == END_TAG) {
721        return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->ns.index);
722    }
723    return -1;
724}
725
726const uint16_t* ResXMLParser::getElementNamespace(size_t* outLen) const
727{
728    int32_t id = getElementNamespaceID();
729    return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
730}
731
732int32_t ResXMLParser::getElementNameID() const
733{
734    if (mEventCode == START_TAG) {
735        return dtohl(((const ResXMLTree_attrExt*)mCurExt)->name.index);
736    }
737    if (mEventCode == END_TAG) {
738        return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->name.index);
739    }
740    return -1;
741}
742
743const uint16_t* ResXMLParser::getElementName(size_t* outLen) const
744{
745    int32_t id = getElementNameID();
746    return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
747}
748
749size_t ResXMLParser::getAttributeCount() const
750{
751    if (mEventCode == START_TAG) {
752        return dtohs(((const ResXMLTree_attrExt*)mCurExt)->attributeCount);
753    }
754    return 0;
755}
756
757int32_t ResXMLParser::getAttributeNamespaceID(size_t idx) const
758{
759    if (mEventCode == START_TAG) {
760        const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
761        if (idx < dtohs(tag->attributeCount)) {
762            const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
763                (((const uint8_t*)tag)
764                 + dtohs(tag->attributeStart)
765                 + (dtohs(tag->attributeSize)*idx));
766            return dtohl(attr->ns.index);
767        }
768    }
769    return -2;
770}
771
772const uint16_t* ResXMLParser::getAttributeNamespace(size_t idx, size_t* outLen) const
773{
774    int32_t id = getAttributeNamespaceID(idx);
775    //printf("attribute namespace=%d  idx=%d  event=%p\n", id, idx, mEventCode);
776    //XML_NOISY(printf("getAttributeNamespace 0x%x=0x%x\n", idx, id));
777    return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
778}
779
780int32_t ResXMLParser::getAttributeNameID(size_t idx) const
781{
782    if (mEventCode == START_TAG) {
783        const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
784        if (idx < dtohs(tag->attributeCount)) {
785            const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
786                (((const uint8_t*)tag)
787                 + dtohs(tag->attributeStart)
788                 + (dtohs(tag->attributeSize)*idx));
789            return dtohl(attr->name.index);
790        }
791    }
792    return -1;
793}
794
795const uint16_t* ResXMLParser::getAttributeName(size_t idx, size_t* outLen) const
796{
797    int32_t id = getAttributeNameID(idx);
798    //printf("attribute name=%d  idx=%d  event=%p\n", id, idx, mEventCode);
799    //XML_NOISY(printf("getAttributeName 0x%x=0x%x\n", idx, id));
800    return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
801}
802
803uint32_t ResXMLParser::getAttributeNameResID(size_t idx) const
804{
805    int32_t id = getAttributeNameID(idx);
806    if (id >= 0 && (size_t)id < mTree.mNumResIds) {
807        return dtohl(mTree.mResIds[id]);
808    }
809    return 0;
810}
811
812int32_t ResXMLParser::getAttributeValueStringID(size_t idx) const
813{
814    if (mEventCode == START_TAG) {
815        const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
816        if (idx < dtohs(tag->attributeCount)) {
817            const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
818                (((const uint8_t*)tag)
819                 + dtohs(tag->attributeStart)
820                 + (dtohs(tag->attributeSize)*idx));
821            return dtohl(attr->rawValue.index);
822        }
823    }
824    return -1;
825}
826
827const uint16_t* ResXMLParser::getAttributeStringValue(size_t idx, size_t* outLen) const
828{
829    int32_t id = getAttributeValueStringID(idx);
830    //XML_NOISY(printf("getAttributeValue 0x%x=0x%x\n", idx, id));
831    return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
832}
833
834int32_t ResXMLParser::getAttributeDataType(size_t idx) const
835{
836    if (mEventCode == START_TAG) {
837        const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
838        if (idx < dtohs(tag->attributeCount)) {
839            const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
840                (((const uint8_t*)tag)
841                 + dtohs(tag->attributeStart)
842                 + (dtohs(tag->attributeSize)*idx));
843            return attr->typedValue.dataType;
844        }
845    }
846    return Res_value::TYPE_NULL;
847}
848
849int32_t ResXMLParser::getAttributeData(size_t idx) const
850{
851    if (mEventCode == START_TAG) {
852        const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
853        if (idx < dtohs(tag->attributeCount)) {
854            const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
855                (((const uint8_t*)tag)
856                 + dtohs(tag->attributeStart)
857                 + (dtohs(tag->attributeSize)*idx));
858            return dtohl(attr->typedValue.data);
859        }
860    }
861    return 0;
862}
863
864ssize_t ResXMLParser::getAttributeValue(size_t idx, Res_value* outValue) const
865{
866    if (mEventCode == START_TAG) {
867        const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
868        if (idx < dtohs(tag->attributeCount)) {
869            const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
870                (((const uint8_t*)tag)
871                 + dtohs(tag->attributeStart)
872                 + (dtohs(tag->attributeSize)*idx));
873            outValue->copyFrom_dtoh(attr->typedValue);
874            return sizeof(Res_value);
875        }
876    }
877    return BAD_TYPE;
878}
879
880ssize_t ResXMLParser::indexOfAttribute(const char* ns, const char* attr) const
881{
882    String16 nsStr(ns != NULL ? ns : "");
883    String16 attrStr(attr);
884    return indexOfAttribute(ns ? nsStr.string() : NULL, ns ? nsStr.size() : 0,
885                            attrStr.string(), attrStr.size());
886}
887
888ssize_t ResXMLParser::indexOfAttribute(const char16_t* ns, size_t nsLen,
889                                       const char16_t* attr, size_t attrLen) const
890{
891    if (mEventCode == START_TAG) {
892        const size_t N = getAttributeCount();
893        for (size_t i=0; i<N; i++) {
894            size_t curNsLen, curAttrLen;
895            const char16_t* curNs = getAttributeNamespace(i, &curNsLen);
896            const char16_t* curAttr = getAttributeName(i, &curAttrLen);
897            //printf("%d: ns=%p attr=%p curNs=%p curAttr=%p\n",
898            //       i, ns, attr, curNs, curAttr);
899            //printf(" --> attr=%s, curAttr=%s\n",
900            //       String8(attr).string(), String8(curAttr).string());
901            if (attr && curAttr && (strzcmp16(attr, attrLen, curAttr, curAttrLen) == 0)) {
902                if (ns == NULL) {
903                    if (curNs == NULL) return i;
904                } else if (curNs != NULL) {
905                    //printf(" --> ns=%s, curNs=%s\n",
906                    //       String8(ns).string(), String8(curNs).string());
907                    if (strzcmp16(ns, nsLen, curNs, curNsLen) == 0) return i;
908                }
909            }
910        }
911    }
912
913    return NAME_NOT_FOUND;
914}
915
916ssize_t ResXMLParser::indexOfID() const
917{
918    if (mEventCode == START_TAG) {
919        const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->idIndex);
920        if (idx > 0) return (idx-1);
921    }
922    return NAME_NOT_FOUND;
923}
924
925ssize_t ResXMLParser::indexOfClass() const
926{
927    if (mEventCode == START_TAG) {
928        const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->classIndex);
929        if (idx > 0) return (idx-1);
930    }
931    return NAME_NOT_FOUND;
932}
933
934ssize_t ResXMLParser::indexOfStyle() const
935{
936    if (mEventCode == START_TAG) {
937        const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->styleIndex);
938        if (idx > 0) return (idx-1);
939    }
940    return NAME_NOT_FOUND;
941}
942
943ResXMLParser::event_code_t ResXMLParser::nextNode()
944{
945    if (mEventCode < 0) {
946        return mEventCode;
947    }
948
949    do {
950        const ResXMLTree_node* next = (const ResXMLTree_node*)
951            (((const uint8_t*)mCurNode) + dtohl(mCurNode->header.size));
952        //LOGW("Next node: prev=%p, next=%p\n", mCurNode, next);
953
954        if (((const uint8_t*)next) >= mTree.mDataEnd) {
955            mCurNode = NULL;
956            return (mEventCode=END_DOCUMENT);
957        }
958
959        if (mTree.validateNode(next) != NO_ERROR) {
960            mCurNode = NULL;
961            return (mEventCode=BAD_DOCUMENT);
962        }
963
964        mCurNode = next;
965        const uint16_t headerSize = dtohs(next->header.headerSize);
966        const uint32_t totalSize = dtohl(next->header.size);
967        mCurExt = ((const uint8_t*)next) + headerSize;
968        size_t minExtSize = 0;
969        event_code_t eventCode = (event_code_t)dtohs(next->header.type);
970        switch ((mEventCode=eventCode)) {
971            case RES_XML_START_NAMESPACE_TYPE:
972            case RES_XML_END_NAMESPACE_TYPE:
973                minExtSize = sizeof(ResXMLTree_namespaceExt);
974                break;
975            case RES_XML_START_ELEMENT_TYPE:
976                minExtSize = sizeof(ResXMLTree_attrExt);
977                break;
978            case RES_XML_END_ELEMENT_TYPE:
979                minExtSize = sizeof(ResXMLTree_endElementExt);
980                break;
981            case RES_XML_CDATA_TYPE:
982                minExtSize = sizeof(ResXMLTree_cdataExt);
983                break;
984            default:
985                LOGW("Unknown XML block: header type %d in node at %d\n",
986                     (int)dtohs(next->header.type),
987                     (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)));
988                continue;
989        }
990
991        if ((totalSize-headerSize) < minExtSize) {
992            LOGW("Bad XML block: header type 0x%x in node at 0x%x has size %d, need %d\n",
993                 (int)dtohs(next->header.type),
994                 (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)),
995                 (int)(totalSize-headerSize), (int)minExtSize);
996            return (mEventCode=BAD_DOCUMENT);
997        }
998
999        //printf("CurNode=%p, CurExt=%p, headerSize=%d, minExtSize=%d\n",
1000        //       mCurNode, mCurExt, headerSize, minExtSize);
1001
1002        return eventCode;
1003    } while (true);
1004}
1005
1006void ResXMLParser::getPosition(ResXMLParser::ResXMLPosition* pos) const
1007{
1008    pos->eventCode = mEventCode;
1009    pos->curNode = mCurNode;
1010    pos->curExt = mCurExt;
1011}
1012
1013void ResXMLParser::setPosition(const ResXMLParser::ResXMLPosition& pos)
1014{
1015    mEventCode = pos.eventCode;
1016    mCurNode = pos.curNode;
1017    mCurExt = pos.curExt;
1018}
1019
1020
1021// --------------------------------------------------------------------
1022
1023static volatile int32_t gCount = 0;
1024
1025ResXMLTree::ResXMLTree()
1026    : ResXMLParser(*this)
1027    , mError(NO_INIT), mOwnedData(NULL)
1028{
1029    //LOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1);
1030    restart();
1031}
1032
1033ResXMLTree::ResXMLTree(const void* data, size_t size, bool copyData)
1034    : ResXMLParser(*this)
1035    , mError(NO_INIT), mOwnedData(NULL)
1036{
1037    //LOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1);
1038    setTo(data, size, copyData);
1039}
1040
1041ResXMLTree::~ResXMLTree()
1042{
1043    //LOGI("Destroying ResXMLTree in %p #%d\n", this, android_atomic_dec(&gCount)-1);
1044    uninit();
1045}
1046
1047status_t ResXMLTree::setTo(const void* data, size_t size, bool copyData)
1048{
1049    uninit();
1050    mEventCode = START_DOCUMENT;
1051
1052    if (copyData) {
1053        mOwnedData = malloc(size);
1054        if (mOwnedData == NULL) {
1055            return (mError=NO_MEMORY);
1056        }
1057        memcpy(mOwnedData, data, size);
1058        data = mOwnedData;
1059    }
1060
1061    mHeader = (const ResXMLTree_header*)data;
1062    mSize = dtohl(mHeader->header.size);
1063    if (dtohs(mHeader->header.headerSize) > mSize || mSize > size) {
1064        LOGW("Bad XML block: header size %d or total size %d is larger than data size %d\n",
1065             (int)dtohs(mHeader->header.headerSize),
1066             (int)dtohl(mHeader->header.size), (int)size);
1067        mError = BAD_TYPE;
1068        restart();
1069        return mError;
1070    }
1071    mDataEnd = ((const uint8_t*)mHeader) + mSize;
1072
1073    mStrings.uninit();
1074    mRootNode = NULL;
1075    mResIds = NULL;
1076    mNumResIds = 0;
1077
1078    // First look for a couple interesting chunks: the string block
1079    // and first XML node.
1080    const ResChunk_header* chunk =
1081        (const ResChunk_header*)(((const uint8_t*)mHeader) + dtohs(mHeader->header.headerSize));
1082    const ResChunk_header* lastChunk = chunk;
1083    while (((const uint8_t*)chunk) < (mDataEnd-sizeof(ResChunk_header)) &&
1084           ((const uint8_t*)chunk) < (mDataEnd-dtohl(chunk->size))) {
1085        status_t err = validate_chunk(chunk, sizeof(ResChunk_header), mDataEnd, "XML");
1086        if (err != NO_ERROR) {
1087            mError = err;
1088            goto done;
1089        }
1090        const uint16_t type = dtohs(chunk->type);
1091        const size_t size = dtohl(chunk->size);
1092        XML_NOISY(printf("Scanning @ %p: type=0x%x, size=0x%x\n",
1093                     (void*)(((uint32_t)chunk)-((uint32_t)mHeader)), type, size));
1094        if (type == RES_STRING_POOL_TYPE) {
1095            mStrings.setTo(chunk, size);
1096        } else if (type == RES_XML_RESOURCE_MAP_TYPE) {
1097            mResIds = (const uint32_t*)
1098                (((const uint8_t*)chunk)+dtohs(chunk->headerSize));
1099            mNumResIds = (dtohl(chunk->size)-dtohs(chunk->headerSize))/sizeof(uint32_t);
1100        } else if (type >= RES_XML_FIRST_CHUNK_TYPE
1101                   && type <= RES_XML_LAST_CHUNK_TYPE) {
1102            if (validateNode((const ResXMLTree_node*)chunk) != NO_ERROR) {
1103                mError = BAD_TYPE;
1104                goto done;
1105            }
1106            mCurNode = (const ResXMLTree_node*)lastChunk;
1107            if (nextNode() == BAD_DOCUMENT) {
1108                mError = BAD_TYPE;
1109                goto done;
1110            }
1111            mRootNode = mCurNode;
1112            mRootExt = mCurExt;
1113            mRootCode = mEventCode;
1114            break;
1115        } else {
1116            XML_NOISY(printf("Skipping unknown chunk!\n"));
1117        }
1118        lastChunk = chunk;
1119        chunk = (const ResChunk_header*)
1120            (((const uint8_t*)chunk) + size);
1121    }
1122
1123    if (mRootNode == NULL) {
1124        LOGW("Bad XML block: no root element node found\n");
1125        mError = BAD_TYPE;
1126        goto done;
1127    }
1128
1129    mError = mStrings.getError();
1130
1131done:
1132    restart();
1133    return mError;
1134}
1135
1136status_t ResXMLTree::getError() const
1137{
1138    return mError;
1139}
1140
1141void ResXMLTree::uninit()
1142{
1143    mError = NO_INIT;
1144    mStrings.uninit();
1145    if (mOwnedData) {
1146        free(mOwnedData);
1147        mOwnedData = NULL;
1148    }
1149    restart();
1150}
1151
1152const ResStringPool& ResXMLTree::getStrings() const
1153{
1154    return mStrings;
1155}
1156
1157status_t ResXMLTree::validateNode(const ResXMLTree_node* node) const
1158{
1159    const uint16_t eventCode = dtohs(node->header.type);
1160
1161    status_t err = validate_chunk(
1162        &node->header, sizeof(ResXMLTree_node),
1163        mDataEnd, "ResXMLTree_node");
1164
1165    if (err >= NO_ERROR) {
1166        // Only perform additional validation on START nodes
1167        if (eventCode != RES_XML_START_ELEMENT_TYPE) {
1168            return NO_ERROR;
1169        }
1170
1171        const uint16_t headerSize = dtohs(node->header.headerSize);
1172        const uint32_t size = dtohl(node->header.size);
1173        const ResXMLTree_attrExt* attrExt = (const ResXMLTree_attrExt*)
1174            (((const uint8_t*)node) + headerSize);
1175        // check for sensical values pulled out of the stream so far...
1176        if ((size >= headerSize + sizeof(ResXMLTree_attrExt))
1177                && ((void*)attrExt > (void*)node)) {
1178            const size_t attrSize = ((size_t)dtohs(attrExt->attributeSize))
1179                * dtohs(attrExt->attributeCount);
1180            if ((dtohs(attrExt->attributeStart)+attrSize) <= (size-headerSize)) {
1181                return NO_ERROR;
1182            }
1183            LOGW("Bad XML block: node attributes use 0x%x bytes, only have 0x%x bytes\n",
1184                    (unsigned int)(dtohs(attrExt->attributeStart)+attrSize),
1185                    (unsigned int)(size-headerSize));
1186        }
1187        else {
1188            LOGW("Bad XML start block: node header size 0x%x, size 0x%x\n",
1189                (unsigned int)headerSize, (unsigned int)size);
1190        }
1191        return BAD_TYPE;
1192    }
1193
1194    return err;
1195
1196#if 0
1197    const bool isStart = dtohs(node->header.type) == RES_XML_START_ELEMENT_TYPE;
1198
1199    const uint16_t headerSize = dtohs(node->header.headerSize);
1200    const uint32_t size = dtohl(node->header.size);
1201
1202    if (headerSize >= (isStart ? sizeof(ResXMLTree_attrNode) : sizeof(ResXMLTree_node))) {
1203        if (size >= headerSize) {
1204            if (((const uint8_t*)node) <= (mDataEnd-size)) {
1205                if (!isStart) {
1206                    return NO_ERROR;
1207                }
1208                if ((((size_t)dtohs(node->attributeSize))*dtohs(node->attributeCount))
1209                        <= (size-headerSize)) {
1210                    return NO_ERROR;
1211                }
1212                LOGW("Bad XML block: node attributes use 0x%x bytes, only have 0x%x bytes\n",
1213                        ((int)dtohs(node->attributeSize))*dtohs(node->attributeCount),
1214                        (int)(size-headerSize));
1215                return BAD_TYPE;
1216            }
1217            LOGW("Bad XML block: node at 0x%x extends beyond data end 0x%x\n",
1218                    (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)), (int)mSize);
1219            return BAD_TYPE;
1220        }
1221        LOGW("Bad XML block: node at 0x%x header size 0x%x smaller than total size 0x%x\n",
1222                (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)),
1223                (int)headerSize, (int)size);
1224        return BAD_TYPE;
1225    }
1226    LOGW("Bad XML block: node at 0x%x header size 0x%x too small\n",
1227            (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)),
1228            (int)headerSize);
1229    return BAD_TYPE;
1230#endif
1231}
1232
1233// --------------------------------------------------------------------
1234// --------------------------------------------------------------------
1235// --------------------------------------------------------------------
1236
1237struct ResTable::Header
1238{
1239    Header(ResTable* _owner) : owner(_owner), ownedData(NULL), header(NULL) { }
1240
1241    ResTable* const                 owner;
1242    void*                           ownedData;
1243    const ResTable_header*          header;
1244    size_t                          size;
1245    const uint8_t*                  dataEnd;
1246    size_t                          index;
1247    void*                           cookie;
1248
1249    ResStringPool                   values;
1250};
1251
1252struct ResTable::Type
1253{
1254    Type(const Header* _header, const Package* _package, size_t count)
1255        : header(_header), package(_package), entryCount(count),
1256          typeSpec(NULL), typeSpecFlags(NULL) { }
1257    const Header* const             header;
1258    const Package* const            package;
1259    const size_t                    entryCount;
1260    const ResTable_typeSpec*        typeSpec;
1261    const uint32_t*                 typeSpecFlags;
1262    Vector<const ResTable_type*>    configs;
1263};
1264
1265struct ResTable::Package
1266{
1267    Package(ResTable* _owner, const Header* _header, const ResTable_package* _package)
1268        : owner(_owner), header(_header), package(_package) { }
1269    ~Package()
1270    {
1271        size_t i = types.size();
1272        while (i > 0) {
1273            i--;
1274            delete types[i];
1275        }
1276    }
1277
1278    ResTable* const                 owner;
1279    const Header* const             header;
1280    const ResTable_package* const   package;
1281    Vector<Type*>                   types;
1282
1283    ResStringPool                   typeStrings;
1284    ResStringPool                   keyStrings;
1285
1286    const Type* getType(size_t idx) const {
1287        return idx < types.size() ? types[idx] : NULL;
1288    }
1289};
1290
1291// A group of objects describing a particular resource package.
1292// The first in 'package' is always the root object (from the resource
1293// table that defined the package); the ones after are skins on top of it.
1294struct ResTable::PackageGroup
1295{
1296    PackageGroup(ResTable* _owner, const String16& _name, uint32_t _id)
1297        : owner(_owner), name(_name), id(_id), typeCount(0), bags(NULL) { }
1298    ~PackageGroup() {
1299        clearBagCache();
1300        const size_t N = packages.size();
1301        for (size_t i=0; i<N; i++) {
1302            Package* pkg = packages[i];
1303            if (pkg->owner == owner) {
1304                delete pkg;
1305            }
1306        }
1307    }
1308
1309    void clearBagCache() {
1310        if (bags) {
1311            TABLE_NOISY(printf("bags=%p\n", bags));
1312            Package* pkg = packages[0];
1313            TABLE_NOISY(printf("typeCount=%x\n", typeCount));
1314            for (size_t i=0; i<typeCount; i++) {
1315                TABLE_NOISY(printf("type=%d\n", i));
1316                const Type* type = pkg->getType(i);
1317                if (type != NULL) {
1318                    bag_set** typeBags = bags[i];
1319                    TABLE_NOISY(printf("typeBags=%p\n", typeBags));
1320                    if (typeBags) {
1321                        TABLE_NOISY(printf("type->entryCount=%x\n", type->entryCount));
1322                        const size_t N = type->entryCount;
1323                        for (size_t j=0; j<N; j++) {
1324                            if (typeBags[j] && typeBags[j] != (bag_set*)0xFFFFFFFF)
1325                                free(typeBags[j]);
1326                        }
1327                        free(typeBags);
1328                    }
1329                }
1330            }
1331            free(bags);
1332            bags = NULL;
1333        }
1334    }
1335
1336    ResTable* const                 owner;
1337    String16 const                  name;
1338    uint32_t const                  id;
1339    Vector<Package*>                packages;
1340
1341    // This is for finding typeStrings and other common package stuff.
1342    Package*                        basePackage;
1343
1344    // For quick access.
1345    size_t                          typeCount;
1346
1347    // Computed attribute bags, first indexed by the type and second
1348    // by the entry in that type.
1349    bag_set***                      bags;
1350};
1351
1352struct ResTable::bag_set
1353{
1354    size_t numAttrs;    // number in array
1355    size_t availAttrs;  // total space in array
1356    uint32_t typeSpecFlags;
1357    // Followed by 'numAttr' bag_entry structures.
1358};
1359
1360ResTable::Theme::Theme(const ResTable& table)
1361    : mTable(table)
1362{
1363    memset(mPackages, 0, sizeof(mPackages));
1364}
1365
1366ResTable::Theme::~Theme()
1367{
1368    for (size_t i=0; i<Res_MAXPACKAGE; i++) {
1369        package_info* pi = mPackages[i];
1370        if (pi != NULL) {
1371            free_package(pi);
1372        }
1373    }
1374}
1375
1376void ResTable::Theme::free_package(package_info* pi)
1377{
1378    for (size_t j=0; j<pi->numTypes; j++) {
1379        theme_entry* te = pi->types[j].entries;
1380        if (te != NULL) {
1381            free(te);
1382        }
1383    }
1384    free(pi);
1385}
1386
1387ResTable::Theme::package_info* ResTable::Theme::copy_package(package_info* pi)
1388{
1389    package_info* newpi = (package_info*)malloc(
1390        sizeof(package_info) + (pi->numTypes*sizeof(type_info)));
1391    newpi->numTypes = pi->numTypes;
1392    for (size_t j=0; j<newpi->numTypes; j++) {
1393        size_t cnt = pi->types[j].numEntries;
1394        newpi->types[j].numEntries = cnt;
1395        theme_entry* te = pi->types[j].entries;
1396        if (te != NULL) {
1397            theme_entry* newte = (theme_entry*)malloc(cnt*sizeof(theme_entry));
1398            newpi->types[j].entries = newte;
1399            memcpy(newte, te, cnt*sizeof(theme_entry));
1400        } else {
1401            newpi->types[j].entries = NULL;
1402        }
1403    }
1404    return newpi;
1405}
1406
1407status_t ResTable::Theme::applyStyle(uint32_t resID, bool force)
1408{
1409    const bag_entry* bag;
1410    uint32_t bagTypeSpecFlags = 0;
1411    mTable.lock();
1412    const ssize_t N = mTable.getBagLocked(resID, &bag, &bagTypeSpecFlags);
1413    TABLE_NOISY(LOGV("Applying style 0x%08x to theme %p, count=%d", resID, this, N));
1414    if (N < 0) {
1415        mTable.unlock();
1416        return N;
1417    }
1418
1419    uint32_t curPackage = 0xffffffff;
1420    ssize_t curPackageIndex = 0;
1421    package_info* curPI = NULL;
1422    uint32_t curType = 0xffffffff;
1423    size_t numEntries = 0;
1424    theme_entry* curEntries = NULL;
1425
1426    const bag_entry* end = bag + N;
1427    while (bag < end) {
1428        const uint32_t attrRes = bag->map.name.ident;
1429        const uint32_t p = Res_GETPACKAGE(attrRes);
1430        const uint32_t t = Res_GETTYPE(attrRes);
1431        const uint32_t e = Res_GETENTRY(attrRes);
1432
1433        if (curPackage != p) {
1434            const ssize_t pidx = mTable.getResourcePackageIndex(attrRes);
1435            if (pidx < 0) {
1436                LOGE("Style contains key with bad package: 0x%08x\n", attrRes);
1437                bag++;
1438                continue;
1439            }
1440            curPackage = p;
1441            curPackageIndex = pidx;
1442            curPI = mPackages[pidx];
1443            if (curPI == NULL) {
1444                PackageGroup* const grp = mTable.mPackageGroups[pidx];
1445                int cnt = grp->typeCount;
1446                curPI = (package_info*)malloc(
1447                    sizeof(package_info) + (cnt*sizeof(type_info)));
1448                curPI->numTypes = cnt;
1449                memset(curPI->types, 0, cnt*sizeof(type_info));
1450                mPackages[pidx] = curPI;
1451            }
1452            curType = 0xffffffff;
1453        }
1454        if (curType != t) {
1455            if (t >= curPI->numTypes) {
1456                LOGE("Style contains key with bad type: 0x%08x\n", attrRes);
1457                bag++;
1458                continue;
1459            }
1460            curType = t;
1461            curEntries = curPI->types[t].entries;
1462            if (curEntries == NULL) {
1463                PackageGroup* const grp = mTable.mPackageGroups[curPackageIndex];
1464                const Type* type = grp->packages[0]->getType(t);
1465                int cnt = type != NULL ? type->entryCount : 0;
1466                curEntries = (theme_entry*)malloc(cnt*sizeof(theme_entry));
1467                memset(curEntries, Res_value::TYPE_NULL, cnt*sizeof(theme_entry));
1468                curPI->types[t].numEntries = cnt;
1469                curPI->types[t].entries = curEntries;
1470            }
1471            numEntries = curPI->types[t].numEntries;
1472        }
1473        if (e >= numEntries) {
1474            LOGE("Style contains key with bad entry: 0x%08x\n", attrRes);
1475            bag++;
1476            continue;
1477        }
1478        theme_entry* curEntry = curEntries + e;
1479        TABLE_NOISY(LOGV("Attr 0x%08x: type=0x%x, data=0x%08x; curType=0x%x",
1480                   attrRes, bag->map.value.dataType, bag->map.value.data,
1481             curEntry->value.dataType));
1482        if (force || curEntry->value.dataType == Res_value::TYPE_NULL) {
1483            curEntry->stringBlock = bag->stringBlock;
1484            curEntry->typeSpecFlags |= bagTypeSpecFlags;
1485            curEntry->value = bag->map.value;
1486        }
1487
1488        bag++;
1489    }
1490
1491    mTable.unlock();
1492
1493    //LOGI("Applying style 0x%08x (force=%d)  theme %p...\n", resID, force, this);
1494    //dumpToLog();
1495
1496    return NO_ERROR;
1497}
1498
1499status_t ResTable::Theme::setTo(const Theme& other)
1500{
1501    //LOGI("Setting theme %p from theme %p...\n", this, &other);
1502    //dumpToLog();
1503    //other.dumpToLog();
1504
1505    if (&mTable == &other.mTable) {
1506        for (size_t i=0; i<Res_MAXPACKAGE; i++) {
1507            if (mPackages[i] != NULL) {
1508                free_package(mPackages[i]);
1509            }
1510            if (other.mPackages[i] != NULL) {
1511                mPackages[i] = copy_package(other.mPackages[i]);
1512            } else {
1513                mPackages[i] = NULL;
1514            }
1515        }
1516    } else {
1517        // @todo: need to really implement this, not just copy
1518        // the system package (which is still wrong because it isn't
1519        // fixing up resource references).
1520        for (size_t i=0; i<Res_MAXPACKAGE; i++) {
1521            if (mPackages[i] != NULL) {
1522                free_package(mPackages[i]);
1523            }
1524            if (i == 0 && other.mPackages[i] != NULL) {
1525                mPackages[i] = copy_package(other.mPackages[i]);
1526            } else {
1527                mPackages[i] = NULL;
1528            }
1529        }
1530    }
1531
1532    //LOGI("Final theme:");
1533    //dumpToLog();
1534
1535    return NO_ERROR;
1536}
1537
1538ssize_t ResTable::Theme::getAttribute(uint32_t resID, Res_value* outValue,
1539        uint32_t* outTypeSpecFlags) const
1540{
1541    int cnt = 20;
1542
1543    if (outTypeSpecFlags != NULL) *outTypeSpecFlags = 0;
1544
1545    do {
1546        const ssize_t p = mTable.getResourcePackageIndex(resID);
1547        const uint32_t t = Res_GETTYPE(resID);
1548        const uint32_t e = Res_GETENTRY(resID);
1549
1550        TABLE_THEME(LOGI("Looking up attr 0x%08x in theme %p", resID, this));
1551
1552        if (p >= 0) {
1553            const package_info* const pi = mPackages[p];
1554            TABLE_THEME(LOGI("Found package: %p", pi));
1555            if (pi != NULL) {
1556                TABLE_THEME(LOGI("Desired type index is %ld in avail %d", t, pi->numTypes));
1557                if (t < pi->numTypes) {
1558                    const type_info& ti = pi->types[t];
1559                    TABLE_THEME(LOGI("Desired entry index is %ld in avail %d", e, ti.numEntries));
1560                    if (e < ti.numEntries) {
1561                        const theme_entry& te = ti.entries[e];
1562                        if (outTypeSpecFlags != NULL) {
1563                            *outTypeSpecFlags |= te.typeSpecFlags;
1564                        }
1565                        TABLE_THEME(LOGI("Theme value: type=0x%x, data=0x%08x",
1566                                te.value.dataType, te.value.data));
1567                        const uint8_t type = te.value.dataType;
1568                        if (type == Res_value::TYPE_ATTRIBUTE) {
1569                            if (cnt > 0) {
1570                                cnt--;
1571                                resID = te.value.data;
1572                                continue;
1573                            }
1574                            LOGW("Too many attribute references, stopped at: 0x%08x\n", resID);
1575                            return BAD_INDEX;
1576                        } else if (type != Res_value::TYPE_NULL) {
1577                            *outValue = te.value;
1578                            return te.stringBlock;
1579                        }
1580                        return BAD_INDEX;
1581                    }
1582                }
1583            }
1584        }
1585        break;
1586
1587    } while (true);
1588
1589    return BAD_INDEX;
1590}
1591
1592ssize_t ResTable::Theme::resolveAttributeReference(Res_value* inOutValue,
1593        ssize_t blockIndex, uint32_t* outLastRef,
1594        uint32_t* inoutTypeSpecFlags, ResTable_config* inoutConfig) const
1595{
1596    //printf("Resolving type=0x%x\n", inOutValue->dataType);
1597    if (inOutValue->dataType == Res_value::TYPE_ATTRIBUTE) {
1598        uint32_t newTypeSpecFlags;
1599        blockIndex = getAttribute(inOutValue->data, inOutValue, &newTypeSpecFlags);
1600        TABLE_THEME(LOGI("Resolving attr reference: blockIndex=%d, type=0x%x, data=%p\n",
1601             (int)blockIndex, (int)inOutValue->dataType, (void*)inOutValue->data));
1602        if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newTypeSpecFlags;
1603        //printf("Retrieved attribute new type=0x%x\n", inOutValue->dataType);
1604        if (blockIndex < 0) {
1605            return blockIndex;
1606        }
1607    }
1608    return mTable.resolveReference(inOutValue, blockIndex, outLastRef,
1609            inoutTypeSpecFlags, inoutConfig);
1610}
1611
1612void ResTable::Theme::dumpToLog() const
1613{
1614    LOGI("Theme %p:\n", this);
1615    for (size_t i=0; i<Res_MAXPACKAGE; i++) {
1616        package_info* pi = mPackages[i];
1617        if (pi == NULL) continue;
1618
1619        LOGI("  Package #0x%02x:\n", (int)(i+1));
1620        for (size_t j=0; j<pi->numTypes; j++) {
1621            type_info& ti = pi->types[j];
1622            if (ti.numEntries == 0) continue;
1623
1624            LOGI("    Type #0x%02x:\n", (int)(j+1));
1625            for (size_t k=0; k<ti.numEntries; k++) {
1626                theme_entry& te = ti.entries[k];
1627                if (te.value.dataType == Res_value::TYPE_NULL) continue;
1628                LOGI("      0x%08x: t=0x%x, d=0x%08x (block=%d)\n",
1629                     (int)Res_MAKEID(i, j, k),
1630                     te.value.dataType, (int)te.value.data, (int)te.stringBlock);
1631            }
1632        }
1633    }
1634}
1635
1636ResTable::ResTable()
1637    : mError(NO_INIT)
1638{
1639    memset(&mParams, 0, sizeof(mParams));
1640    memset(mPackageMap, 0, sizeof(mPackageMap));
1641    //LOGI("Creating ResTable %p\n", this);
1642}
1643
1644ResTable::ResTable(const void* data, size_t size, void* cookie, bool copyData)
1645    : mError(NO_INIT)
1646{
1647    memset(&mParams, 0, sizeof(mParams));
1648    memset(mPackageMap, 0, sizeof(mPackageMap));
1649    add(data, size, cookie, copyData);
1650    LOG_FATAL_IF(mError != NO_ERROR, "Error parsing resource table");
1651    //LOGI("Creating ResTable %p\n", this);
1652}
1653
1654ResTable::~ResTable()
1655{
1656    //LOGI("Destroying ResTable in %p\n", this);
1657    uninit();
1658}
1659
1660inline ssize_t ResTable::getResourcePackageIndex(uint32_t resID) const
1661{
1662    return ((ssize_t)mPackageMap[Res_GETPACKAGE(resID)+1])-1;
1663}
1664
1665status_t ResTable::add(const void* data, size_t size, void* cookie, bool copyData)
1666{
1667    return add(data, size, cookie, NULL, copyData);
1668}
1669
1670status_t ResTable::add(Asset* asset, void* cookie, bool copyData)
1671{
1672    const void* data = asset->getBuffer(true);
1673    if (data == NULL) {
1674        LOGW("Unable to get buffer of resource asset file");
1675        return UNKNOWN_ERROR;
1676    }
1677    size_t size = (size_t)asset->getLength();
1678    return add(data, size, cookie, asset, copyData);
1679}
1680
1681status_t ResTable::add(ResTable* src)
1682{
1683    mError = src->mError;
1684
1685    for (size_t i=0; i<src->mHeaders.size(); i++) {
1686        mHeaders.add(src->mHeaders[i]);
1687    }
1688
1689    for (size_t i=0; i<src->mPackageGroups.size(); i++) {
1690        PackageGroup* srcPg = src->mPackageGroups[i];
1691        PackageGroup* pg = new PackageGroup(this, srcPg->name, srcPg->id);
1692        for (size_t j=0; j<srcPg->packages.size(); j++) {
1693            pg->packages.add(srcPg->packages[j]);
1694        }
1695        pg->basePackage = srcPg->basePackage;
1696        pg->typeCount = srcPg->typeCount;
1697        mPackageGroups.add(pg);
1698    }
1699
1700    memcpy(mPackageMap, src->mPackageMap, sizeof(mPackageMap));
1701
1702    return mError;
1703}
1704
1705status_t ResTable::add(const void* data, size_t size, void* cookie,
1706                       Asset* asset, bool copyData)
1707{
1708    if (!data) return NO_ERROR;
1709    Header* header = new Header(this);
1710    header->index = mHeaders.size();
1711    header->cookie = cookie;
1712    mHeaders.add(header);
1713
1714    const bool notDeviceEndian = htods(0xf0) != 0xf0;
1715
1716    LOAD_TABLE_NOISY(
1717        LOGV("Adding resources to ResTable: data=%p, size=0x%x, cookie=%p, asset=%p, copy=%d\n",
1718             data, size, cookie, asset, copyData));
1719
1720    if (copyData || notDeviceEndian) {
1721        header->ownedData = malloc(size);
1722        if (header->ownedData == NULL) {
1723            return (mError=NO_MEMORY);
1724        }
1725        memcpy(header->ownedData, data, size);
1726        data = header->ownedData;
1727    }
1728
1729    header->header = (const ResTable_header*)data;
1730    header->size = dtohl(header->header->header.size);
1731    //LOGI("Got size 0x%x, again size 0x%x, raw size 0x%x\n", header->size,
1732    //     dtohl(header->header->header.size), header->header->header.size);
1733    LOAD_TABLE_NOISY(LOGV("Loading ResTable @%p:\n", header->header));
1734    LOAD_TABLE_NOISY(printHexData(2, header->header, header->size < 256 ? header->size : 256,
1735                                  16, 16, 0, false, printToLogFunc));
1736    if (dtohs(header->header->header.headerSize) > header->size
1737            || header->size > size) {
1738        LOGW("Bad resource table: header size 0x%x or total size 0x%x is larger than data size 0x%x\n",
1739             (int)dtohs(header->header->header.headerSize),
1740             (int)header->size, (int)size);
1741        return (mError=BAD_TYPE);
1742    }
1743    if (((dtohs(header->header->header.headerSize)|header->size)&0x3) != 0) {
1744        LOGW("Bad resource table: header size 0x%x or total size 0x%x is not on an integer boundary\n",
1745             (int)dtohs(header->header->header.headerSize),
1746             (int)header->size);
1747        return (mError=BAD_TYPE);
1748    }
1749    header->dataEnd = ((const uint8_t*)header->header) + header->size;
1750
1751    // Iterate through all chunks.
1752    size_t curPackage = 0;
1753
1754    const ResChunk_header* chunk =
1755        (const ResChunk_header*)(((const uint8_t*)header->header)
1756                                 + dtohs(header->header->header.headerSize));
1757    while (((const uint8_t*)chunk) <= (header->dataEnd-sizeof(ResChunk_header)) &&
1758           ((const uint8_t*)chunk) <= (header->dataEnd-dtohl(chunk->size))) {
1759        status_t err = validate_chunk(chunk, sizeof(ResChunk_header), header->dataEnd, "ResTable");
1760        if (err != NO_ERROR) {
1761            return (mError=err);
1762        }
1763        TABLE_NOISY(LOGV("Chunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n",
1764                     dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
1765                     (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header))));
1766        const size_t csize = dtohl(chunk->size);
1767        const uint16_t ctype = dtohs(chunk->type);
1768        if (ctype == RES_STRING_POOL_TYPE) {
1769            if (header->values.getError() != NO_ERROR) {
1770                // Only use the first string chunk; ignore any others that
1771                // may appear.
1772                status_t err = header->values.setTo(chunk, csize);
1773                if (err != NO_ERROR) {
1774                    return (mError=err);
1775                }
1776            } else {
1777                LOGW("Multiple string chunks found in resource table.");
1778            }
1779        } else if (ctype == RES_TABLE_PACKAGE_TYPE) {
1780            if (curPackage >= dtohl(header->header->packageCount)) {
1781                LOGW("More package chunks were found than the %d declared in the header.",
1782                     dtohl(header->header->packageCount));
1783                return (mError=BAD_TYPE);
1784            }
1785            if (parsePackage((ResTable_package*)chunk, header) != NO_ERROR) {
1786                return mError;
1787            }
1788            curPackage++;
1789        } else {
1790            LOGW("Unknown chunk type %p in table at %p.\n",
1791                 (void*)(int)(ctype),
1792                 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)));
1793        }
1794        chunk = (const ResChunk_header*)
1795            (((const uint8_t*)chunk) + csize);
1796    }
1797
1798    if (curPackage < dtohl(header->header->packageCount)) {
1799        LOGW("Fewer package chunks (%d) were found than the %d declared in the header.",
1800             (int)curPackage, dtohl(header->header->packageCount));
1801        return (mError=BAD_TYPE);
1802    }
1803    mError = header->values.getError();
1804    if (mError != NO_ERROR) {
1805        LOGW("No string values found in resource table!");
1806    }
1807    TABLE_NOISY(LOGV("Returning from add with mError=%d\n", mError));
1808    return mError;
1809}
1810
1811status_t ResTable::getError() const
1812{
1813    return mError;
1814}
1815
1816void ResTable::uninit()
1817{
1818    mError = NO_INIT;
1819    size_t N = mPackageGroups.size();
1820    for (size_t i=0; i<N; i++) {
1821        PackageGroup* g = mPackageGroups[i];
1822        delete g;
1823    }
1824    N = mHeaders.size();
1825    for (size_t i=0; i<N; i++) {
1826        Header* header = mHeaders[i];
1827        if (header->owner == this) {
1828            if (header->ownedData) {
1829                free(header->ownedData);
1830            }
1831            delete header;
1832        }
1833    }
1834
1835    mPackageGroups.clear();
1836    mHeaders.clear();
1837}
1838
1839bool ResTable::getResourceName(uint32_t resID, resource_name* outName) const
1840{
1841    if (mError != NO_ERROR) {
1842        return false;
1843    }
1844
1845    const ssize_t p = getResourcePackageIndex(resID);
1846    const int t = Res_GETTYPE(resID);
1847    const int e = Res_GETENTRY(resID);
1848
1849    if (p < 0) {
1850        if (Res_GETPACKAGE(resID)+1 == 0) {
1851            LOGW("No package identifier when getting name for resource number 0x%08x", resID);
1852        } else {
1853            LOGW("No known package when getting name for resource number 0x%08x", resID);
1854        }
1855        return false;
1856    }
1857    if (t < 0) {
1858        LOGW("No type identifier when getting name for resource number 0x%08x", resID);
1859        return false;
1860    }
1861
1862    const PackageGroup* const grp = mPackageGroups[p];
1863    if (grp == NULL) {
1864        LOGW("Bad identifier when getting name for resource number 0x%08x", resID);
1865        return false;
1866    }
1867    if (grp->packages.size() > 0) {
1868        const Package* const package = grp->packages[0];
1869
1870        const ResTable_type* type;
1871        const ResTable_entry* entry;
1872        ssize_t offset = getEntry(package, t, e, NULL, &type, &entry, NULL);
1873        if (offset <= 0) {
1874            return false;
1875        }
1876
1877        outName->package = grp->name.string();
1878        outName->packageLen = grp->name.size();
1879        outName->type = grp->basePackage->typeStrings.stringAt(t, &outName->typeLen);
1880        outName->name = grp->basePackage->keyStrings.stringAt(
1881            dtohl(entry->key.index), &outName->nameLen);
1882        return true;
1883    }
1884
1885    return false;
1886}
1887
1888ssize_t ResTable::getResource(uint32_t resID, Res_value* outValue, bool mayBeBag,
1889        uint32_t* outSpecFlags, ResTable_config* outConfig) const
1890{
1891    if (mError != NO_ERROR) {
1892        return mError;
1893    }
1894
1895    const ssize_t p = getResourcePackageIndex(resID);
1896    const int t = Res_GETTYPE(resID);
1897    const int e = Res_GETENTRY(resID);
1898
1899    if (p < 0) {
1900        if (Res_GETPACKAGE(resID)+1 == 0) {
1901            LOGW("No package identifier when getting value for resource number 0x%08x", resID);
1902        } else {
1903            LOGW("No known package when getting value for resource number 0x%08x", resID);
1904        }
1905        return BAD_INDEX;
1906    }
1907    if (t < 0) {
1908        LOGW("No type identifier when getting value for resource number 0x%08x", resID);
1909        return BAD_INDEX;
1910    }
1911
1912    const Res_value* bestValue = NULL;
1913    const Package* bestPackage = NULL;
1914    ResTable_config bestItem;
1915    memset(&bestItem, 0, sizeof(bestItem)); // make the compiler shut up
1916
1917    if (outSpecFlags != NULL) *outSpecFlags = 0;
1918
1919    // Look through all resource packages, starting with the most
1920    // recently added.
1921    const PackageGroup* const grp = mPackageGroups[p];
1922    if (grp == NULL) {
1923        LOGW("Bad identifier when getting value for resource number 0x%08x", resID);
1924        return BAD_INDEX;
1925    }
1926    size_t ip = grp->packages.size();
1927    while (ip > 0) {
1928        ip--;
1929
1930        const Package* const package = grp->packages[ip];
1931
1932        const ResTable_type* type;
1933        const ResTable_entry* entry;
1934        const Type* typeClass;
1935        ssize_t offset = getEntry(package, t, e, &mParams, &type, &entry, &typeClass);
1936        if (offset <= 0) {
1937            if (offset < 0) {
1938                LOGW("Failure getting entry for 0x%08x (t=%d e=%d) in package %d: 0x%08x\n",
1939                        resID, t, e, (int)ip, (int)offset);
1940                return offset;
1941            }
1942            continue;
1943        }
1944
1945        if ((dtohs(entry->flags)&entry->FLAG_COMPLEX) != 0) {
1946            if (!mayBeBag) {
1947                LOGW("Requesting resource %p failed because it is complex\n",
1948                     (void*)resID);
1949            }
1950            continue;
1951        }
1952
1953        TABLE_NOISY(aout << "Resource type data: "
1954              << HexDump(type, dtohl(type->header.size)) << endl);
1955
1956        if ((size_t)offset > (dtohl(type->header.size)-sizeof(Res_value))) {
1957            LOGW("ResTable_item at %d is beyond type chunk data %d",
1958                 (int)offset, dtohl(type->header.size));
1959            return BAD_TYPE;
1960        }
1961
1962        const Res_value* item =
1963            (const Res_value*)(((const uint8_t*)type) + offset);
1964        ResTable_config thisConfig;
1965        thisConfig.copyFromDtoH(type->config);
1966
1967        if (outSpecFlags != NULL) {
1968            if (typeClass->typeSpecFlags != NULL) {
1969                *outSpecFlags |= dtohl(typeClass->typeSpecFlags[e]);
1970            } else {
1971                *outSpecFlags = -1;
1972            }
1973        }
1974
1975        if (bestPackage != NULL && bestItem.isMoreSpecificThan(thisConfig)) {
1976            continue;
1977        }
1978
1979        bestItem = thisConfig;
1980        bestValue = item;
1981        bestPackage = package;
1982    }
1983
1984    TABLE_NOISY(printf("Found result: package %p\n", bestPackage));
1985
1986    if (bestValue) {
1987        outValue->size = dtohs(bestValue->size);
1988        outValue->res0 = bestValue->res0;
1989        outValue->dataType = bestValue->dataType;
1990        outValue->data = dtohl(bestValue->data);
1991        if (outConfig != NULL) {
1992            *outConfig = bestItem;
1993        }
1994        TABLE_NOISY(size_t len;
1995              printf("Found value: pkg=%d, type=%d, str=%s, int=%d\n",
1996                     bestPackage->header->index,
1997                     outValue->dataType,
1998                     outValue->dataType == bestValue->TYPE_STRING
1999                     ? String8(bestPackage->header->values.stringAt(
2000                         outValue->data, &len)).string()
2001                     : "",
2002                     outValue->data));
2003        return bestPackage->header->index;
2004    }
2005
2006    return BAD_VALUE;
2007}
2008
2009ssize_t ResTable::resolveReference(Res_value* value, ssize_t blockIndex,
2010        uint32_t* outLastRef, uint32_t* inoutTypeSpecFlags,
2011        ResTable_config* outConfig) const
2012{
2013    int count=0;
2014    while (blockIndex >= 0 && value->dataType == value->TYPE_REFERENCE
2015           && value->data != 0 && count < 20) {
2016        if (outLastRef) *outLastRef = value->data;
2017        uint32_t lastRef = value->data;
2018        uint32_t newFlags = 0;
2019        const ssize_t newIndex = getResource(value->data, value, true, &newFlags,
2020                outConfig);
2021        if (newIndex == BAD_INDEX) {
2022            return BAD_INDEX;
2023        }
2024        TABLE_THEME(LOGI("Resolving reference %p: newIndex=%d, type=0x%x, data=%p\n",
2025             (void*)lastRef, (int)newIndex, (int)value->dataType, (void*)value->data));
2026        //printf("Getting reference 0x%08x: newIndex=%d\n", value->data, newIndex);
2027        if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newFlags;
2028        if (newIndex < 0) {
2029            // This can fail if the resource being referenced is a style...
2030            // in this case, just return the reference, and expect the
2031            // caller to deal with.
2032            return blockIndex;
2033        }
2034        blockIndex = newIndex;
2035        count++;
2036    }
2037    return blockIndex;
2038}
2039
2040const char16_t* ResTable::valueToString(
2041    const Res_value* value, size_t stringBlock,
2042    char16_t tmpBuffer[TMP_BUFFER_SIZE], size_t* outLen)
2043{
2044    if (!value) {
2045        return NULL;
2046    }
2047    if (value->dataType == value->TYPE_STRING) {
2048        return getTableStringBlock(stringBlock)->stringAt(value->data, outLen);
2049    }
2050    // XXX do int to string conversions.
2051    return NULL;
2052}
2053
2054ssize_t ResTable::lockBag(uint32_t resID, const bag_entry** outBag) const
2055{
2056    mLock.lock();
2057    ssize_t err = getBagLocked(resID, outBag);
2058    if (err < NO_ERROR) {
2059        //printf("*** get failed!  unlocking\n");
2060        mLock.unlock();
2061    }
2062    return err;
2063}
2064
2065void ResTable::unlockBag(const bag_entry* bag) const
2066{
2067    //printf("<<< unlockBag %p\n", this);
2068    mLock.unlock();
2069}
2070
2071void ResTable::lock() const
2072{
2073    mLock.lock();
2074}
2075
2076void ResTable::unlock() const
2077{
2078    mLock.unlock();
2079}
2080
2081ssize_t ResTable::getBagLocked(uint32_t resID, const bag_entry** outBag,
2082        uint32_t* outTypeSpecFlags) const
2083{
2084    if (mError != NO_ERROR) {
2085        return mError;
2086    }
2087
2088    const ssize_t p = getResourcePackageIndex(resID);
2089    const int t = Res_GETTYPE(resID);
2090    const int e = Res_GETENTRY(resID);
2091
2092    if (p < 0) {
2093        LOGW("Invalid package identifier when getting bag for resource number 0x%08x", resID);
2094        return BAD_INDEX;
2095    }
2096    if (t < 0) {
2097        LOGW("No type identifier when getting bag for resource number 0x%08x", resID);
2098        return BAD_INDEX;
2099    }
2100
2101    //printf("Get bag: id=0x%08x, p=%d, t=%d\n", resID, p, t);
2102    PackageGroup* const grp = mPackageGroups[p];
2103    if (grp == NULL) {
2104        LOGW("Bad identifier when getting bag for resource number 0x%08x", resID);
2105        return false;
2106    }
2107
2108    if (t >= (int)grp->typeCount) {
2109        LOGW("Type identifier 0x%x is larger than type count 0x%x",
2110             t+1, (int)grp->typeCount);
2111        return BAD_INDEX;
2112    }
2113
2114    const Package* const basePackage = grp->packages[0];
2115
2116    const Type* const typeConfigs = basePackage->getType(t);
2117
2118    const size_t NENTRY = typeConfigs->entryCount;
2119    if (e >= (int)NENTRY) {
2120        LOGW("Entry identifier 0x%x is larger than entry count 0x%x",
2121             e, (int)typeConfigs->entryCount);
2122        return BAD_INDEX;
2123    }
2124
2125    // First see if we've already computed this bag...
2126    if (grp->bags) {
2127        bag_set** typeSet = grp->bags[t];
2128        if (typeSet) {
2129            bag_set* set = typeSet[e];
2130            if (set) {
2131                if (set != (bag_set*)0xFFFFFFFF) {
2132                    if (outTypeSpecFlags != NULL) {
2133                        *outTypeSpecFlags = set->typeSpecFlags;
2134                    }
2135                    *outBag = (bag_entry*)(set+1);
2136                    //LOGI("Found existing bag for: %p\n", (void*)resID);
2137                    return set->numAttrs;
2138                }
2139                LOGW("Attempt to retrieve bag 0x%08x which is invalid or in a cycle.",
2140                     resID);
2141                return BAD_INDEX;
2142            }
2143        }
2144    }
2145
2146    // Bag not found, we need to compute it!
2147    if (!grp->bags) {
2148        grp->bags = (bag_set***)malloc(sizeof(bag_set*)*grp->typeCount);
2149        if (!grp->bags) return NO_MEMORY;
2150        memset(grp->bags, 0, sizeof(bag_set*)*grp->typeCount);
2151    }
2152
2153    bag_set** typeSet = grp->bags[t];
2154    if (!typeSet) {
2155        typeSet = (bag_set**)malloc(sizeof(bag_set*)*NENTRY);
2156        if (!typeSet) return NO_MEMORY;
2157        memset(typeSet, 0, sizeof(bag_set*)*NENTRY);
2158        grp->bags[t] = typeSet;
2159    }
2160
2161    // Mark that we are currently working on this one.
2162    typeSet[e] = (bag_set*)0xFFFFFFFF;
2163
2164    // This is what we are building.
2165    bag_set* set = NULL;
2166
2167    TABLE_NOISY(LOGI("Building bag: %p\n", (void*)resID));
2168
2169    // Now collect all bag attributes from all packages.
2170    size_t ip = grp->packages.size();
2171    while (ip > 0) {
2172        ip--;
2173
2174        const Package* const package = grp->packages[ip];
2175
2176        const ResTable_type* type;
2177        const ResTable_entry* entry;
2178        const Type* typeClass;
2179        LOGV("Getting entry pkg=%p, t=%d, e=%d\n", package, t, e);
2180        ssize_t offset = getEntry(package, t, e, &mParams, &type, &entry, &typeClass);
2181        LOGV("Resulting offset=%d\n", offset);
2182        if (offset <= 0) {
2183            if (offset < 0) {
2184                if (set) free(set);
2185                return offset;
2186            }
2187            continue;
2188        }
2189
2190        if ((dtohs(entry->flags)&entry->FLAG_COMPLEX) == 0) {
2191            LOGW("Skipping entry %p in package table %d because it is not complex!\n",
2192                 (void*)resID, (int)ip);
2193            continue;
2194        }
2195
2196        const uint16_t entrySize = dtohs(entry->size);
2197        const uint32_t parent = entrySize >= sizeof(ResTable_map_entry)
2198            ? dtohl(((const ResTable_map_entry*)entry)->parent.ident) : 0;
2199        const uint32_t count = entrySize >= sizeof(ResTable_map_entry)
2200            ? dtohl(((const ResTable_map_entry*)entry)->count) : 0;
2201
2202        size_t N = count;
2203
2204        TABLE_NOISY(LOGI("Found map: size=%p parent=%p count=%d\n",
2205                         entrySize, parent, count));
2206
2207        if (set == NULL) {
2208            // If this map inherits from another, we need to start
2209            // with its parent's values.  Otherwise start out empty.
2210            TABLE_NOISY(printf("Creating new bag, entrySize=0x%08x, parent=0x%08x\n",
2211                         entrySize, parent));
2212            if (parent) {
2213                const bag_entry* parentBag;
2214                uint32_t parentTypeSpecFlags = 0;
2215                const ssize_t NP = getBagLocked(parent, &parentBag, &parentTypeSpecFlags);
2216                const size_t NT = ((NP >= 0) ? NP : 0) + N;
2217                set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*NT);
2218                if (set == NULL) {
2219                    return NO_MEMORY;
2220                }
2221                if (NP > 0) {
2222                    memcpy(set+1, parentBag, NP*sizeof(bag_entry));
2223                    set->numAttrs = NP;
2224                    TABLE_NOISY(LOGI("Initialized new bag with %d inherited attributes.\n", NP));
2225                } else {
2226                    TABLE_NOISY(LOGI("Initialized new bag with no inherited attributes.\n"));
2227                    set->numAttrs = 0;
2228                }
2229                set->availAttrs = NT;
2230                set->typeSpecFlags = parentTypeSpecFlags;
2231            } else {
2232                set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*N);
2233                if (set == NULL) {
2234                    return NO_MEMORY;
2235                }
2236                set->numAttrs = 0;
2237                set->availAttrs = N;
2238                set->typeSpecFlags = 0;
2239            }
2240        }
2241
2242        if (typeClass->typeSpecFlags != NULL) {
2243            set->typeSpecFlags |= dtohl(typeClass->typeSpecFlags[e]);
2244        } else {
2245            set->typeSpecFlags = -1;
2246        }
2247
2248        // Now merge in the new attributes...
2249        ssize_t curOff = offset;
2250        const ResTable_map* map;
2251        bag_entry* entries = (bag_entry*)(set+1);
2252        size_t curEntry = 0;
2253        uint32_t pos = 0;
2254        TABLE_NOISY(LOGI("Starting with set %p, entries=%p, avail=%d\n",
2255                     set, entries, set->availAttrs));
2256        while (pos < count) {
2257            TABLE_NOISY(printf("Now at %p\n", (void*)curOff));
2258
2259            if ((size_t)curOff > (dtohl(type->header.size)-sizeof(ResTable_map))) {
2260                LOGW("ResTable_map at %d is beyond type chunk data %d",
2261                     (int)curOff, dtohl(type->header.size));
2262                return BAD_TYPE;
2263            }
2264            map = (const ResTable_map*)(((const uint8_t*)type) + curOff);
2265            N++;
2266
2267            const uint32_t newName = htodl(map->name.ident);
2268            bool isInside;
2269            uint32_t oldName = 0;
2270            while ((isInside=(curEntry < set->numAttrs))
2271                    && (oldName=entries[curEntry].map.name.ident) < newName) {
2272                TABLE_NOISY(printf("#%d: Keeping existing attribute: 0x%08x\n",
2273                             curEntry, entries[curEntry].map.name.ident));
2274                curEntry++;
2275            }
2276
2277            if ((!isInside) || oldName != newName) {
2278                // This is a new attribute...  figure out what to do with it.
2279                if (set->numAttrs >= set->availAttrs) {
2280                    // Need to alloc more memory...
2281                    const size_t newAvail = set->availAttrs+N;
2282                    set = (bag_set*)realloc(set,
2283                                            sizeof(bag_set)
2284                                            + sizeof(bag_entry)*newAvail);
2285                    if (set == NULL) {
2286                        return NO_MEMORY;
2287                    }
2288                    set->availAttrs = newAvail;
2289                    entries = (bag_entry*)(set+1);
2290                    TABLE_NOISY(printf("Reallocated set %p, entries=%p, avail=%d\n",
2291                                 set, entries, set->availAttrs));
2292                }
2293                if (isInside) {
2294                    // Going in the middle, need to make space.
2295                    memmove(entries+curEntry+1, entries+curEntry,
2296                            sizeof(bag_entry)*(set->numAttrs-curEntry));
2297                    set->numAttrs++;
2298                }
2299                TABLE_NOISY(printf("#%d: Inserting new attribute: 0x%08x\n",
2300                             curEntry, newName));
2301            } else {
2302                TABLE_NOISY(printf("#%d: Replacing existing attribute: 0x%08x\n",
2303                             curEntry, oldName));
2304            }
2305
2306            bag_entry* cur = entries+curEntry;
2307
2308            cur->stringBlock = package->header->index;
2309            cur->map.name.ident = newName;
2310            cur->map.value.copyFrom_dtoh(map->value);
2311            TABLE_NOISY(printf("Setting entry #%d %p: block=%d, name=0x%08x, type=%d, data=0x%08x\n",
2312                         curEntry, cur, cur->stringBlock, cur->map.name.ident,
2313                         cur->map.value.dataType, cur->map.value.data));
2314
2315            // On to the next!
2316            curEntry++;
2317            pos++;
2318            const size_t size = dtohs(map->value.size);
2319            curOff += size + sizeof(*map)-sizeof(map->value);
2320        };
2321        if (curEntry > set->numAttrs) {
2322            set->numAttrs = curEntry;
2323        }
2324    }
2325
2326    // And this is it...
2327    typeSet[e] = set;
2328    if (set) {
2329        if (outTypeSpecFlags != NULL) {
2330            *outTypeSpecFlags = set->typeSpecFlags;
2331        }
2332        *outBag = (bag_entry*)(set+1);
2333        TABLE_NOISY(LOGI("Returning %d attrs\n", set->numAttrs));
2334        return set->numAttrs;
2335    }
2336    return BAD_INDEX;
2337}
2338
2339void ResTable::setParameters(const ResTable_config* params)
2340{
2341    mLock.lock();
2342    TABLE_GETENTRY(LOGI("Setting parameters: imsi:%d/%d lang:%c%c cnt:%c%c "
2343                        "orien:%d touch:%d density:%d key:%d inp:%d nav:%d w:%d h:%d\n",
2344                       params->mcc, params->mnc,
2345                       params->language[0] ? params->language[0] : '-',
2346                       params->language[1] ? params->language[1] : '-',
2347                       params->country[0] ? params->country[0] : '-',
2348                       params->country[1] ? params->country[1] : '-',
2349                       params->orientation,
2350                       params->touchscreen,
2351                       params->density,
2352                       params->keyboard,
2353                       params->inputFlags,
2354                       params->navigation,
2355                       params->screenWidth,
2356                       params->screenHeight));
2357    mParams = *params;
2358    for (size_t i=0; i<mPackageGroups.size(); i++) {
2359        TABLE_NOISY(LOGI("CLEARING BAGS FOR GROUP %d!", i));
2360        mPackageGroups[i]->clearBagCache();
2361    }
2362    mLock.unlock();
2363}
2364
2365void ResTable::getParameters(ResTable_config* params) const
2366{
2367    mLock.lock();
2368    *params = mParams;
2369    mLock.unlock();
2370}
2371
2372struct id_name_map {
2373    uint32_t id;
2374    size_t len;
2375    char16_t name[6];
2376};
2377
2378const static id_name_map ID_NAMES[] = {
2379    { ResTable_map::ATTR_TYPE,  5, { '^', 't', 'y', 'p', 'e' } },
2380    { ResTable_map::ATTR_L10N,  5, { '^', 'l', '1', '0', 'n' } },
2381    { ResTable_map::ATTR_MIN,   4, { '^', 'm', 'i', 'n' } },
2382    { ResTable_map::ATTR_MAX,   4, { '^', 'm', 'a', 'x' } },
2383    { ResTable_map::ATTR_OTHER, 6, { '^', 'o', 't', 'h', 'e', 'r' } },
2384    { ResTable_map::ATTR_ZERO,  5, { '^', 'z', 'e', 'r', 'o' } },
2385    { ResTable_map::ATTR_ONE,   4, { '^', 'o', 'n', 'e' } },
2386    { ResTable_map::ATTR_TWO,   4, { '^', 't', 'w', 'o' } },
2387    { ResTable_map::ATTR_FEW,   4, { '^', 'f', 'e', 'w' } },
2388    { ResTable_map::ATTR_MANY,  5, { '^', 'm', 'a', 'n', 'y' } },
2389};
2390
2391uint32_t ResTable::identifierForName(const char16_t* name, size_t nameLen,
2392                                     const char16_t* type, size_t typeLen,
2393                                     const char16_t* package,
2394                                     size_t packageLen,
2395                                     uint32_t* outTypeSpecFlags) const
2396{
2397    TABLE_SUPER_NOISY(printf("Identifier for name: error=%d\n", mError));
2398
2399    // Check for internal resource identifier as the very first thing, so
2400    // that we will always find them even when there are no resources.
2401    if (name[0] == '^') {
2402        const int N = (sizeof(ID_NAMES)/sizeof(ID_NAMES[0]));
2403        size_t len;
2404        for (int i=0; i<N; i++) {
2405            const id_name_map* m = ID_NAMES + i;
2406            len = m->len;
2407            if (len != nameLen) {
2408                continue;
2409            }
2410            for (size_t j=1; j<len; j++) {
2411                if (m->name[j] != name[j]) {
2412                    goto nope;
2413                }
2414            }
2415            return m->id;
2416nope:
2417            ;
2418        }
2419        if (nameLen > 7) {
2420            if (name[1] == 'i' && name[2] == 'n'
2421                && name[3] == 'd' && name[4] == 'e' && name[5] == 'x'
2422                && name[6] == '_') {
2423                int index = atoi(String8(name + 7, nameLen - 7).string());
2424                if (Res_CHECKID(index)) {
2425                    LOGW("Array resource index: %d is too large.",
2426                         index);
2427                    return 0;
2428                }
2429                return  Res_MAKEARRAY(index);
2430            }
2431        }
2432        return 0;
2433    }
2434
2435    if (mError != NO_ERROR) {
2436        return 0;
2437    }
2438
2439    // Figure out the package and type we are looking in...
2440
2441    const char16_t* packageEnd = NULL;
2442    const char16_t* typeEnd = NULL;
2443    const char16_t* const nameEnd = name+nameLen;
2444    const char16_t* p = name;
2445    while (p < nameEnd) {
2446        if (*p == ':') packageEnd = p;
2447        else if (*p == '/') typeEnd = p;
2448        p++;
2449    }
2450    if (*name == '@') name++;
2451    if (name >= nameEnd) {
2452        return 0;
2453    }
2454
2455    if (packageEnd) {
2456        package = name;
2457        packageLen = packageEnd-name;
2458        name = packageEnd+1;
2459    } else if (!package) {
2460        return 0;
2461    }
2462
2463    if (typeEnd) {
2464        type = name;
2465        typeLen = typeEnd-name;
2466        name = typeEnd+1;
2467    } else if (!type) {
2468        return 0;
2469    }
2470
2471    if (name >= nameEnd) {
2472        return 0;
2473    }
2474    nameLen = nameEnd-name;
2475
2476    TABLE_NOISY(printf("Looking for identifier: type=%s, name=%s, package=%s\n",
2477                 String8(type, typeLen).string(),
2478                 String8(name, nameLen).string(),
2479                 String8(package, packageLen).string()));
2480
2481    const size_t NG = mPackageGroups.size();
2482    for (size_t ig=0; ig<NG; ig++) {
2483        const PackageGroup* group = mPackageGroups[ig];
2484
2485        if (strzcmp16(package, packageLen,
2486                      group->name.string(), group->name.size())) {
2487            TABLE_NOISY(printf("Skipping package group: %s\n", String8(group->name).string()));
2488            continue;
2489        }
2490
2491        const ssize_t ti = group->basePackage->typeStrings.indexOfString(type, typeLen);
2492        if (ti < 0) {
2493            TABLE_NOISY(printf("Type not found in package %s\n", String8(group->name).string()));
2494            continue;
2495        }
2496
2497        const ssize_t ei = group->basePackage->keyStrings.indexOfString(name, nameLen);
2498        if (ei < 0) {
2499            TABLE_NOISY(printf("Name not found in package %s\n", String8(group->name).string()));
2500            continue;
2501        }
2502
2503        TABLE_NOISY(printf("Search indices: type=%d, name=%d\n", ti, ei));
2504
2505        const Type* const typeConfigs = group->packages[0]->getType(ti);
2506        if (typeConfigs == NULL || typeConfigs->configs.size() <= 0) {
2507            TABLE_NOISY(printf("Expected type structure not found in package %s for idnex %d\n",
2508                               String8(group->name).string(), ti));
2509        }
2510
2511        size_t NTC = typeConfigs->configs.size();
2512        for (size_t tci=0; tci<NTC; tci++) {
2513            const ResTable_type* const ty = typeConfigs->configs[tci];
2514            const uint32_t typeOffset = dtohl(ty->entriesStart);
2515
2516            const uint8_t* const end = ((const uint8_t*)ty) + dtohl(ty->header.size);
2517            const uint32_t* const eindex = (const uint32_t*)
2518                (((const uint8_t*)ty) + dtohs(ty->header.headerSize));
2519
2520            const size_t NE = dtohl(ty->entryCount);
2521            for (size_t i=0; i<NE; i++) {
2522                uint32_t offset = dtohl(eindex[i]);
2523                if (offset == ResTable_type::NO_ENTRY) {
2524                    continue;
2525                }
2526
2527                offset += typeOffset;
2528
2529                if (offset > (dtohl(ty->header.size)-sizeof(ResTable_entry))) {
2530                    LOGW("ResTable_entry at %d is beyond type chunk data %d",
2531                         offset, dtohl(ty->header.size));
2532                    return 0;
2533                }
2534                if ((offset&0x3) != 0) {
2535                    LOGW("ResTable_entry at %d (pkg=%d type=%d ent=%d) is not on an integer boundary when looking for %s:%s/%s",
2536                         (int)offset, (int)group->id, (int)ti+1, (int)i,
2537                         String8(package, packageLen).string(),
2538                         String8(type, typeLen).string(),
2539                         String8(name, nameLen).string());
2540                    return 0;
2541                }
2542
2543                const ResTable_entry* const entry = (const ResTable_entry*)
2544                    (((const uint8_t*)ty) + offset);
2545                if (dtohs(entry->size) < sizeof(*entry)) {
2546                    LOGW("ResTable_entry size %d is too small", dtohs(entry->size));
2547                    return BAD_TYPE;
2548                }
2549
2550                TABLE_SUPER_NOISY(printf("Looking at entry #%d: want str %d, have %d\n",
2551                                         i, ei, dtohl(entry->key.index)));
2552                if (dtohl(entry->key.index) == (size_t)ei) {
2553                    if (outTypeSpecFlags) {
2554                        *outTypeSpecFlags = typeConfigs->typeSpecFlags[i];
2555                    }
2556                    return Res_MAKEID(group->id-1, ti, i);
2557                }
2558            }
2559        }
2560    }
2561
2562    return 0;
2563}
2564
2565bool ResTable::expandResourceRef(const uint16_t* refStr, size_t refLen,
2566                                 String16* outPackage,
2567                                 String16* outType,
2568                                 String16* outName,
2569                                 const String16* defType,
2570                                 const String16* defPackage,
2571                                 const char** outErrorMsg)
2572{
2573    const char16_t* packageEnd = NULL;
2574    const char16_t* typeEnd = NULL;
2575    const char16_t* p = refStr;
2576    const char16_t* const end = p + refLen;
2577    while (p < end) {
2578        if (*p == ':') packageEnd = p;
2579        else if (*p == '/') {
2580            typeEnd = p;
2581            break;
2582        }
2583        p++;
2584    }
2585    p = refStr;
2586    if (*p == '@') p++;
2587
2588    if (packageEnd) {
2589        *outPackage = String16(p, packageEnd-p);
2590        p = packageEnd+1;
2591    } else {
2592        if (!defPackage) {
2593            if (outErrorMsg) {
2594                *outErrorMsg = "No resource package specified";
2595            }
2596            return false;
2597        }
2598        *outPackage = *defPackage;
2599    }
2600    if (typeEnd) {
2601        *outType = String16(p, typeEnd-p);
2602        p = typeEnd+1;
2603    } else {
2604        if (!defType) {
2605            if (outErrorMsg) {
2606                *outErrorMsg = "No resource type specified";
2607            }
2608            return false;
2609        }
2610        *outType = *defType;
2611    }
2612    *outName = String16(p, end-p);
2613    return true;
2614}
2615
2616static uint32_t get_hex(char c, bool* outError)
2617{
2618    if (c >= '0' && c <= '9') {
2619        return c - '0';
2620    } else if (c >= 'a' && c <= 'f') {
2621        return c - 'a' + 0xa;
2622    } else if (c >= 'A' && c <= 'F') {
2623        return c - 'A' + 0xa;
2624    }
2625    *outError = true;
2626    return 0;
2627}
2628
2629struct unit_entry
2630{
2631    const char* name;
2632    size_t len;
2633    uint8_t type;
2634    uint32_t unit;
2635    float scale;
2636};
2637
2638static const unit_entry unitNames[] = {
2639    { "px", strlen("px"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PX, 1.0f },
2640    { "dip", strlen("dip"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
2641    { "dp", strlen("dp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
2642    { "sp", strlen("sp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_SP, 1.0f },
2643    { "pt", strlen("pt"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PT, 1.0f },
2644    { "in", strlen("in"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_IN, 1.0f },
2645    { "mm", strlen("mm"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_MM, 1.0f },
2646    { "%", strlen("%"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION, 1.0f/100 },
2647    { "%p", strlen("%p"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION_PARENT, 1.0f/100 },
2648    { NULL, 0, 0, 0, 0 }
2649};
2650
2651static bool parse_unit(const char* str, Res_value* outValue,
2652                       float* outScale, const char** outEnd)
2653{
2654    const char* end = str;
2655    while (*end != 0 && !isspace((unsigned char)*end)) {
2656        end++;
2657    }
2658    const size_t len = end-str;
2659
2660    const char* realEnd = end;
2661    while (*realEnd != 0 && isspace((unsigned char)*realEnd)) {
2662        realEnd++;
2663    }
2664    if (*realEnd != 0) {
2665        return false;
2666    }
2667
2668    const unit_entry* cur = unitNames;
2669    while (cur->name) {
2670        if (len == cur->len && strncmp(cur->name, str, len) == 0) {
2671            outValue->dataType = cur->type;
2672            outValue->data = cur->unit << Res_value::COMPLEX_UNIT_SHIFT;
2673            *outScale = cur->scale;
2674            *outEnd = end;
2675            //printf("Found unit %s for %s\n", cur->name, str);
2676            return true;
2677        }
2678        cur++;
2679    }
2680
2681    return false;
2682}
2683
2684
2685bool ResTable::stringToInt(const char16_t* s, size_t len, Res_value* outValue)
2686{
2687    while (len > 0 && isspace16(*s)) {
2688        s++;
2689        len--;
2690    }
2691
2692    if (len <= 0) {
2693        return false;
2694    }
2695
2696    size_t i = 0;
2697    int32_t val = 0;
2698    bool neg = false;
2699
2700    if (*s == '-') {
2701        neg = true;
2702        i++;
2703    }
2704
2705    if (s[i] < '0' || s[i] > '9') {
2706        return false;
2707    }
2708
2709    // Decimal or hex?
2710    if (s[i] == '0' && s[i+1] == 'x') {
2711        if (outValue)
2712            outValue->dataType = outValue->TYPE_INT_HEX;
2713        i += 2;
2714        bool error = false;
2715        while (i < len && !error) {
2716            val = (val*16) + get_hex(s[i], &error);
2717            i++;
2718        }
2719        if (error) {
2720            return false;
2721        }
2722    } else {
2723        if (outValue)
2724            outValue->dataType = outValue->TYPE_INT_DEC;
2725        while (i < len) {
2726            if (s[i] < '0' || s[i] > '9') {
2727                return false;
2728            }
2729            val = (val*10) + s[i]-'0';
2730            i++;
2731        }
2732    }
2733
2734    if (neg) val = -val;
2735
2736    while (i < len && isspace16(s[i])) {
2737        i++;
2738    }
2739
2740    if (i == len) {
2741        if (outValue)
2742            outValue->data = val;
2743        return true;
2744    }
2745
2746    return false;
2747}
2748
2749bool ResTable::stringToFloat(const char16_t* s, size_t len, Res_value* outValue)
2750{
2751    while (len > 0 && isspace16(*s)) {
2752        s++;
2753        len--;
2754    }
2755
2756    if (len <= 0) {
2757        return false;
2758    }
2759
2760    char buf[128];
2761    int i=0;
2762    while (len > 0 && *s != 0 && i < 126) {
2763        if (*s > 255) {
2764            return false;
2765        }
2766        buf[i++] = *s++;
2767        len--;
2768    }
2769
2770    if (len > 0) {
2771        return false;
2772    }
2773    if (buf[0] < '0' && buf[0] > '9' && buf[0] != '.') {
2774        return false;
2775    }
2776
2777    buf[i] = 0;
2778    const char* end;
2779    float f = strtof(buf, (char**)&end);
2780
2781    if (*end != 0 && !isspace((unsigned char)*end)) {
2782        // Might be a unit...
2783        float scale;
2784        if (parse_unit(end, outValue, &scale, &end)) {
2785            f *= scale;
2786            const bool neg = f < 0;
2787            if (neg) f = -f;
2788            uint64_t bits = (uint64_t)(f*(1<<23)+.5f);
2789            uint32_t radix;
2790            uint32_t shift;
2791            if ((bits&0x7fffff) == 0) {
2792                // Always use 23p0 if there is no fraction, just to make
2793                // things easier to read.
2794                radix = Res_value::COMPLEX_RADIX_23p0;
2795                shift = 23;
2796            } else if ((bits&0xffffffffff800000LL) == 0) {
2797                // Magnitude is zero -- can fit in 0 bits of precision.
2798                radix = Res_value::COMPLEX_RADIX_0p23;
2799                shift = 0;
2800            } else if ((bits&0xffffffff80000000LL) == 0) {
2801                // Magnitude can fit in 8 bits of precision.
2802                radix = Res_value::COMPLEX_RADIX_8p15;
2803                shift = 8;
2804            } else if ((bits&0xffffff8000000000LL) == 0) {
2805                // Magnitude can fit in 16 bits of precision.
2806                radix = Res_value::COMPLEX_RADIX_16p7;
2807                shift = 16;
2808            } else {
2809                // Magnitude needs entire range, so no fractional part.
2810                radix = Res_value::COMPLEX_RADIX_23p0;
2811                shift = 23;
2812            }
2813            int32_t mantissa = (int32_t)(
2814                (bits>>shift) & Res_value::COMPLEX_MANTISSA_MASK);
2815            if (neg) {
2816                mantissa = (-mantissa) & Res_value::COMPLEX_MANTISSA_MASK;
2817            }
2818            outValue->data |=
2819                (radix<<Res_value::COMPLEX_RADIX_SHIFT)
2820                | (mantissa<<Res_value::COMPLEX_MANTISSA_SHIFT);
2821            //printf("Input value: %f 0x%016Lx, mult: %f, radix: %d, shift: %d, final: 0x%08x\n",
2822            //       f * (neg ? -1 : 1), bits, f*(1<<23),
2823            //       radix, shift, outValue->data);
2824            return true;
2825        }
2826        return false;
2827    }
2828
2829    while (*end != 0 && isspace((unsigned char)*end)) {
2830        end++;
2831    }
2832
2833    if (*end == 0) {
2834        if (outValue) {
2835            outValue->dataType = outValue->TYPE_FLOAT;
2836            *(float*)(&outValue->data) = f;
2837            return true;
2838        }
2839    }
2840
2841    return false;
2842}
2843
2844bool ResTable::stringToValue(Res_value* outValue, String16* outString,
2845                             const char16_t* s, size_t len,
2846                             bool preserveSpaces, bool coerceType,
2847                             uint32_t attrID,
2848                             const String16* defType,
2849                             const String16* defPackage,
2850                             Accessor* accessor,
2851                             void* accessorCookie,
2852                             uint32_t attrType,
2853                             bool enforcePrivate) const
2854{
2855    bool localizationSetting = accessor != NULL && accessor->getLocalizationSetting();
2856    const char* errorMsg = NULL;
2857
2858    outValue->size = sizeof(Res_value);
2859    outValue->res0 = 0;
2860
2861    // First strip leading/trailing whitespace.  Do this before handling
2862    // escapes, so they can be used to force whitespace into the string.
2863    if (!preserveSpaces) {
2864        while (len > 0 && isspace16(*s)) {
2865            s++;
2866            len--;
2867        }
2868        while (len > 0 && isspace16(s[len-1])) {
2869            len--;
2870        }
2871        // If the string ends with '\', then we keep the space after it.
2872        if (len > 0 && s[len-1] == '\\' && s[len] != 0) {
2873            len++;
2874        }
2875    }
2876
2877    //printf("Value for: %s\n", String8(s, len).string());
2878
2879    uint32_t l10nReq = ResTable_map::L10N_NOT_REQUIRED;
2880    uint32_t attrMin = 0x80000000, attrMax = 0x7fffffff;
2881    bool fromAccessor = false;
2882    if (attrID != 0 && !Res_INTERNALID(attrID)) {
2883        const ssize_t p = getResourcePackageIndex(attrID);
2884        const bag_entry* bag;
2885        ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
2886        //printf("For attr 0x%08x got bag of %d\n", attrID, cnt);
2887        if (cnt >= 0) {
2888            while (cnt > 0) {
2889                //printf("Entry 0x%08x = 0x%08x\n", bag->map.name.ident, bag->map.value.data);
2890                switch (bag->map.name.ident) {
2891                case ResTable_map::ATTR_TYPE:
2892                    attrType = bag->map.value.data;
2893                    break;
2894                case ResTable_map::ATTR_MIN:
2895                    attrMin = bag->map.value.data;
2896                    break;
2897                case ResTable_map::ATTR_MAX:
2898                    attrMax = bag->map.value.data;
2899                    break;
2900                case ResTable_map::ATTR_L10N:
2901                    l10nReq = bag->map.value.data;
2902                    break;
2903                }
2904                bag++;
2905                cnt--;
2906            }
2907            unlockBag(bag);
2908        } else if (accessor && accessor->getAttributeType(attrID, &attrType)) {
2909            fromAccessor = true;
2910            if (attrType == ResTable_map::TYPE_ENUM
2911                    || attrType == ResTable_map::TYPE_FLAGS
2912                    || attrType == ResTable_map::TYPE_INTEGER) {
2913                accessor->getAttributeMin(attrID, &attrMin);
2914                accessor->getAttributeMax(attrID, &attrMax);
2915            }
2916            if (localizationSetting) {
2917                l10nReq = accessor->getAttributeL10N(attrID);
2918            }
2919        }
2920    }
2921
2922    const bool canStringCoerce =
2923        coerceType && (attrType&ResTable_map::TYPE_STRING) != 0;
2924
2925    if (*s == '@') {
2926        outValue->dataType = outValue->TYPE_REFERENCE;
2927
2928        // Note: we don't check attrType here because the reference can
2929        // be to any other type; we just need to count on the client making
2930        // sure the referenced type is correct.
2931
2932        //printf("Looking up ref: %s\n", String8(s, len).string());
2933
2934        // It's a reference!
2935        if (len == 5 && s[1]=='n' && s[2]=='u' && s[3]=='l' && s[4]=='l') {
2936            outValue->data = 0;
2937            return true;
2938        } else {
2939            bool createIfNotFound = false;
2940            const char16_t* resourceRefName;
2941            int resourceNameLen;
2942            if (len > 2 && s[1] == '+') {
2943                createIfNotFound = true;
2944                resourceRefName = s + 2;
2945                resourceNameLen = len - 2;
2946            } else if (len > 2 && s[1] == '*') {
2947                enforcePrivate = false;
2948                resourceRefName = s + 2;
2949                resourceNameLen = len - 2;
2950            } else {
2951                createIfNotFound = false;
2952                resourceRefName = s + 1;
2953                resourceNameLen = len - 1;
2954            }
2955            String16 package, type, name;
2956            if (!expandResourceRef(resourceRefName,resourceNameLen, &package, &type, &name,
2957                                   defType, defPackage, &errorMsg)) {
2958                if (accessor != NULL) {
2959                    accessor->reportError(accessorCookie, errorMsg);
2960                }
2961                return false;
2962            }
2963
2964            uint32_t specFlags = 0;
2965            uint32_t rid = identifierForName(name.string(), name.size(), type.string(),
2966                    type.size(), package.string(), package.size(), &specFlags);
2967            if (rid != 0) {
2968                if (enforcePrivate) {
2969                    if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
2970                        if (accessor != NULL) {
2971                            accessor->reportError(accessorCookie, "Resource is not public.");
2972                        }
2973                        return false;
2974                    }
2975                }
2976                if (!accessor) {
2977                    outValue->data = rid;
2978                    return true;
2979                }
2980                rid = Res_MAKEID(
2981                    accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
2982                    Res_GETTYPE(rid), Res_GETENTRY(rid));
2983                TABLE_NOISY(printf("Incl %s:%s/%s: 0x%08x\n",
2984                       String8(package).string(), String8(type).string(),
2985                       String8(name).string(), rid));
2986                outValue->data = rid;
2987                return true;
2988            }
2989
2990            if (accessor) {
2991                uint32_t rid = accessor->getCustomResourceWithCreation(package, type, name,
2992                                                                       createIfNotFound);
2993                if (rid != 0) {
2994                    TABLE_NOISY(printf("Pckg %s:%s/%s: 0x%08x\n",
2995                           String8(package).string(), String8(type).string(),
2996                           String8(name).string(), rid));
2997                    outValue->data = rid;
2998                    return true;
2999                }
3000            }
3001        }
3002
3003        if (accessor != NULL) {
3004            accessor->reportError(accessorCookie, "No resource found that matches the given name");
3005        }
3006        return false;
3007    }
3008
3009    // if we got to here, and localization is required and it's not a reference,
3010    // complain and bail.
3011    if (l10nReq == ResTable_map::L10N_SUGGESTED) {
3012        if (localizationSetting) {
3013            if (accessor != NULL) {
3014                accessor->reportError(accessorCookie, "This attribute must be localized.");
3015            }
3016        }
3017    }
3018
3019    if (*s == '#') {
3020        // It's a color!  Convert to an integer of the form 0xaarrggbb.
3021        uint32_t color = 0;
3022        bool error = false;
3023        if (len == 4) {
3024            outValue->dataType = outValue->TYPE_INT_COLOR_RGB4;
3025            color |= 0xFF000000;
3026            color |= get_hex(s[1], &error) << 20;
3027            color |= get_hex(s[1], &error) << 16;
3028            color |= get_hex(s[2], &error) << 12;
3029            color |= get_hex(s[2], &error) << 8;
3030            color |= get_hex(s[3], &error) << 4;
3031            color |= get_hex(s[3], &error);
3032        } else if (len == 5) {
3033            outValue->dataType = outValue->TYPE_INT_COLOR_ARGB4;
3034            color |= get_hex(s[1], &error) << 28;
3035            color |= get_hex(s[1], &error) << 24;
3036            color |= get_hex(s[2], &error) << 20;
3037            color |= get_hex(s[2], &error) << 16;
3038            color |= get_hex(s[3], &error) << 12;
3039            color |= get_hex(s[3], &error) << 8;
3040            color |= get_hex(s[4], &error) << 4;
3041            color |= get_hex(s[4], &error);
3042        } else if (len == 7) {
3043            outValue->dataType = outValue->TYPE_INT_COLOR_RGB8;
3044            color |= 0xFF000000;
3045            color |= get_hex(s[1], &error) << 20;
3046            color |= get_hex(s[2], &error) << 16;
3047            color |= get_hex(s[3], &error) << 12;
3048            color |= get_hex(s[4], &error) << 8;
3049            color |= get_hex(s[5], &error) << 4;
3050            color |= get_hex(s[6], &error);
3051        } else if (len == 9) {
3052            outValue->dataType = outValue->TYPE_INT_COLOR_ARGB8;
3053            color |= get_hex(s[1], &error) << 28;
3054            color |= get_hex(s[2], &error) << 24;
3055            color |= get_hex(s[3], &error) << 20;
3056            color |= get_hex(s[4], &error) << 16;
3057            color |= get_hex(s[5], &error) << 12;
3058            color |= get_hex(s[6], &error) << 8;
3059            color |= get_hex(s[7], &error) << 4;
3060            color |= get_hex(s[8], &error);
3061        } else {
3062            error = true;
3063        }
3064        if (!error) {
3065            if ((attrType&ResTable_map::TYPE_COLOR) == 0) {
3066                if (!canStringCoerce) {
3067                    if (accessor != NULL) {
3068                        accessor->reportError(accessorCookie,
3069                                "Color types not allowed");
3070                    }
3071                    return false;
3072                }
3073            } else {
3074                outValue->data = color;
3075                //printf("Color input=%s, output=0x%x\n", String8(s, len).string(), color);
3076                return true;
3077            }
3078        } else {
3079            if ((attrType&ResTable_map::TYPE_COLOR) != 0) {
3080                if (accessor != NULL) {
3081                    accessor->reportError(accessorCookie, "Color value not valid --"
3082                            " must be #rgb, #argb, #rrggbb, or #aarrggbb");
3083                }
3084                #if 0
3085                fprintf(stderr, "%s: Color ID %s value %s is not valid\n",
3086                        "Resource File", //(const char*)in->getPrintableSource(),
3087                        String8(*curTag).string(),
3088                        String8(s, len).string());
3089                #endif
3090                return false;
3091            }
3092        }
3093    }
3094
3095    if (*s == '?') {
3096        outValue->dataType = outValue->TYPE_ATTRIBUTE;
3097
3098        // Note: we don't check attrType here because the reference can
3099        // be to any other type; we just need to count on the client making
3100        // sure the referenced type is correct.
3101
3102        //printf("Looking up attr: %s\n", String8(s, len).string());
3103
3104        static const String16 attr16("attr");
3105        String16 package, type, name;
3106        if (!expandResourceRef(s+1, len-1, &package, &type, &name,
3107                               &attr16, defPackage, &errorMsg)) {
3108            if (accessor != NULL) {
3109                accessor->reportError(accessorCookie, errorMsg);
3110            }
3111            return false;
3112        }
3113
3114        //printf("Pkg: %s, Type: %s, Name: %s\n",
3115        //       String8(package).string(), String8(type).string(),
3116        //       String8(name).string());
3117        uint32_t specFlags = 0;
3118        uint32_t rid =
3119            identifierForName(name.string(), name.size(),
3120                              type.string(), type.size(),
3121                              package.string(), package.size(), &specFlags);
3122        if (rid != 0) {
3123            if (enforcePrivate) {
3124                if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
3125                    if (accessor != NULL) {
3126                        accessor->reportError(accessorCookie, "Attribute is not public.");
3127                    }
3128                    return false;
3129                }
3130            }
3131            if (!accessor) {
3132                outValue->data = rid;
3133                return true;
3134            }
3135            rid = Res_MAKEID(
3136                accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
3137                Res_GETTYPE(rid), Res_GETENTRY(rid));
3138            //printf("Incl %s:%s/%s: 0x%08x\n",
3139            //       String8(package).string(), String8(type).string(),
3140            //       String8(name).string(), rid);
3141            outValue->data = rid;
3142            return true;
3143        }
3144
3145        if (accessor) {
3146            uint32_t rid = accessor->getCustomResource(package, type, name);
3147            if (rid != 0) {
3148                //printf("Mine %s:%s/%s: 0x%08x\n",
3149                //       String8(package).string(), String8(type).string(),
3150                //       String8(name).string(), rid);
3151                outValue->data = rid;
3152                return true;
3153            }
3154        }
3155
3156        if (accessor != NULL) {
3157            accessor->reportError(accessorCookie, "No resource found that matches the given name");
3158        }
3159        return false;
3160    }
3161
3162    if (stringToInt(s, len, outValue)) {
3163        if ((attrType&ResTable_map::TYPE_INTEGER) == 0) {
3164            // If this type does not allow integers, but does allow floats,
3165            // fall through on this error case because the float type should
3166            // be able to accept any integer value.
3167            if (!canStringCoerce && (attrType&ResTable_map::TYPE_FLOAT) == 0) {
3168                if (accessor != NULL) {
3169                    accessor->reportError(accessorCookie, "Integer types not allowed");
3170                }
3171                return false;
3172            }
3173        } else {
3174            if (((int32_t)outValue->data) < ((int32_t)attrMin)
3175                    || ((int32_t)outValue->data) > ((int32_t)attrMax)) {
3176                if (accessor != NULL) {
3177                    accessor->reportError(accessorCookie, "Integer value out of range");
3178                }
3179                return false;
3180            }
3181            return true;
3182        }
3183    }
3184
3185    if (stringToFloat(s, len, outValue)) {
3186        if (outValue->dataType == Res_value::TYPE_DIMENSION) {
3187            if ((attrType&ResTable_map::TYPE_DIMENSION) != 0) {
3188                return true;
3189            }
3190            if (!canStringCoerce) {
3191                if (accessor != NULL) {
3192                    accessor->reportError(accessorCookie, "Dimension types not allowed");
3193                }
3194                return false;
3195            }
3196        } else if (outValue->dataType == Res_value::TYPE_FRACTION) {
3197            if ((attrType&ResTable_map::TYPE_FRACTION) != 0) {
3198                return true;
3199            }
3200            if (!canStringCoerce) {
3201                if (accessor != NULL) {
3202                    accessor->reportError(accessorCookie, "Fraction types not allowed");
3203                }
3204                return false;
3205            }
3206        } else if ((attrType&ResTable_map::TYPE_FLOAT) == 0) {
3207            if (!canStringCoerce) {
3208                if (accessor != NULL) {
3209                    accessor->reportError(accessorCookie, "Float types not allowed");
3210                }
3211                return false;
3212            }
3213        } else {
3214            return true;
3215        }
3216    }
3217
3218    if (len == 4) {
3219        if ((s[0] == 't' || s[0] == 'T') &&
3220            (s[1] == 'r' || s[1] == 'R') &&
3221            (s[2] == 'u' || s[2] == 'U') &&
3222            (s[3] == 'e' || s[3] == 'E')) {
3223            if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
3224                if (!canStringCoerce) {
3225                    if (accessor != NULL) {
3226                        accessor->reportError(accessorCookie, "Boolean types not allowed");
3227                    }
3228                    return false;
3229                }
3230            } else {
3231                outValue->dataType = outValue->TYPE_INT_BOOLEAN;
3232                outValue->data = (uint32_t)-1;
3233                return true;
3234            }
3235        }
3236    }
3237
3238    if (len == 5) {
3239        if ((s[0] == 'f' || s[0] == 'F') &&
3240            (s[1] == 'a' || s[1] == 'A') &&
3241            (s[2] == 'l' || s[2] == 'L') &&
3242            (s[3] == 's' || s[3] == 'S') &&
3243            (s[4] == 'e' || s[4] == 'E')) {
3244            if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
3245                if (!canStringCoerce) {
3246                    if (accessor != NULL) {
3247                        accessor->reportError(accessorCookie, "Boolean types not allowed");
3248                    }
3249                    return false;
3250                }
3251            } else {
3252                outValue->dataType = outValue->TYPE_INT_BOOLEAN;
3253                outValue->data = 0;
3254                return true;
3255            }
3256        }
3257    }
3258
3259    if ((attrType&ResTable_map::TYPE_ENUM) != 0) {
3260        const ssize_t p = getResourcePackageIndex(attrID);
3261        const bag_entry* bag;
3262        ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
3263        //printf("Got %d for enum\n", cnt);
3264        if (cnt >= 0) {
3265            resource_name rname;
3266            while (cnt > 0) {
3267                if (!Res_INTERNALID(bag->map.name.ident)) {
3268                    //printf("Trying attr #%08x\n", bag->map.name.ident);
3269                    if (getResourceName(bag->map.name.ident, &rname)) {
3270                        #if 0
3271                        printf("Matching %s against %s (0x%08x)\n",
3272                               String8(s, len).string(),
3273                               String8(rname.name, rname.nameLen).string(),
3274                               bag->map.name.ident);
3275                        #endif
3276                        if (strzcmp16(s, len, rname.name, rname.nameLen) == 0) {
3277                            outValue->dataType = bag->map.value.dataType;
3278                            outValue->data = bag->map.value.data;
3279                            unlockBag(bag);
3280                            return true;
3281                        }
3282                    }
3283
3284                }
3285                bag++;
3286                cnt--;
3287            }
3288            unlockBag(bag);
3289        }
3290
3291        if (fromAccessor) {
3292            if (accessor->getAttributeEnum(attrID, s, len, outValue)) {
3293                return true;
3294            }
3295        }
3296    }
3297
3298    if ((attrType&ResTable_map::TYPE_FLAGS) != 0) {
3299        const ssize_t p = getResourcePackageIndex(attrID);
3300        const bag_entry* bag;
3301        ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
3302        //printf("Got %d for flags\n", cnt);
3303        if (cnt >= 0) {
3304            bool failed = false;
3305            resource_name rname;
3306            outValue->dataType = Res_value::TYPE_INT_HEX;
3307            outValue->data = 0;
3308            const char16_t* end = s + len;
3309            const char16_t* pos = s;
3310            while (pos < end && !failed) {
3311                const char16_t* start = pos;
3312                pos++;
3313                while (pos < end && *pos != '|') {
3314                    pos++;
3315                }
3316                //printf("Looking for: %s\n", String8(start, pos-start).string());
3317                const bag_entry* bagi = bag;
3318                ssize_t i;
3319                for (i=0; i<cnt; i++, bagi++) {
3320                    if (!Res_INTERNALID(bagi->map.name.ident)) {
3321                        //printf("Trying attr #%08x\n", bagi->map.name.ident);
3322                        if (getResourceName(bagi->map.name.ident, &rname)) {
3323                            #if 0
3324                            printf("Matching %s against %s (0x%08x)\n",
3325                                   String8(start,pos-start).string(),
3326                                   String8(rname.name, rname.nameLen).string(),
3327                                   bagi->map.name.ident);
3328                            #endif
3329                            if (strzcmp16(start, pos-start, rname.name, rname.nameLen) == 0) {
3330                                outValue->data |= bagi->map.value.data;
3331                                break;
3332                            }
3333                        }
3334                    }
3335                }
3336                if (i >= cnt) {
3337                    // Didn't find this flag identifier.
3338                    failed = true;
3339                }
3340                if (pos < end) {
3341                    pos++;
3342                }
3343            }
3344            unlockBag(bag);
3345            if (!failed) {
3346                //printf("Final flag value: 0x%lx\n", outValue->data);
3347                return true;
3348            }
3349        }
3350
3351
3352        if (fromAccessor) {
3353            if (accessor->getAttributeFlags(attrID, s, len, outValue)) {
3354                //printf("Final flag value: 0x%lx\n", outValue->data);
3355                return true;
3356            }
3357        }
3358    }
3359
3360    if ((attrType&ResTable_map::TYPE_STRING) == 0) {
3361        if (accessor != NULL) {
3362            accessor->reportError(accessorCookie, "String types not allowed");
3363        }
3364        return false;
3365    }
3366
3367    // Generic string handling...
3368    outValue->dataType = outValue->TYPE_STRING;
3369    if (outString) {
3370        bool failed = collectString(outString, s, len, preserveSpaces, &errorMsg);
3371        if (accessor != NULL) {
3372            accessor->reportError(accessorCookie, errorMsg);
3373        }
3374        return failed;
3375    }
3376
3377    return true;
3378}
3379
3380bool ResTable::collectString(String16* outString,
3381                             const char16_t* s, size_t len,
3382                             bool preserveSpaces,
3383                             const char** outErrorMsg,
3384                             bool append)
3385{
3386    String16 tmp;
3387
3388    char quoted = 0;
3389    const char16_t* p = s;
3390    while (p < (s+len)) {
3391        while (p < (s+len)) {
3392            const char16_t c = *p;
3393            if (c == '\\') {
3394                break;
3395            }
3396            if (!preserveSpaces) {
3397                if (quoted == 0 && isspace16(c)
3398                    && (c != ' ' || isspace16(*(p+1)))) {
3399                    break;
3400                }
3401                if (c == '"' && (quoted == 0 || quoted == '"')) {
3402                    break;
3403                }
3404                if (c == '\'' && (quoted == 0 || quoted == '\'')) {
3405                    /*
3406                     * In practice, when people write ' instead of \'
3407                     * in a string, they are doing it by accident
3408                     * instead of really meaning to use ' as a quoting
3409                     * character.  Warn them so they don't lose it.
3410                     */
3411                    if (outErrorMsg) {
3412                        *outErrorMsg = "Apostrophe not preceded by \\";
3413                    }
3414                    return false;
3415                }
3416            }
3417            p++;
3418        }
3419        if (p < (s+len)) {
3420            if (p > s) {
3421                tmp.append(String16(s, p-s));
3422            }
3423            if (!preserveSpaces && (*p == '"' || *p == '\'')) {
3424                if (quoted == 0) {
3425                    quoted = *p;
3426                } else {
3427                    quoted = 0;
3428                }
3429                p++;
3430            } else if (!preserveSpaces && isspace16(*p)) {
3431                // Space outside of a quote -- consume all spaces and
3432                // leave a single plain space char.
3433                tmp.append(String16(" "));
3434                p++;
3435                while (p < (s+len) && isspace16(*p)) {
3436                    p++;
3437                }
3438            } else if (*p == '\\') {
3439                p++;
3440                if (p < (s+len)) {
3441                    switch (*p) {
3442                    case 't':
3443                        tmp.append(String16("\t"));
3444                        break;
3445                    case 'n':
3446                        tmp.append(String16("\n"));
3447                        break;
3448                    case '#':
3449                        tmp.append(String16("#"));
3450                        break;
3451                    case '@':
3452                        tmp.append(String16("@"));
3453                        break;
3454                    case '?':
3455                        tmp.append(String16("?"));
3456                        break;
3457                    case '"':
3458                        tmp.append(String16("\""));
3459                        break;
3460                    case '\'':
3461                        tmp.append(String16("'"));
3462                        break;
3463                    case '\\':
3464                        tmp.append(String16("\\"));
3465                        break;
3466                    case 'u':
3467                    {
3468                        char16_t chr = 0;
3469                        int i = 0;
3470                        while (i < 4 && p[1] != 0) {
3471                            p++;
3472                            i++;
3473                            int c;
3474                            if (*p >= '0' && *p <= '9') {
3475                                c = *p - '0';
3476                            } else if (*p >= 'a' && *p <= 'f') {
3477                                c = *p - 'a' + 10;
3478                            } else if (*p >= 'A' && *p <= 'F') {
3479                                c = *p - 'A' + 10;
3480                            } else {
3481                                if (outErrorMsg) {
3482                                    *outErrorMsg = "Bad character in \\u unicode escape sequence";
3483                                }
3484                                return false;
3485                            }
3486                            chr = (chr<<4) | c;
3487                        }
3488                        tmp.append(String16(&chr, 1));
3489                    } break;
3490                    default:
3491                        // ignore unknown escape chars.
3492                        break;
3493                    }
3494                    p++;
3495                }
3496            }
3497            len -= (p-s);
3498            s = p;
3499        }
3500    }
3501
3502    if (tmp.size() != 0) {
3503        if (len > 0) {
3504            tmp.append(String16(s, len));
3505        }
3506        if (append) {
3507            outString->append(tmp);
3508        } else {
3509            outString->setTo(tmp);
3510        }
3511    } else {
3512        if (append) {
3513            outString->append(String16(s, len));
3514        } else {
3515            outString->setTo(s, len);
3516        }
3517    }
3518
3519    return true;
3520}
3521
3522size_t ResTable::getBasePackageCount() const
3523{
3524    if (mError != NO_ERROR) {
3525        return 0;
3526    }
3527    return mPackageGroups.size();
3528}
3529
3530const char16_t* ResTable::getBasePackageName(size_t idx) const
3531{
3532    if (mError != NO_ERROR) {
3533        return 0;
3534    }
3535    LOG_FATAL_IF(idx >= mPackageGroups.size(),
3536                 "Requested package index %d past package count %d",
3537                 (int)idx, (int)mPackageGroups.size());
3538    return mPackageGroups[idx]->name.string();
3539}
3540
3541uint32_t ResTable::getBasePackageId(size_t idx) const
3542{
3543    if (mError != NO_ERROR) {
3544        return 0;
3545    }
3546    LOG_FATAL_IF(idx >= mPackageGroups.size(),
3547                 "Requested package index %d past package count %d",
3548                 (int)idx, (int)mPackageGroups.size());
3549    return mPackageGroups[idx]->id;
3550}
3551
3552size_t ResTable::getTableCount() const
3553{
3554    return mHeaders.size();
3555}
3556
3557const ResStringPool* ResTable::getTableStringBlock(size_t index) const
3558{
3559    return &mHeaders[index]->values;
3560}
3561
3562void* ResTable::getTableCookie(size_t index) const
3563{
3564    return mHeaders[index]->cookie;
3565}
3566
3567void ResTable::getConfigurations(Vector<ResTable_config>* configs) const
3568{
3569    const size_t I = mPackageGroups.size();
3570    for (size_t i=0; i<I; i++) {
3571        const PackageGroup* packageGroup = mPackageGroups[i];
3572        const size_t J = packageGroup->packages.size();
3573        for (size_t j=0; j<J; j++) {
3574            const Package* package = packageGroup->packages[j];
3575            const size_t K = package->types.size();
3576            for (size_t k=0; k<K; k++) {
3577                const Type* type = package->types[k];
3578                if (type == NULL) continue;
3579                const size_t L = type->configs.size();
3580                for (size_t l=0; l<L; l++) {
3581                    const ResTable_type* config = type->configs[l];
3582                    const ResTable_config* cfg = &config->config;
3583                    // only insert unique
3584                    const size_t M = configs->size();
3585                    size_t m;
3586                    for (m=0; m<M; m++) {
3587                        if (0 == (*configs)[m].compare(*cfg)) {
3588                            break;
3589                        }
3590                    }
3591                    // if we didn't find it
3592                    if (m == M) {
3593                        configs->add(*cfg);
3594                    }
3595                }
3596            }
3597        }
3598    }
3599}
3600
3601void ResTable::getLocales(Vector<String8>* locales) const
3602{
3603    Vector<ResTable_config> configs;
3604    LOGD("calling getConfigurations");
3605    getConfigurations(&configs);
3606    LOGD("called getConfigurations size=%d", (int)configs.size());
3607    const size_t I = configs.size();
3608    for (size_t i=0; i<I; i++) {
3609        char locale[6];
3610        configs[i].getLocale(locale);
3611        const size_t J = locales->size();
3612        size_t j;
3613        for (j=0; j<J; j++) {
3614            if (0 == strcmp(locale, (*locales)[j].string())) {
3615                break;
3616            }
3617        }
3618        if (j == J) {
3619            locales->add(String8(locale));
3620        }
3621    }
3622}
3623
3624ssize_t ResTable::getEntry(
3625    const Package* package, int typeIndex, int entryIndex,
3626    const ResTable_config* config,
3627    const ResTable_type** outType, const ResTable_entry** outEntry,
3628    const Type** outTypeClass) const
3629{
3630    LOGV("Getting entry from package %p\n", package);
3631    const ResTable_package* const pkg = package->package;
3632
3633    const Type* allTypes = package->getType(typeIndex);
3634    LOGV("allTypes=%p\n", allTypes);
3635    if (allTypes == NULL) {
3636        LOGV("Skipping entry type index 0x%02x because type is NULL!\n", typeIndex);
3637        return 0;
3638    }
3639
3640    if ((size_t)entryIndex >= allTypes->entryCount) {
3641        LOGW("getEntry failing because entryIndex %d is beyond type entryCount %d",
3642            entryIndex, (int)allTypes->entryCount);
3643        return BAD_TYPE;
3644    }
3645
3646    const ResTable_type* type = NULL;
3647    uint32_t offset = ResTable_type::NO_ENTRY;
3648    ResTable_config bestConfig;
3649    memset(&bestConfig, 0, sizeof(bestConfig)); // make the compiler shut up
3650
3651    const size_t NT = allTypes->configs.size();
3652    for (size_t i=0; i<NT; i++) {
3653        const ResTable_type* const thisType = allTypes->configs[i];
3654        if (thisType == NULL) continue;
3655
3656        ResTable_config thisConfig;
3657        thisConfig.copyFromDtoH(thisType->config);
3658
3659        TABLE_GETENTRY(LOGI("Match entry 0x%x in type 0x%x (sz 0x%x): imsi:%d/%d=%d/%d lang:%c%c=%c%c cnt:%c%c=%c%c "
3660                            "orien:%d=%d touch:%d=%d density:%d=%d key:%d=%d inp:%d=%d nav:%d=%d w:%d=%d h:%d=%d\n",
3661                           entryIndex, typeIndex+1, dtohl(thisType->config.size),
3662                           thisConfig.mcc, thisConfig.mnc,
3663                           config ? config->mcc : 0, config ? config->mnc : 0,
3664                           thisConfig.language[0] ? thisConfig.language[0] : '-',
3665                           thisConfig.language[1] ? thisConfig.language[1] : '-',
3666                           config && config->language[0] ? config->language[0] : '-',
3667                           config && config->language[1] ? config->language[1] : '-',
3668                           thisConfig.country[0] ? thisConfig.country[0] : '-',
3669                           thisConfig.country[1] ? thisConfig.country[1] : '-',
3670                           config && config->country[0] ? config->country[0] : '-',
3671                           config && config->country[1] ? config->country[1] : '-',
3672                           thisConfig.orientation,
3673                           config ? config->orientation : 0,
3674                           thisConfig.touchscreen,
3675                           config ? config->touchscreen : 0,
3676                           thisConfig.density,
3677                           config ? config->density : 0,
3678                           thisConfig.keyboard,
3679                           config ? config->keyboard : 0,
3680                           thisConfig.inputFlags,
3681                           config ? config->inputFlags : 0,
3682                           thisConfig.navigation,
3683                           config ? config->navigation : 0,
3684                           thisConfig.screenWidth,
3685                           config ? config->screenWidth : 0,
3686                           thisConfig.screenHeight,
3687                           config ? config->screenHeight : 0));
3688
3689        // Check to make sure this one is valid for the current parameters.
3690        if (config && !thisConfig.match(*config)) {
3691            TABLE_GETENTRY(LOGI("Does not match config!\n"));
3692            continue;
3693        }
3694
3695        // Check if there is the desired entry in this type.
3696
3697        const uint8_t* const end = ((const uint8_t*)thisType)
3698            + dtohl(thisType->header.size);
3699        const uint32_t* const eindex = (const uint32_t*)
3700            (((const uint8_t*)thisType) + dtohs(thisType->header.headerSize));
3701
3702        uint32_t thisOffset = dtohl(eindex[entryIndex]);
3703        if (thisOffset == ResTable_type::NO_ENTRY) {
3704            TABLE_GETENTRY(LOGI("Skipping because it is not defined!\n"));
3705            continue;
3706        }
3707
3708        if (type != NULL) {
3709            // Check if this one is less specific than the last found.  If so,
3710            // we will skip it.  We check starting with things we most care
3711            // about to those we least care about.
3712            if (!thisConfig.isBetterThan(bestConfig, config)) {
3713                TABLE_GETENTRY(LOGI("This config is worse than last!\n"));
3714                continue;
3715            }
3716        }
3717
3718        type = thisType;
3719        offset = thisOffset;
3720        bestConfig = thisConfig;
3721        TABLE_GETENTRY(LOGI("Best entry so far -- using it!\n"));
3722        if (!config) break;
3723    }
3724
3725    if (type == NULL) {
3726        TABLE_GETENTRY(LOGI("No value found for requested entry!\n"));
3727        return BAD_INDEX;
3728    }
3729
3730    offset += dtohl(type->entriesStart);
3731    TABLE_NOISY(aout << "Looking in resource table " << package->header->header
3732          << ", typeOff="
3733          << (void*)(((const char*)type)-((const char*)package->header->header))
3734          << ", offset=" << (void*)offset << endl);
3735
3736    if (offset > (dtohl(type->header.size)-sizeof(ResTable_entry))) {
3737        LOGW("ResTable_entry at 0x%x is beyond type chunk data 0x%x",
3738             offset, dtohl(type->header.size));
3739        return BAD_TYPE;
3740    }
3741    if ((offset&0x3) != 0) {
3742        LOGW("ResTable_entry at 0x%x is not on an integer boundary",
3743             offset);
3744        return BAD_TYPE;
3745    }
3746
3747    const ResTable_entry* const entry = (const ResTable_entry*)
3748        (((const uint8_t*)type) + offset);
3749    if (dtohs(entry->size) < sizeof(*entry)) {
3750        LOGW("ResTable_entry size 0x%x is too small", dtohs(entry->size));
3751        return BAD_TYPE;
3752    }
3753
3754    *outType = type;
3755    *outEntry = entry;
3756    if (outTypeClass != NULL) {
3757        *outTypeClass = allTypes;
3758    }
3759    return offset + dtohs(entry->size);
3760}
3761
3762status_t ResTable::parsePackage(const ResTable_package* const pkg,
3763                                const Header* const header)
3764{
3765    const uint8_t* base = (const uint8_t*)pkg;
3766    status_t err = validate_chunk(&pkg->header, sizeof(*pkg),
3767                                  header->dataEnd, "ResTable_package");
3768    if (err != NO_ERROR) {
3769        return (mError=err);
3770    }
3771
3772    const size_t pkgSize = dtohl(pkg->header.size);
3773
3774    if (dtohl(pkg->typeStrings) >= pkgSize) {
3775        LOGW("ResTable_package type strings at %p are past chunk size %p.",
3776             (void*)dtohl(pkg->typeStrings), (void*)pkgSize);
3777        return (mError=BAD_TYPE);
3778    }
3779    if ((dtohl(pkg->typeStrings)&0x3) != 0) {
3780        LOGW("ResTable_package type strings at %p is not on an integer boundary.",
3781             (void*)dtohl(pkg->typeStrings));
3782        return (mError=BAD_TYPE);
3783    }
3784    if (dtohl(pkg->keyStrings) >= pkgSize) {
3785        LOGW("ResTable_package key strings at %p are past chunk size %p.",
3786             (void*)dtohl(pkg->keyStrings), (void*)pkgSize);
3787        return (mError=BAD_TYPE);
3788    }
3789    if ((dtohl(pkg->keyStrings)&0x3) != 0) {
3790        LOGW("ResTable_package key strings at %p is not on an integer boundary.",
3791             (void*)dtohl(pkg->keyStrings));
3792        return (mError=BAD_TYPE);
3793    }
3794
3795    Package* package = NULL;
3796    PackageGroup* group = NULL;
3797    uint32_t id = dtohl(pkg->id);
3798    if (id != 0 && id < 256) {
3799
3800        package = new Package(this, header, pkg);
3801        if (package == NULL) {
3802            return (mError=NO_MEMORY);
3803        }
3804
3805        size_t idx = mPackageMap[id];
3806        if (idx == 0) {
3807            idx = mPackageGroups.size()+1;
3808
3809            char16_t tmpName[sizeof(pkg->name)/sizeof(char16_t)];
3810            strcpy16_dtoh(tmpName, pkg->name, sizeof(pkg->name)/sizeof(char16_t));
3811            group = new PackageGroup(this, String16(tmpName), id);
3812            if (group == NULL) {
3813                delete package;
3814                return (mError=NO_MEMORY);
3815            }
3816
3817            err = package->typeStrings.setTo(base+dtohl(pkg->typeStrings),
3818                                           header->dataEnd-(base+dtohl(pkg->typeStrings)));
3819            if (err != NO_ERROR) {
3820                delete group;
3821                delete package;
3822                return (mError=err);
3823            }
3824            err = package->keyStrings.setTo(base+dtohl(pkg->keyStrings),
3825                                          header->dataEnd-(base+dtohl(pkg->keyStrings)));
3826            if (err != NO_ERROR) {
3827                delete group;
3828                delete package;
3829                return (mError=err);
3830            }
3831
3832            //printf("Adding new package id %d at index %d\n", id, idx);
3833            err = mPackageGroups.add(group);
3834            if (err < NO_ERROR) {
3835                return (mError=err);
3836            }
3837            group->basePackage = package;
3838
3839            mPackageMap[id] = (uint8_t)idx;
3840        } else {
3841            group = mPackageGroups.itemAt(idx-1);
3842            if (group == NULL) {
3843                return (mError=UNKNOWN_ERROR);
3844            }
3845        }
3846        err = group->packages.add(package);
3847        if (err < NO_ERROR) {
3848            return (mError=err);
3849        }
3850    } else {
3851        LOG_ALWAYS_FATAL("Skins not supported!");
3852        return NO_ERROR;
3853    }
3854
3855
3856    // Iterate through all chunks.
3857    size_t curPackage = 0;
3858
3859    const ResChunk_header* chunk =
3860        (const ResChunk_header*)(((const uint8_t*)pkg)
3861                                 + dtohs(pkg->header.headerSize));
3862    const uint8_t* endPos = ((const uint8_t*)pkg) + dtohs(pkg->header.size);
3863    while (((const uint8_t*)chunk) <= (endPos-sizeof(ResChunk_header)) &&
3864           ((const uint8_t*)chunk) <= (endPos-dtohl(chunk->size))) {
3865        TABLE_NOISY(LOGV("PackageChunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n",
3866                         dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
3867                         (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header))));
3868        const size_t csize = dtohl(chunk->size);
3869        const uint16_t ctype = dtohs(chunk->type);
3870        if (ctype == RES_TABLE_TYPE_SPEC_TYPE) {
3871            const ResTable_typeSpec* typeSpec = (const ResTable_typeSpec*)(chunk);
3872            err = validate_chunk(&typeSpec->header, sizeof(*typeSpec),
3873                                 endPos, "ResTable_typeSpec");
3874            if (err != NO_ERROR) {
3875                return (mError=err);
3876            }
3877
3878            const size_t typeSpecSize = dtohl(typeSpec->header.size);
3879
3880            LOAD_TABLE_NOISY(printf("TypeSpec off %p: type=0x%x, headerSize=0x%x, size=%p\n",
3881                                    (void*)(base-(const uint8_t*)chunk),
3882                                    dtohs(typeSpec->header.type),
3883                                    dtohs(typeSpec->header.headerSize),
3884                                    (void*)typeSize));
3885            // look for block overrun or int overflow when multiplying by 4
3886            if ((dtohl(typeSpec->entryCount) > (INT32_MAX/sizeof(uint32_t))
3887                    || dtohs(typeSpec->header.headerSize)+(sizeof(uint32_t)*dtohl(typeSpec->entryCount))
3888                    > typeSpecSize)) {
3889                LOGW("ResTable_typeSpec entry index to %p extends beyond chunk end %p.",
3890                     (void*)(dtohs(typeSpec->header.headerSize)
3891                             +(sizeof(uint32_t)*dtohl(typeSpec->entryCount))),
3892                     (void*)typeSpecSize);
3893                return (mError=BAD_TYPE);
3894            }
3895
3896            if (typeSpec->id == 0) {
3897                LOGW("ResTable_type has an id of 0.");
3898                return (mError=BAD_TYPE);
3899            }
3900
3901            while (package->types.size() < typeSpec->id) {
3902                package->types.add(NULL);
3903            }
3904            Type* t = package->types[typeSpec->id-1];
3905            if (t == NULL) {
3906                t = new Type(header, package, dtohl(typeSpec->entryCount));
3907                package->types.editItemAt(typeSpec->id-1) = t;
3908            } else if (dtohl(typeSpec->entryCount) != t->entryCount) {
3909                LOGW("ResTable_typeSpec entry count inconsistent: given %d, previously %d",
3910                    (int)dtohl(typeSpec->entryCount), (int)t->entryCount);
3911                return (mError=BAD_TYPE);
3912            }
3913            t->typeSpecFlags = (const uint32_t*)(
3914                    ((const uint8_t*)typeSpec) + dtohs(typeSpec->header.headerSize));
3915            t->typeSpec = typeSpec;
3916
3917        } else if (ctype == RES_TABLE_TYPE_TYPE) {
3918            const ResTable_type* type = (const ResTable_type*)(chunk);
3919            err = validate_chunk(&type->header, sizeof(*type)-sizeof(ResTable_config)+4,
3920                                 endPos, "ResTable_type");
3921            if (err != NO_ERROR) {
3922                return (mError=err);
3923            }
3924
3925            const size_t typeSize = dtohl(type->header.size);
3926
3927            LOAD_TABLE_NOISY(printf("Type off %p: type=0x%x, headerSize=0x%x, size=%p\n",
3928                                    (void*)(base-(const uint8_t*)chunk),
3929                                    dtohs(type->header.type),
3930                                    dtohs(type->header.headerSize),
3931                                    (void*)typeSize));
3932            if (dtohs(type->header.headerSize)+(sizeof(uint32_t)*dtohl(type->entryCount))
3933                > typeSize) {
3934                LOGW("ResTable_type entry index to %p extends beyond chunk end %p.",
3935                     (void*)(dtohs(type->header.headerSize)
3936                             +(sizeof(uint32_t)*dtohl(type->entryCount))),
3937                     (void*)typeSize);
3938                return (mError=BAD_TYPE);
3939            }
3940            if (dtohl(type->entryCount) != 0
3941                && dtohl(type->entriesStart) > (typeSize-sizeof(ResTable_entry))) {
3942                LOGW("ResTable_type entriesStart at %p extends beyond chunk end %p.",
3943                     (void*)dtohl(type->entriesStart), (void*)typeSize);
3944                return (mError=BAD_TYPE);
3945            }
3946            if (type->id == 0) {
3947                LOGW("ResTable_type has an id of 0.");
3948                return (mError=BAD_TYPE);
3949            }
3950
3951            while (package->types.size() < type->id) {
3952                package->types.add(NULL);
3953            }
3954            Type* t = package->types[type->id-1];
3955            if (t == NULL) {
3956                t = new Type(header, package, dtohl(type->entryCount));
3957                package->types.editItemAt(type->id-1) = t;
3958            } else if (dtohl(type->entryCount) != t->entryCount) {
3959                LOGW("ResTable_type entry count inconsistent: given %d, previously %d",
3960                    (int)dtohl(type->entryCount), (int)t->entryCount);
3961                return (mError=BAD_TYPE);
3962            }
3963
3964            TABLE_GETENTRY(
3965                ResTable_config thisConfig;
3966                thisConfig.copyFromDtoH(type->config);
3967                LOGI("Adding config to type %d: imsi:%d/%d lang:%c%c cnt:%c%c "
3968                     "orien:%d touch:%d density:%d key:%d inp:%d nav:%d w:%d h:%d\n",
3969                      type->id,
3970                      thisConfig.mcc, thisConfig.mnc,
3971                      thisConfig.language[0] ? thisConfig.language[0] : '-',
3972                      thisConfig.language[1] ? thisConfig.language[1] : '-',
3973                      thisConfig.country[0] ? thisConfig.country[0] : '-',
3974                      thisConfig.country[1] ? thisConfig.country[1] : '-',
3975                      thisConfig.orientation,
3976                      thisConfig.touchscreen,
3977                      thisConfig.density,
3978                      thisConfig.keyboard,
3979                      thisConfig.inputFlags,
3980                      thisConfig.navigation,
3981                      thisConfig.screenWidth,
3982                      thisConfig.screenHeight));
3983            t->configs.add(type);
3984        } else {
3985            status_t err = validate_chunk(chunk, sizeof(ResChunk_header),
3986                                          endPos, "ResTable_package:unknown");
3987            if (err != NO_ERROR) {
3988                return (mError=err);
3989            }
3990        }
3991        chunk = (const ResChunk_header*)
3992            (((const uint8_t*)chunk) + csize);
3993    }
3994
3995    if (group->typeCount == 0) {
3996        group->typeCount = package->types.size();
3997    }
3998
3999    return NO_ERROR;
4000}
4001
4002#ifndef HAVE_ANDROID_OS
4003#define CHAR16_TO_CSTR(c16, len) (String8(String16(c16,len)).string())
4004
4005#define CHAR16_ARRAY_EQ(constant, var, len) \
4006        ((len == (sizeof(constant)/sizeof(constant[0]))) && (0 == memcmp((var), (constant), (len))))
4007
4008void print_complex(uint32_t complex, bool isFraction)
4009{
4010    const float MANTISSA_MULT =
4011        1.0f / (1<<Res_value::COMPLEX_MANTISSA_SHIFT);
4012    const float RADIX_MULTS[] = {
4013        1.0f*MANTISSA_MULT, 1.0f/(1<<7)*MANTISSA_MULT,
4014        1.0f/(1<<15)*MANTISSA_MULT, 1.0f/(1<<23)*MANTISSA_MULT
4015    };
4016
4017    float value = (complex&(Res_value::COMPLEX_MANTISSA_MASK
4018                   <<Res_value::COMPLEX_MANTISSA_SHIFT))
4019            * RADIX_MULTS[(complex>>Res_value::COMPLEX_RADIX_SHIFT)
4020                            & Res_value::COMPLEX_RADIX_MASK];
4021    printf("%f", value);
4022
4023    if (!isFraction) {
4024        switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
4025            case Res_value::COMPLEX_UNIT_PX: printf("px"); break;
4026            case Res_value::COMPLEX_UNIT_DIP: printf("dp"); break;
4027            case Res_value::COMPLEX_UNIT_SP: printf("sp"); break;
4028            case Res_value::COMPLEX_UNIT_PT: printf("pt"); break;
4029            case Res_value::COMPLEX_UNIT_IN: printf("in"); break;
4030            case Res_value::COMPLEX_UNIT_MM: printf("mm"); break;
4031            default: printf(" (unknown unit)"); break;
4032        }
4033    } else {
4034        switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
4035            case Res_value::COMPLEX_UNIT_FRACTION: printf("%%"); break;
4036            case Res_value::COMPLEX_UNIT_FRACTION_PARENT: printf("%%p"); break;
4037            default: printf(" (unknown unit)"); break;
4038        }
4039    }
4040}
4041
4042void ResTable::print_value(const Package* pkg, const Res_value& value) const
4043{
4044    if (value.dataType == Res_value::TYPE_NULL) {
4045        printf("(null)\n");
4046    } else if (value.dataType == Res_value::TYPE_REFERENCE) {
4047        printf("(reference) 0x%08x\n", value.data);
4048    } else if (value.dataType == Res_value::TYPE_ATTRIBUTE) {
4049        printf("(attribute) 0x%08x\n", value.data);
4050    } else if (value.dataType == Res_value::TYPE_STRING) {
4051        size_t len;
4052        const char* str8 = pkg->header->values.string8At(
4053                value.data, &len);
4054        if (str8 != NULL) {
4055            printf("(string8) \"%s\"\n", str8);
4056        } else {
4057            const char16_t* str16 = pkg->header->values.stringAt(
4058                    value.data, &len);
4059            if (str16 != NULL) {
4060                printf("(string16) \"%s\"\n",
4061                    String8(str16, len).string());
4062            } else {
4063                printf("(string) null\n");
4064            }
4065        }
4066    } else if (value.dataType == Res_value::TYPE_FLOAT) {
4067        printf("(float) %g\n", *(const float*)&value.data);
4068    } else if (value.dataType == Res_value::TYPE_DIMENSION) {
4069        printf("(dimension) ");
4070        print_complex(value.data, false);
4071        printf("\n");
4072    } else if (value.dataType == Res_value::TYPE_FRACTION) {
4073        printf("(fraction) ");
4074        print_complex(value.data, true);
4075        printf("\n");
4076    } else if (value.dataType >= Res_value::TYPE_FIRST_COLOR_INT
4077            || value.dataType <= Res_value::TYPE_LAST_COLOR_INT) {
4078        printf("(color) #%08x\n", value.data);
4079    } else if (value.dataType == Res_value::TYPE_INT_BOOLEAN) {
4080        printf("(boolean) %s\n", value.data ? "true" : "false");
4081    } else if (value.dataType >= Res_value::TYPE_FIRST_INT
4082            || value.dataType <= Res_value::TYPE_LAST_INT) {
4083        printf("(int) 0x%08x or %d\n", value.data, value.data);
4084    } else {
4085        printf("(unknown type) t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)\n",
4086               (int)value.dataType, (int)value.data,
4087               (int)value.size, (int)value.res0);
4088    }
4089}
4090
4091void ResTable::print(bool inclValues) const
4092{
4093    if (mError != 0) {
4094        printf("mError=0x%x (%s)\n", mError, strerror(mError));
4095    }
4096#if 0
4097    printf("mParams=%c%c-%c%c,\n",
4098            mParams.language[0], mParams.language[1],
4099            mParams.country[0], mParams.country[1]);
4100#endif
4101    size_t pgCount = mPackageGroups.size();
4102    printf("Package Groups (%d)\n", (int)pgCount);
4103    for (size_t pgIndex=0; pgIndex<pgCount; pgIndex++) {
4104        const PackageGroup* pg = mPackageGroups[pgIndex];
4105        printf("Package Group %d id=%d packageCount=%d name=%s\n",
4106                (int)pgIndex, pg->id, (int)pg->packages.size(),
4107                String8(pg->name).string());
4108
4109        size_t pkgCount = pg->packages.size();
4110        for (size_t pkgIndex=0; pkgIndex<pkgCount; pkgIndex++) {
4111            const Package* pkg = pg->packages[pkgIndex];
4112            size_t typeCount = pkg->types.size();
4113            printf("  Package %d id=%d name=%s typeCount=%d\n", (int)pkgIndex,
4114                    pkg->package->id, String8(String16(pkg->package->name)).string(),
4115                    (int)typeCount);
4116            for (size_t typeIndex=0; typeIndex<typeCount; typeIndex++) {
4117                const Type* typeConfigs = pkg->getType(typeIndex);
4118                if (typeConfigs == NULL) {
4119                    printf("    type %d NULL\n", (int)typeIndex);
4120                    continue;
4121                }
4122                const size_t NTC = typeConfigs->configs.size();
4123                printf("    type %d configCount=%d entryCount=%d\n",
4124                       (int)typeIndex, (int)NTC, (int)typeConfigs->entryCount);
4125                if (typeConfigs->typeSpecFlags != NULL) {
4126                    for (size_t entryIndex=0; entryIndex<typeConfigs->entryCount; entryIndex++) {
4127                        uint32_t resID = (0xff000000 & ((pkg->package->id)<<24))
4128                                    | (0x00ff0000 & ((typeIndex+1)<<16))
4129                                    | (0x0000ffff & (entryIndex));
4130                        resource_name resName;
4131                        this->getResourceName(resID, &resName);
4132                        printf("      spec resource 0x%08x %s:%s/%s: flags=0x%08x\n",
4133                            resID,
4134                            CHAR16_TO_CSTR(resName.package, resName.packageLen),
4135                            CHAR16_TO_CSTR(resName.type, resName.typeLen),
4136                            CHAR16_TO_CSTR(resName.name, resName.nameLen),
4137                            dtohl(typeConfigs->typeSpecFlags[entryIndex]));
4138                    }
4139                }
4140                for (size_t configIndex=0; configIndex<NTC; configIndex++) {
4141                    const ResTable_type* type = typeConfigs->configs[configIndex];
4142                    if ((((uint64_t)type)&0x3) != 0) {
4143                        printf("      NON-INTEGER ResTable_type ADDRESS: %p\n", type);
4144                        continue;
4145                    }
4146                    char density[16];
4147                    uint16_t dval = dtohs(type->config.density);
4148                    if (dval == ResTable_config::DENSITY_DEFAULT) {
4149                        strcpy(density, "def");
4150                    } else if (dval == ResTable_config::DENSITY_NONE) {
4151                        strcpy(density, "no");
4152                    } else {
4153                        sprintf(density, "%d", (int)dval);
4154                    }
4155                    printf("      config %d", (int)configIndex);
4156                    if (type->config.mcc != 0) {
4157                        printf(" mcc=%d", dtohs(type->config.mcc));
4158                    }
4159                    if (type->config.mnc != 0) {
4160                        printf(" mnc=%d", dtohs(type->config.mnc));
4161                    }
4162                    if (type->config.locale != 0) {
4163                        printf(" lang=%c%c cnt=%c%c",
4164                               type->config.language[0] ? type->config.language[0] : '-',
4165                               type->config.language[1] ? type->config.language[1] : '-',
4166                               type->config.country[0] ? type->config.country[0] : '-',
4167                               type->config.country[1] ? type->config.country[1] : '-');
4168                    }
4169                    if (type->config.screenLayout != 0) {
4170                        printf(" sz=%d",
4171                                type->config.screenLayout&ResTable_config::MASK_SCREENSIZE);
4172                        switch (type->config.screenLayout&ResTable_config::MASK_SCREENSIZE) {
4173                            case ResTable_config::SCREENSIZE_SMALL:
4174                                printf(" (small)");
4175                                break;
4176                            case ResTable_config::SCREENSIZE_NORMAL:
4177                                printf(" (normal)");
4178                                break;
4179                            case ResTable_config::SCREENSIZE_LARGE:
4180                                printf(" (large)");
4181                                break;
4182                        }
4183                        printf(" lng=%d",
4184                                type->config.screenLayout&ResTable_config::MASK_SCREENLONG);
4185                        switch (type->config.screenLayout&ResTable_config::MASK_SCREENLONG) {
4186                            case ResTable_config::SCREENLONG_NO:
4187                                printf(" (notlong)");
4188                                break;
4189                            case ResTable_config::SCREENLONG_YES:
4190                                printf(" (long)");
4191                                break;
4192                        }
4193                    }
4194                    if (type->config.orientation != 0) {
4195                        printf(" orient=%d", type->config.orientation);
4196                        switch (type->config.orientation) {
4197                            case ResTable_config::ORIENTATION_PORT:
4198                                printf(" (port)");
4199                                break;
4200                            case ResTable_config::ORIENTATION_LAND:
4201                                printf(" (land)");
4202                                break;
4203                            case ResTable_config::ORIENTATION_SQUARE:
4204                                printf(" (square)");
4205                                break;
4206                        }
4207                    }
4208                    if (type->config.uiMode != 0) {
4209                        printf(" type=%d",
4210                                type->config.uiMode&ResTable_config::MASK_UI_MODE_TYPE);
4211                        switch (type->config.uiMode&ResTable_config::MASK_UI_MODE_TYPE) {
4212                            case ResTable_config::UI_MODE_TYPE_NORMAL:
4213                                printf(" (normal)");
4214                                break;
4215                            case ResTable_config::UI_MODE_TYPE_CAR:
4216                                printf(" (car)");
4217                                break;
4218                        }
4219                        printf(" night=%d",
4220                                type->config.uiMode&ResTable_config::MASK_UI_MODE_NIGHT);
4221                        switch (type->config.uiMode&ResTable_config::MASK_UI_MODE_NIGHT) {
4222                            case ResTable_config::UI_MODE_NIGHT_NO:
4223                                printf(" (no)");
4224                                break;
4225                            case ResTable_config::UI_MODE_NIGHT_YES:
4226                                printf(" (yes)");
4227                                break;
4228                        }
4229                    }
4230                    if (dval != 0) {
4231                        printf(" density=%s", density);
4232                    }
4233                    if (type->config.touchscreen != 0) {
4234                        printf(" touch=%d", type->config.touchscreen);
4235                        switch (type->config.touchscreen) {
4236                            case ResTable_config::TOUCHSCREEN_NOTOUCH:
4237                                printf(" (notouch)");
4238                                break;
4239                            case ResTable_config::TOUCHSCREEN_STYLUS:
4240                                printf(" (stylus)");
4241                                break;
4242                            case ResTable_config::TOUCHSCREEN_FINGER:
4243                                printf(" (finger)");
4244                                break;
4245                        }
4246                    }
4247                    if (type->config.inputFlags != 0) {
4248                        printf(" keyhid=%d", type->config.inputFlags&ResTable_config::MASK_KEYSHIDDEN);
4249                        switch (type->config.inputFlags&ResTable_config::MASK_KEYSHIDDEN) {
4250                            case ResTable_config::KEYSHIDDEN_NO:
4251                                printf(" (no)");
4252                                break;
4253                            case ResTable_config::KEYSHIDDEN_YES:
4254                                printf(" (yes)");
4255                                break;
4256                            case ResTable_config::KEYSHIDDEN_SOFT:
4257                                printf(" (soft)");
4258                                break;
4259                        }
4260                        printf(" navhid=%d", type->config.inputFlags&ResTable_config::MASK_NAVHIDDEN);
4261                        switch (type->config.inputFlags&ResTable_config::MASK_NAVHIDDEN) {
4262                            case ResTable_config::NAVHIDDEN_NO:
4263                                printf(" (no)");
4264                                break;
4265                            case ResTable_config::NAVHIDDEN_YES:
4266                                printf(" (yes)");
4267                                break;
4268                        }
4269                    }
4270                    if (type->config.keyboard != 0) {
4271                        printf(" kbd=%d", type->config.keyboard);
4272                        switch (type->config.keyboard) {
4273                            case ResTable_config::KEYBOARD_NOKEYS:
4274                                printf(" (nokeys)");
4275                                break;
4276                            case ResTable_config::KEYBOARD_QWERTY:
4277                                printf(" (qwerty)");
4278                                break;
4279                            case ResTable_config::KEYBOARD_12KEY:
4280                                printf(" (12key)");
4281                                break;
4282                        }
4283                    }
4284                    if (type->config.navigation != 0) {
4285                        printf(" nav=%d", type->config.navigation);
4286                        switch (type->config.navigation) {
4287                            case ResTable_config::NAVIGATION_NONAV:
4288                                printf(" (nonav)");
4289                                break;
4290                            case ResTable_config::NAVIGATION_DPAD:
4291                                printf(" (dpad)");
4292                                break;
4293                            case ResTable_config::NAVIGATION_TRACKBALL:
4294                                printf(" (trackball)");
4295                                break;
4296                            case ResTable_config::NAVIGATION_WHEEL:
4297                                printf(" (wheel)");
4298                                break;
4299                        }
4300                    }
4301                    if (type->config.screenWidth != 0) {
4302                        printf(" w=%d", dtohs(type->config.screenWidth));
4303                    }
4304                    if (type->config.screenHeight != 0) {
4305                        printf(" h=%d", dtohs(type->config.screenHeight));
4306                    }
4307                    if (type->config.sdkVersion != 0) {
4308                        printf(" sdk=%d", dtohs(type->config.sdkVersion));
4309                    }
4310                    if (type->config.minorVersion != 0) {
4311                        printf(" mver=%d", dtohs(type->config.minorVersion));
4312                    }
4313                    printf("\n");
4314                    size_t entryCount = dtohl(type->entryCount);
4315                    uint32_t entriesStart = dtohl(type->entriesStart);
4316                    if ((entriesStart&0x3) != 0) {
4317                        printf("      NON-INTEGER ResTable_type entriesStart OFFSET: %p\n", (void*)entriesStart);
4318                        continue;
4319                    }
4320                    uint32_t typeSize = dtohl(type->header.size);
4321                    if ((typeSize&0x3) != 0) {
4322                        printf("      NON-INTEGER ResTable_type header.size: %p\n", (void*)typeSize);
4323                        continue;
4324                    }
4325                    for (size_t entryIndex=0; entryIndex<entryCount; entryIndex++) {
4326
4327                        const uint8_t* const end = ((const uint8_t*)type)
4328                            + dtohl(type->header.size);
4329                        const uint32_t* const eindex = (const uint32_t*)
4330                            (((const uint8_t*)type) + dtohs(type->header.headerSize));
4331
4332                        uint32_t thisOffset = dtohl(eindex[entryIndex]);
4333                        if (thisOffset == ResTable_type::NO_ENTRY) {
4334                            continue;
4335                        }
4336
4337                        uint32_t resID = (0xff000000 & ((pkg->package->id)<<24))
4338                                    | (0x00ff0000 & ((typeIndex+1)<<16))
4339                                    | (0x0000ffff & (entryIndex));
4340                        resource_name resName;
4341                        this->getResourceName(resID, &resName);
4342                        printf("        resource 0x%08x %s:%s/%s: ", resID,
4343                                CHAR16_TO_CSTR(resName.package, resName.packageLen),
4344                                CHAR16_TO_CSTR(resName.type, resName.typeLen),
4345                                CHAR16_TO_CSTR(resName.name, resName.nameLen));
4346                        if ((thisOffset&0x3) != 0) {
4347                            printf("NON-INTEGER OFFSET: %p\n", (void*)thisOffset);
4348                            continue;
4349                        }
4350                        if ((thisOffset+sizeof(ResTable_entry)) > typeSize) {
4351                            printf("OFFSET OUT OF BOUNDS: %p+%p (size is %p)\n",
4352                                   (void*)entriesStart, (void*)thisOffset,
4353                                   (void*)typeSize);
4354                            continue;
4355                        }
4356
4357                        const ResTable_entry* ent = (const ResTable_entry*)
4358                            (((const uint8_t*)type) + entriesStart + thisOffset);
4359                        if (((entriesStart + thisOffset)&0x3) != 0) {
4360                            printf("NON-INTEGER ResTable_entry OFFSET: %p\n",
4361                                 (void*)(entriesStart + thisOffset));
4362                            continue;
4363                        }
4364
4365                        uint16_t esize = dtohs(ent->size);
4366                        if ((esize&0x3) != 0) {
4367                            printf("NON-INTEGER ResTable_entry SIZE: %p\n", (void*)esize);
4368                            continue;
4369                        }
4370                        if ((thisOffset+esize) > typeSize) {
4371                            printf("ResTable_entry OUT OF BOUNDS: %p+%p+%p (size is %p)\n",
4372                                   (void*)entriesStart, (void*)thisOffset,
4373                                   (void*)esize, (void*)typeSize);
4374                            continue;
4375                        }
4376
4377                        const Res_value* valuePtr = NULL;
4378                        const ResTable_map_entry* bagPtr = NULL;
4379                        Res_value value;
4380                        if ((dtohs(ent->flags)&ResTable_entry::FLAG_COMPLEX) != 0) {
4381                            printf("<bag>");
4382                            bagPtr = (const ResTable_map_entry*)ent;
4383                        } else {
4384                            valuePtr = (const Res_value*)
4385                                (((const uint8_t*)ent) + esize);
4386                            value.copyFrom_dtoh(*valuePtr);
4387                            printf("t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)",
4388                                   (int)value.dataType, (int)value.data,
4389                                   (int)value.size, (int)value.res0);
4390                        }
4391
4392                        if ((dtohs(ent->flags)&ResTable_entry::FLAG_PUBLIC) != 0) {
4393                            printf(" (PUBLIC)");
4394                        }
4395                        printf("\n");
4396
4397                        if (inclValues) {
4398                            if (valuePtr != NULL) {
4399                                printf("          ");
4400                                print_value(pkg, value);
4401                            } else if (bagPtr != NULL) {
4402                                const int N = dtohl(bagPtr->count);
4403                                const ResTable_map* mapPtr = (const ResTable_map*)
4404                                        (((const uint8_t*)ent) + esize);
4405                                printf("          Parent=0x%08x, Count=%d\n",
4406                                    dtohl(bagPtr->parent.ident), N);
4407                                for (int i=0; i<N; i++) {
4408                                    printf("          #%i (Key=0x%08x): ",
4409                                        i, dtohl(mapPtr->name.ident));
4410                                    value.copyFrom_dtoh(mapPtr->value);
4411                                    print_value(pkg, value);
4412                                    const size_t size = dtohs(mapPtr->value.size);
4413                                    mapPtr = (ResTable_map*)(((const uint8_t*)mapPtr)
4414                                            + size + sizeof(*mapPtr)-sizeof(mapPtr->value));
4415                                }
4416                            }
4417                        }
4418                    }
4419                }
4420            }
4421        }
4422    }
4423}
4424
4425#endif // HAVE_ANDROID_OS
4426
4427}   // namespace android
4428