OSDN Git Service

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