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 46 namespace 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 69 static 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. 77 inline 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. 84 static 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 95 static 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 127 inline 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 135 void 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 152 void 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 169 size_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 181 void* 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 190 void 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 204 static 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 220 static 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 234 static 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 282 static 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 295 Res_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 309 ResStringPool::ResStringPool() 310 : mError(NO_INIT), mOwnedData(NULL), mHeader(NULL), mCache(NULL) 311 { 312 } 313 314 ResStringPool::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 320 ResStringPool::~ResStringPool() 321 { 322 uninit(); 323 } 324 325 status_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 499 status_t ResStringPool::getError() const 500 { 501 return mError; 502 } 503 504 void 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 */ 533 static inline size_t 534 decodeLength(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 */ 555 static inline size_t 556 decodeLength(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 567 const 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 650 const 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 677 const 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 687 const ResStringPool_span* ResStringPool::styleAt(const ResStringPool_ref& ref) const 688 { 689 return styleAt(ref.index); 690 } 691 692 const 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 707 ssize_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 820 size_t ResStringPool::size() const 821 { 822 return (mError == NO_ERROR) ? mHeader->stringCount : 0; 823 } 824 825 size_t ResStringPool::styleCount() const 826 { 827 return (mError == NO_ERROR) ? mHeader->styleCount : 0; 828 } 829 830 size_t ResStringPool::bytes() const 831 { 832 return (mError == NO_ERROR) ? mHeader->header.size : 0; 833 } 834 835 bool ResStringPool::isSorted() const 836 { 837 return (mHeader->flags&ResStringPool_header::SORTED_FLAG)!=0; 838 } 839 840 bool ResStringPool::isUTF8() const 841 { 842 return (mHeader->flags&ResStringPool_header::UTF8_FLAG)!=0; 843 } 844 845 // -------------------------------------------------------------------- 846 // -------------------------------------------------------------------- 847 // -------------------------------------------------------------------- 848 849 ResXMLParser::ResXMLParser(const ResXMLTree& tree) 850 : mTree(tree), mEventCode(BAD_DOCUMENT) 851 { 852 } 853 854 void ResXMLParser::restart() 855 { 856 mCurNode = NULL; 857 mEventCode = mTree.mError == NO_ERROR ? START_DOCUMENT : BAD_DOCUMENT; 858 } 859 const ResStringPool& ResXMLParser::getStrings() const 860 { 861 return mTree.mStrings; 862 } 863 864 ResXMLParser::event_code_t ResXMLParser::getEventType() const 865 { 866 return mEventCode; 867 } 868 869 ResXMLParser::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 881 int32_t ResXMLParser::getCommentID() const 882 { 883 return mCurNode != NULL ? dtohl(mCurNode->comment.index) : -1; 884 } 885 886 const 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 892 uint32_t ResXMLParser::getLineNumber() const 893 { 894 return mCurNode != NULL ? dtohl(mCurNode->lineNumber) : -1; 895 } 896 897 int32_t ResXMLParser::getTextID() const 898 { 899 if (mEventCode == TEXT) { 900 return dtohl(((const ResXMLTree_cdataExt*)mCurExt)->data.index); 901 } 902 return -1; 903 } 904 905 const 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 911 ssize_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 920 int32_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 928 const 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 935 int32_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 943 const 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 950 int32_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 961 const 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 967 int32_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 978 const 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 984 size_t ResXMLParser::getAttributeCount() const 985 { 986 if (mEventCode == START_TAG) { 987 return dtohs(((const ResXMLTree_attrExt*)mCurExt)->attributeCount); 988 } 989 return 0; 990 } 991 992 int32_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 1007 const 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 1015 const 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 1023 int32_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 1038 const 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 1046 const 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 1054 uint32_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 1063 int32_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 1078 const 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 1085 int32_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 1100 int32_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 1115 ssize_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 1131 ssize_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 1139 ssize_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 1212 ssize_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 1221 ssize_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 1230 ssize_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 1239 ResXMLParser::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 1302 void ResXMLParser::getPosition(ResXMLParser::ResXMLPosition* pos) const 1303 { 1304 pos->eventCode = mEventCode; 1305 pos->curNode = mCurNode; 1306 pos->curExt = mCurExt; 1307 } 1308 1309 void ResXMLParser::setPosition(const ResXMLParser::ResXMLPosition& pos) 1310 { 1311 mEventCode = pos.eventCode; 1312 mCurNode = pos.curNode; 1313 mCurExt = pos.curExt; 1314 } 1315 1316 1317 // -------------------------------------------------------------------- 1318 1319 static volatile int32_t gCount = 0; 1320 1321 ResXMLTree::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 1329 ResXMLTree::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 1337 ResXMLTree::~ResXMLTree() 1338 { 1339 //ALOGI("Destroying ResXMLTree in %p #%d\n", this, android_atomic_dec(&gCount)-1); 1340 uninit(); 1341 } 1342 1343 status_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 1431 done: 1432 restart(); 1433 return mError; 1434 } 1435 1436 status_t ResXMLTree::getError() const 1437 { 1438 return mError; 1439 } 1440 1441 void ResXMLTree::uninit() 1442 { 1443 mError = NO_INIT; 1444 mStrings.uninit(); 1445 if (mOwnedData) { 1446 free(mOwnedData); 1447 mOwnedData = NULL; 1448 } 1449 restart(); 1450 } 1451 1452 status_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 1532 void 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 1542 void 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 1557 void 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 1571 int 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 1594 int 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 1655 int 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 1677 bool 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 1814 bool 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 2047 bool 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 2169 void 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 2182 String8 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 default: 2297 res.appendFormat("uiModeType=%d", 2298 dtohs(screenLayout&ResTable_config::MASK_UI_MODE_TYPE)); 2299 break; 2300 } 2301 } 2302 if ((uiMode&MASK_UI_MODE_NIGHT) != 0) { 2303 if (res.size() > 0) res.append("-"); 2304 switch (uiMode&ResTable_config::MASK_UI_MODE_NIGHT) { 2305 case ResTable_config::UI_MODE_NIGHT_NO: 2306 res.append("notnight"); 2307 break; 2308 case ResTable_config::UI_MODE_NIGHT_YES: 2309 res.append("night"); 2310 break; 2311 default: 2312 res.appendFormat("uiModeNight=%d", 2313 dtohs(uiMode&MASK_UI_MODE_NIGHT)); 2314 break; 2315 } 2316 } 2317 if (density != DENSITY_DEFAULT) { 2318 if (res.size() > 0) res.append("-"); 2319 switch (density) { 2320 case ResTable_config::DENSITY_LOW: 2321 res.append("ldpi"); 2322 break; 2323 case ResTable_config::DENSITY_MEDIUM: 2324 res.append("mdpi"); 2325 break; 2326 case ResTable_config::DENSITY_TV: 2327 res.append("tvdpi"); 2328 break; 2329 case ResTable_config::DENSITY_HIGH: 2330 res.append("hdpi"); 2331 break; 2332 case ResTable_config::DENSITY_XHIGH: 2333 res.append("xhdpi"); 2334 break; 2335 case ResTable_config::DENSITY_XXHIGH: 2336 res.append("xxhdpi"); 2337 break; 2338 case ResTable_config::DENSITY_NONE: 2339 res.append("nodpi"); 2340 break; 2341 default: 2342 res.appendFormat("%ddpi", dtohs(density)); 2343 break; 2344 } 2345 } 2346 if (touchscreen != TOUCHSCREEN_ANY) { 2347 if (res.size() > 0) res.append("-"); 2348 switch (touchscreen) { 2349 case ResTable_config::TOUCHSCREEN_NOTOUCH: 2350 res.append("notouch"); 2351 break; 2352 case ResTable_config::TOUCHSCREEN_FINGER: 2353 res.append("finger"); 2354 break; 2355 case ResTable_config::TOUCHSCREEN_STYLUS: 2356 res.append("stylus"); 2357 break; 2358 default: 2359 res.appendFormat("touchscreen=%d", dtohs(touchscreen)); 2360 break; 2361 } 2362 } 2363 if (keyboard != KEYBOARD_ANY) { 2364 if (res.size() > 0) res.append("-"); 2365 switch (keyboard) { 2366 case ResTable_config::KEYBOARD_NOKEYS: 2367 res.append("nokeys"); 2368 break; 2369 case ResTable_config::KEYBOARD_QWERTY: 2370 res.append("qwerty"); 2371 break; 2372 case ResTable_config::KEYBOARD_12KEY: 2373 res.append("12key"); 2374 break; 2375 default: 2376 res.appendFormat("keyboard=%d", dtohs(keyboard)); 2377 break; 2378 } 2379 } 2380 if ((inputFlags&MASK_KEYSHIDDEN) != 0) { 2381 if (res.size() > 0) res.append("-"); 2382 switch (inputFlags&MASK_KEYSHIDDEN) { 2383 case ResTable_config::KEYSHIDDEN_NO: 2384 res.append("keysexposed"); 2385 break; 2386 case ResTable_config::KEYSHIDDEN_YES: 2387 res.append("keyshidden"); 2388 break; 2389 case ResTable_config::KEYSHIDDEN_SOFT: 2390 res.append("keyssoft"); 2391 break; 2392 } 2393 } 2394 if (navigation != NAVIGATION_ANY) { 2395 if (res.size() > 0) res.append("-"); 2396 switch (navigation) { 2397 case ResTable_config::NAVIGATION_NONAV: 2398 res.append("nonav"); 2399 break; 2400 case ResTable_config::NAVIGATION_DPAD: 2401 res.append("dpad"); 2402 break; 2403 case ResTable_config::NAVIGATION_TRACKBALL: 2404 res.append("trackball"); 2405 break; 2406 case ResTable_config::NAVIGATION_WHEEL: 2407 res.append("wheel"); 2408 break; 2409 default: 2410 res.appendFormat("navigation=%d", dtohs(navigation)); 2411 break; 2412 } 2413 } 2414 if ((inputFlags&MASK_NAVHIDDEN) != 0) { 2415 if (res.size() > 0) res.append("-"); 2416 switch (inputFlags&MASK_NAVHIDDEN) { 2417 case ResTable_config::NAVHIDDEN_NO: 2418 res.append("navsexposed"); 2419 break; 2420 case ResTable_config::NAVHIDDEN_YES: 2421 res.append("navhidden"); 2422 break; 2423 default: 2424 res.appendFormat("inputFlagsNavHidden=%d", 2425 dtohs(inputFlags&MASK_NAVHIDDEN)); 2426 break; 2427 } 2428 } 2429 if (screenSize != 0) { 2430 if (res.size() > 0) res.append("-"); 2431 res.appendFormat("%dx%d", dtohs(screenWidth), dtohs(screenHeight)); 2432 } 2433 if (version != 0) { 2434 if (res.size() > 0) res.append("-"); 2435 res.appendFormat("v%d", dtohs(sdkVersion)); 2436 if (minorVersion != 0) { 2437 res.appendFormat(".%d", dtohs(minorVersion)); 2438 } 2439 } 2440 2441 return res; 2442 } 2443 2444 // -------------------------------------------------------------------- 2445 // -------------------------------------------------------------------- 2446 // -------------------------------------------------------------------- 2447 2448 struct ResTable::Header 2449 { 2450 Header(ResTable* _owner) : owner(_owner), ownedData(NULL), header(NULL), 2451 resourceIDMap(NULL), resourceIDMapSize(0) { } 2452 2453 ~Header() 2454 { 2455 free(resourceIDMap); 2456 } 2457 2458 ResTable* const owner; 2459 void* ownedData; 2460 const ResTable_header* header; 2461 size_t size; 2462 const uint8_t* dataEnd; 2463 size_t index; 2464 void* cookie; 2465 2466 ResStringPool values; 2467 uint32_t* resourceIDMap; 2468 size_t resourceIDMapSize; 2469 }; 2470 2471 struct ResTable::Type 2472 { 2473 Type(const Header* _header, const Package* _package, size_t count) 2474 : header(_header), package(_package), entryCount(count), 2475 typeSpec(NULL), typeSpecFlags(NULL) { } 2476 const Header* const header; 2477 const Package* const package; 2478 const size_t entryCount; 2479 const ResTable_typeSpec* typeSpec; 2480 const uint32_t* typeSpecFlags; 2481 Vector<const ResTable_type*> configs; 2482 }; 2483 2484 struct ResTable::Package 2485 { 2486 Package(ResTable* _owner, const Header* _header, const ResTable_package* _package) 2487 : owner(_owner), header(_header), package(_package) { } 2488 ~Package() 2489 { 2490 size_t i = types.size(); 2491 while (i > 0) { 2492 i--; 2493 delete types[i]; 2494 } 2495 } 2496 2497 ResTable* const owner; 2498 const Header* const header; 2499 const ResTable_package* const package; 2500 Vector<Type*> types; 2501 2502 ResStringPool typeStrings; 2503 ResStringPool keyStrings; 2504 2505 const Type* getType(size_t idx) const { 2506 return idx < types.size() ? types[idx] : NULL; 2507 } 2508 }; 2509 2510 // A group of objects describing a particular resource package. 2511 // The first in 'package' is always the root object (from the resource 2512 // table that defined the package); the ones after are skins on top of it. 2513 struct ResTable::PackageGroup 2514 { 2515 PackageGroup(ResTable* _owner, const String16& _name, uint32_t _id) 2516 : owner(_owner), name(_name), id(_id), typeCount(0), bags(NULL) { } 2517 ~PackageGroup() { 2518 clearBagCache(); 2519 const size_t N = packages.size(); 2520 for (size_t i=0; i<N; i++) { 2521 Package* pkg = packages[i]; 2522 if (pkg->owner == owner) { 2523 delete pkg; 2524 } 2525 } 2526 } 2527 2528 void clearBagCache() { 2529 if (bags) { 2530 TABLE_NOISY(printf("bags=%p\n", bags)); 2531 Package* pkg = packages[0]; 2532 TABLE_NOISY(printf("typeCount=%x\n", typeCount)); 2533 for (size_t i=0; i<typeCount; i++) { 2534 TABLE_NOISY(printf("type=%d\n", i)); 2535 const Type* type = pkg->getType(i); 2536 if (type != NULL) { 2537 bag_set** typeBags = bags[i]; 2538 TABLE_NOISY(printf("typeBags=%p\n", typeBags)); 2539 if (typeBags) { 2540 TABLE_NOISY(printf("type->entryCount=%x\n", type->entryCount)); 2541 const size_t N = type->entryCount; 2542 for (size_t j=0; j<N; j++) { 2543 if (typeBags[j] && typeBags[j] != (bag_set*)0xFFFFFFFF) 2544 free(typeBags[j]); 2545 } 2546 free(typeBags); 2547 } 2548 } 2549 } 2550 free(bags); 2551 bags = NULL; 2552 } 2553 } 2554 2555 ResTable* const owner; 2556 String16 const name; 2557 uint32_t const id; 2558 Vector<Package*> packages; 2559 2560 // This is for finding typeStrings and other common package stuff. 2561 Package* basePackage; 2562 2563 // For quick access. 2564 size_t typeCount; 2565 2566 // Computed attribute bags, first indexed by the type and second 2567 // by the entry in that type. 2568 bag_set*** bags; 2569 }; 2570 2571 struct ResTable::bag_set 2572 { 2573 size_t numAttrs; // number in array 2574 size_t availAttrs; // total space in array 2575 uint32_t typeSpecFlags; 2576 // Followed by 'numAttr' bag_entry structures. 2577 }; 2578 2579 ResTable::Theme::Theme(const ResTable& table) 2580 : mTable(table) 2581 { 2582 memset(mPackages, 0, sizeof(mPackages)); 2583 } 2584 2585 ResTable::Theme::~Theme() 2586 { 2587 for (size_t i=0; i<Res_MAXPACKAGE; i++) { 2588 package_info* pi = mPackages[i]; 2589 if (pi != NULL) { 2590 free_package(pi); 2591 } 2592 } 2593 } 2594 2595 void ResTable::Theme::free_package(package_info* pi) 2596 { 2597 for (size_t j=0; j<pi->numTypes; j++) { 2598 theme_entry* te = pi->types[j].entries; 2599 if (te != NULL) { 2600 free(te); 2601 } 2602 } 2603 free(pi); 2604 } 2605 2606 ResTable::Theme::package_info* ResTable::Theme::copy_package(package_info* pi) 2607 { 2608 package_info* newpi = (package_info*)malloc( 2609 sizeof(package_info) + (pi->numTypes*sizeof(type_info))); 2610 newpi->numTypes = pi->numTypes; 2611 for (size_t j=0; j<newpi->numTypes; j++) { 2612 size_t cnt = pi->types[j].numEntries; 2613 newpi->types[j].numEntries = cnt; 2614 theme_entry* te = pi->types[j].entries; 2615 if (te != NULL) { 2616 theme_entry* newte = (theme_entry*)malloc(cnt*sizeof(theme_entry)); 2617 newpi->types[j].entries = newte; 2618 memcpy(newte, te, cnt*sizeof(theme_entry)); 2619 } else { 2620 newpi->types[j].entries = NULL; 2621 } 2622 } 2623 return newpi; 2624 } 2625 2626 status_t ResTable::Theme::applyStyle(uint32_t resID, bool force) 2627 { 2628 const bag_entry* bag; 2629 uint32_t bagTypeSpecFlags = 0; 2630 mTable.lock(); 2631 const ssize_t N = mTable.getBagLocked(resID, &bag, &bagTypeSpecFlags); 2632 TABLE_NOISY(ALOGV("Applying style 0x%08x to theme %p, count=%d", resID, this, N)); 2633 if (N < 0) { 2634 mTable.unlock(); 2635 return N; 2636 } 2637 2638 uint32_t curPackage = 0xffffffff; 2639 ssize_t curPackageIndex = 0; 2640 package_info* curPI = NULL; 2641 uint32_t curType = 0xffffffff; 2642 size_t numEntries = 0; 2643 theme_entry* curEntries = NULL; 2644 2645 const bag_entry* end = bag + N; 2646 while (bag < end) { 2647 const uint32_t attrRes = bag->map.name.ident; 2648 const uint32_t p = Res_GETPACKAGE(attrRes); 2649 const uint32_t t = Res_GETTYPE(attrRes); 2650 const uint32_t e = Res_GETENTRY(attrRes); 2651 2652 if (curPackage != p) { 2653 const ssize_t pidx = mTable.getResourcePackageIndex(attrRes); 2654 if (pidx < 0) { 2655 ALOGE("Style contains key with bad package: 0x%08x\n", attrRes); 2656 bag++; 2657 continue; 2658 } 2659 curPackage = p; 2660 curPackageIndex = pidx; 2661 curPI = mPackages[pidx]; 2662 if (curPI == NULL) { 2663 PackageGroup* const grp = mTable.mPackageGroups[pidx]; 2664 int cnt = grp->typeCount; 2665 curPI = (package_info*)malloc( 2666 sizeof(package_info) + (cnt*sizeof(type_info))); 2667 curPI->numTypes = cnt; 2668 memset(curPI->types, 0, cnt*sizeof(type_info)); 2669 mPackages[pidx] = curPI; 2670 } 2671 curType = 0xffffffff; 2672 } 2673 if (curType != t) { 2674 if (t >= curPI->numTypes) { 2675 ALOGE("Style contains key with bad type: 0x%08x\n", attrRes); 2676 bag++; 2677 continue; 2678 } 2679 curType = t; 2680 curEntries = curPI->types[t].entries; 2681 if (curEntries == NULL) { 2682 PackageGroup* const grp = mTable.mPackageGroups[curPackageIndex]; 2683 const Type* type = grp->packages[0]->getType(t); 2684 int cnt = type != NULL ? type->entryCount : 0; 2685 curEntries = (theme_entry*)malloc(cnt*sizeof(theme_entry)); 2686 memset(curEntries, Res_value::TYPE_NULL, cnt*sizeof(theme_entry)); 2687 curPI->types[t].numEntries = cnt; 2688 curPI->types[t].entries = curEntries; 2689 } 2690 numEntries = curPI->types[t].numEntries; 2691 } 2692 if (e >= numEntries) { 2693 ALOGE("Style contains key with bad entry: 0x%08x\n", attrRes); 2694 bag++; 2695 continue; 2696 } 2697 theme_entry* curEntry = curEntries + e; 2698 TABLE_NOISY(ALOGV("Attr 0x%08x: type=0x%x, data=0x%08x; curType=0x%x", 2699 attrRes, bag->map.value.dataType, bag->map.value.data, 2700 curEntry->value.dataType)); 2701 if (force || curEntry->value.dataType == Res_value::TYPE_NULL) { 2702 curEntry->stringBlock = bag->stringBlock; 2703 curEntry->typeSpecFlags |= bagTypeSpecFlags; 2704 curEntry->value = bag->map.value; 2705 } 2706 2707 bag++; 2708 } 2709 2710 mTable.unlock(); 2711 2712 //ALOGI("Applying style 0x%08x (force=%d) theme %p...\n", resID, force, this); 2713 //dumpToLog(); 2714 2715 return NO_ERROR; 2716 } 2717 2718 status_t ResTable::Theme::setTo(const Theme& other) 2719 { 2720 //ALOGI("Setting theme %p from theme %p...\n", this, &other); 2721 //dumpToLog(); 2722 //other.dumpToLog(); 2723 2724 if (&mTable == &other.mTable) { 2725 for (size_t i=0; i<Res_MAXPACKAGE; i++) { 2726 if (mPackages[i] != NULL) { 2727 free_package(mPackages[i]); 2728 } 2729 if (other.mPackages[i] != NULL) { 2730 mPackages[i] = copy_package(other.mPackages[i]); 2731 } else { 2732 mPackages[i] = NULL; 2733 } 2734 } 2735 } else { 2736 // @todo: need to really implement this, not just copy 2737 // the system package (which is still wrong because it isn't 2738 // fixing up resource references). 2739 for (size_t i=0; i<Res_MAXPACKAGE; i++) { 2740 if (mPackages[i] != NULL) { 2741 free_package(mPackages[i]); 2742 } 2743 if (i == 0 && other.mPackages[i] != NULL) { 2744 mPackages[i] = copy_package(other.mPackages[i]); 2745 } else { 2746 mPackages[i] = NULL; 2747 } 2748 } 2749 } 2750 2751 //ALOGI("Final theme:"); 2752 //dumpToLog(); 2753 2754 return NO_ERROR; 2755 } 2756 2757 ssize_t ResTable::Theme::getAttribute(uint32_t resID, Res_value* outValue, 2758 uint32_t* outTypeSpecFlags) const 2759 { 2760 int cnt = 20; 2761 2762 if (outTypeSpecFlags != NULL) *outTypeSpecFlags = 0; 2763 2764 do { 2765 const ssize_t p = mTable.getResourcePackageIndex(resID); 2766 const uint32_t t = Res_GETTYPE(resID); 2767 const uint32_t e = Res_GETENTRY(resID); 2768 2769 TABLE_THEME(ALOGI("Looking up attr 0x%08x in theme %p", resID, this)); 2770 2771 if (p >= 0) { 2772 const package_info* const pi = mPackages[p]; 2773 TABLE_THEME(ALOGI("Found package: %p", pi)); 2774 if (pi != NULL) { 2775 TABLE_THEME(ALOGI("Desired type index is %ld in avail %d", t, pi->numTypes)); 2776 if (t < pi->numTypes) { 2777 const type_info& ti = pi->types[t]; 2778 TABLE_THEME(ALOGI("Desired entry index is %ld in avail %d", e, ti.numEntries)); 2779 if (e < ti.numEntries) { 2780 const theme_entry& te = ti.entries[e]; 2781 if (outTypeSpecFlags != NULL) { 2782 *outTypeSpecFlags |= te.typeSpecFlags; 2783 } 2784 TABLE_THEME(ALOGI("Theme value: type=0x%x, data=0x%08x", 2785 te.value.dataType, te.value.data)); 2786 const uint8_t type = te.value.dataType; 2787 if (type == Res_value::TYPE_ATTRIBUTE) { 2788 if (cnt > 0) { 2789 cnt--; 2790 resID = te.value.data; 2791 continue; 2792 } 2793 ALOGW("Too many attribute references, stopped at: 0x%08x\n", resID); 2794 return BAD_INDEX; 2795 } else if (type != Res_value::TYPE_NULL) { 2796 *outValue = te.value; 2797 return te.stringBlock; 2798 } 2799 return BAD_INDEX; 2800 } 2801 } 2802 } 2803 } 2804 break; 2805 2806 } while (true); 2807 2808 return BAD_INDEX; 2809 } 2810 2811 ssize_t ResTable::Theme::resolveAttributeReference(Res_value* inOutValue, 2812 ssize_t blockIndex, uint32_t* outLastRef, 2813 uint32_t* inoutTypeSpecFlags, ResTable_config* inoutConfig) const 2814 { 2815 //printf("Resolving type=0x%x\n", inOutValue->dataType); 2816 if (inOutValue->dataType == Res_value::TYPE_ATTRIBUTE) { 2817 uint32_t newTypeSpecFlags; 2818 blockIndex = getAttribute(inOutValue->data, inOutValue, &newTypeSpecFlags); 2819 TABLE_THEME(ALOGI("Resolving attr reference: blockIndex=%d, type=0x%x, data=%p\n", 2820 (int)blockIndex, (int)inOutValue->dataType, (void*)inOutValue->data)); 2821 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newTypeSpecFlags; 2822 //printf("Retrieved attribute new type=0x%x\n", inOutValue->dataType); 2823 if (blockIndex < 0) { 2824 return blockIndex; 2825 } 2826 } 2827 return mTable.resolveReference(inOutValue, blockIndex, outLastRef, 2828 inoutTypeSpecFlags, inoutConfig); 2829 } 2830 2831 void ResTable::Theme::dumpToLog() const 2832 { 2833 ALOGI("Theme %p:\n", this); 2834 for (size_t i=0; i<Res_MAXPACKAGE; i++) { 2835 package_info* pi = mPackages[i]; 2836 if (pi == NULL) continue; 2837 2838 ALOGI(" Package #0x%02x:\n", (int)(i+1)); 2839 for (size_t j=0; j<pi->numTypes; j++) { 2840 type_info& ti = pi->types[j]; 2841 if (ti.numEntries == 0) continue; 2842 2843 ALOGI(" Type #0x%02x:\n", (int)(j+1)); 2844 for (size_t k=0; k<ti.numEntries; k++) { 2845 theme_entry& te = ti.entries[k]; 2846 if (te.value.dataType == Res_value::TYPE_NULL) continue; 2847 ALOGI(" 0x%08x: t=0x%x, d=0x%08x (block=%d)\n", 2848 (int)Res_MAKEID(i, j, k), 2849 te.value.dataType, (int)te.value.data, (int)te.stringBlock); 2850 } 2851 } 2852 } 2853 } 2854 2855 ResTable::ResTable() 2856 : mError(NO_INIT) 2857 { 2858 memset(&mParams, 0, sizeof(mParams)); 2859 memset(mPackageMap, 0, sizeof(mPackageMap)); 2860 //ALOGI("Creating ResTable %p\n", this); 2861 } 2862 2863 ResTable::ResTable(const void* data, size_t size, void* cookie, bool copyData) 2864 : mError(NO_INIT) 2865 { 2866 memset(&mParams, 0, sizeof(mParams)); 2867 memset(mPackageMap, 0, sizeof(mPackageMap)); 2868 add(data, size, cookie, copyData); 2869 LOG_FATAL_IF(mError != NO_ERROR, "Error parsing resource table"); 2870 //ALOGI("Creating ResTable %p\n", this); 2871 } 2872 2873 ResTable::~ResTable() 2874 { 2875 //ALOGI("Destroying ResTable in %p\n", this); 2876 uninit(); 2877 } 2878 2879 inline ssize_t ResTable::getResourcePackageIndex(uint32_t resID) const 2880 { 2881 return ((ssize_t)mPackageMap[Res_GETPACKAGE(resID)+1])-1; 2882 } 2883 2884 status_t ResTable::add(const void* data, size_t size, void* cookie, bool copyData, 2885 const void* idmap) 2886 { 2887 return add(data, size, cookie, NULL, copyData, reinterpret_cast<const Asset*>(idmap)); 2888 } 2889 2890 status_t ResTable::add(Asset* asset, void* cookie, bool copyData, const void* idmap) 2891 { 2892 const void* data = asset->getBuffer(true); 2893 if (data == NULL) { 2894 ALOGW("Unable to get buffer of resource asset file"); 2895 return UNKNOWN_ERROR; 2896 } 2897 size_t size = (size_t)asset->getLength(); 2898 return add(data, size, cookie, asset, copyData, reinterpret_cast<const Asset*>(idmap)); 2899 } 2900 2901 status_t ResTable::add(ResTable* src) 2902 { 2903 mError = src->mError; 2904 2905 for (size_t i=0; i<src->mHeaders.size(); i++) { 2906 mHeaders.add(src->mHeaders[i]); 2907 } 2908 2909 for (size_t i=0; i<src->mPackageGroups.size(); i++) { 2910 PackageGroup* srcPg = src->mPackageGroups[i]; 2911 PackageGroup* pg = new PackageGroup(this, srcPg->name, srcPg->id); 2912 for (size_t j=0; j<srcPg->packages.size(); j++) { 2913 pg->packages.add(srcPg->packages[j]); 2914 } 2915 pg->basePackage = srcPg->basePackage; 2916 pg->typeCount = srcPg->typeCount; 2917 mPackageGroups.add(pg); 2918 } 2919 2920 memcpy(mPackageMap, src->mPackageMap, sizeof(mPackageMap)); 2921 2922 return mError; 2923 } 2924 2925 status_t ResTable::add(const void* data, size_t size, void* cookie, 2926 Asset* asset, bool copyData, const Asset* idmap) 2927 { 2928 if (!data) return NO_ERROR; 2929 Header* header = new Header(this); 2930 header->index = mHeaders.size(); 2931 header->cookie = cookie; 2932 if (idmap != NULL) { 2933 const size_t idmap_size = idmap->getLength(); 2934 const void* idmap_data = const_cast<Asset*>(idmap)->getBuffer(true); 2935 header->resourceIDMap = (uint32_t*)malloc(idmap_size); 2936 if (header->resourceIDMap == NULL) { 2937 delete header; 2938 return (mError = NO_MEMORY); 2939 } 2940 memcpy((void*)header->resourceIDMap, idmap_data, idmap_size); 2941 header->resourceIDMapSize = idmap_size; 2942 } 2943 mHeaders.add(header); 2944 2945 const bool notDeviceEndian = htods(0xf0) != 0xf0; 2946 2947 LOAD_TABLE_NOISY( 2948 ALOGV("Adding resources to ResTable: data=%p, size=0x%x, cookie=%p, asset=%p, copy=%d " 2949 "idmap=%p\n", data, size, cookie, asset, copyData, idmap)); 2950 2951 if (copyData || notDeviceEndian) { 2952 header->ownedData = malloc(size); 2953 if (header->ownedData == NULL) { 2954 return (mError=NO_MEMORY); 2955 } 2956 memcpy(header->ownedData, data, size); 2957 data = header->ownedData; 2958 } 2959 2960 header->header = (const ResTable_header*)data; 2961 header->size = dtohl(header->header->header.size); 2962 //ALOGI("Got size 0x%x, again size 0x%x, raw size 0x%x\n", header->size, 2963 // dtohl(header->header->header.size), header->header->header.size); 2964 LOAD_TABLE_NOISY(ALOGV("Loading ResTable @%p:\n", header->header)); 2965 LOAD_TABLE_NOISY(printHexData(2, header->header, header->size < 256 ? header->size : 256, 2966 16, 16, 0, false, printToLogFunc)); 2967 if (dtohs(header->header->header.headerSize) > header->size 2968 || header->size > size) { 2969 ALOGW("Bad resource table: header size 0x%x or total size 0x%x is larger than data size 0x%x\n", 2970 (int)dtohs(header->header->header.headerSize), 2971 (int)header->size, (int)size); 2972 return (mError=BAD_TYPE); 2973 } 2974 if (((dtohs(header->header->header.headerSize)|header->size)&0x3) != 0) { 2975 ALOGW("Bad resource table: header size 0x%x or total size 0x%x is not on an integer boundary\n", 2976 (int)dtohs(header->header->header.headerSize), 2977 (int)header->size); 2978 return (mError=BAD_TYPE); 2979 } 2980 header->dataEnd = ((const uint8_t*)header->header) + header->size; 2981 2982 // Iterate through all chunks. 2983 size_t curPackage = 0; 2984 2985 const ResChunk_header* chunk = 2986 (const ResChunk_header*)(((const uint8_t*)header->header) 2987 + dtohs(header->header->header.headerSize)); 2988 while (((const uint8_t*)chunk) <= (header->dataEnd-sizeof(ResChunk_header)) && 2989 ((const uint8_t*)chunk) <= (header->dataEnd-dtohl(chunk->size))) { 2990 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), header->dataEnd, "ResTable"); 2991 if (err != NO_ERROR) { 2992 return (mError=err); 2993 } 2994 TABLE_NOISY(ALOGV("Chunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n", 2995 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size), 2996 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)))); 2997 const size_t csize = dtohl(chunk->size); 2998 const uint16_t ctype = dtohs(chunk->type); 2999 if (ctype == RES_STRING_POOL_TYPE) { 3000 if (header->values.getError() != NO_ERROR) { 3001 // Only use the first string chunk; ignore any others that 3002 // may appear. 3003 status_t err = header->values.setTo(chunk, csize); 3004 if (err != NO_ERROR) { 3005 return (mError=err); 3006 } 3007 } else { 3008 ALOGW("Multiple string chunks found in resource table."); 3009 } 3010 } else if (ctype == RES_TABLE_PACKAGE_TYPE) { 3011 if (curPackage >= dtohl(header->header->packageCount)) { 3012 ALOGW("More package chunks were found than the %d declared in the header.", 3013 dtohl(header->header->packageCount)); 3014 return (mError=BAD_TYPE); 3015 } 3016 uint32_t idmap_id = 0; 3017 if (idmap != NULL) { 3018 uint32_t tmp; 3019 if (getIdmapPackageId(header->resourceIDMap, 3020 header->resourceIDMapSize, 3021 &tmp) == NO_ERROR) { 3022 idmap_id = tmp; 3023 } 3024 } 3025 if (parsePackage((ResTable_package*)chunk, header, idmap_id) != NO_ERROR) { 3026 return mError; 3027 } 3028 curPackage++; 3029 } else { 3030 ALOGW("Unknown chunk type %p in table at %p.\n", 3031 (void*)(int)(ctype), 3032 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header))); 3033 } 3034 chunk = (const ResChunk_header*) 3035 (((const uint8_t*)chunk) + csize); 3036 } 3037 3038 if (curPackage < dtohl(header->header->packageCount)) { 3039 ALOGW("Fewer package chunks (%d) were found than the %d declared in the header.", 3040 (int)curPackage, dtohl(header->header->packageCount)); 3041 return (mError=BAD_TYPE); 3042 } 3043 mError = header->values.getError(); 3044 if (mError != NO_ERROR) { 3045 ALOGW("No string values found in resource table!"); 3046 } 3047 3048 TABLE_NOISY(ALOGV("Returning from add with mError=%d\n", mError)); 3049 return mError; 3050 } 3051 3052 status_t ResTable::getError() const 3053 { 3054 return mError; 3055 } 3056 3057 void ResTable::uninit() 3058 { 3059 mError = NO_INIT; 3060 size_t N = mPackageGroups.size(); 3061 for (size_t i=0; i<N; i++) { 3062 PackageGroup* g = mPackageGroups[i]; 3063 delete g; 3064 } 3065 N = mHeaders.size(); 3066 for (size_t i=0; i<N; i++) { 3067 Header* header = mHeaders[i]; 3068 if (header->owner == this) { 3069 if (header->ownedData) { 3070 free(header->ownedData); 3071 } 3072 delete header; 3073 } 3074 } 3075 3076 mPackageGroups.clear(); 3077 mHeaders.clear(); 3078 } 3079 3080 bool ResTable::getResourceName(uint32_t resID, bool allowUtf8, resource_name* outName) const 3081 { 3082 if (mError != NO_ERROR) { 3083 return false; 3084 } 3085 3086 const ssize_t p = getResourcePackageIndex(resID); 3087 const int t = Res_GETTYPE(resID); 3088 const int e = Res_GETENTRY(resID); 3089 3090 if (p < 0) { 3091 if (Res_GETPACKAGE(resID)+1 == 0) { 3092 ALOGW("No package identifier when getting name for resource number 0x%08x", resID); 3093 } else { 3094 ALOGW("No known package when getting name for resource number 0x%08x", resID); 3095 } 3096 return false; 3097 } 3098 if (t < 0) { 3099 ALOGW("No type identifier when getting name for resource number 0x%08x", resID); 3100 return false; 3101 } 3102 3103 const PackageGroup* const grp = mPackageGroups[p]; 3104 if (grp == NULL) { 3105 ALOGW("Bad identifier when getting name for resource number 0x%08x", resID); 3106 return false; 3107 } 3108 if (grp->packages.size() > 0) { 3109 const Package* const package = grp->packages[0]; 3110 3111 const ResTable_type* type; 3112 const ResTable_entry* entry; 3113 ssize_t offset = getEntry(package, t, e, NULL, &type, &entry, NULL); 3114 if (offset <= 0) { 3115 return false; 3116 } 3117 3118 outName->package = grp->name.string(); 3119 outName->packageLen = grp->name.size(); 3120 if (allowUtf8) { 3121 outName->type8 = grp->basePackage->typeStrings.string8At(t, &outName->typeLen); 3122 outName->name8 = grp->basePackage->keyStrings.string8At( 3123 dtohl(entry->key.index), &outName->nameLen); 3124 } else { 3125 outName->type8 = NULL; 3126 outName->name8 = NULL; 3127 } 3128 if (outName->type8 == NULL) { 3129 outName->type = grp->basePackage->typeStrings.stringAt(t, &outName->typeLen); 3130 // If we have a bad index for some reason, we should abort. 3131 if (outName->type == NULL) { 3132 return false; 3133 } 3134 } 3135 if (outName->name8 == NULL) { 3136 outName->name = grp->basePackage->keyStrings.stringAt( 3137 dtohl(entry->key.index), &outName->nameLen); 3138 // If we have a bad index for some reason, we should abort. 3139 if (outName->name == NULL) { 3140 return false; 3141 } 3142 } 3143 3144 return true; 3145 } 3146 3147 return false; 3148 } 3149 3150 ssize_t ResTable::getResource(uint32_t resID, Res_value* outValue, bool mayBeBag, uint16_t density, 3151 uint32_t* outSpecFlags, ResTable_config* outConfig) const 3152 { 3153 if (mError != NO_ERROR) { 3154 return mError; 3155 } 3156 3157 const ssize_t p = getResourcePackageIndex(resID); 3158 const int t = Res_GETTYPE(resID); 3159 const int e = Res_GETENTRY(resID); 3160 3161 if (p < 0) { 3162 if (Res_GETPACKAGE(resID)+1 == 0) { 3163 ALOGW("No package identifier when getting value for resource number 0x%08x", resID); 3164 } else { 3165 ALOGW("No known package when getting value for resource number 0x%08x", resID); 3166 } 3167 return BAD_INDEX; 3168 } 3169 if (t < 0) { 3170 ALOGW("No type identifier when getting value for resource number 0x%08x", resID); 3171 return BAD_INDEX; 3172 } 3173 3174 const Res_value* bestValue = NULL; 3175 const Package* bestPackage = NULL; 3176 ResTable_config bestItem; 3177 memset(&bestItem, 0, sizeof(bestItem)); // make the compiler shut up 3178 3179 if (outSpecFlags != NULL) *outSpecFlags = 0; 3180 3181 // Look through all resource packages, starting with the most 3182 // recently added. 3183 const PackageGroup* const grp = mPackageGroups[p]; 3184 if (grp == NULL) { 3185 ALOGW("Bad identifier when getting value for resource number 0x%08x", resID); 3186 return BAD_INDEX; 3187 } 3188 3189 // Allow overriding density 3190 const ResTable_config* desiredConfig = &mParams; 3191 ResTable_config* overrideConfig = NULL; 3192 if (density > 0) { 3193 overrideConfig = (ResTable_config*) malloc(sizeof(ResTable_config)); 3194 if (overrideConfig == NULL) { 3195 ALOGE("Couldn't malloc ResTable_config for overrides: %s", strerror(errno)); 3196 return BAD_INDEX; 3197 } 3198 memcpy(overrideConfig, &mParams, sizeof(ResTable_config)); 3199 overrideConfig->density = density; 3200 desiredConfig = overrideConfig; 3201 } 3202 3203 ssize_t rc = BAD_VALUE; 3204 size_t ip = grp->packages.size(); 3205 while (ip > 0) { 3206 ip--; 3207 int T = t; 3208 int E = e; 3209 3210 const Package* const package = grp->packages[ip]; 3211 if (package->header->resourceIDMap) { 3212 uint32_t overlayResID = 0x0; 3213 status_t retval = idmapLookup(package->header->resourceIDMap, 3214 package->header->resourceIDMapSize, 3215 resID, &overlayResID); 3216 if (retval == NO_ERROR && overlayResID != 0x0) { 3217 // for this loop iteration, this is the type and entry we really want 3218 ALOGV("resource map 0x%08x -> 0x%08x\n", resID, overlayResID); 3219 T = Res_GETTYPE(overlayResID); 3220 E = Res_GETENTRY(overlayResID); 3221 } else { 3222 // resource not present in overlay package, continue with the next package 3223 continue; 3224 } 3225 } 3226 3227 const ResTable_type* type; 3228 const ResTable_entry* entry; 3229 const Type* typeClass; 3230 ssize_t offset = getEntry(package, T, E, desiredConfig, &type, &entry, &typeClass); 3231 if (offset <= 0) { 3232 // No {entry, appropriate config} pair found in package. If this 3233 // package is an overlay package (ip != 0), this simply means the 3234 // overlay package did not specify a default. 3235 // Non-overlay packages are still required to provide a default. 3236 if (offset < 0 && ip == 0) { 3237 ALOGW("Failure getting entry for 0x%08x (t=%d e=%d) in package %zd (error %d)\n", 3238 resID, T, E, ip, (int)offset); 3239 rc = offset; 3240 goto out; 3241 } 3242 continue; 3243 } 3244 3245 if ((dtohs(entry->flags)&entry->FLAG_COMPLEX) != 0) { 3246 if (!mayBeBag) { 3247 ALOGW("Requesting resource %p failed because it is complex\n", 3248 (void*)resID); 3249 } 3250 continue; 3251 } 3252 3253 TABLE_NOISY(aout << "Resource type data: " 3254 << HexDump(type, dtohl(type->header.size)) << endl); 3255 3256 if ((size_t)offset > (dtohl(type->header.size)-sizeof(Res_value))) { 3257 ALOGW("ResTable_item at %d is beyond type chunk data %d", 3258 (int)offset, dtohl(type->header.size)); 3259 rc = BAD_TYPE; 3260 goto out; 3261 } 3262 3263 const Res_value* item = 3264 (const Res_value*)(((const uint8_t*)type) + offset); 3265 ResTable_config thisConfig; 3266 thisConfig.copyFromDtoH(type->config); 3267 3268 if (outSpecFlags != NULL) { 3269 if (typeClass->typeSpecFlags != NULL) { 3270 *outSpecFlags |= dtohl(typeClass->typeSpecFlags[E]); 3271 } else { 3272 *outSpecFlags = -1; 3273 } 3274 } 3275 3276 if (bestPackage != NULL && 3277 (bestItem.isMoreSpecificThan(thisConfig) || bestItem.diff(thisConfig) == 0)) { 3278 // Discard thisConfig not only if bestItem is more specific, but also if the two configs 3279 // are identical (diff == 0), or overlay packages will not take effect. 3280 continue; 3281 } 3282 3283 bestItem = thisConfig; 3284 bestValue = item; 3285 bestPackage = package; 3286 } 3287 3288 TABLE_NOISY(printf("Found result: package %p\n", bestPackage)); 3289 3290 if (bestValue) { 3291 outValue->size = dtohs(bestValue->size); 3292 outValue->res0 = bestValue->res0; 3293 outValue->dataType = bestValue->dataType; 3294 outValue->data = dtohl(bestValue->data); 3295 if (outConfig != NULL) { 3296 *outConfig = bestItem; 3297 } 3298 TABLE_NOISY(size_t len; 3299 printf("Found value: pkg=%d, type=%d, str=%s, int=%d\n", 3300 bestPackage->header->index, 3301 outValue->dataType, 3302 outValue->dataType == bestValue->TYPE_STRING 3303 ? String8(bestPackage->header->values.stringAt( 3304 outValue->data, &len)).string() 3305 : "", 3306 outValue->data)); 3307 rc = bestPackage->header->index; 3308 goto out; 3309 } 3310 3311 out: 3312 if (overrideConfig != NULL) { 3313 free(overrideConfig); 3314 } 3315 3316 return rc; 3317 } 3318 3319 ssize_t ResTable::resolveReference(Res_value* value, ssize_t blockIndex, 3320 uint32_t* outLastRef, uint32_t* inoutTypeSpecFlags, 3321 ResTable_config* outConfig) const 3322 { 3323 int count=0; 3324 while (blockIndex >= 0 && value->dataType == value->TYPE_REFERENCE 3325 && value->data != 0 && count < 20) { 3326 if (outLastRef) *outLastRef = value->data; 3327 uint32_t lastRef = value->data; 3328 uint32_t newFlags = 0; 3329 const ssize_t newIndex = getResource(value->data, value, true, 0, &newFlags, 3330 outConfig); 3331 if (newIndex == BAD_INDEX) { 3332 return BAD_INDEX; 3333 } 3334 TABLE_THEME(ALOGI("Resolving reference %p: newIndex=%d, type=0x%x, data=%p\n", 3335 (void*)lastRef, (int)newIndex, (int)value->dataType, (void*)value->data)); 3336 //printf("Getting reference 0x%08x: newIndex=%d\n", value->data, newIndex); 3337 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newFlags; 3338 if (newIndex < 0) { 3339 // This can fail if the resource being referenced is a style... 3340 // in this case, just return the reference, and expect the 3341 // caller to deal with. 3342 return blockIndex; 3343 } 3344 blockIndex = newIndex; 3345 count++; 3346 } 3347 return blockIndex; 3348 } 3349 3350 const char16_t* ResTable::valueToString( 3351 const Res_value* value, size_t stringBlock, 3352 char16_t tmpBuffer[TMP_BUFFER_SIZE], size_t* outLen) 3353 { 3354 if (!value) { 3355 return NULL; 3356 } 3357 if (value->dataType == value->TYPE_STRING) { 3358 return getTableStringBlock(stringBlock)->stringAt(value->data, outLen); 3359 } 3360 // XXX do int to string conversions. 3361 return NULL; 3362 } 3363 3364 ssize_t ResTable::lockBag(uint32_t resID, const bag_entry** outBag) const 3365 { 3366 mLock.lock(); 3367 ssize_t err = getBagLocked(resID, outBag); 3368 if (err < NO_ERROR) { 3369 //printf("*** get failed! unlocking\n"); 3370 mLock.unlock(); 3371 } 3372 return err; 3373 } 3374 3375 void ResTable::unlockBag(const bag_entry* bag) const 3376 { 3377 //printf("<<< unlockBag %p\n", this); 3378 mLock.unlock(); 3379 } 3380 3381 void ResTable::lock() const 3382 { 3383 mLock.lock(); 3384 } 3385 3386 void ResTable::unlock() const 3387 { 3388 mLock.unlock(); 3389 } 3390 3391 ssize_t ResTable::getBagLocked(uint32_t resID, const bag_entry** outBag, 3392 uint32_t* outTypeSpecFlags) const 3393 { 3394 if (mError != NO_ERROR) { 3395 return mError; 3396 } 3397 3398 const ssize_t p = getResourcePackageIndex(resID); 3399 const int t = Res_GETTYPE(resID); 3400 const int e = Res_GETENTRY(resID); 3401 3402 if (p < 0) { 3403 ALOGW("Invalid package identifier when getting bag for resource number 0x%08x", resID); 3404 return BAD_INDEX; 3405 } 3406 if (t < 0) { 3407 ALOGW("No type identifier when getting bag for resource number 0x%08x", resID); 3408 return BAD_INDEX; 3409 } 3410 3411 //printf("Get bag: id=0x%08x, p=%d, t=%d\n", resID, p, t); 3412 PackageGroup* const grp = mPackageGroups[p]; 3413 if (grp == NULL) { 3414 ALOGW("Bad identifier when getting bag for resource number 0x%08x", resID); 3415 return false; 3416 } 3417 3418 if (t >= (int)grp->typeCount) { 3419 ALOGW("Type identifier 0x%x is larger than type count 0x%x", 3420 t+1, (int)grp->typeCount); 3421 return BAD_INDEX; 3422 } 3423 3424 const Package* const basePackage = grp->packages[0]; 3425 3426 const Type* const typeConfigs = basePackage->getType(t); 3427 3428 const size_t NENTRY = typeConfigs->entryCount; 3429 if (e >= (int)NENTRY) { 3430 ALOGW("Entry identifier 0x%x is larger than entry count 0x%x", 3431 e, (int)typeConfigs->entryCount); 3432 return BAD_INDEX; 3433 } 3434 3435 // First see if we've already computed this bag... 3436 if (grp->bags) { 3437 bag_set** typeSet = grp->bags[t]; 3438 if (typeSet) { 3439 bag_set* set = typeSet[e]; 3440 if (set) { 3441 if (set != (bag_set*)0xFFFFFFFF) { 3442 if (outTypeSpecFlags != NULL) { 3443 *outTypeSpecFlags = set->typeSpecFlags; 3444 } 3445 *outBag = (bag_entry*)(set+1); 3446 //ALOGI("Found existing bag for: %p\n", (void*)resID); 3447 return set->numAttrs; 3448 } 3449 ALOGW("Attempt to retrieve bag 0x%08x which is invalid or in a cycle.", 3450 resID); 3451 return BAD_INDEX; 3452 } 3453 } 3454 } 3455 3456 // Bag not found, we need to compute it! 3457 if (!grp->bags) { 3458 grp->bags = (bag_set***)calloc(grp->typeCount, sizeof(bag_set*)); 3459 if (!grp->bags) return NO_MEMORY; 3460 } 3461 3462 bag_set** typeSet = grp->bags[t]; 3463 if (!typeSet) { 3464 typeSet = (bag_set**)calloc(NENTRY, sizeof(bag_set*)); 3465 if (!typeSet) return NO_MEMORY; 3466 grp->bags[t] = typeSet; 3467 } 3468 3469 // Mark that we are currently working on this one. 3470 typeSet[e] = (bag_set*)0xFFFFFFFF; 3471 3472 // This is what we are building. 3473 bag_set* set = NULL; 3474 3475 TABLE_NOISY(ALOGI("Building bag: %p\n", (void*)resID)); 3476 3477 ResTable_config bestConfig; 3478 memset(&bestConfig, 0, sizeof(bestConfig)); 3479 3480 // Now collect all bag attributes from all packages. 3481 size_t ip = grp->packages.size(); 3482 while (ip > 0) { 3483 ip--; 3484 int T = t; 3485 int E = e; 3486 3487 const Package* const package = grp->packages[ip]; 3488 if (package->header->resourceIDMap) { 3489 uint32_t overlayResID = 0x0; 3490 status_t retval = idmapLookup(package->header->resourceIDMap, 3491 package->header->resourceIDMapSize, 3492 resID, &overlayResID); 3493 if (retval == NO_ERROR && overlayResID != 0x0) { 3494 // for this loop iteration, this is the type and entry we really want 3495 ALOGV("resource map 0x%08x -> 0x%08x\n", resID, overlayResID); 3496 T = Res_GETTYPE(overlayResID); 3497 E = Res_GETENTRY(overlayResID); 3498 } else { 3499 // resource not present in overlay package, continue with the next package 3500 continue; 3501 } 3502 } 3503 3504 const ResTable_type* type; 3505 const ResTable_entry* entry; 3506 const Type* typeClass; 3507 ALOGV("Getting entry pkg=%p, t=%d, e=%d\n", package, T, E); 3508 ssize_t offset = getEntry(package, T, E, &mParams, &type, &entry, &typeClass); 3509 ALOGV("Resulting offset=%d\n", offset); 3510 if (offset <= 0) { 3511 // No {entry, appropriate config} pair found in package. If this 3512 // package is an overlay package (ip != 0), this simply means the 3513 // overlay package did not specify a default. 3514 // Non-overlay packages are still required to provide a default. 3515 if (offset < 0 && ip == 0) { 3516 if (set) free(set); 3517 return offset; 3518 } 3519 continue; 3520 } 3521 3522 if ((dtohs(entry->flags)&entry->FLAG_COMPLEX) == 0) { 3523 ALOGW("Skipping entry %p in package table %d because it is not complex!\n", 3524 (void*)resID, (int)ip); 3525 continue; 3526 } 3527 3528 if (set != NULL && !type->config.isBetterThan(bestConfig, NULL)) { 3529 continue; 3530 } 3531 bestConfig = type->config; 3532 if (set) { 3533 free(set); 3534 set = NULL; 3535 } 3536 3537 const uint16_t entrySize = dtohs(entry->size); 3538 const uint32_t parent = entrySize >= sizeof(ResTable_map_entry) 3539 ? dtohl(((const ResTable_map_entry*)entry)->parent.ident) : 0; 3540 const uint32_t count = entrySize >= sizeof(ResTable_map_entry) 3541 ? dtohl(((const ResTable_map_entry*)entry)->count) : 0; 3542 3543 size_t N = count; 3544 3545 TABLE_NOISY(ALOGI("Found map: size=%p parent=%p count=%d\n", 3546 entrySize, parent, count)); 3547 3548 // If this map inherits from another, we need to start 3549 // with its parent's values. Otherwise start out empty. 3550 TABLE_NOISY(printf("Creating new bag, entrySize=0x%08x, parent=0x%08x\n", 3551 entrySize, parent)); 3552 if (parent) { 3553 const bag_entry* parentBag; 3554 uint32_t parentTypeSpecFlags = 0; 3555 const ssize_t NP = getBagLocked(parent, &parentBag, &parentTypeSpecFlags); 3556 const size_t NT = ((NP >= 0) ? NP : 0) + N; 3557 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*NT); 3558 if (set == NULL) { 3559 return NO_MEMORY; 3560 } 3561 if (NP > 0) { 3562 memcpy(set+1, parentBag, NP*sizeof(bag_entry)); 3563 set->numAttrs = NP; 3564 TABLE_NOISY(ALOGI("Initialized new bag with %d inherited attributes.\n", NP)); 3565 } else { 3566 TABLE_NOISY(ALOGI("Initialized new bag with no inherited attributes.\n")); 3567 set->numAttrs = 0; 3568 } 3569 set->availAttrs = NT; 3570 set->typeSpecFlags = parentTypeSpecFlags; 3571 } else { 3572 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*N); 3573 if (set == NULL) { 3574 return NO_MEMORY; 3575 } 3576 set->numAttrs = 0; 3577 set->availAttrs = N; 3578 set->typeSpecFlags = 0; 3579 } 3580 3581 if (typeClass->typeSpecFlags != NULL) { 3582 set->typeSpecFlags |= dtohl(typeClass->typeSpecFlags[E]); 3583 } else { 3584 set->typeSpecFlags = -1; 3585 } 3586 3587 // Now merge in the new attributes... 3588 ssize_t curOff = offset; 3589 const ResTable_map* map; 3590 bag_entry* entries = (bag_entry*)(set+1); 3591 size_t curEntry = 0; 3592 uint32_t pos = 0; 3593 TABLE_NOISY(ALOGI("Starting with set %p, entries=%p, avail=%d\n", 3594 set, entries, set->availAttrs)); 3595 while (pos < count) { 3596 TABLE_NOISY(printf("Now at %p\n", (void*)curOff)); 3597 3598 if ((size_t)curOff > (dtohl(type->header.size)-sizeof(ResTable_map))) { 3599 ALOGW("ResTable_map at %d is beyond type chunk data %d", 3600 (int)curOff, dtohl(type->header.size)); 3601 return BAD_TYPE; 3602 } 3603 map = (const ResTable_map*)(((const uint8_t*)type) + curOff); 3604 N++; 3605 3606 const uint32_t newName = htodl(map->name.ident); 3607 bool isInside; 3608 uint32_t oldName = 0; 3609 while ((isInside=(curEntry < set->numAttrs)) 3610 && (oldName=entries[curEntry].map.name.ident) < newName) { 3611 TABLE_NOISY(printf("#%d: Keeping existing attribute: 0x%08x\n", 3612 curEntry, entries[curEntry].map.name.ident)); 3613 curEntry++; 3614 } 3615 3616 if ((!isInside) || oldName != newName) { 3617 // This is a new attribute... figure out what to do with it. 3618 if (set->numAttrs >= set->availAttrs) { 3619 // Need to alloc more memory... 3620 const size_t newAvail = set->availAttrs+N; 3621 set = (bag_set*)realloc(set, 3622 sizeof(bag_set) 3623 + sizeof(bag_entry)*newAvail); 3624 if (set == NULL) { 3625 return NO_MEMORY; 3626 } 3627 set->availAttrs = newAvail; 3628 entries = (bag_entry*)(set+1); 3629 TABLE_NOISY(printf("Reallocated set %p, entries=%p, avail=%d\n", 3630 set, entries, set->availAttrs)); 3631 } 3632 if (isInside) { 3633 // Going in the middle, need to make space. 3634 memmove(entries+curEntry+1, entries+curEntry, 3635 sizeof(bag_entry)*(set->numAttrs-curEntry)); 3636 set->numAttrs++; 3637 } 3638 TABLE_NOISY(printf("#%d: Inserting new attribute: 0x%08x\n", 3639 curEntry, newName)); 3640 } else { 3641 TABLE_NOISY(printf("#%d: Replacing existing attribute: 0x%08x\n", 3642 curEntry, oldName)); 3643 } 3644 3645 bag_entry* cur = entries+curEntry; 3646 3647 cur->stringBlock = package->header->index; 3648 cur->map.name.ident = newName; 3649 cur->map.value.copyFrom_dtoh(map->value); 3650 TABLE_NOISY(printf("Setting entry #%d %p: block=%d, name=0x%08x, type=%d, data=0x%08x\n", 3651 curEntry, cur, cur->stringBlock, cur->map.name.ident, 3652 cur->map.value.dataType, cur->map.value.data)); 3653 3654 // On to the next! 3655 curEntry++; 3656 pos++; 3657 const size_t size = dtohs(map->value.size); 3658 curOff += size + sizeof(*map)-sizeof(map->value); 3659 }; 3660 if (curEntry > set->numAttrs) { 3661 set->numAttrs = curEntry; 3662 } 3663 } 3664 3665 // And this is it... 3666 typeSet[e] = set; 3667 if (set) { 3668 if (outTypeSpecFlags != NULL) { 3669 *outTypeSpecFlags = set->typeSpecFlags; 3670 } 3671 *outBag = (bag_entry*)(set+1); 3672 TABLE_NOISY(ALOGI("Returning %d attrs\n", set->numAttrs)); 3673 return set->numAttrs; 3674 } 3675 return BAD_INDEX; 3676 } 3677 3678 void ResTable::setParameters(const ResTable_config* params) 3679 { 3680 mLock.lock(); 3681 TABLE_GETENTRY(ALOGI("Setting parameters: %s\n", params->toString().string())); 3682 mParams = *params; 3683 for (size_t i=0; i<mPackageGroups.size(); i++) { 3684 TABLE_NOISY(ALOGI("CLEARING BAGS FOR GROUP %d!", i)); 3685 mPackageGroups[i]->clearBagCache(); 3686 } 3687 mLock.unlock(); 3688 } 3689 3690 void ResTable::getParameters(ResTable_config* params) const 3691 { 3692 mLock.lock(); 3693 *params = mParams; 3694 mLock.unlock(); 3695 } 3696 3697 struct id_name_map { 3698 uint32_t id; 3699 size_t len; 3700 char16_t name[6]; 3701 }; 3702 3703 const static id_name_map ID_NAMES[] = { 3704 { ResTable_map::ATTR_TYPE, 5, { '^', 't', 'y', 'p', 'e' } }, 3705 { ResTable_map::ATTR_L10N, 5, { '^', 'l', '1', '0', 'n' } }, 3706 { ResTable_map::ATTR_MIN, 4, { '^', 'm', 'i', 'n' } }, 3707 { ResTable_map::ATTR_MAX, 4, { '^', 'm', 'a', 'x' } }, 3708 { ResTable_map::ATTR_OTHER, 6, { '^', 'o', 't', 'h', 'e', 'r' } }, 3709 { ResTable_map::ATTR_ZERO, 5, { '^', 'z', 'e', 'r', 'o' } }, 3710 { ResTable_map::ATTR_ONE, 4, { '^', 'o', 'n', 'e' } }, 3711 { ResTable_map::ATTR_TWO, 4, { '^', 't', 'w', 'o' } }, 3712 { ResTable_map::ATTR_FEW, 4, { '^', 'f', 'e', 'w' } }, 3713 { ResTable_map::ATTR_MANY, 5, { '^', 'm', 'a', 'n', 'y' } }, 3714 }; 3715 3716 uint32_t ResTable::identifierForName(const char16_t* name, size_t nameLen, 3717 const char16_t* type, size_t typeLen, 3718 const char16_t* package, 3719 size_t packageLen, 3720 uint32_t* outTypeSpecFlags) const 3721 { 3722 TABLE_SUPER_NOISY(printf("Identifier for name: error=%d\n", mError)); 3723 3724 // Check for internal resource identifier as the very first thing, so 3725 // that we will always find them even when there are no resources. 3726 if (name[0] == '^') { 3727 const int N = (sizeof(ID_NAMES)/sizeof(ID_NAMES[0])); 3728 size_t len; 3729 for (int i=0; i<N; i++) { 3730 const id_name_map* m = ID_NAMES + i; 3731 len = m->len; 3732 if (len != nameLen) { 3733 continue; 3734 } 3735 for (size_t j=1; j<len; j++) { 3736 if (m->name[j] != name[j]) { 3737 goto nope; 3738 } 3739 } 3740 if (outTypeSpecFlags) { 3741 *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC; 3742 } 3743 return m->id; 3744 nope: 3745 ; 3746 } 3747 if (nameLen > 7) { 3748 if (name[1] == 'i' && name[2] == 'n' 3749 && name[3] == 'd' && name[4] == 'e' && name[5] == 'x' 3750 && name[6] == '_') { 3751 int index = atoi(String8(name + 7, nameLen - 7).string()); 3752 if (Res_CHECKID(index)) { 3753 ALOGW("Array resource index: %d is too large.", 3754 index); 3755 return 0; 3756 } 3757 if (outTypeSpecFlags) { 3758 *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC; 3759 } 3760 return Res_MAKEARRAY(index); 3761 } 3762 } 3763 return 0; 3764 } 3765 3766 if (mError != NO_ERROR) { 3767 return 0; 3768 } 3769 3770 bool fakePublic = false; 3771 3772 // Figure out the package and type we are looking in... 3773 3774 const char16_t* packageEnd = NULL; 3775 const char16_t* typeEnd = NULL; 3776 const char16_t* const nameEnd = name+nameLen; 3777 const char16_t* p = name; 3778 while (p < nameEnd) { 3779 if (*p == ':') packageEnd = p; 3780 else if (*p == '/') typeEnd = p; 3781 p++; 3782 } 3783 if (*name == '@') { 3784 name++; 3785 if (*name == '*') { 3786 fakePublic = true; 3787 name++; 3788 } 3789 } 3790 if (name >= nameEnd) { 3791 return 0; 3792 } 3793 3794 if (packageEnd) { 3795 package = name; 3796 packageLen = packageEnd-name; 3797 name = packageEnd+1; 3798 } else if (!package) { 3799 return 0; 3800 } 3801 3802 if (typeEnd) { 3803 type = name; 3804 typeLen = typeEnd-name; 3805 name = typeEnd+1; 3806 } else if (!type) { 3807 return 0; 3808 } 3809 3810 if (name >= nameEnd) { 3811 return 0; 3812 } 3813 nameLen = nameEnd-name; 3814 3815 TABLE_NOISY(printf("Looking for identifier: type=%s, name=%s, package=%s\n", 3816 String8(type, typeLen).string(), 3817 String8(name, nameLen).string(), 3818 String8(package, packageLen).string())); 3819 3820 const size_t NG = mPackageGroups.size(); 3821 for (size_t ig=0; ig<NG; ig++) { 3822 const PackageGroup* group = mPackageGroups[ig]; 3823 3824 if (strzcmp16(package, packageLen, 3825 group->name.string(), group->name.size())) { 3826 TABLE_NOISY(printf("Skipping package group: %s\n", String8(group->name).string())); 3827 continue; 3828 } 3829 3830 const ssize_t ti = group->basePackage->typeStrings.indexOfString(type, typeLen); 3831 if (ti < 0) { 3832 TABLE_NOISY(printf("Type not found in package %s\n", String8(group->name).string())); 3833 continue; 3834 } 3835 3836 const ssize_t ei = group->basePackage->keyStrings.indexOfString(name, nameLen); 3837 if (ei < 0) { 3838 TABLE_NOISY(printf("Name not found in package %s\n", String8(group->name).string())); 3839 continue; 3840 } 3841 3842 TABLE_NOISY(printf("Search indices: type=%d, name=%d\n", ti, ei)); 3843 3844 const Type* const typeConfigs = group->packages[0]->getType(ti); 3845 if (typeConfigs == NULL || typeConfigs->configs.size() <= 0) { 3846 TABLE_NOISY(printf("Expected type structure not found in package %s for idnex %d\n", 3847 String8(group->name).string(), ti)); 3848 } 3849 3850 size_t NTC = typeConfigs->configs.size(); 3851 for (size_t tci=0; tci<NTC; tci++) { 3852 const ResTable_type* const ty = typeConfigs->configs[tci]; 3853 const uint32_t typeOffset = dtohl(ty->entriesStart); 3854 3855 const uint8_t* const end = ((const uint8_t*)ty) + dtohl(ty->header.size); 3856 const uint32_t* const eindex = (const uint32_t*) 3857 (((const uint8_t*)ty) + dtohs(ty->header.headerSize)); 3858 3859 const size_t NE = dtohl(ty->entryCount); 3860 for (size_t i=0; i<NE; i++) { 3861 uint32_t offset = dtohl(eindex[i]); 3862 if (offset == ResTable_type::NO_ENTRY) { 3863 continue; 3864 } 3865 3866 offset += typeOffset; 3867 3868 if (offset > (dtohl(ty->header.size)-sizeof(ResTable_entry))) { 3869 ALOGW("ResTable_entry at %d is beyond type chunk data %d", 3870 offset, dtohl(ty->header.size)); 3871 return 0; 3872 } 3873 if ((offset&0x3) != 0) { 3874 ALOGW("ResTable_entry at %d (pkg=%d type=%d ent=%d) is not on an integer boundary when looking for %s:%s/%s", 3875 (int)offset, (int)group->id, (int)ti+1, (int)i, 3876 String8(package, packageLen).string(), 3877 String8(type, typeLen).string(), 3878 String8(name, nameLen).string()); 3879 return 0; 3880 } 3881 3882 const ResTable_entry* const entry = (const ResTable_entry*) 3883 (((const uint8_t*)ty) + offset); 3884 if (dtohs(entry->size) < sizeof(*entry)) { 3885 ALOGW("ResTable_entry size %d is too small", dtohs(entry->size)); 3886 return BAD_TYPE; 3887 } 3888 3889 TABLE_SUPER_NOISY(printf("Looking at entry #%d: want str %d, have %d\n", 3890 i, ei, dtohl(entry->key.index))); 3891 if (dtohl(entry->key.index) == (size_t)ei) { 3892 if (outTypeSpecFlags) { 3893 *outTypeSpecFlags = typeConfigs->typeSpecFlags[i]; 3894 if (fakePublic) { 3895 *outTypeSpecFlags |= ResTable_typeSpec::SPEC_PUBLIC; 3896 } 3897 } 3898 return Res_MAKEID(group->id-1, ti, i); 3899 } 3900 } 3901 } 3902 } 3903 3904 return 0; 3905 } 3906 3907 bool ResTable::expandResourceRef(const uint16_t* refStr, size_t refLen, 3908 String16* outPackage, 3909 String16* outType, 3910 String16* outName, 3911 const String16* defType, 3912 const String16* defPackage, 3913 const char** outErrorMsg, 3914 bool* outPublicOnly) 3915 { 3916 const char16_t* packageEnd = NULL; 3917 const char16_t* typeEnd = NULL; 3918 const char16_t* p = refStr; 3919 const char16_t* const end = p + refLen; 3920 while (p < end) { 3921 if (*p == ':') packageEnd = p; 3922 else if (*p == '/') { 3923 typeEnd = p; 3924 break; 3925 } 3926 p++; 3927 } 3928 p = refStr; 3929 if (*p == '@') p++; 3930 3931 if (outPublicOnly != NULL) { 3932 *outPublicOnly = true; 3933 } 3934 if (*p == '*') { 3935 p++; 3936 if (outPublicOnly != NULL) { 3937 *outPublicOnly = false; 3938 } 3939 } 3940 3941 if (packageEnd) { 3942 *outPackage = String16(p, packageEnd-p); 3943 p = packageEnd+1; 3944 } else { 3945 if (!defPackage) { 3946 if (outErrorMsg) { 3947 *outErrorMsg = "No resource package specified"; 3948 } 3949 return false; 3950 } 3951 *outPackage = *defPackage; 3952 } 3953 if (typeEnd) { 3954 *outType = String16(p, typeEnd-p); 3955 p = typeEnd+1; 3956 } else { 3957 if (!defType) { 3958 if (outErrorMsg) { 3959 *outErrorMsg = "No resource type specified"; 3960 } 3961 return false; 3962 } 3963 *outType = *defType; 3964 } 3965 *outName = String16(p, end-p); 3966 if(**outPackage == 0) { 3967 if(outErrorMsg) { 3968 *outErrorMsg = "Resource package cannot be an empty string"; 3969 } 3970 return false; 3971 } 3972 if(**outType == 0) { 3973 if(outErrorMsg) { 3974 *outErrorMsg = "Resource type cannot be an empty string"; 3975 } 3976 return false; 3977 } 3978 if(**outName == 0) { 3979 if(outErrorMsg) { 3980 *outErrorMsg = "Resource id cannot be an empty string"; 3981 } 3982 return false; 3983 } 3984 return true; 3985 } 3986 3987 static uint32_t get_hex(char c, bool* outError) 3988 { 3989 if (c >= '0' && c <= '9') { 3990 return c - '0'; 3991 } else if (c >= 'a' && c <= 'f') { 3992 return c - 'a' + 0xa; 3993 } else if (c >= 'A' && c <= 'F') { 3994 return c - 'A' + 0xa; 3995 } 3996 *outError = true; 3997 return 0; 3998 } 3999 4000 struct unit_entry 4001 { 4002 const char* name; 4003 size_t len; 4004 uint8_t type; 4005 uint32_t unit; 4006 float scale; 4007 }; 4008 4009 static const unit_entry unitNames[] = { 4010 { "px", strlen("px"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PX, 1.0f }, 4011 { "dip", strlen("dip"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f }, 4012 { "dp", strlen("dp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f }, 4013 { "sp", strlen("sp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_SP, 1.0f }, 4014 { "pt", strlen("pt"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PT, 1.0f }, 4015 { "in", strlen("in"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_IN, 1.0f }, 4016 { "mm", strlen("mm"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_MM, 1.0f }, 4017 { "%", strlen("%"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION, 1.0f/100 }, 4018 { "%p", strlen("%p"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION_PARENT, 1.0f/100 }, 4019 { NULL, 0, 0, 0, 0 } 4020 }; 4021 4022 static bool parse_unit(const char* str, Res_value* outValue, 4023 float* outScale, const char** outEnd) 4024 { 4025 const char* end = str; 4026 while (*end != 0 && !isspace((unsigned char)*end)) { 4027 end++; 4028 } 4029 const size_t len = end-str; 4030 4031 const char* realEnd = end; 4032 while (*realEnd != 0 && isspace((unsigned char)*realEnd)) { 4033 realEnd++; 4034 } 4035 if (*realEnd != 0) { 4036 return false; 4037 } 4038 4039 const unit_entry* cur = unitNames; 4040 while (cur->name) { 4041 if (len == cur->len && strncmp(cur->name, str, len) == 0) { 4042 outValue->dataType = cur->type; 4043 outValue->data = cur->unit << Res_value::COMPLEX_UNIT_SHIFT; 4044 *outScale = cur->scale; 4045 *outEnd = end; 4046 //printf("Found unit %s for %s\n", cur->name, str); 4047 return true; 4048 } 4049 cur++; 4050 } 4051 4052 return false; 4053 } 4054 4055 4056 bool ResTable::stringToInt(const char16_t* s, size_t len, Res_value* outValue) 4057 { 4058 while (len > 0 && isspace16(*s)) { 4059 s++; 4060 len--; 4061 } 4062 4063 if (len <= 0) { 4064 return false; 4065 } 4066 4067 size_t i = 0; 4068 int32_t val = 0; 4069 bool neg = false; 4070 4071 if (*s == '-') { 4072 neg = true; 4073 i++; 4074 } 4075 4076 if (s[i] < '0' || s[i] > '9') { 4077 return false; 4078 } 4079 4080 // Decimal or hex? 4081 if (s[i] == '0' && s[i+1] == 'x') { 4082 if (outValue) 4083 outValue->dataType = outValue->TYPE_INT_HEX; 4084 i += 2; 4085 bool error = false; 4086 while (i < len && !error) { 4087 val = (val*16) + get_hex(s[i], &error); 4088 i++; 4089 } 4090 if (error) { 4091 return false; 4092 } 4093 } else { 4094 if (outValue) 4095 outValue->dataType = outValue->TYPE_INT_DEC; 4096 while (i < len) { 4097 if (s[i] < '0' || s[i] > '9') { 4098 return false; 4099 } 4100 val = (val*10) + s[i]-'0'; 4101 i++; 4102 } 4103 } 4104 4105 if (neg) val = -val; 4106 4107 while (i < len && isspace16(s[i])) { 4108 i++; 4109 } 4110 4111 if (i == len) { 4112 if (outValue) 4113 outValue->data = val; 4114 return true; 4115 } 4116 4117 return false; 4118 } 4119 4120 bool ResTable::stringToFloat(const char16_t* s, size_t len, Res_value* outValue) 4121 { 4122 while (len > 0 && isspace16(*s)) { 4123 s++; 4124 len--; 4125 } 4126 4127 if (len <= 0) { 4128 return false; 4129 } 4130 4131 char buf[128]; 4132 int i=0; 4133 while (len > 0 && *s != 0 && i < 126) { 4134 if (*s > 255) { 4135 return false; 4136 } 4137 buf[i++] = *s++; 4138 len--; 4139 } 4140 4141 if (len > 0) { 4142 return false; 4143 } 4144 if (buf[0] < '0' && buf[0] > '9' && buf[0] != '.') { 4145 return false; 4146 } 4147 4148 buf[i] = 0; 4149 const char* end; 4150 float f = strtof(buf, (char**)&end); 4151 4152 if (*end != 0 && !isspace((unsigned char)*end)) { 4153 // Might be a unit... 4154 float scale; 4155 if (parse_unit(end, outValue, &scale, &end)) { 4156 f *= scale; 4157 const bool neg = f < 0; 4158 if (neg) f = -f; 4159 uint64_t bits = (uint64_t)(f*(1<<23)+.5f); 4160 uint32_t radix; 4161 uint32_t shift; 4162 if ((bits&0x7fffff) == 0) { 4163 // Always use 23p0 if there is no fraction, just to make 4164 // things easier to read. 4165 radix = Res_value::COMPLEX_RADIX_23p0; 4166 shift = 23; 4167 } else if ((bits&0xffffffffff800000LL) == 0) { 4168 // Magnitude is zero -- can fit in 0 bits of precision. 4169 radix = Res_value::COMPLEX_RADIX_0p23; 4170 shift = 0; 4171 } else if ((bits&0xffffffff80000000LL) == 0) { 4172 // Magnitude can fit in 8 bits of precision. 4173 radix = Res_value::COMPLEX_RADIX_8p15; 4174 shift = 8; 4175 } else if ((bits&0xffffff8000000000LL) == 0) { 4176 // Magnitude can fit in 16 bits of precision. 4177 radix = Res_value::COMPLEX_RADIX_16p7; 4178 shift = 16; 4179 } else { 4180 // Magnitude needs entire range, so no fractional part. 4181 radix = Res_value::COMPLEX_RADIX_23p0; 4182 shift = 23; 4183 } 4184 int32_t mantissa = (int32_t)( 4185 (bits>>shift) & Res_value::COMPLEX_MANTISSA_MASK); 4186 if (neg) { 4187 mantissa = (-mantissa) & Res_value::COMPLEX_MANTISSA_MASK; 4188 } 4189 outValue->data |= 4190 (radix<<Res_value::COMPLEX_RADIX_SHIFT) 4191 | (mantissa<<Res_value::COMPLEX_MANTISSA_SHIFT); 4192 //printf("Input value: %f 0x%016Lx, mult: %f, radix: %d, shift: %d, final: 0x%08x\n", 4193 // f * (neg ? -1 : 1), bits, f*(1<<23), 4194 // radix, shift, outValue->data); 4195 return true; 4196 } 4197 return false; 4198 } 4199 4200 while (*end != 0 && isspace((unsigned char)*end)) { 4201 end++; 4202 } 4203 4204 if (*end == 0) { 4205 if (outValue) { 4206 outValue->dataType = outValue->TYPE_FLOAT; 4207 *(float*)(&outValue->data) = f; 4208 return true; 4209 } 4210 } 4211 4212 return false; 4213 } 4214 4215 bool ResTable::stringToValue(Res_value* outValue, String16* outString, 4216 const char16_t* s, size_t len, 4217 bool preserveSpaces, bool coerceType, 4218 uint32_t attrID, 4219 const String16* defType, 4220 const String16* defPackage, 4221 Accessor* accessor, 4222 void* accessorCookie, 4223 uint32_t attrType, 4224 bool enforcePrivate) const 4225 { 4226 bool localizationSetting = accessor != NULL && accessor->getLocalizationSetting(); 4227 const char* errorMsg = NULL; 4228 4229 outValue->size = sizeof(Res_value); 4230 outValue->res0 = 0; 4231 4232 // First strip leading/trailing whitespace. Do this before handling 4233 // escapes, so they can be used to force whitespace into the string. 4234 if (!preserveSpaces) { 4235 while (len > 0 && isspace16(*s)) { 4236 s++; 4237 len--; 4238 } 4239 while (len > 0 && isspace16(s[len-1])) { 4240 len--; 4241 } 4242 // If the string ends with '\', then we keep the space after it. 4243 if (len > 0 && s[len-1] == '\\' && s[len] != 0) { 4244 len++; 4245 } 4246 } 4247 4248 //printf("Value for: %s\n", String8(s, len).string()); 4249 4250 uint32_t l10nReq = ResTable_map::L10N_NOT_REQUIRED; 4251 uint32_t attrMin = 0x80000000, attrMax = 0x7fffffff; 4252 bool fromAccessor = false; 4253 if (attrID != 0 && !Res_INTERNALID(attrID)) { 4254 const ssize_t p = getResourcePackageIndex(attrID); 4255 const bag_entry* bag; 4256 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1; 4257 //printf("For attr 0x%08x got bag of %d\n", attrID, cnt); 4258 if (cnt >= 0) { 4259 while (cnt > 0) { 4260 //printf("Entry 0x%08x = 0x%08x\n", bag->map.name.ident, bag->map.value.data); 4261 switch (bag->map.name.ident) { 4262 case ResTable_map::ATTR_TYPE: 4263 attrType = bag->map.value.data; 4264 break; 4265 case ResTable_map::ATTR_MIN: 4266 attrMin = bag->map.value.data; 4267 break; 4268 case ResTable_map::ATTR_MAX: 4269 attrMax = bag->map.value.data; 4270 break; 4271 case ResTable_map::ATTR_L10N: 4272 l10nReq = bag->map.value.data; 4273 break; 4274 } 4275 bag++; 4276 cnt--; 4277 } 4278 unlockBag(bag); 4279 } else if (accessor && accessor->getAttributeType(attrID, &attrType)) { 4280 fromAccessor = true; 4281 if (attrType == ResTable_map::TYPE_ENUM 4282 || attrType == ResTable_map::TYPE_FLAGS 4283 || attrType == ResTable_map::TYPE_INTEGER) { 4284 accessor->getAttributeMin(attrID, &attrMin); 4285 accessor->getAttributeMax(attrID, &attrMax); 4286 } 4287 if (localizationSetting) { 4288 l10nReq = accessor->getAttributeL10N(attrID); 4289 } 4290 } 4291 } 4292 4293 const bool canStringCoerce = 4294 coerceType && (attrType&ResTable_map::TYPE_STRING) != 0; 4295 4296 if (*s == '@') { 4297 outValue->dataType = outValue->TYPE_REFERENCE; 4298 4299 // Note: we don't check attrType here because the reference can 4300 // be to any other type; we just need to count on the client making 4301 // sure the referenced type is correct. 4302 4303 //printf("Looking up ref: %s\n", String8(s, len).string()); 4304 4305 // It's a reference! 4306 if (len == 5 && s[1]=='n' && s[2]=='u' && s[3]=='l' && s[4]=='l') { 4307 outValue->data = 0; 4308 return true; 4309 } else { 4310 bool createIfNotFound = false; 4311 const char16_t* resourceRefName; 4312 int resourceNameLen; 4313 if (len > 2 && s[1] == '+') { 4314 createIfNotFound = true; 4315 resourceRefName = s + 2; 4316 resourceNameLen = len - 2; 4317 } else if (len > 2 && s[1] == '*') { 4318 enforcePrivate = false; 4319 resourceRefName = s + 2; 4320 resourceNameLen = len - 2; 4321 } else { 4322 createIfNotFound = false; 4323 resourceRefName = s + 1; 4324 resourceNameLen = len - 1; 4325 } 4326 String16 package, type, name; 4327 if (!expandResourceRef(resourceRefName,resourceNameLen, &package, &type, &name, 4328 defType, defPackage, &errorMsg)) { 4329 if (accessor != NULL) { 4330 accessor->reportError(accessorCookie, errorMsg); 4331 } 4332 return false; 4333 } 4334 4335 uint32_t specFlags = 0; 4336 uint32_t rid = identifierForName(name.string(), name.size(), type.string(), 4337 type.size(), package.string(), package.size(), &specFlags); 4338 if (rid != 0) { 4339 if (enforcePrivate) { 4340 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) { 4341 if (accessor != NULL) { 4342 accessor->reportError(accessorCookie, "Resource is not public."); 4343 } 4344 return false; 4345 } 4346 } 4347 if (!accessor) { 4348 outValue->data = rid; 4349 return true; 4350 } 4351 rid = Res_MAKEID( 4352 accessor->getRemappedPackage(Res_GETPACKAGE(rid)), 4353 Res_GETTYPE(rid), Res_GETENTRY(rid)); 4354 TABLE_NOISY(printf("Incl %s:%s/%s: 0x%08x\n", 4355 String8(package).string(), String8(type).string(), 4356 String8(name).string(), rid)); 4357 outValue->data = rid; 4358 return true; 4359 } 4360 4361 if (accessor) { 4362 uint32_t rid = accessor->getCustomResourceWithCreation(package, type, name, 4363 createIfNotFound); 4364 if (rid != 0) { 4365 TABLE_NOISY(printf("Pckg %s:%s/%s: 0x%08x\n", 4366 String8(package).string(), String8(type).string(), 4367 String8(name).string(), rid)); 4368 outValue->data = rid; 4369 return true; 4370 } 4371 } 4372 } 4373 4374 if (accessor != NULL) { 4375 accessor->reportError(accessorCookie, "No resource found that matches the given name"); 4376 } 4377 return false; 4378 } 4379 4380 // if we got to here, and localization is required and it's not a reference, 4381 // complain and bail. 4382 if (l10nReq == ResTable_map::L10N_SUGGESTED) { 4383 if (localizationSetting) { 4384 if (accessor != NULL) { 4385 accessor->reportError(accessorCookie, "This attribute must be localized."); 4386 } 4387 } 4388 } 4389 4390 if (*s == '#') { 4391 // It's a color! Convert to an integer of the form 0xaarrggbb. 4392 uint32_t color = 0; 4393 bool error = false; 4394 if (len == 4) { 4395 outValue->dataType = outValue->TYPE_INT_COLOR_RGB4; 4396 color |= 0xFF000000; 4397 color |= get_hex(s[1], &error) << 20; 4398 color |= get_hex(s[1], &error) << 16; 4399 color |= get_hex(s[2], &error) << 12; 4400 color |= get_hex(s[2], &error) << 8; 4401 color |= get_hex(s[3], &error) << 4; 4402 color |= get_hex(s[3], &error); 4403 } else if (len == 5) { 4404 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB4; 4405 color |= get_hex(s[1], &error) << 28; 4406 color |= get_hex(s[1], &error) << 24; 4407 color |= get_hex(s[2], &error) << 20; 4408 color |= get_hex(s[2], &error) << 16; 4409 color |= get_hex(s[3], &error) << 12; 4410 color |= get_hex(s[3], &error) << 8; 4411 color |= get_hex(s[4], &error) << 4; 4412 color |= get_hex(s[4], &error); 4413 } else if (len == 7) { 4414 outValue->dataType = outValue->TYPE_INT_COLOR_RGB8; 4415 color |= 0xFF000000; 4416 color |= get_hex(s[1], &error) << 20; 4417 color |= get_hex(s[2], &error) << 16; 4418 color |= get_hex(s[3], &error) << 12; 4419 color |= get_hex(s[4], &error) << 8; 4420 color |= get_hex(s[5], &error) << 4; 4421 color |= get_hex(s[6], &error); 4422 } else if (len == 9) { 4423 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB8; 4424 color |= get_hex(s[1], &error) << 28; 4425 color |= get_hex(s[2], &error) << 24; 4426 color |= get_hex(s[3], &error) << 20; 4427 color |= get_hex(s[4], &error) << 16; 4428 color |= get_hex(s[5], &error) << 12; 4429 color |= get_hex(s[6], &error) << 8; 4430 color |= get_hex(s[7], &error) << 4; 4431 color |= get_hex(s[8], &error); 4432 } else { 4433 error = true; 4434 } 4435 if (!error) { 4436 if ((attrType&ResTable_map::TYPE_COLOR) == 0) { 4437 if (!canStringCoerce) { 4438 if (accessor != NULL) { 4439 accessor->reportError(accessorCookie, 4440 "Color types not allowed"); 4441 } 4442 return false; 4443 } 4444 } else { 4445 outValue->data = color; 4446 //printf("Color input=%s, output=0x%x\n", String8(s, len).string(), color); 4447 return true; 4448 } 4449 } else { 4450 if ((attrType&ResTable_map::TYPE_COLOR) != 0) { 4451 if (accessor != NULL) { 4452 accessor->reportError(accessorCookie, "Color value not valid --" 4453 " must be #rgb, #argb, #rrggbb, or #aarrggbb"); 4454 } 4455 #if 0 4456 fprintf(stderr, "%s: Color ID %s value %s is not valid\n", 4457 "Resource File", //(const char*)in->getPrintableSource(), 4458 String8(*curTag).string(), 4459 String8(s, len).string()); 4460 #endif 4461 return false; 4462 } 4463 } 4464 } 4465 4466 if (*s == '?') { 4467 outValue->dataType = outValue->TYPE_ATTRIBUTE; 4468 4469 // Note: we don't check attrType here because the reference can 4470 // be to any other type; we just need to count on the client making 4471 // sure the referenced type is correct. 4472 4473 //printf("Looking up attr: %s\n", String8(s, len).string()); 4474 4475 static const String16 attr16("attr"); 4476 String16 package, type, name; 4477 if (!expandResourceRef(s+1, len-1, &package, &type, &name, 4478 &attr16, defPackage, &errorMsg)) { 4479 if (accessor != NULL) { 4480 accessor->reportError(accessorCookie, errorMsg); 4481 } 4482 return false; 4483 } 4484 4485 //printf("Pkg: %s, Type: %s, Name: %s\n", 4486 // String8(package).string(), String8(type).string(), 4487 // String8(name).string()); 4488 uint32_t specFlags = 0; 4489 uint32_t rid = 4490 identifierForName(name.string(), name.size(), 4491 type.string(), type.size(), 4492 package.string(), package.size(), &specFlags); 4493 if (rid != 0) { 4494 if (enforcePrivate) { 4495 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) { 4496 if (accessor != NULL) { 4497 accessor->reportError(accessorCookie, "Attribute is not public."); 4498 } 4499 return false; 4500 } 4501 } 4502 if (!accessor) { 4503 outValue->data = rid; 4504 return true; 4505 } 4506 rid = Res_MAKEID( 4507 accessor->getRemappedPackage(Res_GETPACKAGE(rid)), 4508 Res_GETTYPE(rid), Res_GETENTRY(rid)); 4509 //printf("Incl %s:%s/%s: 0x%08x\n", 4510 // String8(package).string(), String8(type).string(), 4511 // String8(name).string(), rid); 4512 outValue->data = rid; 4513 return true; 4514 } 4515 4516 if (accessor) { 4517 uint32_t rid = accessor->getCustomResource(package, type, name); 4518 if (rid != 0) { 4519 //printf("Mine %s:%s/%s: 0x%08x\n", 4520 // String8(package).string(), String8(type).string(), 4521 // String8(name).string(), rid); 4522 outValue->data = rid; 4523 return true; 4524 } 4525 } 4526 4527 if (accessor != NULL) { 4528 accessor->reportError(accessorCookie, "No resource found that matches the given name"); 4529 } 4530 return false; 4531 } 4532 4533 if (stringToInt(s, len, outValue)) { 4534 if ((attrType&ResTable_map::TYPE_INTEGER) == 0) { 4535 // If this type does not allow integers, but does allow floats, 4536 // fall through on this error case because the float type should 4537 // be able to accept any integer value. 4538 if (!canStringCoerce && (attrType&ResTable_map::TYPE_FLOAT) == 0) { 4539 if (accessor != NULL) { 4540 accessor->reportError(accessorCookie, "Integer types not allowed"); 4541 } 4542 return false; 4543 } 4544 } else { 4545 if (((int32_t)outValue->data) < ((int32_t)attrMin) 4546 || ((int32_t)outValue->data) > ((int32_t)attrMax)) { 4547 if (accessor != NULL) { 4548 accessor->reportError(accessorCookie, "Integer value out of range"); 4549 } 4550 return false; 4551 } 4552 return true; 4553 } 4554 } 4555 4556 if (stringToFloat(s, len, outValue)) { 4557 if (outValue->dataType == Res_value::TYPE_DIMENSION) { 4558 if ((attrType&ResTable_map::TYPE_DIMENSION) != 0) { 4559 return true; 4560 } 4561 if (!canStringCoerce) { 4562 if (accessor != NULL) { 4563 accessor->reportError(accessorCookie, "Dimension types not allowed"); 4564 } 4565 return false; 4566 } 4567 } else if (outValue->dataType == Res_value::TYPE_FRACTION) { 4568 if ((attrType&ResTable_map::TYPE_FRACTION) != 0) { 4569 return true; 4570 } 4571 if (!canStringCoerce) { 4572 if (accessor != NULL) { 4573 accessor->reportError(accessorCookie, "Fraction types not allowed"); 4574 } 4575 return false; 4576 } 4577 } else if ((attrType&ResTable_map::TYPE_FLOAT) == 0) { 4578 if (!canStringCoerce) { 4579 if (accessor != NULL) { 4580 accessor->reportError(accessorCookie, "Float types not allowed"); 4581 } 4582 return false; 4583 } 4584 } else { 4585 return true; 4586 } 4587 } 4588 4589 if (len == 4) { 4590 if ((s[0] == 't' || s[0] == 'T') && 4591 (s[1] == 'r' || s[1] == 'R') && 4592 (s[2] == 'u' || s[2] == 'U') && 4593 (s[3] == 'e' || s[3] == 'E')) { 4594 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) { 4595 if (!canStringCoerce) { 4596 if (accessor != NULL) { 4597 accessor->reportError(accessorCookie, "Boolean types not allowed"); 4598 } 4599 return false; 4600 } 4601 } else { 4602 outValue->dataType = outValue->TYPE_INT_BOOLEAN; 4603 outValue->data = (uint32_t)-1; 4604 return true; 4605 } 4606 } 4607 } 4608 4609 if (len == 5) { 4610 if ((s[0] == 'f' || s[0] == 'F') && 4611 (s[1] == 'a' || s[1] == 'A') && 4612 (s[2] == 'l' || s[2] == 'L') && 4613 (s[3] == 's' || s[3] == 'S') && 4614 (s[4] == 'e' || s[4] == 'E')) { 4615 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) { 4616 if (!canStringCoerce) { 4617 if (accessor != NULL) { 4618 accessor->reportError(accessorCookie, "Boolean types not allowed"); 4619 } 4620 return false; 4621 } 4622 } else { 4623 outValue->dataType = outValue->TYPE_INT_BOOLEAN; 4624 outValue->data = 0; 4625 return true; 4626 } 4627 } 4628 } 4629 4630 if ((attrType&ResTable_map::TYPE_ENUM) != 0) { 4631 const ssize_t p = getResourcePackageIndex(attrID); 4632 const bag_entry* bag; 4633 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1; 4634 //printf("Got %d for enum\n", cnt); 4635 if (cnt >= 0) { 4636 resource_name rname; 4637 while (cnt > 0) { 4638 if (!Res_INTERNALID(bag->map.name.ident)) { 4639 //printf("Trying attr #%08x\n", bag->map.name.ident); 4640 if (getResourceName(bag->map.name.ident, false, &rname)) { 4641 #if 0 4642 printf("Matching %s against %s (0x%08x)\n", 4643 String8(s, len).string(), 4644 String8(rname.name, rname.nameLen).string(), 4645 bag->map.name.ident); 4646 #endif 4647 if (strzcmp16(s, len, rname.name, rname.nameLen) == 0) { 4648 outValue->dataType = bag->map.value.dataType; 4649 outValue->data = bag->map.value.data; 4650 unlockBag(bag); 4651 return true; 4652 } 4653 } 4654 4655 } 4656 bag++; 4657 cnt--; 4658 } 4659 unlockBag(bag); 4660 } 4661 4662 if (fromAccessor) { 4663 if (accessor->getAttributeEnum(attrID, s, len, outValue)) { 4664 return true; 4665 } 4666 } 4667 } 4668 4669 if ((attrType&ResTable_map::TYPE_FLAGS) != 0) { 4670 const ssize_t p = getResourcePackageIndex(attrID); 4671 const bag_entry* bag; 4672 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1; 4673 //printf("Got %d for flags\n", cnt); 4674 if (cnt >= 0) { 4675 bool failed = false; 4676 resource_name rname; 4677 outValue->dataType = Res_value::TYPE_INT_HEX; 4678 outValue->data = 0; 4679 const char16_t* end = s + len; 4680 const char16_t* pos = s; 4681 while (pos < end && !failed) { 4682 const char16_t* start = pos; 4683 pos++; 4684 while (pos < end && *pos != '|') { 4685 pos++; 4686 } 4687 //printf("Looking for: %s\n", String8(start, pos-start).string()); 4688 const bag_entry* bagi = bag; 4689 ssize_t i; 4690 for (i=0; i<cnt; i++, bagi++) { 4691 if (!Res_INTERNALID(bagi->map.name.ident)) { 4692 //printf("Trying attr #%08x\n", bagi->map.name.ident); 4693 if (getResourceName(bagi->map.name.ident, false, &rname)) { 4694 #if 0 4695 printf("Matching %s against %s (0x%08x)\n", 4696 String8(start,pos-start).string(), 4697 String8(rname.name, rname.nameLen).string(), 4698 bagi->map.name.ident); 4699 #endif 4700 if (strzcmp16(start, pos-start, rname.name, rname.nameLen) == 0) { 4701 outValue->data |= bagi->map.value.data; 4702 break; 4703 } 4704 } 4705 } 4706 } 4707 if (i >= cnt) { 4708 // Didn't find this flag identifier. 4709 failed = true; 4710 } 4711 if (pos < end) { 4712 pos++; 4713 } 4714 } 4715 unlockBag(bag); 4716 if (!failed) { 4717 //printf("Final flag value: 0x%lx\n", outValue->data); 4718 return true; 4719 } 4720 } 4721 4722 4723 if (fromAccessor) { 4724 if (accessor->getAttributeFlags(attrID, s, len, outValue)) { 4725 //printf("Final flag value: 0x%lx\n", outValue->data); 4726 return true; 4727 } 4728 } 4729 } 4730 4731 if ((attrType&ResTable_map::TYPE_STRING) == 0) { 4732 if (accessor != NULL) { 4733 accessor->reportError(accessorCookie, "String types not allowed"); 4734 } 4735 return false; 4736 } 4737 4738 // Generic string handling... 4739 outValue->dataType = outValue->TYPE_STRING; 4740 if (outString) { 4741 bool failed = collectString(outString, s, len, preserveSpaces, &errorMsg); 4742 if (accessor != NULL) { 4743 accessor->reportError(accessorCookie, errorMsg); 4744 } 4745 return failed; 4746 } 4747 4748 return true; 4749 } 4750 4751 bool ResTable::collectString(String16* outString, 4752 const char16_t* s, size_t len, 4753 bool preserveSpaces, 4754 const char** outErrorMsg, 4755 bool append) 4756 { 4757 String16 tmp; 4758 4759 char quoted = 0; 4760 const char16_t* p = s; 4761 while (p < (s+len)) { 4762 while (p < (s+len)) { 4763 const char16_t c = *p; 4764 if (c == '\\') { 4765 break; 4766 } 4767 if (!preserveSpaces) { 4768 if (quoted == 0 && isspace16(c) 4769 && (c != ' ' || isspace16(*(p+1)))) { 4770 break; 4771 } 4772 if (c == '"' && (quoted == 0 || quoted == '"')) { 4773 break; 4774 } 4775 if (c == '\'' && (quoted == 0 || quoted == '\'')) { 4776 /* 4777 * In practice, when people write ' instead of \' 4778 * in a string, they are doing it by accident 4779 * instead of really meaning to use ' as a quoting 4780 * character. Warn them so they don't lose it. 4781 */ 4782 if (outErrorMsg) { 4783 *outErrorMsg = "Apostrophe not preceded by \\"; 4784 } 4785 return false; 4786 } 4787 } 4788 p++; 4789 } 4790 if (p < (s+len)) { 4791 if (p > s) { 4792 tmp.append(String16(s, p-s)); 4793 } 4794 if (!preserveSpaces && (*p == '"' || *p == '\'')) { 4795 if (quoted == 0) { 4796 quoted = *p; 4797 } else { 4798 quoted = 0; 4799 } 4800 p++; 4801 } else if (!preserveSpaces && isspace16(*p)) { 4802 // Space outside of a quote -- consume all spaces and 4803 // leave a single plain space char. 4804 tmp.append(String16(" ")); 4805 p++; 4806 while (p < (s+len) && isspace16(*p)) { 4807 p++; 4808 } 4809 } else if (*p == '\\') { 4810 p++; 4811 if (p < (s+len)) { 4812 switch (*p) { 4813 case 't': 4814 tmp.append(String16("\t")); 4815 break; 4816 case 'n': 4817 tmp.append(String16("\n")); 4818 break; 4819 case '#': 4820 tmp.append(String16("#")); 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 'u': 4838 { 4839 char16_t chr = 0; 4840 int i = 0; 4841 while (i < 4 && p[1] != 0) { 4842 p++; 4843 i++; 4844 int c; 4845 if (*p >= '0' && *p <= '9') { 4846 c = *p - '0'; 4847 } else if (*p >= 'a' && *p <= 'f') { 4848 c = *p - 'a' + 10; 4849 } else if (*p >= 'A' && *p <= 'F') { 4850 c = *p - 'A' + 10; 4851 } else { 4852 if (outErrorMsg) { 4853 *outErrorMsg = "Bad character in \\u unicode escape sequence"; 4854 } 4855 return false; 4856 } 4857 chr = (chr<<4) | c; 4858 } 4859 tmp.append(String16(&chr, 1)); 4860 } break; 4861 default: 4862 // ignore unknown escape chars. 4863 break; 4864 } 4865 p++; 4866 } 4867 } 4868 len -= (p-s); 4869 s = p; 4870 } 4871 } 4872 4873 if (tmp.size() != 0) { 4874 if (len > 0) { 4875 tmp.append(String16(s, len)); 4876 } 4877 if (append) { 4878 outString->append(tmp); 4879 } else { 4880 outString->setTo(tmp); 4881 } 4882 } else { 4883 if (append) { 4884 outString->append(String16(s, len)); 4885 } else { 4886 outString->setTo(s, len); 4887 } 4888 } 4889 4890 return true; 4891 } 4892 4893 size_t ResTable::getBasePackageCount() const 4894 { 4895 if (mError != NO_ERROR) { 4896 return 0; 4897 } 4898 return mPackageGroups.size(); 4899 } 4900 4901 const char16_t* ResTable::getBasePackageName(size_t idx) const 4902 { 4903 if (mError != NO_ERROR) { 4904 return 0; 4905 } 4906 LOG_FATAL_IF(idx >= mPackageGroups.size(), 4907 "Requested package index %d past package count %d", 4908 (int)idx, (int)mPackageGroups.size()); 4909 return mPackageGroups[idx]->name.string(); 4910 } 4911 4912 uint32_t ResTable::getBasePackageId(size_t idx) const 4913 { 4914 if (mError != NO_ERROR) { 4915 return 0; 4916 } 4917 LOG_FATAL_IF(idx >= mPackageGroups.size(), 4918 "Requested package index %d past package count %d", 4919 (int)idx, (int)mPackageGroups.size()); 4920 return mPackageGroups[idx]->id; 4921 } 4922 4923 size_t ResTable::getTableCount() const 4924 { 4925 return mHeaders.size(); 4926 } 4927 4928 const ResStringPool* ResTable::getTableStringBlock(size_t index) const 4929 { 4930 return &mHeaders[index]->values; 4931 } 4932 4933 void* ResTable::getTableCookie(size_t index) const 4934 { 4935 return mHeaders[index]->cookie; 4936 } 4937 4938 void ResTable::getConfigurations(Vector<ResTable_config>* configs) const 4939 { 4940 const size_t I = mPackageGroups.size(); 4941 for (size_t i=0; i<I; i++) { 4942 const PackageGroup* packageGroup = mPackageGroups[i]; 4943 const size_t J = packageGroup->packages.size(); 4944 for (size_t j=0; j<J; j++) { 4945 const Package* package = packageGroup->packages[j]; 4946 const size_t K = package->types.size(); 4947 for (size_t k=0; k<K; k++) { 4948 const Type* type = package->types[k]; 4949 if (type == NULL) continue; 4950 const size_t L = type->configs.size(); 4951 for (size_t l=0; l<L; l++) { 4952 const ResTable_type* config = type->configs[l]; 4953 const ResTable_config* cfg = &config->config; 4954 // only insert unique 4955 const size_t M = configs->size(); 4956 size_t m; 4957 for (m=0; m<M; m++) { 4958 if (0 == (*configs)[m].compare(*cfg)) { 4959 break; 4960 } 4961 } 4962 // if we didn't find it 4963 if (m == M) { 4964 configs->add(*cfg); 4965 } 4966 } 4967 } 4968 } 4969 } 4970 } 4971 4972 void ResTable::getLocales(Vector<String8>* locales) const 4973 { 4974 Vector<ResTable_config> configs; 4975 ALOGV("calling getConfigurations"); 4976 getConfigurations(&configs); 4977 ALOGV("called getConfigurations size=%d", (int)configs.size()); 4978 const size_t I = configs.size(); 4979 for (size_t i=0; i<I; i++) { 4980 char locale[6]; 4981 configs[i].getLocale(locale); 4982 const size_t J = locales->size(); 4983 size_t j; 4984 for (j=0; j<J; j++) { 4985 if (0 == strcmp(locale, (*locales)[j].string())) { 4986 break; 4987 } 4988 } 4989 if (j == J) { 4990 locales->add(String8(locale)); 4991 } 4992 } 4993 } 4994 4995 ssize_t ResTable::getEntry( 4996 const Package* package, int typeIndex, int entryIndex, 4997 const ResTable_config* config, 4998 const ResTable_type** outType, const ResTable_entry** outEntry, 4999 const Type** outTypeClass) const 5000 { 5001 ALOGV("Getting entry from package %p\n", package); 5002 const ResTable_package* const pkg = package->package; 5003 5004 const Type* allTypes = package->getType(typeIndex); 5005 ALOGV("allTypes=%p\n", allTypes); 5006 if (allTypes == NULL) { 5007 ALOGV("Skipping entry type index 0x%02x because type is NULL!\n", typeIndex); 5008 return 0; 5009 } 5010 5011 if ((size_t)entryIndex >= allTypes->entryCount) { 5012 ALOGW("getEntry failing because entryIndex %d is beyond type entryCount %d", 5013 entryIndex, (int)allTypes->entryCount); 5014 return BAD_TYPE; 5015 } 5016 5017 const ResTable_type* type = NULL; 5018 uint32_t offset = ResTable_type::NO_ENTRY; 5019 ResTable_config bestConfig; 5020 memset(&bestConfig, 0, sizeof(bestConfig)); // make the compiler shut up 5021 5022 const size_t NT = allTypes->configs.size(); 5023 for (size_t i=0; i<NT; i++) { 5024 const ResTable_type* const thisType = allTypes->configs[i]; 5025 if (thisType == NULL) continue; 5026 5027 ResTable_config thisConfig; 5028 thisConfig.copyFromDtoH(thisType->config); 5029 5030 TABLE_GETENTRY(ALOGI("Match entry 0x%x in type 0x%x (sz 0x%x): %s\n", 5031 entryIndex, typeIndex+1, dtohl(thisType->config.size), 5032 thisConfig.toString().string())); 5033 5034 // Check to make sure this one is valid for the current parameters. 5035 if (config && !thisConfig.match(*config)) { 5036 TABLE_GETENTRY(ALOGI("Does not match config!\n")); 5037 continue; 5038 } 5039 5040 // Check if there is the desired entry in this type. 5041 5042 const uint8_t* const end = ((const uint8_t*)thisType) 5043 + dtohl(thisType->header.size); 5044 const uint32_t* const eindex = (const uint32_t*) 5045 (((const uint8_t*)thisType) + dtohs(thisType->header.headerSize)); 5046 5047 uint32_t thisOffset = dtohl(eindex[entryIndex]); 5048 if (thisOffset == ResTable_type::NO_ENTRY) { 5049 TABLE_GETENTRY(ALOGI("Skipping because it is not defined!\n")); 5050 continue; 5051 } 5052 5053 if (type != NULL) { 5054 // Check if this one is less specific than the last found. If so, 5055 // we will skip it. We check starting with things we most care 5056 // about to those we least care about. 5057 if (!thisConfig.isBetterThan(bestConfig, config)) { 5058 TABLE_GETENTRY(ALOGI("This config is worse than last!\n")); 5059 continue; 5060 } 5061 } 5062 5063 type = thisType; 5064 offset = thisOffset; 5065 bestConfig = thisConfig; 5066 TABLE_GETENTRY(ALOGI("Best entry so far -- using it!\n")); 5067 if (!config) break; 5068 } 5069 5070 if (type == NULL) { 5071 TABLE_GETENTRY(ALOGI("No value found for requested entry!\n")); 5072 return BAD_INDEX; 5073 } 5074 5075 offset += dtohl(type->entriesStart); 5076 TABLE_NOISY(aout << "Looking in resource table " << package->header->header 5077 << ", typeOff=" 5078 << (void*)(((const char*)type)-((const char*)package->header->header)) 5079 << ", offset=" << (void*)offset << endl); 5080 5081 if (offset > (dtohl(type->header.size)-sizeof(ResTable_entry))) { 5082 ALOGW("ResTable_entry at 0x%x is beyond type chunk data 0x%x", 5083 offset, dtohl(type->header.size)); 5084 return BAD_TYPE; 5085 } 5086 if ((offset&0x3) != 0) { 5087 ALOGW("ResTable_entry at 0x%x is not on an integer boundary", 5088 offset); 5089 return BAD_TYPE; 5090 } 5091 5092 const ResTable_entry* const entry = (const ResTable_entry*) 5093 (((const uint8_t*)type) + offset); 5094 if (dtohs(entry->size) < sizeof(*entry)) { 5095 ALOGW("ResTable_entry size 0x%x is too small", dtohs(entry->size)); 5096 return BAD_TYPE; 5097 } 5098 5099 *outType = type; 5100 *outEntry = entry; 5101 if (outTypeClass != NULL) { 5102 *outTypeClass = allTypes; 5103 } 5104 return offset + dtohs(entry->size); 5105 } 5106 5107 status_t ResTable::parsePackage(const ResTable_package* const pkg, 5108 const Header* const header, uint32_t idmap_id) 5109 { 5110 const uint8_t* base = (const uint8_t*)pkg; 5111 status_t err = validate_chunk(&pkg->header, sizeof(*pkg), 5112 header->dataEnd, "ResTable_package"); 5113 if (err != NO_ERROR) { 5114 return (mError=err); 5115 } 5116 5117 const size_t pkgSize = dtohl(pkg->header.size); 5118 5119 if (dtohl(pkg->typeStrings) >= pkgSize) { 5120 ALOGW("ResTable_package type strings at %p are past chunk size %p.", 5121 (void*)dtohl(pkg->typeStrings), (void*)pkgSize); 5122 return (mError=BAD_TYPE); 5123 } 5124 if ((dtohl(pkg->typeStrings)&0x3) != 0) { 5125 ALOGW("ResTable_package type strings at %p is not on an integer boundary.", 5126 (void*)dtohl(pkg->typeStrings)); 5127 return (mError=BAD_TYPE); 5128 } 5129 if (dtohl(pkg->keyStrings) >= pkgSize) { 5130 ALOGW("ResTable_package key strings at %p are past chunk size %p.", 5131 (void*)dtohl(pkg->keyStrings), (void*)pkgSize); 5132 return (mError=BAD_TYPE); 5133 } 5134 if ((dtohl(pkg->keyStrings)&0x3) != 0) { 5135 ALOGW("ResTable_package key strings at %p is not on an integer boundary.", 5136 (void*)dtohl(pkg->keyStrings)); 5137 return (mError=BAD_TYPE); 5138 } 5139 5140 Package* package = NULL; 5141 PackageGroup* group = NULL; 5142 uint32_t id = idmap_id != 0 ? idmap_id : dtohl(pkg->id); 5143 // If at this point id == 0, pkg is an overlay package without a 5144 // corresponding idmap. During regular usage, overlay packages are 5145 // always loaded alongside their idmaps, but during idmap creation 5146 // the package is temporarily loaded by itself. 5147 if (id < 256) { 5148 5149 package = new Package(this, header, pkg); 5150 if (package == NULL) { 5151 return (mError=NO_MEMORY); 5152 } 5153 5154 size_t idx = mPackageMap[id]; 5155 if (idx == 0) { 5156 idx = mPackageGroups.size()+1; 5157 5158 char16_t tmpName[sizeof(pkg->name)/sizeof(char16_t)]; 5159 strcpy16_dtoh(tmpName, pkg->name, sizeof(pkg->name)/sizeof(char16_t)); 5160 group = new PackageGroup(this, String16(tmpName), id); 5161 if (group == NULL) { 5162 delete package; 5163 return (mError=NO_MEMORY); 5164 } 5165 5166 err = package->typeStrings.setTo(base+dtohl(pkg->typeStrings), 5167 header->dataEnd-(base+dtohl(pkg->typeStrings))); 5168 if (err != NO_ERROR) { 5169 delete group; 5170 delete package; 5171 return (mError=err); 5172 } 5173 err = package->keyStrings.setTo(base+dtohl(pkg->keyStrings), 5174 header->dataEnd-(base+dtohl(pkg->keyStrings))); 5175 if (err != NO_ERROR) { 5176 delete group; 5177 delete package; 5178 return (mError=err); 5179 } 5180 5181 //printf("Adding new package id %d at index %d\n", id, idx); 5182 err = mPackageGroups.add(group); 5183 if (err < NO_ERROR) { 5184 return (mError=err); 5185 } 5186 group->basePackage = package; 5187 5188 mPackageMap[id] = (uint8_t)idx; 5189 } else { 5190 group = mPackageGroups.itemAt(idx-1); 5191 if (group == NULL) { 5192 return (mError=UNKNOWN_ERROR); 5193 } 5194 } 5195 err = group->packages.add(package); 5196 if (err < NO_ERROR) { 5197 return (mError=err); 5198 } 5199 } else { 5200 LOG_ALWAYS_FATAL("Package id out of range"); 5201 return NO_ERROR; 5202 } 5203 5204 5205 // Iterate through all chunks. 5206 size_t curPackage = 0; 5207 5208 const ResChunk_header* chunk = 5209 (const ResChunk_header*)(((const uint8_t*)pkg) 5210 + dtohs(pkg->header.headerSize)); 5211 const uint8_t* endPos = ((const uint8_t*)pkg) + dtohs(pkg->header.size); 5212 while (((const uint8_t*)chunk) <= (endPos-sizeof(ResChunk_header)) && 5213 ((const uint8_t*)chunk) <= (endPos-dtohl(chunk->size))) { 5214 TABLE_NOISY(ALOGV("PackageChunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n", 5215 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size), 5216 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)))); 5217 const size_t csize = dtohl(chunk->size); 5218 const uint16_t ctype = dtohs(chunk->type); 5219 if (ctype == RES_TABLE_TYPE_SPEC_TYPE) { 5220 const ResTable_typeSpec* typeSpec = (const ResTable_typeSpec*)(chunk); 5221 err = validate_chunk(&typeSpec->header, sizeof(*typeSpec), 5222 endPos, "ResTable_typeSpec"); 5223 if (err != NO_ERROR) { 5224 return (mError=err); 5225 } 5226 5227 const size_t typeSpecSize = dtohl(typeSpec->header.size); 5228 5229 LOAD_TABLE_NOISY(printf("TypeSpec off %p: type=0x%x, headerSize=0x%x, size=%p\n", 5230 (void*)(base-(const uint8_t*)chunk), 5231 dtohs(typeSpec->header.type), 5232 dtohs(typeSpec->header.headerSize), 5233 (void*)typeSize)); 5234 // look for block overrun or int overflow when multiplying by 4 5235 if ((dtohl(typeSpec->entryCount) > (INT32_MAX/sizeof(uint32_t)) 5236 || dtohs(typeSpec->header.headerSize)+(sizeof(uint32_t)*dtohl(typeSpec->entryCount)) 5237 > typeSpecSize)) { 5238 ALOGW("ResTable_typeSpec entry index to %p extends beyond chunk end %p.", 5239 (void*)(dtohs(typeSpec->header.headerSize) 5240 +(sizeof(uint32_t)*dtohl(typeSpec->entryCount))), 5241 (void*)typeSpecSize); 5242 return (mError=BAD_TYPE); 5243 } 5244 5245 if (typeSpec->id == 0) { 5246 ALOGW("ResTable_type has an id of 0."); 5247 return (mError=BAD_TYPE); 5248 } 5249 5250 while (package->types.size() < typeSpec->id) { 5251 package->types.add(NULL); 5252 } 5253 Type* t = package->types[typeSpec->id-1]; 5254 if (t == NULL) { 5255 t = new Type(header, package, dtohl(typeSpec->entryCount)); 5256 package->types.editItemAt(typeSpec->id-1) = t; 5257 } else if (dtohl(typeSpec->entryCount) != t->entryCount) { 5258 ALOGW("ResTable_typeSpec entry count inconsistent: given %d, previously %d", 5259 (int)dtohl(typeSpec->entryCount), (int)t->entryCount); 5260 return (mError=BAD_TYPE); 5261 } 5262 t->typeSpecFlags = (const uint32_t*)( 5263 ((const uint8_t*)typeSpec) + dtohs(typeSpec->header.headerSize)); 5264 t->typeSpec = typeSpec; 5265 5266 } else if (ctype == RES_TABLE_TYPE_TYPE) { 5267 const ResTable_type* type = (const ResTable_type*)(chunk); 5268 err = validate_chunk(&type->header, sizeof(*type)-sizeof(ResTable_config)+4, 5269 endPos, "ResTable_type"); 5270 if (err != NO_ERROR) { 5271 return (mError=err); 5272 } 5273 5274 const size_t typeSize = dtohl(type->header.size); 5275 5276 LOAD_TABLE_NOISY(printf("Type off %p: type=0x%x, headerSize=0x%x, size=%p\n", 5277 (void*)(base-(const uint8_t*)chunk), 5278 dtohs(type->header.type), 5279 dtohs(type->header.headerSize), 5280 (void*)typeSize)); 5281 if (dtohs(type->header.headerSize)+(sizeof(uint32_t)*dtohl(type->entryCount)) 5282 > typeSize) { 5283 ALOGW("ResTable_type entry index to %p extends beyond chunk end %p.", 5284 (void*)(dtohs(type->header.headerSize) 5285 +(sizeof(uint32_t)*dtohl(type->entryCount))), 5286 (void*)typeSize); 5287 return (mError=BAD_TYPE); 5288 } 5289 if (dtohl(type->entryCount) != 0 5290 && dtohl(type->entriesStart) > (typeSize-sizeof(ResTable_entry))) { 5291 ALOGW("ResTable_type entriesStart at %p extends beyond chunk end %p.", 5292 (void*)dtohl(type->entriesStart), (void*)typeSize); 5293 return (mError=BAD_TYPE); 5294 } 5295 if (type->id == 0) { 5296 ALOGW("ResTable_type has an id of 0."); 5297 return (mError=BAD_TYPE); 5298 } 5299 5300 while (package->types.size() < type->id) { 5301 package->types.add(NULL); 5302 } 5303 Type* t = package->types[type->id-1]; 5304 if (t == NULL) { 5305 t = new Type(header, package, dtohl(type->entryCount)); 5306 package->types.editItemAt(type->id-1) = t; 5307 } else if (dtohl(type->entryCount) != t->entryCount) { 5308 ALOGW("ResTable_type entry count inconsistent: given %d, previously %d", 5309 (int)dtohl(type->entryCount), (int)t->entryCount); 5310 return (mError=BAD_TYPE); 5311 } 5312 5313 TABLE_GETENTRY( 5314 ResTable_config thisConfig; 5315 thisConfig.copyFromDtoH(type->config); 5316 ALOGI("Adding config to type %d: %s\n", 5317 type->id, thisConfig.toString().string())); 5318 t->configs.add(type); 5319 } else { 5320 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), 5321 endPos, "ResTable_package:unknown"); 5322 if (err != NO_ERROR) { 5323 return (mError=err); 5324 } 5325 } 5326 chunk = (const ResChunk_header*) 5327 (((const uint8_t*)chunk) + csize); 5328 } 5329 5330 if (group->typeCount == 0) { 5331 group->typeCount = package->types.size(); 5332 } 5333 5334 return NO_ERROR; 5335 } 5336 5337 status_t ResTable::createIdmap(const ResTable& overlay, uint32_t originalCrc, uint32_t overlayCrc, 5338 void** outData, size_t* outSize) const 5339 { 5340 // see README for details on the format of map 5341 if (mPackageGroups.size() == 0) { 5342 return UNKNOWN_ERROR; 5343 } 5344 if (mPackageGroups[0]->packages.size() == 0) { 5345 return UNKNOWN_ERROR; 5346 } 5347 5348 Vector<Vector<uint32_t> > map; 5349 const PackageGroup* pg = mPackageGroups[0]; 5350 const Package* pkg = pg->packages[0]; 5351 size_t typeCount = pkg->types.size(); 5352 // starting size is header + first item (number of types in map) 5353 *outSize = (IDMAP_HEADER_SIZE + 1) * sizeof(uint32_t); 5354 const String16 overlayPackage(overlay.mPackageGroups[0]->packages[0]->package->name); 5355 const uint32_t pkg_id = pkg->package->id << 24; 5356 5357 for (size_t typeIndex = 0; typeIndex < typeCount; ++typeIndex) { 5358 ssize_t first = -1; 5359 ssize_t last = -1; 5360 const Type* typeConfigs = pkg->getType(typeIndex); 5361 ssize_t mapIndex = map.add(); 5362 if (mapIndex < 0) { 5363 return NO_MEMORY; 5364 } 5365 Vector<uint32_t>& vector = map.editItemAt(mapIndex); 5366 for (size_t entryIndex = 0; entryIndex < typeConfigs->entryCount; ++entryIndex) { 5367 uint32_t resID = pkg_id 5368 | (0x00ff0000 & ((typeIndex+1)<<16)) 5369 | (0x0000ffff & (entryIndex)); 5370 resource_name resName; 5371 if (!this->getResourceName(resID, true, &resName)) { 5372 ALOGW("idmap: resource 0x%08x has spec but lacks values, skipping\n", resID); 5373 // add dummy value, or trimming leading/trailing zeroes later will fail 5374 vector.push(0); 5375 continue; 5376 } 5377 5378 const String16 overlayType(resName.type, resName.typeLen); 5379 const String16 overlayName(resName.name, resName.nameLen); 5380 uint32_t overlayResID = overlay.identifierForName(overlayName.string(), 5381 overlayName.size(), 5382 overlayType.string(), 5383 overlayType.size(), 5384 overlayPackage.string(), 5385 overlayPackage.size()); 5386 if (overlayResID != 0) { 5387 overlayResID = pkg_id | (0x00ffffff & overlayResID); 5388 last = Res_GETENTRY(resID); 5389 if (first == -1) { 5390 first = Res_GETENTRY(resID); 5391 } 5392 } 5393 vector.push(overlayResID); 5394 #if 0 5395 if (overlayResID != 0) { 5396 ALOGD("%s/%s 0x%08x -> 0x%08x\n", 5397 String8(String16(resName.type)).string(), 5398 String8(String16(resName.name)).string(), 5399 resID, overlayResID); 5400 } 5401 #endif 5402 } 5403 5404 if (first != -1) { 5405 // shave off trailing entries which lack overlay values 5406 const size_t last_past_one = last + 1; 5407 if (last_past_one < vector.size()) { 5408 vector.removeItemsAt(last_past_one, vector.size() - last_past_one); 5409 } 5410 // shave off leading entries which lack overlay values 5411 vector.removeItemsAt(0, first); 5412 // store offset to first overlaid resource ID of this type 5413 vector.insertAt((uint32_t)first, 0, 1); 5414 // reserve space for number and offset of entries, and the actual entries 5415 *outSize += (2 + vector.size()) * sizeof(uint32_t); 5416 } else { 5417 // no entries of current type defined in overlay package 5418 vector.clear(); 5419 // reserve space for type offset 5420 *outSize += 1 * sizeof(uint32_t); 5421 } 5422 } 5423 5424 if ((*outData = malloc(*outSize)) == NULL) { 5425 return NO_MEMORY; 5426 } 5427 uint32_t* data = (uint32_t*)*outData; 5428 *data++ = htodl(IDMAP_MAGIC); 5429 *data++ = htodl(originalCrc); 5430 *data++ = htodl(overlayCrc); 5431 const size_t mapSize = map.size(); 5432 *data++ = htodl(mapSize); 5433 size_t offset = mapSize; 5434 for (size_t i = 0; i < mapSize; ++i) { 5435 const Vector<uint32_t>& vector = map.itemAt(i); 5436 const size_t N = vector.size(); 5437 if (N == 0) { 5438 *data++ = htodl(0); 5439 } else { 5440 offset++; 5441 *data++ = htodl(offset); 5442 offset += N; 5443 } 5444 } 5445 for (size_t i = 0; i < mapSize; ++i) { 5446 const Vector<uint32_t>& vector = map.itemAt(i); 5447 const size_t N = vector.size(); 5448 if (N == 0) { 5449 continue; 5450 } 5451 if (N == 1) { // vector expected to hold (offset) + (N > 0 entries) 5452 ALOGW("idmap: type %d supposedly has entries, but no entries found\n", i); 5453 return UNKNOWN_ERROR; 5454 } 5455 *data++ = htodl(N - 1); // do not count the offset (which is vector's first element) 5456 for (size_t j = 0; j < N; ++j) { 5457 const uint32_t& overlayResID = vector.itemAt(j); 5458 *data++ = htodl(overlayResID); 5459 } 5460 } 5461 5462 return NO_ERROR; 5463 } 5464 5465 bool ResTable::getIdmapInfo(const void* idmap, size_t sizeBytes, 5466 uint32_t* pOriginalCrc, uint32_t* pOverlayCrc) 5467 { 5468 const uint32_t* map = (const uint32_t*)idmap; 5469 if (!assertIdmapHeader(map, sizeBytes)) { 5470 return false; 5471 } 5472 *pOriginalCrc = map[1]; 5473 *pOverlayCrc = map[2]; 5474 return true; 5475 } 5476 5477 5478 #define CHAR16_TO_CSTR(c16, len) (String8(String16(c16,len)).string()) 5479 5480 #define CHAR16_ARRAY_EQ(constant, var, len) \ 5481 ((len == (sizeof(constant)/sizeof(constant[0]))) && (0 == memcmp((var), (constant), (len)))) 5482 5483 static void print_complex(uint32_t complex, bool isFraction) 5484 { 5485 const float MANTISSA_MULT = 5486 1.0f / (1<<Res_value::COMPLEX_MANTISSA_SHIFT); 5487 const float RADIX_MULTS[] = { 5488 1.0f*MANTISSA_MULT, 1.0f/(1<<7)*MANTISSA_MULT, 5489 1.0f/(1<<15)*MANTISSA_MULT, 1.0f/(1<<23)*MANTISSA_MULT 5490 }; 5491 5492 float value = (complex&(Res_value::COMPLEX_MANTISSA_MASK 5493 <<Res_value::COMPLEX_MANTISSA_SHIFT)) 5494 * RADIX_MULTS[(complex>>Res_value::COMPLEX_RADIX_SHIFT) 5495 & Res_value::COMPLEX_RADIX_MASK]; 5496 printf("%f", value); 5497 5498 if (!isFraction) { 5499 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) { 5500 case Res_value::COMPLEX_UNIT_PX: printf("px"); break; 5501 case Res_value::COMPLEX_UNIT_DIP: printf("dp"); break; 5502 case Res_value::COMPLEX_UNIT_SP: printf("sp"); break; 5503 case Res_value::COMPLEX_UNIT_PT: printf("pt"); break; 5504 case Res_value::COMPLEX_UNIT_IN: printf("in"); break; 5505 case Res_value::COMPLEX_UNIT_MM: printf("mm"); break; 5506 default: printf(" (unknown unit)"); break; 5507 } 5508 } else { 5509 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) { 5510 case Res_value::COMPLEX_UNIT_FRACTION: printf("%%"); break; 5511 case Res_value::COMPLEX_UNIT_FRACTION_PARENT: printf("%%p"); break; 5512 default: printf(" (unknown unit)"); break; 5513 } 5514 } 5515 } 5516 5517 // Normalize a string for output 5518 String8 ResTable::normalizeForOutput( const char *input ) 5519 { 5520 String8 ret; 5521 char buff[2]; 5522 buff[1] = '\0'; 5523 5524 while (*input != '\0') { 5525 switch (*input) { 5526 // All interesting characters are in the ASCII zone, so we are making our own lives 5527 // easier by scanning the string one byte at a time. 5528 case '\\': 5529 ret += "\\\\"; 5530 break; 5531 case '\n': 5532 ret += "\\n"; 5533 break; 5534 case '"': 5535 ret += "\\\""; 5536 break; 5537 default: 5538 buff[0] = *input; 5539 ret += buff; 5540 break; 5541 } 5542 5543 input++; 5544 } 5545 5546 return ret; 5547 } 5548 5549 void ResTable::print_value(const Package* pkg, const Res_value& value) const 5550 { 5551 if (value.dataType == Res_value::TYPE_NULL) { 5552 printf("(null)\n"); 5553 } else if (value.dataType == Res_value::TYPE_REFERENCE) { 5554 printf("(reference) 0x%08x\n", value.data); 5555 } else if (value.dataType == Res_value::TYPE_ATTRIBUTE) { 5556 printf("(attribute) 0x%08x\n", value.data); 5557 } else if (value.dataType == Res_value::TYPE_STRING) { 5558 size_t len; 5559 const char* str8 = pkg->header->values.string8At( 5560 value.data, &len); 5561 if (str8 != NULL) { 5562 printf("(string8) \"%s\"\n", normalizeForOutput(str8).string()); 5563 } else { 5564 const char16_t* str16 = pkg->header->values.stringAt( 5565 value.data, &len); 5566 if (str16 != NULL) { 5567 printf("(string16) \"%s\"\n", 5568 normalizeForOutput(String8(str16, len).string()).string()); 5569 } else { 5570 printf("(string) null\n"); 5571 } 5572 } 5573 } else if (value.dataType == Res_value::TYPE_FLOAT) { 5574 printf("(float) %g\n", *(const float*)&value.data); 5575 } else if (value.dataType == Res_value::TYPE_DIMENSION) { 5576 printf("(dimension) "); 5577 print_complex(value.data, false); 5578 printf("\n"); 5579 } else if (value.dataType == Res_value::TYPE_FRACTION) { 5580 printf("(fraction) "); 5581 print_complex(value.data, true); 5582 printf("\n"); 5583 } else if (value.dataType >= Res_value::TYPE_FIRST_COLOR_INT 5584 || value.dataType <= Res_value::TYPE_LAST_COLOR_INT) { 5585 printf("(color) #%08x\n", value.data); 5586 } else if (value.dataType == Res_value::TYPE_INT_BOOLEAN) { 5587 printf("(boolean) %s\n", value.data ? "true" : "false"); 5588 } else if (value.dataType >= Res_value::TYPE_FIRST_INT 5589 || value.dataType <= Res_value::TYPE_LAST_INT) { 5590 printf("(int) 0x%08x or %d\n", value.data, value.data); 5591 } else { 5592 printf("(unknown type) t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)\n", 5593 (int)value.dataType, (int)value.data, 5594 (int)value.size, (int)value.res0); 5595 } 5596 } 5597 5598 void ResTable::print(bool inclValues) const 5599 { 5600 if (mError != 0) { 5601 printf("mError=0x%x (%s)\n", mError, strerror(mError)); 5602 } 5603 #if 0 5604 printf("mParams=%c%c-%c%c,\n", 5605 mParams.language[0], mParams.language[1], 5606 mParams.country[0], mParams.country[1]); 5607 #endif 5608 size_t pgCount = mPackageGroups.size(); 5609 printf("Package Groups (%d)\n", (int)pgCount); 5610 for (size_t pgIndex=0; pgIndex<pgCount; pgIndex++) { 5611 const PackageGroup* pg = mPackageGroups[pgIndex]; 5612 printf("Package Group %d id=%d packageCount=%d name=%s\n", 5613 (int)pgIndex, pg->id, (int)pg->packages.size(), 5614 String8(pg->name).string()); 5615 5616 size_t pkgCount = pg->packages.size(); 5617 for (size_t pkgIndex=0; pkgIndex<pkgCount; pkgIndex++) { 5618 const Package* pkg = pg->packages[pkgIndex]; 5619 size_t typeCount = pkg->types.size(); 5620 printf(" Package %d id=%d name=%s typeCount=%d\n", (int)pkgIndex, 5621 pkg->package->id, String8(String16(pkg->package->name)).string(), 5622 (int)typeCount); 5623 for (size_t typeIndex=0; typeIndex<typeCount; typeIndex++) { 5624 const Type* typeConfigs = pkg->getType(typeIndex); 5625 if (typeConfigs == NULL) { 5626 printf(" type %d NULL\n", (int)typeIndex); 5627 continue; 5628 } 5629 const size_t NTC = typeConfigs->configs.size(); 5630 printf(" type %d configCount=%d entryCount=%d\n", 5631 (int)typeIndex, (int)NTC, (int)typeConfigs->entryCount); 5632 if (typeConfigs->typeSpecFlags != NULL) { 5633 for (size_t entryIndex=0; entryIndex<typeConfigs->entryCount; entryIndex++) { 5634 uint32_t resID = (0xff000000 & ((pkg->package->id)<<24)) 5635 | (0x00ff0000 & ((typeIndex+1)<<16)) 5636 | (0x0000ffff & (entryIndex)); 5637 resource_name resName; 5638 if (this->getResourceName(resID, true, &resName)) { 5639 String8 type8; 5640 String8 name8; 5641 if (resName.type8 != NULL) { 5642 type8 = String8(resName.type8, resName.typeLen); 5643 } else { 5644 type8 = String8(resName.type, resName.typeLen); 5645 } 5646 if (resName.name8 != NULL) { 5647 name8 = String8(resName.name8, resName.nameLen); 5648 } else { 5649 name8 = String8(resName.name, resName.nameLen); 5650 } 5651 printf(" spec resource 0x%08x %s:%s/%s: flags=0x%08x\n", 5652 resID, 5653 CHAR16_TO_CSTR(resName.package, resName.packageLen), 5654 type8.string(), name8.string(), 5655 dtohl(typeConfigs->typeSpecFlags[entryIndex])); 5656 } else { 5657 printf(" INVALID TYPE CONFIG FOR RESOURCE 0x%08x\n", resID); 5658 } 5659 } 5660 } 5661 for (size_t configIndex=0; configIndex<NTC; configIndex++) { 5662 const ResTable_type* type = typeConfigs->configs[configIndex]; 5663 if ((((uint64_t)type)&0x3) != 0) { 5664 printf(" NON-INTEGER ResTable_type ADDRESS: %p\n", type); 5665 continue; 5666 } 5667 String8 configStr = type->config.toString(); 5668 printf(" config %s:\n", configStr.size() > 0 5669 ? configStr.string() : "(default)"); 5670 size_t entryCount = dtohl(type->entryCount); 5671 uint32_t entriesStart = dtohl(type->entriesStart); 5672 if ((entriesStart&0x3) != 0) { 5673 printf(" NON-INTEGER ResTable_type entriesStart OFFSET: %p\n", (void*)entriesStart); 5674 continue; 5675 } 5676 uint32_t typeSize = dtohl(type->header.size); 5677 if ((typeSize&0x3) != 0) { 5678 printf(" NON-INTEGER ResTable_type header.size: %p\n", (void*)typeSize); 5679 continue; 5680 } 5681 for (size_t entryIndex=0; entryIndex<entryCount; entryIndex++) { 5682 5683 const uint8_t* const end = ((const uint8_t*)type) 5684 + dtohl(type->header.size); 5685 const uint32_t* const eindex = (const uint32_t*) 5686 (((const uint8_t*)type) + dtohs(type->header.headerSize)); 5687 5688 uint32_t thisOffset = dtohl(eindex[entryIndex]); 5689 if (thisOffset == ResTable_type::NO_ENTRY) { 5690 continue; 5691 } 5692 5693 uint32_t resID = (0xff000000 & ((pkg->package->id)<<24)) 5694 | (0x00ff0000 & ((typeIndex+1)<<16)) 5695 | (0x0000ffff & (entryIndex)); 5696 resource_name resName; 5697 if (this->getResourceName(resID, true, &resName)) { 5698 String8 type8; 5699 String8 name8; 5700 if (resName.type8 != NULL) { 5701 type8 = String8(resName.type8, resName.typeLen); 5702 } else { 5703 type8 = String8(resName.type, resName.typeLen); 5704 } 5705 if (resName.name8 != NULL) { 5706 name8 = String8(resName.name8, resName.nameLen); 5707 } else { 5708 name8 = String8(resName.name, resName.nameLen); 5709 } 5710 printf(" resource 0x%08x %s:%s/%s: ", resID, 5711 CHAR16_TO_CSTR(resName.package, resName.packageLen), 5712 type8.string(), name8.string()); 5713 } else { 5714 printf(" INVALID RESOURCE 0x%08x: ", resID); 5715 } 5716 if ((thisOffset&0x3) != 0) { 5717 printf("NON-INTEGER OFFSET: %p\n", (void*)thisOffset); 5718 continue; 5719 } 5720 if ((thisOffset+sizeof(ResTable_entry)) > typeSize) { 5721 printf("OFFSET OUT OF BOUNDS: %p+%p (size is %p)\n", 5722 (void*)entriesStart, (void*)thisOffset, 5723 (void*)typeSize); 5724 continue; 5725 } 5726 5727 const ResTable_entry* ent = (const ResTable_entry*) 5728 (((const uint8_t*)type) + entriesStart + thisOffset); 5729 if (((entriesStart + thisOffset)&0x3) != 0) { 5730 printf("NON-INTEGER ResTable_entry OFFSET: %p\n", 5731 (void*)(entriesStart + thisOffset)); 5732 continue; 5733 } 5734 5735 uint16_t esize = dtohs(ent->size); 5736 if ((esize&0x3) != 0) { 5737 printf("NON-INTEGER ResTable_entry SIZE: %p\n", (void*)esize); 5738 continue; 5739 } 5740 if ((thisOffset+esize) > typeSize) { 5741 printf("ResTable_entry OUT OF BOUNDS: %p+%p+%p (size is %p)\n", 5742 (void*)entriesStart, (void*)thisOffset, 5743 (void*)esize, (void*)typeSize); 5744 continue; 5745 } 5746 5747 const Res_value* valuePtr = NULL; 5748 const ResTable_map_entry* bagPtr = NULL; 5749 Res_value value; 5750 if ((dtohs(ent->flags)&ResTable_entry::FLAG_COMPLEX) != 0) { 5751 printf("<bag>"); 5752 bagPtr = (const ResTable_map_entry*)ent; 5753 } else { 5754 valuePtr = (const Res_value*) 5755 (((const uint8_t*)ent) + esize); 5756 value.copyFrom_dtoh(*valuePtr); 5757 printf("t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)", 5758 (int)value.dataType, (int)value.data, 5759 (int)value.size, (int)value.res0); 5760 } 5761 5762 if ((dtohs(ent->flags)&ResTable_entry::FLAG_PUBLIC) != 0) { 5763 printf(" (PUBLIC)"); 5764 } 5765 printf("\n"); 5766 5767 if (inclValues) { 5768 if (valuePtr != NULL) { 5769 printf(" "); 5770 print_value(pkg, value); 5771 } else if (bagPtr != NULL) { 5772 const int N = dtohl(bagPtr->count); 5773 const uint8_t* baseMapPtr = (const uint8_t*)ent; 5774 size_t mapOffset = esize; 5775 const ResTable_map* mapPtr = (ResTable_map*)(baseMapPtr+mapOffset); 5776 printf(" Parent=0x%08x, Count=%d\n", 5777 dtohl(bagPtr->parent.ident), N); 5778 for (int i=0; i<N && mapOffset < (typeSize-sizeof(ResTable_map)); i++) { 5779 printf(" #%i (Key=0x%08x): ", 5780 i, dtohl(mapPtr->name.ident)); 5781 value.copyFrom_dtoh(mapPtr->value); 5782 print_value(pkg, value); 5783 const size_t size = dtohs(mapPtr->value.size); 5784 mapOffset += size + sizeof(*mapPtr)-sizeof(mapPtr->value); 5785 mapPtr = (ResTable_map*)(baseMapPtr+mapOffset); 5786 } 5787 } 5788 } 5789 } 5790 } 5791 } 5792 } 5793 } 5794 } 5795 5796 } // namespace android 5797