blob: 3569e32d749e8611808af43b41aa7ad0e0f76ab9 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "ResourceType"
18//#define LOG_NDEBUG 0
19
20#include <utils/Atomic.h>
21#include <utils/ByteOrder.h>
22#include <utils/Debug.h>
23#include <utils/ResourceTypes.h>
24#include <utils/String16.h>
25#include <utils/String8.h>
26#include <utils/TextOutput.h>
27#include <utils/Log.h>
28
29#include <stdlib.h>
30#include <string.h>
31#include <memory.h>
32#include <ctype.h>
33#include <stdint.h>
34
35#ifndef INT32_MAX
36#define INT32_MAX ((int32_t)(2147483647))
37#endif
38
39#define POOL_NOISY(x) //x
40#define XML_NOISY(x) //x
41#define TABLE_NOISY(x) //x
42#define TABLE_GETENTRY(x) //x
43#define TABLE_SUPER_NOISY(x) //x
44#define LOAD_TABLE_NOISY(x) //x
Dianne Hackbornb8d81672009-11-20 14:26:42 -080045#define TABLE_THEME(x) //x
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046
47namespace android {
48
49#ifdef HAVE_WINSOCK
50#undef nhtol
51#undef htonl
52
53#ifdef HAVE_LITTLE_ENDIAN
54#define ntohl(x) ( ((x) << 24) | (((x) >> 24) & 255) | (((x) << 8) & 0xff0000) | (((x) >> 8) & 0xff00) )
55#define htonl(x) ntohl(x)
56#define ntohs(x) ( (((x) << 8) & 0xff00) | (((x) >> 8) & 255) )
57#define htons(x) ntohs(x)
58#else
59#define ntohl(x) (x)
60#define htonl(x) (x)
61#define ntohs(x) (x)
62#define htons(x) (x)
63#endif
64#endif
65
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +010066#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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070static void printToLogFunc(void* cookie, const char* txt)
71{
Steve Block71f2cf12011-10-20 11:56:00 +010072 ALOGV("%s", txt);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073}
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.
78inline 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.
85static 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
96static 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 LOGW("%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 LOGW("%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 LOGW("%s size %p is smaller than header size %p.",
120 name, (void*)size, (void*)(int)headerSize);
121 return BAD_TYPE;
122 }
123 LOGW("%s header size %p is too small.",
124 name, (void*)(int)headerSize);
125 return BAD_TYPE;
126}
127
128inline 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
136void 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
153void 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
170size_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
182void* Res_png_9patch::serialize()
183{
The Android Open Source Project4df24232009-03-05 14:34:35 -0800184 // 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());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 serialize(newData);
188 return newData;
189}
190
191void 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
205static 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
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +0100221static bool assertIdmapHeader(const uint32_t* map, size_t sizeBytes)
222{
223 if (sizeBytes < ResTable::IDMAP_HEADER_SIZE_BYTES) {
224 LOGW("idmap assertion failed: size=%d bytes\n", sizeBytes);
225 return false;
226 }
227 if (*map != htodl(IDMAP_MAGIC)) { // htodl: map data expected to be in correct endianess
228 LOGW("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
235static 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 LOGW("Resource ID map: type=%d exceeds number of types=%d\n", type, typeCount);
250 return UNKNOWN_ERROR;
251 }
252 if (typeCount > size) {
253 LOGW("Resource ID map: number of types=%d exceeds size of map=%d\n", typeCount, 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 LOGW("Resource ID map: type offset=%d exceeds reasonable value, size of map=%d\n",
263 typeOffset, 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 LOGW("Resource ID map: entry index=%d exceeds size of map=%d\n", index, size);
275 *outValue = 0;
276 return NO_ERROR;
277 }
278 *outValue = map[index];
279
280 return NO_ERROR;
281}
282
283static 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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800296Res_png_9patch* Res_png_9patch::deserialize(const void* inData)
297{
298 if (sizeof(void*) != sizeof(int32_t)) {
299 LOGE("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
310ResStringPool::ResStringPool()
Kenny Root19138462009-12-04 09:38:48 -0800311 : mError(NO_INIT), mOwnedData(NULL), mHeader(NULL), mCache(NULL)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800312{
313}
314
315ResStringPool::ResStringPool(const void* data, size_t size, bool copyData)
Kenny Root19138462009-12-04 09:38:48 -0800316 : mError(NO_INIT), mOwnedData(NULL), mHeader(NULL), mCache(NULL)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800317{
318 setTo(data, size, copyData);
319}
320
321ResStringPool::~ResStringPool()
322{
323 uninit();
324}
325
326status_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 LOGW("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 LOGW("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 }
Kenny Root19138462009-12-04 09:38:48 -0800378
379 size_t charSize;
380 if (mHeader->flags&ResStringPool_header::UTF8_FLAG) {
381 charSize = sizeof(uint8_t);
382 mCache = (char16_t**)malloc(sizeof(char16_t**)*mHeader->stringCount);
383 memset(mCache, 0, sizeof(char16_t**)*mHeader->stringCount);
384 } else {
385 charSize = sizeof(char16_t);
386 }
387
388 mStrings = (const void*)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 (((const uint8_t*)data)+mHeader->stringsStart);
390 if (mHeader->stringsStart >= (mHeader->header.size-sizeof(uint16_t))) {
391 LOGW("Bad string block: string pool starts at %d, after total size %d\n",
392 (int)mHeader->stringsStart, (int)mHeader->header.size);
393 return (mError=BAD_TYPE);
394 }
395 if (mHeader->styleCount == 0) {
396 mStringPoolSize =
Kenny Root19138462009-12-04 09:38:48 -0800397 (mHeader->header.size-mHeader->stringsStart)/charSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398 } else {
Kenny Root5e4d9a02010-06-08 12:34:43 -0700399 // check invariant: styles starts before end of data
400 if (mHeader->stylesStart >= (mHeader->header.size-sizeof(uint16_t))) {
401 LOGW("Bad style block: style block starts at %d past data size of %d\n",
402 (int)mHeader->stylesStart, (int)mHeader->header.size);
403 return (mError=BAD_TYPE);
404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 // check invariant: styles follow the strings
406 if (mHeader->stylesStart <= mHeader->stringsStart) {
407 LOGW("Bad style block: style block starts at %d, before strings at %d\n",
408 (int)mHeader->stylesStart, (int)mHeader->stringsStart);
409 return (mError=BAD_TYPE);
410 }
411 mStringPoolSize =
Kenny Root19138462009-12-04 09:38:48 -0800412 (mHeader->stylesStart-mHeader->stringsStart)/charSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413 }
414
415 // check invariant: stringCount > 0 requires a string pool to exist
416 if (mStringPoolSize == 0) {
417 LOGW("Bad string block: stringCount is %d but pool size is 0\n", (int)mHeader->stringCount);
418 return (mError=BAD_TYPE);
419 }
420
421 if (notDeviceEndian) {
422 size_t i;
423 uint32_t* e = const_cast<uint32_t*>(mEntries);
424 for (i=0; i<mHeader->stringCount; i++) {
425 e[i] = dtohl(mEntries[i]);
426 }
Kenny Root19138462009-12-04 09:38:48 -0800427 if (!(mHeader->flags&ResStringPool_header::UTF8_FLAG)) {
428 const char16_t* strings = (const char16_t*)mStrings;
429 char16_t* s = const_cast<char16_t*>(strings);
430 for (i=0; i<mStringPoolSize; i++) {
431 s[i] = dtohs(strings[i]);
432 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800433 }
434 }
435
Kenny Root19138462009-12-04 09:38:48 -0800436 if ((mHeader->flags&ResStringPool_header::UTF8_FLAG &&
437 ((uint8_t*)mStrings)[mStringPoolSize-1] != 0) ||
438 (!mHeader->flags&ResStringPool_header::UTF8_FLAG &&
439 ((char16_t*)mStrings)[mStringPoolSize-1] != 0)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 LOGW("Bad string block: last string is not 0-terminated\n");
441 return (mError=BAD_TYPE);
442 }
443 } else {
444 mStrings = NULL;
445 mStringPoolSize = 0;
446 }
447
448 if (mHeader->styleCount > 0) {
449 mEntryStyles = mEntries + mHeader->stringCount;
450 // invariant: integer overflow in calculating mEntryStyles
451 if (mEntryStyles < mEntries) {
452 LOGW("Bad string block: integer overflow finding styles\n");
453 return (mError=BAD_TYPE);
454 }
455
456 if (((const uint8_t*)mEntryStyles-(const uint8_t*)mHeader) > (int)size) {
457 LOGW("Bad string block: entry of %d styles extends past data size %d\n",
458 (int)((const uint8_t*)mEntryStyles-(const uint8_t*)mHeader),
459 (int)size);
460 return (mError=BAD_TYPE);
461 }
462 mStyles = (const uint32_t*)
463 (((const uint8_t*)data)+mHeader->stylesStart);
464 if (mHeader->stylesStart >= mHeader->header.size) {
465 LOGW("Bad string block: style pool starts %d, after total size %d\n",
466 (int)mHeader->stylesStart, (int)mHeader->header.size);
467 return (mError=BAD_TYPE);
468 }
469 mStylePoolSize =
470 (mHeader->header.size-mHeader->stylesStart)/sizeof(uint32_t);
471
472 if (notDeviceEndian) {
473 size_t i;
474 uint32_t* e = const_cast<uint32_t*>(mEntryStyles);
475 for (i=0; i<mHeader->styleCount; i++) {
476 e[i] = dtohl(mEntryStyles[i]);
477 }
478 uint32_t* s = const_cast<uint32_t*>(mStyles);
479 for (i=0; i<mStylePoolSize; i++) {
480 s[i] = dtohl(mStyles[i]);
481 }
482 }
483
484 const ResStringPool_span endSpan = {
485 { htodl(ResStringPool_span::END) },
486 htodl(ResStringPool_span::END), htodl(ResStringPool_span::END)
487 };
488 if (memcmp(&mStyles[mStylePoolSize-(sizeof(endSpan)/sizeof(uint32_t))],
489 &endSpan, sizeof(endSpan)) != 0) {
490 LOGW("Bad string block: last style is not 0xFFFFFFFF-terminated\n");
491 return (mError=BAD_TYPE);
492 }
493 } else {
494 mEntryStyles = NULL;
495 mStyles = NULL;
496 mStylePoolSize = 0;
497 }
498
499 return (mError=NO_ERROR);
500}
501
502status_t ResStringPool::getError() const
503{
504 return mError;
505}
506
507void ResStringPool::uninit()
508{
509 mError = NO_INIT;
510 if (mOwnedData) {
511 free(mOwnedData);
512 mOwnedData = NULL;
513 }
Kenny Root19138462009-12-04 09:38:48 -0800514 if (mHeader != NULL && mCache != NULL) {
515 for (size_t x = 0; x < mHeader->stringCount; x++) {
516 if (mCache[x] != NULL) {
517 free(mCache[x]);
518 mCache[x] = NULL;
519 }
520 }
521 free(mCache);
522 mCache = NULL;
523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524}
525
Kenny Root300ba682010-11-09 14:37:23 -0800526/**
527 * Strings in UTF-16 format have length indicated by a length encoded in the
528 * stored data. It is either 1 or 2 characters of length data. This allows a
529 * maximum length of 0x7FFFFFF (2147483647 bytes), but if you're storing that
530 * much data in a string, you're abusing them.
531 *
532 * If the high bit is set, then there are two characters or 4 bytes of length
533 * data encoded. In that case, drop the high bit of the first character and
534 * add it together with the next character.
535 */
536static inline size_t
537decodeLength(const char16_t** str)
538{
539 size_t len = **str;
540 if ((len & 0x8000) != 0) {
541 (*str)++;
542 len = ((len & 0x7FFF) << 16) | **str;
543 }
544 (*str)++;
545 return len;
546}
Kenny Root19138462009-12-04 09:38:48 -0800547
Kenny Root300ba682010-11-09 14:37:23 -0800548/**
549 * Strings in UTF-8 format have length indicated by a length encoded in the
550 * stored data. It is either 1 or 2 characters of length data. This allows a
551 * maximum length of 0x7FFF (32767 bytes), but you should consider storing
552 * text in another way if you're using that much data in a single string.
553 *
554 * If the high bit is set, then there are two characters or 2 bytes of length
555 * data encoded. In that case, drop the high bit of the first character and
556 * add it together with the next character.
557 */
558static inline size_t
559decodeLength(const uint8_t** str)
560{
561 size_t len = **str;
562 if ((len & 0x80) != 0) {
563 (*str)++;
564 len = ((len & 0x7F) << 8) | **str;
565 }
566 (*str)++;
567 return len;
568}
569
570const uint16_t* ResStringPool::stringAt(size_t idx, size_t* u16len) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800571{
572 if (mError == NO_ERROR && idx < mHeader->stringCount) {
Kenny Root19138462009-12-04 09:38:48 -0800573 const bool isUTF8 = (mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0;
574 const uint32_t off = mEntries[idx]/(isUTF8?sizeof(char):sizeof(char16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 if (off < (mStringPoolSize-1)) {
Kenny Root19138462009-12-04 09:38:48 -0800576 if (!isUTF8) {
577 const char16_t* strings = (char16_t*)mStrings;
578 const char16_t* str = strings+off;
Kenny Root300ba682010-11-09 14:37:23 -0800579
580 *u16len = decodeLength(&str);
581 if ((uint32_t)(str+*u16len-strings) < mStringPoolSize) {
Kenny Root19138462009-12-04 09:38:48 -0800582 return str;
583 } else {
584 LOGW("Bad string block: string #%d extends to %d, past end at %d\n",
Kenny Root300ba682010-11-09 14:37:23 -0800585 (int)idx, (int)(str+*u16len-strings), (int)mStringPoolSize);
Kenny Root19138462009-12-04 09:38:48 -0800586 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587 } else {
Kenny Root19138462009-12-04 09:38:48 -0800588 const uint8_t* strings = (uint8_t*)mStrings;
Kenny Root300ba682010-11-09 14:37:23 -0800589 const uint8_t* u8str = strings+off;
590
591 *u16len = decodeLength(&u8str);
592 size_t u8len = decodeLength(&u8str);
593
594 // encLen must be less than 0x7FFF due to encoding.
595 if ((uint32_t)(u8str+u8len-strings) < mStringPoolSize) {
Kenny Root19138462009-12-04 09:38:48 -0800596 AutoMutex lock(mDecodeLock);
Kenny Root300ba682010-11-09 14:37:23 -0800597
Kenny Root19138462009-12-04 09:38:48 -0800598 if (mCache[idx] != NULL) {
599 return mCache[idx];
600 }
Kenny Root300ba682010-11-09 14:37:23 -0800601
602 ssize_t actualLen = utf8_to_utf16_length(u8str, u8len);
603 if (actualLen < 0 || (size_t)actualLen != *u16len) {
604 LOGW("Bad string block: string #%lld decoded length is not correct "
605 "%lld vs %llu\n",
606 (long long)idx, (long long)actualLen, (long long)*u16len);
607 return NULL;
608 }
609
610 char16_t *u16str = (char16_t *)calloc(*u16len+1, sizeof(char16_t));
Kenny Root19138462009-12-04 09:38:48 -0800611 if (!u16str) {
612 LOGW("No memory when trying to allocate decode cache for string #%d\n",
613 (int)idx);
614 return NULL;
615 }
Kenny Root300ba682010-11-09 14:37:23 -0800616
617 utf8_to_utf16(u8str, u8len, u16str);
Kenny Root19138462009-12-04 09:38:48 -0800618 mCache[idx] = u16str;
619 return u16str;
620 } else {
Kenny Root300ba682010-11-09 14:37:23 -0800621 LOGW("Bad string block: string #%lld extends to %lld, past end at %lld\n",
622 (long long)idx, (long long)(u8str+u8len-strings),
623 (long long)mStringPoolSize);
Kenny Root19138462009-12-04 09:38:48 -0800624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 }
626 } else {
627 LOGW("Bad string block: string #%d entry is at %d, past end at %d\n",
628 (int)idx, (int)(off*sizeof(uint16_t)),
629 (int)(mStringPoolSize*sizeof(uint16_t)));
630 }
631 }
632 return NULL;
633}
634
Kenny Root780d2a12010-02-22 22:36:26 -0800635const char* ResStringPool::string8At(size_t idx, size_t* outLen) const
636{
637 if (mError == NO_ERROR && idx < mHeader->stringCount) {
638 const bool isUTF8 = (mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0;
639 const uint32_t off = mEntries[idx]/(isUTF8?sizeof(char):sizeof(char16_t));
640 if (off < (mStringPoolSize-1)) {
641 if (isUTF8) {
642 const uint8_t* strings = (uint8_t*)mStrings;
643 const uint8_t* str = strings+off;
Kenny Root300ba682010-11-09 14:37:23 -0800644 *outLen = decodeLength(&str);
645 size_t encLen = decodeLength(&str);
Kenny Root780d2a12010-02-22 22:36:26 -0800646 if ((uint32_t)(str+encLen-strings) < mStringPoolSize) {
647 return (const char*)str;
648 } else {
649 LOGW("Bad string block: string #%d extends to %d, past end at %d\n",
650 (int)idx, (int)(str+encLen-strings), (int)mStringPoolSize);
651 }
652 }
653 } else {
654 LOGW("Bad string block: string #%d entry is at %d, past end at %d\n",
655 (int)idx, (int)(off*sizeof(uint16_t)),
656 (int)(mStringPoolSize*sizeof(uint16_t)));
657 }
658 }
659 return NULL;
660}
661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662const ResStringPool_span* ResStringPool::styleAt(const ResStringPool_ref& ref) const
663{
664 return styleAt(ref.index);
665}
666
667const ResStringPool_span* ResStringPool::styleAt(size_t idx) const
668{
669 if (mError == NO_ERROR && idx < mHeader->styleCount) {
670 const uint32_t off = (mEntryStyles[idx]/sizeof(uint32_t));
671 if (off < mStylePoolSize) {
672 return (const ResStringPool_span*)(mStyles+off);
673 } else {
674 LOGW("Bad string block: style #%d entry is at %d, past end at %d\n",
675 (int)idx, (int)(off*sizeof(uint32_t)),
676 (int)(mStylePoolSize*sizeof(uint32_t)));
677 }
678 }
679 return NULL;
680}
681
682ssize_t ResStringPool::indexOfString(const char16_t* str, size_t strLen) const
683{
684 if (mError != NO_ERROR) {
685 return mError;
686 }
687
688 size_t len;
689
Kenny Root19138462009-12-04 09:38:48 -0800690 // TODO optimize searching for UTF-8 strings taking into account
691 // the cache fill to determine when to convert the searched-for
692 // string key to UTF-8.
693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 if (mHeader->flags&ResStringPool_header::SORTED_FLAG) {
695 // Do a binary search for the string...
696 ssize_t l = 0;
697 ssize_t h = mHeader->stringCount-1;
698
699 ssize_t mid;
700 while (l <= h) {
701 mid = l + (h - l)/2;
702 const char16_t* s = stringAt(mid, &len);
703 int c = s ? strzcmp16(s, len, str, strLen) : -1;
704 POOL_NOISY(printf("Looking for %s, at %s, cmp=%d, l/mid/h=%d/%d/%d\n",
705 String8(str).string(),
706 String8(s).string(),
707 c, (int)l, (int)mid, (int)h));
708 if (c == 0) {
709 return mid;
710 } else if (c < 0) {
711 l = mid + 1;
712 } else {
713 h = mid - 1;
714 }
715 }
716 } else {
717 // It is unusual to get the ID from an unsorted string block...
718 // most often this happens because we want to get IDs for style
719 // span tags; since those always appear at the end of the string
720 // block, start searching at the back.
721 for (int i=mHeader->stringCount-1; i>=0; i--) {
722 const char16_t* s = stringAt(i, &len);
723 POOL_NOISY(printf("Looking for %s, at %s, i=%d\n",
724 String8(str, strLen).string(),
725 String8(s).string(),
726 i));
727 if (s && strzcmp16(s, len, str, strLen) == 0) {
728 return i;
729 }
730 }
731 }
732
733 return NAME_NOT_FOUND;
734}
735
736size_t ResStringPool::size() const
737{
738 return (mError == NO_ERROR) ? mHeader->stringCount : 0;
739}
740
Kenny Rootbb79f642009-12-10 14:20:15 -0800741#ifndef HAVE_ANDROID_OS
742bool ResStringPool::isUTF8() const
743{
744 return (mHeader->flags&ResStringPool_header::UTF8_FLAG)!=0;
745}
746#endif
747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748// --------------------------------------------------------------------
749// --------------------------------------------------------------------
750// --------------------------------------------------------------------
751
752ResXMLParser::ResXMLParser(const ResXMLTree& tree)
753 : mTree(tree), mEventCode(BAD_DOCUMENT)
754{
755}
756
757void ResXMLParser::restart()
758{
759 mCurNode = NULL;
760 mEventCode = mTree.mError == NO_ERROR ? START_DOCUMENT : BAD_DOCUMENT;
761}
Dianne Hackborncf244ad2010-03-09 15:00:30 -0800762const ResStringPool& ResXMLParser::getStrings() const
763{
764 return mTree.mStrings;
765}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766
767ResXMLParser::event_code_t ResXMLParser::getEventType() const
768{
769 return mEventCode;
770}
771
772ResXMLParser::event_code_t ResXMLParser::next()
773{
774 if (mEventCode == START_DOCUMENT) {
775 mCurNode = mTree.mRootNode;
776 mCurExt = mTree.mRootExt;
777 return (mEventCode=mTree.mRootCode);
778 } else if (mEventCode >= FIRST_CHUNK_CODE) {
779 return nextNode();
780 }
781 return mEventCode;
782}
783
Mathias Agopian5f910972009-06-22 02:35:32 -0700784int32_t ResXMLParser::getCommentID() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785{
786 return mCurNode != NULL ? dtohl(mCurNode->comment.index) : -1;
787}
788
789const uint16_t* ResXMLParser::getComment(size_t* outLen) const
790{
791 int32_t id = getCommentID();
792 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
793}
794
Mathias Agopian5f910972009-06-22 02:35:32 -0700795uint32_t ResXMLParser::getLineNumber() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796{
797 return mCurNode != NULL ? dtohl(mCurNode->lineNumber) : -1;
798}
799
Mathias Agopian5f910972009-06-22 02:35:32 -0700800int32_t ResXMLParser::getTextID() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801{
802 if (mEventCode == TEXT) {
803 return dtohl(((const ResXMLTree_cdataExt*)mCurExt)->data.index);
804 }
805 return -1;
806}
807
808const uint16_t* ResXMLParser::getText(size_t* outLen) const
809{
810 int32_t id = getTextID();
811 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
812}
813
814ssize_t ResXMLParser::getTextValue(Res_value* outValue) const
815{
816 if (mEventCode == TEXT) {
817 outValue->copyFrom_dtoh(((const ResXMLTree_cdataExt*)mCurExt)->typedData);
818 return sizeof(Res_value);
819 }
820 return BAD_TYPE;
821}
822
Mathias Agopian5f910972009-06-22 02:35:32 -0700823int32_t ResXMLParser::getNamespacePrefixID() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824{
825 if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) {
826 return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->prefix.index);
827 }
828 return -1;
829}
830
831const uint16_t* ResXMLParser::getNamespacePrefix(size_t* outLen) const
832{
833 int32_t id = getNamespacePrefixID();
834 //printf("prefix=%d event=%p\n", id, mEventCode);
835 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
836}
837
Mathias Agopian5f910972009-06-22 02:35:32 -0700838int32_t ResXMLParser::getNamespaceUriID() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839{
840 if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) {
841 return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->uri.index);
842 }
843 return -1;
844}
845
846const uint16_t* ResXMLParser::getNamespaceUri(size_t* outLen) const
847{
848 int32_t id = getNamespaceUriID();
849 //printf("uri=%d event=%p\n", id, mEventCode);
850 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
851}
852
Mathias Agopian5f910972009-06-22 02:35:32 -0700853int32_t ResXMLParser::getElementNamespaceID() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854{
855 if (mEventCode == START_TAG) {
856 return dtohl(((const ResXMLTree_attrExt*)mCurExt)->ns.index);
857 }
858 if (mEventCode == END_TAG) {
859 return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->ns.index);
860 }
861 return -1;
862}
863
864const uint16_t* ResXMLParser::getElementNamespace(size_t* outLen) const
865{
866 int32_t id = getElementNamespaceID();
867 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
868}
869
Mathias Agopian5f910972009-06-22 02:35:32 -0700870int32_t ResXMLParser::getElementNameID() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871{
872 if (mEventCode == START_TAG) {
873 return dtohl(((const ResXMLTree_attrExt*)mCurExt)->name.index);
874 }
875 if (mEventCode == END_TAG) {
876 return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->name.index);
877 }
878 return -1;
879}
880
881const uint16_t* ResXMLParser::getElementName(size_t* outLen) const
882{
883 int32_t id = getElementNameID();
884 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
885}
886
887size_t ResXMLParser::getAttributeCount() const
888{
889 if (mEventCode == START_TAG) {
890 return dtohs(((const ResXMLTree_attrExt*)mCurExt)->attributeCount);
891 }
892 return 0;
893}
894
Mathias Agopian5f910972009-06-22 02:35:32 -0700895int32_t ResXMLParser::getAttributeNamespaceID(size_t idx) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896{
897 if (mEventCode == START_TAG) {
898 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
899 if (idx < dtohs(tag->attributeCount)) {
900 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
901 (((const uint8_t*)tag)
902 + dtohs(tag->attributeStart)
903 + (dtohs(tag->attributeSize)*idx));
904 return dtohl(attr->ns.index);
905 }
906 }
907 return -2;
908}
909
910const uint16_t* ResXMLParser::getAttributeNamespace(size_t idx, size_t* outLen) const
911{
912 int32_t id = getAttributeNamespaceID(idx);
913 //printf("attribute namespace=%d idx=%d event=%p\n", id, idx, mEventCode);
914 //XML_NOISY(printf("getAttributeNamespace 0x%x=0x%x\n", idx, id));
915 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
916}
917
Mathias Agopian5f910972009-06-22 02:35:32 -0700918int32_t ResXMLParser::getAttributeNameID(size_t idx) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919{
920 if (mEventCode == START_TAG) {
921 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
922 if (idx < dtohs(tag->attributeCount)) {
923 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
924 (((const uint8_t*)tag)
925 + dtohs(tag->attributeStart)
926 + (dtohs(tag->attributeSize)*idx));
927 return dtohl(attr->name.index);
928 }
929 }
930 return -1;
931}
932
933const uint16_t* ResXMLParser::getAttributeName(size_t idx, size_t* outLen) const
934{
935 int32_t id = getAttributeNameID(idx);
936 //printf("attribute name=%d idx=%d event=%p\n", id, idx, mEventCode);
937 //XML_NOISY(printf("getAttributeName 0x%x=0x%x\n", idx, id));
938 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
939}
940
Mathias Agopian5f910972009-06-22 02:35:32 -0700941uint32_t ResXMLParser::getAttributeNameResID(size_t idx) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942{
943 int32_t id = getAttributeNameID(idx);
944 if (id >= 0 && (size_t)id < mTree.mNumResIds) {
945 return dtohl(mTree.mResIds[id]);
946 }
947 return 0;
948}
949
Mathias Agopian5f910972009-06-22 02:35:32 -0700950int32_t ResXMLParser::getAttributeValueStringID(size_t idx) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800951{
952 if (mEventCode == START_TAG) {
953 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
954 if (idx < dtohs(tag->attributeCount)) {
955 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
956 (((const uint8_t*)tag)
957 + dtohs(tag->attributeStart)
958 + (dtohs(tag->attributeSize)*idx));
959 return dtohl(attr->rawValue.index);
960 }
961 }
962 return -1;
963}
964
965const uint16_t* ResXMLParser::getAttributeStringValue(size_t idx, size_t* outLen) const
966{
967 int32_t id = getAttributeValueStringID(idx);
968 //XML_NOISY(printf("getAttributeValue 0x%x=0x%x\n", idx, id));
969 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
970}
971
972int32_t ResXMLParser::getAttributeDataType(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 attr->typedValue.dataType;
982 }
983 }
984 return Res_value::TYPE_NULL;
985}
986
987int32_t ResXMLParser::getAttributeData(size_t idx) const
988{
989 if (mEventCode == START_TAG) {
990 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
991 if (idx < dtohs(tag->attributeCount)) {
992 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
993 (((const uint8_t*)tag)
994 + dtohs(tag->attributeStart)
995 + (dtohs(tag->attributeSize)*idx));
996 return dtohl(attr->typedValue.data);
997 }
998 }
999 return 0;
1000}
1001
1002ssize_t ResXMLParser::getAttributeValue(size_t idx, Res_value* outValue) const
1003{
1004 if (mEventCode == START_TAG) {
1005 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1006 if (idx < dtohs(tag->attributeCount)) {
1007 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1008 (((const uint8_t*)tag)
1009 + dtohs(tag->attributeStart)
1010 + (dtohs(tag->attributeSize)*idx));
1011 outValue->copyFrom_dtoh(attr->typedValue);
1012 return sizeof(Res_value);
1013 }
1014 }
1015 return BAD_TYPE;
1016}
1017
1018ssize_t ResXMLParser::indexOfAttribute(const char* ns, const char* attr) const
1019{
1020 String16 nsStr(ns != NULL ? ns : "");
1021 String16 attrStr(attr);
1022 return indexOfAttribute(ns ? nsStr.string() : NULL, ns ? nsStr.size() : 0,
1023 attrStr.string(), attrStr.size());
1024}
1025
1026ssize_t ResXMLParser::indexOfAttribute(const char16_t* ns, size_t nsLen,
1027 const char16_t* attr, size_t attrLen) const
1028{
1029 if (mEventCode == START_TAG) {
1030 const size_t N = getAttributeCount();
1031 for (size_t i=0; i<N; i++) {
1032 size_t curNsLen, curAttrLen;
1033 const char16_t* curNs = getAttributeNamespace(i, &curNsLen);
1034 const char16_t* curAttr = getAttributeName(i, &curAttrLen);
1035 //printf("%d: ns=%p attr=%p curNs=%p curAttr=%p\n",
1036 // i, ns, attr, curNs, curAttr);
1037 //printf(" --> attr=%s, curAttr=%s\n",
1038 // String8(attr).string(), String8(curAttr).string());
1039 if (attr && curAttr && (strzcmp16(attr, attrLen, curAttr, curAttrLen) == 0)) {
1040 if (ns == NULL) {
1041 if (curNs == NULL) return i;
1042 } else if (curNs != NULL) {
1043 //printf(" --> ns=%s, curNs=%s\n",
1044 // String8(ns).string(), String8(curNs).string());
1045 if (strzcmp16(ns, nsLen, curNs, curNsLen) == 0) return i;
1046 }
1047 }
1048 }
1049 }
1050
1051 return NAME_NOT_FOUND;
1052}
1053
1054ssize_t ResXMLParser::indexOfID() const
1055{
1056 if (mEventCode == START_TAG) {
1057 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->idIndex);
1058 if (idx > 0) return (idx-1);
1059 }
1060 return NAME_NOT_FOUND;
1061}
1062
1063ssize_t ResXMLParser::indexOfClass() const
1064{
1065 if (mEventCode == START_TAG) {
1066 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->classIndex);
1067 if (idx > 0) return (idx-1);
1068 }
1069 return NAME_NOT_FOUND;
1070}
1071
1072ssize_t ResXMLParser::indexOfStyle() const
1073{
1074 if (mEventCode == START_TAG) {
1075 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->styleIndex);
1076 if (idx > 0) return (idx-1);
1077 }
1078 return NAME_NOT_FOUND;
1079}
1080
1081ResXMLParser::event_code_t ResXMLParser::nextNode()
1082{
1083 if (mEventCode < 0) {
1084 return mEventCode;
1085 }
1086
1087 do {
1088 const ResXMLTree_node* next = (const ResXMLTree_node*)
1089 (((const uint8_t*)mCurNode) + dtohl(mCurNode->header.size));
1090 //LOGW("Next node: prev=%p, next=%p\n", mCurNode, next);
1091
1092 if (((const uint8_t*)next) >= mTree.mDataEnd) {
1093 mCurNode = NULL;
1094 return (mEventCode=END_DOCUMENT);
1095 }
1096
1097 if (mTree.validateNode(next) != NO_ERROR) {
1098 mCurNode = NULL;
1099 return (mEventCode=BAD_DOCUMENT);
1100 }
1101
1102 mCurNode = next;
1103 const uint16_t headerSize = dtohs(next->header.headerSize);
1104 const uint32_t totalSize = dtohl(next->header.size);
1105 mCurExt = ((const uint8_t*)next) + headerSize;
1106 size_t minExtSize = 0;
1107 event_code_t eventCode = (event_code_t)dtohs(next->header.type);
1108 switch ((mEventCode=eventCode)) {
1109 case RES_XML_START_NAMESPACE_TYPE:
1110 case RES_XML_END_NAMESPACE_TYPE:
1111 minExtSize = sizeof(ResXMLTree_namespaceExt);
1112 break;
1113 case RES_XML_START_ELEMENT_TYPE:
1114 minExtSize = sizeof(ResXMLTree_attrExt);
1115 break;
1116 case RES_XML_END_ELEMENT_TYPE:
1117 minExtSize = sizeof(ResXMLTree_endElementExt);
1118 break;
1119 case RES_XML_CDATA_TYPE:
1120 minExtSize = sizeof(ResXMLTree_cdataExt);
1121 break;
1122 default:
1123 LOGW("Unknown XML block: header type %d in node at %d\n",
1124 (int)dtohs(next->header.type),
1125 (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)));
1126 continue;
1127 }
1128
1129 if ((totalSize-headerSize) < minExtSize) {
1130 LOGW("Bad XML block: header type 0x%x in node at 0x%x has size %d, need %d\n",
1131 (int)dtohs(next->header.type),
1132 (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)),
1133 (int)(totalSize-headerSize), (int)minExtSize);
1134 return (mEventCode=BAD_DOCUMENT);
1135 }
1136
1137 //printf("CurNode=%p, CurExt=%p, headerSize=%d, minExtSize=%d\n",
1138 // mCurNode, mCurExt, headerSize, minExtSize);
1139
1140 return eventCode;
1141 } while (true);
1142}
1143
1144void ResXMLParser::getPosition(ResXMLParser::ResXMLPosition* pos) const
1145{
1146 pos->eventCode = mEventCode;
1147 pos->curNode = mCurNode;
1148 pos->curExt = mCurExt;
1149}
1150
1151void ResXMLParser::setPosition(const ResXMLParser::ResXMLPosition& pos)
1152{
1153 mEventCode = pos.eventCode;
1154 mCurNode = pos.curNode;
1155 mCurExt = pos.curExt;
1156}
1157
1158
1159// --------------------------------------------------------------------
1160
1161static volatile int32_t gCount = 0;
1162
1163ResXMLTree::ResXMLTree()
1164 : ResXMLParser(*this)
1165 , mError(NO_INIT), mOwnedData(NULL)
1166{
Steve Block6215d3f2012-01-04 20:05:49 +00001167 //ALOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 restart();
1169}
1170
1171ResXMLTree::ResXMLTree(const void* data, size_t size, bool copyData)
1172 : ResXMLParser(*this)
1173 , mError(NO_INIT), mOwnedData(NULL)
1174{
Steve Block6215d3f2012-01-04 20:05:49 +00001175 //ALOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 setTo(data, size, copyData);
1177}
1178
1179ResXMLTree::~ResXMLTree()
1180{
Steve Block6215d3f2012-01-04 20:05:49 +00001181 //ALOGI("Destroying ResXMLTree in %p #%d\n", this, android_atomic_dec(&gCount)-1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 uninit();
1183}
1184
1185status_t ResXMLTree::setTo(const void* data, size_t size, bool copyData)
1186{
1187 uninit();
1188 mEventCode = START_DOCUMENT;
1189
1190 if (copyData) {
1191 mOwnedData = malloc(size);
1192 if (mOwnedData == NULL) {
1193 return (mError=NO_MEMORY);
1194 }
1195 memcpy(mOwnedData, data, size);
1196 data = mOwnedData;
1197 }
1198
1199 mHeader = (const ResXMLTree_header*)data;
1200 mSize = dtohl(mHeader->header.size);
1201 if (dtohs(mHeader->header.headerSize) > mSize || mSize > size) {
1202 LOGW("Bad XML block: header size %d or total size %d is larger than data size %d\n",
1203 (int)dtohs(mHeader->header.headerSize),
1204 (int)dtohl(mHeader->header.size), (int)size);
1205 mError = BAD_TYPE;
1206 restart();
1207 return mError;
1208 }
1209 mDataEnd = ((const uint8_t*)mHeader) + mSize;
1210
1211 mStrings.uninit();
1212 mRootNode = NULL;
1213 mResIds = NULL;
1214 mNumResIds = 0;
1215
1216 // First look for a couple interesting chunks: the string block
1217 // and first XML node.
1218 const ResChunk_header* chunk =
1219 (const ResChunk_header*)(((const uint8_t*)mHeader) + dtohs(mHeader->header.headerSize));
1220 const ResChunk_header* lastChunk = chunk;
1221 while (((const uint8_t*)chunk) < (mDataEnd-sizeof(ResChunk_header)) &&
1222 ((const uint8_t*)chunk) < (mDataEnd-dtohl(chunk->size))) {
1223 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), mDataEnd, "XML");
1224 if (err != NO_ERROR) {
1225 mError = err;
1226 goto done;
1227 }
1228 const uint16_t type = dtohs(chunk->type);
1229 const size_t size = dtohl(chunk->size);
1230 XML_NOISY(printf("Scanning @ %p: type=0x%x, size=0x%x\n",
1231 (void*)(((uint32_t)chunk)-((uint32_t)mHeader)), type, size));
1232 if (type == RES_STRING_POOL_TYPE) {
1233 mStrings.setTo(chunk, size);
1234 } else if (type == RES_XML_RESOURCE_MAP_TYPE) {
1235 mResIds = (const uint32_t*)
1236 (((const uint8_t*)chunk)+dtohs(chunk->headerSize));
1237 mNumResIds = (dtohl(chunk->size)-dtohs(chunk->headerSize))/sizeof(uint32_t);
1238 } else if (type >= RES_XML_FIRST_CHUNK_TYPE
1239 && type <= RES_XML_LAST_CHUNK_TYPE) {
1240 if (validateNode((const ResXMLTree_node*)chunk) != NO_ERROR) {
1241 mError = BAD_TYPE;
1242 goto done;
1243 }
1244 mCurNode = (const ResXMLTree_node*)lastChunk;
1245 if (nextNode() == BAD_DOCUMENT) {
1246 mError = BAD_TYPE;
1247 goto done;
1248 }
1249 mRootNode = mCurNode;
1250 mRootExt = mCurExt;
1251 mRootCode = mEventCode;
1252 break;
1253 } else {
1254 XML_NOISY(printf("Skipping unknown chunk!\n"));
1255 }
1256 lastChunk = chunk;
1257 chunk = (const ResChunk_header*)
1258 (((const uint8_t*)chunk) + size);
1259 }
1260
1261 if (mRootNode == NULL) {
1262 LOGW("Bad XML block: no root element node found\n");
1263 mError = BAD_TYPE;
1264 goto done;
1265 }
1266
1267 mError = mStrings.getError();
1268
1269done:
1270 restart();
1271 return mError;
1272}
1273
1274status_t ResXMLTree::getError() const
1275{
1276 return mError;
1277}
1278
1279void ResXMLTree::uninit()
1280{
1281 mError = NO_INIT;
Kenny Root19138462009-12-04 09:38:48 -08001282 mStrings.uninit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 if (mOwnedData) {
1284 free(mOwnedData);
1285 mOwnedData = NULL;
1286 }
1287 restart();
1288}
1289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290status_t ResXMLTree::validateNode(const ResXMLTree_node* node) const
1291{
1292 const uint16_t eventCode = dtohs(node->header.type);
1293
1294 status_t err = validate_chunk(
1295 &node->header, sizeof(ResXMLTree_node),
1296 mDataEnd, "ResXMLTree_node");
1297
1298 if (err >= NO_ERROR) {
1299 // Only perform additional validation on START nodes
1300 if (eventCode != RES_XML_START_ELEMENT_TYPE) {
1301 return NO_ERROR;
1302 }
1303
1304 const uint16_t headerSize = dtohs(node->header.headerSize);
1305 const uint32_t size = dtohl(node->header.size);
1306 const ResXMLTree_attrExt* attrExt = (const ResXMLTree_attrExt*)
1307 (((const uint8_t*)node) + headerSize);
1308 // check for sensical values pulled out of the stream so far...
1309 if ((size >= headerSize + sizeof(ResXMLTree_attrExt))
1310 && ((void*)attrExt > (void*)node)) {
1311 const size_t attrSize = ((size_t)dtohs(attrExt->attributeSize))
1312 * dtohs(attrExt->attributeCount);
1313 if ((dtohs(attrExt->attributeStart)+attrSize) <= (size-headerSize)) {
1314 return NO_ERROR;
1315 }
1316 LOGW("Bad XML block: node attributes use 0x%x bytes, only have 0x%x bytes\n",
1317 (unsigned int)(dtohs(attrExt->attributeStart)+attrSize),
1318 (unsigned int)(size-headerSize));
1319 }
1320 else {
1321 LOGW("Bad XML start block: node header size 0x%x, size 0x%x\n",
1322 (unsigned int)headerSize, (unsigned int)size);
1323 }
1324 return BAD_TYPE;
1325 }
1326
1327 return err;
1328
1329#if 0
1330 const bool isStart = dtohs(node->header.type) == RES_XML_START_ELEMENT_TYPE;
1331
1332 const uint16_t headerSize = dtohs(node->header.headerSize);
1333 const uint32_t size = dtohl(node->header.size);
1334
1335 if (headerSize >= (isStart ? sizeof(ResXMLTree_attrNode) : sizeof(ResXMLTree_node))) {
1336 if (size >= headerSize) {
1337 if (((const uint8_t*)node) <= (mDataEnd-size)) {
1338 if (!isStart) {
1339 return NO_ERROR;
1340 }
1341 if ((((size_t)dtohs(node->attributeSize))*dtohs(node->attributeCount))
1342 <= (size-headerSize)) {
1343 return NO_ERROR;
1344 }
1345 LOGW("Bad XML block: node attributes use 0x%x bytes, only have 0x%x bytes\n",
1346 ((int)dtohs(node->attributeSize))*dtohs(node->attributeCount),
1347 (int)(size-headerSize));
1348 return BAD_TYPE;
1349 }
1350 LOGW("Bad XML block: node at 0x%x extends beyond data end 0x%x\n",
1351 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)), (int)mSize);
1352 return BAD_TYPE;
1353 }
1354 LOGW("Bad XML block: node at 0x%x header size 0x%x smaller than total size 0x%x\n",
1355 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)),
1356 (int)headerSize, (int)size);
1357 return BAD_TYPE;
1358 }
1359 LOGW("Bad XML block: node at 0x%x header size 0x%x too small\n",
1360 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)),
1361 (int)headerSize);
1362 return BAD_TYPE;
1363#endif
1364}
1365
1366// --------------------------------------------------------------------
1367// --------------------------------------------------------------------
1368// --------------------------------------------------------------------
1369
1370struct ResTable::Header
1371{
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01001372 Header(ResTable* _owner) : owner(_owner), ownedData(NULL), header(NULL),
1373 resourceIDMap(NULL), resourceIDMapSize(0) { }
1374
1375 ~Header()
1376 {
1377 free(resourceIDMap);
1378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379
Dianne Hackborn78c40512009-07-06 11:07:40 -07001380 ResTable* const owner;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 void* ownedData;
1382 const ResTable_header* header;
1383 size_t size;
1384 const uint8_t* dataEnd;
1385 size_t index;
1386 void* cookie;
1387
1388 ResStringPool values;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01001389 uint32_t* resourceIDMap;
1390 size_t resourceIDMapSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391};
1392
1393struct ResTable::Type
1394{
1395 Type(const Header* _header, const Package* _package, size_t count)
1396 : header(_header), package(_package), entryCount(count),
1397 typeSpec(NULL), typeSpecFlags(NULL) { }
1398 const Header* const header;
1399 const Package* const package;
1400 const size_t entryCount;
1401 const ResTable_typeSpec* typeSpec;
1402 const uint32_t* typeSpecFlags;
1403 Vector<const ResTable_type*> configs;
1404};
1405
1406struct ResTable::Package
1407{
Dianne Hackborn78c40512009-07-06 11:07:40 -07001408 Package(ResTable* _owner, const Header* _header, const ResTable_package* _package)
1409 : owner(_owner), header(_header), package(_package) { }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 ~Package()
1411 {
1412 size_t i = types.size();
1413 while (i > 0) {
1414 i--;
1415 delete types[i];
1416 }
1417 }
1418
Dianne Hackborn78c40512009-07-06 11:07:40 -07001419 ResTable* const owner;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 const Header* const header;
1421 const ResTable_package* const package;
1422 Vector<Type*> types;
1423
Dianne Hackborn78c40512009-07-06 11:07:40 -07001424 ResStringPool typeStrings;
1425 ResStringPool keyStrings;
1426
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 const Type* getType(size_t idx) const {
1428 return idx < types.size() ? types[idx] : NULL;
1429 }
1430};
1431
1432// A group of objects describing a particular resource package.
1433// The first in 'package' is always the root object (from the resource
1434// table that defined the package); the ones after are skins on top of it.
1435struct ResTable::PackageGroup
1436{
Dianne Hackborn78c40512009-07-06 11:07:40 -07001437 PackageGroup(ResTable* _owner, const String16& _name, uint32_t _id)
1438 : owner(_owner), name(_name), id(_id), typeCount(0), bags(NULL) { }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 ~PackageGroup() {
1440 clearBagCache();
1441 const size_t N = packages.size();
1442 for (size_t i=0; i<N; i++) {
Dianne Hackborn78c40512009-07-06 11:07:40 -07001443 Package* pkg = packages[i];
1444 if (pkg->owner == owner) {
1445 delete pkg;
1446 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 }
1448 }
1449
1450 void clearBagCache() {
1451 if (bags) {
1452 TABLE_NOISY(printf("bags=%p\n", bags));
1453 Package* pkg = packages[0];
1454 TABLE_NOISY(printf("typeCount=%x\n", typeCount));
1455 for (size_t i=0; i<typeCount; i++) {
1456 TABLE_NOISY(printf("type=%d\n", i));
1457 const Type* type = pkg->getType(i);
1458 if (type != NULL) {
1459 bag_set** typeBags = bags[i];
1460 TABLE_NOISY(printf("typeBags=%p\n", typeBags));
1461 if (typeBags) {
1462 TABLE_NOISY(printf("type->entryCount=%x\n", type->entryCount));
1463 const size_t N = type->entryCount;
1464 for (size_t j=0; j<N; j++) {
1465 if (typeBags[j] && typeBags[j] != (bag_set*)0xFFFFFFFF)
1466 free(typeBags[j]);
1467 }
1468 free(typeBags);
1469 }
1470 }
1471 }
1472 free(bags);
1473 bags = NULL;
1474 }
1475 }
1476
Dianne Hackborn78c40512009-07-06 11:07:40 -07001477 ResTable* const owner;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 String16 const name;
1479 uint32_t const id;
1480 Vector<Package*> packages;
Dianne Hackborn78c40512009-07-06 11:07:40 -07001481
1482 // This is for finding typeStrings and other common package stuff.
1483 Package* basePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484
Dianne Hackborn78c40512009-07-06 11:07:40 -07001485 // For quick access.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 size_t typeCount;
Dianne Hackborn78c40512009-07-06 11:07:40 -07001487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 // Computed attribute bags, first indexed by the type and second
1489 // by the entry in that type.
1490 bag_set*** bags;
1491};
1492
1493struct ResTable::bag_set
1494{
1495 size_t numAttrs; // number in array
1496 size_t availAttrs; // total space in array
1497 uint32_t typeSpecFlags;
1498 // Followed by 'numAttr' bag_entry structures.
1499};
1500
1501ResTable::Theme::Theme(const ResTable& table)
1502 : mTable(table)
1503{
1504 memset(mPackages, 0, sizeof(mPackages));
1505}
1506
1507ResTable::Theme::~Theme()
1508{
1509 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
1510 package_info* pi = mPackages[i];
1511 if (pi != NULL) {
1512 free_package(pi);
1513 }
1514 }
1515}
1516
1517void ResTable::Theme::free_package(package_info* pi)
1518{
1519 for (size_t j=0; j<pi->numTypes; j++) {
1520 theme_entry* te = pi->types[j].entries;
1521 if (te != NULL) {
1522 free(te);
1523 }
1524 }
1525 free(pi);
1526}
1527
1528ResTable::Theme::package_info* ResTable::Theme::copy_package(package_info* pi)
1529{
1530 package_info* newpi = (package_info*)malloc(
1531 sizeof(package_info) + (pi->numTypes*sizeof(type_info)));
1532 newpi->numTypes = pi->numTypes;
1533 for (size_t j=0; j<newpi->numTypes; j++) {
1534 size_t cnt = pi->types[j].numEntries;
1535 newpi->types[j].numEntries = cnt;
1536 theme_entry* te = pi->types[j].entries;
1537 if (te != NULL) {
1538 theme_entry* newte = (theme_entry*)malloc(cnt*sizeof(theme_entry));
1539 newpi->types[j].entries = newte;
1540 memcpy(newte, te, cnt*sizeof(theme_entry));
1541 } else {
1542 newpi->types[j].entries = NULL;
1543 }
1544 }
1545 return newpi;
1546}
1547
1548status_t ResTable::Theme::applyStyle(uint32_t resID, bool force)
1549{
1550 const bag_entry* bag;
1551 uint32_t bagTypeSpecFlags = 0;
1552 mTable.lock();
1553 const ssize_t N = mTable.getBagLocked(resID, &bag, &bagTypeSpecFlags);
1554 TABLE_NOISY(LOGV("Applying style 0x%08x to theme %p, count=%d", resID, this, N));
1555 if (N < 0) {
1556 mTable.unlock();
1557 return N;
1558 }
1559
1560 uint32_t curPackage = 0xffffffff;
1561 ssize_t curPackageIndex = 0;
1562 package_info* curPI = NULL;
1563 uint32_t curType = 0xffffffff;
1564 size_t numEntries = 0;
1565 theme_entry* curEntries = NULL;
1566
1567 const bag_entry* end = bag + N;
1568 while (bag < end) {
1569 const uint32_t attrRes = bag->map.name.ident;
1570 const uint32_t p = Res_GETPACKAGE(attrRes);
1571 const uint32_t t = Res_GETTYPE(attrRes);
1572 const uint32_t e = Res_GETENTRY(attrRes);
1573
1574 if (curPackage != p) {
1575 const ssize_t pidx = mTable.getResourcePackageIndex(attrRes);
1576 if (pidx < 0) {
1577 LOGE("Style contains key with bad package: 0x%08x\n", attrRes);
1578 bag++;
1579 continue;
1580 }
1581 curPackage = p;
1582 curPackageIndex = pidx;
1583 curPI = mPackages[pidx];
1584 if (curPI == NULL) {
1585 PackageGroup* const grp = mTable.mPackageGroups[pidx];
1586 int cnt = grp->typeCount;
1587 curPI = (package_info*)malloc(
1588 sizeof(package_info) + (cnt*sizeof(type_info)));
1589 curPI->numTypes = cnt;
1590 memset(curPI->types, 0, cnt*sizeof(type_info));
1591 mPackages[pidx] = curPI;
1592 }
1593 curType = 0xffffffff;
1594 }
1595 if (curType != t) {
1596 if (t >= curPI->numTypes) {
1597 LOGE("Style contains key with bad type: 0x%08x\n", attrRes);
1598 bag++;
1599 continue;
1600 }
1601 curType = t;
1602 curEntries = curPI->types[t].entries;
1603 if (curEntries == NULL) {
1604 PackageGroup* const grp = mTable.mPackageGroups[curPackageIndex];
1605 const Type* type = grp->packages[0]->getType(t);
1606 int cnt = type != NULL ? type->entryCount : 0;
1607 curEntries = (theme_entry*)malloc(cnt*sizeof(theme_entry));
1608 memset(curEntries, Res_value::TYPE_NULL, cnt*sizeof(theme_entry));
1609 curPI->types[t].numEntries = cnt;
1610 curPI->types[t].entries = curEntries;
1611 }
1612 numEntries = curPI->types[t].numEntries;
1613 }
1614 if (e >= numEntries) {
1615 LOGE("Style contains key with bad entry: 0x%08x\n", attrRes);
1616 bag++;
1617 continue;
1618 }
1619 theme_entry* curEntry = curEntries + e;
1620 TABLE_NOISY(LOGV("Attr 0x%08x: type=0x%x, data=0x%08x; curType=0x%x",
1621 attrRes, bag->map.value.dataType, bag->map.value.data,
1622 curEntry->value.dataType));
1623 if (force || curEntry->value.dataType == Res_value::TYPE_NULL) {
1624 curEntry->stringBlock = bag->stringBlock;
1625 curEntry->typeSpecFlags |= bagTypeSpecFlags;
1626 curEntry->value = bag->map.value;
1627 }
1628
1629 bag++;
1630 }
1631
1632 mTable.unlock();
1633
Steve Block6215d3f2012-01-04 20:05:49 +00001634 //ALOGI("Applying style 0x%08x (force=%d) theme %p...\n", resID, force, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 //dumpToLog();
1636
1637 return NO_ERROR;
1638}
1639
1640status_t ResTable::Theme::setTo(const Theme& other)
1641{
Steve Block6215d3f2012-01-04 20:05:49 +00001642 //ALOGI("Setting theme %p from theme %p...\n", this, &other);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 //dumpToLog();
1644 //other.dumpToLog();
1645
1646 if (&mTable == &other.mTable) {
1647 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
1648 if (mPackages[i] != NULL) {
1649 free_package(mPackages[i]);
1650 }
1651 if (other.mPackages[i] != NULL) {
1652 mPackages[i] = copy_package(other.mPackages[i]);
1653 } else {
1654 mPackages[i] = NULL;
1655 }
1656 }
1657 } else {
1658 // @todo: need to really implement this, not just copy
1659 // the system package (which is still wrong because it isn't
1660 // fixing up resource references).
1661 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
1662 if (mPackages[i] != NULL) {
1663 free_package(mPackages[i]);
1664 }
1665 if (i == 0 && other.mPackages[i] != NULL) {
1666 mPackages[i] = copy_package(other.mPackages[i]);
1667 } else {
1668 mPackages[i] = NULL;
1669 }
1670 }
1671 }
1672
Steve Block6215d3f2012-01-04 20:05:49 +00001673 //ALOGI("Final theme:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 //dumpToLog();
1675
1676 return NO_ERROR;
1677}
1678
1679ssize_t ResTable::Theme::getAttribute(uint32_t resID, Res_value* outValue,
1680 uint32_t* outTypeSpecFlags) const
1681{
1682 int cnt = 20;
1683
1684 if (outTypeSpecFlags != NULL) *outTypeSpecFlags = 0;
1685
1686 do {
1687 const ssize_t p = mTable.getResourcePackageIndex(resID);
1688 const uint32_t t = Res_GETTYPE(resID);
1689 const uint32_t e = Res_GETENTRY(resID);
1690
Dianne Hackbornb8d81672009-11-20 14:26:42 -08001691 TABLE_THEME(LOGI("Looking up attr 0x%08x in theme %p", resID, this));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692
1693 if (p >= 0) {
1694 const package_info* const pi = mPackages[p];
Dianne Hackbornb8d81672009-11-20 14:26:42 -08001695 TABLE_THEME(LOGI("Found package: %p", pi));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 if (pi != NULL) {
Dianne Hackbornb8d81672009-11-20 14:26:42 -08001697 TABLE_THEME(LOGI("Desired type index is %ld in avail %d", t, pi->numTypes));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 if (t < pi->numTypes) {
1699 const type_info& ti = pi->types[t];
Dianne Hackbornb8d81672009-11-20 14:26:42 -08001700 TABLE_THEME(LOGI("Desired entry index is %ld in avail %d", e, ti.numEntries));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 if (e < ti.numEntries) {
1702 const theme_entry& te = ti.entries[e];
Dianne Hackbornb8d81672009-11-20 14:26:42 -08001703 if (outTypeSpecFlags != NULL) {
1704 *outTypeSpecFlags |= te.typeSpecFlags;
1705 }
1706 TABLE_THEME(LOGI("Theme value: type=0x%x, data=0x%08x",
1707 te.value.dataType, te.value.data));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 const uint8_t type = te.value.dataType;
1709 if (type == Res_value::TYPE_ATTRIBUTE) {
1710 if (cnt > 0) {
1711 cnt--;
1712 resID = te.value.data;
1713 continue;
1714 }
1715 LOGW("Too many attribute references, stopped at: 0x%08x\n", resID);
1716 return BAD_INDEX;
1717 } else if (type != Res_value::TYPE_NULL) {
1718 *outValue = te.value;
1719 return te.stringBlock;
1720 }
1721 return BAD_INDEX;
1722 }
1723 }
1724 }
1725 }
1726 break;
1727
1728 } while (true);
1729
1730 return BAD_INDEX;
1731}
1732
1733ssize_t ResTable::Theme::resolveAttributeReference(Res_value* inOutValue,
1734 ssize_t blockIndex, uint32_t* outLastRef,
Dianne Hackborn0d221012009-07-29 15:41:19 -07001735 uint32_t* inoutTypeSpecFlags, ResTable_config* inoutConfig) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736{
1737 //printf("Resolving type=0x%x\n", inOutValue->dataType);
1738 if (inOutValue->dataType == Res_value::TYPE_ATTRIBUTE) {
1739 uint32_t newTypeSpecFlags;
1740 blockIndex = getAttribute(inOutValue->data, inOutValue, &newTypeSpecFlags);
Dianne Hackbornb8d81672009-11-20 14:26:42 -08001741 TABLE_THEME(LOGI("Resolving attr reference: blockIndex=%d, type=0x%x, data=%p\n",
1742 (int)blockIndex, (int)inOutValue->dataType, (void*)inOutValue->data));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newTypeSpecFlags;
1744 //printf("Retrieved attribute new type=0x%x\n", inOutValue->dataType);
1745 if (blockIndex < 0) {
1746 return blockIndex;
1747 }
1748 }
Dianne Hackborn0d221012009-07-29 15:41:19 -07001749 return mTable.resolveReference(inOutValue, blockIndex, outLastRef,
1750 inoutTypeSpecFlags, inoutConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751}
1752
1753void ResTable::Theme::dumpToLog() const
1754{
Steve Block6215d3f2012-01-04 20:05:49 +00001755 ALOGI("Theme %p:\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
1757 package_info* pi = mPackages[i];
1758 if (pi == NULL) continue;
1759
Steve Block6215d3f2012-01-04 20:05:49 +00001760 ALOGI(" Package #0x%02x:\n", (int)(i+1));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 for (size_t j=0; j<pi->numTypes; j++) {
1762 type_info& ti = pi->types[j];
1763 if (ti.numEntries == 0) continue;
1764
Steve Block6215d3f2012-01-04 20:05:49 +00001765 ALOGI(" Type #0x%02x:\n", (int)(j+1));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 for (size_t k=0; k<ti.numEntries; k++) {
1767 theme_entry& te = ti.entries[k];
1768 if (te.value.dataType == Res_value::TYPE_NULL) continue;
Steve Block6215d3f2012-01-04 20:05:49 +00001769 ALOGI(" 0x%08x: t=0x%x, d=0x%08x (block=%d)\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 (int)Res_MAKEID(i, j, k),
1771 te.value.dataType, (int)te.value.data, (int)te.stringBlock);
1772 }
1773 }
1774 }
1775}
1776
1777ResTable::ResTable()
1778 : mError(NO_INIT)
1779{
1780 memset(&mParams, 0, sizeof(mParams));
1781 memset(mPackageMap, 0, sizeof(mPackageMap));
Steve Block6215d3f2012-01-04 20:05:49 +00001782 //ALOGI("Creating ResTable %p\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783}
1784
1785ResTable::ResTable(const void* data, size_t size, void* cookie, bool copyData)
1786 : mError(NO_INIT)
1787{
1788 memset(&mParams, 0, sizeof(mParams));
1789 memset(mPackageMap, 0, sizeof(mPackageMap));
1790 add(data, size, cookie, copyData);
1791 LOG_FATAL_IF(mError != NO_ERROR, "Error parsing resource table");
Steve Block6215d3f2012-01-04 20:05:49 +00001792 //ALOGI("Creating ResTable %p\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793}
1794
1795ResTable::~ResTable()
1796{
Steve Block6215d3f2012-01-04 20:05:49 +00001797 //ALOGI("Destroying ResTable in %p\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 uninit();
1799}
1800
1801inline ssize_t ResTable::getResourcePackageIndex(uint32_t resID) const
1802{
1803 return ((ssize_t)mPackageMap[Res_GETPACKAGE(resID)+1])-1;
1804}
1805
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01001806status_t ResTable::add(const void* data, size_t size, void* cookie, bool copyData,
1807 const void* idmap)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808{
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01001809 return add(data, size, cookie, NULL, copyData, reinterpret_cast<const Asset*>(idmap));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810}
1811
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01001812status_t ResTable::add(Asset* asset, void* cookie, bool copyData, const void* idmap)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813{
1814 const void* data = asset->getBuffer(true);
1815 if (data == NULL) {
1816 LOGW("Unable to get buffer of resource asset file");
1817 return UNKNOWN_ERROR;
1818 }
1819 size_t size = (size_t)asset->getLength();
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01001820 return add(data, size, cookie, asset, copyData, reinterpret_cast<const Asset*>(idmap));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821}
1822
Dianne Hackborn78c40512009-07-06 11:07:40 -07001823status_t ResTable::add(ResTable* src)
1824{
1825 mError = src->mError;
Dianne Hackborn78c40512009-07-06 11:07:40 -07001826
1827 for (size_t i=0; i<src->mHeaders.size(); i++) {
1828 mHeaders.add(src->mHeaders[i]);
1829 }
1830
1831 for (size_t i=0; i<src->mPackageGroups.size(); i++) {
1832 PackageGroup* srcPg = src->mPackageGroups[i];
1833 PackageGroup* pg = new PackageGroup(this, srcPg->name, srcPg->id);
1834 for (size_t j=0; j<srcPg->packages.size(); j++) {
1835 pg->packages.add(srcPg->packages[j]);
1836 }
1837 pg->basePackage = srcPg->basePackage;
1838 pg->typeCount = srcPg->typeCount;
1839 mPackageGroups.add(pg);
1840 }
1841
1842 memcpy(mPackageMap, src->mPackageMap, sizeof(mPackageMap));
1843
1844 return mError;
1845}
1846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001847status_t ResTable::add(const void* data, size_t size, void* cookie,
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01001848 Asset* asset, bool copyData, const Asset* idmap)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849{
1850 if (!data) return NO_ERROR;
Dianne Hackborn78c40512009-07-06 11:07:40 -07001851 Header* header = new Header(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 header->index = mHeaders.size();
1853 header->cookie = cookie;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01001854 if (idmap != NULL) {
1855 const size_t idmap_size = idmap->getLength();
1856 const void* idmap_data = const_cast<Asset*>(idmap)->getBuffer(true);
1857 header->resourceIDMap = (uint32_t*)malloc(idmap_size);
1858 if (header->resourceIDMap == NULL) {
1859 delete header;
1860 return (mError = NO_MEMORY);
1861 }
1862 memcpy((void*)header->resourceIDMap, idmap_data, idmap_size);
1863 header->resourceIDMapSize = idmap_size;
1864 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 mHeaders.add(header);
1866
1867 const bool notDeviceEndian = htods(0xf0) != 0xf0;
1868
1869 LOAD_TABLE_NOISY(
Steve Block71f2cf12011-10-20 11:56:00 +01001870 ALOGV("Adding resources to ResTable: data=%p, size=0x%x, cookie=%p, asset=%p, copy=%d "
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01001871 "idmap=%p\n", data, size, cookie, asset, copyData, idmap));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872
1873 if (copyData || notDeviceEndian) {
1874 header->ownedData = malloc(size);
1875 if (header->ownedData == NULL) {
1876 return (mError=NO_MEMORY);
1877 }
1878 memcpy(header->ownedData, data, size);
1879 data = header->ownedData;
1880 }
1881
1882 header->header = (const ResTable_header*)data;
1883 header->size = dtohl(header->header->header.size);
Steve Block6215d3f2012-01-04 20:05:49 +00001884 //ALOGI("Got size 0x%x, again size 0x%x, raw size 0x%x\n", header->size,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 // dtohl(header->header->header.size), header->header->header.size);
1886 LOAD_TABLE_NOISY(LOGV("Loading ResTable @%p:\n", header->header));
1887 LOAD_TABLE_NOISY(printHexData(2, header->header, header->size < 256 ? header->size : 256,
1888 16, 16, 0, false, printToLogFunc));
1889 if (dtohs(header->header->header.headerSize) > header->size
1890 || header->size > size) {
1891 LOGW("Bad resource table: header size 0x%x or total size 0x%x is larger than data size 0x%x\n",
1892 (int)dtohs(header->header->header.headerSize),
1893 (int)header->size, (int)size);
1894 return (mError=BAD_TYPE);
1895 }
1896 if (((dtohs(header->header->header.headerSize)|header->size)&0x3) != 0) {
1897 LOGW("Bad resource table: header size 0x%x or total size 0x%x is not on an integer boundary\n",
1898 (int)dtohs(header->header->header.headerSize),
1899 (int)header->size);
1900 return (mError=BAD_TYPE);
1901 }
1902 header->dataEnd = ((const uint8_t*)header->header) + header->size;
1903
1904 // Iterate through all chunks.
1905 size_t curPackage = 0;
1906
1907 const ResChunk_header* chunk =
1908 (const ResChunk_header*)(((const uint8_t*)header->header)
1909 + dtohs(header->header->header.headerSize));
1910 while (((const uint8_t*)chunk) <= (header->dataEnd-sizeof(ResChunk_header)) &&
1911 ((const uint8_t*)chunk) <= (header->dataEnd-dtohl(chunk->size))) {
1912 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), header->dataEnd, "ResTable");
1913 if (err != NO_ERROR) {
1914 return (mError=err);
1915 }
1916 TABLE_NOISY(LOGV("Chunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n",
1917 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
1918 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header))));
1919 const size_t csize = dtohl(chunk->size);
1920 const uint16_t ctype = dtohs(chunk->type);
1921 if (ctype == RES_STRING_POOL_TYPE) {
1922 if (header->values.getError() != NO_ERROR) {
1923 // Only use the first string chunk; ignore any others that
1924 // may appear.
1925 status_t err = header->values.setTo(chunk, csize);
1926 if (err != NO_ERROR) {
1927 return (mError=err);
1928 }
1929 } else {
1930 LOGW("Multiple string chunks found in resource table.");
1931 }
1932 } else if (ctype == RES_TABLE_PACKAGE_TYPE) {
1933 if (curPackage >= dtohl(header->header->packageCount)) {
1934 LOGW("More package chunks were found than the %d declared in the header.",
1935 dtohl(header->header->packageCount));
1936 return (mError=BAD_TYPE);
1937 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01001938 uint32_t idmap_id = 0;
1939 if (idmap != NULL) {
1940 uint32_t tmp;
1941 if (getIdmapPackageId(header->resourceIDMap,
1942 header->resourceIDMapSize,
1943 &tmp) == NO_ERROR) {
1944 idmap_id = tmp;
1945 }
1946 }
1947 if (parsePackage((ResTable_package*)chunk, header, idmap_id) != NO_ERROR) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 return mError;
1949 }
1950 curPackage++;
1951 } else {
1952 LOGW("Unknown chunk type %p in table at %p.\n",
1953 (void*)(int)(ctype),
1954 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)));
1955 }
1956 chunk = (const ResChunk_header*)
1957 (((const uint8_t*)chunk) + csize);
1958 }
1959
1960 if (curPackage < dtohl(header->header->packageCount)) {
1961 LOGW("Fewer package chunks (%d) were found than the %d declared in the header.",
1962 (int)curPackage, dtohl(header->header->packageCount));
1963 return (mError=BAD_TYPE);
1964 }
1965 mError = header->values.getError();
1966 if (mError != NO_ERROR) {
1967 LOGW("No string values found in resource table!");
1968 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01001969
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 TABLE_NOISY(LOGV("Returning from add with mError=%d\n", mError));
1971 return mError;
1972}
1973
1974status_t ResTable::getError() const
1975{
1976 return mError;
1977}
1978
1979void ResTable::uninit()
1980{
1981 mError = NO_INIT;
1982 size_t N = mPackageGroups.size();
1983 for (size_t i=0; i<N; i++) {
1984 PackageGroup* g = mPackageGroups[i];
1985 delete g;
1986 }
1987 N = mHeaders.size();
1988 for (size_t i=0; i<N; i++) {
1989 Header* header = mHeaders[i];
Dianne Hackborn78c40512009-07-06 11:07:40 -07001990 if (header->owner == this) {
1991 if (header->ownedData) {
1992 free(header->ownedData);
1993 }
1994 delete header;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 }
1997
1998 mPackageGroups.clear();
1999 mHeaders.clear();
2000}
2001
2002bool ResTable::getResourceName(uint32_t resID, resource_name* outName) const
2003{
2004 if (mError != NO_ERROR) {
2005 return false;
2006 }
2007
2008 const ssize_t p = getResourcePackageIndex(resID);
2009 const int t = Res_GETTYPE(resID);
2010 const int e = Res_GETENTRY(resID);
2011
2012 if (p < 0) {
Dianne Hackborn6cca1592009-09-20 12:40:03 -07002013 if (Res_GETPACKAGE(resID)+1 == 0) {
2014 LOGW("No package identifier when getting name for resource number 0x%08x", resID);
2015 } else {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08002016 LOGW("No known package when getting name for resource number 0x%08x", resID);
Dianne Hackborn6cca1592009-09-20 12:40:03 -07002017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002018 return false;
2019 }
2020 if (t < 0) {
2021 LOGW("No type identifier when getting name for resource number 0x%08x", resID);
2022 return false;
2023 }
2024
2025 const PackageGroup* const grp = mPackageGroups[p];
2026 if (grp == NULL) {
2027 LOGW("Bad identifier when getting name for resource number 0x%08x", resID);
2028 return false;
2029 }
2030 if (grp->packages.size() > 0) {
2031 const Package* const package = grp->packages[0];
2032
2033 const ResTable_type* type;
2034 const ResTable_entry* entry;
2035 ssize_t offset = getEntry(package, t, e, NULL, &type, &entry, NULL);
2036 if (offset <= 0) {
2037 return false;
2038 }
2039
2040 outName->package = grp->name.string();
2041 outName->packageLen = grp->name.size();
Dianne Hackborn78c40512009-07-06 11:07:40 -07002042 outName->type = grp->basePackage->typeStrings.stringAt(t, &outName->typeLen);
2043 outName->name = grp->basePackage->keyStrings.stringAt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 dtohl(entry->key.index), &outName->nameLen);
Kenny Root33791952010-06-08 10:16:48 -07002045
2046 // If we have a bad index for some reason, we should abort.
2047 if (outName->type == NULL || outName->name == NULL) {
2048 return false;
2049 }
2050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 return true;
2052 }
2053
2054 return false;
2055}
2056
Kenny Root55fc8502010-10-28 14:47:01 -07002057ssize_t ResTable::getResource(uint32_t resID, Res_value* outValue, bool mayBeBag, uint16_t density,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 uint32_t* outSpecFlags, ResTable_config* outConfig) const
2059{
2060 if (mError != NO_ERROR) {
2061 return mError;
2062 }
2063
2064 const ssize_t p = getResourcePackageIndex(resID);
2065 const int t = Res_GETTYPE(resID);
2066 const int e = Res_GETENTRY(resID);
2067
2068 if (p < 0) {
Dianne Hackborn6cca1592009-09-20 12:40:03 -07002069 if (Res_GETPACKAGE(resID)+1 == 0) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08002070 LOGW("No package identifier when getting value for resource number 0x%08x", resID);
Dianne Hackborn6cca1592009-09-20 12:40:03 -07002071 } else {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08002072 LOGW("No known package when getting value for resource number 0x%08x", resID);
Dianne Hackborn6cca1592009-09-20 12:40:03 -07002073 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002074 return BAD_INDEX;
2075 }
2076 if (t < 0) {
2077 LOGW("No type identifier when getting value for resource number 0x%08x", resID);
2078 return BAD_INDEX;
2079 }
2080
2081 const Res_value* bestValue = NULL;
2082 const Package* bestPackage = NULL;
2083 ResTable_config bestItem;
2084 memset(&bestItem, 0, sizeof(bestItem)); // make the compiler shut up
2085
2086 if (outSpecFlags != NULL) *outSpecFlags = 0;
Kenny Root55fc8502010-10-28 14:47:01 -07002087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 // Look through all resource packages, starting with the most
2089 // recently added.
2090 const PackageGroup* const grp = mPackageGroups[p];
2091 if (grp == NULL) {
2092 LOGW("Bad identifier when getting value for resource number 0x%08x", resID);
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08002093 return BAD_INDEX;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002094 }
Kenny Root55fc8502010-10-28 14:47:01 -07002095
2096 // Allow overriding density
2097 const ResTable_config* desiredConfig = &mParams;
2098 ResTable_config* overrideConfig = NULL;
2099 if (density > 0) {
2100 overrideConfig = (ResTable_config*) malloc(sizeof(ResTable_config));
2101 if (overrideConfig == NULL) {
2102 LOGE("Couldn't malloc ResTable_config for overrides: %s", strerror(errno));
2103 return BAD_INDEX;
2104 }
2105 memcpy(overrideConfig, &mParams, sizeof(ResTable_config));
2106 overrideConfig->density = density;
2107 desiredConfig = overrideConfig;
2108 }
2109
Kenny Root5c4cf8c2010-11-02 11:27:21 -07002110 ssize_t rc = BAD_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 size_t ip = grp->packages.size();
2112 while (ip > 0) {
2113 ip--;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01002114 int T = t;
2115 int E = e;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002116
2117 const Package* const package = grp->packages[ip];
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01002118 if (package->header->resourceIDMap) {
2119 uint32_t overlayResID = 0x0;
2120 status_t retval = idmapLookup(package->header->resourceIDMap,
2121 package->header->resourceIDMapSize,
2122 resID, &overlayResID);
2123 if (retval == NO_ERROR && overlayResID != 0x0) {
2124 // for this loop iteration, this is the type and entry we really want
Steve Block71f2cf12011-10-20 11:56:00 +01002125 ALOGV("resource map 0x%08x -> 0x%08x\n", resID, overlayResID);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01002126 T = Res_GETTYPE(overlayResID);
2127 E = Res_GETENTRY(overlayResID);
2128 } else {
2129 // resource not present in overlay package, continue with the next package
2130 continue;
2131 }
2132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002133
2134 const ResTable_type* type;
2135 const ResTable_entry* entry;
2136 const Type* typeClass;
Kenny Root18490fb2011-04-12 10:27:15 -07002137 ssize_t offset = getEntry(package, T, E, desiredConfig, &type, &entry, &typeClass);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002138 if (offset <= 0) {
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01002139 // No {entry, appropriate config} pair found in package. If this
2140 // package is an overlay package (ip != 0), this simply means the
2141 // overlay package did not specify a default.
2142 // Non-overlay packages are still required to provide a default.
2143 if (offset < 0 && ip == 0) {
Kenny Root68c2e912010-09-02 14:58:47 -07002144 LOGW("Failure getting entry for 0x%08x (t=%d e=%d) in package %zd (error %d)\n",
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01002145 resID, T, E, ip, (int)offset);
Kenny Root55fc8502010-10-28 14:47:01 -07002146 rc = offset;
2147 goto out;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002148 }
2149 continue;
2150 }
2151
2152 if ((dtohs(entry->flags)&entry->FLAG_COMPLEX) != 0) {
2153 if (!mayBeBag) {
2154 LOGW("Requesting resource %p failed because it is complex\n",
2155 (void*)resID);
2156 }
2157 continue;
2158 }
2159
2160 TABLE_NOISY(aout << "Resource type data: "
2161 << HexDump(type, dtohl(type->header.size)) << endl);
Kenny Root55fc8502010-10-28 14:47:01 -07002162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002163 if ((size_t)offset > (dtohl(type->header.size)-sizeof(Res_value))) {
2164 LOGW("ResTable_item at %d is beyond type chunk data %d",
2165 (int)offset, dtohl(type->header.size));
Kenny Root55fc8502010-10-28 14:47:01 -07002166 rc = BAD_TYPE;
2167 goto out;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002168 }
Kenny Root55fc8502010-10-28 14:47:01 -07002169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002170 const Res_value* item =
2171 (const Res_value*)(((const uint8_t*)type) + offset);
2172 ResTable_config thisConfig;
2173 thisConfig.copyFromDtoH(type->config);
2174
2175 if (outSpecFlags != NULL) {
2176 if (typeClass->typeSpecFlags != NULL) {
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01002177 *outSpecFlags |= dtohl(typeClass->typeSpecFlags[E]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002178 } else {
2179 *outSpecFlags = -1;
2180 }
2181 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01002182
2183 if (bestPackage != NULL &&
2184 (bestItem.isMoreSpecificThan(thisConfig) || bestItem.diff(thisConfig) == 0)) {
2185 // Discard thisConfig not only if bestItem is more specific, but also if the two configs
2186 // are identical (diff == 0), or overlay packages will not take effect.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002187 continue;
2188 }
2189
2190 bestItem = thisConfig;
2191 bestValue = item;
2192 bestPackage = package;
2193 }
2194
2195 TABLE_NOISY(printf("Found result: package %p\n", bestPackage));
2196
2197 if (bestValue) {
2198 outValue->size = dtohs(bestValue->size);
2199 outValue->res0 = bestValue->res0;
2200 outValue->dataType = bestValue->dataType;
2201 outValue->data = dtohl(bestValue->data);
2202 if (outConfig != NULL) {
2203 *outConfig = bestItem;
2204 }
2205 TABLE_NOISY(size_t len;
2206 printf("Found value: pkg=%d, type=%d, str=%s, int=%d\n",
2207 bestPackage->header->index,
2208 outValue->dataType,
2209 outValue->dataType == bestValue->TYPE_STRING
2210 ? String8(bestPackage->header->values.stringAt(
2211 outValue->data, &len)).string()
2212 : "",
2213 outValue->data));
Kenny Root55fc8502010-10-28 14:47:01 -07002214 rc = bestPackage->header->index;
2215 goto out;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002216 }
2217
Kenny Root55fc8502010-10-28 14:47:01 -07002218out:
2219 if (overrideConfig != NULL) {
2220 free(overrideConfig);
2221 }
2222
2223 return rc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002224}
2225
2226ssize_t ResTable::resolveReference(Res_value* value, ssize_t blockIndex,
Dianne Hackborn0d221012009-07-29 15:41:19 -07002227 uint32_t* outLastRef, uint32_t* inoutTypeSpecFlags,
2228 ResTable_config* outConfig) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002229{
2230 int count=0;
2231 while (blockIndex >= 0 && value->dataType == value->TYPE_REFERENCE
2232 && value->data != 0 && count < 20) {
2233 if (outLastRef) *outLastRef = value->data;
2234 uint32_t lastRef = value->data;
2235 uint32_t newFlags = 0;
Kenny Root55fc8502010-10-28 14:47:01 -07002236 const ssize_t newIndex = getResource(value->data, value, true, 0, &newFlags,
Dianne Hackborn0d221012009-07-29 15:41:19 -07002237 outConfig);
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08002238 if (newIndex == BAD_INDEX) {
2239 return BAD_INDEX;
2240 }
Dianne Hackbornb8d81672009-11-20 14:26:42 -08002241 TABLE_THEME(LOGI("Resolving reference %p: newIndex=%d, type=0x%x, data=%p\n",
2242 (void*)lastRef, (int)newIndex, (int)value->dataType, (void*)value->data));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002243 //printf("Getting reference 0x%08x: newIndex=%d\n", value->data, newIndex);
2244 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newFlags;
2245 if (newIndex < 0) {
2246 // This can fail if the resource being referenced is a style...
2247 // in this case, just return the reference, and expect the
2248 // caller to deal with.
2249 return blockIndex;
2250 }
2251 blockIndex = newIndex;
2252 count++;
2253 }
2254 return blockIndex;
2255}
2256
2257const char16_t* ResTable::valueToString(
2258 const Res_value* value, size_t stringBlock,
2259 char16_t tmpBuffer[TMP_BUFFER_SIZE], size_t* outLen)
2260{
2261 if (!value) {
2262 return NULL;
2263 }
2264 if (value->dataType == value->TYPE_STRING) {
2265 return getTableStringBlock(stringBlock)->stringAt(value->data, outLen);
2266 }
2267 // XXX do int to string conversions.
2268 return NULL;
2269}
2270
2271ssize_t ResTable::lockBag(uint32_t resID, const bag_entry** outBag) const
2272{
2273 mLock.lock();
2274 ssize_t err = getBagLocked(resID, outBag);
2275 if (err < NO_ERROR) {
2276 //printf("*** get failed! unlocking\n");
2277 mLock.unlock();
2278 }
2279 return err;
2280}
2281
2282void ResTable::unlockBag(const bag_entry* bag) const
2283{
2284 //printf("<<< unlockBag %p\n", this);
2285 mLock.unlock();
2286}
2287
2288void ResTable::lock() const
2289{
2290 mLock.lock();
2291}
2292
2293void ResTable::unlock() const
2294{
2295 mLock.unlock();
2296}
2297
2298ssize_t ResTable::getBagLocked(uint32_t resID, const bag_entry** outBag,
2299 uint32_t* outTypeSpecFlags) const
2300{
2301 if (mError != NO_ERROR) {
2302 return mError;
2303 }
2304
2305 const ssize_t p = getResourcePackageIndex(resID);
2306 const int t = Res_GETTYPE(resID);
2307 const int e = Res_GETENTRY(resID);
2308
2309 if (p < 0) {
2310 LOGW("Invalid package identifier when getting bag for resource number 0x%08x", resID);
2311 return BAD_INDEX;
2312 }
2313 if (t < 0) {
2314 LOGW("No type identifier when getting bag for resource number 0x%08x", resID);
2315 return BAD_INDEX;
2316 }
2317
2318 //printf("Get bag: id=0x%08x, p=%d, t=%d\n", resID, p, t);
2319 PackageGroup* const grp = mPackageGroups[p];
2320 if (grp == NULL) {
2321 LOGW("Bad identifier when getting bag for resource number 0x%08x", resID);
2322 return false;
2323 }
2324
2325 if (t >= (int)grp->typeCount) {
2326 LOGW("Type identifier 0x%x is larger than type count 0x%x",
2327 t+1, (int)grp->typeCount);
2328 return BAD_INDEX;
2329 }
2330
2331 const Package* const basePackage = grp->packages[0];
2332
2333 const Type* const typeConfigs = basePackage->getType(t);
2334
2335 const size_t NENTRY = typeConfigs->entryCount;
2336 if (e >= (int)NENTRY) {
2337 LOGW("Entry identifier 0x%x is larger than entry count 0x%x",
2338 e, (int)typeConfigs->entryCount);
2339 return BAD_INDEX;
2340 }
2341
2342 // First see if we've already computed this bag...
2343 if (grp->bags) {
2344 bag_set** typeSet = grp->bags[t];
2345 if (typeSet) {
2346 bag_set* set = typeSet[e];
2347 if (set) {
2348 if (set != (bag_set*)0xFFFFFFFF) {
2349 if (outTypeSpecFlags != NULL) {
2350 *outTypeSpecFlags = set->typeSpecFlags;
2351 }
2352 *outBag = (bag_entry*)(set+1);
Steve Block6215d3f2012-01-04 20:05:49 +00002353 //ALOGI("Found existing bag for: %p\n", (void*)resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002354 return set->numAttrs;
2355 }
2356 LOGW("Attempt to retrieve bag 0x%08x which is invalid or in a cycle.",
2357 resID);
2358 return BAD_INDEX;
2359 }
2360 }
2361 }
2362
2363 // Bag not found, we need to compute it!
2364 if (!grp->bags) {
2365 grp->bags = (bag_set***)malloc(sizeof(bag_set*)*grp->typeCount);
2366 if (!grp->bags) return NO_MEMORY;
2367 memset(grp->bags, 0, sizeof(bag_set*)*grp->typeCount);
2368 }
2369
2370 bag_set** typeSet = grp->bags[t];
2371 if (!typeSet) {
2372 typeSet = (bag_set**)malloc(sizeof(bag_set*)*NENTRY);
2373 if (!typeSet) return NO_MEMORY;
2374 memset(typeSet, 0, sizeof(bag_set*)*NENTRY);
2375 grp->bags[t] = typeSet;
2376 }
2377
2378 // Mark that we are currently working on this one.
2379 typeSet[e] = (bag_set*)0xFFFFFFFF;
2380
2381 // This is what we are building.
2382 bag_set* set = NULL;
2383
2384 TABLE_NOISY(LOGI("Building bag: %p\n", (void*)resID));
2385
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01002386 ResTable_config bestConfig;
2387 memset(&bestConfig, 0, sizeof(bestConfig));
2388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002389 // Now collect all bag attributes from all packages.
2390 size_t ip = grp->packages.size();
2391 while (ip > 0) {
2392 ip--;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01002393 int T = t;
2394 int E = e;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002395
2396 const Package* const package = grp->packages[ip];
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01002397 if (package->header->resourceIDMap) {
2398 uint32_t overlayResID = 0x0;
2399 status_t retval = idmapLookup(package->header->resourceIDMap,
2400 package->header->resourceIDMapSize,
2401 resID, &overlayResID);
2402 if (retval == NO_ERROR && overlayResID != 0x0) {
2403 // for this loop iteration, this is the type and entry we really want
Steve Block71f2cf12011-10-20 11:56:00 +01002404 ALOGV("resource map 0x%08x -> 0x%08x\n", resID, overlayResID);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01002405 T = Res_GETTYPE(overlayResID);
2406 E = Res_GETENTRY(overlayResID);
2407 } else {
2408 // resource not present in overlay package, continue with the next package
2409 continue;
2410 }
2411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002412
2413 const ResTable_type* type;
2414 const ResTable_entry* entry;
2415 const Type* typeClass;
Steve Block71f2cf12011-10-20 11:56:00 +01002416 ALOGV("Getting entry pkg=%p, t=%d, e=%d\n", package, T, E);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01002417 ssize_t offset = getEntry(package, T, E, &mParams, &type, &entry, &typeClass);
Steve Block71f2cf12011-10-20 11:56:00 +01002418 ALOGV("Resulting offset=%d\n", offset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002419 if (offset <= 0) {
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01002420 // No {entry, appropriate config} pair found in package. If this
2421 // package is an overlay package (ip != 0), this simply means the
2422 // overlay package did not specify a default.
2423 // Non-overlay packages are still required to provide a default.
2424 if (offset < 0 && ip == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002425 if (set) free(set);
2426 return offset;
2427 }
2428 continue;
2429 }
2430
2431 if ((dtohs(entry->flags)&entry->FLAG_COMPLEX) == 0) {
2432 LOGW("Skipping entry %p in package table %d because it is not complex!\n",
2433 (void*)resID, (int)ip);
2434 continue;
2435 }
2436
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01002437 if (set != NULL && !type->config.isBetterThan(bestConfig, NULL)) {
2438 continue;
2439 }
2440 bestConfig = type->config;
2441 if (set) {
2442 free(set);
2443 set = NULL;
2444 }
2445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446 const uint16_t entrySize = dtohs(entry->size);
2447 const uint32_t parent = entrySize >= sizeof(ResTable_map_entry)
2448 ? dtohl(((const ResTable_map_entry*)entry)->parent.ident) : 0;
2449 const uint32_t count = entrySize >= sizeof(ResTable_map_entry)
2450 ? dtohl(((const ResTable_map_entry*)entry)->count) : 0;
2451
2452 size_t N = count;
2453
2454 TABLE_NOISY(LOGI("Found map: size=%p parent=%p count=%d\n",
2455 entrySize, parent, count));
2456
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01002457 // If this map inherits from another, we need to start
2458 // with its parent's values. Otherwise start out empty.
2459 TABLE_NOISY(printf("Creating new bag, entrySize=0x%08x, parent=0x%08x\n",
2460 entrySize, parent));
2461 if (parent) {
2462 const bag_entry* parentBag;
2463 uint32_t parentTypeSpecFlags = 0;
2464 const ssize_t NP = getBagLocked(parent, &parentBag, &parentTypeSpecFlags);
2465 const size_t NT = ((NP >= 0) ? NP : 0) + N;
2466 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*NT);
2467 if (set == NULL) {
2468 return NO_MEMORY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002469 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01002470 if (NP > 0) {
2471 memcpy(set+1, parentBag, NP*sizeof(bag_entry));
2472 set->numAttrs = NP;
2473 TABLE_NOISY(LOGI("Initialized new bag with %d inherited attributes.\n", NP));
2474 } else {
2475 TABLE_NOISY(LOGI("Initialized new bag with no inherited attributes.\n"));
2476 set->numAttrs = 0;
2477 }
2478 set->availAttrs = NT;
2479 set->typeSpecFlags = parentTypeSpecFlags;
2480 } else {
2481 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*N);
2482 if (set == NULL) {
2483 return NO_MEMORY;
2484 }
2485 set->numAttrs = 0;
2486 set->availAttrs = N;
2487 set->typeSpecFlags = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 }
2489
2490 if (typeClass->typeSpecFlags != NULL) {
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01002491 set->typeSpecFlags |= dtohl(typeClass->typeSpecFlags[E]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 } else {
2493 set->typeSpecFlags = -1;
2494 }
2495
2496 // Now merge in the new attributes...
2497 ssize_t curOff = offset;
2498 const ResTable_map* map;
2499 bag_entry* entries = (bag_entry*)(set+1);
2500 size_t curEntry = 0;
2501 uint32_t pos = 0;
2502 TABLE_NOISY(LOGI("Starting with set %p, entries=%p, avail=%d\n",
2503 set, entries, set->availAttrs));
2504 while (pos < count) {
2505 TABLE_NOISY(printf("Now at %p\n", (void*)curOff));
2506
2507 if ((size_t)curOff > (dtohl(type->header.size)-sizeof(ResTable_map))) {
2508 LOGW("ResTable_map at %d is beyond type chunk data %d",
2509 (int)curOff, dtohl(type->header.size));
2510 return BAD_TYPE;
2511 }
2512 map = (const ResTable_map*)(((const uint8_t*)type) + curOff);
2513 N++;
2514
2515 const uint32_t newName = htodl(map->name.ident);
2516 bool isInside;
2517 uint32_t oldName = 0;
2518 while ((isInside=(curEntry < set->numAttrs))
2519 && (oldName=entries[curEntry].map.name.ident) < newName) {
2520 TABLE_NOISY(printf("#%d: Keeping existing attribute: 0x%08x\n",
2521 curEntry, entries[curEntry].map.name.ident));
2522 curEntry++;
2523 }
2524
2525 if ((!isInside) || oldName != newName) {
2526 // This is a new attribute... figure out what to do with it.
2527 if (set->numAttrs >= set->availAttrs) {
2528 // Need to alloc more memory...
2529 const size_t newAvail = set->availAttrs+N;
2530 set = (bag_set*)realloc(set,
2531 sizeof(bag_set)
2532 + sizeof(bag_entry)*newAvail);
2533 if (set == NULL) {
2534 return NO_MEMORY;
2535 }
2536 set->availAttrs = newAvail;
2537 entries = (bag_entry*)(set+1);
2538 TABLE_NOISY(printf("Reallocated set %p, entries=%p, avail=%d\n",
2539 set, entries, set->availAttrs));
2540 }
2541 if (isInside) {
2542 // Going in the middle, need to make space.
2543 memmove(entries+curEntry+1, entries+curEntry,
2544 sizeof(bag_entry)*(set->numAttrs-curEntry));
2545 set->numAttrs++;
2546 }
2547 TABLE_NOISY(printf("#%d: Inserting new attribute: 0x%08x\n",
2548 curEntry, newName));
2549 } else {
2550 TABLE_NOISY(printf("#%d: Replacing existing attribute: 0x%08x\n",
2551 curEntry, oldName));
2552 }
2553
2554 bag_entry* cur = entries+curEntry;
2555
2556 cur->stringBlock = package->header->index;
2557 cur->map.name.ident = newName;
2558 cur->map.value.copyFrom_dtoh(map->value);
2559 TABLE_NOISY(printf("Setting entry #%d %p: block=%d, name=0x%08x, type=%d, data=0x%08x\n",
2560 curEntry, cur, cur->stringBlock, cur->map.name.ident,
2561 cur->map.value.dataType, cur->map.value.data));
2562
2563 // On to the next!
2564 curEntry++;
2565 pos++;
2566 const size_t size = dtohs(map->value.size);
2567 curOff += size + sizeof(*map)-sizeof(map->value);
2568 };
2569 if (curEntry > set->numAttrs) {
2570 set->numAttrs = curEntry;
2571 }
2572 }
2573
2574 // And this is it...
2575 typeSet[e] = set;
2576 if (set) {
2577 if (outTypeSpecFlags != NULL) {
2578 *outTypeSpecFlags = set->typeSpecFlags;
2579 }
2580 *outBag = (bag_entry*)(set+1);
2581 TABLE_NOISY(LOGI("Returning %d attrs\n", set->numAttrs));
2582 return set->numAttrs;
2583 }
2584 return BAD_INDEX;
2585}
2586
2587void ResTable::setParameters(const ResTable_config* params)
2588{
2589 mLock.lock();
2590 TABLE_GETENTRY(LOGI("Setting parameters: imsi:%d/%d lang:%c%c cnt:%c%c "
Dianne Hackborn69cb8752011-05-19 18:13:32 -07002591 "orien:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d sw%ddp w%ddp h%ddp\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002592 params->mcc, params->mnc,
2593 params->language[0] ? params->language[0] : '-',
2594 params->language[1] ? params->language[1] : '-',
2595 params->country[0] ? params->country[0] : '-',
2596 params->country[1] ? params->country[1] : '-',
2597 params->orientation,
2598 params->touchscreen,
2599 params->density,
2600 params->keyboard,
2601 params->inputFlags,
2602 params->navigation,
2603 params->screenWidth,
Dianne Hackbornebff8f92011-05-12 18:07:47 -07002604 params->screenHeight,
Dianne Hackborn69cb8752011-05-19 18:13:32 -07002605 params->smallestScreenWidthDp,
Dianne Hackbornebff8f92011-05-12 18:07:47 -07002606 params->screenWidthDp,
2607 params->screenHeightDp));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 mParams = *params;
2609 for (size_t i=0; i<mPackageGroups.size(); i++) {
2610 TABLE_NOISY(LOGI("CLEARING BAGS FOR GROUP %d!", i));
2611 mPackageGroups[i]->clearBagCache();
2612 }
2613 mLock.unlock();
2614}
2615
2616void ResTable::getParameters(ResTable_config* params) const
2617{
2618 mLock.lock();
2619 *params = mParams;
2620 mLock.unlock();
2621}
2622
2623struct id_name_map {
2624 uint32_t id;
2625 size_t len;
2626 char16_t name[6];
2627};
2628
2629const static id_name_map ID_NAMES[] = {
2630 { ResTable_map::ATTR_TYPE, 5, { '^', 't', 'y', 'p', 'e' } },
2631 { ResTable_map::ATTR_L10N, 5, { '^', 'l', '1', '0', 'n' } },
2632 { ResTable_map::ATTR_MIN, 4, { '^', 'm', 'i', 'n' } },
2633 { ResTable_map::ATTR_MAX, 4, { '^', 'm', 'a', 'x' } },
2634 { ResTable_map::ATTR_OTHER, 6, { '^', 'o', 't', 'h', 'e', 'r' } },
2635 { ResTable_map::ATTR_ZERO, 5, { '^', 'z', 'e', 'r', 'o' } },
2636 { ResTable_map::ATTR_ONE, 4, { '^', 'o', 'n', 'e' } },
2637 { ResTable_map::ATTR_TWO, 4, { '^', 't', 'w', 'o' } },
2638 { ResTable_map::ATTR_FEW, 4, { '^', 'f', 'e', 'w' } },
2639 { ResTable_map::ATTR_MANY, 5, { '^', 'm', 'a', 'n', 'y' } },
2640};
2641
2642uint32_t ResTable::identifierForName(const char16_t* name, size_t nameLen,
2643 const char16_t* type, size_t typeLen,
2644 const char16_t* package,
2645 size_t packageLen,
2646 uint32_t* outTypeSpecFlags) const
2647{
2648 TABLE_SUPER_NOISY(printf("Identifier for name: error=%d\n", mError));
2649
2650 // Check for internal resource identifier as the very first thing, so
2651 // that we will always find them even when there are no resources.
2652 if (name[0] == '^') {
2653 const int N = (sizeof(ID_NAMES)/sizeof(ID_NAMES[0]));
2654 size_t len;
2655 for (int i=0; i<N; i++) {
2656 const id_name_map* m = ID_NAMES + i;
2657 len = m->len;
2658 if (len != nameLen) {
2659 continue;
2660 }
2661 for (size_t j=1; j<len; j++) {
2662 if (m->name[j] != name[j]) {
2663 goto nope;
2664 }
2665 }
Dianne Hackborn426431a2011-06-09 11:29:08 -07002666 if (outTypeSpecFlags) {
2667 *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC;
2668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002669 return m->id;
2670nope:
2671 ;
2672 }
2673 if (nameLen > 7) {
2674 if (name[1] == 'i' && name[2] == 'n'
2675 && name[3] == 'd' && name[4] == 'e' && name[5] == 'x'
2676 && name[6] == '_') {
2677 int index = atoi(String8(name + 7, nameLen - 7).string());
2678 if (Res_CHECKID(index)) {
2679 LOGW("Array resource index: %d is too large.",
2680 index);
2681 return 0;
2682 }
Dianne Hackborn426431a2011-06-09 11:29:08 -07002683 if (outTypeSpecFlags) {
2684 *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC;
2685 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 return Res_MAKEARRAY(index);
2687 }
2688 }
2689 return 0;
2690 }
2691
2692 if (mError != NO_ERROR) {
2693 return 0;
2694 }
2695
Dianne Hackborn426431a2011-06-09 11:29:08 -07002696 bool fakePublic = false;
2697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 // Figure out the package and type we are looking in...
2699
2700 const char16_t* packageEnd = NULL;
2701 const char16_t* typeEnd = NULL;
2702 const char16_t* const nameEnd = name+nameLen;
2703 const char16_t* p = name;
2704 while (p < nameEnd) {
2705 if (*p == ':') packageEnd = p;
2706 else if (*p == '/') typeEnd = p;
2707 p++;
2708 }
Dianne Hackborn426431a2011-06-09 11:29:08 -07002709 if (*name == '@') {
2710 name++;
2711 if (*name == '*') {
2712 fakePublic = true;
2713 name++;
2714 }
2715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 if (name >= nameEnd) {
2717 return 0;
2718 }
2719
2720 if (packageEnd) {
2721 package = name;
2722 packageLen = packageEnd-name;
2723 name = packageEnd+1;
2724 } else if (!package) {
2725 return 0;
2726 }
2727
2728 if (typeEnd) {
2729 type = name;
2730 typeLen = typeEnd-name;
2731 name = typeEnd+1;
2732 } else if (!type) {
2733 return 0;
2734 }
2735
2736 if (name >= nameEnd) {
2737 return 0;
2738 }
2739 nameLen = nameEnd-name;
2740
2741 TABLE_NOISY(printf("Looking for identifier: type=%s, name=%s, package=%s\n",
2742 String8(type, typeLen).string(),
2743 String8(name, nameLen).string(),
2744 String8(package, packageLen).string()));
2745
2746 const size_t NG = mPackageGroups.size();
2747 for (size_t ig=0; ig<NG; ig++) {
2748 const PackageGroup* group = mPackageGroups[ig];
2749
2750 if (strzcmp16(package, packageLen,
2751 group->name.string(), group->name.size())) {
2752 TABLE_NOISY(printf("Skipping package group: %s\n", String8(group->name).string()));
2753 continue;
2754 }
2755
Dianne Hackborn78c40512009-07-06 11:07:40 -07002756 const ssize_t ti = group->basePackage->typeStrings.indexOfString(type, typeLen);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002757 if (ti < 0) {
2758 TABLE_NOISY(printf("Type not found in package %s\n", String8(group->name).string()));
2759 continue;
2760 }
2761
Dianne Hackborn78c40512009-07-06 11:07:40 -07002762 const ssize_t ei = group->basePackage->keyStrings.indexOfString(name, nameLen);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002763 if (ei < 0) {
2764 TABLE_NOISY(printf("Name not found in package %s\n", String8(group->name).string()));
2765 continue;
2766 }
2767
2768 TABLE_NOISY(printf("Search indices: type=%d, name=%d\n", ti, ei));
2769
2770 const Type* const typeConfigs = group->packages[0]->getType(ti);
2771 if (typeConfigs == NULL || typeConfigs->configs.size() <= 0) {
2772 TABLE_NOISY(printf("Expected type structure not found in package %s for idnex %d\n",
2773 String8(group->name).string(), ti));
2774 }
2775
2776 size_t NTC = typeConfigs->configs.size();
2777 for (size_t tci=0; tci<NTC; tci++) {
2778 const ResTable_type* const ty = typeConfigs->configs[tci];
2779 const uint32_t typeOffset = dtohl(ty->entriesStart);
2780
2781 const uint8_t* const end = ((const uint8_t*)ty) + dtohl(ty->header.size);
2782 const uint32_t* const eindex = (const uint32_t*)
2783 (((const uint8_t*)ty) + dtohs(ty->header.headerSize));
2784
2785 const size_t NE = dtohl(ty->entryCount);
2786 for (size_t i=0; i<NE; i++) {
2787 uint32_t offset = dtohl(eindex[i]);
2788 if (offset == ResTable_type::NO_ENTRY) {
2789 continue;
2790 }
2791
2792 offset += typeOffset;
2793
2794 if (offset > (dtohl(ty->header.size)-sizeof(ResTable_entry))) {
2795 LOGW("ResTable_entry at %d is beyond type chunk data %d",
2796 offset, dtohl(ty->header.size));
2797 return 0;
2798 }
2799 if ((offset&0x3) != 0) {
2800 LOGW("ResTable_entry at %d (pkg=%d type=%d ent=%d) is not on an integer boundary when looking for %s:%s/%s",
2801 (int)offset, (int)group->id, (int)ti+1, (int)i,
2802 String8(package, packageLen).string(),
2803 String8(type, typeLen).string(),
2804 String8(name, nameLen).string());
2805 return 0;
2806 }
2807
2808 const ResTable_entry* const entry = (const ResTable_entry*)
2809 (((const uint8_t*)ty) + offset);
2810 if (dtohs(entry->size) < sizeof(*entry)) {
2811 LOGW("ResTable_entry size %d is too small", dtohs(entry->size));
2812 return BAD_TYPE;
2813 }
2814
2815 TABLE_SUPER_NOISY(printf("Looking at entry #%d: want str %d, have %d\n",
2816 i, ei, dtohl(entry->key.index)));
2817 if (dtohl(entry->key.index) == (size_t)ei) {
2818 if (outTypeSpecFlags) {
2819 *outTypeSpecFlags = typeConfigs->typeSpecFlags[i];
Dianne Hackborn426431a2011-06-09 11:29:08 -07002820 if (fakePublic) {
2821 *outTypeSpecFlags |= ResTable_typeSpec::SPEC_PUBLIC;
2822 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 }
2824 return Res_MAKEID(group->id-1, ti, i);
2825 }
2826 }
2827 }
2828 }
2829
2830 return 0;
2831}
2832
2833bool ResTable::expandResourceRef(const uint16_t* refStr, size_t refLen,
2834 String16* outPackage,
2835 String16* outType,
2836 String16* outName,
2837 const String16* defType,
2838 const String16* defPackage,
Dianne Hackborn426431a2011-06-09 11:29:08 -07002839 const char** outErrorMsg,
2840 bool* outPublicOnly)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841{
2842 const char16_t* packageEnd = NULL;
2843 const char16_t* typeEnd = NULL;
2844 const char16_t* p = refStr;
2845 const char16_t* const end = p + refLen;
2846 while (p < end) {
2847 if (*p == ':') packageEnd = p;
2848 else if (*p == '/') {
2849 typeEnd = p;
2850 break;
2851 }
2852 p++;
2853 }
2854 p = refStr;
2855 if (*p == '@') p++;
2856
Dianne Hackborn426431a2011-06-09 11:29:08 -07002857 if (outPublicOnly != NULL) {
2858 *outPublicOnly = true;
2859 }
2860 if (*p == '*') {
2861 p++;
2862 if (outPublicOnly != NULL) {
2863 *outPublicOnly = false;
2864 }
2865 }
2866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002867 if (packageEnd) {
2868 *outPackage = String16(p, packageEnd-p);
2869 p = packageEnd+1;
2870 } else {
2871 if (!defPackage) {
2872 if (outErrorMsg) {
2873 *outErrorMsg = "No resource package specified";
2874 }
2875 return false;
2876 }
2877 *outPackage = *defPackage;
2878 }
2879 if (typeEnd) {
2880 *outType = String16(p, typeEnd-p);
2881 p = typeEnd+1;
2882 } else {
2883 if (!defType) {
2884 if (outErrorMsg) {
2885 *outErrorMsg = "No resource type specified";
2886 }
2887 return false;
2888 }
2889 *outType = *defType;
2890 }
2891 *outName = String16(p, end-p);
Konstantin Lopyrevddcafcb2010-06-04 14:36:49 -07002892 if(**outPackage == 0) {
2893 if(outErrorMsg) {
2894 *outErrorMsg = "Resource package cannot be an empty string";
2895 }
2896 return false;
2897 }
2898 if(**outType == 0) {
2899 if(outErrorMsg) {
2900 *outErrorMsg = "Resource type cannot be an empty string";
2901 }
2902 return false;
2903 }
2904 if(**outName == 0) {
2905 if(outErrorMsg) {
2906 *outErrorMsg = "Resource id cannot be an empty string";
2907 }
2908 return false;
2909 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002910 return true;
2911}
2912
2913static uint32_t get_hex(char c, bool* outError)
2914{
2915 if (c >= '0' && c <= '9') {
2916 return c - '0';
2917 } else if (c >= 'a' && c <= 'f') {
2918 return c - 'a' + 0xa;
2919 } else if (c >= 'A' && c <= 'F') {
2920 return c - 'A' + 0xa;
2921 }
2922 *outError = true;
2923 return 0;
2924}
2925
2926struct unit_entry
2927{
2928 const char* name;
2929 size_t len;
2930 uint8_t type;
2931 uint32_t unit;
2932 float scale;
2933};
2934
2935static const unit_entry unitNames[] = {
2936 { "px", strlen("px"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PX, 1.0f },
2937 { "dip", strlen("dip"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
2938 { "dp", strlen("dp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
2939 { "sp", strlen("sp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_SP, 1.0f },
2940 { "pt", strlen("pt"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PT, 1.0f },
2941 { "in", strlen("in"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_IN, 1.0f },
2942 { "mm", strlen("mm"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_MM, 1.0f },
2943 { "%", strlen("%"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION, 1.0f/100 },
2944 { "%p", strlen("%p"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION_PARENT, 1.0f/100 },
2945 { NULL, 0, 0, 0, 0 }
2946};
2947
2948static bool parse_unit(const char* str, Res_value* outValue,
2949 float* outScale, const char** outEnd)
2950{
2951 const char* end = str;
2952 while (*end != 0 && !isspace((unsigned char)*end)) {
2953 end++;
2954 }
2955 const size_t len = end-str;
2956
2957 const char* realEnd = end;
2958 while (*realEnd != 0 && isspace((unsigned char)*realEnd)) {
2959 realEnd++;
2960 }
2961 if (*realEnd != 0) {
2962 return false;
2963 }
2964
2965 const unit_entry* cur = unitNames;
2966 while (cur->name) {
2967 if (len == cur->len && strncmp(cur->name, str, len) == 0) {
2968 outValue->dataType = cur->type;
2969 outValue->data = cur->unit << Res_value::COMPLEX_UNIT_SHIFT;
2970 *outScale = cur->scale;
2971 *outEnd = end;
2972 //printf("Found unit %s for %s\n", cur->name, str);
2973 return true;
2974 }
2975 cur++;
2976 }
2977
2978 return false;
2979}
2980
2981
2982bool ResTable::stringToInt(const char16_t* s, size_t len, Res_value* outValue)
2983{
2984 while (len > 0 && isspace16(*s)) {
2985 s++;
2986 len--;
2987 }
2988
2989 if (len <= 0) {
2990 return false;
2991 }
2992
2993 size_t i = 0;
2994 int32_t val = 0;
2995 bool neg = false;
2996
2997 if (*s == '-') {
2998 neg = true;
2999 i++;
3000 }
3001
3002 if (s[i] < '0' || s[i] > '9') {
3003 return false;
3004 }
3005
3006 // Decimal or hex?
3007 if (s[i] == '0' && s[i+1] == 'x') {
3008 if (outValue)
3009 outValue->dataType = outValue->TYPE_INT_HEX;
3010 i += 2;
3011 bool error = false;
3012 while (i < len && !error) {
3013 val = (val*16) + get_hex(s[i], &error);
3014 i++;
3015 }
3016 if (error) {
3017 return false;
3018 }
3019 } else {
3020 if (outValue)
3021 outValue->dataType = outValue->TYPE_INT_DEC;
3022 while (i < len) {
3023 if (s[i] < '0' || s[i] > '9') {
3024 return false;
3025 }
3026 val = (val*10) + s[i]-'0';
3027 i++;
3028 }
3029 }
3030
3031 if (neg) val = -val;
3032
3033 while (i < len && isspace16(s[i])) {
3034 i++;
3035 }
3036
3037 if (i == len) {
3038 if (outValue)
3039 outValue->data = val;
3040 return true;
3041 }
3042
3043 return false;
3044}
3045
3046bool ResTable::stringToFloat(const char16_t* s, size_t len, Res_value* outValue)
3047{
3048 while (len > 0 && isspace16(*s)) {
3049 s++;
3050 len--;
3051 }
3052
3053 if (len <= 0) {
3054 return false;
3055 }
3056
3057 char buf[128];
3058 int i=0;
3059 while (len > 0 && *s != 0 && i < 126) {
3060 if (*s > 255) {
3061 return false;
3062 }
3063 buf[i++] = *s++;
3064 len--;
3065 }
3066
3067 if (len > 0) {
3068 return false;
3069 }
3070 if (buf[0] < '0' && buf[0] > '9' && buf[0] != '.') {
3071 return false;
3072 }
3073
3074 buf[i] = 0;
3075 const char* end;
3076 float f = strtof(buf, (char**)&end);
3077
3078 if (*end != 0 && !isspace((unsigned char)*end)) {
3079 // Might be a unit...
3080 float scale;
3081 if (parse_unit(end, outValue, &scale, &end)) {
3082 f *= scale;
3083 const bool neg = f < 0;
3084 if (neg) f = -f;
3085 uint64_t bits = (uint64_t)(f*(1<<23)+.5f);
3086 uint32_t radix;
3087 uint32_t shift;
3088 if ((bits&0x7fffff) == 0) {
3089 // Always use 23p0 if there is no fraction, just to make
3090 // things easier to read.
3091 radix = Res_value::COMPLEX_RADIX_23p0;
3092 shift = 23;
3093 } else if ((bits&0xffffffffff800000LL) == 0) {
3094 // Magnitude is zero -- can fit in 0 bits of precision.
3095 radix = Res_value::COMPLEX_RADIX_0p23;
3096 shift = 0;
3097 } else if ((bits&0xffffffff80000000LL) == 0) {
3098 // Magnitude can fit in 8 bits of precision.
3099 radix = Res_value::COMPLEX_RADIX_8p15;
3100 shift = 8;
3101 } else if ((bits&0xffffff8000000000LL) == 0) {
3102 // Magnitude can fit in 16 bits of precision.
3103 radix = Res_value::COMPLEX_RADIX_16p7;
3104 shift = 16;
3105 } else {
3106 // Magnitude needs entire range, so no fractional part.
3107 radix = Res_value::COMPLEX_RADIX_23p0;
3108 shift = 23;
3109 }
3110 int32_t mantissa = (int32_t)(
3111 (bits>>shift) & Res_value::COMPLEX_MANTISSA_MASK);
3112 if (neg) {
3113 mantissa = (-mantissa) & Res_value::COMPLEX_MANTISSA_MASK;
3114 }
3115 outValue->data |=
3116 (radix<<Res_value::COMPLEX_RADIX_SHIFT)
3117 | (mantissa<<Res_value::COMPLEX_MANTISSA_SHIFT);
3118 //printf("Input value: %f 0x%016Lx, mult: %f, radix: %d, shift: %d, final: 0x%08x\n",
3119 // f * (neg ? -1 : 1), bits, f*(1<<23),
3120 // radix, shift, outValue->data);
3121 return true;
3122 }
3123 return false;
3124 }
3125
3126 while (*end != 0 && isspace((unsigned char)*end)) {
3127 end++;
3128 }
3129
3130 if (*end == 0) {
3131 if (outValue) {
3132 outValue->dataType = outValue->TYPE_FLOAT;
3133 *(float*)(&outValue->data) = f;
3134 return true;
3135 }
3136 }
3137
3138 return false;
3139}
3140
3141bool ResTable::stringToValue(Res_value* outValue, String16* outString,
3142 const char16_t* s, size_t len,
3143 bool preserveSpaces, bool coerceType,
3144 uint32_t attrID,
3145 const String16* defType,
3146 const String16* defPackage,
3147 Accessor* accessor,
3148 void* accessorCookie,
3149 uint32_t attrType,
3150 bool enforcePrivate) const
3151{
3152 bool localizationSetting = accessor != NULL && accessor->getLocalizationSetting();
3153 const char* errorMsg = NULL;
3154
3155 outValue->size = sizeof(Res_value);
3156 outValue->res0 = 0;
3157
3158 // First strip leading/trailing whitespace. Do this before handling
3159 // escapes, so they can be used to force whitespace into the string.
3160 if (!preserveSpaces) {
3161 while (len > 0 && isspace16(*s)) {
3162 s++;
3163 len--;
3164 }
3165 while (len > 0 && isspace16(s[len-1])) {
3166 len--;
3167 }
3168 // If the string ends with '\', then we keep the space after it.
3169 if (len > 0 && s[len-1] == '\\' && s[len] != 0) {
3170 len++;
3171 }
3172 }
3173
3174 //printf("Value for: %s\n", String8(s, len).string());
3175
3176 uint32_t l10nReq = ResTable_map::L10N_NOT_REQUIRED;
3177 uint32_t attrMin = 0x80000000, attrMax = 0x7fffffff;
3178 bool fromAccessor = false;
3179 if (attrID != 0 && !Res_INTERNALID(attrID)) {
3180 const ssize_t p = getResourcePackageIndex(attrID);
3181 const bag_entry* bag;
3182 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
3183 //printf("For attr 0x%08x got bag of %d\n", attrID, cnt);
3184 if (cnt >= 0) {
3185 while (cnt > 0) {
3186 //printf("Entry 0x%08x = 0x%08x\n", bag->map.name.ident, bag->map.value.data);
3187 switch (bag->map.name.ident) {
3188 case ResTable_map::ATTR_TYPE:
3189 attrType = bag->map.value.data;
3190 break;
3191 case ResTable_map::ATTR_MIN:
3192 attrMin = bag->map.value.data;
3193 break;
3194 case ResTable_map::ATTR_MAX:
3195 attrMax = bag->map.value.data;
3196 break;
3197 case ResTable_map::ATTR_L10N:
3198 l10nReq = bag->map.value.data;
3199 break;
3200 }
3201 bag++;
3202 cnt--;
3203 }
3204 unlockBag(bag);
3205 } else if (accessor && accessor->getAttributeType(attrID, &attrType)) {
3206 fromAccessor = true;
3207 if (attrType == ResTable_map::TYPE_ENUM
3208 || attrType == ResTable_map::TYPE_FLAGS
3209 || attrType == ResTable_map::TYPE_INTEGER) {
3210 accessor->getAttributeMin(attrID, &attrMin);
3211 accessor->getAttributeMax(attrID, &attrMax);
3212 }
3213 if (localizationSetting) {
3214 l10nReq = accessor->getAttributeL10N(attrID);
3215 }
3216 }
3217 }
3218
3219 const bool canStringCoerce =
3220 coerceType && (attrType&ResTable_map::TYPE_STRING) != 0;
3221
3222 if (*s == '@') {
3223 outValue->dataType = outValue->TYPE_REFERENCE;
3224
3225 // Note: we don't check attrType here because the reference can
3226 // be to any other type; we just need to count on the client making
3227 // sure the referenced type is correct.
3228
3229 //printf("Looking up ref: %s\n", String8(s, len).string());
3230
3231 // It's a reference!
3232 if (len == 5 && s[1]=='n' && s[2]=='u' && s[3]=='l' && s[4]=='l') {
3233 outValue->data = 0;
3234 return true;
3235 } else {
3236 bool createIfNotFound = false;
3237 const char16_t* resourceRefName;
3238 int resourceNameLen;
3239 if (len > 2 && s[1] == '+') {
3240 createIfNotFound = true;
3241 resourceRefName = s + 2;
3242 resourceNameLen = len - 2;
3243 } else if (len > 2 && s[1] == '*') {
3244 enforcePrivate = false;
3245 resourceRefName = s + 2;
3246 resourceNameLen = len - 2;
3247 } else {
3248 createIfNotFound = false;
3249 resourceRefName = s + 1;
3250 resourceNameLen = len - 1;
3251 }
3252 String16 package, type, name;
3253 if (!expandResourceRef(resourceRefName,resourceNameLen, &package, &type, &name,
3254 defType, defPackage, &errorMsg)) {
3255 if (accessor != NULL) {
3256 accessor->reportError(accessorCookie, errorMsg);
3257 }
3258 return false;
3259 }
3260
3261 uint32_t specFlags = 0;
3262 uint32_t rid = identifierForName(name.string(), name.size(), type.string(),
3263 type.size(), package.string(), package.size(), &specFlags);
3264 if (rid != 0) {
3265 if (enforcePrivate) {
3266 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
3267 if (accessor != NULL) {
3268 accessor->reportError(accessorCookie, "Resource is not public.");
3269 }
3270 return false;
3271 }
3272 }
3273 if (!accessor) {
3274 outValue->data = rid;
3275 return true;
3276 }
3277 rid = Res_MAKEID(
3278 accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
3279 Res_GETTYPE(rid), Res_GETENTRY(rid));
3280 TABLE_NOISY(printf("Incl %s:%s/%s: 0x%08x\n",
3281 String8(package).string(), String8(type).string(),
3282 String8(name).string(), rid));
3283 outValue->data = rid;
3284 return true;
3285 }
3286
3287 if (accessor) {
3288 uint32_t rid = accessor->getCustomResourceWithCreation(package, type, name,
3289 createIfNotFound);
3290 if (rid != 0) {
3291 TABLE_NOISY(printf("Pckg %s:%s/%s: 0x%08x\n",
3292 String8(package).string(), String8(type).string(),
3293 String8(name).string(), rid));
3294 outValue->data = rid;
3295 return true;
3296 }
3297 }
3298 }
3299
3300 if (accessor != NULL) {
3301 accessor->reportError(accessorCookie, "No resource found that matches the given name");
3302 }
3303 return false;
3304 }
3305
3306 // if we got to here, and localization is required and it's not a reference,
3307 // complain and bail.
3308 if (l10nReq == ResTable_map::L10N_SUGGESTED) {
3309 if (localizationSetting) {
3310 if (accessor != NULL) {
3311 accessor->reportError(accessorCookie, "This attribute must be localized.");
3312 }
3313 }
3314 }
3315
3316 if (*s == '#') {
3317 // It's a color! Convert to an integer of the form 0xaarrggbb.
3318 uint32_t color = 0;
3319 bool error = false;
3320 if (len == 4) {
3321 outValue->dataType = outValue->TYPE_INT_COLOR_RGB4;
3322 color |= 0xFF000000;
3323 color |= get_hex(s[1], &error) << 20;
3324 color |= get_hex(s[1], &error) << 16;
3325 color |= get_hex(s[2], &error) << 12;
3326 color |= get_hex(s[2], &error) << 8;
3327 color |= get_hex(s[3], &error) << 4;
3328 color |= get_hex(s[3], &error);
3329 } else if (len == 5) {
3330 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB4;
3331 color |= get_hex(s[1], &error) << 28;
3332 color |= get_hex(s[1], &error) << 24;
3333 color |= get_hex(s[2], &error) << 20;
3334 color |= get_hex(s[2], &error) << 16;
3335 color |= get_hex(s[3], &error) << 12;
3336 color |= get_hex(s[3], &error) << 8;
3337 color |= get_hex(s[4], &error) << 4;
3338 color |= get_hex(s[4], &error);
3339 } else if (len == 7) {
3340 outValue->dataType = outValue->TYPE_INT_COLOR_RGB8;
3341 color |= 0xFF000000;
3342 color |= get_hex(s[1], &error) << 20;
3343 color |= get_hex(s[2], &error) << 16;
3344 color |= get_hex(s[3], &error) << 12;
3345 color |= get_hex(s[4], &error) << 8;
3346 color |= get_hex(s[5], &error) << 4;
3347 color |= get_hex(s[6], &error);
3348 } else if (len == 9) {
3349 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB8;
3350 color |= get_hex(s[1], &error) << 28;
3351 color |= get_hex(s[2], &error) << 24;
3352 color |= get_hex(s[3], &error) << 20;
3353 color |= get_hex(s[4], &error) << 16;
3354 color |= get_hex(s[5], &error) << 12;
3355 color |= get_hex(s[6], &error) << 8;
3356 color |= get_hex(s[7], &error) << 4;
3357 color |= get_hex(s[8], &error);
3358 } else {
3359 error = true;
3360 }
3361 if (!error) {
3362 if ((attrType&ResTable_map::TYPE_COLOR) == 0) {
3363 if (!canStringCoerce) {
3364 if (accessor != NULL) {
3365 accessor->reportError(accessorCookie,
3366 "Color types not allowed");
3367 }
3368 return false;
3369 }
3370 } else {
3371 outValue->data = color;
3372 //printf("Color input=%s, output=0x%x\n", String8(s, len).string(), color);
3373 return true;
3374 }
3375 } else {
3376 if ((attrType&ResTable_map::TYPE_COLOR) != 0) {
3377 if (accessor != NULL) {
3378 accessor->reportError(accessorCookie, "Color value not valid --"
3379 " must be #rgb, #argb, #rrggbb, or #aarrggbb");
3380 }
3381 #if 0
3382 fprintf(stderr, "%s: Color ID %s value %s is not valid\n",
3383 "Resource File", //(const char*)in->getPrintableSource(),
3384 String8(*curTag).string(),
3385 String8(s, len).string());
3386 #endif
3387 return false;
3388 }
3389 }
3390 }
3391
3392 if (*s == '?') {
3393 outValue->dataType = outValue->TYPE_ATTRIBUTE;
3394
3395 // Note: we don't check attrType here because the reference can
3396 // be to any other type; we just need to count on the client making
3397 // sure the referenced type is correct.
3398
3399 //printf("Looking up attr: %s\n", String8(s, len).string());
3400
3401 static const String16 attr16("attr");
3402 String16 package, type, name;
3403 if (!expandResourceRef(s+1, len-1, &package, &type, &name,
3404 &attr16, defPackage, &errorMsg)) {
3405 if (accessor != NULL) {
3406 accessor->reportError(accessorCookie, errorMsg);
3407 }
3408 return false;
3409 }
3410
3411 //printf("Pkg: %s, Type: %s, Name: %s\n",
3412 // String8(package).string(), String8(type).string(),
3413 // String8(name).string());
3414 uint32_t specFlags = 0;
3415 uint32_t rid =
3416 identifierForName(name.string(), name.size(),
3417 type.string(), type.size(),
3418 package.string(), package.size(), &specFlags);
3419 if (rid != 0) {
3420 if (enforcePrivate) {
3421 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
3422 if (accessor != NULL) {
3423 accessor->reportError(accessorCookie, "Attribute is not public.");
3424 }
3425 return false;
3426 }
3427 }
3428 if (!accessor) {
3429 outValue->data = rid;
3430 return true;
3431 }
3432 rid = Res_MAKEID(
3433 accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
3434 Res_GETTYPE(rid), Res_GETENTRY(rid));
3435 //printf("Incl %s:%s/%s: 0x%08x\n",
3436 // String8(package).string(), String8(type).string(),
3437 // String8(name).string(), rid);
3438 outValue->data = rid;
3439 return true;
3440 }
3441
3442 if (accessor) {
3443 uint32_t rid = accessor->getCustomResource(package, type, name);
3444 if (rid != 0) {
3445 //printf("Mine %s:%s/%s: 0x%08x\n",
3446 // String8(package).string(), String8(type).string(),
3447 // String8(name).string(), rid);
3448 outValue->data = rid;
3449 return true;
3450 }
3451 }
3452
3453 if (accessor != NULL) {
3454 accessor->reportError(accessorCookie, "No resource found that matches the given name");
3455 }
3456 return false;
3457 }
3458
3459 if (stringToInt(s, len, outValue)) {
3460 if ((attrType&ResTable_map::TYPE_INTEGER) == 0) {
3461 // If this type does not allow integers, but does allow floats,
3462 // fall through on this error case because the float type should
3463 // be able to accept any integer value.
3464 if (!canStringCoerce && (attrType&ResTable_map::TYPE_FLOAT) == 0) {
3465 if (accessor != NULL) {
3466 accessor->reportError(accessorCookie, "Integer types not allowed");
3467 }
3468 return false;
3469 }
3470 } else {
3471 if (((int32_t)outValue->data) < ((int32_t)attrMin)
3472 || ((int32_t)outValue->data) > ((int32_t)attrMax)) {
3473 if (accessor != NULL) {
3474 accessor->reportError(accessorCookie, "Integer value out of range");
3475 }
3476 return false;
3477 }
3478 return true;
3479 }
3480 }
3481
3482 if (stringToFloat(s, len, outValue)) {
3483 if (outValue->dataType == Res_value::TYPE_DIMENSION) {
3484 if ((attrType&ResTable_map::TYPE_DIMENSION) != 0) {
3485 return true;
3486 }
3487 if (!canStringCoerce) {
3488 if (accessor != NULL) {
3489 accessor->reportError(accessorCookie, "Dimension types not allowed");
3490 }
3491 return false;
3492 }
3493 } else if (outValue->dataType == Res_value::TYPE_FRACTION) {
3494 if ((attrType&ResTable_map::TYPE_FRACTION) != 0) {
3495 return true;
3496 }
3497 if (!canStringCoerce) {
3498 if (accessor != NULL) {
3499 accessor->reportError(accessorCookie, "Fraction types not allowed");
3500 }
3501 return false;
3502 }
3503 } else if ((attrType&ResTable_map::TYPE_FLOAT) == 0) {
3504 if (!canStringCoerce) {
3505 if (accessor != NULL) {
3506 accessor->reportError(accessorCookie, "Float types not allowed");
3507 }
3508 return false;
3509 }
3510 } else {
3511 return true;
3512 }
3513 }
3514
3515 if (len == 4) {
3516 if ((s[0] == 't' || s[0] == 'T') &&
3517 (s[1] == 'r' || s[1] == 'R') &&
3518 (s[2] == 'u' || s[2] == 'U') &&
3519 (s[3] == 'e' || s[3] == 'E')) {
3520 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
3521 if (!canStringCoerce) {
3522 if (accessor != NULL) {
3523 accessor->reportError(accessorCookie, "Boolean types not allowed");
3524 }
3525 return false;
3526 }
3527 } else {
3528 outValue->dataType = outValue->TYPE_INT_BOOLEAN;
3529 outValue->data = (uint32_t)-1;
3530 return true;
3531 }
3532 }
3533 }
3534
3535 if (len == 5) {
3536 if ((s[0] == 'f' || s[0] == 'F') &&
3537 (s[1] == 'a' || s[1] == 'A') &&
3538 (s[2] == 'l' || s[2] == 'L') &&
3539 (s[3] == 's' || s[3] == 'S') &&
3540 (s[4] == 'e' || s[4] == 'E')) {
3541 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
3542 if (!canStringCoerce) {
3543 if (accessor != NULL) {
3544 accessor->reportError(accessorCookie, "Boolean types not allowed");
3545 }
3546 return false;
3547 }
3548 } else {
3549 outValue->dataType = outValue->TYPE_INT_BOOLEAN;
3550 outValue->data = 0;
3551 return true;
3552 }
3553 }
3554 }
3555
3556 if ((attrType&ResTable_map::TYPE_ENUM) != 0) {
3557 const ssize_t p = getResourcePackageIndex(attrID);
3558 const bag_entry* bag;
3559 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
3560 //printf("Got %d for enum\n", cnt);
3561 if (cnt >= 0) {
3562 resource_name rname;
3563 while (cnt > 0) {
3564 if (!Res_INTERNALID(bag->map.name.ident)) {
3565 //printf("Trying attr #%08x\n", bag->map.name.ident);
3566 if (getResourceName(bag->map.name.ident, &rname)) {
3567 #if 0
3568 printf("Matching %s against %s (0x%08x)\n",
3569 String8(s, len).string(),
3570 String8(rname.name, rname.nameLen).string(),
3571 bag->map.name.ident);
3572 #endif
3573 if (strzcmp16(s, len, rname.name, rname.nameLen) == 0) {
3574 outValue->dataType = bag->map.value.dataType;
3575 outValue->data = bag->map.value.data;
3576 unlockBag(bag);
3577 return true;
3578 }
3579 }
3580
3581 }
3582 bag++;
3583 cnt--;
3584 }
3585 unlockBag(bag);
3586 }
3587
3588 if (fromAccessor) {
3589 if (accessor->getAttributeEnum(attrID, s, len, outValue)) {
3590 return true;
3591 }
3592 }
3593 }
3594
3595 if ((attrType&ResTable_map::TYPE_FLAGS) != 0) {
3596 const ssize_t p = getResourcePackageIndex(attrID);
3597 const bag_entry* bag;
3598 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
3599 //printf("Got %d for flags\n", cnt);
3600 if (cnt >= 0) {
3601 bool failed = false;
3602 resource_name rname;
3603 outValue->dataType = Res_value::TYPE_INT_HEX;
3604 outValue->data = 0;
3605 const char16_t* end = s + len;
3606 const char16_t* pos = s;
3607 while (pos < end && !failed) {
3608 const char16_t* start = pos;
The Android Open Source Project4df24232009-03-05 14:34:35 -08003609 pos++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003610 while (pos < end && *pos != '|') {
3611 pos++;
3612 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08003613 //printf("Looking for: %s\n", String8(start, pos-start).string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003614 const bag_entry* bagi = bag;
The Android Open Source Project4df24232009-03-05 14:34:35 -08003615 ssize_t i;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003616 for (i=0; i<cnt; i++, bagi++) {
3617 if (!Res_INTERNALID(bagi->map.name.ident)) {
3618 //printf("Trying attr #%08x\n", bagi->map.name.ident);
3619 if (getResourceName(bagi->map.name.ident, &rname)) {
3620 #if 0
3621 printf("Matching %s against %s (0x%08x)\n",
3622 String8(start,pos-start).string(),
3623 String8(rname.name, rname.nameLen).string(),
3624 bagi->map.name.ident);
3625 #endif
3626 if (strzcmp16(start, pos-start, rname.name, rname.nameLen) == 0) {
3627 outValue->data |= bagi->map.value.data;
3628 break;
3629 }
3630 }
3631 }
3632 }
3633 if (i >= cnt) {
3634 // Didn't find this flag identifier.
3635 failed = true;
3636 }
3637 if (pos < end) {
3638 pos++;
3639 }
3640 }
3641 unlockBag(bag);
3642 if (!failed) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08003643 //printf("Final flag value: 0x%lx\n", outValue->data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003644 return true;
3645 }
3646 }
3647
3648
3649 if (fromAccessor) {
3650 if (accessor->getAttributeFlags(attrID, s, len, outValue)) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08003651 //printf("Final flag value: 0x%lx\n", outValue->data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003652 return true;
3653 }
3654 }
3655 }
3656
3657 if ((attrType&ResTable_map::TYPE_STRING) == 0) {
3658 if (accessor != NULL) {
3659 accessor->reportError(accessorCookie, "String types not allowed");
3660 }
3661 return false;
3662 }
3663
3664 // Generic string handling...
3665 outValue->dataType = outValue->TYPE_STRING;
3666 if (outString) {
3667 bool failed = collectString(outString, s, len, preserveSpaces, &errorMsg);
3668 if (accessor != NULL) {
3669 accessor->reportError(accessorCookie, errorMsg);
3670 }
3671 return failed;
3672 }
3673
3674 return true;
3675}
3676
3677bool ResTable::collectString(String16* outString,
3678 const char16_t* s, size_t len,
3679 bool preserveSpaces,
3680 const char** outErrorMsg,
3681 bool append)
3682{
3683 String16 tmp;
3684
3685 char quoted = 0;
3686 const char16_t* p = s;
3687 while (p < (s+len)) {
3688 while (p < (s+len)) {
3689 const char16_t c = *p;
3690 if (c == '\\') {
3691 break;
3692 }
3693 if (!preserveSpaces) {
3694 if (quoted == 0 && isspace16(c)
3695 && (c != ' ' || isspace16(*(p+1)))) {
3696 break;
3697 }
3698 if (c == '"' && (quoted == 0 || quoted == '"')) {
3699 break;
3700 }
3701 if (c == '\'' && (quoted == 0 || quoted == '\'')) {
Eric Fischerc87d2522009-09-01 15:20:30 -07003702 /*
3703 * In practice, when people write ' instead of \'
3704 * in a string, they are doing it by accident
3705 * instead of really meaning to use ' as a quoting
3706 * character. Warn them so they don't lose it.
3707 */
3708 if (outErrorMsg) {
3709 *outErrorMsg = "Apostrophe not preceded by \\";
3710 }
3711 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003712 }
3713 }
3714 p++;
3715 }
3716 if (p < (s+len)) {
3717 if (p > s) {
3718 tmp.append(String16(s, p-s));
3719 }
3720 if (!preserveSpaces && (*p == '"' || *p == '\'')) {
3721 if (quoted == 0) {
3722 quoted = *p;
3723 } else {
3724 quoted = 0;
3725 }
3726 p++;
3727 } else if (!preserveSpaces && isspace16(*p)) {
3728 // Space outside of a quote -- consume all spaces and
3729 // leave a single plain space char.
3730 tmp.append(String16(" "));
3731 p++;
3732 while (p < (s+len) && isspace16(*p)) {
3733 p++;
3734 }
3735 } else if (*p == '\\') {
3736 p++;
3737 if (p < (s+len)) {
3738 switch (*p) {
3739 case 't':
3740 tmp.append(String16("\t"));
3741 break;
3742 case 'n':
3743 tmp.append(String16("\n"));
3744 break;
3745 case '#':
3746 tmp.append(String16("#"));
3747 break;
3748 case '@':
3749 tmp.append(String16("@"));
3750 break;
3751 case '?':
3752 tmp.append(String16("?"));
3753 break;
3754 case '"':
3755 tmp.append(String16("\""));
3756 break;
3757 case '\'':
3758 tmp.append(String16("'"));
3759 break;
3760 case '\\':
3761 tmp.append(String16("\\"));
3762 break;
3763 case 'u':
3764 {
3765 char16_t chr = 0;
3766 int i = 0;
3767 while (i < 4 && p[1] != 0) {
3768 p++;
3769 i++;
3770 int c;
3771 if (*p >= '0' && *p <= '9') {
3772 c = *p - '0';
3773 } else if (*p >= 'a' && *p <= 'f') {
3774 c = *p - 'a' + 10;
3775 } else if (*p >= 'A' && *p <= 'F') {
3776 c = *p - 'A' + 10;
3777 } else {
3778 if (outErrorMsg) {
3779 *outErrorMsg = "Bad character in \\u unicode escape sequence";
3780 }
3781 return false;
3782 }
3783 chr = (chr<<4) | c;
3784 }
3785 tmp.append(String16(&chr, 1));
3786 } break;
3787 default:
3788 // ignore unknown escape chars.
3789 break;
3790 }
3791 p++;
3792 }
3793 }
3794 len -= (p-s);
3795 s = p;
3796 }
3797 }
3798
3799 if (tmp.size() != 0) {
3800 if (len > 0) {
3801 tmp.append(String16(s, len));
3802 }
3803 if (append) {
3804 outString->append(tmp);
3805 } else {
3806 outString->setTo(tmp);
3807 }
3808 } else {
3809 if (append) {
3810 outString->append(String16(s, len));
3811 } else {
3812 outString->setTo(s, len);
3813 }
3814 }
3815
3816 return true;
3817}
3818
3819size_t ResTable::getBasePackageCount() const
3820{
3821 if (mError != NO_ERROR) {
3822 return 0;
3823 }
3824 return mPackageGroups.size();
3825}
3826
3827const char16_t* ResTable::getBasePackageName(size_t idx) const
3828{
3829 if (mError != NO_ERROR) {
3830 return 0;
3831 }
3832 LOG_FATAL_IF(idx >= mPackageGroups.size(),
3833 "Requested package index %d past package count %d",
3834 (int)idx, (int)mPackageGroups.size());
3835 return mPackageGroups[idx]->name.string();
3836}
3837
3838uint32_t ResTable::getBasePackageId(size_t idx) const
3839{
3840 if (mError != NO_ERROR) {
3841 return 0;
3842 }
3843 LOG_FATAL_IF(idx >= mPackageGroups.size(),
3844 "Requested package index %d past package count %d",
3845 (int)idx, (int)mPackageGroups.size());
3846 return mPackageGroups[idx]->id;
3847}
3848
3849size_t ResTable::getTableCount() const
3850{
3851 return mHeaders.size();
3852}
3853
3854const ResStringPool* ResTable::getTableStringBlock(size_t index) const
3855{
3856 return &mHeaders[index]->values;
3857}
3858
3859void* ResTable::getTableCookie(size_t index) const
3860{
3861 return mHeaders[index]->cookie;
3862}
3863
3864void ResTable::getConfigurations(Vector<ResTable_config>* configs) const
3865{
3866 const size_t I = mPackageGroups.size();
3867 for (size_t i=0; i<I; i++) {
3868 const PackageGroup* packageGroup = mPackageGroups[i];
3869 const size_t J = packageGroup->packages.size();
3870 for (size_t j=0; j<J; j++) {
3871 const Package* package = packageGroup->packages[j];
3872 const size_t K = package->types.size();
3873 for (size_t k=0; k<K; k++) {
3874 const Type* type = package->types[k];
3875 if (type == NULL) continue;
3876 const size_t L = type->configs.size();
3877 for (size_t l=0; l<L; l++) {
3878 const ResTable_type* config = type->configs[l];
3879 const ResTable_config* cfg = &config->config;
3880 // only insert unique
3881 const size_t M = configs->size();
3882 size_t m;
3883 for (m=0; m<M; m++) {
3884 if (0 == (*configs)[m].compare(*cfg)) {
3885 break;
3886 }
3887 }
3888 // if we didn't find it
3889 if (m == M) {
3890 configs->add(*cfg);
3891 }
3892 }
3893 }
3894 }
3895 }
3896}
3897
3898void ResTable::getLocales(Vector<String8>* locales) const
3899{
3900 Vector<ResTable_config> configs;
Steve Block71f2cf12011-10-20 11:56:00 +01003901 ALOGV("calling getConfigurations");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003902 getConfigurations(&configs);
Steve Block71f2cf12011-10-20 11:56:00 +01003903 ALOGV("called getConfigurations size=%d", (int)configs.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003904 const size_t I = configs.size();
3905 for (size_t i=0; i<I; i++) {
3906 char locale[6];
3907 configs[i].getLocale(locale);
3908 const size_t J = locales->size();
3909 size_t j;
3910 for (j=0; j<J; j++) {
3911 if (0 == strcmp(locale, (*locales)[j].string())) {
3912 break;
3913 }
3914 }
3915 if (j == J) {
3916 locales->add(String8(locale));
3917 }
3918 }
3919}
3920
3921ssize_t ResTable::getEntry(
3922 const Package* package, int typeIndex, int entryIndex,
3923 const ResTable_config* config,
3924 const ResTable_type** outType, const ResTable_entry** outEntry,
3925 const Type** outTypeClass) const
3926{
Steve Block71f2cf12011-10-20 11:56:00 +01003927 ALOGV("Getting entry from package %p\n", package);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003928 const ResTable_package* const pkg = package->package;
3929
3930 const Type* allTypes = package->getType(typeIndex);
Steve Block71f2cf12011-10-20 11:56:00 +01003931 ALOGV("allTypes=%p\n", allTypes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003932 if (allTypes == NULL) {
Steve Block71f2cf12011-10-20 11:56:00 +01003933 ALOGV("Skipping entry type index 0x%02x because type is NULL!\n", typeIndex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003934 return 0;
3935 }
3936
3937 if ((size_t)entryIndex >= allTypes->entryCount) {
3938 LOGW("getEntry failing because entryIndex %d is beyond type entryCount %d",
3939 entryIndex, (int)allTypes->entryCount);
3940 return BAD_TYPE;
3941 }
3942
3943 const ResTable_type* type = NULL;
3944 uint32_t offset = ResTable_type::NO_ENTRY;
3945 ResTable_config bestConfig;
3946 memset(&bestConfig, 0, sizeof(bestConfig)); // make the compiler shut up
3947
3948 const size_t NT = allTypes->configs.size();
3949 for (size_t i=0; i<NT; i++) {
3950 const ResTable_type* const thisType = allTypes->configs[i];
3951 if (thisType == NULL) continue;
3952
3953 ResTable_config thisConfig;
3954 thisConfig.copyFromDtoH(thisType->config);
3955
Dianne Hackbornebff8f92011-05-12 18:07:47 -07003956 TABLE_GETENTRY(LOGI("Match entry 0x%x in type 0x%x (sz 0x%x): imsi:%d/%d=%d/%d "
3957 "lang:%c%c=%c%c cnt:%c%c=%c%c orien:%d=%d touch:%d=%d "
3958 "density:%d=%d key:%d=%d inp:%d=%d nav:%d=%d w:%d=%d h:%d=%d "
Dianne Hackborn69cb8752011-05-19 18:13:32 -07003959 "swdp:%d=%d wdp:%d=%d hdp:%d=%d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003960 entryIndex, typeIndex+1, dtohl(thisType->config.size),
3961 thisConfig.mcc, thisConfig.mnc,
3962 config ? config->mcc : 0, config ? config->mnc : 0,
3963 thisConfig.language[0] ? thisConfig.language[0] : '-',
3964 thisConfig.language[1] ? thisConfig.language[1] : '-',
3965 config && config->language[0] ? config->language[0] : '-',
3966 config && config->language[1] ? config->language[1] : '-',
3967 thisConfig.country[0] ? thisConfig.country[0] : '-',
3968 thisConfig.country[1] ? thisConfig.country[1] : '-',
3969 config && config->country[0] ? config->country[0] : '-',
3970 config && config->country[1] ? config->country[1] : '-',
3971 thisConfig.orientation,
3972 config ? config->orientation : 0,
3973 thisConfig.touchscreen,
3974 config ? config->touchscreen : 0,
3975 thisConfig.density,
3976 config ? config->density : 0,
3977 thisConfig.keyboard,
3978 config ? config->keyboard : 0,
3979 thisConfig.inputFlags,
3980 config ? config->inputFlags : 0,
3981 thisConfig.navigation,
3982 config ? config->navigation : 0,
3983 thisConfig.screenWidth,
3984 config ? config->screenWidth : 0,
3985 thisConfig.screenHeight,
Dianne Hackbornebff8f92011-05-12 18:07:47 -07003986 config ? config->screenHeight : 0,
Dianne Hackborn69cb8752011-05-19 18:13:32 -07003987 thisConfig.smallestScreenWidthDp,
3988 config ? config->smallestScreenWidthDp : 0,
Dianne Hackbornebff8f92011-05-12 18:07:47 -07003989 thisConfig.screenWidthDp,
3990 config ? config->screenWidthDp : 0,
3991 thisConfig.screenHeightDp,
3992 config ? config->screenHeightDp : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003993
3994 // Check to make sure this one is valid for the current parameters.
3995 if (config && !thisConfig.match(*config)) {
3996 TABLE_GETENTRY(LOGI("Does not match config!\n"));
3997 continue;
3998 }
3999
4000 // Check if there is the desired entry in this type.
4001
4002 const uint8_t* const end = ((const uint8_t*)thisType)
4003 + dtohl(thisType->header.size);
4004 const uint32_t* const eindex = (const uint32_t*)
4005 (((const uint8_t*)thisType) + dtohs(thisType->header.headerSize));
4006
4007 uint32_t thisOffset = dtohl(eindex[entryIndex]);
4008 if (thisOffset == ResTable_type::NO_ENTRY) {
4009 TABLE_GETENTRY(LOGI("Skipping because it is not defined!\n"));
4010 continue;
4011 }
4012
4013 if (type != NULL) {
4014 // Check if this one is less specific than the last found. If so,
4015 // we will skip it. We check starting with things we most care
4016 // about to those we least care about.
4017 if (!thisConfig.isBetterThan(bestConfig, config)) {
4018 TABLE_GETENTRY(LOGI("This config is worse than last!\n"));
4019 continue;
4020 }
4021 }
4022
4023 type = thisType;
4024 offset = thisOffset;
4025 bestConfig = thisConfig;
4026 TABLE_GETENTRY(LOGI("Best entry so far -- using it!\n"));
4027 if (!config) break;
4028 }
4029
4030 if (type == NULL) {
4031 TABLE_GETENTRY(LOGI("No value found for requested entry!\n"));
4032 return BAD_INDEX;
4033 }
4034
4035 offset += dtohl(type->entriesStart);
4036 TABLE_NOISY(aout << "Looking in resource table " << package->header->header
4037 << ", typeOff="
4038 << (void*)(((const char*)type)-((const char*)package->header->header))
4039 << ", offset=" << (void*)offset << endl);
4040
4041 if (offset > (dtohl(type->header.size)-sizeof(ResTable_entry))) {
4042 LOGW("ResTable_entry at 0x%x is beyond type chunk data 0x%x",
4043 offset, dtohl(type->header.size));
4044 return BAD_TYPE;
4045 }
4046 if ((offset&0x3) != 0) {
4047 LOGW("ResTable_entry at 0x%x is not on an integer boundary",
4048 offset);
4049 return BAD_TYPE;
4050 }
4051
4052 const ResTable_entry* const entry = (const ResTable_entry*)
4053 (((const uint8_t*)type) + offset);
4054 if (dtohs(entry->size) < sizeof(*entry)) {
4055 LOGW("ResTable_entry size 0x%x is too small", dtohs(entry->size));
4056 return BAD_TYPE;
4057 }
4058
4059 *outType = type;
4060 *outEntry = entry;
4061 if (outTypeClass != NULL) {
4062 *outTypeClass = allTypes;
4063 }
4064 return offset + dtohs(entry->size);
4065}
4066
4067status_t ResTable::parsePackage(const ResTable_package* const pkg,
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01004068 const Header* const header, uint32_t idmap_id)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004069{
4070 const uint8_t* base = (const uint8_t*)pkg;
4071 status_t err = validate_chunk(&pkg->header, sizeof(*pkg),
4072 header->dataEnd, "ResTable_package");
4073 if (err != NO_ERROR) {
4074 return (mError=err);
4075 }
4076
4077 const size_t pkgSize = dtohl(pkg->header.size);
4078
4079 if (dtohl(pkg->typeStrings) >= pkgSize) {
4080 LOGW("ResTable_package type strings at %p are past chunk size %p.",
4081 (void*)dtohl(pkg->typeStrings), (void*)pkgSize);
4082 return (mError=BAD_TYPE);
4083 }
4084 if ((dtohl(pkg->typeStrings)&0x3) != 0) {
4085 LOGW("ResTable_package type strings at %p is not on an integer boundary.",
4086 (void*)dtohl(pkg->typeStrings));
4087 return (mError=BAD_TYPE);
4088 }
4089 if (dtohl(pkg->keyStrings) >= pkgSize) {
4090 LOGW("ResTable_package key strings at %p are past chunk size %p.",
4091 (void*)dtohl(pkg->keyStrings), (void*)pkgSize);
4092 return (mError=BAD_TYPE);
4093 }
4094 if ((dtohl(pkg->keyStrings)&0x3) != 0) {
4095 LOGW("ResTable_package key strings at %p is not on an integer boundary.",
4096 (void*)dtohl(pkg->keyStrings));
4097 return (mError=BAD_TYPE);
4098 }
4099
4100 Package* package = NULL;
4101 PackageGroup* group = NULL;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01004102 uint32_t id = idmap_id != 0 ? idmap_id : dtohl(pkg->id);
4103 // If at this point id == 0, pkg is an overlay package without a
4104 // corresponding idmap. During regular usage, overlay packages are
4105 // always loaded alongside their idmaps, but during idmap creation
4106 // the package is temporarily loaded by itself.
4107 if (id < 256) {
Dianne Hackborn78c40512009-07-06 11:07:40 -07004108
4109 package = new Package(this, header, pkg);
4110 if (package == NULL) {
4111 return (mError=NO_MEMORY);
4112 }
4113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004114 size_t idx = mPackageMap[id];
4115 if (idx == 0) {
4116 idx = mPackageGroups.size()+1;
4117
4118 char16_t tmpName[sizeof(pkg->name)/sizeof(char16_t)];
4119 strcpy16_dtoh(tmpName, pkg->name, sizeof(pkg->name)/sizeof(char16_t));
Dianne Hackborn78c40512009-07-06 11:07:40 -07004120 group = new PackageGroup(this, String16(tmpName), id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004121 if (group == NULL) {
Dianne Hackborn78c40512009-07-06 11:07:40 -07004122 delete package;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004123 return (mError=NO_MEMORY);
4124 }
4125
Dianne Hackborn78c40512009-07-06 11:07:40 -07004126 err = package->typeStrings.setTo(base+dtohl(pkg->typeStrings),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004127 header->dataEnd-(base+dtohl(pkg->typeStrings)));
4128 if (err != NO_ERROR) {
Dianne Hackborn78c40512009-07-06 11:07:40 -07004129 delete group;
4130 delete package;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004131 return (mError=err);
4132 }
Dianne Hackborn78c40512009-07-06 11:07:40 -07004133 err = package->keyStrings.setTo(base+dtohl(pkg->keyStrings),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004134 header->dataEnd-(base+dtohl(pkg->keyStrings)));
4135 if (err != NO_ERROR) {
Dianne Hackborn78c40512009-07-06 11:07:40 -07004136 delete group;
4137 delete package;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004138 return (mError=err);
4139 }
4140
4141 //printf("Adding new package id %d at index %d\n", id, idx);
4142 err = mPackageGroups.add(group);
4143 if (err < NO_ERROR) {
4144 return (mError=err);
4145 }
Dianne Hackborn78c40512009-07-06 11:07:40 -07004146 group->basePackage = package;
4147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004148 mPackageMap[id] = (uint8_t)idx;
4149 } else {
4150 group = mPackageGroups.itemAt(idx-1);
4151 if (group == NULL) {
4152 return (mError=UNKNOWN_ERROR);
4153 }
4154 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004155 err = group->packages.add(package);
4156 if (err < NO_ERROR) {
4157 return (mError=err);
4158 }
4159 } else {
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01004160 LOG_ALWAYS_FATAL("Package id out of range");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004161 return NO_ERROR;
4162 }
4163
4164
4165 // Iterate through all chunks.
4166 size_t curPackage = 0;
4167
4168 const ResChunk_header* chunk =
4169 (const ResChunk_header*)(((const uint8_t*)pkg)
4170 + dtohs(pkg->header.headerSize));
4171 const uint8_t* endPos = ((const uint8_t*)pkg) + dtohs(pkg->header.size);
4172 while (((const uint8_t*)chunk) <= (endPos-sizeof(ResChunk_header)) &&
4173 ((const uint8_t*)chunk) <= (endPos-dtohl(chunk->size))) {
4174 TABLE_NOISY(LOGV("PackageChunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n",
4175 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
4176 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header))));
4177 const size_t csize = dtohl(chunk->size);
4178 const uint16_t ctype = dtohs(chunk->type);
4179 if (ctype == RES_TABLE_TYPE_SPEC_TYPE) {
4180 const ResTable_typeSpec* typeSpec = (const ResTable_typeSpec*)(chunk);
4181 err = validate_chunk(&typeSpec->header, sizeof(*typeSpec),
4182 endPos, "ResTable_typeSpec");
4183 if (err != NO_ERROR) {
4184 return (mError=err);
4185 }
4186
4187 const size_t typeSpecSize = dtohl(typeSpec->header.size);
4188
4189 LOAD_TABLE_NOISY(printf("TypeSpec off %p: type=0x%x, headerSize=0x%x, size=%p\n",
4190 (void*)(base-(const uint8_t*)chunk),
4191 dtohs(typeSpec->header.type),
4192 dtohs(typeSpec->header.headerSize),
4193 (void*)typeSize));
4194 // look for block overrun or int overflow when multiplying by 4
4195 if ((dtohl(typeSpec->entryCount) > (INT32_MAX/sizeof(uint32_t))
4196 || dtohs(typeSpec->header.headerSize)+(sizeof(uint32_t)*dtohl(typeSpec->entryCount))
4197 > typeSpecSize)) {
4198 LOGW("ResTable_typeSpec entry index to %p extends beyond chunk end %p.",
4199 (void*)(dtohs(typeSpec->header.headerSize)
4200 +(sizeof(uint32_t)*dtohl(typeSpec->entryCount))),
4201 (void*)typeSpecSize);
4202 return (mError=BAD_TYPE);
4203 }
4204
4205 if (typeSpec->id == 0) {
4206 LOGW("ResTable_type has an id of 0.");
4207 return (mError=BAD_TYPE);
4208 }
4209
4210 while (package->types.size() < typeSpec->id) {
4211 package->types.add(NULL);
4212 }
4213 Type* t = package->types[typeSpec->id-1];
4214 if (t == NULL) {
4215 t = new Type(header, package, dtohl(typeSpec->entryCount));
4216 package->types.editItemAt(typeSpec->id-1) = t;
4217 } else if (dtohl(typeSpec->entryCount) != t->entryCount) {
4218 LOGW("ResTable_typeSpec entry count inconsistent: given %d, previously %d",
4219 (int)dtohl(typeSpec->entryCount), (int)t->entryCount);
4220 return (mError=BAD_TYPE);
4221 }
4222 t->typeSpecFlags = (const uint32_t*)(
4223 ((const uint8_t*)typeSpec) + dtohs(typeSpec->header.headerSize));
4224 t->typeSpec = typeSpec;
4225
4226 } else if (ctype == RES_TABLE_TYPE_TYPE) {
4227 const ResTable_type* type = (const ResTable_type*)(chunk);
4228 err = validate_chunk(&type->header, sizeof(*type)-sizeof(ResTable_config)+4,
4229 endPos, "ResTable_type");
4230 if (err != NO_ERROR) {
4231 return (mError=err);
4232 }
4233
4234 const size_t typeSize = dtohl(type->header.size);
4235
4236 LOAD_TABLE_NOISY(printf("Type off %p: type=0x%x, headerSize=0x%x, size=%p\n",
4237 (void*)(base-(const uint8_t*)chunk),
4238 dtohs(type->header.type),
4239 dtohs(type->header.headerSize),
4240 (void*)typeSize));
4241 if (dtohs(type->header.headerSize)+(sizeof(uint32_t)*dtohl(type->entryCount))
4242 > typeSize) {
4243 LOGW("ResTable_type entry index to %p extends beyond chunk end %p.",
4244 (void*)(dtohs(type->header.headerSize)
4245 +(sizeof(uint32_t)*dtohl(type->entryCount))),
4246 (void*)typeSize);
4247 return (mError=BAD_TYPE);
4248 }
4249 if (dtohl(type->entryCount) != 0
4250 && dtohl(type->entriesStart) > (typeSize-sizeof(ResTable_entry))) {
4251 LOGW("ResTable_type entriesStart at %p extends beyond chunk end %p.",
4252 (void*)dtohl(type->entriesStart), (void*)typeSize);
4253 return (mError=BAD_TYPE);
4254 }
4255 if (type->id == 0) {
4256 LOGW("ResTable_type has an id of 0.");
4257 return (mError=BAD_TYPE);
4258 }
4259
4260 while (package->types.size() < type->id) {
4261 package->types.add(NULL);
4262 }
4263 Type* t = package->types[type->id-1];
4264 if (t == NULL) {
4265 t = new Type(header, package, dtohl(type->entryCount));
4266 package->types.editItemAt(type->id-1) = t;
4267 } else if (dtohl(type->entryCount) != t->entryCount) {
4268 LOGW("ResTable_type entry count inconsistent: given %d, previously %d",
4269 (int)dtohl(type->entryCount), (int)t->entryCount);
4270 return (mError=BAD_TYPE);
4271 }
4272
4273 TABLE_GETENTRY(
4274 ResTable_config thisConfig;
4275 thisConfig.copyFromDtoH(type->config);
Steve Block6215d3f2012-01-04 20:05:49 +00004276 ALOGI("Adding config to type %d: imsi:%d/%d lang:%c%c cnt:%c%c "
Dianne Hackbornebff8f92011-05-12 18:07:47 -07004277 "orien:%d touch:%d density:%d key:%d inp:%d nav:%d w:%d h:%d "
Dianne Hackborn69cb8752011-05-19 18:13:32 -07004278 "swdp:%d wdp:%d hdp:%d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004279 type->id,
4280 thisConfig.mcc, thisConfig.mnc,
4281 thisConfig.language[0] ? thisConfig.language[0] : '-',
4282 thisConfig.language[1] ? thisConfig.language[1] : '-',
4283 thisConfig.country[0] ? thisConfig.country[0] : '-',
4284 thisConfig.country[1] ? thisConfig.country[1] : '-',
4285 thisConfig.orientation,
4286 thisConfig.touchscreen,
4287 thisConfig.density,
4288 thisConfig.keyboard,
4289 thisConfig.inputFlags,
4290 thisConfig.navigation,
4291 thisConfig.screenWidth,
Dianne Hackbornebff8f92011-05-12 18:07:47 -07004292 thisConfig.screenHeight,
Dianne Hackborn69cb8752011-05-19 18:13:32 -07004293 thisConfig.smallestScreenWidthDp,
Dianne Hackbornebff8f92011-05-12 18:07:47 -07004294 thisConfig.screenWidthDp,
4295 thisConfig.screenHeightDp));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004296 t->configs.add(type);
4297 } else {
4298 status_t err = validate_chunk(chunk, sizeof(ResChunk_header),
4299 endPos, "ResTable_package:unknown");
4300 if (err != NO_ERROR) {
4301 return (mError=err);
4302 }
4303 }
4304 chunk = (const ResChunk_header*)
4305 (((const uint8_t*)chunk) + csize);
4306 }
4307
4308 if (group->typeCount == 0) {
4309 group->typeCount = package->types.size();
4310 }
4311
4312 return NO_ERROR;
4313}
4314
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01004315status_t ResTable::createIdmap(const ResTable& overlay, uint32_t originalCrc, uint32_t overlayCrc,
4316 void** outData, size_t* outSize) const
4317{
4318 // see README for details on the format of map
4319 if (mPackageGroups.size() == 0) {
4320 return UNKNOWN_ERROR;
4321 }
4322 if (mPackageGroups[0]->packages.size() == 0) {
4323 return UNKNOWN_ERROR;
4324 }
4325
4326 Vector<Vector<uint32_t> > map;
4327 const PackageGroup* pg = mPackageGroups[0];
4328 const Package* pkg = pg->packages[0];
4329 size_t typeCount = pkg->types.size();
4330 // starting size is header + first item (number of types in map)
4331 *outSize = (IDMAP_HEADER_SIZE + 1) * sizeof(uint32_t);
4332 const String16 overlayPackage(overlay.mPackageGroups[0]->packages[0]->package->name);
4333 const uint32_t pkg_id = pkg->package->id << 24;
4334
4335 for (size_t typeIndex = 0; typeIndex < typeCount; ++typeIndex) {
4336 ssize_t offset = -1;
4337 const Type* typeConfigs = pkg->getType(typeIndex);
4338 ssize_t mapIndex = map.add();
4339 if (mapIndex < 0) {
4340 return NO_MEMORY;
4341 }
4342 Vector<uint32_t>& vector = map.editItemAt(mapIndex);
4343 for (size_t entryIndex = 0; entryIndex < typeConfigs->entryCount; ++entryIndex) {
4344 uint32_t resID = (0xff000000 & ((pkg->package->id)<<24))
4345 | (0x00ff0000 & ((typeIndex+1)<<16))
4346 | (0x0000ffff & (entryIndex));
4347 resource_name resName;
4348 if (!this->getResourceName(resID, &resName)) {
MÃ¥rten Kongstadfcaba142011-05-19 16:02:35 +02004349 LOGW("idmap: resource 0x%08x has spec but lacks values, skipping\n", resID);
4350 continue;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01004351 }
4352
4353 const String16 overlayType(resName.type, resName.typeLen);
4354 const String16 overlayName(resName.name, resName.nameLen);
4355 uint32_t overlayResID = overlay.identifierForName(overlayName.string(),
4356 overlayName.size(),
4357 overlayType.string(),
4358 overlayType.size(),
4359 overlayPackage.string(),
4360 overlayPackage.size());
4361 if (overlayResID != 0) {
4362 // overlay package has package ID == 0, use original package's ID instead
4363 overlayResID |= pkg_id;
4364 }
4365 vector.push(overlayResID);
4366 if (overlayResID != 0 && offset == -1) {
4367 offset = Res_GETENTRY(resID);
4368 }
4369#if 0
4370 if (overlayResID != 0) {
Steve Block5baa3a62011-12-20 16:23:08 +00004371 ALOGD("%s/%s 0x%08x -> 0x%08x\n",
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01004372 String8(String16(resName.type)).string(),
4373 String8(String16(resName.name)).string(),
4374 resID, overlayResID);
4375 }
4376#endif
4377 }
4378
4379 if (offset != -1) {
4380 // shave off leading and trailing entries which lack overlay values
4381 vector.removeItemsAt(0, offset);
4382 vector.insertAt((uint32_t)offset, 0, 1);
4383 while (vector.top() == 0) {
4384 vector.pop();
4385 }
4386 // reserve space for number and offset of entries, and the actual entries
4387 *outSize += (2 + vector.size()) * sizeof(uint32_t);
4388 } else {
4389 // no entries of current type defined in overlay package
4390 vector.clear();
4391 // reserve space for type offset
4392 *outSize += 1 * sizeof(uint32_t);
4393 }
4394 }
4395
4396 if ((*outData = malloc(*outSize)) == NULL) {
4397 return NO_MEMORY;
4398 }
4399 uint32_t* data = (uint32_t*)*outData;
4400 *data++ = htodl(IDMAP_MAGIC);
4401 *data++ = htodl(originalCrc);
4402 *data++ = htodl(overlayCrc);
4403 const size_t mapSize = map.size();
4404 *data++ = htodl(mapSize);
4405 size_t offset = mapSize;
4406 for (size_t i = 0; i < mapSize; ++i) {
4407 const Vector<uint32_t>& vector = map.itemAt(i);
4408 const size_t N = vector.size();
4409 if (N == 0) {
4410 *data++ = htodl(0);
4411 } else {
4412 offset++;
4413 *data++ = htodl(offset);
4414 offset += N;
4415 }
4416 }
4417 for (size_t i = 0; i < mapSize; ++i) {
4418 const Vector<uint32_t>& vector = map.itemAt(i);
4419 const size_t N = vector.size();
4420 if (N == 0) {
4421 continue;
4422 }
4423 *data++ = htodl(N - 1); // do not count the offset (which is vector's first element)
4424 for (size_t j = 0; j < N; ++j) {
4425 const uint32_t& overlayResID = vector.itemAt(j);
4426 *data++ = htodl(overlayResID);
4427 }
4428 }
4429
4430 return NO_ERROR;
4431}
4432
4433bool ResTable::getIdmapInfo(const void* idmap, size_t sizeBytes,
4434 uint32_t* pOriginalCrc, uint32_t* pOverlayCrc)
4435{
4436 const uint32_t* map = (const uint32_t*)idmap;
4437 if (!assertIdmapHeader(map, sizeBytes)) {
4438 return false;
4439 }
4440 *pOriginalCrc = map[1];
4441 *pOverlayCrc = map[2];
4442 return true;
4443}
4444
4445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004446#ifndef HAVE_ANDROID_OS
4447#define CHAR16_TO_CSTR(c16, len) (String8(String16(c16,len)).string())
4448
4449#define CHAR16_ARRAY_EQ(constant, var, len) \
4450 ((len == (sizeof(constant)/sizeof(constant[0]))) && (0 == memcmp((var), (constant), (len))))
4451
Dianne Hackborne17086b2009-06-19 15:13:28 -07004452void print_complex(uint32_t complex, bool isFraction)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004453{
Dianne Hackborne17086b2009-06-19 15:13:28 -07004454 const float MANTISSA_MULT =
4455 1.0f / (1<<Res_value::COMPLEX_MANTISSA_SHIFT);
4456 const float RADIX_MULTS[] = {
4457 1.0f*MANTISSA_MULT, 1.0f/(1<<7)*MANTISSA_MULT,
4458 1.0f/(1<<15)*MANTISSA_MULT, 1.0f/(1<<23)*MANTISSA_MULT
4459 };
4460
4461 float value = (complex&(Res_value::COMPLEX_MANTISSA_MASK
4462 <<Res_value::COMPLEX_MANTISSA_SHIFT))
4463 * RADIX_MULTS[(complex>>Res_value::COMPLEX_RADIX_SHIFT)
4464 & Res_value::COMPLEX_RADIX_MASK];
4465 printf("%f", value);
4466
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004467 if (!isFraction) {
Dianne Hackborne17086b2009-06-19 15:13:28 -07004468 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
4469 case Res_value::COMPLEX_UNIT_PX: printf("px"); break;
4470 case Res_value::COMPLEX_UNIT_DIP: printf("dp"); break;
4471 case Res_value::COMPLEX_UNIT_SP: printf("sp"); break;
4472 case Res_value::COMPLEX_UNIT_PT: printf("pt"); break;
4473 case Res_value::COMPLEX_UNIT_IN: printf("in"); break;
4474 case Res_value::COMPLEX_UNIT_MM: printf("mm"); break;
4475 default: printf(" (unknown unit)"); break;
4476 }
4477 } else {
4478 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
4479 case Res_value::COMPLEX_UNIT_FRACTION: printf("%%"); break;
4480 case Res_value::COMPLEX_UNIT_FRACTION_PARENT: printf("%%p"); break;
4481 default: printf(" (unknown unit)"); break;
4482 }
4483 }
4484}
4485
Shachar Shemesh9872bf42010-12-20 17:38:33 +02004486// Normalize a string for output
4487String8 ResTable::normalizeForOutput( const char *input )
4488{
4489 String8 ret;
4490 char buff[2];
4491 buff[1] = '\0';
4492
4493 while (*input != '\0') {
4494 switch (*input) {
4495 // All interesting characters are in the ASCII zone, so we are making our own lives
4496 // easier by scanning the string one byte at a time.
4497 case '\\':
4498 ret += "\\\\";
4499 break;
4500 case '\n':
4501 ret += "\\n";
4502 break;
4503 case '"':
4504 ret += "\\\"";
4505 break;
4506 default:
4507 buff[0] = *input;
4508 ret += buff;
4509 break;
4510 }
4511
4512 input++;
4513 }
4514
4515 return ret;
4516}
4517
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004518void ResTable::print_value(const Package* pkg, const Res_value& value) const
4519{
4520 if (value.dataType == Res_value::TYPE_NULL) {
4521 printf("(null)\n");
4522 } else if (value.dataType == Res_value::TYPE_REFERENCE) {
4523 printf("(reference) 0x%08x\n", value.data);
4524 } else if (value.dataType == Res_value::TYPE_ATTRIBUTE) {
4525 printf("(attribute) 0x%08x\n", value.data);
4526 } else if (value.dataType == Res_value::TYPE_STRING) {
4527 size_t len;
Kenny Root780d2a12010-02-22 22:36:26 -08004528 const char* str8 = pkg->header->values.string8At(
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004529 value.data, &len);
Kenny Root780d2a12010-02-22 22:36:26 -08004530 if (str8 != NULL) {
Shachar Shemesh9872bf42010-12-20 17:38:33 +02004531 printf("(string8) \"%s\"\n", normalizeForOutput(str8).string());
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004532 } else {
Kenny Root780d2a12010-02-22 22:36:26 -08004533 const char16_t* str16 = pkg->header->values.stringAt(
4534 value.data, &len);
4535 if (str16 != NULL) {
4536 printf("(string16) \"%s\"\n",
Shachar Shemesh9872bf42010-12-20 17:38:33 +02004537 normalizeForOutput(String8(str16, len).string()).string());
Kenny Root780d2a12010-02-22 22:36:26 -08004538 } else {
4539 printf("(string) null\n");
4540 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004541 }
4542 } else if (value.dataType == Res_value::TYPE_FLOAT) {
4543 printf("(float) %g\n", *(const float*)&value.data);
4544 } else if (value.dataType == Res_value::TYPE_DIMENSION) {
4545 printf("(dimension) ");
4546 print_complex(value.data, false);
4547 printf("\n");
4548 } else if (value.dataType == Res_value::TYPE_FRACTION) {
4549 printf("(fraction) ");
4550 print_complex(value.data, true);
4551 printf("\n");
4552 } else if (value.dataType >= Res_value::TYPE_FIRST_COLOR_INT
4553 || value.dataType <= Res_value::TYPE_LAST_COLOR_INT) {
4554 printf("(color) #%08x\n", value.data);
4555 } else if (value.dataType == Res_value::TYPE_INT_BOOLEAN) {
4556 printf("(boolean) %s\n", value.data ? "true" : "false");
4557 } else if (value.dataType >= Res_value::TYPE_FIRST_INT
4558 || value.dataType <= Res_value::TYPE_LAST_INT) {
4559 printf("(int) 0x%08x or %d\n", value.data, value.data);
4560 } else {
4561 printf("(unknown type) t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)\n",
4562 (int)value.dataType, (int)value.data,
4563 (int)value.size, (int)value.res0);
4564 }
4565}
4566
Dianne Hackborne17086b2009-06-19 15:13:28 -07004567void ResTable::print(bool inclValues) const
4568{
4569 if (mError != 0) {
4570 printf("mError=0x%x (%s)\n", mError, strerror(mError));
4571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004572#if 0
4573 printf("mParams=%c%c-%c%c,\n",
4574 mParams.language[0], mParams.language[1],
4575 mParams.country[0], mParams.country[1]);
4576#endif
4577 size_t pgCount = mPackageGroups.size();
4578 printf("Package Groups (%d)\n", (int)pgCount);
4579 for (size_t pgIndex=0; pgIndex<pgCount; pgIndex++) {
4580 const PackageGroup* pg = mPackageGroups[pgIndex];
4581 printf("Package Group %d id=%d packageCount=%d name=%s\n",
4582 (int)pgIndex, pg->id, (int)pg->packages.size(),
4583 String8(pg->name).string());
4584
4585 size_t pkgCount = pg->packages.size();
4586 for (size_t pkgIndex=0; pkgIndex<pkgCount; pkgIndex++) {
4587 const Package* pkg = pg->packages[pkgIndex];
4588 size_t typeCount = pkg->types.size();
4589 printf(" Package %d id=%d name=%s typeCount=%d\n", (int)pkgIndex,
4590 pkg->package->id, String8(String16(pkg->package->name)).string(),
4591 (int)typeCount);
4592 for (size_t typeIndex=0; typeIndex<typeCount; typeIndex++) {
4593 const Type* typeConfigs = pkg->getType(typeIndex);
4594 if (typeConfigs == NULL) {
4595 printf(" type %d NULL\n", (int)typeIndex);
4596 continue;
4597 }
4598 const size_t NTC = typeConfigs->configs.size();
4599 printf(" type %d configCount=%d entryCount=%d\n",
4600 (int)typeIndex, (int)NTC, (int)typeConfigs->entryCount);
4601 if (typeConfigs->typeSpecFlags != NULL) {
4602 for (size_t entryIndex=0; entryIndex<typeConfigs->entryCount; entryIndex++) {
4603 uint32_t resID = (0xff000000 & ((pkg->package->id)<<24))
4604 | (0x00ff0000 & ((typeIndex+1)<<16))
4605 | (0x0000ffff & (entryIndex));
4606 resource_name resName;
Kenny Root33791952010-06-08 10:16:48 -07004607 if (this->getResourceName(resID, &resName)) {
4608 printf(" spec resource 0x%08x %s:%s/%s: flags=0x%08x\n",
4609 resID,
4610 CHAR16_TO_CSTR(resName.package, resName.packageLen),
4611 CHAR16_TO_CSTR(resName.type, resName.typeLen),
4612 CHAR16_TO_CSTR(resName.name, resName.nameLen),
4613 dtohl(typeConfigs->typeSpecFlags[entryIndex]));
4614 } else {
4615 printf(" INVALID TYPE CONFIG FOR RESOURCE 0x%08x\n", resID);
4616 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004617 }
4618 }
4619 for (size_t configIndex=0; configIndex<NTC; configIndex++) {
4620 const ResTable_type* type = typeConfigs->configs[configIndex];
4621 if ((((uint64_t)type)&0x3) != 0) {
4622 printf(" NON-INTEGER ResTable_type ADDRESS: %p\n", type);
4623 continue;
4624 }
Dianne Hackborna53b8282009-07-17 11:13:48 -07004625 char density[16];
4626 uint16_t dval = dtohs(type->config.density);
4627 if (dval == ResTable_config::DENSITY_DEFAULT) {
4628 strcpy(density, "def");
4629 } else if (dval == ResTable_config::DENSITY_NONE) {
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07004630 strcpy(density, "no");
Dianne Hackborna53b8282009-07-17 11:13:48 -07004631 } else {
4632 sprintf(density, "%d", (int)dval);
4633 }
Dianne Hackbornef05e072010-03-01 17:43:39 -08004634 printf(" config %d", (int)configIndex);
4635 if (type->config.mcc != 0) {
4636 printf(" mcc=%d", dtohs(type->config.mcc));
4637 }
4638 if (type->config.mnc != 0) {
4639 printf(" mnc=%d", dtohs(type->config.mnc));
4640 }
4641 if (type->config.locale != 0) {
4642 printf(" lang=%c%c cnt=%c%c",
4643 type->config.language[0] ? type->config.language[0] : '-',
4644 type->config.language[1] ? type->config.language[1] : '-',
4645 type->config.country[0] ? type->config.country[0] : '-',
4646 type->config.country[1] ? type->config.country[1] : '-');
4647 }
4648 if (type->config.screenLayout != 0) {
4649 printf(" sz=%d",
4650 type->config.screenLayout&ResTable_config::MASK_SCREENSIZE);
4651 switch (type->config.screenLayout&ResTable_config::MASK_SCREENSIZE) {
4652 case ResTable_config::SCREENSIZE_SMALL:
4653 printf(" (small)");
4654 break;
4655 case ResTable_config::SCREENSIZE_NORMAL:
4656 printf(" (normal)");
4657 break;
4658 case ResTable_config::SCREENSIZE_LARGE:
4659 printf(" (large)");
4660 break;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07004661 case ResTable_config::SCREENSIZE_XLARGE:
4662 printf(" (xlarge)");
4663 break;
Dianne Hackbornef05e072010-03-01 17:43:39 -08004664 }
4665 printf(" lng=%d",
4666 type->config.screenLayout&ResTable_config::MASK_SCREENLONG);
4667 switch (type->config.screenLayout&ResTable_config::MASK_SCREENLONG) {
4668 case ResTable_config::SCREENLONG_NO:
4669 printf(" (notlong)");
4670 break;
4671 case ResTable_config::SCREENLONG_YES:
4672 printf(" (long)");
4673 break;
4674 }
4675 }
4676 if (type->config.orientation != 0) {
4677 printf(" orient=%d", type->config.orientation);
4678 switch (type->config.orientation) {
4679 case ResTable_config::ORIENTATION_PORT:
4680 printf(" (port)");
4681 break;
4682 case ResTable_config::ORIENTATION_LAND:
4683 printf(" (land)");
4684 break;
4685 case ResTable_config::ORIENTATION_SQUARE:
4686 printf(" (square)");
4687 break;
4688 }
4689 }
4690 if (type->config.uiMode != 0) {
4691 printf(" type=%d",
4692 type->config.uiMode&ResTable_config::MASK_UI_MODE_TYPE);
4693 switch (type->config.uiMode&ResTable_config::MASK_UI_MODE_TYPE) {
4694 case ResTable_config::UI_MODE_TYPE_NORMAL:
4695 printf(" (normal)");
4696 break;
4697 case ResTable_config::UI_MODE_TYPE_CAR:
4698 printf(" (car)");
4699 break;
4700 }
4701 printf(" night=%d",
4702 type->config.uiMode&ResTable_config::MASK_UI_MODE_NIGHT);
4703 switch (type->config.uiMode&ResTable_config::MASK_UI_MODE_NIGHT) {
4704 case ResTable_config::UI_MODE_NIGHT_NO:
4705 printf(" (no)");
4706 break;
4707 case ResTable_config::UI_MODE_NIGHT_YES:
4708 printf(" (yes)");
4709 break;
4710 }
4711 }
4712 if (dval != 0) {
4713 printf(" density=%s", density);
4714 }
4715 if (type->config.touchscreen != 0) {
4716 printf(" touch=%d", type->config.touchscreen);
4717 switch (type->config.touchscreen) {
4718 case ResTable_config::TOUCHSCREEN_NOTOUCH:
4719 printf(" (notouch)");
4720 break;
4721 case ResTable_config::TOUCHSCREEN_STYLUS:
4722 printf(" (stylus)");
4723 break;
4724 case ResTable_config::TOUCHSCREEN_FINGER:
4725 printf(" (finger)");
4726 break;
4727 }
4728 }
4729 if (type->config.inputFlags != 0) {
4730 printf(" keyhid=%d", type->config.inputFlags&ResTable_config::MASK_KEYSHIDDEN);
4731 switch (type->config.inputFlags&ResTable_config::MASK_KEYSHIDDEN) {
4732 case ResTable_config::KEYSHIDDEN_NO:
4733 printf(" (no)");
4734 break;
4735 case ResTable_config::KEYSHIDDEN_YES:
4736 printf(" (yes)");
4737 break;
4738 case ResTable_config::KEYSHIDDEN_SOFT:
4739 printf(" (soft)");
4740 break;
4741 }
4742 printf(" navhid=%d", type->config.inputFlags&ResTable_config::MASK_NAVHIDDEN);
4743 switch (type->config.inputFlags&ResTable_config::MASK_NAVHIDDEN) {
4744 case ResTable_config::NAVHIDDEN_NO:
4745 printf(" (no)");
4746 break;
4747 case ResTable_config::NAVHIDDEN_YES:
4748 printf(" (yes)");
4749 break;
4750 }
4751 }
4752 if (type->config.keyboard != 0) {
4753 printf(" kbd=%d", type->config.keyboard);
4754 switch (type->config.keyboard) {
4755 case ResTable_config::KEYBOARD_NOKEYS:
4756 printf(" (nokeys)");
4757 break;
4758 case ResTable_config::KEYBOARD_QWERTY:
4759 printf(" (qwerty)");
4760 break;
4761 case ResTable_config::KEYBOARD_12KEY:
4762 printf(" (12key)");
4763 break;
4764 }
4765 }
4766 if (type->config.navigation != 0) {
4767 printf(" nav=%d", type->config.navigation);
4768 switch (type->config.navigation) {
4769 case ResTable_config::NAVIGATION_NONAV:
4770 printf(" (nonav)");
4771 break;
4772 case ResTable_config::NAVIGATION_DPAD:
4773 printf(" (dpad)");
4774 break;
4775 case ResTable_config::NAVIGATION_TRACKBALL:
4776 printf(" (trackball)");
4777 break;
4778 case ResTable_config::NAVIGATION_WHEEL:
4779 printf(" (wheel)");
4780 break;
4781 }
4782 }
4783 if (type->config.screenWidth != 0) {
4784 printf(" w=%d", dtohs(type->config.screenWidth));
4785 }
4786 if (type->config.screenHeight != 0) {
4787 printf(" h=%d", dtohs(type->config.screenHeight));
4788 }
Dianne Hackborn69cb8752011-05-19 18:13:32 -07004789 if (type->config.smallestScreenWidthDp != 0) {
4790 printf(" swdp=%d", dtohs(type->config.smallestScreenWidthDp));
4791 }
Dianne Hackbornebff8f92011-05-12 18:07:47 -07004792 if (type->config.screenWidthDp != 0) {
4793 printf(" wdp=%d", dtohs(type->config.screenWidthDp));
4794 }
4795 if (type->config.screenHeightDp != 0) {
4796 printf(" hdp=%d", dtohs(type->config.screenHeightDp));
4797 }
Dianne Hackbornef05e072010-03-01 17:43:39 -08004798 if (type->config.sdkVersion != 0) {
4799 printf(" sdk=%d", dtohs(type->config.sdkVersion));
4800 }
4801 if (type->config.minorVersion != 0) {
4802 printf(" mver=%d", dtohs(type->config.minorVersion));
4803 }
4804 printf("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004805 size_t entryCount = dtohl(type->entryCount);
4806 uint32_t entriesStart = dtohl(type->entriesStart);
4807 if ((entriesStart&0x3) != 0) {
4808 printf(" NON-INTEGER ResTable_type entriesStart OFFSET: %p\n", (void*)entriesStart);
4809 continue;
4810 }
4811 uint32_t typeSize = dtohl(type->header.size);
4812 if ((typeSize&0x3) != 0) {
4813 printf(" NON-INTEGER ResTable_type header.size: %p\n", (void*)typeSize);
4814 continue;
4815 }
4816 for (size_t entryIndex=0; entryIndex<entryCount; entryIndex++) {
4817
4818 const uint8_t* const end = ((const uint8_t*)type)
4819 + dtohl(type->header.size);
4820 const uint32_t* const eindex = (const uint32_t*)
4821 (((const uint8_t*)type) + dtohs(type->header.headerSize));
4822
4823 uint32_t thisOffset = dtohl(eindex[entryIndex]);
4824 if (thisOffset == ResTable_type::NO_ENTRY) {
4825 continue;
4826 }
4827
4828 uint32_t resID = (0xff000000 & ((pkg->package->id)<<24))
4829 | (0x00ff0000 & ((typeIndex+1)<<16))
4830 | (0x0000ffff & (entryIndex));
4831 resource_name resName;
Kenny Root33791952010-06-08 10:16:48 -07004832 if (this->getResourceName(resID, &resName)) {
4833 printf(" resource 0x%08x %s:%s/%s: ", resID,
4834 CHAR16_TO_CSTR(resName.package, resName.packageLen),
4835 CHAR16_TO_CSTR(resName.type, resName.typeLen),
4836 CHAR16_TO_CSTR(resName.name, resName.nameLen));
4837 } else {
4838 printf(" INVALID RESOURCE 0x%08x: ", resID);
4839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004840 if ((thisOffset&0x3) != 0) {
4841 printf("NON-INTEGER OFFSET: %p\n", (void*)thisOffset);
4842 continue;
4843 }
4844 if ((thisOffset+sizeof(ResTable_entry)) > typeSize) {
4845 printf("OFFSET OUT OF BOUNDS: %p+%p (size is %p)\n",
4846 (void*)entriesStart, (void*)thisOffset,
4847 (void*)typeSize);
4848 continue;
4849 }
4850
4851 const ResTable_entry* ent = (const ResTable_entry*)
4852 (((const uint8_t*)type) + entriesStart + thisOffset);
4853 if (((entriesStart + thisOffset)&0x3) != 0) {
4854 printf("NON-INTEGER ResTable_entry OFFSET: %p\n",
4855 (void*)(entriesStart + thisOffset));
4856 continue;
4857 }
Dianne Hackborne17086b2009-06-19 15:13:28 -07004858
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004859 uint16_t esize = dtohs(ent->size);
4860 if ((esize&0x3) != 0) {
4861 printf("NON-INTEGER ResTable_entry SIZE: %p\n", (void*)esize);
4862 continue;
4863 }
4864 if ((thisOffset+esize) > typeSize) {
4865 printf("ResTable_entry OUT OF BOUNDS: %p+%p+%p (size is %p)\n",
4866 (void*)entriesStart, (void*)thisOffset,
4867 (void*)esize, (void*)typeSize);
4868 continue;
4869 }
4870
4871 const Res_value* valuePtr = NULL;
4872 const ResTable_map_entry* bagPtr = NULL;
4873 Res_value value;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004874 if ((dtohs(ent->flags)&ResTable_entry::FLAG_COMPLEX) != 0) {
4875 printf("<bag>");
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004876 bagPtr = (const ResTable_map_entry*)ent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004877 } else {
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004878 valuePtr = (const Res_value*)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004879 (((const uint8_t*)ent) + esize);
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004880 value.copyFrom_dtoh(*valuePtr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004881 printf("t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)",
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004882 (int)value.dataType, (int)value.data,
4883 (int)value.size, (int)value.res0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004884 }
4885
4886 if ((dtohs(ent->flags)&ResTable_entry::FLAG_PUBLIC) != 0) {
4887 printf(" (PUBLIC)");
4888 }
4889 printf("\n");
Dianne Hackborne17086b2009-06-19 15:13:28 -07004890
4891 if (inclValues) {
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004892 if (valuePtr != NULL) {
Dianne Hackborne17086b2009-06-19 15:13:28 -07004893 printf(" ");
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004894 print_value(pkg, value);
4895 } else if (bagPtr != NULL) {
4896 const int N = dtohl(bagPtr->count);
Kenny Root06983bc2010-06-08 12:45:31 -07004897 const uint8_t* baseMapPtr = (const uint8_t*)ent;
4898 size_t mapOffset = esize;
4899 const ResTable_map* mapPtr = (ResTable_map*)(baseMapPtr+mapOffset);
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004900 printf(" Parent=0x%08x, Count=%d\n",
4901 dtohl(bagPtr->parent.ident), N);
Kenny Root06983bc2010-06-08 12:45:31 -07004902 for (int i=0; i<N && mapOffset < (typeSize-sizeof(ResTable_map)); i++) {
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004903 printf(" #%i (Key=0x%08x): ",
4904 i, dtohl(mapPtr->name.ident));
4905 value.copyFrom_dtoh(mapPtr->value);
4906 print_value(pkg, value);
4907 const size_t size = dtohs(mapPtr->value.size);
Kenny Root06983bc2010-06-08 12:45:31 -07004908 mapOffset += size + sizeof(*mapPtr)-sizeof(mapPtr->value);
4909 mapPtr = (ResTable_map*)(baseMapPtr+mapOffset);
Dianne Hackborne17086b2009-06-19 15:13:28 -07004910 }
4911 }
4912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004913 }
4914 }
4915 }
4916 }
4917 }
4918}
4919
4920#endif // HAVE_ANDROID_OS
4921
4922} // namespace android