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