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