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