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