OSDN Git Service

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