• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <androidfw/ResourceTypes.h>
21 #include <utils/Atomic.h>
22 #include <utils/ByteOrder.h>
23 #include <utils/Debug.h>
24 #include <utils/Log.h>
25 #include <utils/String16.h>
26 #include <utils/String8.h>
27 #include <utils/TextOutput.h>
28 
29 #include <stdlib.h>
30 #include <string.h>
31 #include <memory.h>
32 #include <ctype.h>
33 #include <stdint.h>
34 
35 #ifndef INT32_MAX
36 #define INT32_MAX ((int32_t)(2147483647))
37 #endif
38 
39 #define POOL_NOISY(x) //x
40 #define XML_NOISY(x) //x
41 #define TABLE_NOISY(x) //x
42 #define TABLE_GETENTRY(x) //x
43 #define TABLE_SUPER_NOISY(x) //x
44 #define LOAD_TABLE_NOISY(x) //x
45 #define TABLE_THEME(x) //x
46 
47 namespace android {
48 
49 #ifdef HAVE_WINSOCK
50 #undef  nhtol
51 #undef  htonl
52 
53 #ifdef HAVE_LITTLE_ENDIAN
54 #define ntohl(x)    ( ((x) << 24) | (((x) >> 24) & 255) | (((x) << 8) & 0xff0000) | (((x) >> 8) & 0xff00) )
55 #define htonl(x)    ntohl(x)
56 #define ntohs(x)    ( (((x) << 8) & 0xff00) | (((x) >> 8) & 255) )
57 #define htons(x)    ntohs(x)
58 #else
59 #define ntohl(x)    (x)
60 #define htonl(x)    (x)
61 #define ntohs(x)    (x)
62 #define htons(x)    (x)
63 #endif
64 #endif
65 
66 #define IDMAP_MAGIC         0x706d6469
67 // size measured in sizeof(uint32_t)
68 #define IDMAP_HEADER_SIZE (ResTable::IDMAP_HEADER_SIZE_BYTES / sizeof(uint32_t))
69 
printToLogFunc(void * cookie,const char * txt)70 static void printToLogFunc(void* cookie, const char* txt)
71 {
72     ALOGV("%s", txt);
73 }
74 
75 // Standard C isspace() is only required to look at the low byte of its input, so
76 // produces incorrect results for UTF-16 characters.  For safety's sake, assume that
77 // any high-byte UTF-16 code point is not whitespace.
isspace16(char16_t c)78 inline int isspace16(char16_t c) {
79     return (c < 0x0080 && isspace(c));
80 }
81 
82 // range checked; guaranteed to NUL-terminate within the stated number of available slots
83 // NOTE: if this truncates the dst string due to running out of space, no attempt is
84 // made to avoid splitting surrogate pairs.
strcpy16_dtoh(uint16_t * dst,const uint16_t * src,size_t avail)85 static void strcpy16_dtoh(uint16_t* dst, const uint16_t* src, size_t avail)
86 {
87     uint16_t* last = dst + avail - 1;
88     while (*src && (dst < last)) {
89         char16_t s = dtohs(*src);
90         *dst++ = s;
91         src++;
92     }
93     *dst = 0;
94 }
95 
validate_chunk(const ResChunk_header * chunk,size_t minSize,const uint8_t * dataEnd,const char * name)96 static status_t validate_chunk(const ResChunk_header* chunk,
97                                size_t minSize,
98                                const uint8_t* dataEnd,
99                                const char* name)
100 {
101     const uint16_t headerSize = dtohs(chunk->headerSize);
102     const uint32_t size = dtohl(chunk->size);
103 
104     if (headerSize >= minSize) {
105         if (headerSize <= size) {
106             if (((headerSize|size)&0x3) == 0) {
107                 if ((ssize_t)size <= (dataEnd-((const uint8_t*)chunk))) {
108                     return NO_ERROR;
109                 }
110                 ALOGW("%s data size %p extends beyond resource end %p.",
111                      name, (void*)size,
112                      (void*)(dataEnd-((const uint8_t*)chunk)));
113                 return BAD_TYPE;
114             }
115             ALOGW("%s size 0x%x or headerSize 0x%x is not on an integer boundary.",
116                  name, (int)size, (int)headerSize);
117             return BAD_TYPE;
118         }
119         ALOGW("%s size %p is smaller than header size %p.",
120              name, (void*)size, (void*)(int)headerSize);
121         return BAD_TYPE;
122     }
123     ALOGW("%s header size %p is too small.",
124          name, (void*)(int)headerSize);
125     return BAD_TYPE;
126 }
127 
copyFrom_dtoh(const Res_value & src)128 inline void Res_value::copyFrom_dtoh(const Res_value& src)
129 {
130     size = dtohs(src.size);
131     res0 = src.res0;
132     dataType = src.dataType;
133     data = dtohl(src.data);
134 }
135 
deviceToFile()136 void Res_png_9patch::deviceToFile()
137 {
138     for (int i = 0; i < numXDivs; i++) {
139         xDivs[i] = htonl(xDivs[i]);
140     }
141     for (int i = 0; i < numYDivs; i++) {
142         yDivs[i] = htonl(yDivs[i]);
143     }
144     paddingLeft = htonl(paddingLeft);
145     paddingRight = htonl(paddingRight);
146     paddingTop = htonl(paddingTop);
147     paddingBottom = htonl(paddingBottom);
148     for (int i=0; i<numColors; i++) {
149         colors[i] = htonl(colors[i]);
150     }
151 }
152 
fileToDevice()153 void Res_png_9patch::fileToDevice()
154 {
155     for (int i = 0; i < numXDivs; i++) {
156         xDivs[i] = ntohl(xDivs[i]);
157     }
158     for (int i = 0; i < numYDivs; i++) {
159         yDivs[i] = ntohl(yDivs[i]);
160     }
161     paddingLeft = ntohl(paddingLeft);
162     paddingRight = ntohl(paddingRight);
163     paddingTop = ntohl(paddingTop);
164     paddingBottom = ntohl(paddingBottom);
165     for (int i=0; i<numColors; i++) {
166         colors[i] = ntohl(colors[i]);
167     }
168 }
169 
serializedSize()170 size_t Res_png_9patch::serializedSize()
171 {
172     // The size of this struct is 32 bytes on the 32-bit target system
173     // 4 * int8_t
174     // 4 * int32_t
175     // 3 * pointer
176     return 32
177             + numXDivs * sizeof(int32_t)
178             + numYDivs * sizeof(int32_t)
179             + numColors * sizeof(uint32_t);
180 }
181 
serialize()182 void* Res_png_9patch::serialize()
183 {
184     // Use calloc since we're going to leave a few holes in the data
185     // and want this to run cleanly under valgrind
186     void* newData = calloc(1, serializedSize());
187     serialize(newData);
188     return newData;
189 }
190 
serialize(void * outData)191 void Res_png_9patch::serialize(void * outData)
192 {
193     char* data = (char*) outData;
194     memmove(data, &wasDeserialized, 4);     // copy  wasDeserialized, numXDivs, numYDivs, numColors
195     memmove(data + 12, &paddingLeft, 16);   // copy paddingXXXX
196     data += 32;
197 
198     memmove(data, this->xDivs, numXDivs * sizeof(int32_t));
199     data +=  numXDivs * sizeof(int32_t);
200     memmove(data, this->yDivs, numYDivs * sizeof(int32_t));
201     data +=  numYDivs * sizeof(int32_t);
202     memmove(data, this->colors, numColors * sizeof(uint32_t));
203 }
204 
deserializeInternal(const void * inData,Res_png_9patch * outData)205 static void deserializeInternal(const void* inData, Res_png_9patch* outData) {
206     char* patch = (char*) inData;
207     if (inData != outData) {
208         memmove(&outData->wasDeserialized, patch, 4);     // copy  wasDeserialized, numXDivs, numYDivs, numColors
209         memmove(&outData->paddingLeft, patch + 12, 4);     // copy  wasDeserialized, numXDivs, numYDivs, numColors
210     }
211     outData->wasDeserialized = true;
212     char* data = (char*)outData;
213     data +=  sizeof(Res_png_9patch);
214     outData->xDivs = (int32_t*) data;
215     data +=  outData->numXDivs * sizeof(int32_t);
216     outData->yDivs = (int32_t*) data;
217     data +=  outData->numYDivs * sizeof(int32_t);
218     outData->colors = (uint32_t*) data;
219 }
220 
assertIdmapHeader(const uint32_t * map,size_t sizeBytes)221 static bool assertIdmapHeader(const uint32_t* map, size_t sizeBytes)
222 {
223     if (sizeBytes < ResTable::IDMAP_HEADER_SIZE_BYTES) {
224         ALOGW("idmap assertion failed: size=%d bytes\n", (int)sizeBytes);
225         return false;
226     }
227     if (*map != htodl(IDMAP_MAGIC)) { // htodl: map data expected to be in correct endianess
228         ALOGW("idmap assertion failed: invalid magic found (is 0x%08x, expected 0x%08x)\n",
229              *map, htodl(IDMAP_MAGIC));
230         return false;
231     }
232     return true;
233 }
234 
idmapLookup(const uint32_t * map,size_t sizeBytes,uint32_t key,uint32_t * outValue)235 static status_t idmapLookup(const uint32_t* map, size_t sizeBytes, uint32_t key, uint32_t* outValue)
236 {
237     // see README for details on the format of map
238     if (!assertIdmapHeader(map, sizeBytes)) {
239         return UNKNOWN_ERROR;
240     }
241     map = map + IDMAP_HEADER_SIZE; // skip ahead to data segment
242     // size of data block, in uint32_t
243     const size_t size = (sizeBytes - ResTable::IDMAP_HEADER_SIZE_BYTES) / sizeof(uint32_t);
244     const uint32_t type = Res_GETTYPE(key) + 1; // add one, idmap stores "public" type id
245     const uint32_t entry = Res_GETENTRY(key);
246     const uint32_t typeCount = *map;
247 
248     if (type > typeCount) {
249         ALOGW("Resource ID map: type=%d exceeds number of types=%d\n", type, typeCount);
250         return UNKNOWN_ERROR;
251     }
252     if (typeCount > size) {
253         ALOGW("Resource ID map: number of types=%d exceeds size of map=%d\n", typeCount, (int)size);
254         return UNKNOWN_ERROR;
255     }
256     const uint32_t typeOffset = map[type];
257     if (typeOffset == 0) {
258         *outValue = 0;
259         return NO_ERROR;
260     }
261     if (typeOffset + 1 > size) {
262         ALOGW("Resource ID map: type offset=%d exceeds reasonable value, size of map=%d\n",
263              typeOffset, (int)size);
264         return UNKNOWN_ERROR;
265     }
266     const uint32_t entryCount = map[typeOffset];
267     const uint32_t entryOffset = map[typeOffset + 1];
268     if (entryCount == 0 || entry < entryOffset || entry - entryOffset > entryCount - 1) {
269         *outValue = 0;
270         return NO_ERROR;
271     }
272     const uint32_t index = typeOffset + 2 + entry - entryOffset;
273     if (index > size) {
274         ALOGW("Resource ID map: entry index=%d exceeds size of map=%d\n", index, (int)size);
275         *outValue = 0;
276         return NO_ERROR;
277     }
278     *outValue = map[index];
279 
280     return NO_ERROR;
281 }
282 
getIdmapPackageId(const uint32_t * map,size_t mapSize,uint32_t * outId)283 static status_t getIdmapPackageId(const uint32_t* map, size_t mapSize, uint32_t *outId)
284 {
285     if (!assertIdmapHeader(map, mapSize)) {
286         return UNKNOWN_ERROR;
287     }
288     const uint32_t* p = map + IDMAP_HEADER_SIZE + 1;
289     while (*p == 0) {
290         ++p;
291     }
292     *outId = (map[*p + IDMAP_HEADER_SIZE + 2] >> 24) & 0x000000ff;
293     return NO_ERROR;
294 }
295 
deserialize(const void * inData)296 Res_png_9patch* Res_png_9patch::deserialize(const void* inData)
297 {
298     if (sizeof(void*) != sizeof(int32_t)) {
299         ALOGE("Cannot deserialize on non 32-bit system\n");
300         return NULL;
301     }
302     deserializeInternal(inData, (Res_png_9patch*) inData);
303     return (Res_png_9patch*) inData;
304 }
305 
306 // --------------------------------------------------------------------
307 // --------------------------------------------------------------------
308 // --------------------------------------------------------------------
309 
ResStringPool()310 ResStringPool::ResStringPool()
311     : mError(NO_INIT), mOwnedData(NULL), mHeader(NULL), mCache(NULL)
312 {
313 }
314 
ResStringPool(const void * data,size_t size,bool copyData)315 ResStringPool::ResStringPool(const void* data, size_t size, bool copyData)
316     : mError(NO_INIT), mOwnedData(NULL), mHeader(NULL), mCache(NULL)
317 {
318     setTo(data, size, copyData);
319 }
320 
~ResStringPool()321 ResStringPool::~ResStringPool()
322 {
323     uninit();
324 }
325 
setTo(const void * data,size_t size,bool copyData)326 status_t ResStringPool::setTo(const void* data, size_t size, bool copyData)
327 {
328     if (!data || !size) {
329         return (mError=BAD_TYPE);
330     }
331 
332     uninit();
333 
334     const bool notDeviceEndian = htods(0xf0) != 0xf0;
335 
336     if (copyData || notDeviceEndian) {
337         mOwnedData = malloc(size);
338         if (mOwnedData == NULL) {
339             return (mError=NO_MEMORY);
340         }
341         memcpy(mOwnedData, data, size);
342         data = mOwnedData;
343     }
344 
345     mHeader = (const ResStringPool_header*)data;
346 
347     if (notDeviceEndian) {
348         ResStringPool_header* h = const_cast<ResStringPool_header*>(mHeader);
349         h->header.headerSize = dtohs(mHeader->header.headerSize);
350         h->header.type = dtohs(mHeader->header.type);
351         h->header.size = dtohl(mHeader->header.size);
352         h->stringCount = dtohl(mHeader->stringCount);
353         h->styleCount = dtohl(mHeader->styleCount);
354         h->flags = dtohl(mHeader->flags);
355         h->stringsStart = dtohl(mHeader->stringsStart);
356         h->stylesStart = dtohl(mHeader->stylesStart);
357     }
358 
359     if (mHeader->header.headerSize > mHeader->header.size
360             || mHeader->header.size > size) {
361         ALOGW("Bad string block: header size %d or total size %d is larger than data size %d\n",
362                 (int)mHeader->header.headerSize, (int)mHeader->header.size, (int)size);
363         return (mError=BAD_TYPE);
364     }
365     mSize = mHeader->header.size;
366     mEntries = (const uint32_t*)
367         (((const uint8_t*)data)+mHeader->header.headerSize);
368 
369     if (mHeader->stringCount > 0) {
370         if ((mHeader->stringCount*sizeof(uint32_t) < mHeader->stringCount)  // uint32 overflow?
371             || (mHeader->header.headerSize+(mHeader->stringCount*sizeof(uint32_t)))
372                 > size) {
373             ALOGW("Bad string block: entry of %d items extends past data size %d\n",
374                     (int)(mHeader->header.headerSize+(mHeader->stringCount*sizeof(uint32_t))),
375                     (int)size);
376             return (mError=BAD_TYPE);
377         }
378 
379         size_t charSize;
380         if (mHeader->flags&ResStringPool_header::UTF8_FLAG) {
381             charSize = sizeof(uint8_t);
382             mCache = (char16_t**)calloc(mHeader->stringCount, sizeof(char16_t**));
383         } else {
384             charSize = sizeof(char16_t);
385         }
386 
387         mStrings = (const void*)
388             (((const uint8_t*)data)+mHeader->stringsStart);
389         if (mHeader->stringsStart >= (mHeader->header.size-sizeof(uint16_t))) {
390             ALOGW("Bad string block: string pool starts at %d, after total size %d\n",
391                     (int)mHeader->stringsStart, (int)mHeader->header.size);
392             return (mError=BAD_TYPE);
393         }
394         if (mHeader->styleCount == 0) {
395             mStringPoolSize =
396                 (mHeader->header.size-mHeader->stringsStart)/charSize;
397         } else {
398             // check invariant: styles starts before end of data
399             if (mHeader->stylesStart >= (mHeader->header.size-sizeof(uint16_t))) {
400                 ALOGW("Bad style block: style block starts at %d past data size of %d\n",
401                     (int)mHeader->stylesStart, (int)mHeader->header.size);
402                 return (mError=BAD_TYPE);
403             }
404             // check invariant: styles follow the strings
405             if (mHeader->stylesStart <= mHeader->stringsStart) {
406                 ALOGW("Bad style block: style block starts at %d, before strings at %d\n",
407                     (int)mHeader->stylesStart, (int)mHeader->stringsStart);
408                 return (mError=BAD_TYPE);
409             }
410             mStringPoolSize =
411                 (mHeader->stylesStart-mHeader->stringsStart)/charSize;
412         }
413 
414         // check invariant: stringCount > 0 requires a string pool to exist
415         if (mStringPoolSize == 0) {
416             ALOGW("Bad string block: stringCount is %d but pool size is 0\n", (int)mHeader->stringCount);
417             return (mError=BAD_TYPE);
418         }
419 
420         if (notDeviceEndian) {
421             size_t i;
422             uint32_t* e = const_cast<uint32_t*>(mEntries);
423             for (i=0; i<mHeader->stringCount; i++) {
424                 e[i] = dtohl(mEntries[i]);
425             }
426             if (!(mHeader->flags&ResStringPool_header::UTF8_FLAG)) {
427                 const char16_t* strings = (const char16_t*)mStrings;
428                 char16_t* s = const_cast<char16_t*>(strings);
429                 for (i=0; i<mStringPoolSize; i++) {
430                     s[i] = dtohs(strings[i]);
431                 }
432             }
433         }
434 
435         if ((mHeader->flags&ResStringPool_header::UTF8_FLAG &&
436                 ((uint8_t*)mStrings)[mStringPoolSize-1] != 0) ||
437                 (!mHeader->flags&ResStringPool_header::UTF8_FLAG &&
438                 ((char16_t*)mStrings)[mStringPoolSize-1] != 0)) {
439             ALOGW("Bad string block: last string is not 0-terminated\n");
440             return (mError=BAD_TYPE);
441         }
442     } else {
443         mStrings = NULL;
444         mStringPoolSize = 0;
445     }
446 
447     if (mHeader->styleCount > 0) {
448         mEntryStyles = mEntries + mHeader->stringCount;
449         // invariant: integer overflow in calculating mEntryStyles
450         if (mEntryStyles < mEntries) {
451             ALOGW("Bad string block: integer overflow finding styles\n");
452             return (mError=BAD_TYPE);
453         }
454 
455         if (((const uint8_t*)mEntryStyles-(const uint8_t*)mHeader) > (int)size) {
456             ALOGW("Bad string block: entry of %d styles extends past data size %d\n",
457                     (int)((const uint8_t*)mEntryStyles-(const uint8_t*)mHeader),
458                     (int)size);
459             return (mError=BAD_TYPE);
460         }
461         mStyles = (const uint32_t*)
462             (((const uint8_t*)data)+mHeader->stylesStart);
463         if (mHeader->stylesStart >= mHeader->header.size) {
464             ALOGW("Bad string block: style pool starts %d, after total size %d\n",
465                     (int)mHeader->stylesStart, (int)mHeader->header.size);
466             return (mError=BAD_TYPE);
467         }
468         mStylePoolSize =
469             (mHeader->header.size-mHeader->stylesStart)/sizeof(uint32_t);
470 
471         if (notDeviceEndian) {
472             size_t i;
473             uint32_t* e = const_cast<uint32_t*>(mEntryStyles);
474             for (i=0; i<mHeader->styleCount; i++) {
475                 e[i] = dtohl(mEntryStyles[i]);
476             }
477             uint32_t* s = const_cast<uint32_t*>(mStyles);
478             for (i=0; i<mStylePoolSize; i++) {
479                 s[i] = dtohl(mStyles[i]);
480             }
481         }
482 
483         const ResStringPool_span endSpan = {
484             { htodl(ResStringPool_span::END) },
485             htodl(ResStringPool_span::END), htodl(ResStringPool_span::END)
486         };
487         if (memcmp(&mStyles[mStylePoolSize-(sizeof(endSpan)/sizeof(uint32_t))],
488                    &endSpan, sizeof(endSpan)) != 0) {
489             ALOGW("Bad string block: last style is not 0xFFFFFFFF-terminated\n");
490             return (mError=BAD_TYPE);
491         }
492     } else {
493         mEntryStyles = NULL;
494         mStyles = NULL;
495         mStylePoolSize = 0;
496     }
497 
498     return (mError=NO_ERROR);
499 }
500 
getError() const501 status_t ResStringPool::getError() const
502 {
503     return mError;
504 }
505 
uninit()506 void ResStringPool::uninit()
507 {
508     mError = NO_INIT;
509     if (mOwnedData) {
510         free(mOwnedData);
511         mOwnedData = NULL;
512     }
513     if (mHeader != NULL && mCache != NULL) {
514         for (size_t x = 0; x < mHeader->stringCount; x++) {
515             if (mCache[x] != NULL) {
516                 free(mCache[x]);
517                 mCache[x] = NULL;
518             }
519         }
520         free(mCache);
521         mCache = NULL;
522     }
523 }
524 
525 /**
526  * Strings in UTF-16 format have length indicated by a length encoded in the
527  * stored data. It is either 1 or 2 characters of length data. This allows a
528  * maximum length of 0x7FFFFFF (2147483647 bytes), but if you're storing that
529  * much data in a string, you're abusing them.
530  *
531  * If the high bit is set, then there are two characters or 4 bytes of length
532  * data encoded. In that case, drop the high bit of the first character and
533  * add it together with the next character.
534  */
535 static inline size_t
decodeLength(const char16_t ** str)536 decodeLength(const char16_t** str)
537 {
538     size_t len = **str;
539     if ((len & 0x8000) != 0) {
540         (*str)++;
541         len = ((len & 0x7FFF) << 16) | **str;
542     }
543     (*str)++;
544     return len;
545 }
546 
547 /**
548  * Strings in UTF-8 format have length indicated by a length encoded in the
549  * stored data. It is either 1 or 2 characters of length data. This allows a
550  * maximum length of 0x7FFF (32767 bytes), but you should consider storing
551  * text in another way if you're using that much data in a single string.
552  *
553  * If the high bit is set, then there are two characters or 2 bytes of length
554  * data encoded. In that case, drop the high bit of the first character and
555  * add it together with the next character.
556  */
557 static inline size_t
decodeLength(const uint8_t ** str)558 decodeLength(const uint8_t** str)
559 {
560     size_t len = **str;
561     if ((len & 0x80) != 0) {
562         (*str)++;
563         len = ((len & 0x7F) << 8) | **str;
564     }
565     (*str)++;
566     return len;
567 }
568 
stringAt(size_t idx,size_t * u16len) const569 const uint16_t* ResStringPool::stringAt(size_t idx, size_t* u16len) const
570 {
571     if (mError == NO_ERROR && idx < mHeader->stringCount) {
572         const bool isUTF8 = (mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0;
573         const uint32_t off = mEntries[idx]/(isUTF8?sizeof(char):sizeof(char16_t));
574         if (off < (mStringPoolSize-1)) {
575             if (!isUTF8) {
576                 const char16_t* strings = (char16_t*)mStrings;
577                 const char16_t* str = strings+off;
578 
579                 *u16len = decodeLength(&str);
580                 if ((uint32_t)(str+*u16len-strings) < mStringPoolSize) {
581                     return str;
582                 } else {
583                     ALOGW("Bad string block: string #%d extends to %d, past end at %d\n",
584                             (int)idx, (int)(str+*u16len-strings), (int)mStringPoolSize);
585                 }
586             } else {
587                 const uint8_t* strings = (uint8_t*)mStrings;
588                 const uint8_t* u8str = strings+off;
589 
590                 *u16len = decodeLength(&u8str);
591                 size_t u8len = decodeLength(&u8str);
592 
593                 // encLen must be less than 0x7FFF due to encoding.
594                 if ((uint32_t)(u8str+u8len-strings) < mStringPoolSize) {
595                     AutoMutex lock(mDecodeLock);
596 
597                     if (mCache[idx] != NULL) {
598                         return mCache[idx];
599                     }
600 
601                     ssize_t actualLen = utf8_to_utf16_length(u8str, u8len);
602                     if (actualLen < 0 || (size_t)actualLen != *u16len) {
603                         ALOGW("Bad string block: string #%lld decoded length is not correct "
604                                 "%lld vs %llu\n",
605                                 (long long)idx, (long long)actualLen, (long long)*u16len);
606                         return NULL;
607                     }
608 
609                     char16_t *u16str = (char16_t *)calloc(*u16len+1, sizeof(char16_t));
610                     if (!u16str) {
611                         ALOGW("No memory when trying to allocate decode cache for string #%d\n",
612                                 (int)idx);
613                         return NULL;
614                     }
615 
616                     utf8_to_utf16(u8str, u8len, u16str);
617                     mCache[idx] = u16str;
618                     return u16str;
619                 } else {
620                     ALOGW("Bad string block: string #%lld extends to %lld, past end at %lld\n",
621                             (long long)idx, (long long)(u8str+u8len-strings),
622                             (long long)mStringPoolSize);
623                 }
624             }
625         } else {
626             ALOGW("Bad string block: string #%d entry is at %d, past end at %d\n",
627                     (int)idx, (int)(off*sizeof(uint16_t)),
628                     (int)(mStringPoolSize*sizeof(uint16_t)));
629         }
630     }
631     return NULL;
632 }
633 
string8At(size_t idx,size_t * outLen) const634 const char* ResStringPool::string8At(size_t idx, size_t* outLen) const
635 {
636     if (mError == NO_ERROR && idx < mHeader->stringCount) {
637         const bool isUTF8 = (mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0;
638         const uint32_t off = mEntries[idx]/(isUTF8?sizeof(char):sizeof(char16_t));
639         if (off < (mStringPoolSize-1)) {
640             if (isUTF8) {
641                 const uint8_t* strings = (uint8_t*)mStrings;
642                 const uint8_t* str = strings+off;
643                 *outLen = decodeLength(&str);
644                 size_t encLen = decodeLength(&str);
645                 if ((uint32_t)(str+encLen-strings) < mStringPoolSize) {
646                     return (const char*)str;
647                 } else {
648                     ALOGW("Bad string block: string #%d extends to %d, past end at %d\n",
649                             (int)idx, (int)(str+encLen-strings), (int)mStringPoolSize);
650                 }
651             }
652         } else {
653             ALOGW("Bad string block: string #%d entry is at %d, past end at %d\n",
654                     (int)idx, (int)(off*sizeof(uint16_t)),
655                     (int)(mStringPoolSize*sizeof(uint16_t)));
656         }
657     }
658     return NULL;
659 }
660 
string8ObjectAt(size_t idx) const661 const String8 ResStringPool::string8ObjectAt(size_t idx) const
662 {
663     size_t len;
664     const char *str = (const char*)string8At(idx, &len);
665     if (str != NULL) {
666         return String8(str);
667     }
668     return String8(stringAt(idx, &len));
669 }
670 
styleAt(const ResStringPool_ref & ref) const671 const ResStringPool_span* ResStringPool::styleAt(const ResStringPool_ref& ref) const
672 {
673     return styleAt(ref.index);
674 }
675 
styleAt(size_t idx) const676 const ResStringPool_span* ResStringPool::styleAt(size_t idx) const
677 {
678     if (mError == NO_ERROR && idx < mHeader->styleCount) {
679         const uint32_t off = (mEntryStyles[idx]/sizeof(uint32_t));
680         if (off < mStylePoolSize) {
681             return (const ResStringPool_span*)(mStyles+off);
682         } else {
683             ALOGW("Bad string block: style #%d entry is at %d, past end at %d\n",
684                     (int)idx, (int)(off*sizeof(uint32_t)),
685                     (int)(mStylePoolSize*sizeof(uint32_t)));
686         }
687     }
688     return NULL;
689 }
690 
indexOfString(const char16_t * str,size_t strLen) const691 ssize_t ResStringPool::indexOfString(const char16_t* str, size_t strLen) const
692 {
693     if (mError != NO_ERROR) {
694         return mError;
695     }
696 
697     size_t len;
698 
699     // TODO optimize searching for UTF-8 strings taking into account
700     // the cache fill to determine when to convert the searched-for
701     // string key to UTF-8.
702 
703     if (mHeader->flags&ResStringPool_header::SORTED_FLAG) {
704         // Do a binary search for the string...
705         ssize_t l = 0;
706         ssize_t h = mHeader->stringCount-1;
707 
708         ssize_t mid;
709         while (l <= h) {
710             mid = l + (h - l)/2;
711             const char16_t* s = stringAt(mid, &len);
712             int c = s ? strzcmp16(s, len, str, strLen) : -1;
713             POOL_NOISY(printf("Looking for %s, at %s, cmp=%d, l/mid/h=%d/%d/%d\n",
714                          String8(str).string(),
715                          String8(s).string(),
716                          c, (int)l, (int)mid, (int)h));
717             if (c == 0) {
718                 return mid;
719             } else if (c < 0) {
720                 l = mid + 1;
721             } else {
722                 h = mid - 1;
723             }
724         }
725     } else {
726         // It is unusual to get the ID from an unsorted string block...
727         // most often this happens because we want to get IDs for style
728         // span tags; since those always appear at the end of the string
729         // block, start searching at the back.
730         for (int i=mHeader->stringCount-1; i>=0; i--) {
731             const char16_t* s = stringAt(i, &len);
732             POOL_NOISY(printf("Looking for %s, at %s, i=%d\n",
733                          String8(str, strLen).string(),
734                          String8(s).string(),
735                          i));
736             if (s && strzcmp16(s, len, str, strLen) == 0) {
737                 return i;
738             }
739         }
740     }
741 
742     return NAME_NOT_FOUND;
743 }
744 
size() const745 size_t ResStringPool::size() const
746 {
747     return (mError == NO_ERROR) ? mHeader->stringCount : 0;
748 }
749 
styleCount() const750 size_t ResStringPool::styleCount() const
751 {
752     return (mError == NO_ERROR) ? mHeader->styleCount : 0;
753 }
754 
bytes() const755 size_t ResStringPool::bytes() const
756 {
757     return (mError == NO_ERROR) ? mHeader->header.size : 0;
758 }
759 
isSorted() const760 bool ResStringPool::isSorted() const
761 {
762     return (mHeader->flags&ResStringPool_header::SORTED_FLAG)!=0;
763 }
764 
isUTF8() const765 bool ResStringPool::isUTF8() const
766 {
767     return (mHeader->flags&ResStringPool_header::UTF8_FLAG)!=0;
768 }
769 
770 // --------------------------------------------------------------------
771 // --------------------------------------------------------------------
772 // --------------------------------------------------------------------
773 
ResXMLParser(const ResXMLTree & tree)774 ResXMLParser::ResXMLParser(const ResXMLTree& tree)
775     : mTree(tree), mEventCode(BAD_DOCUMENT)
776 {
777 }
778 
restart()779 void ResXMLParser::restart()
780 {
781     mCurNode = NULL;
782     mEventCode = mTree.mError == NO_ERROR ? START_DOCUMENT : BAD_DOCUMENT;
783 }
getStrings() const784 const ResStringPool& ResXMLParser::getStrings() const
785 {
786     return mTree.mStrings;
787 }
788 
getEventType() const789 ResXMLParser::event_code_t ResXMLParser::getEventType() const
790 {
791     return mEventCode;
792 }
793 
next()794 ResXMLParser::event_code_t ResXMLParser::next()
795 {
796     if (mEventCode == START_DOCUMENT) {
797         mCurNode = mTree.mRootNode;
798         mCurExt = mTree.mRootExt;
799         return (mEventCode=mTree.mRootCode);
800     } else if (mEventCode >= FIRST_CHUNK_CODE) {
801         return nextNode();
802     }
803     return mEventCode;
804 }
805 
getCommentID() const806 int32_t ResXMLParser::getCommentID() const
807 {
808     return mCurNode != NULL ? dtohl(mCurNode->comment.index) : -1;
809 }
810 
getComment(size_t * outLen) const811 const uint16_t* ResXMLParser::getComment(size_t* outLen) const
812 {
813     int32_t id = getCommentID();
814     return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
815 }
816 
getLineNumber() const817 uint32_t ResXMLParser::getLineNumber() const
818 {
819     return mCurNode != NULL ? dtohl(mCurNode->lineNumber) : -1;
820 }
821 
getTextID() const822 int32_t ResXMLParser::getTextID() const
823 {
824     if (mEventCode == TEXT) {
825         return dtohl(((const ResXMLTree_cdataExt*)mCurExt)->data.index);
826     }
827     return -1;
828 }
829 
getText(size_t * outLen) const830 const uint16_t* ResXMLParser::getText(size_t* outLen) const
831 {
832     int32_t id = getTextID();
833     return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
834 }
835 
getTextValue(Res_value * outValue) const836 ssize_t ResXMLParser::getTextValue(Res_value* outValue) const
837 {
838     if (mEventCode == TEXT) {
839         outValue->copyFrom_dtoh(((const ResXMLTree_cdataExt*)mCurExt)->typedData);
840         return sizeof(Res_value);
841     }
842     return BAD_TYPE;
843 }
844 
getNamespacePrefixID() const845 int32_t ResXMLParser::getNamespacePrefixID() const
846 {
847     if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) {
848         return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->prefix.index);
849     }
850     return -1;
851 }
852 
getNamespacePrefix(size_t * outLen) const853 const uint16_t* ResXMLParser::getNamespacePrefix(size_t* outLen) const
854 {
855     int32_t id = getNamespacePrefixID();
856     //printf("prefix=%d  event=%p\n", id, mEventCode);
857     return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
858 }
859 
getNamespaceUriID() const860 int32_t ResXMLParser::getNamespaceUriID() const
861 {
862     if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) {
863         return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->uri.index);
864     }
865     return -1;
866 }
867 
getNamespaceUri(size_t * outLen) const868 const uint16_t* ResXMLParser::getNamespaceUri(size_t* outLen) const
869 {
870     int32_t id = getNamespaceUriID();
871     //printf("uri=%d  event=%p\n", id, mEventCode);
872     return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
873 }
874 
getElementNamespaceID() const875 int32_t ResXMLParser::getElementNamespaceID() const
876 {
877     if (mEventCode == START_TAG) {
878         return dtohl(((const ResXMLTree_attrExt*)mCurExt)->ns.index);
879     }
880     if (mEventCode == END_TAG) {
881         return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->ns.index);
882     }
883     return -1;
884 }
885 
getElementNamespace(size_t * outLen) const886 const uint16_t* ResXMLParser::getElementNamespace(size_t* outLen) const
887 {
888     int32_t id = getElementNamespaceID();
889     return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
890 }
891 
getElementNameID() const892 int32_t ResXMLParser::getElementNameID() const
893 {
894     if (mEventCode == START_TAG) {
895         return dtohl(((const ResXMLTree_attrExt*)mCurExt)->name.index);
896     }
897     if (mEventCode == END_TAG) {
898         return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->name.index);
899     }
900     return -1;
901 }
902 
getElementName(size_t * outLen) const903 const uint16_t* ResXMLParser::getElementName(size_t* outLen) const
904 {
905     int32_t id = getElementNameID();
906     return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
907 }
908 
getAttributeCount() const909 size_t ResXMLParser::getAttributeCount() const
910 {
911     if (mEventCode == START_TAG) {
912         return dtohs(((const ResXMLTree_attrExt*)mCurExt)->attributeCount);
913     }
914     return 0;
915 }
916 
getAttributeNamespaceID(size_t idx) const917 int32_t ResXMLParser::getAttributeNamespaceID(size_t idx) const
918 {
919     if (mEventCode == START_TAG) {
920         const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
921         if (idx < dtohs(tag->attributeCount)) {
922             const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
923                 (((const uint8_t*)tag)
924                  + dtohs(tag->attributeStart)
925                  + (dtohs(tag->attributeSize)*idx));
926             return dtohl(attr->ns.index);
927         }
928     }
929     return -2;
930 }
931 
getAttributeNamespace(size_t idx,size_t * outLen) const932 const uint16_t* ResXMLParser::getAttributeNamespace(size_t idx, size_t* outLen) const
933 {
934     int32_t id = getAttributeNamespaceID(idx);
935     //printf("attribute namespace=%d  idx=%d  event=%p\n", id, idx, mEventCode);
936     //XML_NOISY(printf("getAttributeNamespace 0x%x=0x%x\n", idx, id));
937     return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
938 }
939 
getAttributeNameID(size_t idx) const940 int32_t ResXMLParser::getAttributeNameID(size_t idx) const
941 {
942     if (mEventCode == START_TAG) {
943         const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
944         if (idx < dtohs(tag->attributeCount)) {
945             const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
946                 (((const uint8_t*)tag)
947                  + dtohs(tag->attributeStart)
948                  + (dtohs(tag->attributeSize)*idx));
949             return dtohl(attr->name.index);
950         }
951     }
952     return -1;
953 }
954 
getAttributeName(size_t idx,size_t * outLen) const955 const uint16_t* ResXMLParser::getAttributeName(size_t idx, size_t* outLen) const
956 {
957     int32_t id = getAttributeNameID(idx);
958     //printf("attribute name=%d  idx=%d  event=%p\n", id, idx, mEventCode);
959     //XML_NOISY(printf("getAttributeName 0x%x=0x%x\n", idx, id));
960     return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
961 }
962 
getAttributeNameResID(size_t idx) const963 uint32_t ResXMLParser::getAttributeNameResID(size_t idx) const
964 {
965     int32_t id = getAttributeNameID(idx);
966     if (id >= 0 && (size_t)id < mTree.mNumResIds) {
967         return dtohl(mTree.mResIds[id]);
968     }
969     return 0;
970 }
971 
getAttributeValueStringID(size_t idx) const972 int32_t ResXMLParser::getAttributeValueStringID(size_t idx) const
973 {
974     if (mEventCode == START_TAG) {
975         const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
976         if (idx < dtohs(tag->attributeCount)) {
977             const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
978                 (((const uint8_t*)tag)
979                  + dtohs(tag->attributeStart)
980                  + (dtohs(tag->attributeSize)*idx));
981             return dtohl(attr->rawValue.index);
982         }
983     }
984     return -1;
985 }
986 
getAttributeStringValue(size_t idx,size_t * outLen) const987 const uint16_t* ResXMLParser::getAttributeStringValue(size_t idx, size_t* outLen) const
988 {
989     int32_t id = getAttributeValueStringID(idx);
990     //XML_NOISY(printf("getAttributeValue 0x%x=0x%x\n", idx, id));
991     return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
992 }
993 
getAttributeDataType(size_t idx) const994 int32_t ResXMLParser::getAttributeDataType(size_t idx) const
995 {
996     if (mEventCode == START_TAG) {
997         const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
998         if (idx < dtohs(tag->attributeCount)) {
999             const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1000                 (((const uint8_t*)tag)
1001                  + dtohs(tag->attributeStart)
1002                  + (dtohs(tag->attributeSize)*idx));
1003             return attr->typedValue.dataType;
1004         }
1005     }
1006     return Res_value::TYPE_NULL;
1007 }
1008 
getAttributeData(size_t idx) const1009 int32_t ResXMLParser::getAttributeData(size_t idx) const
1010 {
1011     if (mEventCode == START_TAG) {
1012         const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1013         if (idx < dtohs(tag->attributeCount)) {
1014             const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1015                 (((const uint8_t*)tag)
1016                  + dtohs(tag->attributeStart)
1017                  + (dtohs(tag->attributeSize)*idx));
1018             return dtohl(attr->typedValue.data);
1019         }
1020     }
1021     return 0;
1022 }
1023 
getAttributeValue(size_t idx,Res_value * outValue) const1024 ssize_t ResXMLParser::getAttributeValue(size_t idx, Res_value* outValue) const
1025 {
1026     if (mEventCode == START_TAG) {
1027         const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1028         if (idx < dtohs(tag->attributeCount)) {
1029             const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1030                 (((const uint8_t*)tag)
1031                  + dtohs(tag->attributeStart)
1032                  + (dtohs(tag->attributeSize)*idx));
1033             outValue->copyFrom_dtoh(attr->typedValue);
1034             return sizeof(Res_value);
1035         }
1036     }
1037     return BAD_TYPE;
1038 }
1039 
indexOfAttribute(const char * ns,const char * attr) const1040 ssize_t ResXMLParser::indexOfAttribute(const char* ns, const char* attr) const
1041 {
1042     String16 nsStr(ns != NULL ? ns : "");
1043     String16 attrStr(attr);
1044     return indexOfAttribute(ns ? nsStr.string() : NULL, ns ? nsStr.size() : 0,
1045                             attrStr.string(), attrStr.size());
1046 }
1047 
indexOfAttribute(const char16_t * ns,size_t nsLen,const char16_t * attr,size_t attrLen) const1048 ssize_t ResXMLParser::indexOfAttribute(const char16_t* ns, size_t nsLen,
1049                                        const char16_t* attr, size_t attrLen) const
1050 {
1051     if (mEventCode == START_TAG) {
1052         const size_t N = getAttributeCount();
1053         for (size_t i=0; i<N; i++) {
1054             size_t curNsLen, curAttrLen;
1055             const char16_t* curNs = getAttributeNamespace(i, &curNsLen);
1056             const char16_t* curAttr = getAttributeName(i, &curAttrLen);
1057             //printf("%d: ns=%p attr=%p curNs=%p curAttr=%p\n",
1058             //       i, ns, attr, curNs, curAttr);
1059             //printf(" --> attr=%s, curAttr=%s\n",
1060             //       String8(attr).string(), String8(curAttr).string());
1061             if (attr && curAttr && (strzcmp16(attr, attrLen, curAttr, curAttrLen) == 0)) {
1062                 if (ns == NULL) {
1063                     if (curNs == NULL) return i;
1064                 } else if (curNs != NULL) {
1065                     //printf(" --> ns=%s, curNs=%s\n",
1066                     //       String8(ns).string(), String8(curNs).string());
1067                     if (strzcmp16(ns, nsLen, curNs, curNsLen) == 0) return i;
1068                 }
1069             }
1070         }
1071     }
1072 
1073     return NAME_NOT_FOUND;
1074 }
1075 
indexOfID() const1076 ssize_t ResXMLParser::indexOfID() const
1077 {
1078     if (mEventCode == START_TAG) {
1079         const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->idIndex);
1080         if (idx > 0) return (idx-1);
1081     }
1082     return NAME_NOT_FOUND;
1083 }
1084 
indexOfClass() const1085 ssize_t ResXMLParser::indexOfClass() const
1086 {
1087     if (mEventCode == START_TAG) {
1088         const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->classIndex);
1089         if (idx > 0) return (idx-1);
1090     }
1091     return NAME_NOT_FOUND;
1092 }
1093 
indexOfStyle() const1094 ssize_t ResXMLParser::indexOfStyle() const
1095 {
1096     if (mEventCode == START_TAG) {
1097         const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->styleIndex);
1098         if (idx > 0) return (idx-1);
1099     }
1100     return NAME_NOT_FOUND;
1101 }
1102 
nextNode()1103 ResXMLParser::event_code_t ResXMLParser::nextNode()
1104 {
1105     if (mEventCode < 0) {
1106         return mEventCode;
1107     }
1108 
1109     do {
1110         const ResXMLTree_node* next = (const ResXMLTree_node*)
1111             (((const uint8_t*)mCurNode) + dtohl(mCurNode->header.size));
1112         //ALOGW("Next node: prev=%p, next=%p\n", mCurNode, next);
1113 
1114         if (((const uint8_t*)next) >= mTree.mDataEnd) {
1115             mCurNode = NULL;
1116             return (mEventCode=END_DOCUMENT);
1117         }
1118 
1119         if (mTree.validateNode(next) != NO_ERROR) {
1120             mCurNode = NULL;
1121             return (mEventCode=BAD_DOCUMENT);
1122         }
1123 
1124         mCurNode = next;
1125         const uint16_t headerSize = dtohs(next->header.headerSize);
1126         const uint32_t totalSize = dtohl(next->header.size);
1127         mCurExt = ((const uint8_t*)next) + headerSize;
1128         size_t minExtSize = 0;
1129         event_code_t eventCode = (event_code_t)dtohs(next->header.type);
1130         switch ((mEventCode=eventCode)) {
1131             case RES_XML_START_NAMESPACE_TYPE:
1132             case RES_XML_END_NAMESPACE_TYPE:
1133                 minExtSize = sizeof(ResXMLTree_namespaceExt);
1134                 break;
1135             case RES_XML_START_ELEMENT_TYPE:
1136                 minExtSize = sizeof(ResXMLTree_attrExt);
1137                 break;
1138             case RES_XML_END_ELEMENT_TYPE:
1139                 minExtSize = sizeof(ResXMLTree_endElementExt);
1140                 break;
1141             case RES_XML_CDATA_TYPE:
1142                 minExtSize = sizeof(ResXMLTree_cdataExt);
1143                 break;
1144             default:
1145                 ALOGW("Unknown XML block: header type %d in node at %d\n",
1146                      (int)dtohs(next->header.type),
1147                      (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)));
1148                 continue;
1149         }
1150 
1151         if ((totalSize-headerSize) < minExtSize) {
1152             ALOGW("Bad XML block: header type 0x%x in node at 0x%x has size %d, need %d\n",
1153                  (int)dtohs(next->header.type),
1154                  (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)),
1155                  (int)(totalSize-headerSize), (int)minExtSize);
1156             return (mEventCode=BAD_DOCUMENT);
1157         }
1158 
1159         //printf("CurNode=%p, CurExt=%p, headerSize=%d, minExtSize=%d\n",
1160         //       mCurNode, mCurExt, headerSize, minExtSize);
1161 
1162         return eventCode;
1163     } while (true);
1164 }
1165 
getPosition(ResXMLParser::ResXMLPosition * pos) const1166 void ResXMLParser::getPosition(ResXMLParser::ResXMLPosition* pos) const
1167 {
1168     pos->eventCode = mEventCode;
1169     pos->curNode = mCurNode;
1170     pos->curExt = mCurExt;
1171 }
1172 
setPosition(const ResXMLParser::ResXMLPosition & pos)1173 void ResXMLParser::setPosition(const ResXMLParser::ResXMLPosition& pos)
1174 {
1175     mEventCode = pos.eventCode;
1176     mCurNode = pos.curNode;
1177     mCurExt = pos.curExt;
1178 }
1179 
1180 
1181 // --------------------------------------------------------------------
1182 
1183 static volatile int32_t gCount = 0;
1184 
ResXMLTree()1185 ResXMLTree::ResXMLTree()
1186     : ResXMLParser(*this)
1187     , mError(NO_INIT), mOwnedData(NULL)
1188 {
1189     //ALOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1);
1190     restart();
1191 }
1192 
ResXMLTree(const void * data,size_t size,bool copyData)1193 ResXMLTree::ResXMLTree(const void* data, size_t size, bool copyData)
1194     : ResXMLParser(*this)
1195     , mError(NO_INIT), mOwnedData(NULL)
1196 {
1197     //ALOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1);
1198     setTo(data, size, copyData);
1199 }
1200 
~ResXMLTree()1201 ResXMLTree::~ResXMLTree()
1202 {
1203     //ALOGI("Destroying ResXMLTree in %p #%d\n", this, android_atomic_dec(&gCount)-1);
1204     uninit();
1205 }
1206 
setTo(const void * data,size_t size,bool copyData)1207 status_t ResXMLTree::setTo(const void* data, size_t size, bool copyData)
1208 {
1209     uninit();
1210     mEventCode = START_DOCUMENT;
1211 
1212     if (copyData) {
1213         mOwnedData = malloc(size);
1214         if (mOwnedData == NULL) {
1215             return (mError=NO_MEMORY);
1216         }
1217         memcpy(mOwnedData, data, size);
1218         data = mOwnedData;
1219     }
1220 
1221     mHeader = (const ResXMLTree_header*)data;
1222     mSize = dtohl(mHeader->header.size);
1223     if (dtohs(mHeader->header.headerSize) > mSize || mSize > size) {
1224         ALOGW("Bad XML block: header size %d or total size %d is larger than data size %d\n",
1225              (int)dtohs(mHeader->header.headerSize),
1226              (int)dtohl(mHeader->header.size), (int)size);
1227         mError = BAD_TYPE;
1228         restart();
1229         return mError;
1230     }
1231     mDataEnd = ((const uint8_t*)mHeader) + mSize;
1232 
1233     mStrings.uninit();
1234     mRootNode = NULL;
1235     mResIds = NULL;
1236     mNumResIds = 0;
1237 
1238     // First look for a couple interesting chunks: the string block
1239     // and first XML node.
1240     const ResChunk_header* chunk =
1241         (const ResChunk_header*)(((const uint8_t*)mHeader) + dtohs(mHeader->header.headerSize));
1242     const ResChunk_header* lastChunk = chunk;
1243     while (((const uint8_t*)chunk) < (mDataEnd-sizeof(ResChunk_header)) &&
1244            ((const uint8_t*)chunk) < (mDataEnd-dtohl(chunk->size))) {
1245         status_t err = validate_chunk(chunk, sizeof(ResChunk_header), mDataEnd, "XML");
1246         if (err != NO_ERROR) {
1247             mError = err;
1248             goto done;
1249         }
1250         const uint16_t type = dtohs(chunk->type);
1251         const size_t size = dtohl(chunk->size);
1252         XML_NOISY(printf("Scanning @ %p: type=0x%x, size=0x%x\n",
1253                      (void*)(((uint32_t)chunk)-((uint32_t)mHeader)), type, size));
1254         if (type == RES_STRING_POOL_TYPE) {
1255             mStrings.setTo(chunk, size);
1256         } else if (type == RES_XML_RESOURCE_MAP_TYPE) {
1257             mResIds = (const uint32_t*)
1258                 (((const uint8_t*)chunk)+dtohs(chunk->headerSize));
1259             mNumResIds = (dtohl(chunk->size)-dtohs(chunk->headerSize))/sizeof(uint32_t);
1260         } else if (type >= RES_XML_FIRST_CHUNK_TYPE
1261                    && type <= RES_XML_LAST_CHUNK_TYPE) {
1262             if (validateNode((const ResXMLTree_node*)chunk) != NO_ERROR) {
1263                 mError = BAD_TYPE;
1264                 goto done;
1265             }
1266             mCurNode = (const ResXMLTree_node*)lastChunk;
1267             if (nextNode() == BAD_DOCUMENT) {
1268                 mError = BAD_TYPE;
1269                 goto done;
1270             }
1271             mRootNode = mCurNode;
1272             mRootExt = mCurExt;
1273             mRootCode = mEventCode;
1274             break;
1275         } else {
1276             XML_NOISY(printf("Skipping unknown chunk!\n"));
1277         }
1278         lastChunk = chunk;
1279         chunk = (const ResChunk_header*)
1280             (((const uint8_t*)chunk) + size);
1281     }
1282 
1283     if (mRootNode == NULL) {
1284         ALOGW("Bad XML block: no root element node found\n");
1285         mError = BAD_TYPE;
1286         goto done;
1287     }
1288 
1289     mError = mStrings.getError();
1290 
1291 done:
1292     restart();
1293     return mError;
1294 }
1295 
getError() const1296 status_t ResXMLTree::getError() const
1297 {
1298     return mError;
1299 }
1300 
uninit()1301 void ResXMLTree::uninit()
1302 {
1303     mError = NO_INIT;
1304     mStrings.uninit();
1305     if (mOwnedData) {
1306         free(mOwnedData);
1307         mOwnedData = NULL;
1308     }
1309     restart();
1310 }
1311 
validateNode(const ResXMLTree_node * node) const1312 status_t ResXMLTree::validateNode(const ResXMLTree_node* node) const
1313 {
1314     const uint16_t eventCode = dtohs(node->header.type);
1315 
1316     status_t err = validate_chunk(
1317         &node->header, sizeof(ResXMLTree_node),
1318         mDataEnd, "ResXMLTree_node");
1319 
1320     if (err >= NO_ERROR) {
1321         // Only perform additional validation on START nodes
1322         if (eventCode != RES_XML_START_ELEMENT_TYPE) {
1323             return NO_ERROR;
1324         }
1325 
1326         const uint16_t headerSize = dtohs(node->header.headerSize);
1327         const uint32_t size = dtohl(node->header.size);
1328         const ResXMLTree_attrExt* attrExt = (const ResXMLTree_attrExt*)
1329             (((const uint8_t*)node) + headerSize);
1330         // check for sensical values pulled out of the stream so far...
1331         if ((size >= headerSize + sizeof(ResXMLTree_attrExt))
1332                 && ((void*)attrExt > (void*)node)) {
1333             const size_t attrSize = ((size_t)dtohs(attrExt->attributeSize))
1334                 * dtohs(attrExt->attributeCount);
1335             if ((dtohs(attrExt->attributeStart)+attrSize) <= (size-headerSize)) {
1336                 return NO_ERROR;
1337             }
1338             ALOGW("Bad XML block: node attributes use 0x%x bytes, only have 0x%x bytes\n",
1339                     (unsigned int)(dtohs(attrExt->attributeStart)+attrSize),
1340                     (unsigned int)(size-headerSize));
1341         }
1342         else {
1343             ALOGW("Bad XML start block: node header size 0x%x, size 0x%x\n",
1344                 (unsigned int)headerSize, (unsigned int)size);
1345         }
1346         return BAD_TYPE;
1347     }
1348 
1349     return err;
1350 
1351 #if 0
1352     const bool isStart = dtohs(node->header.type) == RES_XML_START_ELEMENT_TYPE;
1353 
1354     const uint16_t headerSize = dtohs(node->header.headerSize);
1355     const uint32_t size = dtohl(node->header.size);
1356 
1357     if (headerSize >= (isStart ? sizeof(ResXMLTree_attrNode) : sizeof(ResXMLTree_node))) {
1358         if (size >= headerSize) {
1359             if (((const uint8_t*)node) <= (mDataEnd-size)) {
1360                 if (!isStart) {
1361                     return NO_ERROR;
1362                 }
1363                 if ((((size_t)dtohs(node->attributeSize))*dtohs(node->attributeCount))
1364                         <= (size-headerSize)) {
1365                     return NO_ERROR;
1366                 }
1367                 ALOGW("Bad XML block: node attributes use 0x%x bytes, only have 0x%x bytes\n",
1368                         ((int)dtohs(node->attributeSize))*dtohs(node->attributeCount),
1369                         (int)(size-headerSize));
1370                 return BAD_TYPE;
1371             }
1372             ALOGW("Bad XML block: node at 0x%x extends beyond data end 0x%x\n",
1373                     (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)), (int)mSize);
1374             return BAD_TYPE;
1375         }
1376         ALOGW("Bad XML block: node at 0x%x header size 0x%x smaller than total size 0x%x\n",
1377                 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)),
1378                 (int)headerSize, (int)size);
1379         return BAD_TYPE;
1380     }
1381     ALOGW("Bad XML block: node at 0x%x header size 0x%x too small\n",
1382             (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)),
1383             (int)headerSize);
1384     return BAD_TYPE;
1385 #endif
1386 }
1387 
1388 // --------------------------------------------------------------------
1389 // --------------------------------------------------------------------
1390 // --------------------------------------------------------------------
1391 
copyFromDeviceNoSwap(const ResTable_config & o)1392 void ResTable_config::copyFromDeviceNoSwap(const ResTable_config& o) {
1393     const size_t size = dtohl(o.size);
1394     if (size >= sizeof(ResTable_config)) {
1395         *this = o;
1396     } else {
1397         memcpy(this, &o, size);
1398         memset(((uint8_t*)this)+size, 0, sizeof(ResTable_config)-size);
1399     }
1400 }
1401 
copyFromDtoH(const ResTable_config & o)1402 void ResTable_config::copyFromDtoH(const ResTable_config& o) {
1403     copyFromDeviceNoSwap(o);
1404     size = sizeof(ResTable_config);
1405     mcc = dtohs(mcc);
1406     mnc = dtohs(mnc);
1407     density = dtohs(density);
1408     screenWidth = dtohs(screenWidth);
1409     screenHeight = dtohs(screenHeight);
1410     sdkVersion = dtohs(sdkVersion);
1411     minorVersion = dtohs(minorVersion);
1412     smallestScreenWidthDp = dtohs(smallestScreenWidthDp);
1413     screenWidthDp = dtohs(screenWidthDp);
1414     screenHeightDp = dtohs(screenHeightDp);
1415 }
1416 
swapHtoD()1417 void ResTable_config::swapHtoD() {
1418     size = htodl(size);
1419     mcc = htods(mcc);
1420     mnc = htods(mnc);
1421     density = htods(density);
1422     screenWidth = htods(screenWidth);
1423     screenHeight = htods(screenHeight);
1424     sdkVersion = htods(sdkVersion);
1425     minorVersion = htods(minorVersion);
1426     smallestScreenWidthDp = htods(smallestScreenWidthDp);
1427     screenWidthDp = htods(screenWidthDp);
1428     screenHeightDp = htods(screenHeightDp);
1429 }
1430 
compare(const ResTable_config & o) const1431 int ResTable_config::compare(const ResTable_config& o) const {
1432     int32_t diff = (int32_t)(imsi - o.imsi);
1433     if (diff != 0) return diff;
1434     diff = (int32_t)(locale - o.locale);
1435     if (diff != 0) return diff;
1436     diff = (int32_t)(screenType - o.screenType);
1437     if (diff != 0) return diff;
1438     diff = (int32_t)(input - o.input);
1439     if (diff != 0) return diff;
1440     diff = (int32_t)(screenSize - o.screenSize);
1441     if (diff != 0) return diff;
1442     diff = (int32_t)(version - o.version);
1443     if (diff != 0) return diff;
1444     diff = (int32_t)(screenLayout - o.screenLayout);
1445     if (diff != 0) return diff;
1446     diff = (int32_t)(uiMode - o.uiMode);
1447     if (diff != 0) return diff;
1448     diff = (int32_t)(smallestScreenWidthDp - o.smallestScreenWidthDp);
1449     if (diff != 0) return diff;
1450     diff = (int32_t)(screenSizeDp - o.screenSizeDp);
1451     return (int)diff;
1452 }
1453 
compareLogical(const ResTable_config & o) const1454 int ResTable_config::compareLogical(const ResTable_config& o) const {
1455     if (mcc != o.mcc) {
1456         return mcc < o.mcc ? -1 : 1;
1457     }
1458     if (mnc != o.mnc) {
1459         return mnc < o.mnc ? -1 : 1;
1460     }
1461     if (language[0] != o.language[0]) {
1462         return language[0] < o.language[0] ? -1 : 1;
1463     }
1464     if (language[1] != o.language[1]) {
1465         return language[1] < o.language[1] ? -1 : 1;
1466     }
1467     if (country[0] != o.country[0]) {
1468         return country[0] < o.country[0] ? -1 : 1;
1469     }
1470     if (country[1] != o.country[1]) {
1471         return country[1] < o.country[1] ? -1 : 1;
1472     }
1473     if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
1474         return smallestScreenWidthDp < o.smallestScreenWidthDp ? -1 : 1;
1475     }
1476     if (screenWidthDp != o.screenWidthDp) {
1477         return screenWidthDp < o.screenWidthDp ? -1 : 1;
1478     }
1479     if (screenHeightDp != o.screenHeightDp) {
1480         return screenHeightDp < o.screenHeightDp ? -1 : 1;
1481     }
1482     if (screenWidth != o.screenWidth) {
1483         return screenWidth < o.screenWidth ? -1 : 1;
1484     }
1485     if (screenHeight != o.screenHeight) {
1486         return screenHeight < o.screenHeight ? -1 : 1;
1487     }
1488     if (density != o.density) {
1489         return density < o.density ? -1 : 1;
1490     }
1491     if (orientation != o.orientation) {
1492         return orientation < o.orientation ? -1 : 1;
1493     }
1494     if (touchscreen != o.touchscreen) {
1495         return touchscreen < o.touchscreen ? -1 : 1;
1496     }
1497     if (input != o.input) {
1498         return input < o.input ? -1 : 1;
1499     }
1500     if (screenLayout != o.screenLayout) {
1501         return screenLayout < o.screenLayout ? -1 : 1;
1502     }
1503     if (uiMode != o.uiMode) {
1504         return uiMode < o.uiMode ? -1 : 1;
1505     }
1506     if (version != o.version) {
1507         return version < o.version ? -1 : 1;
1508     }
1509     return 0;
1510 }
1511 
diff(const ResTable_config & o) const1512 int ResTable_config::diff(const ResTable_config& o) const {
1513     int diffs = 0;
1514     if (mcc != o.mcc) diffs |= CONFIG_MCC;
1515     if (mnc != o.mnc) diffs |= CONFIG_MNC;
1516     if (locale != o.locale) diffs |= CONFIG_LOCALE;
1517     if (orientation != o.orientation) diffs |= CONFIG_ORIENTATION;
1518     if (density != o.density) diffs |= CONFIG_DENSITY;
1519     if (touchscreen != o.touchscreen) diffs |= CONFIG_TOUCHSCREEN;
1520     if (((inputFlags^o.inputFlags)&(MASK_KEYSHIDDEN|MASK_NAVHIDDEN)) != 0)
1521             diffs |= CONFIG_KEYBOARD_HIDDEN;
1522     if (keyboard != o.keyboard) diffs |= CONFIG_KEYBOARD;
1523     if (navigation != o.navigation) diffs |= CONFIG_NAVIGATION;
1524     if (screenSize != o.screenSize) diffs |= CONFIG_SCREEN_SIZE;
1525     if (version != o.version) diffs |= CONFIG_VERSION;
1526     if (screenLayout != o.screenLayout) diffs |= CONFIG_SCREEN_LAYOUT;
1527     if (uiMode != o.uiMode) diffs |= CONFIG_UI_MODE;
1528     if (smallestScreenWidthDp != o.smallestScreenWidthDp) diffs |= CONFIG_SMALLEST_SCREEN_SIZE;
1529     if (screenSizeDp != o.screenSizeDp) diffs |= CONFIG_SCREEN_SIZE;
1530     return diffs;
1531 }
1532 
isMoreSpecificThan(const ResTable_config & o) const1533 bool ResTable_config::isMoreSpecificThan(const ResTable_config& o) const {
1534     // The order of the following tests defines the importance of one
1535     // configuration parameter over another.  Those tests first are more
1536     // important, trumping any values in those following them.
1537     if (imsi || o.imsi) {
1538         if (mcc != o.mcc) {
1539             if (!mcc) return false;
1540             if (!o.mcc) return true;
1541         }
1542 
1543         if (mnc != o.mnc) {
1544             if (!mnc) return false;
1545             if (!o.mnc) return true;
1546         }
1547     }
1548 
1549     if (locale || o.locale) {
1550         if (language[0] != o.language[0]) {
1551             if (!language[0]) return false;
1552             if (!o.language[0]) return true;
1553         }
1554 
1555         if (country[0] != o.country[0]) {
1556             if (!country[0]) return false;
1557             if (!o.country[0]) return true;
1558         }
1559     }
1560 
1561     if (smallestScreenWidthDp || o.smallestScreenWidthDp) {
1562         if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
1563             if (!smallestScreenWidthDp) return false;
1564             if (!o.smallestScreenWidthDp) return true;
1565         }
1566     }
1567 
1568     if (screenSizeDp || o.screenSizeDp) {
1569         if (screenWidthDp != o.screenWidthDp) {
1570             if (!screenWidthDp) return false;
1571             if (!o.screenWidthDp) return true;
1572         }
1573 
1574         if (screenHeightDp != o.screenHeightDp) {
1575             if (!screenHeightDp) return false;
1576             if (!o.screenHeightDp) return true;
1577         }
1578     }
1579 
1580     if (screenLayout || o.screenLayout) {
1581         if (((screenLayout^o.screenLayout) & MASK_SCREENSIZE) != 0) {
1582             if (!(screenLayout & MASK_SCREENSIZE)) return false;
1583             if (!(o.screenLayout & MASK_SCREENSIZE)) return true;
1584         }
1585         if (((screenLayout^o.screenLayout) & MASK_SCREENLONG) != 0) {
1586             if (!(screenLayout & MASK_SCREENLONG)) return false;
1587             if (!(o.screenLayout & MASK_SCREENLONG)) return true;
1588         }
1589     }
1590 
1591     if (orientation != o.orientation) {
1592         if (!orientation) return false;
1593         if (!o.orientation) return true;
1594     }
1595 
1596     if (uiMode || o.uiMode) {
1597         if (((uiMode^o.uiMode) & MASK_UI_MODE_TYPE) != 0) {
1598             if (!(uiMode & MASK_UI_MODE_TYPE)) return false;
1599             if (!(o.uiMode & MASK_UI_MODE_TYPE)) return true;
1600         }
1601         if (((uiMode^o.uiMode) & MASK_UI_MODE_NIGHT) != 0) {
1602             if (!(uiMode & MASK_UI_MODE_NIGHT)) return false;
1603             if (!(o.uiMode & MASK_UI_MODE_NIGHT)) return true;
1604         }
1605     }
1606 
1607     // density is never 'more specific'
1608     // as the default just equals 160
1609 
1610     if (touchscreen != o.touchscreen) {
1611         if (!touchscreen) return false;
1612         if (!o.touchscreen) return true;
1613     }
1614 
1615     if (input || o.input) {
1616         if (((inputFlags^o.inputFlags) & MASK_KEYSHIDDEN) != 0) {
1617             if (!(inputFlags & MASK_KEYSHIDDEN)) return false;
1618             if (!(o.inputFlags & MASK_KEYSHIDDEN)) return true;
1619         }
1620 
1621         if (((inputFlags^o.inputFlags) & MASK_NAVHIDDEN) != 0) {
1622             if (!(inputFlags & MASK_NAVHIDDEN)) return false;
1623             if (!(o.inputFlags & MASK_NAVHIDDEN)) return true;
1624         }
1625 
1626         if (keyboard != o.keyboard) {
1627             if (!keyboard) return false;
1628             if (!o.keyboard) return true;
1629         }
1630 
1631         if (navigation != o.navigation) {
1632             if (!navigation) return false;
1633             if (!o.navigation) return true;
1634         }
1635     }
1636 
1637     if (screenSize || o.screenSize) {
1638         if (screenWidth != o.screenWidth) {
1639             if (!screenWidth) return false;
1640             if (!o.screenWidth) return true;
1641         }
1642 
1643         if (screenHeight != o.screenHeight) {
1644             if (!screenHeight) return false;
1645             if (!o.screenHeight) return true;
1646         }
1647     }
1648 
1649     if (version || o.version) {
1650         if (sdkVersion != o.sdkVersion) {
1651             if (!sdkVersion) return false;
1652             if (!o.sdkVersion) return true;
1653         }
1654 
1655         if (minorVersion != o.minorVersion) {
1656             if (!minorVersion) return false;
1657             if (!o.minorVersion) return true;
1658         }
1659     }
1660     return false;
1661 }
1662 
isBetterThan(const ResTable_config & o,const ResTable_config * requested) const1663 bool ResTable_config::isBetterThan(const ResTable_config& o,
1664         const ResTable_config* requested) const {
1665     if (requested) {
1666         if (imsi || o.imsi) {
1667             if ((mcc != o.mcc) && requested->mcc) {
1668                 return (mcc);
1669             }
1670 
1671             if ((mnc != o.mnc) && requested->mnc) {
1672                 return (mnc);
1673             }
1674         }
1675 
1676         if (locale || o.locale) {
1677             if ((language[0] != o.language[0]) && requested->language[0]) {
1678                 return (language[0]);
1679             }
1680 
1681             if ((country[0] != o.country[0]) && requested->country[0]) {
1682                 return (country[0]);
1683             }
1684         }
1685 
1686         if (smallestScreenWidthDp || o.smallestScreenWidthDp) {
1687             // The configuration closest to the actual size is best.
1688             // We assume that larger configs have already been filtered
1689             // out at this point.  That means we just want the largest one.
1690             if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
1691                 return smallestScreenWidthDp > o.smallestScreenWidthDp;
1692             }
1693         }
1694 
1695         if (screenSizeDp || o.screenSizeDp) {
1696             // "Better" is based on the sum of the difference between both
1697             // width and height from the requested dimensions.  We are
1698             // assuming the invalid configs (with smaller dimens) have
1699             // already been filtered.  Note that if a particular dimension
1700             // is unspecified, we will end up with a large value (the
1701             // difference between 0 and the requested dimension), which is
1702             // good since we will prefer a config that has specified a
1703             // dimension value.
1704             int myDelta = 0, otherDelta = 0;
1705             if (requested->screenWidthDp) {
1706                 myDelta += requested->screenWidthDp - screenWidthDp;
1707                 otherDelta += requested->screenWidthDp - o.screenWidthDp;
1708             }
1709             if (requested->screenHeightDp) {
1710                 myDelta += requested->screenHeightDp - screenHeightDp;
1711                 otherDelta += requested->screenHeightDp - o.screenHeightDp;
1712             }
1713             //ALOGI("Comparing this %dx%d to other %dx%d in %dx%d: myDelta=%d otherDelta=%d",
1714             //    screenWidthDp, screenHeightDp, o.screenWidthDp, o.screenHeightDp,
1715             //    requested->screenWidthDp, requested->screenHeightDp, myDelta, otherDelta);
1716             if (myDelta != otherDelta) {
1717                 return myDelta < otherDelta;
1718             }
1719         }
1720 
1721         if (screenLayout || o.screenLayout) {
1722             if (((screenLayout^o.screenLayout) & MASK_SCREENSIZE) != 0
1723                     && (requested->screenLayout & MASK_SCREENSIZE)) {
1724                 // A little backwards compatibility here: undefined is
1725                 // considered equivalent to normal.  But only if the
1726                 // requested size is at least normal; otherwise, small
1727                 // is better than the default.
1728                 int mySL = (screenLayout & MASK_SCREENSIZE);
1729                 int oSL = (o.screenLayout & MASK_SCREENSIZE);
1730                 int fixedMySL = mySL;
1731                 int fixedOSL = oSL;
1732                 if ((requested->screenLayout & MASK_SCREENSIZE) >= SCREENSIZE_NORMAL) {
1733                     if (fixedMySL == 0) fixedMySL = SCREENSIZE_NORMAL;
1734                     if (fixedOSL == 0) fixedOSL = SCREENSIZE_NORMAL;
1735                 }
1736                 // For screen size, the best match is the one that is
1737                 // closest to the requested screen size, but not over
1738                 // (the not over part is dealt with in match() below).
1739                 if (fixedMySL == fixedOSL) {
1740                     // If the two are the same, but 'this' is actually
1741                     // undefined, then the other is really a better match.
1742                     if (mySL == 0) return false;
1743                     return true;
1744                 }
1745                 if (fixedMySL != fixedOSL) {
1746                     return fixedMySL > fixedOSL;
1747                 }
1748             }
1749             if (((screenLayout^o.screenLayout) & MASK_SCREENLONG) != 0
1750                     && (requested->screenLayout & MASK_SCREENLONG)) {
1751                 return (screenLayout & MASK_SCREENLONG);
1752             }
1753         }
1754 
1755         if ((orientation != o.orientation) && requested->orientation) {
1756             return (orientation);
1757         }
1758 
1759         if (uiMode || o.uiMode) {
1760             if (((uiMode^o.uiMode) & MASK_UI_MODE_TYPE) != 0
1761                     && (requested->uiMode & MASK_UI_MODE_TYPE)) {
1762                 return (uiMode & MASK_UI_MODE_TYPE);
1763             }
1764             if (((uiMode^o.uiMode) & MASK_UI_MODE_NIGHT) != 0
1765                     && (requested->uiMode & MASK_UI_MODE_NIGHT)) {
1766                 return (uiMode & MASK_UI_MODE_NIGHT);
1767             }
1768         }
1769 
1770         if (screenType || o.screenType) {
1771             if (density != o.density) {
1772                 // density is tough.  Any density is potentially useful
1773                 // because the system will scale it.  Scaling down
1774                 // is generally better than scaling up.
1775                 // Default density counts as 160dpi (the system default)
1776                 // TODO - remove 160 constants
1777                 int h = (density?density:160);
1778                 int l = (o.density?o.density:160);
1779                 bool bImBigger = true;
1780                 if (l > h) {
1781                     int t = h;
1782                     h = l;
1783                     l = t;
1784                     bImBigger = false;
1785                 }
1786 
1787                 int reqValue = (requested->density?requested->density:160);
1788                 if (reqValue >= h) {
1789                     // requested value higher than both l and h, give h
1790                     return bImBigger;
1791                 }
1792                 if (l >= reqValue) {
1793                     // requested value lower than both l and h, give l
1794                     return !bImBigger;
1795                 }
1796                 // saying that scaling down is 2x better than up
1797                 if (((2 * l) - reqValue) * h > reqValue * reqValue) {
1798                     return !bImBigger;
1799                 } else {
1800                     return bImBigger;
1801                 }
1802             }
1803 
1804             if ((touchscreen != o.touchscreen) && requested->touchscreen) {
1805                 return (touchscreen);
1806             }
1807         }
1808 
1809         if (input || o.input) {
1810             const int keysHidden = inputFlags & MASK_KEYSHIDDEN;
1811             const int oKeysHidden = o.inputFlags & MASK_KEYSHIDDEN;
1812             if (keysHidden != oKeysHidden) {
1813                 const int reqKeysHidden =
1814                         requested->inputFlags & MASK_KEYSHIDDEN;
1815                 if (reqKeysHidden) {
1816 
1817                     if (!keysHidden) return false;
1818                     if (!oKeysHidden) return true;
1819                     // For compatibility, we count KEYSHIDDEN_NO as being
1820                     // the same as KEYSHIDDEN_SOFT.  Here we disambiguate
1821                     // these by making an exact match more specific.
1822                     if (reqKeysHidden == keysHidden) return true;
1823                     if (reqKeysHidden == oKeysHidden) return false;
1824                 }
1825             }
1826 
1827             const int navHidden = inputFlags & MASK_NAVHIDDEN;
1828             const int oNavHidden = o.inputFlags & MASK_NAVHIDDEN;
1829             if (navHidden != oNavHidden) {
1830                 const int reqNavHidden =
1831                         requested->inputFlags & MASK_NAVHIDDEN;
1832                 if (reqNavHidden) {
1833 
1834                     if (!navHidden) return false;
1835                     if (!oNavHidden) return true;
1836                 }
1837             }
1838 
1839             if ((keyboard != o.keyboard) && requested->keyboard) {
1840                 return (keyboard);
1841             }
1842 
1843             if ((navigation != o.navigation) && requested->navigation) {
1844                 return (navigation);
1845             }
1846         }
1847 
1848         if (screenSize || o.screenSize) {
1849             // "Better" is based on the sum of the difference between both
1850             // width and height from the requested dimensions.  We are
1851             // assuming the invalid configs (with smaller sizes) have
1852             // already been filtered.  Note that if a particular dimension
1853             // is unspecified, we will end up with a large value (the
1854             // difference between 0 and the requested dimension), which is
1855             // good since we will prefer a config that has specified a
1856             // size value.
1857             int myDelta = 0, otherDelta = 0;
1858             if (requested->screenWidth) {
1859                 myDelta += requested->screenWidth - screenWidth;
1860                 otherDelta += requested->screenWidth - o.screenWidth;
1861             }
1862             if (requested->screenHeight) {
1863                 myDelta += requested->screenHeight - screenHeight;
1864                 otherDelta += requested->screenHeight - o.screenHeight;
1865             }
1866             if (myDelta != otherDelta) {
1867                 return myDelta < otherDelta;
1868             }
1869         }
1870 
1871         if (version || o.version) {
1872             if ((sdkVersion != o.sdkVersion) && requested->sdkVersion) {
1873                 return (sdkVersion > o.sdkVersion);
1874             }
1875 
1876             if ((minorVersion != o.minorVersion) &&
1877                     requested->minorVersion) {
1878                 return (minorVersion);
1879             }
1880         }
1881 
1882         return false;
1883     }
1884     return isMoreSpecificThan(o);
1885 }
1886 
match(const ResTable_config & settings) const1887 bool ResTable_config::match(const ResTable_config& settings) const {
1888     if (imsi != 0) {
1889         if (mcc != 0 && mcc != settings.mcc) {
1890             return false;
1891         }
1892         if (mnc != 0 && mnc != settings.mnc) {
1893             return false;
1894         }
1895     }
1896     if (locale != 0) {
1897         if (language[0] != 0
1898             && (language[0] != settings.language[0]
1899                 || language[1] != settings.language[1])) {
1900             return false;
1901         }
1902         if (country[0] != 0
1903             && (country[0] != settings.country[0]
1904                 || country[1] != settings.country[1])) {
1905             return false;
1906         }
1907     }
1908     if (screenConfig != 0) {
1909         const int screenSize = screenLayout&MASK_SCREENSIZE;
1910         const int setScreenSize = settings.screenLayout&MASK_SCREENSIZE;
1911         // Any screen sizes for larger screens than the setting do not
1912         // match.
1913         if (screenSize != 0 && screenSize > setScreenSize) {
1914             return false;
1915         }
1916 
1917         const int screenLong = screenLayout&MASK_SCREENLONG;
1918         const int setScreenLong = settings.screenLayout&MASK_SCREENLONG;
1919         if (screenLong != 0 && screenLong != setScreenLong) {
1920             return false;
1921         }
1922 
1923         const int uiModeType = uiMode&MASK_UI_MODE_TYPE;
1924         const int setUiModeType = settings.uiMode&MASK_UI_MODE_TYPE;
1925         if (uiModeType != 0 && uiModeType != setUiModeType) {
1926             return false;
1927         }
1928 
1929         const int uiModeNight = uiMode&MASK_UI_MODE_NIGHT;
1930         const int setUiModeNight = settings.uiMode&MASK_UI_MODE_NIGHT;
1931         if (uiModeNight != 0 && uiModeNight != setUiModeNight) {
1932             return false;
1933         }
1934 
1935         if (smallestScreenWidthDp != 0
1936                 && smallestScreenWidthDp > settings.smallestScreenWidthDp) {
1937             return false;
1938         }
1939     }
1940     if (screenSizeDp != 0) {
1941         if (screenWidthDp != 0 && screenWidthDp > settings.screenWidthDp) {
1942             //ALOGI("Filtering out width %d in requested %d", screenWidthDp, settings.screenWidthDp);
1943             return false;
1944         }
1945         if (screenHeightDp != 0 && screenHeightDp > settings.screenHeightDp) {
1946             //ALOGI("Filtering out height %d in requested %d", screenHeightDp, settings.screenHeightDp);
1947             return false;
1948         }
1949     }
1950     if (screenType != 0) {
1951         if (orientation != 0 && orientation != settings.orientation) {
1952             return false;
1953         }
1954         // density always matches - we can scale it.  See isBetterThan
1955         if (touchscreen != 0 && touchscreen != settings.touchscreen) {
1956             return false;
1957         }
1958     }
1959     if (input != 0) {
1960         const int keysHidden = inputFlags&MASK_KEYSHIDDEN;
1961         const int setKeysHidden = settings.inputFlags&MASK_KEYSHIDDEN;
1962         if (keysHidden != 0 && keysHidden != setKeysHidden) {
1963             // For compatibility, we count a request for KEYSHIDDEN_NO as also
1964             // matching the more recent KEYSHIDDEN_SOFT.  Basically
1965             // KEYSHIDDEN_NO means there is some kind of keyboard available.
1966             //ALOGI("Matching keysHidden: have=%d, config=%d\n", keysHidden, setKeysHidden);
1967             if (keysHidden != KEYSHIDDEN_NO || setKeysHidden != KEYSHIDDEN_SOFT) {
1968                 //ALOGI("No match!");
1969                 return false;
1970             }
1971         }
1972         const int navHidden = inputFlags&MASK_NAVHIDDEN;
1973         const int setNavHidden = settings.inputFlags&MASK_NAVHIDDEN;
1974         if (navHidden != 0 && navHidden != setNavHidden) {
1975             return false;
1976         }
1977         if (keyboard != 0 && keyboard != settings.keyboard) {
1978             return false;
1979         }
1980         if (navigation != 0 && navigation != settings.navigation) {
1981             return false;
1982         }
1983     }
1984     if (screenSize != 0) {
1985         if (screenWidth != 0 && screenWidth > settings.screenWidth) {
1986             return false;
1987         }
1988         if (screenHeight != 0 && screenHeight > settings.screenHeight) {
1989             return false;
1990         }
1991     }
1992     if (version != 0) {
1993         if (sdkVersion != 0 && sdkVersion > settings.sdkVersion) {
1994             return false;
1995         }
1996         if (minorVersion != 0 && minorVersion != settings.minorVersion) {
1997             return false;
1998         }
1999     }
2000     return true;
2001 }
2002 
getLocale(char str[6]) const2003 void ResTable_config::getLocale(char str[6]) const {
2004     memset(str, 0, 6);
2005     if (language[0]) {
2006         str[0] = language[0];
2007         str[1] = language[1];
2008         if (country[0]) {
2009             str[2] = '_';
2010             str[3] = country[0];
2011             str[4] = country[1];
2012         }
2013     }
2014 }
2015 
toString() const2016 String8 ResTable_config::toString() const {
2017     String8 res;
2018 
2019     if (mcc != 0) {
2020         if (res.size() > 0) res.append("-");
2021         res.appendFormat("%dmcc", dtohs(mcc));
2022     }
2023     if (mnc != 0) {
2024         if (res.size() > 0) res.append("-");
2025         res.appendFormat("%dmnc", dtohs(mnc));
2026     }
2027     if (language[0] != 0) {
2028         if (res.size() > 0) res.append("-");
2029         res.append(language, 2);
2030     }
2031     if (country[0] != 0) {
2032         if (res.size() > 0) res.append("-");
2033         res.append(country, 2);
2034     }
2035     if (smallestScreenWidthDp != 0) {
2036         if (res.size() > 0) res.append("-");
2037         res.appendFormat("sw%ddp", dtohs(smallestScreenWidthDp));
2038     }
2039     if (screenWidthDp != 0) {
2040         if (res.size() > 0) res.append("-");
2041         res.appendFormat("w%ddp", dtohs(screenWidthDp));
2042     }
2043     if (screenHeightDp != 0) {
2044         if (res.size() > 0) res.append("-");
2045         res.appendFormat("h%ddp", dtohs(screenHeightDp));
2046     }
2047     if ((screenLayout&MASK_SCREENSIZE) != SCREENSIZE_ANY) {
2048         if (res.size() > 0) res.append("-");
2049         switch (screenLayout&ResTable_config::MASK_SCREENSIZE) {
2050             case ResTable_config::SCREENSIZE_SMALL:
2051                 res.append("small");
2052                 break;
2053             case ResTable_config::SCREENSIZE_NORMAL:
2054                 res.append("normal");
2055                 break;
2056             case ResTable_config::SCREENSIZE_LARGE:
2057                 res.append("large");
2058                 break;
2059             case ResTable_config::SCREENSIZE_XLARGE:
2060                 res.append("xlarge");
2061                 break;
2062             default:
2063                 res.appendFormat("screenLayoutSize=%d",
2064                         dtohs(screenLayout&ResTable_config::MASK_SCREENSIZE));
2065                 break;
2066         }
2067     }
2068     if ((screenLayout&MASK_SCREENLONG) != 0) {
2069         if (res.size() > 0) res.append("-");
2070         switch (screenLayout&ResTable_config::MASK_SCREENLONG) {
2071             case ResTable_config::SCREENLONG_NO:
2072                 res.append("notlong");
2073                 break;
2074             case ResTable_config::SCREENLONG_YES:
2075                 res.append("long");
2076                 break;
2077             default:
2078                 res.appendFormat("screenLayoutLong=%d",
2079                         dtohs(screenLayout&ResTable_config::MASK_SCREENLONG));
2080                 break;
2081         }
2082     }
2083     if (orientation != ORIENTATION_ANY) {
2084         if (res.size() > 0) res.append("-");
2085         switch (orientation) {
2086             case ResTable_config::ORIENTATION_PORT:
2087                 res.append("port");
2088                 break;
2089             case ResTable_config::ORIENTATION_LAND:
2090                 res.append("land");
2091                 break;
2092             case ResTable_config::ORIENTATION_SQUARE:
2093                 res.append("square");
2094                 break;
2095             default:
2096                 res.appendFormat("orientation=%d", dtohs(orientation));
2097                 break;
2098         }
2099     }
2100     if ((uiMode&MASK_UI_MODE_TYPE) != UI_MODE_TYPE_ANY) {
2101         if (res.size() > 0) res.append("-");
2102         switch (uiMode&ResTable_config::MASK_UI_MODE_TYPE) {
2103             case ResTable_config::UI_MODE_TYPE_DESK:
2104                 res.append("desk");
2105                 break;
2106             case ResTable_config::UI_MODE_TYPE_CAR:
2107                 res.append("car");
2108                 break;
2109             case ResTable_config::UI_MODE_TYPE_TELEVISION:
2110                 res.append("television");
2111                 break;
2112             case ResTable_config::UI_MODE_TYPE_APPLIANCE:
2113                 res.append("appliance");
2114                 break;
2115             default:
2116                 res.appendFormat("uiModeType=%d",
2117                         dtohs(screenLayout&ResTable_config::MASK_UI_MODE_TYPE));
2118                 break;
2119         }
2120     }
2121     if ((uiMode&MASK_UI_MODE_NIGHT) != 0) {
2122         if (res.size() > 0) res.append("-");
2123         switch (uiMode&ResTable_config::MASK_UI_MODE_NIGHT) {
2124             case ResTable_config::UI_MODE_NIGHT_NO:
2125                 res.append("notnight");
2126                 break;
2127             case ResTable_config::UI_MODE_NIGHT_YES:
2128                 res.append("night");
2129                 break;
2130             default:
2131                 res.appendFormat("uiModeNight=%d",
2132                         dtohs(uiMode&MASK_UI_MODE_NIGHT));
2133                 break;
2134         }
2135     }
2136     if (density != DENSITY_DEFAULT) {
2137         if (res.size() > 0) res.append("-");
2138         switch (density) {
2139             case ResTable_config::DENSITY_LOW:
2140                 res.append("ldpi");
2141                 break;
2142             case ResTable_config::DENSITY_MEDIUM:
2143                 res.append("mdpi");
2144                 break;
2145             case ResTable_config::DENSITY_TV:
2146                 res.append("tvdpi");
2147                 break;
2148             case ResTable_config::DENSITY_HIGH:
2149                 res.append("hdpi");
2150                 break;
2151             case ResTable_config::DENSITY_XHIGH:
2152                 res.append("xhdpi");
2153                 break;
2154             case ResTable_config::DENSITY_XXHIGH:
2155                 res.append("xxhdpi");
2156                 break;
2157             case ResTable_config::DENSITY_NONE:
2158                 res.append("nodpi");
2159                 break;
2160             default:
2161                 res.appendFormat("%ddpi", dtohs(density));
2162                 break;
2163         }
2164     }
2165     if (touchscreen != TOUCHSCREEN_ANY) {
2166         if (res.size() > 0) res.append("-");
2167         switch (touchscreen) {
2168             case ResTable_config::TOUCHSCREEN_NOTOUCH:
2169                 res.append("notouch");
2170                 break;
2171             case ResTable_config::TOUCHSCREEN_FINGER:
2172                 res.append("finger");
2173                 break;
2174             case ResTable_config::TOUCHSCREEN_STYLUS:
2175                 res.append("stylus");
2176                 break;
2177             default:
2178                 res.appendFormat("touchscreen=%d", dtohs(touchscreen));
2179                 break;
2180         }
2181     }
2182     if (keyboard != KEYBOARD_ANY) {
2183         if (res.size() > 0) res.append("-");
2184         switch (keyboard) {
2185             case ResTable_config::KEYBOARD_NOKEYS:
2186                 res.append("nokeys");
2187                 break;
2188             case ResTable_config::KEYBOARD_QWERTY:
2189                 res.append("qwerty");
2190                 break;
2191             case ResTable_config::KEYBOARD_12KEY:
2192                 res.append("12key");
2193                 break;
2194             default:
2195                 res.appendFormat("keyboard=%d", dtohs(keyboard));
2196                 break;
2197         }
2198     }
2199     if ((inputFlags&MASK_KEYSHIDDEN) != 0) {
2200         if (res.size() > 0) res.append("-");
2201         switch (inputFlags&MASK_KEYSHIDDEN) {
2202             case ResTable_config::KEYSHIDDEN_NO:
2203                 res.append("keysexposed");
2204                 break;
2205             case ResTable_config::KEYSHIDDEN_YES:
2206                 res.append("keyshidden");
2207                 break;
2208             case ResTable_config::KEYSHIDDEN_SOFT:
2209                 res.append("keyssoft");
2210                 break;
2211         }
2212     }
2213     if (navigation != NAVIGATION_ANY) {
2214         if (res.size() > 0) res.append("-");
2215         switch (navigation) {
2216             case ResTable_config::NAVIGATION_NONAV:
2217                 res.append("nonav");
2218                 break;
2219             case ResTable_config::NAVIGATION_DPAD:
2220                 res.append("dpad");
2221                 break;
2222             case ResTable_config::NAVIGATION_TRACKBALL:
2223                 res.append("trackball");
2224                 break;
2225             case ResTable_config::NAVIGATION_WHEEL:
2226                 res.append("wheel");
2227                 break;
2228             default:
2229                 res.appendFormat("navigation=%d", dtohs(navigation));
2230                 break;
2231         }
2232     }
2233     if ((inputFlags&MASK_NAVHIDDEN) != 0) {
2234         if (res.size() > 0) res.append("-");
2235         switch (inputFlags&MASK_NAVHIDDEN) {
2236             case ResTable_config::NAVHIDDEN_NO:
2237                 res.append("navsexposed");
2238                 break;
2239             case ResTable_config::NAVHIDDEN_YES:
2240                 res.append("navhidden");
2241                 break;
2242             default:
2243                 res.appendFormat("inputFlagsNavHidden=%d",
2244                         dtohs(inputFlags&MASK_NAVHIDDEN));
2245                 break;
2246         }
2247     }
2248     if (screenSize != 0) {
2249         if (res.size() > 0) res.append("-");
2250         res.appendFormat("%dx%d", dtohs(screenWidth), dtohs(screenHeight));
2251     }
2252     if (version != 0) {
2253         if (res.size() > 0) res.append("-");
2254         res.appendFormat("v%d", dtohs(sdkVersion));
2255         if (minorVersion != 0) {
2256             res.appendFormat(".%d", dtohs(minorVersion));
2257         }
2258     }
2259 
2260     return res;
2261 }
2262 
2263 // --------------------------------------------------------------------
2264 // --------------------------------------------------------------------
2265 // --------------------------------------------------------------------
2266 
2267 struct ResTable::Header
2268 {
Headerandroid::ResTable::Header2269     Header(ResTable* _owner) : owner(_owner), ownedData(NULL), header(NULL),
2270         resourceIDMap(NULL), resourceIDMapSize(0) { }
2271 
~Headerandroid::ResTable::Header2272     ~Header()
2273     {
2274         free(resourceIDMap);
2275     }
2276 
2277     ResTable* const                 owner;
2278     void*                           ownedData;
2279     const ResTable_header*          header;
2280     size_t                          size;
2281     const uint8_t*                  dataEnd;
2282     size_t                          index;
2283     void*                           cookie;
2284 
2285     ResStringPool                   values;
2286     uint32_t*                       resourceIDMap;
2287     size_t                          resourceIDMapSize;
2288 };
2289 
2290 struct ResTable::Type
2291 {
Typeandroid::ResTable::Type2292     Type(const Header* _header, const Package* _package, size_t count)
2293         : header(_header), package(_package), entryCount(count),
2294           typeSpec(NULL), typeSpecFlags(NULL) { }
2295     const Header* const             header;
2296     const Package* const            package;
2297     const size_t                    entryCount;
2298     const ResTable_typeSpec*        typeSpec;
2299     const uint32_t*                 typeSpecFlags;
2300     Vector<const ResTable_type*>    configs;
2301 };
2302 
2303 struct ResTable::Package
2304 {
Packageandroid::ResTable::Package2305     Package(ResTable* _owner, const Header* _header, const ResTable_package* _package)
2306         : owner(_owner), header(_header), package(_package) { }
~Packageandroid::ResTable::Package2307     ~Package()
2308     {
2309         size_t i = types.size();
2310         while (i > 0) {
2311             i--;
2312             delete types[i];
2313         }
2314     }
2315 
2316     ResTable* const                 owner;
2317     const Header* const             header;
2318     const ResTable_package* const   package;
2319     Vector<Type*>                   types;
2320 
2321     ResStringPool                   typeStrings;
2322     ResStringPool                   keyStrings;
2323 
getTypeandroid::ResTable::Package2324     const Type* getType(size_t idx) const {
2325         return idx < types.size() ? types[idx] : NULL;
2326     }
2327 };
2328 
2329 // A group of objects describing a particular resource package.
2330 // The first in 'package' is always the root object (from the resource
2331 // table that defined the package); the ones after are skins on top of it.
2332 struct ResTable::PackageGroup
2333 {
PackageGroupandroid::ResTable::PackageGroup2334     PackageGroup(ResTable* _owner, const String16& _name, uint32_t _id)
2335         : owner(_owner), name(_name), id(_id), typeCount(0), bags(NULL) { }
~PackageGroupandroid::ResTable::PackageGroup2336     ~PackageGroup() {
2337         clearBagCache();
2338         const size_t N = packages.size();
2339         for (size_t i=0; i<N; i++) {
2340             Package* pkg = packages[i];
2341             if (pkg->owner == owner) {
2342                 delete pkg;
2343             }
2344         }
2345     }
2346 
clearBagCacheandroid::ResTable::PackageGroup2347     void clearBagCache() {
2348         if (bags) {
2349             TABLE_NOISY(printf("bags=%p\n", bags));
2350             Package* pkg = packages[0];
2351             TABLE_NOISY(printf("typeCount=%x\n", typeCount));
2352             for (size_t i=0; i<typeCount; i++) {
2353                 TABLE_NOISY(printf("type=%d\n", i));
2354                 const Type* type = pkg->getType(i);
2355                 if (type != NULL) {
2356                     bag_set** typeBags = bags[i];
2357                     TABLE_NOISY(printf("typeBags=%p\n", typeBags));
2358                     if (typeBags) {
2359                         TABLE_NOISY(printf("type->entryCount=%x\n", type->entryCount));
2360                         const size_t N = type->entryCount;
2361                         for (size_t j=0; j<N; j++) {
2362                             if (typeBags[j] && typeBags[j] != (bag_set*)0xFFFFFFFF)
2363                                 free(typeBags[j]);
2364                         }
2365                         free(typeBags);
2366                     }
2367                 }
2368             }
2369             free(bags);
2370             bags = NULL;
2371         }
2372     }
2373 
2374     ResTable* const                 owner;
2375     String16 const                  name;
2376     uint32_t const                  id;
2377     Vector<Package*>                packages;
2378 
2379     // This is for finding typeStrings and other common package stuff.
2380     Package*                        basePackage;
2381 
2382     // For quick access.
2383     size_t                          typeCount;
2384 
2385     // Computed attribute bags, first indexed by the type and second
2386     // by the entry in that type.
2387     bag_set***                      bags;
2388 };
2389 
2390 struct ResTable::bag_set
2391 {
2392     size_t numAttrs;    // number in array
2393     size_t availAttrs;  // total space in array
2394     uint32_t typeSpecFlags;
2395     // Followed by 'numAttr' bag_entry structures.
2396 };
2397 
Theme(const ResTable & table)2398 ResTable::Theme::Theme(const ResTable& table)
2399     : mTable(table)
2400 {
2401     memset(mPackages, 0, sizeof(mPackages));
2402 }
2403 
~Theme()2404 ResTable::Theme::~Theme()
2405 {
2406     for (size_t i=0; i<Res_MAXPACKAGE; i++) {
2407         package_info* pi = mPackages[i];
2408         if (pi != NULL) {
2409             free_package(pi);
2410         }
2411     }
2412 }
2413 
free_package(package_info * pi)2414 void ResTable::Theme::free_package(package_info* pi)
2415 {
2416     for (size_t j=0; j<pi->numTypes; j++) {
2417         theme_entry* te = pi->types[j].entries;
2418         if (te != NULL) {
2419             free(te);
2420         }
2421     }
2422     free(pi);
2423 }
2424 
copy_package(package_info * pi)2425 ResTable::Theme::package_info* ResTable::Theme::copy_package(package_info* pi)
2426 {
2427     package_info* newpi = (package_info*)malloc(
2428         sizeof(package_info) + (pi->numTypes*sizeof(type_info)));
2429     newpi->numTypes = pi->numTypes;
2430     for (size_t j=0; j<newpi->numTypes; j++) {
2431         size_t cnt = pi->types[j].numEntries;
2432         newpi->types[j].numEntries = cnt;
2433         theme_entry* te = pi->types[j].entries;
2434         if (te != NULL) {
2435             theme_entry* newte = (theme_entry*)malloc(cnt*sizeof(theme_entry));
2436             newpi->types[j].entries = newte;
2437             memcpy(newte, te, cnt*sizeof(theme_entry));
2438         } else {
2439             newpi->types[j].entries = NULL;
2440         }
2441     }
2442     return newpi;
2443 }
2444 
applyStyle(uint32_t resID,bool force)2445 status_t ResTable::Theme::applyStyle(uint32_t resID, bool force)
2446 {
2447     const bag_entry* bag;
2448     uint32_t bagTypeSpecFlags = 0;
2449     mTable.lock();
2450     const ssize_t N = mTable.getBagLocked(resID, &bag, &bagTypeSpecFlags);
2451     TABLE_NOISY(ALOGV("Applying style 0x%08x to theme %p, count=%d", resID, this, N));
2452     if (N < 0) {
2453         mTable.unlock();
2454         return N;
2455     }
2456 
2457     uint32_t curPackage = 0xffffffff;
2458     ssize_t curPackageIndex = 0;
2459     package_info* curPI = NULL;
2460     uint32_t curType = 0xffffffff;
2461     size_t numEntries = 0;
2462     theme_entry* curEntries = NULL;
2463 
2464     const bag_entry* end = bag + N;
2465     while (bag < end) {
2466         const uint32_t attrRes = bag->map.name.ident;
2467         const uint32_t p = Res_GETPACKAGE(attrRes);
2468         const uint32_t t = Res_GETTYPE(attrRes);
2469         const uint32_t e = Res_GETENTRY(attrRes);
2470 
2471         if (curPackage != p) {
2472             const ssize_t pidx = mTable.getResourcePackageIndex(attrRes);
2473             if (pidx < 0) {
2474                 ALOGE("Style contains key with bad package: 0x%08x\n", attrRes);
2475                 bag++;
2476                 continue;
2477             }
2478             curPackage = p;
2479             curPackageIndex = pidx;
2480             curPI = mPackages[pidx];
2481             if (curPI == NULL) {
2482                 PackageGroup* const grp = mTable.mPackageGroups[pidx];
2483                 int cnt = grp->typeCount;
2484                 curPI = (package_info*)malloc(
2485                     sizeof(package_info) + (cnt*sizeof(type_info)));
2486                 curPI->numTypes = cnt;
2487                 memset(curPI->types, 0, cnt*sizeof(type_info));
2488                 mPackages[pidx] = curPI;
2489             }
2490             curType = 0xffffffff;
2491         }
2492         if (curType != t) {
2493             if (t >= curPI->numTypes) {
2494                 ALOGE("Style contains key with bad type: 0x%08x\n", attrRes);
2495                 bag++;
2496                 continue;
2497             }
2498             curType = t;
2499             curEntries = curPI->types[t].entries;
2500             if (curEntries == NULL) {
2501                 PackageGroup* const grp = mTable.mPackageGroups[curPackageIndex];
2502                 const Type* type = grp->packages[0]->getType(t);
2503                 int cnt = type != NULL ? type->entryCount : 0;
2504                 curEntries = (theme_entry*)malloc(cnt*sizeof(theme_entry));
2505                 memset(curEntries, Res_value::TYPE_NULL, cnt*sizeof(theme_entry));
2506                 curPI->types[t].numEntries = cnt;
2507                 curPI->types[t].entries = curEntries;
2508             }
2509             numEntries = curPI->types[t].numEntries;
2510         }
2511         if (e >= numEntries) {
2512             ALOGE("Style contains key with bad entry: 0x%08x\n", attrRes);
2513             bag++;
2514             continue;
2515         }
2516         theme_entry* curEntry = curEntries + e;
2517         TABLE_NOISY(ALOGV("Attr 0x%08x: type=0x%x, data=0x%08x; curType=0x%x",
2518                    attrRes, bag->map.value.dataType, bag->map.value.data,
2519              curEntry->value.dataType));
2520         if (force || curEntry->value.dataType == Res_value::TYPE_NULL) {
2521             curEntry->stringBlock = bag->stringBlock;
2522             curEntry->typeSpecFlags |= bagTypeSpecFlags;
2523             curEntry->value = bag->map.value;
2524         }
2525 
2526         bag++;
2527     }
2528 
2529     mTable.unlock();
2530 
2531     //ALOGI("Applying style 0x%08x (force=%d)  theme %p...\n", resID, force, this);
2532     //dumpToLog();
2533 
2534     return NO_ERROR;
2535 }
2536 
setTo(const Theme & other)2537 status_t ResTable::Theme::setTo(const Theme& other)
2538 {
2539     //ALOGI("Setting theme %p from theme %p...\n", this, &other);
2540     //dumpToLog();
2541     //other.dumpToLog();
2542 
2543     if (&mTable == &other.mTable) {
2544         for (size_t i=0; i<Res_MAXPACKAGE; i++) {
2545             if (mPackages[i] != NULL) {
2546                 free_package(mPackages[i]);
2547             }
2548             if (other.mPackages[i] != NULL) {
2549                 mPackages[i] = copy_package(other.mPackages[i]);
2550             } else {
2551                 mPackages[i] = NULL;
2552             }
2553         }
2554     } else {
2555         // @todo: need to really implement this, not just copy
2556         // the system package (which is still wrong because it isn't
2557         // fixing up resource references).
2558         for (size_t i=0; i<Res_MAXPACKAGE; i++) {
2559             if (mPackages[i] != NULL) {
2560                 free_package(mPackages[i]);
2561             }
2562             if (i == 0 && other.mPackages[i] != NULL) {
2563                 mPackages[i] = copy_package(other.mPackages[i]);
2564             } else {
2565                 mPackages[i] = NULL;
2566             }
2567         }
2568     }
2569 
2570     //ALOGI("Final theme:");
2571     //dumpToLog();
2572 
2573     return NO_ERROR;
2574 }
2575 
getAttribute(uint32_t resID,Res_value * outValue,uint32_t * outTypeSpecFlags) const2576 ssize_t ResTable::Theme::getAttribute(uint32_t resID, Res_value* outValue,
2577         uint32_t* outTypeSpecFlags) const
2578 {
2579     int cnt = 20;
2580 
2581     if (outTypeSpecFlags != NULL) *outTypeSpecFlags = 0;
2582 
2583     do {
2584         const ssize_t p = mTable.getResourcePackageIndex(resID);
2585         const uint32_t t = Res_GETTYPE(resID);
2586         const uint32_t e = Res_GETENTRY(resID);
2587 
2588         TABLE_THEME(ALOGI("Looking up attr 0x%08x in theme %p", resID, this));
2589 
2590         if (p >= 0) {
2591             const package_info* const pi = mPackages[p];
2592             TABLE_THEME(ALOGI("Found package: %p", pi));
2593             if (pi != NULL) {
2594                 TABLE_THEME(ALOGI("Desired type index is %ld in avail %d", t, pi->numTypes));
2595                 if (t < pi->numTypes) {
2596                     const type_info& ti = pi->types[t];
2597                     TABLE_THEME(ALOGI("Desired entry index is %ld in avail %d", e, ti.numEntries));
2598                     if (e < ti.numEntries) {
2599                         const theme_entry& te = ti.entries[e];
2600                         if (outTypeSpecFlags != NULL) {
2601                             *outTypeSpecFlags |= te.typeSpecFlags;
2602                         }
2603                         TABLE_THEME(ALOGI("Theme value: type=0x%x, data=0x%08x",
2604                                 te.value.dataType, te.value.data));
2605                         const uint8_t type = te.value.dataType;
2606                         if (type == Res_value::TYPE_ATTRIBUTE) {
2607                             if (cnt > 0) {
2608                                 cnt--;
2609                                 resID = te.value.data;
2610                                 continue;
2611                             }
2612                             ALOGW("Too many attribute references, stopped at: 0x%08x\n", resID);
2613                             return BAD_INDEX;
2614                         } else if (type != Res_value::TYPE_NULL) {
2615                             *outValue = te.value;
2616                             return te.stringBlock;
2617                         }
2618                         return BAD_INDEX;
2619                     }
2620                 }
2621             }
2622         }
2623         break;
2624 
2625     } while (true);
2626 
2627     return BAD_INDEX;
2628 }
2629 
resolveAttributeReference(Res_value * inOutValue,ssize_t blockIndex,uint32_t * outLastRef,uint32_t * inoutTypeSpecFlags,ResTable_config * inoutConfig) const2630 ssize_t ResTable::Theme::resolveAttributeReference(Res_value* inOutValue,
2631         ssize_t blockIndex, uint32_t* outLastRef,
2632         uint32_t* inoutTypeSpecFlags, ResTable_config* inoutConfig) const
2633 {
2634     //printf("Resolving type=0x%x\n", inOutValue->dataType);
2635     if (inOutValue->dataType == Res_value::TYPE_ATTRIBUTE) {
2636         uint32_t newTypeSpecFlags;
2637         blockIndex = getAttribute(inOutValue->data, inOutValue, &newTypeSpecFlags);
2638         TABLE_THEME(ALOGI("Resolving attr reference: blockIndex=%d, type=0x%x, data=%p\n",
2639              (int)blockIndex, (int)inOutValue->dataType, (void*)inOutValue->data));
2640         if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newTypeSpecFlags;
2641         //printf("Retrieved attribute new type=0x%x\n", inOutValue->dataType);
2642         if (blockIndex < 0) {
2643             return blockIndex;
2644         }
2645     }
2646     return mTable.resolveReference(inOutValue, blockIndex, outLastRef,
2647             inoutTypeSpecFlags, inoutConfig);
2648 }
2649 
dumpToLog() const2650 void ResTable::Theme::dumpToLog() const
2651 {
2652     ALOGI("Theme %p:\n", this);
2653     for (size_t i=0; i<Res_MAXPACKAGE; i++) {
2654         package_info* pi = mPackages[i];
2655         if (pi == NULL) continue;
2656 
2657         ALOGI("  Package #0x%02x:\n", (int)(i+1));
2658         for (size_t j=0; j<pi->numTypes; j++) {
2659             type_info& ti = pi->types[j];
2660             if (ti.numEntries == 0) continue;
2661 
2662             ALOGI("    Type #0x%02x:\n", (int)(j+1));
2663             for (size_t k=0; k<ti.numEntries; k++) {
2664                 theme_entry& te = ti.entries[k];
2665                 if (te.value.dataType == Res_value::TYPE_NULL) continue;
2666                 ALOGI("      0x%08x: t=0x%x, d=0x%08x (block=%d)\n",
2667                      (int)Res_MAKEID(i, j, k),
2668                      te.value.dataType, (int)te.value.data, (int)te.stringBlock);
2669             }
2670         }
2671     }
2672 }
2673 
ResTable()2674 ResTable::ResTable()
2675     : mError(NO_INIT)
2676 {
2677     memset(&mParams, 0, sizeof(mParams));
2678     memset(mPackageMap, 0, sizeof(mPackageMap));
2679     //ALOGI("Creating ResTable %p\n", this);
2680 }
2681 
ResTable(const void * data,size_t size,void * cookie,bool copyData)2682 ResTable::ResTable(const void* data, size_t size, void* cookie, bool copyData)
2683     : mError(NO_INIT)
2684 {
2685     memset(&mParams, 0, sizeof(mParams));
2686     memset(mPackageMap, 0, sizeof(mPackageMap));
2687     add(data, size, cookie, copyData);
2688     LOG_FATAL_IF(mError != NO_ERROR, "Error parsing resource table");
2689     //ALOGI("Creating ResTable %p\n", this);
2690 }
2691 
~ResTable()2692 ResTable::~ResTable()
2693 {
2694     //ALOGI("Destroying ResTable in %p\n", this);
2695     uninit();
2696 }
2697 
getResourcePackageIndex(uint32_t resID) const2698 inline ssize_t ResTable::getResourcePackageIndex(uint32_t resID) const
2699 {
2700     return ((ssize_t)mPackageMap[Res_GETPACKAGE(resID)+1])-1;
2701 }
2702 
add(const void * data,size_t size,void * cookie,bool copyData,const void * idmap)2703 status_t ResTable::add(const void* data, size_t size, void* cookie, bool copyData,
2704                        const void* idmap)
2705 {
2706     return add(data, size, cookie, NULL, copyData, reinterpret_cast<const Asset*>(idmap));
2707 }
2708 
add(Asset * asset,void * cookie,bool copyData,const void * idmap)2709 status_t ResTable::add(Asset* asset, void* cookie, bool copyData, const void* idmap)
2710 {
2711     const void* data = asset->getBuffer(true);
2712     if (data == NULL) {
2713         ALOGW("Unable to get buffer of resource asset file");
2714         return UNKNOWN_ERROR;
2715     }
2716     size_t size = (size_t)asset->getLength();
2717     return add(data, size, cookie, asset, copyData, reinterpret_cast<const Asset*>(idmap));
2718 }
2719 
add(ResTable * src)2720 status_t ResTable::add(ResTable* src)
2721 {
2722     mError = src->mError;
2723 
2724     for (size_t i=0; i<src->mHeaders.size(); i++) {
2725         mHeaders.add(src->mHeaders[i]);
2726     }
2727 
2728     for (size_t i=0; i<src->mPackageGroups.size(); i++) {
2729         PackageGroup* srcPg = src->mPackageGroups[i];
2730         PackageGroup* pg = new PackageGroup(this, srcPg->name, srcPg->id);
2731         for (size_t j=0; j<srcPg->packages.size(); j++) {
2732             pg->packages.add(srcPg->packages[j]);
2733         }
2734         pg->basePackage = srcPg->basePackage;
2735         pg->typeCount = srcPg->typeCount;
2736         mPackageGroups.add(pg);
2737     }
2738 
2739     memcpy(mPackageMap, src->mPackageMap, sizeof(mPackageMap));
2740 
2741     return mError;
2742 }
2743 
add(const void * data,size_t size,void * cookie,Asset * asset,bool copyData,const Asset * idmap)2744 status_t ResTable::add(const void* data, size_t size, void* cookie,
2745                        Asset* asset, bool copyData, const Asset* idmap)
2746 {
2747     if (!data) return NO_ERROR;
2748     Header* header = new Header(this);
2749     header->index = mHeaders.size();
2750     header->cookie = cookie;
2751     if (idmap != NULL) {
2752         const size_t idmap_size = idmap->getLength();
2753         const void* idmap_data = const_cast<Asset*>(idmap)->getBuffer(true);
2754         header->resourceIDMap = (uint32_t*)malloc(idmap_size);
2755         if (header->resourceIDMap == NULL) {
2756             delete header;
2757             return (mError = NO_MEMORY);
2758         }
2759         memcpy((void*)header->resourceIDMap, idmap_data, idmap_size);
2760         header->resourceIDMapSize = idmap_size;
2761     }
2762     mHeaders.add(header);
2763 
2764     const bool notDeviceEndian = htods(0xf0) != 0xf0;
2765 
2766     LOAD_TABLE_NOISY(
2767         ALOGV("Adding resources to ResTable: data=%p, size=0x%x, cookie=%p, asset=%p, copy=%d "
2768              "idmap=%p\n", data, size, cookie, asset, copyData, idmap));
2769 
2770     if (copyData || notDeviceEndian) {
2771         header->ownedData = malloc(size);
2772         if (header->ownedData == NULL) {
2773             return (mError=NO_MEMORY);
2774         }
2775         memcpy(header->ownedData, data, size);
2776         data = header->ownedData;
2777     }
2778 
2779     header->header = (const ResTable_header*)data;
2780     header->size = dtohl(header->header->header.size);
2781     //ALOGI("Got size 0x%x, again size 0x%x, raw size 0x%x\n", header->size,
2782     //     dtohl(header->header->header.size), header->header->header.size);
2783     LOAD_TABLE_NOISY(ALOGV("Loading ResTable @%p:\n", header->header));
2784     LOAD_TABLE_NOISY(printHexData(2, header->header, header->size < 256 ? header->size : 256,
2785                                   16, 16, 0, false, printToLogFunc));
2786     if (dtohs(header->header->header.headerSize) > header->size
2787             || header->size > size) {
2788         ALOGW("Bad resource table: header size 0x%x or total size 0x%x is larger than data size 0x%x\n",
2789              (int)dtohs(header->header->header.headerSize),
2790              (int)header->size, (int)size);
2791         return (mError=BAD_TYPE);
2792     }
2793     if (((dtohs(header->header->header.headerSize)|header->size)&0x3) != 0) {
2794         ALOGW("Bad resource table: header size 0x%x or total size 0x%x is not on an integer boundary\n",
2795              (int)dtohs(header->header->header.headerSize),
2796              (int)header->size);
2797         return (mError=BAD_TYPE);
2798     }
2799     header->dataEnd = ((const uint8_t*)header->header) + header->size;
2800 
2801     // Iterate through all chunks.
2802     size_t curPackage = 0;
2803 
2804     const ResChunk_header* chunk =
2805         (const ResChunk_header*)(((const uint8_t*)header->header)
2806                                  + dtohs(header->header->header.headerSize));
2807     while (((const uint8_t*)chunk) <= (header->dataEnd-sizeof(ResChunk_header)) &&
2808            ((const uint8_t*)chunk) <= (header->dataEnd-dtohl(chunk->size))) {
2809         status_t err = validate_chunk(chunk, sizeof(ResChunk_header), header->dataEnd, "ResTable");
2810         if (err != NO_ERROR) {
2811             return (mError=err);
2812         }
2813         TABLE_NOISY(ALOGV("Chunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n",
2814                      dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
2815                      (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header))));
2816         const size_t csize = dtohl(chunk->size);
2817         const uint16_t ctype = dtohs(chunk->type);
2818         if (ctype == RES_STRING_POOL_TYPE) {
2819             if (header->values.getError() != NO_ERROR) {
2820                 // Only use the first string chunk; ignore any others that
2821                 // may appear.
2822                 status_t err = header->values.setTo(chunk, csize);
2823                 if (err != NO_ERROR) {
2824                     return (mError=err);
2825                 }
2826             } else {
2827                 ALOGW("Multiple string chunks found in resource table.");
2828             }
2829         } else if (ctype == RES_TABLE_PACKAGE_TYPE) {
2830             if (curPackage >= dtohl(header->header->packageCount)) {
2831                 ALOGW("More package chunks were found than the %d declared in the header.",
2832                      dtohl(header->header->packageCount));
2833                 return (mError=BAD_TYPE);
2834             }
2835             uint32_t idmap_id = 0;
2836             if (idmap != NULL) {
2837                 uint32_t tmp;
2838                 if (getIdmapPackageId(header->resourceIDMap,
2839                                       header->resourceIDMapSize,
2840                                       &tmp) == NO_ERROR) {
2841                     idmap_id = tmp;
2842                 }
2843             }
2844             if (parsePackage((ResTable_package*)chunk, header, idmap_id) != NO_ERROR) {
2845                 return mError;
2846             }
2847             curPackage++;
2848         } else {
2849             ALOGW("Unknown chunk type %p in table at %p.\n",
2850                  (void*)(int)(ctype),
2851                  (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)));
2852         }
2853         chunk = (const ResChunk_header*)
2854             (((const uint8_t*)chunk) + csize);
2855     }
2856 
2857     if (curPackage < dtohl(header->header->packageCount)) {
2858         ALOGW("Fewer package chunks (%d) were found than the %d declared in the header.",
2859              (int)curPackage, dtohl(header->header->packageCount));
2860         return (mError=BAD_TYPE);
2861     }
2862     mError = header->values.getError();
2863     if (mError != NO_ERROR) {
2864         ALOGW("No string values found in resource table!");
2865     }
2866 
2867     TABLE_NOISY(ALOGV("Returning from add with mError=%d\n", mError));
2868     return mError;
2869 }
2870 
getError() const2871 status_t ResTable::getError() const
2872 {
2873     return mError;
2874 }
2875 
uninit()2876 void ResTable::uninit()
2877 {
2878     mError = NO_INIT;
2879     size_t N = mPackageGroups.size();
2880     for (size_t i=0; i<N; i++) {
2881         PackageGroup* g = mPackageGroups[i];
2882         delete g;
2883     }
2884     N = mHeaders.size();
2885     for (size_t i=0; i<N; i++) {
2886         Header* header = mHeaders[i];
2887         if (header->owner == this) {
2888             if (header->ownedData) {
2889                 free(header->ownedData);
2890             }
2891             delete header;
2892         }
2893     }
2894 
2895     mPackageGroups.clear();
2896     mHeaders.clear();
2897 }
2898 
getResourceName(uint32_t resID,resource_name * outName) const2899 bool ResTable::getResourceName(uint32_t resID, resource_name* outName) const
2900 {
2901     if (mError != NO_ERROR) {
2902         return false;
2903     }
2904 
2905     const ssize_t p = getResourcePackageIndex(resID);
2906     const int t = Res_GETTYPE(resID);
2907     const int e = Res_GETENTRY(resID);
2908 
2909     if (p < 0) {
2910         if (Res_GETPACKAGE(resID)+1 == 0) {
2911             ALOGW("No package identifier when getting name for resource number 0x%08x", resID);
2912         } else {
2913             ALOGW("No known package when getting name for resource number 0x%08x", resID);
2914         }
2915         return false;
2916     }
2917     if (t < 0) {
2918         ALOGW("No type identifier when getting name for resource number 0x%08x", resID);
2919         return false;
2920     }
2921 
2922     const PackageGroup* const grp = mPackageGroups[p];
2923     if (grp == NULL) {
2924         ALOGW("Bad identifier when getting name for resource number 0x%08x", resID);
2925         return false;
2926     }
2927     if (grp->packages.size() > 0) {
2928         const Package* const package = grp->packages[0];
2929 
2930         const ResTable_type* type;
2931         const ResTable_entry* entry;
2932         ssize_t offset = getEntry(package, t, e, NULL, &type, &entry, NULL);
2933         if (offset <= 0) {
2934             return false;
2935         }
2936 
2937         outName->package = grp->name.string();
2938         outName->packageLen = grp->name.size();
2939         outName->type = grp->basePackage->typeStrings.stringAt(t, &outName->typeLen);
2940         outName->name = grp->basePackage->keyStrings.stringAt(
2941             dtohl(entry->key.index), &outName->nameLen);
2942 
2943         // If we have a bad index for some reason, we should abort.
2944         if (outName->type == NULL || outName->name == NULL) {
2945             return false;
2946         }
2947 
2948         return true;
2949     }
2950 
2951     return false;
2952 }
2953 
getResource(uint32_t resID,Res_value * outValue,bool mayBeBag,uint16_t density,uint32_t * outSpecFlags,ResTable_config * outConfig) const2954 ssize_t ResTable::getResource(uint32_t resID, Res_value* outValue, bool mayBeBag, uint16_t density,
2955         uint32_t* outSpecFlags, ResTable_config* outConfig) const
2956 {
2957     if (mError != NO_ERROR) {
2958         return mError;
2959     }
2960 
2961     const ssize_t p = getResourcePackageIndex(resID);
2962     const int t = Res_GETTYPE(resID);
2963     const int e = Res_GETENTRY(resID);
2964 
2965     if (p < 0) {
2966         if (Res_GETPACKAGE(resID)+1 == 0) {
2967             ALOGW("No package identifier when getting value for resource number 0x%08x", resID);
2968         } else {
2969             ALOGW("No known package when getting value for resource number 0x%08x", resID);
2970         }
2971         return BAD_INDEX;
2972     }
2973     if (t < 0) {
2974         ALOGW("No type identifier when getting value for resource number 0x%08x", resID);
2975         return BAD_INDEX;
2976     }
2977 
2978     const Res_value* bestValue = NULL;
2979     const Package* bestPackage = NULL;
2980     ResTable_config bestItem;
2981     memset(&bestItem, 0, sizeof(bestItem)); // make the compiler shut up
2982 
2983     if (outSpecFlags != NULL) *outSpecFlags = 0;
2984 
2985     // Look through all resource packages, starting with the most
2986     // recently added.
2987     const PackageGroup* const grp = mPackageGroups[p];
2988     if (grp == NULL) {
2989         ALOGW("Bad identifier when getting value for resource number 0x%08x", resID);
2990         return BAD_INDEX;
2991     }
2992 
2993     // Allow overriding density
2994     const ResTable_config* desiredConfig = &mParams;
2995     ResTable_config* overrideConfig = NULL;
2996     if (density > 0) {
2997         overrideConfig = (ResTable_config*) malloc(sizeof(ResTable_config));
2998         if (overrideConfig == NULL) {
2999             ALOGE("Couldn't malloc ResTable_config for overrides: %s", strerror(errno));
3000             return BAD_INDEX;
3001         }
3002         memcpy(overrideConfig, &mParams, sizeof(ResTable_config));
3003         overrideConfig->density = density;
3004         desiredConfig = overrideConfig;
3005     }
3006 
3007     ssize_t rc = BAD_VALUE;
3008     size_t ip = grp->packages.size();
3009     while (ip > 0) {
3010         ip--;
3011         int T = t;
3012         int E = e;
3013 
3014         const Package* const package = grp->packages[ip];
3015         if (package->header->resourceIDMap) {
3016             uint32_t overlayResID = 0x0;
3017             status_t retval = idmapLookup(package->header->resourceIDMap,
3018                                           package->header->resourceIDMapSize,
3019                                           resID, &overlayResID);
3020             if (retval == NO_ERROR && overlayResID != 0x0) {
3021                 // for this loop iteration, this is the type and entry we really want
3022                 ALOGV("resource map 0x%08x -> 0x%08x\n", resID, overlayResID);
3023                 T = Res_GETTYPE(overlayResID);
3024                 E = Res_GETENTRY(overlayResID);
3025             } else {
3026                 // resource not present in overlay package, continue with the next package
3027                 continue;
3028             }
3029         }
3030 
3031         const ResTable_type* type;
3032         const ResTable_entry* entry;
3033         const Type* typeClass;
3034         ssize_t offset = getEntry(package, T, E, desiredConfig, &type, &entry, &typeClass);
3035         if (offset <= 0) {
3036             // No {entry, appropriate config} pair found in package. If this
3037             // package is an overlay package (ip != 0), this simply means the
3038             // overlay package did not specify a default.
3039             // Non-overlay packages are still required to provide a default.
3040             if (offset < 0 && ip == 0) {
3041                 ALOGW("Failure getting entry for 0x%08x (t=%d e=%d) in package %zd (error %d)\n",
3042                         resID, T, E, ip, (int)offset);
3043                 rc = offset;
3044                 goto out;
3045             }
3046             continue;
3047         }
3048 
3049         if ((dtohs(entry->flags)&entry->FLAG_COMPLEX) != 0) {
3050             if (!mayBeBag) {
3051                 ALOGW("Requesting resource %p failed because it is complex\n",
3052                      (void*)resID);
3053             }
3054             continue;
3055         }
3056 
3057         TABLE_NOISY(aout << "Resource type data: "
3058               << HexDump(type, dtohl(type->header.size)) << endl);
3059 
3060         if ((size_t)offset > (dtohl(type->header.size)-sizeof(Res_value))) {
3061             ALOGW("ResTable_item at %d is beyond type chunk data %d",
3062                  (int)offset, dtohl(type->header.size));
3063             rc = BAD_TYPE;
3064             goto out;
3065         }
3066 
3067         const Res_value* item =
3068             (const Res_value*)(((const uint8_t*)type) + offset);
3069         ResTable_config thisConfig;
3070         thisConfig.copyFromDtoH(type->config);
3071 
3072         if (outSpecFlags != NULL) {
3073             if (typeClass->typeSpecFlags != NULL) {
3074                 *outSpecFlags |= dtohl(typeClass->typeSpecFlags[E]);
3075             } else {
3076                 *outSpecFlags = -1;
3077             }
3078         }
3079 
3080         if (bestPackage != NULL &&
3081             (bestItem.isMoreSpecificThan(thisConfig) || bestItem.diff(thisConfig) == 0)) {
3082             // Discard thisConfig not only if bestItem is more specific, but also if the two configs
3083             // are identical (diff == 0), or overlay packages will not take effect.
3084             continue;
3085         }
3086 
3087         bestItem = thisConfig;
3088         bestValue = item;
3089         bestPackage = package;
3090     }
3091 
3092     TABLE_NOISY(printf("Found result: package %p\n", bestPackage));
3093 
3094     if (bestValue) {
3095         outValue->size = dtohs(bestValue->size);
3096         outValue->res0 = bestValue->res0;
3097         outValue->dataType = bestValue->dataType;
3098         outValue->data = dtohl(bestValue->data);
3099         if (outConfig != NULL) {
3100             *outConfig = bestItem;
3101         }
3102         TABLE_NOISY(size_t len;
3103               printf("Found value: pkg=%d, type=%d, str=%s, int=%d\n",
3104                      bestPackage->header->index,
3105                      outValue->dataType,
3106                      outValue->dataType == bestValue->TYPE_STRING
3107                      ? String8(bestPackage->header->values.stringAt(
3108                          outValue->data, &len)).string()
3109                      : "",
3110                      outValue->data));
3111         rc = bestPackage->header->index;
3112         goto out;
3113     }
3114 
3115 out:
3116     if (overrideConfig != NULL) {
3117         free(overrideConfig);
3118     }
3119 
3120     return rc;
3121 }
3122 
resolveReference(Res_value * value,ssize_t blockIndex,uint32_t * outLastRef,uint32_t * inoutTypeSpecFlags,ResTable_config * outConfig) const3123 ssize_t ResTable::resolveReference(Res_value* value, ssize_t blockIndex,
3124         uint32_t* outLastRef, uint32_t* inoutTypeSpecFlags,
3125         ResTable_config* outConfig) const
3126 {
3127     int count=0;
3128     while (blockIndex >= 0 && value->dataType == value->TYPE_REFERENCE
3129            && value->data != 0 && count < 20) {
3130         if (outLastRef) *outLastRef = value->data;
3131         uint32_t lastRef = value->data;
3132         uint32_t newFlags = 0;
3133         const ssize_t newIndex = getResource(value->data, value, true, 0, &newFlags,
3134                 outConfig);
3135         if (newIndex == BAD_INDEX) {
3136             return BAD_INDEX;
3137         }
3138         TABLE_THEME(ALOGI("Resolving reference %p: newIndex=%d, type=0x%x, data=%p\n",
3139              (void*)lastRef, (int)newIndex, (int)value->dataType, (void*)value->data));
3140         //printf("Getting reference 0x%08x: newIndex=%d\n", value->data, newIndex);
3141         if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newFlags;
3142         if (newIndex < 0) {
3143             // This can fail if the resource being referenced is a style...
3144             // in this case, just return the reference, and expect the
3145             // caller to deal with.
3146             return blockIndex;
3147         }
3148         blockIndex = newIndex;
3149         count++;
3150     }
3151     return blockIndex;
3152 }
3153 
valueToString(const Res_value * value,size_t stringBlock,char16_t tmpBuffer[TMP_BUFFER_SIZE],size_t * outLen)3154 const char16_t* ResTable::valueToString(
3155     const Res_value* value, size_t stringBlock,
3156     char16_t tmpBuffer[TMP_BUFFER_SIZE], size_t* outLen)
3157 {
3158     if (!value) {
3159         return NULL;
3160     }
3161     if (value->dataType == value->TYPE_STRING) {
3162         return getTableStringBlock(stringBlock)->stringAt(value->data, outLen);
3163     }
3164     // XXX do int to string conversions.
3165     return NULL;
3166 }
3167 
lockBag(uint32_t resID,const bag_entry ** outBag) const3168 ssize_t ResTable::lockBag(uint32_t resID, const bag_entry** outBag) const
3169 {
3170     mLock.lock();
3171     ssize_t err = getBagLocked(resID, outBag);
3172     if (err < NO_ERROR) {
3173         //printf("*** get failed!  unlocking\n");
3174         mLock.unlock();
3175     }
3176     return err;
3177 }
3178 
unlockBag(const bag_entry * bag) const3179 void ResTable::unlockBag(const bag_entry* bag) const
3180 {
3181     //printf("<<< unlockBag %p\n", this);
3182     mLock.unlock();
3183 }
3184 
lock() const3185 void ResTable::lock() const
3186 {
3187     mLock.lock();
3188 }
3189 
unlock() const3190 void ResTable::unlock() const
3191 {
3192     mLock.unlock();
3193 }
3194 
getBagLocked(uint32_t resID,const bag_entry ** outBag,uint32_t * outTypeSpecFlags) const3195 ssize_t ResTable::getBagLocked(uint32_t resID, const bag_entry** outBag,
3196         uint32_t* outTypeSpecFlags) const
3197 {
3198     if (mError != NO_ERROR) {
3199         return mError;
3200     }
3201 
3202     const ssize_t p = getResourcePackageIndex(resID);
3203     const int t = Res_GETTYPE(resID);
3204     const int e = Res_GETENTRY(resID);
3205 
3206     if (p < 0) {
3207         ALOGW("Invalid package identifier when getting bag for resource number 0x%08x", resID);
3208         return BAD_INDEX;
3209     }
3210     if (t < 0) {
3211         ALOGW("No type identifier when getting bag for resource number 0x%08x", resID);
3212         return BAD_INDEX;
3213     }
3214 
3215     //printf("Get bag: id=0x%08x, p=%d, t=%d\n", resID, p, t);
3216     PackageGroup* const grp = mPackageGroups[p];
3217     if (grp == NULL) {
3218         ALOGW("Bad identifier when getting bag for resource number 0x%08x", resID);
3219         return false;
3220     }
3221 
3222     if (t >= (int)grp->typeCount) {
3223         ALOGW("Type identifier 0x%x is larger than type count 0x%x",
3224              t+1, (int)grp->typeCount);
3225         return BAD_INDEX;
3226     }
3227 
3228     const Package* const basePackage = grp->packages[0];
3229 
3230     const Type* const typeConfigs = basePackage->getType(t);
3231 
3232     const size_t NENTRY = typeConfigs->entryCount;
3233     if (e >= (int)NENTRY) {
3234         ALOGW("Entry identifier 0x%x is larger than entry count 0x%x",
3235              e, (int)typeConfigs->entryCount);
3236         return BAD_INDEX;
3237     }
3238 
3239     // First see if we've already computed this bag...
3240     if (grp->bags) {
3241         bag_set** typeSet = grp->bags[t];
3242         if (typeSet) {
3243             bag_set* set = typeSet[e];
3244             if (set) {
3245                 if (set != (bag_set*)0xFFFFFFFF) {
3246                     if (outTypeSpecFlags != NULL) {
3247                         *outTypeSpecFlags = set->typeSpecFlags;
3248                     }
3249                     *outBag = (bag_entry*)(set+1);
3250                     //ALOGI("Found existing bag for: %p\n", (void*)resID);
3251                     return set->numAttrs;
3252                 }
3253                 ALOGW("Attempt to retrieve bag 0x%08x which is invalid or in a cycle.",
3254                      resID);
3255                 return BAD_INDEX;
3256             }
3257         }
3258     }
3259 
3260     // Bag not found, we need to compute it!
3261     if (!grp->bags) {
3262         grp->bags = (bag_set***)calloc(grp->typeCount, sizeof(bag_set*));
3263         if (!grp->bags) return NO_MEMORY;
3264     }
3265 
3266     bag_set** typeSet = grp->bags[t];
3267     if (!typeSet) {
3268         typeSet = (bag_set**)calloc(NENTRY, sizeof(bag_set*));
3269         if (!typeSet) return NO_MEMORY;
3270         grp->bags[t] = typeSet;
3271     }
3272 
3273     // Mark that we are currently working on this one.
3274     typeSet[e] = (bag_set*)0xFFFFFFFF;
3275 
3276     // This is what we are building.
3277     bag_set* set = NULL;
3278 
3279     TABLE_NOISY(ALOGI("Building bag: %p\n", (void*)resID));
3280 
3281     ResTable_config bestConfig;
3282     memset(&bestConfig, 0, sizeof(bestConfig));
3283 
3284     // Now collect all bag attributes from all packages.
3285     size_t ip = grp->packages.size();
3286     while (ip > 0) {
3287         ip--;
3288         int T = t;
3289         int E = e;
3290 
3291         const Package* const package = grp->packages[ip];
3292         if (package->header->resourceIDMap) {
3293             uint32_t overlayResID = 0x0;
3294             status_t retval = idmapLookup(package->header->resourceIDMap,
3295                                           package->header->resourceIDMapSize,
3296                                           resID, &overlayResID);
3297             if (retval == NO_ERROR && overlayResID != 0x0) {
3298                 // for this loop iteration, this is the type and entry we really want
3299                 ALOGV("resource map 0x%08x -> 0x%08x\n", resID, overlayResID);
3300                 T = Res_GETTYPE(overlayResID);
3301                 E = Res_GETENTRY(overlayResID);
3302             } else {
3303                 // resource not present in overlay package, continue with the next package
3304                 continue;
3305             }
3306         }
3307 
3308         const ResTable_type* type;
3309         const ResTable_entry* entry;
3310         const Type* typeClass;
3311         ALOGV("Getting entry pkg=%p, t=%d, e=%d\n", package, T, E);
3312         ssize_t offset = getEntry(package, T, E, &mParams, &type, &entry, &typeClass);
3313         ALOGV("Resulting offset=%d\n", offset);
3314         if (offset <= 0) {
3315             // No {entry, appropriate config} pair found in package. If this
3316             // package is an overlay package (ip != 0), this simply means the
3317             // overlay package did not specify a default.
3318             // Non-overlay packages are still required to provide a default.
3319             if (offset < 0 && ip == 0) {
3320                 if (set) free(set);
3321                 return offset;
3322             }
3323             continue;
3324         }
3325 
3326         if ((dtohs(entry->flags)&entry->FLAG_COMPLEX) == 0) {
3327             ALOGW("Skipping entry %p in package table %d because it is not complex!\n",
3328                  (void*)resID, (int)ip);
3329             continue;
3330         }
3331 
3332         if (set != NULL && !type->config.isBetterThan(bestConfig, NULL)) {
3333             continue;
3334         }
3335         bestConfig = type->config;
3336         if (set) {
3337             free(set);
3338             set = NULL;
3339         }
3340 
3341         const uint16_t entrySize = dtohs(entry->size);
3342         const uint32_t parent = entrySize >= sizeof(ResTable_map_entry)
3343             ? dtohl(((const ResTable_map_entry*)entry)->parent.ident) : 0;
3344         const uint32_t count = entrySize >= sizeof(ResTable_map_entry)
3345             ? dtohl(((const ResTable_map_entry*)entry)->count) : 0;
3346 
3347         size_t N = count;
3348 
3349         TABLE_NOISY(ALOGI("Found map: size=%p parent=%p count=%d\n",
3350                          entrySize, parent, count));
3351 
3352         // If this map inherits from another, we need to start
3353         // with its parent's values.  Otherwise start out empty.
3354         TABLE_NOISY(printf("Creating new bag, entrySize=0x%08x, parent=0x%08x\n",
3355                            entrySize, parent));
3356         if (parent) {
3357             const bag_entry* parentBag;
3358             uint32_t parentTypeSpecFlags = 0;
3359             const ssize_t NP = getBagLocked(parent, &parentBag, &parentTypeSpecFlags);
3360             const size_t NT = ((NP >= 0) ? NP : 0) + N;
3361             set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*NT);
3362             if (set == NULL) {
3363                 return NO_MEMORY;
3364             }
3365             if (NP > 0) {
3366                 memcpy(set+1, parentBag, NP*sizeof(bag_entry));
3367                 set->numAttrs = NP;
3368                 TABLE_NOISY(ALOGI("Initialized new bag with %d inherited attributes.\n", NP));
3369             } else {
3370                 TABLE_NOISY(ALOGI("Initialized new bag with no inherited attributes.\n"));
3371                 set->numAttrs = 0;
3372             }
3373             set->availAttrs = NT;
3374             set->typeSpecFlags = parentTypeSpecFlags;
3375         } else {
3376             set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*N);
3377             if (set == NULL) {
3378                 return NO_MEMORY;
3379             }
3380             set->numAttrs = 0;
3381             set->availAttrs = N;
3382             set->typeSpecFlags = 0;
3383         }
3384 
3385         if (typeClass->typeSpecFlags != NULL) {
3386             set->typeSpecFlags |= dtohl(typeClass->typeSpecFlags[E]);
3387         } else {
3388             set->typeSpecFlags = -1;
3389         }
3390 
3391         // Now merge in the new attributes...
3392         ssize_t curOff = offset;
3393         const ResTable_map* map;
3394         bag_entry* entries = (bag_entry*)(set+1);
3395         size_t curEntry = 0;
3396         uint32_t pos = 0;
3397         TABLE_NOISY(ALOGI("Starting with set %p, entries=%p, avail=%d\n",
3398                      set, entries, set->availAttrs));
3399         while (pos < count) {
3400             TABLE_NOISY(printf("Now at %p\n", (void*)curOff));
3401 
3402             if ((size_t)curOff > (dtohl(type->header.size)-sizeof(ResTable_map))) {
3403                 ALOGW("ResTable_map at %d is beyond type chunk data %d",
3404                      (int)curOff, dtohl(type->header.size));
3405                 return BAD_TYPE;
3406             }
3407             map = (const ResTable_map*)(((const uint8_t*)type) + curOff);
3408             N++;
3409 
3410             const uint32_t newName = htodl(map->name.ident);
3411             bool isInside;
3412             uint32_t oldName = 0;
3413             while ((isInside=(curEntry < set->numAttrs))
3414                     && (oldName=entries[curEntry].map.name.ident) < newName) {
3415                 TABLE_NOISY(printf("#%d: Keeping existing attribute: 0x%08x\n",
3416                              curEntry, entries[curEntry].map.name.ident));
3417                 curEntry++;
3418             }
3419 
3420             if ((!isInside) || oldName != newName) {
3421                 // This is a new attribute...  figure out what to do with it.
3422                 if (set->numAttrs >= set->availAttrs) {
3423                     // Need to alloc more memory...
3424                     const size_t newAvail = set->availAttrs+N;
3425                     set = (bag_set*)realloc(set,
3426                                             sizeof(bag_set)
3427                                             + sizeof(bag_entry)*newAvail);
3428                     if (set == NULL) {
3429                         return NO_MEMORY;
3430                     }
3431                     set->availAttrs = newAvail;
3432                     entries = (bag_entry*)(set+1);
3433                     TABLE_NOISY(printf("Reallocated set %p, entries=%p, avail=%d\n",
3434                                  set, entries, set->availAttrs));
3435                 }
3436                 if (isInside) {
3437                     // Going in the middle, need to make space.
3438                     memmove(entries+curEntry+1, entries+curEntry,
3439                             sizeof(bag_entry)*(set->numAttrs-curEntry));
3440                     set->numAttrs++;
3441                 }
3442                 TABLE_NOISY(printf("#%d: Inserting new attribute: 0x%08x\n",
3443                              curEntry, newName));
3444             } else {
3445                 TABLE_NOISY(printf("#%d: Replacing existing attribute: 0x%08x\n",
3446                              curEntry, oldName));
3447             }
3448 
3449             bag_entry* cur = entries+curEntry;
3450 
3451             cur->stringBlock = package->header->index;
3452             cur->map.name.ident = newName;
3453             cur->map.value.copyFrom_dtoh(map->value);
3454             TABLE_NOISY(printf("Setting entry #%d %p: block=%d, name=0x%08x, type=%d, data=0x%08x\n",
3455                          curEntry, cur, cur->stringBlock, cur->map.name.ident,
3456                          cur->map.value.dataType, cur->map.value.data));
3457 
3458             // On to the next!
3459             curEntry++;
3460             pos++;
3461             const size_t size = dtohs(map->value.size);
3462             curOff += size + sizeof(*map)-sizeof(map->value);
3463         };
3464         if (curEntry > set->numAttrs) {
3465             set->numAttrs = curEntry;
3466         }
3467     }
3468 
3469     // And this is it...
3470     typeSet[e] = set;
3471     if (set) {
3472         if (outTypeSpecFlags != NULL) {
3473             *outTypeSpecFlags = set->typeSpecFlags;
3474         }
3475         *outBag = (bag_entry*)(set+1);
3476         TABLE_NOISY(ALOGI("Returning %d attrs\n", set->numAttrs));
3477         return set->numAttrs;
3478     }
3479     return BAD_INDEX;
3480 }
3481 
setParameters(const ResTable_config * params)3482 void ResTable::setParameters(const ResTable_config* params)
3483 {
3484     mLock.lock();
3485     TABLE_GETENTRY(ALOGI("Setting parameters: %s\n", params->toString().string()));
3486     mParams = *params;
3487     for (size_t i=0; i<mPackageGroups.size(); i++) {
3488         TABLE_NOISY(ALOGI("CLEARING BAGS FOR GROUP %d!", i));
3489         mPackageGroups[i]->clearBagCache();
3490     }
3491     mLock.unlock();
3492 }
3493 
getParameters(ResTable_config * params) const3494 void ResTable::getParameters(ResTable_config* params) const
3495 {
3496     mLock.lock();
3497     *params = mParams;
3498     mLock.unlock();
3499 }
3500 
3501 struct id_name_map {
3502     uint32_t id;
3503     size_t len;
3504     char16_t name[6];
3505 };
3506 
3507 const static id_name_map ID_NAMES[] = {
3508     { ResTable_map::ATTR_TYPE,  5, { '^', 't', 'y', 'p', 'e' } },
3509     { ResTable_map::ATTR_L10N,  5, { '^', 'l', '1', '0', 'n' } },
3510     { ResTable_map::ATTR_MIN,   4, { '^', 'm', 'i', 'n' } },
3511     { ResTable_map::ATTR_MAX,   4, { '^', 'm', 'a', 'x' } },
3512     { ResTable_map::ATTR_OTHER, 6, { '^', 'o', 't', 'h', 'e', 'r' } },
3513     { ResTable_map::ATTR_ZERO,  5, { '^', 'z', 'e', 'r', 'o' } },
3514     { ResTable_map::ATTR_ONE,   4, { '^', 'o', 'n', 'e' } },
3515     { ResTable_map::ATTR_TWO,   4, { '^', 't', 'w', 'o' } },
3516     { ResTable_map::ATTR_FEW,   4, { '^', 'f', 'e', 'w' } },
3517     { ResTable_map::ATTR_MANY,  5, { '^', 'm', 'a', 'n', 'y' } },
3518 };
3519 
identifierForName(const char16_t * name,size_t nameLen,const char16_t * type,size_t typeLen,const char16_t * package,size_t packageLen,uint32_t * outTypeSpecFlags) const3520 uint32_t ResTable::identifierForName(const char16_t* name, size_t nameLen,
3521                                      const char16_t* type, size_t typeLen,
3522                                      const char16_t* package,
3523                                      size_t packageLen,
3524                                      uint32_t* outTypeSpecFlags) const
3525 {
3526     TABLE_SUPER_NOISY(printf("Identifier for name: error=%d\n", mError));
3527 
3528     // Check for internal resource identifier as the very first thing, so
3529     // that we will always find them even when there are no resources.
3530     if (name[0] == '^') {
3531         const int N = (sizeof(ID_NAMES)/sizeof(ID_NAMES[0]));
3532         size_t len;
3533         for (int i=0; i<N; i++) {
3534             const id_name_map* m = ID_NAMES + i;
3535             len = m->len;
3536             if (len != nameLen) {
3537                 continue;
3538             }
3539             for (size_t j=1; j<len; j++) {
3540                 if (m->name[j] != name[j]) {
3541                     goto nope;
3542                 }
3543             }
3544             if (outTypeSpecFlags) {
3545                 *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC;
3546             }
3547             return m->id;
3548 nope:
3549             ;
3550         }
3551         if (nameLen > 7) {
3552             if (name[1] == 'i' && name[2] == 'n'
3553                 && name[3] == 'd' && name[4] == 'e' && name[5] == 'x'
3554                 && name[6] == '_') {
3555                 int index = atoi(String8(name + 7, nameLen - 7).string());
3556                 if (Res_CHECKID(index)) {
3557                     ALOGW("Array resource index: %d is too large.",
3558                          index);
3559                     return 0;
3560                 }
3561                 if (outTypeSpecFlags) {
3562                     *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC;
3563                 }
3564                 return  Res_MAKEARRAY(index);
3565             }
3566         }
3567         return 0;
3568     }
3569 
3570     if (mError != NO_ERROR) {
3571         return 0;
3572     }
3573 
3574     bool fakePublic = false;
3575 
3576     // Figure out the package and type we are looking in...
3577 
3578     const char16_t* packageEnd = NULL;
3579     const char16_t* typeEnd = NULL;
3580     const char16_t* const nameEnd = name+nameLen;
3581     const char16_t* p = name;
3582     while (p < nameEnd) {
3583         if (*p == ':') packageEnd = p;
3584         else if (*p == '/') typeEnd = p;
3585         p++;
3586     }
3587     if (*name == '@') {
3588         name++;
3589         if (*name == '*') {
3590             fakePublic = true;
3591             name++;
3592         }
3593     }
3594     if (name >= nameEnd) {
3595         return 0;
3596     }
3597 
3598     if (packageEnd) {
3599         package = name;
3600         packageLen = packageEnd-name;
3601         name = packageEnd+1;
3602     } else if (!package) {
3603         return 0;
3604     }
3605 
3606     if (typeEnd) {
3607         type = name;
3608         typeLen = typeEnd-name;
3609         name = typeEnd+1;
3610     } else if (!type) {
3611         return 0;
3612     }
3613 
3614     if (name >= nameEnd) {
3615         return 0;
3616     }
3617     nameLen = nameEnd-name;
3618 
3619     TABLE_NOISY(printf("Looking for identifier: type=%s, name=%s, package=%s\n",
3620                  String8(type, typeLen).string(),
3621                  String8(name, nameLen).string(),
3622                  String8(package, packageLen).string()));
3623 
3624     const size_t NG = mPackageGroups.size();
3625     for (size_t ig=0; ig<NG; ig++) {
3626         const PackageGroup* group = mPackageGroups[ig];
3627 
3628         if (strzcmp16(package, packageLen,
3629                       group->name.string(), group->name.size())) {
3630             TABLE_NOISY(printf("Skipping package group: %s\n", String8(group->name).string()));
3631             continue;
3632         }
3633 
3634         const ssize_t ti = group->basePackage->typeStrings.indexOfString(type, typeLen);
3635         if (ti < 0) {
3636             TABLE_NOISY(printf("Type not found in package %s\n", String8(group->name).string()));
3637             continue;
3638         }
3639 
3640         const ssize_t ei = group->basePackage->keyStrings.indexOfString(name, nameLen);
3641         if (ei < 0) {
3642             TABLE_NOISY(printf("Name not found in package %s\n", String8(group->name).string()));
3643             continue;
3644         }
3645 
3646         TABLE_NOISY(printf("Search indices: type=%d, name=%d\n", ti, ei));
3647 
3648         const Type* const typeConfigs = group->packages[0]->getType(ti);
3649         if (typeConfigs == NULL || typeConfigs->configs.size() <= 0) {
3650             TABLE_NOISY(printf("Expected type structure not found in package %s for idnex %d\n",
3651                                String8(group->name).string(), ti));
3652         }
3653 
3654         size_t NTC = typeConfigs->configs.size();
3655         for (size_t tci=0; tci<NTC; tci++) {
3656             const ResTable_type* const ty = typeConfigs->configs[tci];
3657             const uint32_t typeOffset = dtohl(ty->entriesStart);
3658 
3659             const uint8_t* const end = ((const uint8_t*)ty) + dtohl(ty->header.size);
3660             const uint32_t* const eindex = (const uint32_t*)
3661                 (((const uint8_t*)ty) + dtohs(ty->header.headerSize));
3662 
3663             const size_t NE = dtohl(ty->entryCount);
3664             for (size_t i=0; i<NE; i++) {
3665                 uint32_t offset = dtohl(eindex[i]);
3666                 if (offset == ResTable_type::NO_ENTRY) {
3667                     continue;
3668                 }
3669 
3670                 offset += typeOffset;
3671 
3672                 if (offset > (dtohl(ty->header.size)-sizeof(ResTable_entry))) {
3673                     ALOGW("ResTable_entry at %d is beyond type chunk data %d",
3674                          offset, dtohl(ty->header.size));
3675                     return 0;
3676                 }
3677                 if ((offset&0x3) != 0) {
3678                     ALOGW("ResTable_entry at %d (pkg=%d type=%d ent=%d) is not on an integer boundary when looking for %s:%s/%s",
3679                          (int)offset, (int)group->id, (int)ti+1, (int)i,
3680                          String8(package, packageLen).string(),
3681                          String8(type, typeLen).string(),
3682                          String8(name, nameLen).string());
3683                     return 0;
3684                 }
3685 
3686                 const ResTable_entry* const entry = (const ResTable_entry*)
3687                     (((const uint8_t*)ty) + offset);
3688                 if (dtohs(entry->size) < sizeof(*entry)) {
3689                     ALOGW("ResTable_entry size %d is too small", dtohs(entry->size));
3690                     return BAD_TYPE;
3691                 }
3692 
3693                 TABLE_SUPER_NOISY(printf("Looking at entry #%d: want str %d, have %d\n",
3694                                          i, ei, dtohl(entry->key.index)));
3695                 if (dtohl(entry->key.index) == (size_t)ei) {
3696                     if (outTypeSpecFlags) {
3697                         *outTypeSpecFlags = typeConfigs->typeSpecFlags[i];
3698                         if (fakePublic) {
3699                             *outTypeSpecFlags |= ResTable_typeSpec::SPEC_PUBLIC;
3700                         }
3701                     }
3702                     return Res_MAKEID(group->id-1, ti, i);
3703                 }
3704             }
3705         }
3706     }
3707 
3708     return 0;
3709 }
3710 
expandResourceRef(const uint16_t * refStr,size_t refLen,String16 * outPackage,String16 * outType,String16 * outName,const String16 * defType,const String16 * defPackage,const char ** outErrorMsg,bool * outPublicOnly)3711 bool ResTable::expandResourceRef(const uint16_t* refStr, size_t refLen,
3712                                  String16* outPackage,
3713                                  String16* outType,
3714                                  String16* outName,
3715                                  const String16* defType,
3716                                  const String16* defPackage,
3717                                  const char** outErrorMsg,
3718                                  bool* outPublicOnly)
3719 {
3720     const char16_t* packageEnd = NULL;
3721     const char16_t* typeEnd = NULL;
3722     const char16_t* p = refStr;
3723     const char16_t* const end = p + refLen;
3724     while (p < end) {
3725         if (*p == ':') packageEnd = p;
3726         else if (*p == '/') {
3727             typeEnd = p;
3728             break;
3729         }
3730         p++;
3731     }
3732     p = refStr;
3733     if (*p == '@') p++;
3734 
3735     if (outPublicOnly != NULL) {
3736         *outPublicOnly = true;
3737     }
3738     if (*p == '*') {
3739         p++;
3740         if (outPublicOnly != NULL) {
3741             *outPublicOnly = false;
3742         }
3743     }
3744 
3745     if (packageEnd) {
3746         *outPackage = String16(p, packageEnd-p);
3747         p = packageEnd+1;
3748     } else {
3749         if (!defPackage) {
3750             if (outErrorMsg) {
3751                 *outErrorMsg = "No resource package specified";
3752             }
3753             return false;
3754         }
3755         *outPackage = *defPackage;
3756     }
3757     if (typeEnd) {
3758         *outType = String16(p, typeEnd-p);
3759         p = typeEnd+1;
3760     } else {
3761         if (!defType) {
3762             if (outErrorMsg) {
3763                 *outErrorMsg = "No resource type specified";
3764             }
3765             return false;
3766         }
3767         *outType = *defType;
3768     }
3769     *outName = String16(p, end-p);
3770     if(**outPackage == 0) {
3771         if(outErrorMsg) {
3772             *outErrorMsg = "Resource package cannot be an empty string";
3773         }
3774         return false;
3775     }
3776     if(**outType == 0) {
3777         if(outErrorMsg) {
3778             *outErrorMsg = "Resource type cannot be an empty string";
3779         }
3780         return false;
3781     }
3782     if(**outName == 0) {
3783         if(outErrorMsg) {
3784             *outErrorMsg = "Resource id cannot be an empty string";
3785         }
3786         return false;
3787     }
3788     return true;
3789 }
3790 
get_hex(char c,bool * outError)3791 static uint32_t get_hex(char c, bool* outError)
3792 {
3793     if (c >= '0' && c <= '9') {
3794         return c - '0';
3795     } else if (c >= 'a' && c <= 'f') {
3796         return c - 'a' + 0xa;
3797     } else if (c >= 'A' && c <= 'F') {
3798         return c - 'A' + 0xa;
3799     }
3800     *outError = true;
3801     return 0;
3802 }
3803 
3804 struct unit_entry
3805 {
3806     const char* name;
3807     size_t len;
3808     uint8_t type;
3809     uint32_t unit;
3810     float scale;
3811 };
3812 
3813 static const unit_entry unitNames[] = {
3814     { "px", strlen("px"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PX, 1.0f },
3815     { "dip", strlen("dip"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
3816     { "dp", strlen("dp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
3817     { "sp", strlen("sp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_SP, 1.0f },
3818     { "pt", strlen("pt"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PT, 1.0f },
3819     { "in", strlen("in"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_IN, 1.0f },
3820     { "mm", strlen("mm"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_MM, 1.0f },
3821     { "%", strlen("%"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION, 1.0f/100 },
3822     { "%p", strlen("%p"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION_PARENT, 1.0f/100 },
3823     { NULL, 0, 0, 0, 0 }
3824 };
3825 
parse_unit(const char * str,Res_value * outValue,float * outScale,const char ** outEnd)3826 static bool parse_unit(const char* str, Res_value* outValue,
3827                        float* outScale, const char** outEnd)
3828 {
3829     const char* end = str;
3830     while (*end != 0 && !isspace((unsigned char)*end)) {
3831         end++;
3832     }
3833     const size_t len = end-str;
3834 
3835     const char* realEnd = end;
3836     while (*realEnd != 0 && isspace((unsigned char)*realEnd)) {
3837         realEnd++;
3838     }
3839     if (*realEnd != 0) {
3840         return false;
3841     }
3842 
3843     const unit_entry* cur = unitNames;
3844     while (cur->name) {
3845         if (len == cur->len && strncmp(cur->name, str, len) == 0) {
3846             outValue->dataType = cur->type;
3847             outValue->data = cur->unit << Res_value::COMPLEX_UNIT_SHIFT;
3848             *outScale = cur->scale;
3849             *outEnd = end;
3850             //printf("Found unit %s for %s\n", cur->name, str);
3851             return true;
3852         }
3853         cur++;
3854     }
3855 
3856     return false;
3857 }
3858 
3859 
stringToInt(const char16_t * s,size_t len,Res_value * outValue)3860 bool ResTable::stringToInt(const char16_t* s, size_t len, Res_value* outValue)
3861 {
3862     while (len > 0 && isspace16(*s)) {
3863         s++;
3864         len--;
3865     }
3866 
3867     if (len <= 0) {
3868         return false;
3869     }
3870 
3871     size_t i = 0;
3872     int32_t val = 0;
3873     bool neg = false;
3874 
3875     if (*s == '-') {
3876         neg = true;
3877         i++;
3878     }
3879 
3880     if (s[i] < '0' || s[i] > '9') {
3881         return false;
3882     }
3883 
3884     // Decimal or hex?
3885     if (s[i] == '0' && s[i+1] == 'x') {
3886         if (outValue)
3887             outValue->dataType = outValue->TYPE_INT_HEX;
3888         i += 2;
3889         bool error = false;
3890         while (i < len && !error) {
3891             val = (val*16) + get_hex(s[i], &error);
3892             i++;
3893         }
3894         if (error) {
3895             return false;
3896         }
3897     } else {
3898         if (outValue)
3899             outValue->dataType = outValue->TYPE_INT_DEC;
3900         while (i < len) {
3901             if (s[i] < '0' || s[i] > '9') {
3902                 return false;
3903             }
3904             val = (val*10) + s[i]-'0';
3905             i++;
3906         }
3907     }
3908 
3909     if (neg) val = -val;
3910 
3911     while (i < len && isspace16(s[i])) {
3912         i++;
3913     }
3914 
3915     if (i == len) {
3916         if (outValue)
3917             outValue->data = val;
3918         return true;
3919     }
3920 
3921     return false;
3922 }
3923 
stringToFloat(const char16_t * s,size_t len,Res_value * outValue)3924 bool ResTable::stringToFloat(const char16_t* s, size_t len, Res_value* outValue)
3925 {
3926     while (len > 0 && isspace16(*s)) {
3927         s++;
3928         len--;
3929     }
3930 
3931     if (len <= 0) {
3932         return false;
3933     }
3934 
3935     char buf[128];
3936     int i=0;
3937     while (len > 0 && *s != 0 && i < 126) {
3938         if (*s > 255) {
3939             return false;
3940         }
3941         buf[i++] = *s++;
3942         len--;
3943     }
3944 
3945     if (len > 0) {
3946         return false;
3947     }
3948     if (buf[0] < '0' && buf[0] > '9' && buf[0] != '.') {
3949         return false;
3950     }
3951 
3952     buf[i] = 0;
3953     const char* end;
3954     float f = strtof(buf, (char**)&end);
3955 
3956     if (*end != 0 && !isspace((unsigned char)*end)) {
3957         // Might be a unit...
3958         float scale;
3959         if (parse_unit(end, outValue, &scale, &end)) {
3960             f *= scale;
3961             const bool neg = f < 0;
3962             if (neg) f = -f;
3963             uint64_t bits = (uint64_t)(f*(1<<23)+.5f);
3964             uint32_t radix;
3965             uint32_t shift;
3966             if ((bits&0x7fffff) == 0) {
3967                 // Always use 23p0 if there is no fraction, just to make
3968                 // things easier to read.
3969                 radix = Res_value::COMPLEX_RADIX_23p0;
3970                 shift = 23;
3971             } else if ((bits&0xffffffffff800000LL) == 0) {
3972                 // Magnitude is zero -- can fit in 0 bits of precision.
3973                 radix = Res_value::COMPLEX_RADIX_0p23;
3974                 shift = 0;
3975             } else if ((bits&0xffffffff80000000LL) == 0) {
3976                 // Magnitude can fit in 8 bits of precision.
3977                 radix = Res_value::COMPLEX_RADIX_8p15;
3978                 shift = 8;
3979             } else if ((bits&0xffffff8000000000LL) == 0) {
3980                 // Magnitude can fit in 16 bits of precision.
3981                 radix = Res_value::COMPLEX_RADIX_16p7;
3982                 shift = 16;
3983             } else {
3984                 // Magnitude needs entire range, so no fractional part.
3985                 radix = Res_value::COMPLEX_RADIX_23p0;
3986                 shift = 23;
3987             }
3988             int32_t mantissa = (int32_t)(
3989                 (bits>>shift) & Res_value::COMPLEX_MANTISSA_MASK);
3990             if (neg) {
3991                 mantissa = (-mantissa) & Res_value::COMPLEX_MANTISSA_MASK;
3992             }
3993             outValue->data |=
3994                 (radix<<Res_value::COMPLEX_RADIX_SHIFT)
3995                 | (mantissa<<Res_value::COMPLEX_MANTISSA_SHIFT);
3996             //printf("Input value: %f 0x%016Lx, mult: %f, radix: %d, shift: %d, final: 0x%08x\n",
3997             //       f * (neg ? -1 : 1), bits, f*(1<<23),
3998             //       radix, shift, outValue->data);
3999             return true;
4000         }
4001         return false;
4002     }
4003 
4004     while (*end != 0 && isspace((unsigned char)*end)) {
4005         end++;
4006     }
4007 
4008     if (*end == 0) {
4009         if (outValue) {
4010             outValue->dataType = outValue->TYPE_FLOAT;
4011             *(float*)(&outValue->data) = f;
4012             return true;
4013         }
4014     }
4015 
4016     return false;
4017 }
4018 
stringToValue(Res_value * outValue,String16 * outString,const char16_t * s,size_t len,bool preserveSpaces,bool coerceType,uint32_t attrID,const String16 * defType,const String16 * defPackage,Accessor * accessor,void * accessorCookie,uint32_t attrType,bool enforcePrivate) const4019 bool ResTable::stringToValue(Res_value* outValue, String16* outString,
4020                              const char16_t* s, size_t len,
4021                              bool preserveSpaces, bool coerceType,
4022                              uint32_t attrID,
4023                              const String16* defType,
4024                              const String16* defPackage,
4025                              Accessor* accessor,
4026                              void* accessorCookie,
4027                              uint32_t attrType,
4028                              bool enforcePrivate) const
4029 {
4030     bool localizationSetting = accessor != NULL && accessor->getLocalizationSetting();
4031     const char* errorMsg = NULL;
4032 
4033     outValue->size = sizeof(Res_value);
4034     outValue->res0 = 0;
4035 
4036     // First strip leading/trailing whitespace.  Do this before handling
4037     // escapes, so they can be used to force whitespace into the string.
4038     if (!preserveSpaces) {
4039         while (len > 0 && isspace16(*s)) {
4040             s++;
4041             len--;
4042         }
4043         while (len > 0 && isspace16(s[len-1])) {
4044             len--;
4045         }
4046         // If the string ends with '\', then we keep the space after it.
4047         if (len > 0 && s[len-1] == '\\' && s[len] != 0) {
4048             len++;
4049         }
4050     }
4051 
4052     //printf("Value for: %s\n", String8(s, len).string());
4053 
4054     uint32_t l10nReq = ResTable_map::L10N_NOT_REQUIRED;
4055     uint32_t attrMin = 0x80000000, attrMax = 0x7fffffff;
4056     bool fromAccessor = false;
4057     if (attrID != 0 && !Res_INTERNALID(attrID)) {
4058         const ssize_t p = getResourcePackageIndex(attrID);
4059         const bag_entry* bag;
4060         ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
4061         //printf("For attr 0x%08x got bag of %d\n", attrID, cnt);
4062         if (cnt >= 0) {
4063             while (cnt > 0) {
4064                 //printf("Entry 0x%08x = 0x%08x\n", bag->map.name.ident, bag->map.value.data);
4065                 switch (bag->map.name.ident) {
4066                 case ResTable_map::ATTR_TYPE:
4067                     attrType = bag->map.value.data;
4068                     break;
4069                 case ResTable_map::ATTR_MIN:
4070                     attrMin = bag->map.value.data;
4071                     break;
4072                 case ResTable_map::ATTR_MAX:
4073                     attrMax = bag->map.value.data;
4074                     break;
4075                 case ResTable_map::ATTR_L10N:
4076                     l10nReq = bag->map.value.data;
4077                     break;
4078                 }
4079                 bag++;
4080                 cnt--;
4081             }
4082             unlockBag(bag);
4083         } else if (accessor && accessor->getAttributeType(attrID, &attrType)) {
4084             fromAccessor = true;
4085             if (attrType == ResTable_map::TYPE_ENUM
4086                     || attrType == ResTable_map::TYPE_FLAGS
4087                     || attrType == ResTable_map::TYPE_INTEGER) {
4088                 accessor->getAttributeMin(attrID, &attrMin);
4089                 accessor->getAttributeMax(attrID, &attrMax);
4090             }
4091             if (localizationSetting) {
4092                 l10nReq = accessor->getAttributeL10N(attrID);
4093             }
4094         }
4095     }
4096 
4097     const bool canStringCoerce =
4098         coerceType && (attrType&ResTable_map::TYPE_STRING) != 0;
4099 
4100     if (*s == '@') {
4101         outValue->dataType = outValue->TYPE_REFERENCE;
4102 
4103         // Note: we don't check attrType here because the reference can
4104         // be to any other type; we just need to count on the client making
4105         // sure the referenced type is correct.
4106 
4107         //printf("Looking up ref: %s\n", String8(s, len).string());
4108 
4109         // It's a reference!
4110         if (len == 5 && s[1]=='n' && s[2]=='u' && s[3]=='l' && s[4]=='l') {
4111             outValue->data = 0;
4112             return true;
4113         } else {
4114             bool createIfNotFound = false;
4115             const char16_t* resourceRefName;
4116             int resourceNameLen;
4117             if (len > 2 && s[1] == '+') {
4118                 createIfNotFound = true;
4119                 resourceRefName = s + 2;
4120                 resourceNameLen = len - 2;
4121             } else if (len > 2 && s[1] == '*') {
4122                 enforcePrivate = false;
4123                 resourceRefName = s + 2;
4124                 resourceNameLen = len - 2;
4125             } else {
4126                 createIfNotFound = false;
4127                 resourceRefName = s + 1;
4128                 resourceNameLen = len - 1;
4129             }
4130             String16 package, type, name;
4131             if (!expandResourceRef(resourceRefName,resourceNameLen, &package, &type, &name,
4132                                    defType, defPackage, &errorMsg)) {
4133                 if (accessor != NULL) {
4134                     accessor->reportError(accessorCookie, errorMsg);
4135                 }
4136                 return false;
4137             }
4138 
4139             uint32_t specFlags = 0;
4140             uint32_t rid = identifierForName(name.string(), name.size(), type.string(),
4141                     type.size(), package.string(), package.size(), &specFlags);
4142             if (rid != 0) {
4143                 if (enforcePrivate) {
4144                     if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
4145                         if (accessor != NULL) {
4146                             accessor->reportError(accessorCookie, "Resource is not public.");
4147                         }
4148                         return false;
4149                     }
4150                 }
4151                 if (!accessor) {
4152                     outValue->data = rid;
4153                     return true;
4154                 }
4155                 rid = Res_MAKEID(
4156                     accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
4157                     Res_GETTYPE(rid), Res_GETENTRY(rid));
4158                 TABLE_NOISY(printf("Incl %s:%s/%s: 0x%08x\n",
4159                        String8(package).string(), String8(type).string(),
4160                        String8(name).string(), rid));
4161                 outValue->data = rid;
4162                 return true;
4163             }
4164 
4165             if (accessor) {
4166                 uint32_t rid = accessor->getCustomResourceWithCreation(package, type, name,
4167                                                                        createIfNotFound);
4168                 if (rid != 0) {
4169                     TABLE_NOISY(printf("Pckg %s:%s/%s: 0x%08x\n",
4170                            String8(package).string(), String8(type).string(),
4171                            String8(name).string(), rid));
4172                     outValue->data = rid;
4173                     return true;
4174                 }
4175             }
4176         }
4177 
4178         if (accessor != NULL) {
4179             accessor->reportError(accessorCookie, "No resource found that matches the given name");
4180         }
4181         return false;
4182     }
4183 
4184     // if we got to here, and localization is required and it's not a reference,
4185     // complain and bail.
4186     if (l10nReq == ResTable_map::L10N_SUGGESTED) {
4187         if (localizationSetting) {
4188             if (accessor != NULL) {
4189                 accessor->reportError(accessorCookie, "This attribute must be localized.");
4190             }
4191         }
4192     }
4193 
4194     if (*s == '#') {
4195         // It's a color!  Convert to an integer of the form 0xaarrggbb.
4196         uint32_t color = 0;
4197         bool error = false;
4198         if (len == 4) {
4199             outValue->dataType = outValue->TYPE_INT_COLOR_RGB4;
4200             color |= 0xFF000000;
4201             color |= get_hex(s[1], &error) << 20;
4202             color |= get_hex(s[1], &error) << 16;
4203             color |= get_hex(s[2], &error) << 12;
4204             color |= get_hex(s[2], &error) << 8;
4205             color |= get_hex(s[3], &error) << 4;
4206             color |= get_hex(s[3], &error);
4207         } else if (len == 5) {
4208             outValue->dataType = outValue->TYPE_INT_COLOR_ARGB4;
4209             color |= get_hex(s[1], &error) << 28;
4210             color |= get_hex(s[1], &error) << 24;
4211             color |= get_hex(s[2], &error) << 20;
4212             color |= get_hex(s[2], &error) << 16;
4213             color |= get_hex(s[3], &error) << 12;
4214             color |= get_hex(s[3], &error) << 8;
4215             color |= get_hex(s[4], &error) << 4;
4216             color |= get_hex(s[4], &error);
4217         } else if (len == 7) {
4218             outValue->dataType = outValue->TYPE_INT_COLOR_RGB8;
4219             color |= 0xFF000000;
4220             color |= get_hex(s[1], &error) << 20;
4221             color |= get_hex(s[2], &error) << 16;
4222             color |= get_hex(s[3], &error) << 12;
4223             color |= get_hex(s[4], &error) << 8;
4224             color |= get_hex(s[5], &error) << 4;
4225             color |= get_hex(s[6], &error);
4226         } else if (len == 9) {
4227             outValue->dataType = outValue->TYPE_INT_COLOR_ARGB8;
4228             color |= get_hex(s[1], &error) << 28;
4229             color |= get_hex(s[2], &error) << 24;
4230             color |= get_hex(s[3], &error) << 20;
4231             color |= get_hex(s[4], &error) << 16;
4232             color |= get_hex(s[5], &error) << 12;
4233             color |= get_hex(s[6], &error) << 8;
4234             color |= get_hex(s[7], &error) << 4;
4235             color |= get_hex(s[8], &error);
4236         } else {
4237             error = true;
4238         }
4239         if (!error) {
4240             if ((attrType&ResTable_map::TYPE_COLOR) == 0) {
4241                 if (!canStringCoerce) {
4242                     if (accessor != NULL) {
4243                         accessor->reportError(accessorCookie,
4244                                 "Color types not allowed");
4245                     }
4246                     return false;
4247                 }
4248             } else {
4249                 outValue->data = color;
4250                 //printf("Color input=%s, output=0x%x\n", String8(s, len).string(), color);
4251                 return true;
4252             }
4253         } else {
4254             if ((attrType&ResTable_map::TYPE_COLOR) != 0) {
4255                 if (accessor != NULL) {
4256                     accessor->reportError(accessorCookie, "Color value not valid --"
4257                             " must be #rgb, #argb, #rrggbb, or #aarrggbb");
4258                 }
4259                 #if 0
4260                 fprintf(stderr, "%s: Color ID %s value %s is not valid\n",
4261                         "Resource File", //(const char*)in->getPrintableSource(),
4262                         String8(*curTag).string(),
4263                         String8(s, len).string());
4264                 #endif
4265                 return false;
4266             }
4267         }
4268     }
4269 
4270     if (*s == '?') {
4271         outValue->dataType = outValue->TYPE_ATTRIBUTE;
4272 
4273         // Note: we don't check attrType here because the reference can
4274         // be to any other type; we just need to count on the client making
4275         // sure the referenced type is correct.
4276 
4277         //printf("Looking up attr: %s\n", String8(s, len).string());
4278 
4279         static const String16 attr16("attr");
4280         String16 package, type, name;
4281         if (!expandResourceRef(s+1, len-1, &package, &type, &name,
4282                                &attr16, defPackage, &errorMsg)) {
4283             if (accessor != NULL) {
4284                 accessor->reportError(accessorCookie, errorMsg);
4285             }
4286             return false;
4287         }
4288 
4289         //printf("Pkg: %s, Type: %s, Name: %s\n",
4290         //       String8(package).string(), String8(type).string(),
4291         //       String8(name).string());
4292         uint32_t specFlags = 0;
4293         uint32_t rid =
4294             identifierForName(name.string(), name.size(),
4295                               type.string(), type.size(),
4296                               package.string(), package.size(), &specFlags);
4297         if (rid != 0) {
4298             if (enforcePrivate) {
4299                 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
4300                     if (accessor != NULL) {
4301                         accessor->reportError(accessorCookie, "Attribute is not public.");
4302                     }
4303                     return false;
4304                 }
4305             }
4306             if (!accessor) {
4307                 outValue->data = rid;
4308                 return true;
4309             }
4310             rid = Res_MAKEID(
4311                 accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
4312                 Res_GETTYPE(rid), Res_GETENTRY(rid));
4313             //printf("Incl %s:%s/%s: 0x%08x\n",
4314             //       String8(package).string(), String8(type).string(),
4315             //       String8(name).string(), rid);
4316             outValue->data = rid;
4317             return true;
4318         }
4319 
4320         if (accessor) {
4321             uint32_t rid = accessor->getCustomResource(package, type, name);
4322             if (rid != 0) {
4323                 //printf("Mine %s:%s/%s: 0x%08x\n",
4324                 //       String8(package).string(), String8(type).string(),
4325                 //       String8(name).string(), rid);
4326                 outValue->data = rid;
4327                 return true;
4328             }
4329         }
4330 
4331         if (accessor != NULL) {
4332             accessor->reportError(accessorCookie, "No resource found that matches the given name");
4333         }
4334         return false;
4335     }
4336 
4337     if (stringToInt(s, len, outValue)) {
4338         if ((attrType&ResTable_map::TYPE_INTEGER) == 0) {
4339             // If this type does not allow integers, but does allow floats,
4340             // fall through on this error case because the float type should
4341             // be able to accept any integer value.
4342             if (!canStringCoerce && (attrType&ResTable_map::TYPE_FLOAT) == 0) {
4343                 if (accessor != NULL) {
4344                     accessor->reportError(accessorCookie, "Integer types not allowed");
4345                 }
4346                 return false;
4347             }
4348         } else {
4349             if (((int32_t)outValue->data) < ((int32_t)attrMin)
4350                     || ((int32_t)outValue->data) > ((int32_t)attrMax)) {
4351                 if (accessor != NULL) {
4352                     accessor->reportError(accessorCookie, "Integer value out of range");
4353                 }
4354                 return false;
4355             }
4356             return true;
4357         }
4358     }
4359 
4360     if (stringToFloat(s, len, outValue)) {
4361         if (outValue->dataType == Res_value::TYPE_DIMENSION) {
4362             if ((attrType&ResTable_map::TYPE_DIMENSION) != 0) {
4363                 return true;
4364             }
4365             if (!canStringCoerce) {
4366                 if (accessor != NULL) {
4367                     accessor->reportError(accessorCookie, "Dimension types not allowed");
4368                 }
4369                 return false;
4370             }
4371         } else if (outValue->dataType == Res_value::TYPE_FRACTION) {
4372             if ((attrType&ResTable_map::TYPE_FRACTION) != 0) {
4373                 return true;
4374             }
4375             if (!canStringCoerce) {
4376                 if (accessor != NULL) {
4377                     accessor->reportError(accessorCookie, "Fraction types not allowed");
4378                 }
4379                 return false;
4380             }
4381         } else if ((attrType&ResTable_map::TYPE_FLOAT) == 0) {
4382             if (!canStringCoerce) {
4383                 if (accessor != NULL) {
4384                     accessor->reportError(accessorCookie, "Float types not allowed");
4385                 }
4386                 return false;
4387             }
4388         } else {
4389             return true;
4390         }
4391     }
4392 
4393     if (len == 4) {
4394         if ((s[0] == 't' || s[0] == 'T') &&
4395             (s[1] == 'r' || s[1] == 'R') &&
4396             (s[2] == 'u' || s[2] == 'U') &&
4397             (s[3] == 'e' || s[3] == 'E')) {
4398             if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
4399                 if (!canStringCoerce) {
4400                     if (accessor != NULL) {
4401                         accessor->reportError(accessorCookie, "Boolean types not allowed");
4402                     }
4403                     return false;
4404                 }
4405             } else {
4406                 outValue->dataType = outValue->TYPE_INT_BOOLEAN;
4407                 outValue->data = (uint32_t)-1;
4408                 return true;
4409             }
4410         }
4411     }
4412 
4413     if (len == 5) {
4414         if ((s[0] == 'f' || s[0] == 'F') &&
4415             (s[1] == 'a' || s[1] == 'A') &&
4416             (s[2] == 'l' || s[2] == 'L') &&
4417             (s[3] == 's' || s[3] == 'S') &&
4418             (s[4] == 'e' || s[4] == 'E')) {
4419             if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
4420                 if (!canStringCoerce) {
4421                     if (accessor != NULL) {
4422                         accessor->reportError(accessorCookie, "Boolean types not allowed");
4423                     }
4424                     return false;
4425                 }
4426             } else {
4427                 outValue->dataType = outValue->TYPE_INT_BOOLEAN;
4428                 outValue->data = 0;
4429                 return true;
4430             }
4431         }
4432     }
4433 
4434     if ((attrType&ResTable_map::TYPE_ENUM) != 0) {
4435         const ssize_t p = getResourcePackageIndex(attrID);
4436         const bag_entry* bag;
4437         ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
4438         //printf("Got %d for enum\n", cnt);
4439         if (cnt >= 0) {
4440             resource_name rname;
4441             while (cnt > 0) {
4442                 if (!Res_INTERNALID(bag->map.name.ident)) {
4443                     //printf("Trying attr #%08x\n", bag->map.name.ident);
4444                     if (getResourceName(bag->map.name.ident, &rname)) {
4445                         #if 0
4446                         printf("Matching %s against %s (0x%08x)\n",
4447                                String8(s, len).string(),
4448                                String8(rname.name, rname.nameLen).string(),
4449                                bag->map.name.ident);
4450                         #endif
4451                         if (strzcmp16(s, len, rname.name, rname.nameLen) == 0) {
4452                             outValue->dataType = bag->map.value.dataType;
4453                             outValue->data = bag->map.value.data;
4454                             unlockBag(bag);
4455                             return true;
4456                         }
4457                     }
4458 
4459                 }
4460                 bag++;
4461                 cnt--;
4462             }
4463             unlockBag(bag);
4464         }
4465 
4466         if (fromAccessor) {
4467             if (accessor->getAttributeEnum(attrID, s, len, outValue)) {
4468                 return true;
4469             }
4470         }
4471     }
4472 
4473     if ((attrType&ResTable_map::TYPE_FLAGS) != 0) {
4474         const ssize_t p = getResourcePackageIndex(attrID);
4475         const bag_entry* bag;
4476         ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
4477         //printf("Got %d for flags\n", cnt);
4478         if (cnt >= 0) {
4479             bool failed = false;
4480             resource_name rname;
4481             outValue->dataType = Res_value::TYPE_INT_HEX;
4482             outValue->data = 0;
4483             const char16_t* end = s + len;
4484             const char16_t* pos = s;
4485             while (pos < end && !failed) {
4486                 const char16_t* start = pos;
4487                 pos++;
4488                 while (pos < end && *pos != '|') {
4489                     pos++;
4490                 }
4491                 //printf("Looking for: %s\n", String8(start, pos-start).string());
4492                 const bag_entry* bagi = bag;
4493                 ssize_t i;
4494                 for (i=0; i<cnt; i++, bagi++) {
4495                     if (!Res_INTERNALID(bagi->map.name.ident)) {
4496                         //printf("Trying attr #%08x\n", bagi->map.name.ident);
4497                         if (getResourceName(bagi->map.name.ident, &rname)) {
4498                             #if 0
4499                             printf("Matching %s against %s (0x%08x)\n",
4500                                    String8(start,pos-start).string(),
4501                                    String8(rname.name, rname.nameLen).string(),
4502                                    bagi->map.name.ident);
4503                             #endif
4504                             if (strzcmp16(start, pos-start, rname.name, rname.nameLen) == 0) {
4505                                 outValue->data |= bagi->map.value.data;
4506                                 break;
4507                             }
4508                         }
4509                     }
4510                 }
4511                 if (i >= cnt) {
4512                     // Didn't find this flag identifier.
4513                     failed = true;
4514                 }
4515                 if (pos < end) {
4516                     pos++;
4517                 }
4518             }
4519             unlockBag(bag);
4520             if (!failed) {
4521                 //printf("Final flag value: 0x%lx\n", outValue->data);
4522                 return true;
4523             }
4524         }
4525 
4526 
4527         if (fromAccessor) {
4528             if (accessor->getAttributeFlags(attrID, s, len, outValue)) {
4529                 //printf("Final flag value: 0x%lx\n", outValue->data);
4530                 return true;
4531             }
4532         }
4533     }
4534 
4535     if ((attrType&ResTable_map::TYPE_STRING) == 0) {
4536         if (accessor != NULL) {
4537             accessor->reportError(accessorCookie, "String types not allowed");
4538         }
4539         return false;
4540     }
4541 
4542     // Generic string handling...
4543     outValue->dataType = outValue->TYPE_STRING;
4544     if (outString) {
4545         bool failed = collectString(outString, s, len, preserveSpaces, &errorMsg);
4546         if (accessor != NULL) {
4547             accessor->reportError(accessorCookie, errorMsg);
4548         }
4549         return failed;
4550     }
4551 
4552     return true;
4553 }
4554 
collectString(String16 * outString,const char16_t * s,size_t len,bool preserveSpaces,const char ** outErrorMsg,bool append)4555 bool ResTable::collectString(String16* outString,
4556                              const char16_t* s, size_t len,
4557                              bool preserveSpaces,
4558                              const char** outErrorMsg,
4559                              bool append)
4560 {
4561     String16 tmp;
4562 
4563     char quoted = 0;
4564     const char16_t* p = s;
4565     while (p < (s+len)) {
4566         while (p < (s+len)) {
4567             const char16_t c = *p;
4568             if (c == '\\') {
4569                 break;
4570             }
4571             if (!preserveSpaces) {
4572                 if (quoted == 0 && isspace16(c)
4573                     && (c != ' ' || isspace16(*(p+1)))) {
4574                     break;
4575                 }
4576                 if (c == '"' && (quoted == 0 || quoted == '"')) {
4577                     break;
4578                 }
4579                 if (c == '\'' && (quoted == 0 || quoted == '\'')) {
4580                     /*
4581                      * In practice, when people write ' instead of \'
4582                      * in a string, they are doing it by accident
4583                      * instead of really meaning to use ' as a quoting
4584                      * character.  Warn them so they don't lose it.
4585                      */
4586                     if (outErrorMsg) {
4587                         *outErrorMsg = "Apostrophe not preceded by \\";
4588                     }
4589                     return false;
4590                 }
4591             }
4592             p++;
4593         }
4594         if (p < (s+len)) {
4595             if (p > s) {
4596                 tmp.append(String16(s, p-s));
4597             }
4598             if (!preserveSpaces && (*p == '"' || *p == '\'')) {
4599                 if (quoted == 0) {
4600                     quoted = *p;
4601                 } else {
4602                     quoted = 0;
4603                 }
4604                 p++;
4605             } else if (!preserveSpaces && isspace16(*p)) {
4606                 // Space outside of a quote -- consume all spaces and
4607                 // leave a single plain space char.
4608                 tmp.append(String16(" "));
4609                 p++;
4610                 while (p < (s+len) && isspace16(*p)) {
4611                     p++;
4612                 }
4613             } else if (*p == '\\') {
4614                 p++;
4615                 if (p < (s+len)) {
4616                     switch (*p) {
4617                     case 't':
4618                         tmp.append(String16("\t"));
4619                         break;
4620                     case 'n':
4621                         tmp.append(String16("\n"));
4622                         break;
4623                     case '#':
4624                         tmp.append(String16("#"));
4625                         break;
4626                     case '@':
4627                         tmp.append(String16("@"));
4628                         break;
4629                     case '?':
4630                         tmp.append(String16("?"));
4631                         break;
4632                     case '"':
4633                         tmp.append(String16("\""));
4634                         break;
4635                     case '\'':
4636                         tmp.append(String16("'"));
4637                         break;
4638                     case '\\':
4639                         tmp.append(String16("\\"));
4640                         break;
4641                     case 'u':
4642                     {
4643                         char16_t chr = 0;
4644                         int i = 0;
4645                         while (i < 4 && p[1] != 0) {
4646                             p++;
4647                             i++;
4648                             int c;
4649                             if (*p >= '0' && *p <= '9') {
4650                                 c = *p - '0';
4651                             } else if (*p >= 'a' && *p <= 'f') {
4652                                 c = *p - 'a' + 10;
4653                             } else if (*p >= 'A' && *p <= 'F') {
4654                                 c = *p - 'A' + 10;
4655                             } else {
4656                                 if (outErrorMsg) {
4657                                     *outErrorMsg = "Bad character in \\u unicode escape sequence";
4658                                 }
4659                                 return false;
4660                             }
4661                             chr = (chr<<4) | c;
4662                         }
4663                         tmp.append(String16(&chr, 1));
4664                     } break;
4665                     default:
4666                         // ignore unknown escape chars.
4667                         break;
4668                     }
4669                     p++;
4670                 }
4671             }
4672             len -= (p-s);
4673             s = p;
4674         }
4675     }
4676 
4677     if (tmp.size() != 0) {
4678         if (len > 0) {
4679             tmp.append(String16(s, len));
4680         }
4681         if (append) {
4682             outString->append(tmp);
4683         } else {
4684             outString->setTo(tmp);
4685         }
4686     } else {
4687         if (append) {
4688             outString->append(String16(s, len));
4689         } else {
4690             outString->setTo(s, len);
4691         }
4692     }
4693 
4694     return true;
4695 }
4696 
getBasePackageCount() const4697 size_t ResTable::getBasePackageCount() const
4698 {
4699     if (mError != NO_ERROR) {
4700         return 0;
4701     }
4702     return mPackageGroups.size();
4703 }
4704 
getBasePackageName(size_t idx) const4705 const char16_t* ResTable::getBasePackageName(size_t idx) const
4706 {
4707     if (mError != NO_ERROR) {
4708         return 0;
4709     }
4710     LOG_FATAL_IF(idx >= mPackageGroups.size(),
4711                  "Requested package index %d past package count %d",
4712                  (int)idx, (int)mPackageGroups.size());
4713     return mPackageGroups[idx]->name.string();
4714 }
4715 
getBasePackageId(size_t idx) const4716 uint32_t ResTable::getBasePackageId(size_t idx) const
4717 {
4718     if (mError != NO_ERROR) {
4719         return 0;
4720     }
4721     LOG_FATAL_IF(idx >= mPackageGroups.size(),
4722                  "Requested package index %d past package count %d",
4723                  (int)idx, (int)mPackageGroups.size());
4724     return mPackageGroups[idx]->id;
4725 }
4726 
getTableCount() const4727 size_t ResTable::getTableCount() const
4728 {
4729     return mHeaders.size();
4730 }
4731 
getTableStringBlock(size_t index) const4732 const ResStringPool* ResTable::getTableStringBlock(size_t index) const
4733 {
4734     return &mHeaders[index]->values;
4735 }
4736 
getTableCookie(size_t index) const4737 void* ResTable::getTableCookie(size_t index) const
4738 {
4739     return mHeaders[index]->cookie;
4740 }
4741 
getConfigurations(Vector<ResTable_config> * configs) const4742 void ResTable::getConfigurations(Vector<ResTable_config>* configs) const
4743 {
4744     const size_t I = mPackageGroups.size();
4745     for (size_t i=0; i<I; i++) {
4746         const PackageGroup* packageGroup = mPackageGroups[i];
4747         const size_t J = packageGroup->packages.size();
4748         for (size_t j=0; j<J; j++) {
4749             const Package* package = packageGroup->packages[j];
4750             const size_t K = package->types.size();
4751             for (size_t k=0; k<K; k++) {
4752                 const Type* type = package->types[k];
4753                 if (type == NULL) continue;
4754                 const size_t L = type->configs.size();
4755                 for (size_t l=0; l<L; l++) {
4756                     const ResTable_type* config = type->configs[l];
4757                     const ResTable_config* cfg = &config->config;
4758                     // only insert unique
4759                     const size_t M = configs->size();
4760                     size_t m;
4761                     for (m=0; m<M; m++) {
4762                         if (0 == (*configs)[m].compare(*cfg)) {
4763                             break;
4764                         }
4765                     }
4766                     // if we didn't find it
4767                     if (m == M) {
4768                         configs->add(*cfg);
4769                     }
4770                 }
4771             }
4772         }
4773     }
4774 }
4775 
getLocales(Vector<String8> * locales) const4776 void ResTable::getLocales(Vector<String8>* locales) const
4777 {
4778     Vector<ResTable_config> configs;
4779     ALOGV("calling getConfigurations");
4780     getConfigurations(&configs);
4781     ALOGV("called getConfigurations size=%d", (int)configs.size());
4782     const size_t I = configs.size();
4783     for (size_t i=0; i<I; i++) {
4784         char locale[6];
4785         configs[i].getLocale(locale);
4786         const size_t J = locales->size();
4787         size_t j;
4788         for (j=0; j<J; j++) {
4789             if (0 == strcmp(locale, (*locales)[j].string())) {
4790                 break;
4791             }
4792         }
4793         if (j == J) {
4794             locales->add(String8(locale));
4795         }
4796     }
4797 }
4798 
getEntry(const Package * package,int typeIndex,int entryIndex,const ResTable_config * config,const ResTable_type ** outType,const ResTable_entry ** outEntry,const Type ** outTypeClass) const4799 ssize_t ResTable::getEntry(
4800     const Package* package, int typeIndex, int entryIndex,
4801     const ResTable_config* config,
4802     const ResTable_type** outType, const ResTable_entry** outEntry,
4803     const Type** outTypeClass) const
4804 {
4805     ALOGV("Getting entry from package %p\n", package);
4806     const ResTable_package* const pkg = package->package;
4807 
4808     const Type* allTypes = package->getType(typeIndex);
4809     ALOGV("allTypes=%p\n", allTypes);
4810     if (allTypes == NULL) {
4811         ALOGV("Skipping entry type index 0x%02x because type is NULL!\n", typeIndex);
4812         return 0;
4813     }
4814 
4815     if ((size_t)entryIndex >= allTypes->entryCount) {
4816         ALOGW("getEntry failing because entryIndex %d is beyond type entryCount %d",
4817             entryIndex, (int)allTypes->entryCount);
4818         return BAD_TYPE;
4819     }
4820 
4821     const ResTable_type* type = NULL;
4822     uint32_t offset = ResTable_type::NO_ENTRY;
4823     ResTable_config bestConfig;
4824     memset(&bestConfig, 0, sizeof(bestConfig)); // make the compiler shut up
4825 
4826     const size_t NT = allTypes->configs.size();
4827     for (size_t i=0; i<NT; i++) {
4828         const ResTable_type* const thisType = allTypes->configs[i];
4829         if (thisType == NULL) continue;
4830 
4831         ResTable_config thisConfig;
4832         thisConfig.copyFromDtoH(thisType->config);
4833 
4834         TABLE_GETENTRY(ALOGI("Match entry 0x%x in type 0x%x (sz 0x%x): %s\n",
4835                            entryIndex, typeIndex+1, dtohl(thisType->config.size),
4836                            thisConfig.toString().string()));
4837 
4838         // Check to make sure this one is valid for the current parameters.
4839         if (config && !thisConfig.match(*config)) {
4840             TABLE_GETENTRY(ALOGI("Does not match config!\n"));
4841             continue;
4842         }
4843 
4844         // Check if there is the desired entry in this type.
4845 
4846         const uint8_t* const end = ((const uint8_t*)thisType)
4847             + dtohl(thisType->header.size);
4848         const uint32_t* const eindex = (const uint32_t*)
4849             (((const uint8_t*)thisType) + dtohs(thisType->header.headerSize));
4850 
4851         uint32_t thisOffset = dtohl(eindex[entryIndex]);
4852         if (thisOffset == ResTable_type::NO_ENTRY) {
4853             TABLE_GETENTRY(ALOGI("Skipping because it is not defined!\n"));
4854             continue;
4855         }
4856 
4857         if (type != NULL) {
4858             // Check if this one is less specific than the last found.  If so,
4859             // we will skip it.  We check starting with things we most care
4860             // about to those we least care about.
4861             if (!thisConfig.isBetterThan(bestConfig, config)) {
4862                 TABLE_GETENTRY(ALOGI("This config is worse than last!\n"));
4863                 continue;
4864             }
4865         }
4866 
4867         type = thisType;
4868         offset = thisOffset;
4869         bestConfig = thisConfig;
4870         TABLE_GETENTRY(ALOGI("Best entry so far -- using it!\n"));
4871         if (!config) break;
4872     }
4873 
4874     if (type == NULL) {
4875         TABLE_GETENTRY(ALOGI("No value found for requested entry!\n"));
4876         return BAD_INDEX;
4877     }
4878 
4879     offset += dtohl(type->entriesStart);
4880     TABLE_NOISY(aout << "Looking in resource table " << package->header->header
4881           << ", typeOff="
4882           << (void*)(((const char*)type)-((const char*)package->header->header))
4883           << ", offset=" << (void*)offset << endl);
4884 
4885     if (offset > (dtohl(type->header.size)-sizeof(ResTable_entry))) {
4886         ALOGW("ResTable_entry at 0x%x is beyond type chunk data 0x%x",
4887              offset, dtohl(type->header.size));
4888         return BAD_TYPE;
4889     }
4890     if ((offset&0x3) != 0) {
4891         ALOGW("ResTable_entry at 0x%x is not on an integer boundary",
4892              offset);
4893         return BAD_TYPE;
4894     }
4895 
4896     const ResTable_entry* const entry = (const ResTable_entry*)
4897         (((const uint8_t*)type) + offset);
4898     if (dtohs(entry->size) < sizeof(*entry)) {
4899         ALOGW("ResTable_entry size 0x%x is too small", dtohs(entry->size));
4900         return BAD_TYPE;
4901     }
4902 
4903     *outType = type;
4904     *outEntry = entry;
4905     if (outTypeClass != NULL) {
4906         *outTypeClass = allTypes;
4907     }
4908     return offset + dtohs(entry->size);
4909 }
4910 
parsePackage(const ResTable_package * const pkg,const Header * const header,uint32_t idmap_id)4911 status_t ResTable::parsePackage(const ResTable_package* const pkg,
4912                                 const Header* const header, uint32_t idmap_id)
4913 {
4914     const uint8_t* base = (const uint8_t*)pkg;
4915     status_t err = validate_chunk(&pkg->header, sizeof(*pkg),
4916                                   header->dataEnd, "ResTable_package");
4917     if (err != NO_ERROR) {
4918         return (mError=err);
4919     }
4920 
4921     const size_t pkgSize = dtohl(pkg->header.size);
4922 
4923     if (dtohl(pkg->typeStrings) >= pkgSize) {
4924         ALOGW("ResTable_package type strings at %p are past chunk size %p.",
4925              (void*)dtohl(pkg->typeStrings), (void*)pkgSize);
4926         return (mError=BAD_TYPE);
4927     }
4928     if ((dtohl(pkg->typeStrings)&0x3) != 0) {
4929         ALOGW("ResTable_package type strings at %p is not on an integer boundary.",
4930              (void*)dtohl(pkg->typeStrings));
4931         return (mError=BAD_TYPE);
4932     }
4933     if (dtohl(pkg->keyStrings) >= pkgSize) {
4934         ALOGW("ResTable_package key strings at %p are past chunk size %p.",
4935              (void*)dtohl(pkg->keyStrings), (void*)pkgSize);
4936         return (mError=BAD_TYPE);
4937     }
4938     if ((dtohl(pkg->keyStrings)&0x3) != 0) {
4939         ALOGW("ResTable_package key strings at %p is not on an integer boundary.",
4940              (void*)dtohl(pkg->keyStrings));
4941         return (mError=BAD_TYPE);
4942     }
4943 
4944     Package* package = NULL;
4945     PackageGroup* group = NULL;
4946     uint32_t id = idmap_id != 0 ? idmap_id : dtohl(pkg->id);
4947     // If at this point id == 0, pkg is an overlay package without a
4948     // corresponding idmap. During regular usage, overlay packages are
4949     // always loaded alongside their idmaps, but during idmap creation
4950     // the package is temporarily loaded by itself.
4951     if (id < 256) {
4952 
4953         package = new Package(this, header, pkg);
4954         if (package == NULL) {
4955             return (mError=NO_MEMORY);
4956         }
4957 
4958         size_t idx = mPackageMap[id];
4959         if (idx == 0) {
4960             idx = mPackageGroups.size()+1;
4961 
4962             char16_t tmpName[sizeof(pkg->name)/sizeof(char16_t)];
4963             strcpy16_dtoh(tmpName, pkg->name, sizeof(pkg->name)/sizeof(char16_t));
4964             group = new PackageGroup(this, String16(tmpName), id);
4965             if (group == NULL) {
4966                 delete package;
4967                 return (mError=NO_MEMORY);
4968             }
4969 
4970             err = package->typeStrings.setTo(base+dtohl(pkg->typeStrings),
4971                                            header->dataEnd-(base+dtohl(pkg->typeStrings)));
4972             if (err != NO_ERROR) {
4973                 delete group;
4974                 delete package;
4975                 return (mError=err);
4976             }
4977             err = package->keyStrings.setTo(base+dtohl(pkg->keyStrings),
4978                                           header->dataEnd-(base+dtohl(pkg->keyStrings)));
4979             if (err != NO_ERROR) {
4980                 delete group;
4981                 delete package;
4982                 return (mError=err);
4983             }
4984 
4985             //printf("Adding new package id %d at index %d\n", id, idx);
4986             err = mPackageGroups.add(group);
4987             if (err < NO_ERROR) {
4988                 return (mError=err);
4989             }
4990             group->basePackage = package;
4991 
4992             mPackageMap[id] = (uint8_t)idx;
4993         } else {
4994             group = mPackageGroups.itemAt(idx-1);
4995             if (group == NULL) {
4996                 return (mError=UNKNOWN_ERROR);
4997             }
4998         }
4999         err = group->packages.add(package);
5000         if (err < NO_ERROR) {
5001             return (mError=err);
5002         }
5003     } else {
5004         LOG_ALWAYS_FATAL("Package id out of range");
5005         return NO_ERROR;
5006     }
5007 
5008 
5009     // Iterate through all chunks.
5010     size_t curPackage = 0;
5011 
5012     const ResChunk_header* chunk =
5013         (const ResChunk_header*)(((const uint8_t*)pkg)
5014                                  + dtohs(pkg->header.headerSize));
5015     const uint8_t* endPos = ((const uint8_t*)pkg) + dtohs(pkg->header.size);
5016     while (((const uint8_t*)chunk) <= (endPos-sizeof(ResChunk_header)) &&
5017            ((const uint8_t*)chunk) <= (endPos-dtohl(chunk->size))) {
5018         TABLE_NOISY(ALOGV("PackageChunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n",
5019                          dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
5020                          (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header))));
5021         const size_t csize = dtohl(chunk->size);
5022         const uint16_t ctype = dtohs(chunk->type);
5023         if (ctype == RES_TABLE_TYPE_SPEC_TYPE) {
5024             const ResTable_typeSpec* typeSpec = (const ResTable_typeSpec*)(chunk);
5025             err = validate_chunk(&typeSpec->header, sizeof(*typeSpec),
5026                                  endPos, "ResTable_typeSpec");
5027             if (err != NO_ERROR) {
5028                 return (mError=err);
5029             }
5030 
5031             const size_t typeSpecSize = dtohl(typeSpec->header.size);
5032 
5033             LOAD_TABLE_NOISY(printf("TypeSpec off %p: type=0x%x, headerSize=0x%x, size=%p\n",
5034                                     (void*)(base-(const uint8_t*)chunk),
5035                                     dtohs(typeSpec->header.type),
5036                                     dtohs(typeSpec->header.headerSize),
5037                                     (void*)typeSize));
5038             // look for block overrun or int overflow when multiplying by 4
5039             if ((dtohl(typeSpec->entryCount) > (INT32_MAX/sizeof(uint32_t))
5040                     || dtohs(typeSpec->header.headerSize)+(sizeof(uint32_t)*dtohl(typeSpec->entryCount))
5041                     > typeSpecSize)) {
5042                 ALOGW("ResTable_typeSpec entry index to %p extends beyond chunk end %p.",
5043                      (void*)(dtohs(typeSpec->header.headerSize)
5044                              +(sizeof(uint32_t)*dtohl(typeSpec->entryCount))),
5045                      (void*)typeSpecSize);
5046                 return (mError=BAD_TYPE);
5047             }
5048 
5049             if (typeSpec->id == 0) {
5050                 ALOGW("ResTable_type has an id of 0.");
5051                 return (mError=BAD_TYPE);
5052             }
5053 
5054             while (package->types.size() < typeSpec->id) {
5055                 package->types.add(NULL);
5056             }
5057             Type* t = package->types[typeSpec->id-1];
5058             if (t == NULL) {
5059                 t = new Type(header, package, dtohl(typeSpec->entryCount));
5060                 package->types.editItemAt(typeSpec->id-1) = t;
5061             } else if (dtohl(typeSpec->entryCount) != t->entryCount) {
5062                 ALOGW("ResTable_typeSpec entry count inconsistent: given %d, previously %d",
5063                     (int)dtohl(typeSpec->entryCount), (int)t->entryCount);
5064                 return (mError=BAD_TYPE);
5065             }
5066             t->typeSpecFlags = (const uint32_t*)(
5067                     ((const uint8_t*)typeSpec) + dtohs(typeSpec->header.headerSize));
5068             t->typeSpec = typeSpec;
5069 
5070         } else if (ctype == RES_TABLE_TYPE_TYPE) {
5071             const ResTable_type* type = (const ResTable_type*)(chunk);
5072             err = validate_chunk(&type->header, sizeof(*type)-sizeof(ResTable_config)+4,
5073                                  endPos, "ResTable_type");
5074             if (err != NO_ERROR) {
5075                 return (mError=err);
5076             }
5077 
5078             const size_t typeSize = dtohl(type->header.size);
5079 
5080             LOAD_TABLE_NOISY(printf("Type off %p: type=0x%x, headerSize=0x%x, size=%p\n",
5081                                     (void*)(base-(const uint8_t*)chunk),
5082                                     dtohs(type->header.type),
5083                                     dtohs(type->header.headerSize),
5084                                     (void*)typeSize));
5085             if (dtohs(type->header.headerSize)+(sizeof(uint32_t)*dtohl(type->entryCount))
5086                 > typeSize) {
5087                 ALOGW("ResTable_type entry index to %p extends beyond chunk end %p.",
5088                      (void*)(dtohs(type->header.headerSize)
5089                              +(sizeof(uint32_t)*dtohl(type->entryCount))),
5090                      (void*)typeSize);
5091                 return (mError=BAD_TYPE);
5092             }
5093             if (dtohl(type->entryCount) != 0
5094                 && dtohl(type->entriesStart) > (typeSize-sizeof(ResTable_entry))) {
5095                 ALOGW("ResTable_type entriesStart at %p extends beyond chunk end %p.",
5096                      (void*)dtohl(type->entriesStart), (void*)typeSize);
5097                 return (mError=BAD_TYPE);
5098             }
5099             if (type->id == 0) {
5100                 ALOGW("ResTable_type has an id of 0.");
5101                 return (mError=BAD_TYPE);
5102             }
5103 
5104             while (package->types.size() < type->id) {
5105                 package->types.add(NULL);
5106             }
5107             Type* t = package->types[type->id-1];
5108             if (t == NULL) {
5109                 t = new Type(header, package, dtohl(type->entryCount));
5110                 package->types.editItemAt(type->id-1) = t;
5111             } else if (dtohl(type->entryCount) != t->entryCount) {
5112                 ALOGW("ResTable_type entry count inconsistent: given %d, previously %d",
5113                     (int)dtohl(type->entryCount), (int)t->entryCount);
5114                 return (mError=BAD_TYPE);
5115             }
5116 
5117             TABLE_GETENTRY(
5118                 ResTable_config thisConfig;
5119                 thisConfig.copyFromDtoH(type->config);
5120                 ALOGI("Adding config to type %d: %s\n",
5121                       type->id, thisConfig.toString().string()));
5122             t->configs.add(type);
5123         } else {
5124             status_t err = validate_chunk(chunk, sizeof(ResChunk_header),
5125                                           endPos, "ResTable_package:unknown");
5126             if (err != NO_ERROR) {
5127                 return (mError=err);
5128             }
5129         }
5130         chunk = (const ResChunk_header*)
5131             (((const uint8_t*)chunk) + csize);
5132     }
5133 
5134     if (group->typeCount == 0) {
5135         group->typeCount = package->types.size();
5136     }
5137 
5138     return NO_ERROR;
5139 }
5140 
createIdmap(const ResTable & overlay,uint32_t originalCrc,uint32_t overlayCrc,void ** outData,size_t * outSize) const5141 status_t ResTable::createIdmap(const ResTable& overlay, uint32_t originalCrc, uint32_t overlayCrc,
5142                                void** outData, size_t* outSize) const
5143 {
5144     // see README for details on the format of map
5145     if (mPackageGroups.size() == 0) {
5146         return UNKNOWN_ERROR;
5147     }
5148     if (mPackageGroups[0]->packages.size() == 0) {
5149         return UNKNOWN_ERROR;
5150     }
5151 
5152     Vector<Vector<uint32_t> > map;
5153     const PackageGroup* pg = mPackageGroups[0];
5154     const Package* pkg = pg->packages[0];
5155     size_t typeCount = pkg->types.size();
5156     // starting size is header + first item (number of types in map)
5157     *outSize = (IDMAP_HEADER_SIZE + 1) * sizeof(uint32_t);
5158     const String16 overlayPackage(overlay.mPackageGroups[0]->packages[0]->package->name);
5159     const uint32_t pkg_id = pkg->package->id << 24;
5160 
5161     for (size_t typeIndex = 0; typeIndex < typeCount; ++typeIndex) {
5162         ssize_t offset = -1;
5163         const Type* typeConfigs = pkg->getType(typeIndex);
5164         ssize_t mapIndex = map.add();
5165         if (mapIndex < 0) {
5166             return NO_MEMORY;
5167         }
5168         Vector<uint32_t>& vector = map.editItemAt(mapIndex);
5169         for (size_t entryIndex = 0; entryIndex < typeConfigs->entryCount; ++entryIndex) {
5170             uint32_t resID = (0xff000000 & ((pkg->package->id)<<24))
5171                 | (0x00ff0000 & ((typeIndex+1)<<16))
5172                 | (0x0000ffff & (entryIndex));
5173             resource_name resName;
5174             if (!this->getResourceName(resID, &resName)) {
5175                 ALOGW("idmap: resource 0x%08x has spec but lacks values, skipping\n", resID);
5176                 continue;
5177             }
5178 
5179             const String16 overlayType(resName.type, resName.typeLen);
5180             const String16 overlayName(resName.name, resName.nameLen);
5181             uint32_t overlayResID = overlay.identifierForName(overlayName.string(),
5182                                                               overlayName.size(),
5183                                                               overlayType.string(),
5184                                                               overlayType.size(),
5185                                                               overlayPackage.string(),
5186                                                               overlayPackage.size());
5187             if (overlayResID != 0) {
5188                 // overlay package has package ID == 0, use original package's ID instead
5189                 overlayResID |= pkg_id;
5190             }
5191             vector.push(overlayResID);
5192             if (overlayResID != 0 && offset == -1) {
5193                 offset = Res_GETENTRY(resID);
5194             }
5195 #if 0
5196             if (overlayResID != 0) {
5197                 ALOGD("%s/%s 0x%08x -> 0x%08x\n",
5198                      String8(String16(resName.type)).string(),
5199                      String8(String16(resName.name)).string(),
5200                      resID, overlayResID);
5201             }
5202 #endif
5203         }
5204 
5205         if (offset != -1) {
5206             // shave off leading and trailing entries which lack overlay values
5207             vector.removeItemsAt(0, offset);
5208             vector.insertAt((uint32_t)offset, 0, 1);
5209             while (vector.top() == 0) {
5210                 vector.pop();
5211             }
5212             // reserve space for number and offset of entries, and the actual entries
5213             *outSize += (2 + vector.size()) * sizeof(uint32_t);
5214         } else {
5215             // no entries of current type defined in overlay package
5216             vector.clear();
5217             // reserve space for type offset
5218             *outSize += 1 * sizeof(uint32_t);
5219         }
5220     }
5221 
5222     if ((*outData = malloc(*outSize)) == NULL) {
5223         return NO_MEMORY;
5224     }
5225     uint32_t* data = (uint32_t*)*outData;
5226     *data++ = htodl(IDMAP_MAGIC);
5227     *data++ = htodl(originalCrc);
5228     *data++ = htodl(overlayCrc);
5229     const size_t mapSize = map.size();
5230     *data++ = htodl(mapSize);
5231     size_t offset = mapSize;
5232     for (size_t i = 0; i < mapSize; ++i) {
5233         const Vector<uint32_t>& vector = map.itemAt(i);
5234         const size_t N = vector.size();
5235         if (N == 0) {
5236             *data++ = htodl(0);
5237         } else {
5238             offset++;
5239             *data++ = htodl(offset);
5240             offset += N;
5241         }
5242     }
5243     for (size_t i = 0; i < mapSize; ++i) {
5244         const Vector<uint32_t>& vector = map.itemAt(i);
5245         const size_t N = vector.size();
5246         if (N == 0) {
5247             continue;
5248         }
5249         *data++ = htodl(N - 1); // do not count the offset (which is vector's first element)
5250         for (size_t j = 0; j < N; ++j) {
5251             const uint32_t& overlayResID = vector.itemAt(j);
5252             *data++ = htodl(overlayResID);
5253         }
5254     }
5255 
5256     return NO_ERROR;
5257 }
5258 
getIdmapInfo(const void * idmap,size_t sizeBytes,uint32_t * pOriginalCrc,uint32_t * pOverlayCrc)5259 bool ResTable::getIdmapInfo(const void* idmap, size_t sizeBytes,
5260                             uint32_t* pOriginalCrc, uint32_t* pOverlayCrc)
5261 {
5262     const uint32_t* map = (const uint32_t*)idmap;
5263     if (!assertIdmapHeader(map, sizeBytes)) {
5264         return false;
5265     }
5266     *pOriginalCrc = map[1];
5267     *pOverlayCrc = map[2];
5268     return true;
5269 }
5270 
5271 
5272 #ifndef HAVE_ANDROID_OS
5273 #define CHAR16_TO_CSTR(c16, len) (String8(String16(c16,len)).string())
5274 
5275 #define CHAR16_ARRAY_EQ(constant, var, len) \
5276         ((len == (sizeof(constant)/sizeof(constant[0]))) && (0 == memcmp((var), (constant), (len))))
5277 
print_complex(uint32_t complex,bool isFraction)5278 void print_complex(uint32_t complex, bool isFraction)
5279 {
5280     const float MANTISSA_MULT =
5281         1.0f / (1<<Res_value::COMPLEX_MANTISSA_SHIFT);
5282     const float RADIX_MULTS[] = {
5283         1.0f*MANTISSA_MULT, 1.0f/(1<<7)*MANTISSA_MULT,
5284         1.0f/(1<<15)*MANTISSA_MULT, 1.0f/(1<<23)*MANTISSA_MULT
5285     };
5286 
5287     float value = (complex&(Res_value::COMPLEX_MANTISSA_MASK
5288                    <<Res_value::COMPLEX_MANTISSA_SHIFT))
5289             * RADIX_MULTS[(complex>>Res_value::COMPLEX_RADIX_SHIFT)
5290                             & Res_value::COMPLEX_RADIX_MASK];
5291     printf("%f", value);
5292 
5293     if (!isFraction) {
5294         switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
5295             case Res_value::COMPLEX_UNIT_PX: printf("px"); break;
5296             case Res_value::COMPLEX_UNIT_DIP: printf("dp"); break;
5297             case Res_value::COMPLEX_UNIT_SP: printf("sp"); break;
5298             case Res_value::COMPLEX_UNIT_PT: printf("pt"); break;
5299             case Res_value::COMPLEX_UNIT_IN: printf("in"); break;
5300             case Res_value::COMPLEX_UNIT_MM: printf("mm"); break;
5301             default: printf(" (unknown unit)"); break;
5302         }
5303     } else {
5304         switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
5305             case Res_value::COMPLEX_UNIT_FRACTION: printf("%%"); break;
5306             case Res_value::COMPLEX_UNIT_FRACTION_PARENT: printf("%%p"); break;
5307             default: printf(" (unknown unit)"); break;
5308         }
5309     }
5310 }
5311 
5312 // Normalize a string for output
normalizeForOutput(const char * input)5313 String8 ResTable::normalizeForOutput( const char *input )
5314 {
5315     String8 ret;
5316     char buff[2];
5317     buff[1] = '\0';
5318 
5319     while (*input != '\0') {
5320         switch (*input) {
5321             // All interesting characters are in the ASCII zone, so we are making our own lives
5322             // easier by scanning the string one byte at a time.
5323         case '\\':
5324             ret += "\\\\";
5325             break;
5326         case '\n':
5327             ret += "\\n";
5328             break;
5329         case '"':
5330             ret += "\\\"";
5331             break;
5332         default:
5333             buff[0] = *input;
5334             ret += buff;
5335             break;
5336         }
5337 
5338         input++;
5339     }
5340 
5341     return ret;
5342 }
5343 
print_value(const Package * pkg,const Res_value & value) const5344 void ResTable::print_value(const Package* pkg, const Res_value& value) const
5345 {
5346     if (value.dataType == Res_value::TYPE_NULL) {
5347         printf("(null)\n");
5348     } else if (value.dataType == Res_value::TYPE_REFERENCE) {
5349         printf("(reference) 0x%08x\n", value.data);
5350     } else if (value.dataType == Res_value::TYPE_ATTRIBUTE) {
5351         printf("(attribute) 0x%08x\n", value.data);
5352     } else if (value.dataType == Res_value::TYPE_STRING) {
5353         size_t len;
5354         const char* str8 = pkg->header->values.string8At(
5355                 value.data, &len);
5356         if (str8 != NULL) {
5357             printf("(string8) \"%s\"\n", normalizeForOutput(str8).string());
5358         } else {
5359             const char16_t* str16 = pkg->header->values.stringAt(
5360                     value.data, &len);
5361             if (str16 != NULL) {
5362                 printf("(string16) \"%s\"\n",
5363                     normalizeForOutput(String8(str16, len).string()).string());
5364             } else {
5365                 printf("(string) null\n");
5366             }
5367         }
5368     } else if (value.dataType == Res_value::TYPE_FLOAT) {
5369         printf("(float) %g\n", *(const float*)&value.data);
5370     } else if (value.dataType == Res_value::TYPE_DIMENSION) {
5371         printf("(dimension) ");
5372         print_complex(value.data, false);
5373         printf("\n");
5374     } else if (value.dataType == Res_value::TYPE_FRACTION) {
5375         printf("(fraction) ");
5376         print_complex(value.data, true);
5377         printf("\n");
5378     } else if (value.dataType >= Res_value::TYPE_FIRST_COLOR_INT
5379             || value.dataType <= Res_value::TYPE_LAST_COLOR_INT) {
5380         printf("(color) #%08x\n", value.data);
5381     } else if (value.dataType == Res_value::TYPE_INT_BOOLEAN) {
5382         printf("(boolean) %s\n", value.data ? "true" : "false");
5383     } else if (value.dataType >= Res_value::TYPE_FIRST_INT
5384             || value.dataType <= Res_value::TYPE_LAST_INT) {
5385         printf("(int) 0x%08x or %d\n", value.data, value.data);
5386     } else {
5387         printf("(unknown type) t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)\n",
5388                (int)value.dataType, (int)value.data,
5389                (int)value.size, (int)value.res0);
5390     }
5391 }
5392 
print(bool inclValues) const5393 void ResTable::print(bool inclValues) const
5394 {
5395     if (mError != 0) {
5396         printf("mError=0x%x (%s)\n", mError, strerror(mError));
5397     }
5398 #if 0
5399     printf("mParams=%c%c-%c%c,\n",
5400             mParams.language[0], mParams.language[1],
5401             mParams.country[0], mParams.country[1]);
5402 #endif
5403     size_t pgCount = mPackageGroups.size();
5404     printf("Package Groups (%d)\n", (int)pgCount);
5405     for (size_t pgIndex=0; pgIndex<pgCount; pgIndex++) {
5406         const PackageGroup* pg = mPackageGroups[pgIndex];
5407         printf("Package Group %d id=%d packageCount=%d name=%s\n",
5408                 (int)pgIndex, pg->id, (int)pg->packages.size(),
5409                 String8(pg->name).string());
5410 
5411         size_t pkgCount = pg->packages.size();
5412         for (size_t pkgIndex=0; pkgIndex<pkgCount; pkgIndex++) {
5413             const Package* pkg = pg->packages[pkgIndex];
5414             size_t typeCount = pkg->types.size();
5415             printf("  Package %d id=%d name=%s typeCount=%d\n", (int)pkgIndex,
5416                     pkg->package->id, String8(String16(pkg->package->name)).string(),
5417                     (int)typeCount);
5418             for (size_t typeIndex=0; typeIndex<typeCount; typeIndex++) {
5419                 const Type* typeConfigs = pkg->getType(typeIndex);
5420                 if (typeConfigs == NULL) {
5421                     printf("    type %d NULL\n", (int)typeIndex);
5422                     continue;
5423                 }
5424                 const size_t NTC = typeConfigs->configs.size();
5425                 printf("    type %d configCount=%d entryCount=%d\n",
5426                        (int)typeIndex, (int)NTC, (int)typeConfigs->entryCount);
5427                 if (typeConfigs->typeSpecFlags != NULL) {
5428                     for (size_t entryIndex=0; entryIndex<typeConfigs->entryCount; entryIndex++) {
5429                         uint32_t resID = (0xff000000 & ((pkg->package->id)<<24))
5430                                     | (0x00ff0000 & ((typeIndex+1)<<16))
5431                                     | (0x0000ffff & (entryIndex));
5432                         resource_name resName;
5433                         if (this->getResourceName(resID, &resName)) {
5434                             printf("      spec resource 0x%08x %s:%s/%s: flags=0x%08x\n",
5435                                 resID,
5436                                 CHAR16_TO_CSTR(resName.package, resName.packageLen),
5437                                 CHAR16_TO_CSTR(resName.type, resName.typeLen),
5438                                 CHAR16_TO_CSTR(resName.name, resName.nameLen),
5439                                 dtohl(typeConfigs->typeSpecFlags[entryIndex]));
5440                         } else {
5441                             printf("      INVALID TYPE CONFIG FOR RESOURCE 0x%08x\n", resID);
5442                         }
5443                     }
5444                 }
5445                 for (size_t configIndex=0; configIndex<NTC; configIndex++) {
5446                     const ResTable_type* type = typeConfigs->configs[configIndex];
5447                     if ((((uint64_t)type)&0x3) != 0) {
5448                         printf("      NON-INTEGER ResTable_type ADDRESS: %p\n", type);
5449                         continue;
5450                     }
5451                     String8 configStr = type->config.toString();
5452                     printf("      config %s:\n", configStr.size() > 0
5453                             ? configStr.string() : "(default)");
5454                     size_t entryCount = dtohl(type->entryCount);
5455                     uint32_t entriesStart = dtohl(type->entriesStart);
5456                     if ((entriesStart&0x3) != 0) {
5457                         printf("      NON-INTEGER ResTable_type entriesStart OFFSET: %p\n", (void*)entriesStart);
5458                         continue;
5459                     }
5460                     uint32_t typeSize = dtohl(type->header.size);
5461                     if ((typeSize&0x3) != 0) {
5462                         printf("      NON-INTEGER ResTable_type header.size: %p\n", (void*)typeSize);
5463                         continue;
5464                     }
5465                     for (size_t entryIndex=0; entryIndex<entryCount; entryIndex++) {
5466 
5467                         const uint8_t* const end = ((const uint8_t*)type)
5468                             + dtohl(type->header.size);
5469                         const uint32_t* const eindex = (const uint32_t*)
5470                             (((const uint8_t*)type) + dtohs(type->header.headerSize));
5471 
5472                         uint32_t thisOffset = dtohl(eindex[entryIndex]);
5473                         if (thisOffset == ResTable_type::NO_ENTRY) {
5474                             continue;
5475                         }
5476 
5477                         uint32_t resID = (0xff000000 & ((pkg->package->id)<<24))
5478                                     | (0x00ff0000 & ((typeIndex+1)<<16))
5479                                     | (0x0000ffff & (entryIndex));
5480                         resource_name resName;
5481                         if (this->getResourceName(resID, &resName)) {
5482                             printf("        resource 0x%08x %s:%s/%s: ", resID,
5483                                     CHAR16_TO_CSTR(resName.package, resName.packageLen),
5484                                     CHAR16_TO_CSTR(resName.type, resName.typeLen),
5485                                     CHAR16_TO_CSTR(resName.name, resName.nameLen));
5486                         } else {
5487                             printf("        INVALID RESOURCE 0x%08x: ", resID);
5488                         }
5489                         if ((thisOffset&0x3) != 0) {
5490                             printf("NON-INTEGER OFFSET: %p\n", (void*)thisOffset);
5491                             continue;
5492                         }
5493                         if ((thisOffset+sizeof(ResTable_entry)) > typeSize) {
5494                             printf("OFFSET OUT OF BOUNDS: %p+%p (size is %p)\n",
5495                                    (void*)entriesStart, (void*)thisOffset,
5496                                    (void*)typeSize);
5497                             continue;
5498                         }
5499 
5500                         const ResTable_entry* ent = (const ResTable_entry*)
5501                             (((const uint8_t*)type) + entriesStart + thisOffset);
5502                         if (((entriesStart + thisOffset)&0x3) != 0) {
5503                             printf("NON-INTEGER ResTable_entry OFFSET: %p\n",
5504                                  (void*)(entriesStart + thisOffset));
5505                             continue;
5506                         }
5507 
5508                         uint16_t esize = dtohs(ent->size);
5509                         if ((esize&0x3) != 0) {
5510                             printf("NON-INTEGER ResTable_entry SIZE: %p\n", (void*)esize);
5511                             continue;
5512                         }
5513                         if ((thisOffset+esize) > typeSize) {
5514                             printf("ResTable_entry OUT OF BOUNDS: %p+%p+%p (size is %p)\n",
5515                                    (void*)entriesStart, (void*)thisOffset,
5516                                    (void*)esize, (void*)typeSize);
5517                             continue;
5518                         }
5519 
5520                         const Res_value* valuePtr = NULL;
5521                         const ResTable_map_entry* bagPtr = NULL;
5522                         Res_value value;
5523                         if ((dtohs(ent->flags)&ResTable_entry::FLAG_COMPLEX) != 0) {
5524                             printf("<bag>");
5525                             bagPtr = (const ResTable_map_entry*)ent;
5526                         } else {
5527                             valuePtr = (const Res_value*)
5528                                 (((const uint8_t*)ent) + esize);
5529                             value.copyFrom_dtoh(*valuePtr);
5530                             printf("t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)",
5531                                    (int)value.dataType, (int)value.data,
5532                                    (int)value.size, (int)value.res0);
5533                         }
5534 
5535                         if ((dtohs(ent->flags)&ResTable_entry::FLAG_PUBLIC) != 0) {
5536                             printf(" (PUBLIC)");
5537                         }
5538                         printf("\n");
5539 
5540                         if (inclValues) {
5541                             if (valuePtr != NULL) {
5542                                 printf("          ");
5543                                 print_value(pkg, value);
5544                             } else if (bagPtr != NULL) {
5545                                 const int N = dtohl(bagPtr->count);
5546                                 const uint8_t* baseMapPtr = (const uint8_t*)ent;
5547                                 size_t mapOffset = esize;
5548                                 const ResTable_map* mapPtr = (ResTable_map*)(baseMapPtr+mapOffset);
5549                                 printf("          Parent=0x%08x, Count=%d\n",
5550                                     dtohl(bagPtr->parent.ident), N);
5551                                 for (int i=0; i<N && mapOffset < (typeSize-sizeof(ResTable_map)); i++) {
5552                                     printf("          #%i (Key=0x%08x): ",
5553                                         i, dtohl(mapPtr->name.ident));
5554                                     value.copyFrom_dtoh(mapPtr->value);
5555                                     print_value(pkg, value);
5556                                     const size_t size = dtohs(mapPtr->value.size);
5557                                     mapOffset += size + sizeof(*mapPtr)-sizeof(mapPtr->value);
5558                                     mapPtr = (ResTable_map*)(baseMapPtr+mapOffset);
5559                                 }
5560                             }
5561                         }
5562                     }
5563                 }
5564             }
5565         }
5566     }
5567 }
5568 
5569 #endif // HAVE_ANDROID_OS
5570 
5571 }   // namespace android
5572