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 <ctype.h> 21 #include <memory.h> 22 #include <stddef.h> 23 #include <stdint.h> 24 #include <stdlib.h> 25 #include <string.h> 26 27 #include <algorithm> 28 #include <limits> 29 #include <memory> 30 #include <type_traits> 31 32 #include <androidfw/ByteBucketArray.h> 33 #include <androidfw/ResourceTypes.h> 34 #include <androidfw/TypeWrappers.h> 35 #include <utils/Atomic.h> 36 #include <utils/ByteOrder.h> 37 #include <utils/Debug.h> 38 #include <utils/Log.h> 39 #include <utils/String16.h> 40 #include <utils/String8.h> 41 42 #ifdef __ANDROID__ 43 #include <binder/TextOutput.h> 44 #endif 45 46 #ifndef INT32_MAX 47 #define INT32_MAX ((int32_t)(2147483647)) 48 #endif 49 50 namespace android { 51 52 #if defined(_WIN32) 53 #undef nhtol 54 #undef htonl 55 #define ntohl(x) ( ((x) << 24) | (((x) >> 24) & 255) | (((x) << 8) & 0xff0000) | (((x) >> 8) & 0xff00) ) 56 #define htonl(x) ntohl(x) 57 #define ntohs(x) ( (((x) << 8) & 0xff00) | (((x) >> 8) & 255) ) 58 #define htons(x) ntohs(x) 59 #endif 60 61 #define IDMAP_MAGIC 0x504D4449 62 #define IDMAP_CURRENT_VERSION 0x00000001 63 64 #define APP_PACKAGE_ID 0x7f 65 #define SYS_PACKAGE_ID 0x01 66 67 static const bool kDebugStringPoolNoisy = false; 68 static const bool kDebugXMLNoisy = false; 69 static const bool kDebugTableNoisy = false; 70 static const bool kDebugTableGetEntry = false; 71 static const bool kDebugTableSuperNoisy = false; 72 static const bool kDebugLoadTableNoisy = false; 73 static const bool kDebugLoadTableSuperNoisy = false; 74 static const bool kDebugTableTheme = false; 75 static const bool kDebugResXMLTree = false; 76 static const bool kDebugLibNoisy = false; 77 78 // TODO: This code uses 0xFFFFFFFF converted to bag_set* as a sentinel value. This is bad practice. 79 80 // Standard C isspace() is only required to look at the low byte of its input, so 81 // produces incorrect results for UTF-16 characters. For safety's sake, assume that 82 // any high-byte UTF-16 code point is not whitespace. 83 inline int isspace16(char16_t c) { 84 return (c < 0x0080 && isspace(c)); 85 } 86 87 template<typename T> 88 inline static T max(T a, T b) { 89 return a > b ? a : b; 90 } 91 92 // range checked; guaranteed to NUL-terminate within the stated number of available slots 93 // NOTE: if this truncates the dst string due to running out of space, no attempt is 94 // made to avoid splitting surrogate pairs. 95 static void strcpy16_dtoh(char16_t* dst, const uint16_t* src, size_t avail) 96 { 97 char16_t* last = dst + avail - 1; 98 while (*src && (dst < last)) { 99 char16_t s = dtohs(static_cast<char16_t>(*src)); 100 *dst++ = s; 101 src++; 102 } 103 *dst = 0; 104 } 105 106 static status_t validate_chunk(const ResChunk_header* chunk, 107 size_t minSize, 108 const uint8_t* dataEnd, 109 const char* name) 110 { 111 const uint16_t headerSize = dtohs(chunk->headerSize); 112 const uint32_t size = dtohl(chunk->size); 113 114 if (headerSize >= minSize) { 115 if (headerSize <= size) { 116 if (((headerSize|size)&0x3) == 0) { 117 if ((size_t)size <= (size_t)(dataEnd-((const uint8_t*)chunk))) { 118 return NO_ERROR; 119 } 120 ALOGW("%s data size 0x%x extends beyond resource end %p.", 121 name, size, (void*)(dataEnd-((const uint8_t*)chunk))); 122 return BAD_TYPE; 123 } 124 ALOGW("%s size 0x%x or headerSize 0x%x is not on an integer boundary.", 125 name, (int)size, (int)headerSize); 126 return BAD_TYPE; 127 } 128 ALOGW("%s size 0x%x is smaller than header size 0x%x.", 129 name, size, headerSize); 130 return BAD_TYPE; 131 } 132 ALOGW("%s header size 0x%04x is too small.", 133 name, headerSize); 134 return BAD_TYPE; 135 } 136 137 static void fill9patchOffsets(Res_png_9patch* patch) { 138 patch->xDivsOffset = sizeof(Res_png_9patch); 139 patch->yDivsOffset = patch->xDivsOffset + (patch->numXDivs * sizeof(int32_t)); 140 patch->colorsOffset = patch->yDivsOffset + (patch->numYDivs * sizeof(int32_t)); 141 } 142 143 void Res_value::copyFrom_dtoh(const Res_value& src) 144 { 145 size = dtohs(src.size); 146 res0 = src.res0; 147 dataType = src.dataType; 148 data = dtohl(src.data); 149 } 150 151 void Res_png_9patch::deviceToFile() 152 { 153 int32_t* xDivs = getXDivs(); 154 for (int i = 0; i < numXDivs; i++) { 155 xDivs[i] = htonl(xDivs[i]); 156 } 157 int32_t* yDivs = getYDivs(); 158 for (int i = 0; i < numYDivs; i++) { 159 yDivs[i] = htonl(yDivs[i]); 160 } 161 paddingLeft = htonl(paddingLeft); 162 paddingRight = htonl(paddingRight); 163 paddingTop = htonl(paddingTop); 164 paddingBottom = htonl(paddingBottom); 165 uint32_t* colors = getColors(); 166 for (int i=0; i<numColors; i++) { 167 colors[i] = htonl(colors[i]); 168 } 169 } 170 171 void Res_png_9patch::fileToDevice() 172 { 173 int32_t* xDivs = getXDivs(); 174 for (int i = 0; i < numXDivs; i++) { 175 xDivs[i] = ntohl(xDivs[i]); 176 } 177 int32_t* yDivs = getYDivs(); 178 for (int i = 0; i < numYDivs; i++) { 179 yDivs[i] = ntohl(yDivs[i]); 180 } 181 paddingLeft = ntohl(paddingLeft); 182 paddingRight = ntohl(paddingRight); 183 paddingTop = ntohl(paddingTop); 184 paddingBottom = ntohl(paddingBottom); 185 uint32_t* colors = getColors(); 186 for (int i=0; i<numColors; i++) { 187 colors[i] = ntohl(colors[i]); 188 } 189 } 190 191 size_t Res_png_9patch::serializedSize() const 192 { 193 // The size of this struct is 32 bytes on the 32-bit target system 194 // 4 * int8_t 195 // 4 * int32_t 196 // 3 * uint32_t 197 return 32 198 + numXDivs * sizeof(int32_t) 199 + numYDivs * sizeof(int32_t) 200 + numColors * sizeof(uint32_t); 201 } 202 203 void* Res_png_9patch::serialize(const Res_png_9patch& patch, const int32_t* xDivs, 204 const int32_t* yDivs, const uint32_t* colors) 205 { 206 // Use calloc since we're going to leave a few holes in the data 207 // and want this to run cleanly under valgrind 208 void* newData = calloc(1, patch.serializedSize()); 209 serialize(patch, xDivs, yDivs, colors, newData); 210 return newData; 211 } 212 213 void Res_png_9patch::serialize(const Res_png_9patch& patch, const int32_t* xDivs, 214 const int32_t* yDivs, const uint32_t* colors, void* outData) 215 { 216 uint8_t* data = (uint8_t*) outData; 217 memcpy(data, &patch.wasDeserialized, 4); // copy wasDeserialized, numXDivs, numYDivs, numColors 218 memcpy(data + 12, &patch.paddingLeft, 16); // copy paddingXXXX 219 data += 32; 220 221 memcpy(data, xDivs, patch.numXDivs * sizeof(int32_t)); 222 data += patch.numXDivs * sizeof(int32_t); 223 memcpy(data, yDivs, patch.numYDivs * sizeof(int32_t)); 224 data += patch.numYDivs * sizeof(int32_t); 225 memcpy(data, colors, patch.numColors * sizeof(uint32_t)); 226 227 fill9patchOffsets(reinterpret_cast<Res_png_9patch*>(outData)); 228 } 229 230 static bool assertIdmapHeader(const void* idmap, size_t size) { 231 if (reinterpret_cast<uintptr_t>(idmap) & 0x03) { 232 ALOGE("idmap: header is not word aligned"); 233 return false; 234 } 235 236 if (size < ResTable::IDMAP_HEADER_SIZE_BYTES) { 237 ALOGW("idmap: header too small (%d bytes)", (uint32_t) size); 238 return false; 239 } 240 241 const uint32_t magic = htodl(*reinterpret_cast<const uint32_t*>(idmap)); 242 if (magic != IDMAP_MAGIC) { 243 ALOGW("idmap: no magic found in header (is 0x%08x, expected 0x%08x)", 244 magic, IDMAP_MAGIC); 245 return false; 246 } 247 248 const uint32_t version = htodl(*(reinterpret_cast<const uint32_t*>(idmap) + 1)); 249 if (version != IDMAP_CURRENT_VERSION) { 250 // We are strict about versions because files with this format are 251 // auto-generated and don't need backwards compatibility. 252 ALOGW("idmap: version mismatch in header (is 0x%08x, expected 0x%08x)", 253 version, IDMAP_CURRENT_VERSION); 254 return false; 255 } 256 return true; 257 } 258 259 class IdmapEntries { 260 public: 261 IdmapEntries() : mData(NULL) {} 262 263 bool hasEntries() const { 264 if (mData == NULL) { 265 return false; 266 } 267 268 return (dtohs(*mData) > 0); 269 } 270 271 size_t byteSize() const { 272 if (mData == NULL) { 273 return 0; 274 } 275 uint16_t entryCount = dtohs(mData[2]); 276 return (sizeof(uint16_t) * 4) + (sizeof(uint32_t) * static_cast<size_t>(entryCount)); 277 } 278 279 uint8_t targetTypeId() const { 280 if (mData == NULL) { 281 return 0; 282 } 283 return dtohs(mData[0]); 284 } 285 286 uint8_t overlayTypeId() const { 287 if (mData == NULL) { 288 return 0; 289 } 290 return dtohs(mData[1]); 291 } 292 293 status_t setTo(const void* entryHeader, size_t size) { 294 if (reinterpret_cast<uintptr_t>(entryHeader) & 0x03) { 295 ALOGE("idmap: entry header is not word aligned"); 296 return UNKNOWN_ERROR; 297 } 298 299 if (size < sizeof(uint16_t) * 4) { 300 ALOGE("idmap: entry header is too small (%u bytes)", (uint32_t) size); 301 return UNKNOWN_ERROR; 302 } 303 304 const uint16_t* header = reinterpret_cast<const uint16_t*>(entryHeader); 305 const uint16_t targetTypeId = dtohs(header[0]); 306 const uint16_t overlayTypeId = dtohs(header[1]); 307 if (targetTypeId == 0 || overlayTypeId == 0 || targetTypeId > 255 || overlayTypeId > 255) { 308 ALOGE("idmap: invalid type map (%u -> %u)", targetTypeId, overlayTypeId); 309 return UNKNOWN_ERROR; 310 } 311 312 uint16_t entryCount = dtohs(header[2]); 313 if (size < sizeof(uint32_t) * (entryCount + 2)) { 314 ALOGE("idmap: too small (%u bytes) for the number of entries (%u)", 315 (uint32_t) size, (uint32_t) entryCount); 316 return UNKNOWN_ERROR; 317 } 318 mData = header; 319 return NO_ERROR; 320 } 321 322 status_t lookup(uint16_t entryId, uint16_t* outEntryId) const { 323 uint16_t entryCount = dtohs(mData[2]); 324 uint16_t offset = dtohs(mData[3]); 325 326 if (entryId < offset) { 327 // The entry is not present in this idmap 328 return BAD_INDEX; 329 } 330 331 entryId -= offset; 332 333 if (entryId >= entryCount) { 334 // The entry is not present in this idmap 335 return BAD_INDEX; 336 } 337 338 // It is safe to access the type here without checking the size because 339 // we have checked this when it was first loaded. 340 const uint32_t* entries = reinterpret_cast<const uint32_t*>(mData) + 2; 341 uint32_t mappedEntry = dtohl(entries[entryId]); 342 if (mappedEntry == 0xffffffff) { 343 // This entry is not present in this idmap 344 return BAD_INDEX; 345 } 346 *outEntryId = static_cast<uint16_t>(mappedEntry); 347 return NO_ERROR; 348 } 349 350 private: 351 const uint16_t* mData; 352 }; 353 354 status_t parseIdmap(const void* idmap, size_t size, uint8_t* outPackageId, KeyedVector<uint8_t, IdmapEntries>* outMap) { 355 if (!assertIdmapHeader(idmap, size)) { 356 return UNKNOWN_ERROR; 357 } 358 359 size -= ResTable::IDMAP_HEADER_SIZE_BYTES; 360 if (size < sizeof(uint16_t) * 2) { 361 ALOGE("idmap: too small to contain any mapping"); 362 return UNKNOWN_ERROR; 363 } 364 365 const uint16_t* data = reinterpret_cast<const uint16_t*>( 366 reinterpret_cast<const uint8_t*>(idmap) + ResTable::IDMAP_HEADER_SIZE_BYTES); 367 368 uint16_t targetPackageId = dtohs(*(data++)); 369 if (targetPackageId == 0 || targetPackageId > 255) { 370 ALOGE("idmap: target package ID is invalid (%02x)", targetPackageId); 371 return UNKNOWN_ERROR; 372 } 373 374 uint16_t mapCount = dtohs(*(data++)); 375 if (mapCount == 0) { 376 ALOGE("idmap: no mappings"); 377 return UNKNOWN_ERROR; 378 } 379 380 if (mapCount > 255) { 381 ALOGW("idmap: too many mappings. Only 255 are possible but %u are present", (uint32_t) mapCount); 382 } 383 384 while (size > sizeof(uint16_t) * 4) { 385 IdmapEntries entries; 386 status_t err = entries.setTo(data, size); 387 if (err != NO_ERROR) { 388 return err; 389 } 390 391 ssize_t index = outMap->add(entries.overlayTypeId(), entries); 392 if (index < 0) { 393 return NO_MEMORY; 394 } 395 396 data += entries.byteSize() / sizeof(uint16_t); 397 size -= entries.byteSize(); 398 } 399 400 if (outPackageId != NULL) { 401 *outPackageId = static_cast<uint8_t>(targetPackageId); 402 } 403 return NO_ERROR; 404 } 405 406 Res_png_9patch* Res_png_9patch::deserialize(void* inData) 407 { 408 409 Res_png_9patch* patch = reinterpret_cast<Res_png_9patch*>(inData); 410 patch->wasDeserialized = true; 411 fill9patchOffsets(patch); 412 413 return patch; 414 } 415 416 // -------------------------------------------------------------------- 417 // -------------------------------------------------------------------- 418 // -------------------------------------------------------------------- 419 420 ResStringPool::ResStringPool() 421 : mError(NO_INIT), mOwnedData(NULL), mHeader(NULL), mCache(NULL) 422 { 423 } 424 425 ResStringPool::ResStringPool(const void* data, size_t size, bool copyData) 426 : mError(NO_INIT), mOwnedData(NULL), mHeader(NULL), mCache(NULL) 427 { 428 setTo(data, size, copyData); 429 } 430 431 ResStringPool::~ResStringPool() 432 { 433 uninit(); 434 } 435 436 void ResStringPool::setToEmpty() 437 { 438 uninit(); 439 440 mOwnedData = calloc(1, sizeof(ResStringPool_header)); 441 ResStringPool_header* header = (ResStringPool_header*) mOwnedData; 442 mSize = 0; 443 mEntries = NULL; 444 mStrings = NULL; 445 mStringPoolSize = 0; 446 mEntryStyles = NULL; 447 mStyles = NULL; 448 mStylePoolSize = 0; 449 mHeader = (const ResStringPool_header*) header; 450 } 451 452 status_t ResStringPool::setTo(const void* data, size_t size, bool copyData) 453 { 454 if (!data || !size) { 455 return (mError=BAD_TYPE); 456 } 457 458 uninit(); 459 460 const bool notDeviceEndian = htods(0xf0) != 0xf0; 461 462 if (copyData || notDeviceEndian) { 463 mOwnedData = malloc(size); 464 if (mOwnedData == NULL) { 465 return (mError=NO_MEMORY); 466 } 467 memcpy(mOwnedData, data, size); 468 data = mOwnedData; 469 } 470 471 mHeader = (const ResStringPool_header*)data; 472 473 if (notDeviceEndian) { 474 ResStringPool_header* h = const_cast<ResStringPool_header*>(mHeader); 475 h->header.headerSize = dtohs(mHeader->header.headerSize); 476 h->header.type = dtohs(mHeader->header.type); 477 h->header.size = dtohl(mHeader->header.size); 478 h->stringCount = dtohl(mHeader->stringCount); 479 h->styleCount = dtohl(mHeader->styleCount); 480 h->flags = dtohl(mHeader->flags); 481 h->stringsStart = dtohl(mHeader->stringsStart); 482 h->stylesStart = dtohl(mHeader->stylesStart); 483 } 484 485 if (mHeader->header.headerSize > mHeader->header.size 486 || mHeader->header.size > size) { 487 ALOGW("Bad string block: header size %d or total size %d is larger than data size %d\n", 488 (int)mHeader->header.headerSize, (int)mHeader->header.size, (int)size); 489 return (mError=BAD_TYPE); 490 } 491 mSize = mHeader->header.size; 492 mEntries = (const uint32_t*) 493 (((const uint8_t*)data)+mHeader->header.headerSize); 494 495 if (mHeader->stringCount > 0) { 496 if ((mHeader->stringCount*sizeof(uint32_t) < mHeader->stringCount) // uint32 overflow? 497 || (mHeader->header.headerSize+(mHeader->stringCount*sizeof(uint32_t))) 498 > size) { 499 ALOGW("Bad string block: entry of %d items extends past data size %d\n", 500 (int)(mHeader->header.headerSize+(mHeader->stringCount*sizeof(uint32_t))), 501 (int)size); 502 return (mError=BAD_TYPE); 503 } 504 505 size_t charSize; 506 if (mHeader->flags&ResStringPool_header::UTF8_FLAG) { 507 charSize = sizeof(uint8_t); 508 } else { 509 charSize = sizeof(uint16_t); 510 } 511 512 // There should be at least space for the smallest string 513 // (2 bytes length, null terminator). 514 if (mHeader->stringsStart >= (mSize - sizeof(uint16_t))) { 515 ALOGW("Bad string block: string pool starts at %d, after total size %d\n", 516 (int)mHeader->stringsStart, (int)mHeader->header.size); 517 return (mError=BAD_TYPE); 518 } 519 520 mStrings = (const void*) 521 (((const uint8_t*)data) + mHeader->stringsStart); 522 523 if (mHeader->styleCount == 0) { 524 mStringPoolSize = (mSize - mHeader->stringsStart) / charSize; 525 } else { 526 // check invariant: styles starts before end of data 527 if (mHeader->stylesStart >= (mSize - sizeof(uint16_t))) { 528 ALOGW("Bad style block: style block starts at %d past data size of %d\n", 529 (int)mHeader->stylesStart, (int)mHeader->header.size); 530 return (mError=BAD_TYPE); 531 } 532 // check invariant: styles follow the strings 533 if (mHeader->stylesStart <= mHeader->stringsStart) { 534 ALOGW("Bad style block: style block starts at %d, before strings at %d\n", 535 (int)mHeader->stylesStart, (int)mHeader->stringsStart); 536 return (mError=BAD_TYPE); 537 } 538 mStringPoolSize = 539 (mHeader->stylesStart-mHeader->stringsStart)/charSize; 540 } 541 542 // check invariant: stringCount > 0 requires a string pool to exist 543 if (mStringPoolSize == 0) { 544 ALOGW("Bad string block: stringCount is %d but pool size is 0\n", (int)mHeader->stringCount); 545 return (mError=BAD_TYPE); 546 } 547 548 if (notDeviceEndian) { 549 size_t i; 550 uint32_t* e = const_cast<uint32_t*>(mEntries); 551 for (i=0; i<mHeader->stringCount; i++) { 552 e[i] = dtohl(mEntries[i]); 553 } 554 if (!(mHeader->flags&ResStringPool_header::UTF8_FLAG)) { 555 const uint16_t* strings = (const uint16_t*)mStrings; 556 uint16_t* s = const_cast<uint16_t*>(strings); 557 for (i=0; i<mStringPoolSize; i++) { 558 s[i] = dtohs(strings[i]); 559 } 560 } 561 } 562 563 if ((mHeader->flags&ResStringPool_header::UTF8_FLAG && 564 ((uint8_t*)mStrings)[mStringPoolSize-1] != 0) || 565 (!(mHeader->flags&ResStringPool_header::UTF8_FLAG) && 566 ((uint16_t*)mStrings)[mStringPoolSize-1] != 0)) { 567 ALOGW("Bad string block: last string is not 0-terminated\n"); 568 return (mError=BAD_TYPE); 569 } 570 } else { 571 mStrings = NULL; 572 mStringPoolSize = 0; 573 } 574 575 if (mHeader->styleCount > 0) { 576 mEntryStyles = mEntries + mHeader->stringCount; 577 // invariant: integer overflow in calculating mEntryStyles 578 if (mEntryStyles < mEntries) { 579 ALOGW("Bad string block: integer overflow finding styles\n"); 580 return (mError=BAD_TYPE); 581 } 582 583 if (((const uint8_t*)mEntryStyles-(const uint8_t*)mHeader) > (int)size) { 584 ALOGW("Bad string block: entry of %d styles extends past data size %d\n", 585 (int)((const uint8_t*)mEntryStyles-(const uint8_t*)mHeader), 586 (int)size); 587 return (mError=BAD_TYPE); 588 } 589 mStyles = (const uint32_t*) 590 (((const uint8_t*)data)+mHeader->stylesStart); 591 if (mHeader->stylesStart >= mHeader->header.size) { 592 ALOGW("Bad string block: style pool starts %d, after total size %d\n", 593 (int)mHeader->stylesStart, (int)mHeader->header.size); 594 return (mError=BAD_TYPE); 595 } 596 mStylePoolSize = 597 (mHeader->header.size-mHeader->stylesStart)/sizeof(uint32_t); 598 599 if (notDeviceEndian) { 600 size_t i; 601 uint32_t* e = const_cast<uint32_t*>(mEntryStyles); 602 for (i=0; i<mHeader->styleCount; i++) { 603 e[i] = dtohl(mEntryStyles[i]); 604 } 605 uint32_t* s = const_cast<uint32_t*>(mStyles); 606 for (i=0; i<mStylePoolSize; i++) { 607 s[i] = dtohl(mStyles[i]); 608 } 609 } 610 611 const ResStringPool_span endSpan = { 612 { htodl(ResStringPool_span::END) }, 613 htodl(ResStringPool_span::END), htodl(ResStringPool_span::END) 614 }; 615 if (memcmp(&mStyles[mStylePoolSize-(sizeof(endSpan)/sizeof(uint32_t))], 616 &endSpan, sizeof(endSpan)) != 0) { 617 ALOGW("Bad string block: last style is not 0xFFFFFFFF-terminated\n"); 618 return (mError=BAD_TYPE); 619 } 620 } else { 621 mEntryStyles = NULL; 622 mStyles = NULL; 623 mStylePoolSize = 0; 624 } 625 626 return (mError=NO_ERROR); 627 } 628 629 status_t ResStringPool::getError() const 630 { 631 return mError; 632 } 633 634 void ResStringPool::uninit() 635 { 636 mError = NO_INIT; 637 if (mHeader != NULL && mCache != NULL) { 638 for (size_t x = 0; x < mHeader->stringCount; x++) { 639 if (mCache[x] != NULL) { 640 free(mCache[x]); 641 mCache[x] = NULL; 642 } 643 } 644 free(mCache); 645 mCache = NULL; 646 } 647 if (mOwnedData) { 648 free(mOwnedData); 649 mOwnedData = NULL; 650 } 651 } 652 653 /** 654 * Strings in UTF-16 format have length indicated by a length encoded in the 655 * stored data. It is either 1 or 2 characters of length data. This allows a 656 * maximum length of 0x7FFFFFF (2147483647 bytes), but if you're storing that 657 * much data in a string, you're abusing them. 658 * 659 * If the high bit is set, then there are two characters or 4 bytes of length 660 * data encoded. In that case, drop the high bit of the first character and 661 * add it together with the next character. 662 */ 663 static inline size_t 664 decodeLength(const uint16_t** str) 665 { 666 size_t len = **str; 667 if ((len & 0x8000) != 0) { 668 (*str)++; 669 len = ((len & 0x7FFF) << 16) | **str; 670 } 671 (*str)++; 672 return len; 673 } 674 675 /** 676 * Strings in UTF-8 format have length indicated by a length encoded in the 677 * stored data. It is either 1 or 2 characters of length data. This allows a 678 * maximum length of 0x7FFF (32767 bytes), but you should consider storing 679 * text in another way if you're using that much data in a single string. 680 * 681 * If the high bit is set, then there are two characters or 2 bytes of length 682 * data encoded. In that case, drop the high bit of the first character and 683 * add it together with the next character. 684 */ 685 static inline size_t 686 decodeLength(const uint8_t** str) 687 { 688 size_t len = **str; 689 if ((len & 0x80) != 0) { 690 (*str)++; 691 len = ((len & 0x7F) << 8) | **str; 692 } 693 (*str)++; 694 return len; 695 } 696 697 const char16_t* ResStringPool::stringAt(size_t idx, size_t* u16len) const 698 { 699 if (mError == NO_ERROR && idx < mHeader->stringCount) { 700 const bool isUTF8 = (mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0; 701 const uint32_t off = mEntries[idx]/(isUTF8?sizeof(uint8_t):sizeof(uint16_t)); 702 if (off < (mStringPoolSize-1)) { 703 if (!isUTF8) { 704 const uint16_t* strings = (uint16_t*)mStrings; 705 const uint16_t* str = strings+off; 706 707 *u16len = decodeLength(&str); 708 if ((uint32_t)(str+*u16len-strings) < mStringPoolSize) { 709 // Reject malformed (non null-terminated) strings 710 if (str[*u16len] != 0x0000) { 711 ALOGW("Bad string block: string #%d is not null-terminated", 712 (int)idx); 713 return NULL; 714 } 715 return reinterpret_cast<const char16_t*>(str); 716 } else { 717 ALOGW("Bad string block: string #%d extends to %d, past end at %d\n", 718 (int)idx, (int)(str+*u16len-strings), (int)mStringPoolSize); 719 } 720 } else { 721 const uint8_t* strings = (uint8_t*)mStrings; 722 const uint8_t* u8str = strings+off; 723 724 *u16len = decodeLength(&u8str); 725 size_t u8len = decodeLength(&u8str); 726 727 // encLen must be less than 0x7FFF due to encoding. 728 if ((uint32_t)(u8str+u8len-strings) < mStringPoolSize) { 729 AutoMutex lock(mDecodeLock); 730 731 if (mCache == NULL) { 732 #ifndef __ANDROID__ 733 if (kDebugStringPoolNoisy) { 734 ALOGI("CREATING STRING CACHE OF %zu bytes", 735 mHeader->stringCount*sizeof(char16_t**)); 736 } 737 #else 738 // We do not want to be in this case when actually running Android. 739 ALOGW("CREATING STRING CACHE OF %zu bytes", 740 static_cast<size_t>(mHeader->stringCount*sizeof(char16_t**))); 741 #endif 742 mCache = (char16_t**)calloc(mHeader->stringCount, sizeof(char16_t*)); 743 if (mCache == NULL) { 744 ALOGW("No memory trying to allocate decode cache table of %d bytes\n", 745 (int)(mHeader->stringCount*sizeof(char16_t**))); 746 return NULL; 747 } 748 } 749 750 if (mCache[idx] != NULL) { 751 return mCache[idx]; 752 } 753 754 ssize_t actualLen = utf8_to_utf16_length(u8str, u8len); 755 if (actualLen < 0 || (size_t)actualLen != *u16len) { 756 ALOGW("Bad string block: string #%lld decoded length is not correct " 757 "%lld vs %llu\n", 758 (long long)idx, (long long)actualLen, (long long)*u16len); 759 return NULL; 760 } 761 762 // Reject malformed (non null-terminated) strings 763 if (u8str[u8len] != 0x00) { 764 ALOGW("Bad string block: string #%d is not null-terminated", 765 (int)idx); 766 return NULL; 767 } 768 769 char16_t *u16str = (char16_t *)calloc(*u16len+1, sizeof(char16_t)); 770 if (!u16str) { 771 ALOGW("No memory when trying to allocate decode cache for string #%d\n", 772 (int)idx); 773 return NULL; 774 } 775 776 if (kDebugStringPoolNoisy) { 777 ALOGI("Caching UTF8 string: %s", u8str); 778 } 779 utf8_to_utf16(u8str, u8len, u16str, *u16len + 1); 780 mCache[idx] = u16str; 781 return u16str; 782 } else { 783 ALOGW("Bad string block: string #%lld extends to %lld, past end at %lld\n", 784 (long long)idx, (long long)(u8str+u8len-strings), 785 (long long)mStringPoolSize); 786 } 787 } 788 } else { 789 ALOGW("Bad string block: string #%d entry is at %d, past end at %d\n", 790 (int)idx, (int)(off*sizeof(uint16_t)), 791 (int)(mStringPoolSize*sizeof(uint16_t))); 792 } 793 } 794 return NULL; 795 } 796 797 const char* ResStringPool::string8At(size_t idx, size_t* outLen) const 798 { 799 if (mError == NO_ERROR && idx < mHeader->stringCount) { 800 if ((mHeader->flags&ResStringPool_header::UTF8_FLAG) == 0) { 801 return NULL; 802 } 803 const uint32_t off = mEntries[idx]/sizeof(char); 804 if (off < (mStringPoolSize-1)) { 805 const uint8_t* strings = (uint8_t*)mStrings; 806 const uint8_t* str = strings+off; 807 808 // Decode the UTF-16 length. This is not used if we're not 809 // converting to UTF-16 from UTF-8. 810 decodeLength(&str); 811 812 const size_t encLen = decodeLength(&str); 813 *outLen = encLen; 814 815 if ((uint32_t)(str+encLen-strings) < mStringPoolSize) { 816 return (const char*)str; 817 } else { 818 ALOGW("Bad string block: string #%d extends to %d, past end at %d\n", 819 (int)idx, (int)(str+encLen-strings), (int)mStringPoolSize); 820 } 821 } else { 822 ALOGW("Bad string block: string #%d entry is at %d, past end at %d\n", 823 (int)idx, (int)(off*sizeof(uint16_t)), 824 (int)(mStringPoolSize*sizeof(uint16_t))); 825 } 826 } 827 return NULL; 828 } 829 830 const String8 ResStringPool::string8ObjectAt(size_t idx) const 831 { 832 size_t len; 833 const char *str = string8At(idx, &len); 834 if (str != NULL) { 835 return String8(str, len); 836 } 837 838 const char16_t *str16 = stringAt(idx, &len); 839 if (str16 != NULL) { 840 return String8(str16, len); 841 } 842 return String8(); 843 } 844 845 const ResStringPool_span* ResStringPool::styleAt(const ResStringPool_ref& ref) const 846 { 847 return styleAt(ref.index); 848 } 849 850 const ResStringPool_span* ResStringPool::styleAt(size_t idx) const 851 { 852 if (mError == NO_ERROR && idx < mHeader->styleCount) { 853 const uint32_t off = (mEntryStyles[idx]/sizeof(uint32_t)); 854 if (off < mStylePoolSize) { 855 return (const ResStringPool_span*)(mStyles+off); 856 } else { 857 ALOGW("Bad string block: style #%d entry is at %d, past end at %d\n", 858 (int)idx, (int)(off*sizeof(uint32_t)), 859 (int)(mStylePoolSize*sizeof(uint32_t))); 860 } 861 } 862 return NULL; 863 } 864 865 ssize_t ResStringPool::indexOfString(const char16_t* str, size_t strLen) const 866 { 867 if (mError != NO_ERROR) { 868 return mError; 869 } 870 871 size_t len; 872 873 if ((mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0) { 874 if (kDebugStringPoolNoisy) { 875 ALOGI("indexOfString UTF-8: %s", String8(str, strLen).string()); 876 } 877 878 // The string pool contains UTF 8 strings; we don't want to cause 879 // temporary UTF-16 strings to be created as we search. 880 if (mHeader->flags&ResStringPool_header::SORTED_FLAG) { 881 // Do a binary search for the string... this is a little tricky, 882 // because the strings are sorted with strzcmp16(). So to match 883 // the ordering, we need to convert strings in the pool to UTF-16. 884 // But we don't want to hit the cache, so instead we will have a 885 // local temporary allocation for the conversions. 886 size_t convBufferLen = strLen + 4; 887 char16_t* convBuffer = (char16_t*)calloc(convBufferLen, sizeof(char16_t)); 888 ssize_t l = 0; 889 ssize_t h = mHeader->stringCount-1; 890 891 ssize_t mid; 892 while (l <= h) { 893 mid = l + (h - l)/2; 894 const uint8_t* s = (const uint8_t*)string8At(mid, &len); 895 int c; 896 if (s != NULL) { 897 char16_t* end = utf8_to_utf16(s, len, convBuffer, convBufferLen); 898 c = strzcmp16(convBuffer, end-convBuffer, str, strLen); 899 } else { 900 c = -1; 901 } 902 if (kDebugStringPoolNoisy) { 903 ALOGI("Looking at %s, cmp=%d, l/mid/h=%d/%d/%d\n", 904 (const char*)s, c, (int)l, (int)mid, (int)h); 905 } 906 if (c == 0) { 907 if (kDebugStringPoolNoisy) { 908 ALOGI("MATCH!"); 909 } 910 free(convBuffer); 911 return mid; 912 } else if (c < 0) { 913 l = mid + 1; 914 } else { 915 h = mid - 1; 916 } 917 } 918 free(convBuffer); 919 } else { 920 // It is unusual to get the ID from an unsorted string block... 921 // most often this happens because we want to get IDs for style 922 // span tags; since those always appear at the end of the string 923 // block, start searching at the back. 924 String8 str8(str, strLen); 925 const size_t str8Len = str8.size(); 926 for (int i=mHeader->stringCount-1; i>=0; i--) { 927 const char* s = string8At(i, &len); 928 if (kDebugStringPoolNoisy) { 929 ALOGI("Looking at %s, i=%d\n", String8(s).string(), i); 930 } 931 if (s && str8Len == len && memcmp(s, str8.string(), str8Len) == 0) { 932 if (kDebugStringPoolNoisy) { 933 ALOGI("MATCH!"); 934 } 935 return i; 936 } 937 } 938 } 939 940 } else { 941 if (kDebugStringPoolNoisy) { 942 ALOGI("indexOfString UTF-16: %s", String8(str, strLen).string()); 943 } 944 945 if (mHeader->flags&ResStringPool_header::SORTED_FLAG) { 946 // Do a binary search for the string... 947 ssize_t l = 0; 948 ssize_t h = mHeader->stringCount-1; 949 950 ssize_t mid; 951 while (l <= h) { 952 mid = l + (h - l)/2; 953 const char16_t* s = stringAt(mid, &len); 954 int c = s ? strzcmp16(s, len, str, strLen) : -1; 955 if (kDebugStringPoolNoisy) { 956 ALOGI("Looking at %s, cmp=%d, l/mid/h=%d/%d/%d\n", 957 String8(s).string(), c, (int)l, (int)mid, (int)h); 958 } 959 if (c == 0) { 960 if (kDebugStringPoolNoisy) { 961 ALOGI("MATCH!"); 962 } 963 return mid; 964 } else if (c < 0) { 965 l = mid + 1; 966 } else { 967 h = mid - 1; 968 } 969 } 970 } else { 971 // It is unusual to get the ID from an unsorted string block... 972 // most often this happens because we want to get IDs for style 973 // span tags; since those always appear at the end of the string 974 // block, start searching at the back. 975 for (int i=mHeader->stringCount-1; i>=0; i--) { 976 const char16_t* s = stringAt(i, &len); 977 if (kDebugStringPoolNoisy) { 978 ALOGI("Looking at %s, i=%d\n", String8(s).string(), i); 979 } 980 if (s && strLen == len && strzcmp16(s, len, str, strLen) == 0) { 981 if (kDebugStringPoolNoisy) { 982 ALOGI("MATCH!"); 983 } 984 return i; 985 } 986 } 987 } 988 } 989 990 return NAME_NOT_FOUND; 991 } 992 993 size_t ResStringPool::size() const 994 { 995 return (mError == NO_ERROR) ? mHeader->stringCount : 0; 996 } 997 998 size_t ResStringPool::styleCount() const 999 { 1000 return (mError == NO_ERROR) ? mHeader->styleCount : 0; 1001 } 1002 1003 size_t ResStringPool::bytes() const 1004 { 1005 return (mError == NO_ERROR) ? mHeader->header.size : 0; 1006 } 1007 1008 bool ResStringPool::isSorted() const 1009 { 1010 return (mHeader->flags&ResStringPool_header::SORTED_FLAG)!=0; 1011 } 1012 1013 bool ResStringPool::isUTF8() const 1014 { 1015 return (mHeader->flags&ResStringPool_header::UTF8_FLAG)!=0; 1016 } 1017 1018 // -------------------------------------------------------------------- 1019 // -------------------------------------------------------------------- 1020 // -------------------------------------------------------------------- 1021 1022 ResXMLParser::ResXMLParser(const ResXMLTree& tree) 1023 : mTree(tree), mEventCode(BAD_DOCUMENT) 1024 { 1025 } 1026 1027 void ResXMLParser::restart() 1028 { 1029 mCurNode = NULL; 1030 mEventCode = mTree.mError == NO_ERROR ? START_DOCUMENT : BAD_DOCUMENT; 1031 } 1032 const ResStringPool& ResXMLParser::getStrings() const 1033 { 1034 return mTree.mStrings; 1035 } 1036 1037 ResXMLParser::event_code_t ResXMLParser::getEventType() const 1038 { 1039 return mEventCode; 1040 } 1041 1042 ResXMLParser::event_code_t ResXMLParser::next() 1043 { 1044 if (mEventCode == START_DOCUMENT) { 1045 mCurNode = mTree.mRootNode; 1046 mCurExt = mTree.mRootExt; 1047 return (mEventCode=mTree.mRootCode); 1048 } else if (mEventCode >= FIRST_CHUNK_CODE) { 1049 return nextNode(); 1050 } 1051 return mEventCode; 1052 } 1053 1054 int32_t ResXMLParser::getCommentID() const 1055 { 1056 return mCurNode != NULL ? dtohl(mCurNode->comment.index) : -1; 1057 } 1058 1059 const char16_t* ResXMLParser::getComment(size_t* outLen) const 1060 { 1061 int32_t id = getCommentID(); 1062 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL; 1063 } 1064 1065 uint32_t ResXMLParser::getLineNumber() const 1066 { 1067 return mCurNode != NULL ? dtohl(mCurNode->lineNumber) : -1; 1068 } 1069 1070 int32_t ResXMLParser::getTextID() const 1071 { 1072 if (mEventCode == TEXT) { 1073 return dtohl(((const ResXMLTree_cdataExt*)mCurExt)->data.index); 1074 } 1075 return -1; 1076 } 1077 1078 const char16_t* ResXMLParser::getText(size_t* outLen) const 1079 { 1080 int32_t id = getTextID(); 1081 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL; 1082 } 1083 1084 ssize_t ResXMLParser::getTextValue(Res_value* outValue) const 1085 { 1086 if (mEventCode == TEXT) { 1087 outValue->copyFrom_dtoh(((const ResXMLTree_cdataExt*)mCurExt)->typedData); 1088 return sizeof(Res_value); 1089 } 1090 return BAD_TYPE; 1091 } 1092 1093 int32_t ResXMLParser::getNamespacePrefixID() const 1094 { 1095 if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) { 1096 return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->prefix.index); 1097 } 1098 return -1; 1099 } 1100 1101 const char16_t* ResXMLParser::getNamespacePrefix(size_t* outLen) const 1102 { 1103 int32_t id = getNamespacePrefixID(); 1104 //printf("prefix=%d event=%p\n", id, mEventCode); 1105 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL; 1106 } 1107 1108 int32_t ResXMLParser::getNamespaceUriID() const 1109 { 1110 if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) { 1111 return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->uri.index); 1112 } 1113 return -1; 1114 } 1115 1116 const char16_t* ResXMLParser::getNamespaceUri(size_t* outLen) const 1117 { 1118 int32_t id = getNamespaceUriID(); 1119 //printf("uri=%d event=%p\n", id, mEventCode); 1120 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL; 1121 } 1122 1123 int32_t ResXMLParser::getElementNamespaceID() const 1124 { 1125 if (mEventCode == START_TAG) { 1126 return dtohl(((const ResXMLTree_attrExt*)mCurExt)->ns.index); 1127 } 1128 if (mEventCode == END_TAG) { 1129 return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->ns.index); 1130 } 1131 return -1; 1132 } 1133 1134 const char16_t* ResXMLParser::getElementNamespace(size_t* outLen) const 1135 { 1136 int32_t id = getElementNamespaceID(); 1137 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL; 1138 } 1139 1140 int32_t ResXMLParser::getElementNameID() const 1141 { 1142 if (mEventCode == START_TAG) { 1143 return dtohl(((const ResXMLTree_attrExt*)mCurExt)->name.index); 1144 } 1145 if (mEventCode == END_TAG) { 1146 return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->name.index); 1147 } 1148 return -1; 1149 } 1150 1151 const char16_t* ResXMLParser::getElementName(size_t* outLen) const 1152 { 1153 int32_t id = getElementNameID(); 1154 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL; 1155 } 1156 1157 size_t ResXMLParser::getAttributeCount() const 1158 { 1159 if (mEventCode == START_TAG) { 1160 return dtohs(((const ResXMLTree_attrExt*)mCurExt)->attributeCount); 1161 } 1162 return 0; 1163 } 1164 1165 int32_t ResXMLParser::getAttributeNamespaceID(size_t idx) const 1166 { 1167 if (mEventCode == START_TAG) { 1168 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt; 1169 if (idx < dtohs(tag->attributeCount)) { 1170 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*) 1171 (((const uint8_t*)tag) 1172 + dtohs(tag->attributeStart) 1173 + (dtohs(tag->attributeSize)*idx)); 1174 return dtohl(attr->ns.index); 1175 } 1176 } 1177 return -2; 1178 } 1179 1180 const char16_t* ResXMLParser::getAttributeNamespace(size_t idx, size_t* outLen) const 1181 { 1182 int32_t id = getAttributeNamespaceID(idx); 1183 //printf("attribute namespace=%d idx=%d event=%p\n", id, idx, mEventCode); 1184 if (kDebugXMLNoisy) { 1185 printf("getAttributeNamespace 0x%zx=0x%x\n", idx, id); 1186 } 1187 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL; 1188 } 1189 1190 const char* ResXMLParser::getAttributeNamespace8(size_t idx, size_t* outLen) const 1191 { 1192 int32_t id = getAttributeNamespaceID(idx); 1193 //printf("attribute namespace=%d idx=%d event=%p\n", id, idx, mEventCode); 1194 if (kDebugXMLNoisy) { 1195 printf("getAttributeNamespace 0x%zx=0x%x\n", idx, id); 1196 } 1197 return id >= 0 ? mTree.mStrings.string8At(id, outLen) : NULL; 1198 } 1199 1200 int32_t ResXMLParser::getAttributeNameID(size_t idx) const 1201 { 1202 if (mEventCode == START_TAG) { 1203 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt; 1204 if (idx < dtohs(tag->attributeCount)) { 1205 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*) 1206 (((const uint8_t*)tag) 1207 + dtohs(tag->attributeStart) 1208 + (dtohs(tag->attributeSize)*idx)); 1209 return dtohl(attr->name.index); 1210 } 1211 } 1212 return -1; 1213 } 1214 1215 const char16_t* ResXMLParser::getAttributeName(size_t idx, size_t* outLen) const 1216 { 1217 int32_t id = getAttributeNameID(idx); 1218 //printf("attribute name=%d idx=%d event=%p\n", id, idx, mEventCode); 1219 if (kDebugXMLNoisy) { 1220 printf("getAttributeName 0x%zx=0x%x\n", idx, id); 1221 } 1222 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL; 1223 } 1224 1225 const char* ResXMLParser::getAttributeName8(size_t idx, size_t* outLen) const 1226 { 1227 int32_t id = getAttributeNameID(idx); 1228 //printf("attribute name=%d idx=%d event=%p\n", id, idx, mEventCode); 1229 if (kDebugXMLNoisy) { 1230 printf("getAttributeName 0x%zx=0x%x\n", idx, id); 1231 } 1232 return id >= 0 ? mTree.mStrings.string8At(id, outLen) : NULL; 1233 } 1234 1235 uint32_t ResXMLParser::getAttributeNameResID(size_t idx) const 1236 { 1237 int32_t id = getAttributeNameID(idx); 1238 if (id >= 0 && (size_t)id < mTree.mNumResIds) { 1239 uint32_t resId = dtohl(mTree.mResIds[id]); 1240 if (mTree.mDynamicRefTable != NULL) { 1241 mTree.mDynamicRefTable->lookupResourceId(&resId); 1242 } 1243 return resId; 1244 } 1245 return 0; 1246 } 1247 1248 int32_t ResXMLParser::getAttributeValueStringID(size_t idx) const 1249 { 1250 if (mEventCode == START_TAG) { 1251 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt; 1252 if (idx < dtohs(tag->attributeCount)) { 1253 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*) 1254 (((const uint8_t*)tag) 1255 + dtohs(tag->attributeStart) 1256 + (dtohs(tag->attributeSize)*idx)); 1257 return dtohl(attr->rawValue.index); 1258 } 1259 } 1260 return -1; 1261 } 1262 1263 const char16_t* ResXMLParser::getAttributeStringValue(size_t idx, size_t* outLen) const 1264 { 1265 int32_t id = getAttributeValueStringID(idx); 1266 if (kDebugXMLNoisy) { 1267 printf("getAttributeValue 0x%zx=0x%x\n", idx, id); 1268 } 1269 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL; 1270 } 1271 1272 int32_t ResXMLParser::getAttributeDataType(size_t idx) const 1273 { 1274 if (mEventCode == START_TAG) { 1275 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt; 1276 if (idx < dtohs(tag->attributeCount)) { 1277 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*) 1278 (((const uint8_t*)tag) 1279 + dtohs(tag->attributeStart) 1280 + (dtohs(tag->attributeSize)*idx)); 1281 uint8_t type = attr->typedValue.dataType; 1282 if (type != Res_value::TYPE_DYNAMIC_REFERENCE) { 1283 return type; 1284 } 1285 1286 // This is a dynamic reference. We adjust those references 1287 // to regular references at this level, so lie to the caller. 1288 return Res_value::TYPE_REFERENCE; 1289 } 1290 } 1291 return Res_value::TYPE_NULL; 1292 } 1293 1294 int32_t ResXMLParser::getAttributeData(size_t idx) const 1295 { 1296 if (mEventCode == START_TAG) { 1297 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt; 1298 if (idx < dtohs(tag->attributeCount)) { 1299 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*) 1300 (((const uint8_t*)tag) 1301 + dtohs(tag->attributeStart) 1302 + (dtohs(tag->attributeSize)*idx)); 1303 if (attr->typedValue.dataType != Res_value::TYPE_DYNAMIC_REFERENCE || 1304 mTree.mDynamicRefTable == NULL) { 1305 return dtohl(attr->typedValue.data); 1306 } 1307 1308 uint32_t data = dtohl(attr->typedValue.data); 1309 if (mTree.mDynamicRefTable->lookupResourceId(&data) == NO_ERROR) { 1310 return data; 1311 } 1312 } 1313 } 1314 return 0; 1315 } 1316 1317 ssize_t ResXMLParser::getAttributeValue(size_t idx, Res_value* outValue) const 1318 { 1319 if (mEventCode == START_TAG) { 1320 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt; 1321 if (idx < dtohs(tag->attributeCount)) { 1322 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*) 1323 (((const uint8_t*)tag) 1324 + dtohs(tag->attributeStart) 1325 + (dtohs(tag->attributeSize)*idx)); 1326 outValue->copyFrom_dtoh(attr->typedValue); 1327 if (mTree.mDynamicRefTable != NULL && 1328 mTree.mDynamicRefTable->lookupResourceValue(outValue) != NO_ERROR) { 1329 return BAD_TYPE; 1330 } 1331 return sizeof(Res_value); 1332 } 1333 } 1334 return BAD_TYPE; 1335 } 1336 1337 ssize_t ResXMLParser::indexOfAttribute(const char* ns, const char* attr) const 1338 { 1339 String16 nsStr(ns != NULL ? ns : ""); 1340 String16 attrStr(attr); 1341 return indexOfAttribute(ns ? nsStr.string() : NULL, ns ? nsStr.size() : 0, 1342 attrStr.string(), attrStr.size()); 1343 } 1344 1345 ssize_t ResXMLParser::indexOfAttribute(const char16_t* ns, size_t nsLen, 1346 const char16_t* attr, size_t attrLen) const 1347 { 1348 if (mEventCode == START_TAG) { 1349 if (attr == NULL) { 1350 return NAME_NOT_FOUND; 1351 } 1352 const size_t N = getAttributeCount(); 1353 if (mTree.mStrings.isUTF8()) { 1354 String8 ns8, attr8; 1355 if (ns != NULL) { 1356 ns8 = String8(ns, nsLen); 1357 } 1358 attr8 = String8(attr, attrLen); 1359 if (kDebugStringPoolNoisy) { 1360 ALOGI("indexOfAttribute UTF8 %s (%zu) / %s (%zu)", ns8.string(), nsLen, 1361 attr8.string(), attrLen); 1362 } 1363 for (size_t i=0; i<N; i++) { 1364 size_t curNsLen = 0, curAttrLen = 0; 1365 const char* curNs = getAttributeNamespace8(i, &curNsLen); 1366 const char* curAttr = getAttributeName8(i, &curAttrLen); 1367 if (kDebugStringPoolNoisy) { 1368 ALOGI(" curNs=%s (%zu), curAttr=%s (%zu)", curNs, curNsLen, curAttr, curAttrLen); 1369 } 1370 if (curAttr != NULL && curNsLen == nsLen && curAttrLen == attrLen 1371 && memcmp(attr8.string(), curAttr, attrLen) == 0) { 1372 if (ns == NULL) { 1373 if (curNs == NULL) { 1374 if (kDebugStringPoolNoisy) { 1375 ALOGI(" FOUND!"); 1376 } 1377 return i; 1378 } 1379 } else if (curNs != NULL) { 1380 //printf(" --> ns=%s, curNs=%s\n", 1381 // String8(ns).string(), String8(curNs).string()); 1382 if (memcmp(ns8.string(), curNs, nsLen) == 0) { 1383 if (kDebugStringPoolNoisy) { 1384 ALOGI(" FOUND!"); 1385 } 1386 return i; 1387 } 1388 } 1389 } 1390 } 1391 } else { 1392 if (kDebugStringPoolNoisy) { 1393 ALOGI("indexOfAttribute UTF16 %s (%zu) / %s (%zu)", 1394 String8(ns, nsLen).string(), nsLen, 1395 String8(attr, attrLen).string(), attrLen); 1396 } 1397 for (size_t i=0; i<N; i++) { 1398 size_t curNsLen = 0, curAttrLen = 0; 1399 const char16_t* curNs = getAttributeNamespace(i, &curNsLen); 1400 const char16_t* curAttr = getAttributeName(i, &curAttrLen); 1401 if (kDebugStringPoolNoisy) { 1402 ALOGI(" curNs=%s (%zu), curAttr=%s (%zu)", 1403 String8(curNs, curNsLen).string(), curNsLen, 1404 String8(curAttr, curAttrLen).string(), curAttrLen); 1405 } 1406 if (curAttr != NULL && curNsLen == nsLen && curAttrLen == attrLen 1407 && (memcmp(attr, curAttr, attrLen*sizeof(char16_t)) == 0)) { 1408 if (ns == NULL) { 1409 if (curNs == NULL) { 1410 if (kDebugStringPoolNoisy) { 1411 ALOGI(" FOUND!"); 1412 } 1413 return i; 1414 } 1415 } else if (curNs != NULL) { 1416 //printf(" --> ns=%s, curNs=%s\n", 1417 // String8(ns).string(), String8(curNs).string()); 1418 if (memcmp(ns, curNs, nsLen*sizeof(char16_t)) == 0) { 1419 if (kDebugStringPoolNoisy) { 1420 ALOGI(" FOUND!"); 1421 } 1422 return i; 1423 } 1424 } 1425 } 1426 } 1427 } 1428 } 1429 1430 return NAME_NOT_FOUND; 1431 } 1432 1433 ssize_t ResXMLParser::indexOfID() const 1434 { 1435 if (mEventCode == START_TAG) { 1436 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->idIndex); 1437 if (idx > 0) return (idx-1); 1438 } 1439 return NAME_NOT_FOUND; 1440 } 1441 1442 ssize_t ResXMLParser::indexOfClass() const 1443 { 1444 if (mEventCode == START_TAG) { 1445 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->classIndex); 1446 if (idx > 0) return (idx-1); 1447 } 1448 return NAME_NOT_FOUND; 1449 } 1450 1451 ssize_t ResXMLParser::indexOfStyle() const 1452 { 1453 if (mEventCode == START_TAG) { 1454 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->styleIndex); 1455 if (idx > 0) return (idx-1); 1456 } 1457 return NAME_NOT_FOUND; 1458 } 1459 1460 ResXMLParser::event_code_t ResXMLParser::nextNode() 1461 { 1462 if (mEventCode < 0) { 1463 return mEventCode; 1464 } 1465 1466 do { 1467 const ResXMLTree_node* next = (const ResXMLTree_node*) 1468 (((const uint8_t*)mCurNode) + dtohl(mCurNode->header.size)); 1469 if (kDebugXMLNoisy) { 1470 ALOGI("Next node: prev=%p, next=%p\n", mCurNode, next); 1471 } 1472 1473 if (((const uint8_t*)next) >= mTree.mDataEnd) { 1474 mCurNode = NULL; 1475 return (mEventCode=END_DOCUMENT); 1476 } 1477 1478 if (mTree.validateNode(next) != NO_ERROR) { 1479 mCurNode = NULL; 1480 return (mEventCode=BAD_DOCUMENT); 1481 } 1482 1483 mCurNode = next; 1484 const uint16_t headerSize = dtohs(next->header.headerSize); 1485 const uint32_t totalSize = dtohl(next->header.size); 1486 mCurExt = ((const uint8_t*)next) + headerSize; 1487 size_t minExtSize = 0; 1488 event_code_t eventCode = (event_code_t)dtohs(next->header.type); 1489 switch ((mEventCode=eventCode)) { 1490 case RES_XML_START_NAMESPACE_TYPE: 1491 case RES_XML_END_NAMESPACE_TYPE: 1492 minExtSize = sizeof(ResXMLTree_namespaceExt); 1493 break; 1494 case RES_XML_START_ELEMENT_TYPE: 1495 minExtSize = sizeof(ResXMLTree_attrExt); 1496 break; 1497 case RES_XML_END_ELEMENT_TYPE: 1498 minExtSize = sizeof(ResXMLTree_endElementExt); 1499 break; 1500 case RES_XML_CDATA_TYPE: 1501 minExtSize = sizeof(ResXMLTree_cdataExt); 1502 break; 1503 default: 1504 ALOGW("Unknown XML block: header type %d in node at %d\n", 1505 (int)dtohs(next->header.type), 1506 (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader))); 1507 continue; 1508 } 1509 1510 if ((totalSize-headerSize) < minExtSize) { 1511 ALOGW("Bad XML block: header type 0x%x in node at 0x%x has size %d, need %d\n", 1512 (int)dtohs(next->header.type), 1513 (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)), 1514 (int)(totalSize-headerSize), (int)minExtSize); 1515 return (mEventCode=BAD_DOCUMENT); 1516 } 1517 1518 //printf("CurNode=%p, CurExt=%p, headerSize=%d, minExtSize=%d\n", 1519 // mCurNode, mCurExt, headerSize, minExtSize); 1520 1521 return eventCode; 1522 } while (true); 1523 } 1524 1525 void ResXMLParser::getPosition(ResXMLParser::ResXMLPosition* pos) const 1526 { 1527 pos->eventCode = mEventCode; 1528 pos->curNode = mCurNode; 1529 pos->curExt = mCurExt; 1530 } 1531 1532 void ResXMLParser::setPosition(const ResXMLParser::ResXMLPosition& pos) 1533 { 1534 mEventCode = pos.eventCode; 1535 mCurNode = pos.curNode; 1536 mCurExt = pos.curExt; 1537 } 1538 1539 // -------------------------------------------------------------------- 1540 1541 static volatile int32_t gCount = 0; 1542 1543 ResXMLTree::ResXMLTree(const DynamicRefTable* dynamicRefTable) 1544 : ResXMLParser(*this) 1545 , mDynamicRefTable(dynamicRefTable) 1546 , mError(NO_INIT), mOwnedData(NULL) 1547 { 1548 if (kDebugResXMLTree) { 1549 ALOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1); 1550 } 1551 restart(); 1552 } 1553 1554 ResXMLTree::ResXMLTree() 1555 : ResXMLParser(*this) 1556 , mDynamicRefTable(NULL) 1557 , mError(NO_INIT), mOwnedData(NULL) 1558 { 1559 if (kDebugResXMLTree) { 1560 ALOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1); 1561 } 1562 restart(); 1563 } 1564 1565 ResXMLTree::~ResXMLTree() 1566 { 1567 if (kDebugResXMLTree) { 1568 ALOGI("Destroying ResXMLTree in %p #%d\n", this, android_atomic_dec(&gCount)-1); 1569 } 1570 uninit(); 1571 } 1572 1573 status_t ResXMLTree::setTo(const void* data, size_t size, bool copyData) 1574 { 1575 uninit(); 1576 mEventCode = START_DOCUMENT; 1577 1578 if (!data || !size) { 1579 return (mError=BAD_TYPE); 1580 } 1581 1582 if (copyData) { 1583 mOwnedData = malloc(size); 1584 if (mOwnedData == NULL) { 1585 return (mError=NO_MEMORY); 1586 } 1587 memcpy(mOwnedData, data, size); 1588 data = mOwnedData; 1589 } 1590 1591 mHeader = (const ResXMLTree_header*)data; 1592 mSize = dtohl(mHeader->header.size); 1593 if (dtohs(mHeader->header.headerSize) > mSize || mSize > size) { 1594 ALOGW("Bad XML block: header size %d or total size %d is larger than data size %d\n", 1595 (int)dtohs(mHeader->header.headerSize), 1596 (int)dtohl(mHeader->header.size), (int)size); 1597 mError = BAD_TYPE; 1598 restart(); 1599 return mError; 1600 } 1601 mDataEnd = ((const uint8_t*)mHeader) + mSize; 1602 1603 mStrings.uninit(); 1604 mRootNode = NULL; 1605 mResIds = NULL; 1606 mNumResIds = 0; 1607 1608 // First look for a couple interesting chunks: the string block 1609 // and first XML node. 1610 const ResChunk_header* chunk = 1611 (const ResChunk_header*)(((const uint8_t*)mHeader) + dtohs(mHeader->header.headerSize)); 1612 const ResChunk_header* lastChunk = chunk; 1613 while (((const uint8_t*)chunk) < (mDataEnd-sizeof(ResChunk_header)) && 1614 ((const uint8_t*)chunk) < (mDataEnd-dtohl(chunk->size))) { 1615 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), mDataEnd, "XML"); 1616 if (err != NO_ERROR) { 1617 mError = err; 1618 goto done; 1619 } 1620 const uint16_t type = dtohs(chunk->type); 1621 const size_t size = dtohl(chunk->size); 1622 if (kDebugXMLNoisy) { 1623 printf("Scanning @ %p: type=0x%x, size=0x%zx\n", 1624 (void*)(((uintptr_t)chunk)-((uintptr_t)mHeader)), type, size); 1625 } 1626 if (type == RES_STRING_POOL_TYPE) { 1627 mStrings.setTo(chunk, size); 1628 } else if (type == RES_XML_RESOURCE_MAP_TYPE) { 1629 mResIds = (const uint32_t*) 1630 (((const uint8_t*)chunk)+dtohs(chunk->headerSize)); 1631 mNumResIds = (dtohl(chunk->size)-dtohs(chunk->headerSize))/sizeof(uint32_t); 1632 } else if (type >= RES_XML_FIRST_CHUNK_TYPE 1633 && type <= RES_XML_LAST_CHUNK_TYPE) { 1634 if (validateNode((const ResXMLTree_node*)chunk) != NO_ERROR) { 1635 mError = BAD_TYPE; 1636 goto done; 1637 } 1638 mCurNode = (const ResXMLTree_node*)lastChunk; 1639 if (nextNode() == BAD_DOCUMENT) { 1640 mError = BAD_TYPE; 1641 goto done; 1642 } 1643 mRootNode = mCurNode; 1644 mRootExt = mCurExt; 1645 mRootCode = mEventCode; 1646 break; 1647 } else { 1648 if (kDebugXMLNoisy) { 1649 printf("Skipping unknown chunk!\n"); 1650 } 1651 } 1652 lastChunk = chunk; 1653 chunk = (const ResChunk_header*) 1654 (((const uint8_t*)chunk) + size); 1655 } 1656 1657 if (mRootNode == NULL) { 1658 ALOGW("Bad XML block: no root element node found\n"); 1659 mError = BAD_TYPE; 1660 goto done; 1661 } 1662 1663 mError = mStrings.getError(); 1664 1665 done: 1666 restart(); 1667 return mError; 1668 } 1669 1670 status_t ResXMLTree::getError() const 1671 { 1672 return mError; 1673 } 1674 1675 void ResXMLTree::uninit() 1676 { 1677 mError = NO_INIT; 1678 mStrings.uninit(); 1679 if (mOwnedData) { 1680 free(mOwnedData); 1681 mOwnedData = NULL; 1682 } 1683 restart(); 1684 } 1685 1686 status_t ResXMLTree::validateNode(const ResXMLTree_node* node) const 1687 { 1688 const uint16_t eventCode = dtohs(node->header.type); 1689 1690 status_t err = validate_chunk( 1691 &node->header, sizeof(ResXMLTree_node), 1692 mDataEnd, "ResXMLTree_node"); 1693 1694 if (err >= NO_ERROR) { 1695 // Only perform additional validation on START nodes 1696 if (eventCode != RES_XML_START_ELEMENT_TYPE) { 1697 return NO_ERROR; 1698 } 1699 1700 const uint16_t headerSize = dtohs(node->header.headerSize); 1701 const uint32_t size = dtohl(node->header.size); 1702 const ResXMLTree_attrExt* attrExt = (const ResXMLTree_attrExt*) 1703 (((const uint8_t*)node) + headerSize); 1704 // check for sensical values pulled out of the stream so far... 1705 if ((size >= headerSize + sizeof(ResXMLTree_attrExt)) 1706 && ((void*)attrExt > (void*)node)) { 1707 const size_t attrSize = ((size_t)dtohs(attrExt->attributeSize)) 1708 * dtohs(attrExt->attributeCount); 1709 if ((dtohs(attrExt->attributeStart)+attrSize) <= (size-headerSize)) { 1710 return NO_ERROR; 1711 } 1712 ALOGW("Bad XML block: node attributes use 0x%x bytes, only have 0x%x bytes\n", 1713 (unsigned int)(dtohs(attrExt->attributeStart)+attrSize), 1714 (unsigned int)(size-headerSize)); 1715 } 1716 else { 1717 ALOGW("Bad XML start block: node header size 0x%x, size 0x%x\n", 1718 (unsigned int)headerSize, (unsigned int)size); 1719 } 1720 return BAD_TYPE; 1721 } 1722 1723 return err; 1724 1725 #if 0 1726 const bool isStart = dtohs(node->header.type) == RES_XML_START_ELEMENT_TYPE; 1727 1728 const uint16_t headerSize = dtohs(node->header.headerSize); 1729 const uint32_t size = dtohl(node->header.size); 1730 1731 if (headerSize >= (isStart ? sizeof(ResXMLTree_attrNode) : sizeof(ResXMLTree_node))) { 1732 if (size >= headerSize) { 1733 if (((const uint8_t*)node) <= (mDataEnd-size)) { 1734 if (!isStart) { 1735 return NO_ERROR; 1736 } 1737 if ((((size_t)dtohs(node->attributeSize))*dtohs(node->attributeCount)) 1738 <= (size-headerSize)) { 1739 return NO_ERROR; 1740 } 1741 ALOGW("Bad XML block: node attributes use 0x%x bytes, only have 0x%x bytes\n", 1742 ((int)dtohs(node->attributeSize))*dtohs(node->attributeCount), 1743 (int)(size-headerSize)); 1744 return BAD_TYPE; 1745 } 1746 ALOGW("Bad XML block: node at 0x%x extends beyond data end 0x%x\n", 1747 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)), (int)mSize); 1748 return BAD_TYPE; 1749 } 1750 ALOGW("Bad XML block: node at 0x%x header size 0x%x smaller than total size 0x%x\n", 1751 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)), 1752 (int)headerSize, (int)size); 1753 return BAD_TYPE; 1754 } 1755 ALOGW("Bad XML block: node at 0x%x header size 0x%x too small\n", 1756 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)), 1757 (int)headerSize); 1758 return BAD_TYPE; 1759 #endif 1760 } 1761 1762 // -------------------------------------------------------------------- 1763 // -------------------------------------------------------------------- 1764 // -------------------------------------------------------------------- 1765 1766 void ResTable_config::copyFromDeviceNoSwap(const ResTable_config& o) { 1767 const size_t size = dtohl(o.size); 1768 if (size >= sizeof(ResTable_config)) { 1769 *this = o; 1770 } else { 1771 memcpy(this, &o, size); 1772 memset(((uint8_t*)this)+size, 0, sizeof(ResTable_config)-size); 1773 } 1774 } 1775 1776 /* static */ size_t unpackLanguageOrRegion(const char in[2], const char base, 1777 char out[4]) { 1778 if (in[0] & 0x80) { 1779 // The high bit is "1", which means this is a packed three letter 1780 // language code. 1781 1782 // The smallest 5 bits of the second char are the first alphabet. 1783 const uint8_t first = in[1] & 0x1f; 1784 // The last three bits of the second char and the first two bits 1785 // of the first char are the second alphabet. 1786 const uint8_t second = ((in[1] & 0xe0) >> 5) + ((in[0] & 0x03) << 3); 1787 // Bits 3 to 7 (inclusive) of the first char are the third alphabet. 1788 const uint8_t third = (in[0] & 0x7c) >> 2; 1789 1790 out[0] = first + base; 1791 out[1] = second + base; 1792 out[2] = third + base; 1793 out[3] = 0; 1794 1795 return 3; 1796 } 1797 1798 if (in[0]) { 1799 memcpy(out, in, 2); 1800 memset(out + 2, 0, 2); 1801 return 2; 1802 } 1803 1804 memset(out, 0, 4); 1805 return 0; 1806 } 1807 1808 /* static */ void packLanguageOrRegion(const char* in, const char base, 1809 char out[2]) { 1810 if (in[2] == 0 || in[2] == '-') { 1811 out[0] = in[0]; 1812 out[1] = in[1]; 1813 } else { 1814 uint8_t first = (in[0] - base) & 0x007f; 1815 uint8_t second = (in[1] - base) & 0x007f; 1816 uint8_t third = (in[2] - base) & 0x007f; 1817 1818 out[0] = (0x80 | (third << 2) | (second >> 3)); 1819 out[1] = ((second << 5) | first); 1820 } 1821 } 1822 1823 1824 void ResTable_config::packLanguage(const char* language) { 1825 packLanguageOrRegion(language, 'a', this->language); 1826 } 1827 1828 void ResTable_config::packRegion(const char* region) { 1829 packLanguageOrRegion(region, '0', this->country); 1830 } 1831 1832 size_t ResTable_config::unpackLanguage(char language[4]) const { 1833 return unpackLanguageOrRegion(this->language, 'a', language); 1834 } 1835 1836 size_t ResTable_config::unpackRegion(char region[4]) const { 1837 return unpackLanguageOrRegion(this->country, '0', region); 1838 } 1839 1840 1841 void ResTable_config::copyFromDtoH(const ResTable_config& o) { 1842 copyFromDeviceNoSwap(o); 1843 size = sizeof(ResTable_config); 1844 mcc = dtohs(mcc); 1845 mnc = dtohs(mnc); 1846 density = dtohs(density); 1847 screenWidth = dtohs(screenWidth); 1848 screenHeight = dtohs(screenHeight); 1849 sdkVersion = dtohs(sdkVersion); 1850 minorVersion = dtohs(minorVersion); 1851 smallestScreenWidthDp = dtohs(smallestScreenWidthDp); 1852 screenWidthDp = dtohs(screenWidthDp); 1853 screenHeightDp = dtohs(screenHeightDp); 1854 } 1855 1856 void ResTable_config::swapHtoD() { 1857 size = htodl(size); 1858 mcc = htods(mcc); 1859 mnc = htods(mnc); 1860 density = htods(density); 1861 screenWidth = htods(screenWidth); 1862 screenHeight = htods(screenHeight); 1863 sdkVersion = htods(sdkVersion); 1864 minorVersion = htods(minorVersion); 1865 smallestScreenWidthDp = htods(smallestScreenWidthDp); 1866 screenWidthDp = htods(screenWidthDp); 1867 screenHeightDp = htods(screenHeightDp); 1868 } 1869 1870 /* static */ inline int compareLocales(const ResTable_config &l, const ResTable_config &r) { 1871 if (l.locale != r.locale) { 1872 // NOTE: This is the old behaviour with respect to comparison orders. 1873 // The diff value here doesn't make much sense (given our bit packing scheme) 1874 // but it's stable, and that's all we need. 1875 return l.locale - r.locale; 1876 } 1877 1878 // The language & region are equal, so compare the scripts and variants. 1879 const char emptyScript[sizeof(l.localeScript)] = {'\0', '\0', '\0', '\0'}; 1880 const char *lScript = l.localeScriptWasComputed ? emptyScript : l.localeScript; 1881 const char *rScript = r.localeScriptWasComputed ? emptyScript : r.localeScript; 1882 int script = memcmp(lScript, rScript, sizeof(l.localeScript)); 1883 if (script) { 1884 return script; 1885 } 1886 1887 // The language, region and script are equal, so compare variants. 1888 // 1889 // This should happen very infrequently (if at all.) 1890 return memcmp(l.localeVariant, r.localeVariant, sizeof(l.localeVariant)); 1891 } 1892 1893 int ResTable_config::compare(const ResTable_config& o) const { 1894 int32_t diff = (int32_t)(imsi - o.imsi); 1895 if (diff != 0) return diff; 1896 diff = compareLocales(*this, o); 1897 if (diff != 0) return diff; 1898 diff = (int32_t)(screenType - o.screenType); 1899 if (diff != 0) return diff; 1900 diff = (int32_t)(input - o.input); 1901 if (diff != 0) return diff; 1902 diff = (int32_t)(screenSize - o.screenSize); 1903 if (diff != 0) return diff; 1904 diff = (int32_t)(version - o.version); 1905 if (diff != 0) return diff; 1906 diff = (int32_t)(screenLayout - o.screenLayout); 1907 if (diff != 0) return diff; 1908 diff = (int32_t)(screenLayout2 - o.screenLayout2); 1909 if (diff != 0) return diff; 1910 diff = (int32_t)(colorMode - o.colorMode); 1911 if (diff != 0) return diff; 1912 diff = (int32_t)(uiMode - o.uiMode); 1913 if (diff != 0) return diff; 1914 diff = (int32_t)(smallestScreenWidthDp - o.smallestScreenWidthDp); 1915 if (diff != 0) return diff; 1916 diff = (int32_t)(screenSizeDp - o.screenSizeDp); 1917 return (int)diff; 1918 } 1919 1920 int ResTable_config::compareLogical(const ResTable_config& o) const { 1921 if (mcc != o.mcc) { 1922 return mcc < o.mcc ? -1 : 1; 1923 } 1924 if (mnc != o.mnc) { 1925 return mnc < o.mnc ? -1 : 1; 1926 } 1927 1928 int diff = compareLocales(*this, o); 1929 if (diff < 0) { 1930 return -1; 1931 } 1932 if (diff > 0) { 1933 return 1; 1934 } 1935 1936 if ((screenLayout & MASK_LAYOUTDIR) != (o.screenLayout & MASK_LAYOUTDIR)) { 1937 return (screenLayout & MASK_LAYOUTDIR) < (o.screenLayout & MASK_LAYOUTDIR) ? -1 : 1; 1938 } 1939 if (smallestScreenWidthDp != o.smallestScreenWidthDp) { 1940 return smallestScreenWidthDp < o.smallestScreenWidthDp ? -1 : 1; 1941 } 1942 if (screenWidthDp != o.screenWidthDp) { 1943 return screenWidthDp < o.screenWidthDp ? -1 : 1; 1944 } 1945 if (screenHeightDp != o.screenHeightDp) { 1946 return screenHeightDp < o.screenHeightDp ? -1 : 1; 1947 } 1948 if (screenWidth != o.screenWidth) { 1949 return screenWidth < o.screenWidth ? -1 : 1; 1950 } 1951 if (screenHeight != o.screenHeight) { 1952 return screenHeight < o.screenHeight ? -1 : 1; 1953 } 1954 if (density != o.density) { 1955 return density < o.density ? -1 : 1; 1956 } 1957 if (orientation != o.orientation) { 1958 return orientation < o.orientation ? -1 : 1; 1959 } 1960 if (touchscreen != o.touchscreen) { 1961 return touchscreen < o.touchscreen ? -1 : 1; 1962 } 1963 if (input != o.input) { 1964 return input < o.input ? -1 : 1; 1965 } 1966 if (screenLayout != o.screenLayout) { 1967 return screenLayout < o.screenLayout ? -1 : 1; 1968 } 1969 if (screenLayout2 != o.screenLayout2) { 1970 return screenLayout2 < o.screenLayout2 ? -1 : 1; 1971 } 1972 if (colorMode != o.colorMode) { 1973 return colorMode < o.colorMode ? -1 : 1; 1974 } 1975 if (uiMode != o.uiMode) { 1976 return uiMode < o.uiMode ? -1 : 1; 1977 } 1978 if (version != o.version) { 1979 return version < o.version ? -1 : 1; 1980 } 1981 return 0; 1982 } 1983 1984 int ResTable_config::diff(const ResTable_config& o) const { 1985 int diffs = 0; 1986 if (mcc != o.mcc) diffs |= CONFIG_MCC; 1987 if (mnc != o.mnc) diffs |= CONFIG_MNC; 1988 if (orientation != o.orientation) diffs |= CONFIG_ORIENTATION; 1989 if (density != o.density) diffs |= CONFIG_DENSITY; 1990 if (touchscreen != o.touchscreen) diffs |= CONFIG_TOUCHSCREEN; 1991 if (((inputFlags^o.inputFlags)&(MASK_KEYSHIDDEN|MASK_NAVHIDDEN)) != 0) 1992 diffs |= CONFIG_KEYBOARD_HIDDEN; 1993 if (keyboard != o.keyboard) diffs |= CONFIG_KEYBOARD; 1994 if (navigation != o.navigation) diffs |= CONFIG_NAVIGATION; 1995 if (screenSize != o.screenSize) diffs |= CONFIG_SCREEN_SIZE; 1996 if (version != o.version) diffs |= CONFIG_VERSION; 1997 if ((screenLayout & MASK_LAYOUTDIR) != (o.screenLayout & MASK_LAYOUTDIR)) diffs |= CONFIG_LAYOUTDIR; 1998 if ((screenLayout & ~MASK_LAYOUTDIR) != (o.screenLayout & ~MASK_LAYOUTDIR)) diffs |= CONFIG_SCREEN_LAYOUT; 1999 if ((screenLayout2 & MASK_SCREENROUND) != (o.screenLayout2 & MASK_SCREENROUND)) diffs |= CONFIG_SCREEN_ROUND; 2000 if ((colorMode & MASK_WIDE_COLOR_GAMUT) != (o.colorMode & MASK_WIDE_COLOR_GAMUT)) diffs |= CONFIG_COLOR_MODE; 2001 if ((colorMode & MASK_HDR) != (o.colorMode & MASK_HDR)) diffs |= CONFIG_COLOR_MODE; 2002 if (uiMode != o.uiMode) diffs |= CONFIG_UI_MODE; 2003 if (smallestScreenWidthDp != o.smallestScreenWidthDp) diffs |= CONFIG_SMALLEST_SCREEN_SIZE; 2004 if (screenSizeDp != o.screenSizeDp) diffs |= CONFIG_SCREEN_SIZE; 2005 2006 const int diff = compareLocales(*this, o); 2007 if (diff) diffs |= CONFIG_LOCALE; 2008 2009 return diffs; 2010 } 2011 2012 int ResTable_config::isLocaleMoreSpecificThan(const ResTable_config& o) const { 2013 if (locale || o.locale) { 2014 if (language[0] != o.language[0]) { 2015 if (!language[0]) return -1; 2016 if (!o.language[0]) return 1; 2017 } 2018 2019 if (country[0] != o.country[0]) { 2020 if (!country[0]) return -1; 2021 if (!o.country[0]) return 1; 2022 } 2023 } 2024 2025 // There isn't a well specified "importance" order between variants and 2026 // scripts. We can't easily tell whether, say "en-Latn-US" is more or less 2027 // specific than "en-US-POSIX". 2028 // 2029 // We therefore arbitrarily decide to give priority to variants over 2030 // scripts since it seems more useful to do so. We will consider 2031 // "en-US-POSIX" to be more specific than "en-Latn-US". 2032 2033 const int score = ((localeScript[0] != '\0' && !localeScriptWasComputed) ? 1 : 0) + 2034 ((localeVariant[0] != '\0') ? 2 : 0); 2035 2036 const int oScore = (o.localeScript[0] != '\0' && !o.localeScriptWasComputed ? 1 : 0) + 2037 ((o.localeVariant[0] != '\0') ? 2 : 0); 2038 2039 return score - oScore; 2040 } 2041 2042 bool ResTable_config::isMoreSpecificThan(const ResTable_config& o) const { 2043 // The order of the following tests defines the importance of one 2044 // configuration parameter over another. Those tests first are more 2045 // important, trumping any values in those following them. 2046 if (imsi || o.imsi) { 2047 if (mcc != o.mcc) { 2048 if (!mcc) return false; 2049 if (!o.mcc) return true; 2050 } 2051 2052 if (mnc != o.mnc) { 2053 if (!mnc) return false; 2054 if (!o.mnc) return true; 2055 } 2056 } 2057 2058 if (locale || o.locale) { 2059 const int diff = isLocaleMoreSpecificThan(o); 2060 if (diff < 0) { 2061 return false; 2062 } 2063 2064 if (diff > 0) { 2065 return true; 2066 } 2067 } 2068 2069 if (screenLayout || o.screenLayout) { 2070 if (((screenLayout^o.screenLayout) & MASK_LAYOUTDIR) != 0) { 2071 if (!(screenLayout & MASK_LAYOUTDIR)) return false; 2072 if (!(o.screenLayout & MASK_LAYOUTDIR)) return true; 2073 } 2074 } 2075 2076 if (smallestScreenWidthDp || o.smallestScreenWidthDp) { 2077 if (smallestScreenWidthDp != o.smallestScreenWidthDp) { 2078 if (!smallestScreenWidthDp) return false; 2079 if (!o.smallestScreenWidthDp) return true; 2080 } 2081 } 2082 2083 if (screenSizeDp || o.screenSizeDp) { 2084 if (screenWidthDp != o.screenWidthDp) { 2085 if (!screenWidthDp) return false; 2086 if (!o.screenWidthDp) return true; 2087 } 2088 2089 if (screenHeightDp != o.screenHeightDp) { 2090 if (!screenHeightDp) return false; 2091 if (!o.screenHeightDp) return true; 2092 } 2093 } 2094 2095 if (screenLayout || o.screenLayout) { 2096 if (((screenLayout^o.screenLayout) & MASK_SCREENSIZE) != 0) { 2097 if (!(screenLayout & MASK_SCREENSIZE)) return false; 2098 if (!(o.screenLayout & MASK_SCREENSIZE)) return true; 2099 } 2100 if (((screenLayout^o.screenLayout) & MASK_SCREENLONG) != 0) { 2101 if (!(screenLayout & MASK_SCREENLONG)) return false; 2102 if (!(o.screenLayout & MASK_SCREENLONG)) return true; 2103 } 2104 } 2105 2106 if (screenLayout2 || o.screenLayout2) { 2107 if (((screenLayout2^o.screenLayout2) & MASK_SCREENROUND) != 0) { 2108 if (!(screenLayout2 & MASK_SCREENROUND)) return false; 2109 if (!(o.screenLayout2 & MASK_SCREENROUND)) return true; 2110 } 2111 } 2112 2113 if (colorMode || o.colorMode) { 2114 if (((colorMode^o.colorMode) & MASK_HDR) != 0) { 2115 if (!(colorMode & MASK_HDR)) return false; 2116 if (!(o.colorMode & MASK_HDR)) return true; 2117 } 2118 if (((colorMode^o.colorMode) & MASK_WIDE_COLOR_GAMUT) != 0) { 2119 if (!(colorMode & MASK_WIDE_COLOR_GAMUT)) return false; 2120 if (!(o.colorMode & MASK_WIDE_COLOR_GAMUT)) return true; 2121 } 2122 } 2123 2124 if (orientation != o.orientation) { 2125 if (!orientation) return false; 2126 if (!o.orientation) return true; 2127 } 2128 2129 if (uiMode || o.uiMode) { 2130 if (((uiMode^o.uiMode) & MASK_UI_MODE_TYPE) != 0) { 2131 if (!(uiMode & MASK_UI_MODE_TYPE)) return false; 2132 if (!(o.uiMode & MASK_UI_MODE_TYPE)) return true; 2133 } 2134 if (((uiMode^o.uiMode) & MASK_UI_MODE_NIGHT) != 0) { 2135 if (!(uiMode & MASK_UI_MODE_NIGHT)) return false; 2136 if (!(o.uiMode & MASK_UI_MODE_NIGHT)) return true; 2137 } 2138 } 2139 2140 // density is never 'more specific' 2141 // as the default just equals 160 2142 2143 if (touchscreen != o.touchscreen) { 2144 if (!touchscreen) return false; 2145 if (!o.touchscreen) return true; 2146 } 2147 2148 if (input || o.input) { 2149 if (((inputFlags^o.inputFlags) & MASK_KEYSHIDDEN) != 0) { 2150 if (!(inputFlags & MASK_KEYSHIDDEN)) return false; 2151 if (!(o.inputFlags & MASK_KEYSHIDDEN)) return true; 2152 } 2153 2154 if (((inputFlags^o.inputFlags) & MASK_NAVHIDDEN) != 0) { 2155 if (!(inputFlags & MASK_NAVHIDDEN)) return false; 2156 if (!(o.inputFlags & MASK_NAVHIDDEN)) return true; 2157 } 2158 2159 if (keyboard != o.keyboard) { 2160 if (!keyboard) return false; 2161 if (!o.keyboard) return true; 2162 } 2163 2164 if (navigation != o.navigation) { 2165 if (!navigation) return false; 2166 if (!o.navigation) return true; 2167 } 2168 } 2169 2170 if (screenSize || o.screenSize) { 2171 if (screenWidth != o.screenWidth) { 2172 if (!screenWidth) return false; 2173 if (!o.screenWidth) return true; 2174 } 2175 2176 if (screenHeight != o.screenHeight) { 2177 if (!screenHeight) return false; 2178 if (!o.screenHeight) return true; 2179 } 2180 } 2181 2182 if (version || o.version) { 2183 if (sdkVersion != o.sdkVersion) { 2184 if (!sdkVersion) return false; 2185 if (!o.sdkVersion) return true; 2186 } 2187 2188 if (minorVersion != o.minorVersion) { 2189 if (!minorVersion) return false; 2190 if (!o.minorVersion) return true; 2191 } 2192 } 2193 return false; 2194 } 2195 2196 // Codes for specially handled languages and regions 2197 static const char kEnglish[2] = {'e', 'n'}; // packed version of "en" 2198 static const char kUnitedStates[2] = {'U', 'S'}; // packed version of "US" 2199 static const char kFilipino[2] = {'\xAD', '\x05'}; // packed version of "fil" 2200 static const char kTagalog[2] = {'t', 'l'}; // packed version of "tl" 2201 2202 // Checks if two language or region codes are identical 2203 inline bool areIdentical(const char code1[2], const char code2[2]) { 2204 return code1[0] == code2[0] && code1[1] == code2[1]; 2205 } 2206 2207 inline bool langsAreEquivalent(const char lang1[2], const char lang2[2]) { 2208 return areIdentical(lang1, lang2) || 2209 (areIdentical(lang1, kTagalog) && areIdentical(lang2, kFilipino)) || 2210 (areIdentical(lang1, kFilipino) && areIdentical(lang2, kTagalog)); 2211 } 2212 2213 bool ResTable_config::isLocaleBetterThan(const ResTable_config& o, 2214 const ResTable_config* requested) const { 2215 if (requested->locale == 0) { 2216 // The request doesn't have a locale, so no resource is better 2217 // than the other. 2218 return false; 2219 } 2220 2221 if (locale == 0 && o.locale == 0) { 2222 // The locale part of both resources is empty, so none is better 2223 // than the other. 2224 return false; 2225 } 2226 2227 // Non-matching locales have been filtered out, so both resources 2228 // match the requested locale. 2229 // 2230 // Because of the locale-related checks in match() and the checks, we know 2231 // that: 2232 // 1) The resource languages are either empty or match the request; 2233 // and 2234 // 2) If the request's script is known, the resource scripts are either 2235 // unknown or match the request. 2236 2237 if (!langsAreEquivalent(language, o.language)) { 2238 // The languages of the two resources are not equivalent. If we are 2239 // here, we can only assume that the two resources matched the request 2240 // because one doesn't have a language and the other has a matching 2241 // language. 2242 // 2243 // We consider the one that has the language specified a better match. 2244 // 2245 // The exception is that we consider no-language resources a better match 2246 // for US English and similar locales than locales that are a descendant 2247 // of Internatinal English (en-001), since no-language resources are 2248 // where the US English resource have traditionally lived for most apps. 2249 if (areIdentical(requested->language, kEnglish)) { 2250 if (areIdentical(requested->country, kUnitedStates)) { 2251 // For US English itself, we consider a no-locale resource a 2252 // better match if the other resource has a country other than 2253 // US specified. 2254 if (language[0] != '\0') { 2255 return country[0] == '\0' || areIdentical(country, kUnitedStates); 2256 } else { 2257 return !(o.country[0] == '\0' || areIdentical(o.country, kUnitedStates)); 2258 } 2259 } else if (localeDataIsCloseToUsEnglish(requested->country)) { 2260 if (language[0] != '\0') { 2261 return localeDataIsCloseToUsEnglish(country); 2262 } else { 2263 return !localeDataIsCloseToUsEnglish(o.country); 2264 } 2265 } 2266 } 2267 return (language[0] != '\0'); 2268 } 2269 2270 // If we are here, both the resources have an equivalent non-empty language 2271 // to the request. 2272 // 2273 // Because the languages are equivalent, computeScript() always returns a 2274 // non-empty script for languages it knows about, and we have passed the 2275 // script checks in match(), the scripts are either all unknown or are all 2276 // the same. So we can't gain anything by checking the scripts. We need to 2277 // check the region and variant. 2278 2279 // See if any of the regions is better than the other. 2280 const int region_comparison = localeDataCompareRegions( 2281 country, o.country, 2282 requested->language, requested->localeScript, requested->country); 2283 if (region_comparison != 0) { 2284 return (region_comparison > 0); 2285 } 2286 2287 // The regions are the same. Try the variant. 2288 const bool localeMatches = strncmp( 2289 localeVariant, requested->localeVariant, sizeof(localeVariant)) == 0; 2290 const bool otherMatches = strncmp( 2291 o.localeVariant, requested->localeVariant, sizeof(localeVariant)) == 0; 2292 if (localeMatches != otherMatches) { 2293 return localeMatches; 2294 } 2295 2296 // Finally, the languages, although equivalent, may still be different 2297 // (like for Tagalog and Filipino). Identical is better than just 2298 // equivalent. 2299 if (areIdentical(language, requested->language) 2300 && !areIdentical(o.language, requested->language)) { 2301 return true; 2302 } 2303 2304 return false; 2305 } 2306 2307 bool ResTable_config::isBetterThan(const ResTable_config& o, 2308 const ResTable_config* requested) const { 2309 if (requested) { 2310 if (imsi || o.imsi) { 2311 if ((mcc != o.mcc) && requested->mcc) { 2312 return (mcc); 2313 } 2314 2315 if ((mnc != o.mnc) && requested->mnc) { 2316 return (mnc); 2317 } 2318 } 2319 2320 if (isLocaleBetterThan(o, requested)) { 2321 return true; 2322 } 2323 2324 if (screenLayout || o.screenLayout) { 2325 if (((screenLayout^o.screenLayout) & MASK_LAYOUTDIR) != 0 2326 && (requested->screenLayout & MASK_LAYOUTDIR)) { 2327 int myLayoutDir = screenLayout & MASK_LAYOUTDIR; 2328 int oLayoutDir = o.screenLayout & MASK_LAYOUTDIR; 2329 return (myLayoutDir > oLayoutDir); 2330 } 2331 } 2332 2333 if (smallestScreenWidthDp || o.smallestScreenWidthDp) { 2334 // The configuration closest to the actual size is best. 2335 // We assume that larger configs have already been filtered 2336 // out at this point. That means we just want the largest one. 2337 if (smallestScreenWidthDp != o.smallestScreenWidthDp) { 2338 return smallestScreenWidthDp > o.smallestScreenWidthDp; 2339 } 2340 } 2341 2342 if (screenSizeDp || o.screenSizeDp) { 2343 // "Better" is based on the sum of the difference between both 2344 // width and height from the requested dimensions. We are 2345 // assuming the invalid configs (with smaller dimens) have 2346 // already been filtered. Note that if a particular dimension 2347 // is unspecified, we will end up with a large value (the 2348 // difference between 0 and the requested dimension), which is 2349 // good since we will prefer a config that has specified a 2350 // dimension value. 2351 int myDelta = 0, otherDelta = 0; 2352 if (requested->screenWidthDp) { 2353 myDelta += requested->screenWidthDp - screenWidthDp; 2354 otherDelta += requested->screenWidthDp - o.screenWidthDp; 2355 } 2356 if (requested->screenHeightDp) { 2357 myDelta += requested->screenHeightDp - screenHeightDp; 2358 otherDelta += requested->screenHeightDp - o.screenHeightDp; 2359 } 2360 if (kDebugTableSuperNoisy) { 2361 ALOGI("Comparing this %dx%d to other %dx%d in %dx%d: myDelta=%d otherDelta=%d", 2362 screenWidthDp, screenHeightDp, o.screenWidthDp, o.screenHeightDp, 2363 requested->screenWidthDp, requested->screenHeightDp, myDelta, otherDelta); 2364 } 2365 if (myDelta != otherDelta) { 2366 return myDelta < otherDelta; 2367 } 2368 } 2369 2370 if (screenLayout || o.screenLayout) { 2371 if (((screenLayout^o.screenLayout) & MASK_SCREENSIZE) != 0 2372 && (requested->screenLayout & MASK_SCREENSIZE)) { 2373 // A little backwards compatibility here: undefined is 2374 // considered equivalent to normal. But only if the 2375 // requested size is at least normal; otherwise, small 2376 // is better than the default. 2377 int mySL = (screenLayout & MASK_SCREENSIZE); 2378 int oSL = (o.screenLayout & MASK_SCREENSIZE); 2379 int fixedMySL = mySL; 2380 int fixedOSL = oSL; 2381 if ((requested->screenLayout & MASK_SCREENSIZE) >= SCREENSIZE_NORMAL) { 2382 if (fixedMySL == 0) fixedMySL = SCREENSIZE_NORMAL; 2383 if (fixedOSL == 0) fixedOSL = SCREENSIZE_NORMAL; 2384 } 2385 // For screen size, the best match is the one that is 2386 // closest to the requested screen size, but not over 2387 // (the not over part is dealt with in match() below). 2388 if (fixedMySL == fixedOSL) { 2389 // If the two are the same, but 'this' is actually 2390 // undefined, then the other is really a better match. 2391 if (mySL == 0) return false; 2392 return true; 2393 } 2394 if (fixedMySL != fixedOSL) { 2395 return fixedMySL > fixedOSL; 2396 } 2397 } 2398 if (((screenLayout^o.screenLayout) & MASK_SCREENLONG) != 0 2399 && (requested->screenLayout & MASK_SCREENLONG)) { 2400 return (screenLayout & MASK_SCREENLONG); 2401 } 2402 } 2403 2404 if (screenLayout2 || o.screenLayout2) { 2405 if (((screenLayout2^o.screenLayout2) & MASK_SCREENROUND) != 0 && 2406 (requested->screenLayout2 & MASK_SCREENROUND)) { 2407 return screenLayout2 & MASK_SCREENROUND; 2408 } 2409 } 2410 2411 if (colorMode || o.colorMode) { 2412 if (((colorMode^o.colorMode) & MASK_WIDE_COLOR_GAMUT) != 0 && 2413 (requested->colorMode & MASK_WIDE_COLOR_GAMUT)) { 2414 return colorMode & MASK_WIDE_COLOR_GAMUT; 2415 } 2416 if (((colorMode^o.colorMode) & MASK_HDR) != 0 && 2417 (requested->colorMode & MASK_HDR)) { 2418 return colorMode & MASK_HDR; 2419 } 2420 } 2421 2422 if ((orientation != o.orientation) && requested->orientation) { 2423 return (orientation); 2424 } 2425 2426 if (uiMode || o.uiMode) { 2427 if (((uiMode^o.uiMode) & MASK_UI_MODE_TYPE) != 0 2428 && (requested->uiMode & MASK_UI_MODE_TYPE)) { 2429 return (uiMode & MASK_UI_MODE_TYPE); 2430 } 2431 if (((uiMode^o.uiMode) & MASK_UI_MODE_NIGHT) != 0 2432 && (requested->uiMode & MASK_UI_MODE_NIGHT)) { 2433 return (uiMode & MASK_UI_MODE_NIGHT); 2434 } 2435 } 2436 2437 if (screenType || o.screenType) { 2438 if (density != o.density) { 2439 // Use the system default density (DENSITY_MEDIUM, 160dpi) if none specified. 2440 const int thisDensity = density ? density : int(ResTable_config::DENSITY_MEDIUM); 2441 const int otherDensity = o.density ? o.density : int(ResTable_config::DENSITY_MEDIUM); 2442 2443 // We always prefer DENSITY_ANY over scaling a density bucket. 2444 if (thisDensity == ResTable_config::DENSITY_ANY) { 2445 return true; 2446 } else if (otherDensity == ResTable_config::DENSITY_ANY) { 2447 return false; 2448 } 2449 2450 int requestedDensity = requested->density; 2451 if (requested->density == 0 || 2452 requested->density == ResTable_config::DENSITY_ANY) { 2453 requestedDensity = ResTable_config::DENSITY_MEDIUM; 2454 } 2455 2456 // DENSITY_ANY is now dealt with. We should look to 2457 // pick a density bucket and potentially scale it. 2458 // Any density is potentially useful 2459 // because the system will scale it. Scaling down 2460 // is generally better than scaling up. 2461 int h = thisDensity; 2462 int l = otherDensity; 2463 bool bImBigger = true; 2464 if (l > h) { 2465 int t = h; 2466 h = l; 2467 l = t; 2468 bImBigger = false; 2469 } 2470 2471 if (requestedDensity >= h) { 2472 // requested value higher than both l and h, give h 2473 return bImBigger; 2474 } 2475 if (l >= requestedDensity) { 2476 // requested value lower than both l and h, give l 2477 return !bImBigger; 2478 } 2479 // saying that scaling down is 2x better than up 2480 if (((2 * l) - requestedDensity) * h > requestedDensity * requestedDensity) { 2481 return !bImBigger; 2482 } else { 2483 return bImBigger; 2484 } 2485 } 2486 2487 if ((touchscreen != o.touchscreen) && requested->touchscreen) { 2488 return (touchscreen); 2489 } 2490 } 2491 2492 if (input || o.input) { 2493 const int keysHidden = inputFlags & MASK_KEYSHIDDEN; 2494 const int oKeysHidden = o.inputFlags & MASK_KEYSHIDDEN; 2495 if (keysHidden != oKeysHidden) { 2496 const int reqKeysHidden = 2497 requested->inputFlags & MASK_KEYSHIDDEN; 2498 if (reqKeysHidden) { 2499 2500 if (!keysHidden) return false; 2501 if (!oKeysHidden) return true; 2502 // For compatibility, we count KEYSHIDDEN_NO as being 2503 // the same as KEYSHIDDEN_SOFT. Here we disambiguate 2504 // these by making an exact match more specific. 2505 if (reqKeysHidden == keysHidden) return true; 2506 if (reqKeysHidden == oKeysHidden) return false; 2507 } 2508 } 2509 2510 const int navHidden = inputFlags & MASK_NAVHIDDEN; 2511 const int oNavHidden = o.inputFlags & MASK_NAVHIDDEN; 2512 if (navHidden != oNavHidden) { 2513 const int reqNavHidden = 2514 requested->inputFlags & MASK_NAVHIDDEN; 2515 if (reqNavHidden) { 2516 2517 if (!navHidden) return false; 2518 if (!oNavHidden) return true; 2519 } 2520 } 2521 2522 if ((keyboard != o.keyboard) && requested->keyboard) { 2523 return (keyboard); 2524 } 2525 2526 if ((navigation != o.navigation) && requested->navigation) { 2527 return (navigation); 2528 } 2529 } 2530 2531 if (screenSize || o.screenSize) { 2532 // "Better" is based on the sum of the difference between both 2533 // width and height from the requested dimensions. We are 2534 // assuming the invalid configs (with smaller sizes) have 2535 // already been filtered. Note that if a particular dimension 2536 // is unspecified, we will end up with a large value (the 2537 // difference between 0 and the requested dimension), which is 2538 // good since we will prefer a config that has specified a 2539 // size value. 2540 int myDelta = 0, otherDelta = 0; 2541 if (requested->screenWidth) { 2542 myDelta += requested->screenWidth - screenWidth; 2543 otherDelta += requested->screenWidth - o.screenWidth; 2544 } 2545 if (requested->screenHeight) { 2546 myDelta += requested->screenHeight - screenHeight; 2547 otherDelta += requested->screenHeight - o.screenHeight; 2548 } 2549 if (myDelta != otherDelta) { 2550 return myDelta < otherDelta; 2551 } 2552 } 2553 2554 if (version || o.version) { 2555 if ((sdkVersion != o.sdkVersion) && requested->sdkVersion) { 2556 return (sdkVersion > o.sdkVersion); 2557 } 2558 2559 if ((minorVersion != o.minorVersion) && 2560 requested->minorVersion) { 2561 return (minorVersion); 2562 } 2563 } 2564 2565 return false; 2566 } 2567 return isMoreSpecificThan(o); 2568 } 2569 2570 bool ResTable_config::match(const ResTable_config& settings) const { 2571 if (imsi != 0) { 2572 if (mcc != 0 && mcc != settings.mcc) { 2573 return false; 2574 } 2575 if (mnc != 0 && mnc != settings.mnc) { 2576 return false; 2577 } 2578 } 2579 if (locale != 0) { 2580 // Don't consider country and variants when deciding matches. 2581 // (Theoretically, the variant can also affect the script. For 2582 // example, "ar-alalc97" probably implies the Latin script, but since 2583 // CLDR doesn't support getting likely scripts for that, we'll assume 2584 // the variant doesn't change the script.) 2585 // 2586 // If two configs differ only in their country and variant, 2587 // they can be weeded out in the isMoreSpecificThan test. 2588 if (!langsAreEquivalent(language, settings.language)) { 2589 return false; 2590 } 2591 2592 // For backward compatibility and supporting private-use locales, we 2593 // fall back to old behavior if we couldn't determine the script for 2594 // either of the desired locale or the provided locale. But if we could determine 2595 // the scripts, they should be the same for the locales to match. 2596 bool countriesMustMatch = false; 2597 char computed_script[4]; 2598 const char* script; 2599 if (settings.localeScript[0] == '\0') { // could not determine the request's script 2600 countriesMustMatch = true; 2601 } else { 2602 if (localeScript[0] == '\0' && !localeScriptWasComputed) { 2603 // script was not provided or computed, so we try to compute it 2604 localeDataComputeScript(computed_script, language, country); 2605 if (computed_script[0] == '\0') { // we could not compute the script 2606 countriesMustMatch = true; 2607 } else { 2608 script = computed_script; 2609 } 2610 } else { // script was provided, so just use it 2611 script = localeScript; 2612 } 2613 } 2614 2615 if (countriesMustMatch) { 2616 if (country[0] != '\0' && !areIdentical(country, settings.country)) { 2617 return false; 2618 } 2619 } else { 2620 if (memcmp(script, settings.localeScript, sizeof(settings.localeScript)) != 0) { 2621 return false; 2622 } 2623 } 2624 } 2625 2626 if (screenConfig != 0) { 2627 const int layoutDir = screenLayout&MASK_LAYOUTDIR; 2628 const int setLayoutDir = settings.screenLayout&MASK_LAYOUTDIR; 2629 if (layoutDir != 0 && layoutDir != setLayoutDir) { 2630 return false; 2631 } 2632 2633 const int screenSize = screenLayout&MASK_SCREENSIZE; 2634 const int setScreenSize = settings.screenLayout&MASK_SCREENSIZE; 2635 // Any screen sizes for larger screens than the setting do not 2636 // match. 2637 if (screenSize != 0 && screenSize > setScreenSize) { 2638 return false; 2639 } 2640 2641 const int screenLong = screenLayout&MASK_SCREENLONG; 2642 const int setScreenLong = settings.screenLayout&MASK_SCREENLONG; 2643 if (screenLong != 0 && screenLong != setScreenLong) { 2644 return false; 2645 } 2646 2647 const int uiModeType = uiMode&MASK_UI_MODE_TYPE; 2648 const int setUiModeType = settings.uiMode&MASK_UI_MODE_TYPE; 2649 if (uiModeType != 0 && uiModeType != setUiModeType) { 2650 return false; 2651 } 2652 2653 const int uiModeNight = uiMode&MASK_UI_MODE_NIGHT; 2654 const int setUiModeNight = settings.uiMode&MASK_UI_MODE_NIGHT; 2655 if (uiModeNight != 0 && uiModeNight != setUiModeNight) { 2656 return false; 2657 } 2658 2659 if (smallestScreenWidthDp != 0 2660 && smallestScreenWidthDp > settings.smallestScreenWidthDp) { 2661 return false; 2662 } 2663 } 2664 2665 if (screenConfig2 != 0) { 2666 const int screenRound = screenLayout2 & MASK_SCREENROUND; 2667 const int setScreenRound = settings.screenLayout2 & MASK_SCREENROUND; 2668 if (screenRound != 0 && screenRound != setScreenRound) { 2669 return false; 2670 } 2671 2672 const int hdr = colorMode & MASK_HDR; 2673 const int setHdr = settings.colorMode & MASK_HDR; 2674 if (hdr != 0 && hdr != setHdr) { 2675 return false; 2676 } 2677 2678 const int wideColorGamut = colorMode & MASK_WIDE_COLOR_GAMUT; 2679 const int setWideColorGamut = settings.colorMode & MASK_WIDE_COLOR_GAMUT; 2680 if (wideColorGamut != 0 && wideColorGamut != setWideColorGamut) { 2681 return false; 2682 } 2683 } 2684 2685 if (screenSizeDp != 0) { 2686 if (screenWidthDp != 0 && screenWidthDp > settings.screenWidthDp) { 2687 if (kDebugTableSuperNoisy) { 2688 ALOGI("Filtering out width %d in requested %d", screenWidthDp, 2689 settings.screenWidthDp); 2690 } 2691 return false; 2692 } 2693 if (screenHeightDp != 0 && screenHeightDp > settings.screenHeightDp) { 2694 if (kDebugTableSuperNoisy) { 2695 ALOGI("Filtering out height %d in requested %d", screenHeightDp, 2696 settings.screenHeightDp); 2697 } 2698 return false; 2699 } 2700 } 2701 if (screenType != 0) { 2702 if (orientation != 0 && orientation != settings.orientation) { 2703 return false; 2704 } 2705 // density always matches - we can scale it. See isBetterThan 2706 if (touchscreen != 0 && touchscreen != settings.touchscreen) { 2707 return false; 2708 } 2709 } 2710 if (input != 0) { 2711 const int keysHidden = inputFlags&MASK_KEYSHIDDEN; 2712 const int setKeysHidden = settings.inputFlags&MASK_KEYSHIDDEN; 2713 if (keysHidden != 0 && keysHidden != setKeysHidden) { 2714 // For compatibility, we count a request for KEYSHIDDEN_NO as also 2715 // matching the more recent KEYSHIDDEN_SOFT. Basically 2716 // KEYSHIDDEN_NO means there is some kind of keyboard available. 2717 if (kDebugTableSuperNoisy) { 2718 ALOGI("Matching keysHidden: have=%d, config=%d\n", keysHidden, setKeysHidden); 2719 } 2720 if (keysHidden != KEYSHIDDEN_NO || setKeysHidden != KEYSHIDDEN_SOFT) { 2721 if (kDebugTableSuperNoisy) { 2722 ALOGI("No match!"); 2723 } 2724 return false; 2725 } 2726 } 2727 const int navHidden = inputFlags&MASK_NAVHIDDEN; 2728 const int setNavHidden = settings.inputFlags&MASK_NAVHIDDEN; 2729 if (navHidden != 0 && navHidden != setNavHidden) { 2730 return false; 2731 } 2732 if (keyboard != 0 && keyboard != settings.keyboard) { 2733 return false; 2734 } 2735 if (navigation != 0 && navigation != settings.navigation) { 2736 return false; 2737 } 2738 } 2739 if (screenSize != 0) { 2740 if (screenWidth != 0 && screenWidth > settings.screenWidth) { 2741 return false; 2742 } 2743 if (screenHeight != 0 && screenHeight > settings.screenHeight) { 2744 return false; 2745 } 2746 } 2747 if (version != 0) { 2748 if (sdkVersion != 0 && sdkVersion > settings.sdkVersion) { 2749 return false; 2750 } 2751 if (minorVersion != 0 && minorVersion != settings.minorVersion) { 2752 return false; 2753 } 2754 } 2755 return true; 2756 } 2757 2758 void ResTable_config::appendDirLocale(String8& out) const { 2759 if (!language[0]) { 2760 return; 2761 } 2762 const bool scriptWasProvided = localeScript[0] != '\0' && !localeScriptWasComputed; 2763 if (!scriptWasProvided && !localeVariant[0]) { 2764 // Legacy format. 2765 if (out.size() > 0) { 2766 out.append("-"); 2767 } 2768 2769 char buf[4]; 2770 size_t len = unpackLanguage(buf); 2771 out.append(buf, len); 2772 2773 if (country[0]) { 2774 out.append("-r"); 2775 len = unpackRegion(buf); 2776 out.append(buf, len); 2777 } 2778 return; 2779 } 2780 2781 // We are writing the modified BCP 47 tag. 2782 // It starts with 'b+' and uses '+' as a separator. 2783 2784 if (out.size() > 0) { 2785 out.append("-"); 2786 } 2787 out.append("b+"); 2788 2789 char buf[4]; 2790 size_t len = unpackLanguage(buf); 2791 out.append(buf, len); 2792 2793 if (scriptWasProvided) { 2794 out.append("+"); 2795 out.append(localeScript, sizeof(localeScript)); 2796 } 2797 2798 if (country[0]) { 2799 out.append("+"); 2800 len = unpackRegion(buf); 2801 out.append(buf, len); 2802 } 2803 2804 if (localeVariant[0]) { 2805 out.append("+"); 2806 out.append(localeVariant, strnlen(localeVariant, sizeof(localeVariant))); 2807 } 2808 } 2809 2810 void ResTable_config::getBcp47Locale(char str[RESTABLE_MAX_LOCALE_LEN], bool canonicalize) const { 2811 memset(str, 0, RESTABLE_MAX_LOCALE_LEN); 2812 2813 // This represents the "any" locale value, which has traditionally been 2814 // represented by the empty string. 2815 if (language[0] == '\0' && country[0] == '\0') { 2816 return; 2817 } 2818 2819 size_t charsWritten = 0; 2820 if (language[0] != '\0') { 2821 if (canonicalize && areIdentical(language, kTagalog)) { 2822 // Replace Tagalog with Filipino if we are canonicalizing 2823 str[0] = 'f'; str[1] = 'i'; str[2] = 'l'; str[3] = '\0'; // 3-letter code for Filipino 2824 charsWritten += 3; 2825 } else { 2826 charsWritten += unpackLanguage(str); 2827 } 2828 } 2829 2830 if (localeScript[0] != '\0' && !localeScriptWasComputed) { 2831 if (charsWritten > 0) { 2832 str[charsWritten++] = '-'; 2833 } 2834 memcpy(str + charsWritten, localeScript, sizeof(localeScript)); 2835 charsWritten += sizeof(localeScript); 2836 } 2837 2838 if (country[0] != '\0') { 2839 if (charsWritten > 0) { 2840 str[charsWritten++] = '-'; 2841 } 2842 charsWritten += unpackRegion(str + charsWritten); 2843 } 2844 2845 if (localeVariant[0] != '\0') { 2846 if (charsWritten > 0) { 2847 str[charsWritten++] = '-'; 2848 } 2849 memcpy(str + charsWritten, localeVariant, sizeof(localeVariant)); 2850 } 2851 } 2852 2853 /* static */ inline bool assignLocaleComponent(ResTable_config* config, 2854 const char* start, size_t size) { 2855 2856 switch (size) { 2857 case 0: 2858 return false; 2859 case 2: 2860 case 3: 2861 config->language[0] ? config->packRegion(start) : config->packLanguage(start); 2862 break; 2863 case 4: 2864 if ('0' <= start[0] && start[0] <= '9') { 2865 // this is a variant, so fall through 2866 } else { 2867 config->localeScript[0] = toupper(start[0]); 2868 for (size_t i = 1; i < 4; ++i) { 2869 config->localeScript[i] = tolower(start[i]); 2870 } 2871 break; 2872 } 2873 case 5: 2874 case 6: 2875 case 7: 2876 case 8: 2877 for (size_t i = 0; i < size; ++i) { 2878 config->localeVariant[i] = tolower(start[i]); 2879 } 2880 break; 2881 default: 2882 return false; 2883 } 2884 2885 return true; 2886 } 2887 2888 void ResTable_config::setBcp47Locale(const char* in) { 2889 locale = 0; 2890 memset(localeScript, 0, sizeof(localeScript)); 2891 memset(localeVariant, 0, sizeof(localeVariant)); 2892 2893 const char* separator = in; 2894 const char* start = in; 2895 while ((separator = strchr(start, '-')) != NULL) { 2896 const size_t size = separator - start; 2897 if (!assignLocaleComponent(this, start, size)) { 2898 fprintf(stderr, "Invalid BCP-47 locale string: %s", in); 2899 } 2900 2901 start = (separator + 1); 2902 } 2903 2904 const size_t size = in + strlen(in) - start; 2905 assignLocaleComponent(this, start, size); 2906 localeScriptWasComputed = (localeScript[0] == '\0'); 2907 if (localeScriptWasComputed) { 2908 computeScript(); 2909 } 2910 } 2911 2912 String8 ResTable_config::toString() const { 2913 String8 res; 2914 2915 if (mcc != 0) { 2916 if (res.size() > 0) res.append("-"); 2917 res.appendFormat("mcc%d", dtohs(mcc)); 2918 } 2919 if (mnc != 0) { 2920 if (res.size() > 0) res.append("-"); 2921 res.appendFormat("mnc%d", dtohs(mnc)); 2922 } 2923 2924 appendDirLocale(res); 2925 2926 if ((screenLayout&MASK_LAYOUTDIR) != 0) { 2927 if (res.size() > 0) res.append("-"); 2928 switch (screenLayout&ResTable_config::MASK_LAYOUTDIR) { 2929 case ResTable_config::LAYOUTDIR_LTR: 2930 res.append("ldltr"); 2931 break; 2932 case ResTable_config::LAYOUTDIR_RTL: 2933 res.append("ldrtl"); 2934 break; 2935 default: 2936 res.appendFormat("layoutDir=%d", 2937 dtohs(screenLayout&ResTable_config::MASK_LAYOUTDIR)); 2938 break; 2939 } 2940 } 2941 if (smallestScreenWidthDp != 0) { 2942 if (res.size() > 0) res.append("-"); 2943 res.appendFormat("sw%ddp", dtohs(smallestScreenWidthDp)); 2944 } 2945 if (screenWidthDp != 0) { 2946 if (res.size() > 0) res.append("-"); 2947 res.appendFormat("w%ddp", dtohs(screenWidthDp)); 2948 } 2949 if (screenHeightDp != 0) { 2950 if (res.size() > 0) res.append("-"); 2951 res.appendFormat("h%ddp", dtohs(screenHeightDp)); 2952 } 2953 if ((screenLayout&MASK_SCREENSIZE) != SCREENSIZE_ANY) { 2954 if (res.size() > 0) res.append("-"); 2955 switch (screenLayout&ResTable_config::MASK_SCREENSIZE) { 2956 case ResTable_config::SCREENSIZE_SMALL: 2957 res.append("small"); 2958 break; 2959 case ResTable_config::SCREENSIZE_NORMAL: 2960 res.append("normal"); 2961 break; 2962 case ResTable_config::SCREENSIZE_LARGE: 2963 res.append("large"); 2964 break; 2965 case ResTable_config::SCREENSIZE_XLARGE: 2966 res.append("xlarge"); 2967 break; 2968 default: 2969 res.appendFormat("screenLayoutSize=%d", 2970 dtohs(screenLayout&ResTable_config::MASK_SCREENSIZE)); 2971 break; 2972 } 2973 } 2974 if ((screenLayout&MASK_SCREENLONG) != 0) { 2975 if (res.size() > 0) res.append("-"); 2976 switch (screenLayout&ResTable_config::MASK_SCREENLONG) { 2977 case ResTable_config::SCREENLONG_NO: 2978 res.append("notlong"); 2979 break; 2980 case ResTable_config::SCREENLONG_YES: 2981 res.append("long"); 2982 break; 2983 default: 2984 res.appendFormat("screenLayoutLong=%d", 2985 dtohs(screenLayout&ResTable_config::MASK_SCREENLONG)); 2986 break; 2987 } 2988 } 2989 if ((screenLayout2&MASK_SCREENROUND) != 0) { 2990 if (res.size() > 0) res.append("-"); 2991 switch (screenLayout2&MASK_SCREENROUND) { 2992 case SCREENROUND_NO: 2993 res.append("notround"); 2994 break; 2995 case SCREENROUND_YES: 2996 res.append("round"); 2997 break; 2998 default: 2999 res.appendFormat("screenRound=%d", dtohs(screenLayout2&MASK_SCREENROUND)); 3000 break; 3001 } 3002 } 3003 if ((colorMode&MASK_HDR) != 0) { 3004 if (res.size() > 0) res.append("-"); 3005 switch (colorMode&MASK_HDR) { 3006 case ResTable_config::HDR_NO: 3007 res.append("lowdr"); 3008 break; 3009 case ResTable_config::HDR_YES: 3010 res.append("highdr"); 3011 break; 3012 default: 3013 res.appendFormat("hdr=%d", dtohs(colorMode&MASK_HDR)); 3014 break; 3015 } 3016 } 3017 if ((colorMode&MASK_WIDE_COLOR_GAMUT) != 0) { 3018 if (res.size() > 0) res.append("-"); 3019 switch (colorMode&MASK_WIDE_COLOR_GAMUT) { 3020 case ResTable_config::WIDE_COLOR_GAMUT_NO: 3021 res.append("nowidecg"); 3022 break; 3023 case ResTable_config::WIDE_COLOR_GAMUT_YES: 3024 res.append("widecg"); 3025 break; 3026 default: 3027 res.appendFormat("wideColorGamut=%d", dtohs(colorMode&MASK_WIDE_COLOR_GAMUT)); 3028 break; 3029 } 3030 } 3031 if (orientation != ORIENTATION_ANY) { 3032 if (res.size() > 0) res.append("-"); 3033 switch (orientation) { 3034 case ResTable_config::ORIENTATION_PORT: 3035 res.append("port"); 3036 break; 3037 case ResTable_config::ORIENTATION_LAND: 3038 res.append("land"); 3039 break; 3040 case ResTable_config::ORIENTATION_SQUARE: 3041 res.append("square"); 3042 break; 3043 default: 3044 res.appendFormat("orientation=%d", dtohs(orientation)); 3045 break; 3046 } 3047 } 3048 if ((uiMode&MASK_UI_MODE_TYPE) != UI_MODE_TYPE_ANY) { 3049 if (res.size() > 0) res.append("-"); 3050 switch (uiMode&ResTable_config::MASK_UI_MODE_TYPE) { 3051 case ResTable_config::UI_MODE_TYPE_DESK: 3052 res.append("desk"); 3053 break; 3054 case ResTable_config::UI_MODE_TYPE_CAR: 3055 res.append("car"); 3056 break; 3057 case ResTable_config::UI_MODE_TYPE_TELEVISION: 3058 res.append("television"); 3059 break; 3060 case ResTable_config::UI_MODE_TYPE_APPLIANCE: 3061 res.append("appliance"); 3062 break; 3063 case ResTable_config::UI_MODE_TYPE_WATCH: 3064 res.append("watch"); 3065 break; 3066 case ResTable_config::UI_MODE_TYPE_VR_HEADSET: 3067 res.append("vrheadset"); 3068 break; 3069 default: 3070 res.appendFormat("uiModeType=%d", 3071 dtohs(screenLayout&ResTable_config::MASK_UI_MODE_TYPE)); 3072 break; 3073 } 3074 } 3075 if ((uiMode&MASK_UI_MODE_NIGHT) != 0) { 3076 if (res.size() > 0) res.append("-"); 3077 switch (uiMode&ResTable_config::MASK_UI_MODE_NIGHT) { 3078 case ResTable_config::UI_MODE_NIGHT_NO: 3079 res.append("notnight"); 3080 break; 3081 case ResTable_config::UI_MODE_NIGHT_YES: 3082 res.append("night"); 3083 break; 3084 default: 3085 res.appendFormat("uiModeNight=%d", 3086 dtohs(uiMode&MASK_UI_MODE_NIGHT)); 3087 break; 3088 } 3089 } 3090 if (density != DENSITY_DEFAULT) { 3091 if (res.size() > 0) res.append("-"); 3092 switch (density) { 3093 case ResTable_config::DENSITY_LOW: 3094 res.append("ldpi"); 3095 break; 3096 case ResTable_config::DENSITY_MEDIUM: 3097 res.append("mdpi"); 3098 break; 3099 case ResTable_config::DENSITY_TV: 3100 res.append("tvdpi"); 3101 break; 3102 case ResTable_config::DENSITY_HIGH: 3103 res.append("hdpi"); 3104 break; 3105 case ResTable_config::DENSITY_XHIGH: 3106 res.append("xhdpi"); 3107 break; 3108 case ResTable_config::DENSITY_XXHIGH: 3109 res.append("xxhdpi"); 3110 break; 3111 case ResTable_config::DENSITY_XXXHIGH: 3112 res.append("xxxhdpi"); 3113 break; 3114 case ResTable_config::DENSITY_NONE: 3115 res.append("nodpi"); 3116 break; 3117 case ResTable_config::DENSITY_ANY: 3118 res.append("anydpi"); 3119 break; 3120 default: 3121 res.appendFormat("%ddpi", dtohs(density)); 3122 break; 3123 } 3124 } 3125 if (touchscreen != TOUCHSCREEN_ANY) { 3126 if (res.size() > 0) res.append("-"); 3127 switch (touchscreen) { 3128 case ResTable_config::TOUCHSCREEN_NOTOUCH: 3129 res.append("notouch"); 3130 break; 3131 case ResTable_config::TOUCHSCREEN_FINGER: 3132 res.append("finger"); 3133 break; 3134 case ResTable_config::TOUCHSCREEN_STYLUS: 3135 res.append("stylus"); 3136 break; 3137 default: 3138 res.appendFormat("touchscreen=%d", dtohs(touchscreen)); 3139 break; 3140 } 3141 } 3142 if ((inputFlags&MASK_KEYSHIDDEN) != 0) { 3143 if (res.size() > 0) res.append("-"); 3144 switch (inputFlags&MASK_KEYSHIDDEN) { 3145 case ResTable_config::KEYSHIDDEN_NO: 3146 res.append("keysexposed"); 3147 break; 3148 case ResTable_config::KEYSHIDDEN_YES: 3149 res.append("keyshidden"); 3150 break; 3151 case ResTable_config::KEYSHIDDEN_SOFT: 3152 res.append("keyssoft"); 3153 break; 3154 } 3155 } 3156 if (keyboard != KEYBOARD_ANY) { 3157 if (res.size() > 0) res.append("-"); 3158 switch (keyboard) { 3159 case ResTable_config::KEYBOARD_NOKEYS: 3160 res.append("nokeys"); 3161 break; 3162 case ResTable_config::KEYBOARD_QWERTY: 3163 res.append("qwerty"); 3164 break; 3165 case ResTable_config::KEYBOARD_12KEY: 3166 res.append("12key"); 3167 break; 3168 default: 3169 res.appendFormat("keyboard=%d", dtohs(keyboard)); 3170 break; 3171 } 3172 } 3173 if ((inputFlags&MASK_NAVHIDDEN) != 0) { 3174 if (res.size() > 0) res.append("-"); 3175 switch (inputFlags&MASK_NAVHIDDEN) { 3176 case ResTable_config::NAVHIDDEN_NO: 3177 res.append("navexposed"); 3178 break; 3179 case ResTable_config::NAVHIDDEN_YES: 3180 res.append("navhidden"); 3181 break; 3182 default: 3183 res.appendFormat("inputFlagsNavHidden=%d", 3184 dtohs(inputFlags&MASK_NAVHIDDEN)); 3185 break; 3186 } 3187 } 3188 if (navigation != NAVIGATION_ANY) { 3189 if (res.size() > 0) res.append("-"); 3190 switch (navigation) { 3191 case ResTable_config::NAVIGATION_NONAV: 3192 res.append("nonav"); 3193 break; 3194 case ResTable_config::NAVIGATION_DPAD: 3195 res.append("dpad"); 3196 break; 3197 case ResTable_config::NAVIGATION_TRACKBALL: 3198 res.append("trackball"); 3199 break; 3200 case ResTable_config::NAVIGATION_WHEEL: 3201 res.append("wheel"); 3202 break; 3203 default: 3204 res.appendFormat("navigation=%d", dtohs(navigation)); 3205 break; 3206 } 3207 } 3208 if (screenSize != 0) { 3209 if (res.size() > 0) res.append("-"); 3210 res.appendFormat("%dx%d", dtohs(screenWidth), dtohs(screenHeight)); 3211 } 3212 if (version != 0) { 3213 if (res.size() > 0) res.append("-"); 3214 res.appendFormat("v%d", dtohs(sdkVersion)); 3215 if (minorVersion != 0) { 3216 res.appendFormat(".%d", dtohs(minorVersion)); 3217 } 3218 } 3219 3220 return res; 3221 } 3222 3223 // -------------------------------------------------------------------- 3224 // -------------------------------------------------------------------- 3225 // -------------------------------------------------------------------- 3226 3227 struct ResTable::Header 3228 { 3229 explicit Header(ResTable* _owner) : owner(_owner), ownedData(NULL), header(NULL), 3230 resourceIDMap(NULL), resourceIDMapSize(0) { } 3231 3232 ~Header() 3233 { 3234 free(resourceIDMap); 3235 } 3236 3237 const ResTable* const owner; 3238 void* ownedData; 3239 const ResTable_header* header; 3240 size_t size; 3241 const uint8_t* dataEnd; 3242 size_t index; 3243 int32_t cookie; 3244 3245 ResStringPool values; 3246 uint32_t* resourceIDMap; 3247 size_t resourceIDMapSize; 3248 }; 3249 3250 struct ResTable::Entry { 3251 ResTable_config config; 3252 const ResTable_entry* entry; 3253 const ResTable_type* type; 3254 uint32_t specFlags; 3255 const Package* package; 3256 3257 StringPoolRef typeStr; 3258 StringPoolRef keyStr; 3259 }; 3260 3261 struct ResTable::Type 3262 { 3263 Type(const Header* _header, const Package* _package, size_t count) 3264 : header(_header), package(_package), entryCount(count), 3265 typeSpec(NULL), typeSpecFlags(NULL) { } 3266 const Header* const header; 3267 const Package* const package; 3268 const size_t entryCount; 3269 const ResTable_typeSpec* typeSpec; 3270 const uint32_t* typeSpecFlags; 3271 IdmapEntries idmapEntries; 3272 Vector<const ResTable_type*> configs; 3273 }; 3274 3275 struct ResTable::Package 3276 { 3277 Package(ResTable* _owner, const Header* _header, const ResTable_package* _package) 3278 : owner(_owner), header(_header), package(_package), typeIdOffset(0) { 3279 if (dtohs(package->header.headerSize) == sizeof(*package)) { 3280 // The package structure is the same size as the definition. 3281 // This means it contains the typeIdOffset field. 3282 typeIdOffset = package->typeIdOffset; 3283 } 3284 } 3285 3286 const ResTable* const owner; 3287 const Header* const header; 3288 const ResTable_package* const package; 3289 3290 ResStringPool typeStrings; 3291 ResStringPool keyStrings; 3292 3293 size_t typeIdOffset; 3294 }; 3295 3296 // A group of objects describing a particular resource package. 3297 // The first in 'package' is always the root object (from the resource 3298 // table that defined the package); the ones after are skins on top of it. 3299 struct ResTable::PackageGroup 3300 { 3301 PackageGroup( 3302 ResTable* _owner, const String16& _name, uint32_t _id, 3303 bool appAsLib, bool _isSystemAsset) 3304 : owner(_owner) 3305 , name(_name) 3306 , id(_id) 3307 , largestTypeId(0) 3308 , dynamicRefTable(static_cast<uint8_t>(_id), appAsLib) 3309 , isSystemAsset(_isSystemAsset) 3310 { } 3311 3312 ~PackageGroup() { 3313 clearBagCache(); 3314 const size_t numTypes = types.size(); 3315 for (size_t i = 0; i < numTypes; i++) { 3316 TypeList& typeList = types.editItemAt(i); 3317 const size_t numInnerTypes = typeList.size(); 3318 for (size_t j = 0; j < numInnerTypes; j++) { 3319 if (typeList[j]->package->owner == owner) { 3320 delete typeList[j]; 3321 } 3322 } 3323 typeList.clear(); 3324 } 3325 3326 const size_t N = packages.size(); 3327 for (size_t i=0; i<N; i++) { 3328 Package* pkg = packages[i]; 3329 if (pkg->owner == owner) { 3330 delete pkg; 3331 } 3332 } 3333 } 3334 3335 /** 3336 * Clear all cache related data that depends on parameters/configuration. 3337 * This includes the bag caches and filtered types. 3338 */ 3339 void clearBagCache() { 3340 for (size_t i = 0; i < typeCacheEntries.size(); i++) { 3341 if (kDebugTableNoisy) { 3342 printf("type=%zu\n", i); 3343 } 3344 const TypeList& typeList = types[i]; 3345 if (!typeList.isEmpty()) { 3346 TypeCacheEntry& cacheEntry = typeCacheEntries.editItemAt(i); 3347 3348 // Reset the filtered configurations. 3349 cacheEntry.filteredConfigs.clear(); 3350 3351 bag_set** typeBags = cacheEntry.cachedBags; 3352 if (kDebugTableNoisy) { 3353 printf("typeBags=%p\n", typeBags); 3354 } 3355 3356 if (typeBags) { 3357 const size_t N = typeList[0]->entryCount; 3358 if (kDebugTableNoisy) { 3359 printf("type->entryCount=%zu\n", N); 3360 } 3361 for (size_t j = 0; j < N; j++) { 3362 if (typeBags[j] && typeBags[j] != (bag_set*)0xFFFFFFFF) { 3363 free(typeBags[j]); 3364 } 3365 } 3366 free(typeBags); 3367 cacheEntry.cachedBags = NULL; 3368 } 3369 } 3370 } 3371 } 3372 3373 ssize_t findType16(const char16_t* type, size_t len) const { 3374 const size_t N = packages.size(); 3375 for (size_t i = 0; i < N; i++) { 3376 ssize_t index = packages[i]->typeStrings.indexOfString(type, len); 3377 if (index >= 0) { 3378 return index + packages[i]->typeIdOffset; 3379 } 3380 } 3381 return -1; 3382 } 3383 3384 const ResTable* const owner; 3385 String16 const name; 3386 uint32_t const id; 3387 3388 // This is mainly used to keep track of the loaded packages 3389 // and to clean them up properly. Accessing resources happens from 3390 // the 'types' array. 3391 Vector<Package*> packages; 3392 3393 ByteBucketArray<TypeList> types; 3394 3395 uint8_t largestTypeId; 3396 3397 // Cached objects dependent on the parameters/configuration of this ResTable. 3398 // Gets cleared whenever the parameters/configuration changes. 3399 // These are stored here in a parallel structure because the data in `types` may 3400 // be shared by other ResTable's (framework resources are shared this way). 3401 ByteBucketArray<TypeCacheEntry> typeCacheEntries; 3402 3403 // The table mapping dynamic references to resolved references for 3404 // this package group. 3405 // TODO: We may be able to support dynamic references in overlays 3406 // by having these tables in a per-package scope rather than 3407 // per-package-group. 3408 DynamicRefTable dynamicRefTable; 3409 3410 // If the package group comes from a system asset. Used in 3411 // determining non-system locales. 3412 const bool isSystemAsset; 3413 }; 3414 3415 ResTable::Theme::Theme(const ResTable& table) 3416 : mTable(table) 3417 , mTypeSpecFlags(0) 3418 { 3419 memset(mPackages, 0, sizeof(mPackages)); 3420 } 3421 3422 ResTable::Theme::~Theme() 3423 { 3424 for (size_t i=0; i<Res_MAXPACKAGE; i++) { 3425 package_info* pi = mPackages[i]; 3426 if (pi != NULL) { 3427 free_package(pi); 3428 } 3429 } 3430 } 3431 3432 void ResTable::Theme::free_package(package_info* pi) 3433 { 3434 for (size_t j = 0; j <= Res_MAXTYPE; j++) { 3435 theme_entry* te = pi->types[j].entries; 3436 if (te != NULL) { 3437 free(te); 3438 } 3439 } 3440 free(pi); 3441 } 3442 3443 ResTable::Theme::package_info* ResTable::Theme::copy_package(package_info* pi) 3444 { 3445 package_info* newpi = (package_info*)malloc(sizeof(package_info)); 3446 for (size_t j = 0; j <= Res_MAXTYPE; j++) { 3447 size_t cnt = pi->types[j].numEntries; 3448 newpi->types[j].numEntries = cnt; 3449 theme_entry* te = pi->types[j].entries; 3450 size_t cnt_max = SIZE_MAX / sizeof(theme_entry); 3451 if (te != NULL && (cnt < 0xFFFFFFFF-1) && (cnt < cnt_max)) { 3452 theme_entry* newte = (theme_entry*)malloc(cnt*sizeof(theme_entry)); 3453 newpi->types[j].entries = newte; 3454 memcpy(newte, te, cnt*sizeof(theme_entry)); 3455 } else { 3456 newpi->types[j].entries = NULL; 3457 } 3458 } 3459 return newpi; 3460 } 3461 3462 status_t ResTable::Theme::applyStyle(uint32_t resID, bool force) 3463 { 3464 const bag_entry* bag; 3465 uint32_t bagTypeSpecFlags = 0; 3466 mTable.lock(); 3467 const ssize_t N = mTable.getBagLocked(resID, &bag, &bagTypeSpecFlags); 3468 if (kDebugTableNoisy) { 3469 ALOGV("Applying style 0x%08x to theme %p, count=%zu", resID, this, N); 3470 } 3471 if (N < 0) { 3472 mTable.unlock(); 3473 return N; 3474 } 3475 3476 mTypeSpecFlags |= bagTypeSpecFlags; 3477 3478 uint32_t curPackage = 0xffffffff; 3479 ssize_t curPackageIndex = 0; 3480 package_info* curPI = NULL; 3481 uint32_t curType = 0xffffffff; 3482 size_t numEntries = 0; 3483 theme_entry* curEntries = NULL; 3484 3485 const bag_entry* end = bag + N; 3486 while (bag < end) { 3487 const uint32_t attrRes = bag->map.name.ident; 3488 const uint32_t p = Res_GETPACKAGE(attrRes); 3489 const uint32_t t = Res_GETTYPE(attrRes); 3490 const uint32_t e = Res_GETENTRY(attrRes); 3491 3492 if (curPackage != p) { 3493 const ssize_t pidx = mTable.getResourcePackageIndex(attrRes); 3494 if (pidx < 0) { 3495 ALOGE("Style contains key with bad package: 0x%08x\n", attrRes); 3496 bag++; 3497 continue; 3498 } 3499 curPackage = p; 3500 curPackageIndex = pidx; 3501 curPI = mPackages[pidx]; 3502 if (curPI == NULL) { 3503 curPI = (package_info*)malloc(sizeof(package_info)); 3504 memset(curPI, 0, sizeof(*curPI)); 3505 mPackages[pidx] = curPI; 3506 } 3507 curType = 0xffffffff; 3508 } 3509 if (curType != t) { 3510 if (t > Res_MAXTYPE) { 3511 ALOGE("Style contains key with bad type: 0x%08x\n", attrRes); 3512 bag++; 3513 continue; 3514 } 3515 curType = t; 3516 curEntries = curPI->types[t].entries; 3517 if (curEntries == NULL) { 3518 PackageGroup* const grp = mTable.mPackageGroups[curPackageIndex]; 3519 const TypeList& typeList = grp->types[t]; 3520 size_t cnt = typeList.isEmpty() ? 0 : typeList[0]->entryCount; 3521 size_t cnt_max = SIZE_MAX / sizeof(theme_entry); 3522 size_t buff_size = (cnt < cnt_max && cnt < 0xFFFFFFFF-1) ? 3523 cnt*sizeof(theme_entry) : 0; 3524 curEntries = (theme_entry*)malloc(buff_size); 3525 memset(curEntries, Res_value::TYPE_NULL, buff_size); 3526 curPI->types[t].numEntries = cnt; 3527 curPI->types[t].entries = curEntries; 3528 } 3529 numEntries = curPI->types[t].numEntries; 3530 } 3531 if (e >= numEntries) { 3532 ALOGE("Style contains key with bad entry: 0x%08x\n", attrRes); 3533 bag++; 3534 continue; 3535 } 3536 theme_entry* curEntry = curEntries + e; 3537 if (kDebugTableNoisy) { 3538 ALOGV("Attr 0x%08x: type=0x%x, data=0x%08x; curType=0x%x", 3539 attrRes, bag->map.value.dataType, bag->map.value.data, 3540 curEntry->value.dataType); 3541 } 3542 if (force || (curEntry->value.dataType == Res_value::TYPE_NULL 3543 && curEntry->value.data != Res_value::DATA_NULL_EMPTY)) { 3544 curEntry->stringBlock = bag->stringBlock; 3545 curEntry->typeSpecFlags |= bagTypeSpecFlags; 3546 curEntry->value = bag->map.value; 3547 } 3548 3549 bag++; 3550 } 3551 3552 mTable.unlock(); 3553 3554 if (kDebugTableTheme) { 3555 ALOGI("Applying style 0x%08x (force=%d) theme %p...\n", resID, force, this); 3556 dumpToLog(); 3557 } 3558 3559 return NO_ERROR; 3560 } 3561 3562 status_t ResTable::Theme::setTo(const Theme& other) 3563 { 3564 if (kDebugTableTheme) { 3565 ALOGI("Setting theme %p from theme %p...\n", this, &other); 3566 dumpToLog(); 3567 other.dumpToLog(); 3568 } 3569 3570 if (&mTable == &other.mTable) { 3571 for (size_t i=0; i<Res_MAXPACKAGE; i++) { 3572 if (mPackages[i] != NULL) { 3573 free_package(mPackages[i]); 3574 } 3575 if (other.mPackages[i] != NULL) { 3576 mPackages[i] = copy_package(other.mPackages[i]); 3577 } else { 3578 mPackages[i] = NULL; 3579 } 3580 } 3581 } else { 3582 // @todo: need to really implement this, not just copy 3583 // the system package (which is still wrong because it isn't 3584 // fixing up resource references). 3585 for (size_t i=0; i<Res_MAXPACKAGE; i++) { 3586 if (mPackages[i] != NULL) { 3587 free_package(mPackages[i]); 3588 } 3589 if (i == 0 && other.mPackages[i] != NULL) { 3590 mPackages[i] = copy_package(other.mPackages[i]); 3591 } else { 3592 mPackages[i] = NULL; 3593 } 3594 } 3595 } 3596 3597 mTypeSpecFlags = other.mTypeSpecFlags; 3598 3599 if (kDebugTableTheme) { 3600 ALOGI("Final theme:"); 3601 dumpToLog(); 3602 } 3603 3604 return NO_ERROR; 3605 } 3606 3607 status_t ResTable::Theme::clear() 3608 { 3609 if (kDebugTableTheme) { 3610 ALOGI("Clearing theme %p...\n", this); 3611 dumpToLog(); 3612 } 3613 3614 for (size_t i = 0; i < Res_MAXPACKAGE; i++) { 3615 if (mPackages[i] != NULL) { 3616 free_package(mPackages[i]); 3617 mPackages[i] = NULL; 3618 } 3619 } 3620 3621 mTypeSpecFlags = 0; 3622 3623 if (kDebugTableTheme) { 3624 ALOGI("Final theme:"); 3625 dumpToLog(); 3626 } 3627 3628 return NO_ERROR; 3629 } 3630 3631 ssize_t ResTable::Theme::getAttribute(uint32_t resID, Res_value* outValue, 3632 uint32_t* outTypeSpecFlags) const 3633 { 3634 int cnt = 20; 3635 3636 if (outTypeSpecFlags != NULL) *outTypeSpecFlags = 0; 3637 3638 do { 3639 const ssize_t p = mTable.getResourcePackageIndex(resID); 3640 const uint32_t t = Res_GETTYPE(resID); 3641 const uint32_t e = Res_GETENTRY(resID); 3642 3643 if (kDebugTableTheme) { 3644 ALOGI("Looking up attr 0x%08x in theme %p", resID, this); 3645 } 3646 3647 if (p >= 0) { 3648 const package_info* const pi = mPackages[p]; 3649 if (kDebugTableTheme) { 3650 ALOGI("Found package: %p", pi); 3651 } 3652 if (pi != NULL) { 3653 if (kDebugTableTheme) { 3654 ALOGI("Desired type index is %u in avail %zu", t, Res_MAXTYPE + 1); 3655 } 3656 if (t <= Res_MAXTYPE) { 3657 const type_info& ti = pi->types[t]; 3658 if (kDebugTableTheme) { 3659 ALOGI("Desired entry index is %u in avail %zu", e, ti.numEntries); 3660 } 3661 if (e < ti.numEntries) { 3662 const theme_entry& te = ti.entries[e]; 3663 if (outTypeSpecFlags != NULL) { 3664 *outTypeSpecFlags |= te.typeSpecFlags; 3665 } 3666 if (kDebugTableTheme) { 3667 ALOGI("Theme value: type=0x%x, data=0x%08x", 3668 te.value.dataType, te.value.data); 3669 } 3670 const uint8_t type = te.value.dataType; 3671 if (type == Res_value::TYPE_ATTRIBUTE) { 3672 if (cnt > 0) { 3673 cnt--; 3674 resID = te.value.data; 3675 continue; 3676 } 3677 ALOGW("Too many attribute references, stopped at: 0x%08x\n", resID); 3678 return BAD_INDEX; 3679 } else if (type != Res_value::TYPE_NULL 3680 || te.value.data == Res_value::DATA_NULL_EMPTY) { 3681 *outValue = te.value; 3682 return te.stringBlock; 3683 } 3684 return BAD_INDEX; 3685 } 3686 } 3687 } 3688 } 3689 break; 3690 3691 } while (true); 3692 3693 return BAD_INDEX; 3694 } 3695 3696 ssize_t ResTable::Theme::resolveAttributeReference(Res_value* inOutValue, 3697 ssize_t blockIndex, uint32_t* outLastRef, 3698 uint32_t* inoutTypeSpecFlags, ResTable_config* inoutConfig) const 3699 { 3700 //printf("Resolving type=0x%x\n", inOutValue->dataType); 3701 if (inOutValue->dataType == Res_value::TYPE_ATTRIBUTE) { 3702 uint32_t newTypeSpecFlags; 3703 blockIndex = getAttribute(inOutValue->data, inOutValue, &newTypeSpecFlags); 3704 if (kDebugTableTheme) { 3705 ALOGI("Resolving attr reference: blockIndex=%d, type=0x%x, data=0x%x\n", 3706 (int)blockIndex, (int)inOutValue->dataType, inOutValue->data); 3707 } 3708 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newTypeSpecFlags; 3709 //printf("Retrieved attribute new type=0x%x\n", inOutValue->dataType); 3710 if (blockIndex < 0) { 3711 return blockIndex; 3712 } 3713 } 3714 return mTable.resolveReference(inOutValue, blockIndex, outLastRef, 3715 inoutTypeSpecFlags, inoutConfig); 3716 } 3717 3718 uint32_t ResTable::Theme::getChangingConfigurations() const 3719 { 3720 return mTypeSpecFlags; 3721 } 3722 3723 void ResTable::Theme::dumpToLog() const 3724 { 3725 ALOGI("Theme %p:\n", this); 3726 for (size_t i=0; i<Res_MAXPACKAGE; i++) { 3727 package_info* pi = mPackages[i]; 3728 if (pi == NULL) continue; 3729 3730 ALOGI(" Package #0x%02x:\n", (int)(i + 1)); 3731 for (size_t j = 0; j <= Res_MAXTYPE; j++) { 3732 type_info& ti = pi->types[j]; 3733 if (ti.numEntries == 0) continue; 3734 ALOGI(" Type #0x%02x:\n", (int)(j + 1)); 3735 for (size_t k = 0; k < ti.numEntries; k++) { 3736 const theme_entry& te = ti.entries[k]; 3737 if (te.value.dataType == Res_value::TYPE_NULL) continue; 3738 ALOGI(" 0x%08x: t=0x%x, d=0x%08x (block=%d)\n", 3739 (int)Res_MAKEID(i, j, k), 3740 te.value.dataType, (int)te.value.data, (int)te.stringBlock); 3741 } 3742 } 3743 } 3744 } 3745 3746 ResTable::ResTable() 3747 : mError(NO_INIT), mNextPackageId(2) 3748 { 3749 memset(&mParams, 0, sizeof(mParams)); 3750 memset(mPackageMap, 0, sizeof(mPackageMap)); 3751 if (kDebugTableSuperNoisy) { 3752 ALOGI("Creating ResTable %p\n", this); 3753 } 3754 } 3755 3756 ResTable::ResTable(const void* data, size_t size, const int32_t cookie, bool copyData) 3757 : mError(NO_INIT), mNextPackageId(2) 3758 { 3759 memset(&mParams, 0, sizeof(mParams)); 3760 memset(mPackageMap, 0, sizeof(mPackageMap)); 3761 addInternal(data, size, NULL, 0, false, cookie, copyData); 3762 LOG_FATAL_IF(mError != NO_ERROR, "Error parsing resource table"); 3763 if (kDebugTableSuperNoisy) { 3764 ALOGI("Creating ResTable %p\n", this); 3765 } 3766 } 3767 3768 ResTable::~ResTable() 3769 { 3770 if (kDebugTableSuperNoisy) { 3771 ALOGI("Destroying ResTable in %p\n", this); 3772 } 3773 uninit(); 3774 } 3775 3776 inline ssize_t ResTable::getResourcePackageIndex(uint32_t resID) const 3777 { 3778 return ((ssize_t)mPackageMap[Res_GETPACKAGE(resID)+1])-1; 3779 } 3780 3781 status_t ResTable::add(const void* data, size_t size, const int32_t cookie, bool copyData) { 3782 return addInternal(data, size, NULL, 0, false, cookie, copyData); 3783 } 3784 3785 status_t ResTable::add(const void* data, size_t size, const void* idmapData, size_t idmapDataSize, 3786 const int32_t cookie, bool copyData, bool appAsLib) { 3787 return addInternal(data, size, idmapData, idmapDataSize, appAsLib, cookie, copyData); 3788 } 3789 3790 status_t ResTable::add(Asset* asset, const int32_t cookie, bool copyData) { 3791 const void* data = asset->getBuffer(true); 3792 if (data == NULL) { 3793 ALOGW("Unable to get buffer of resource asset file"); 3794 return UNKNOWN_ERROR; 3795 } 3796 3797 return addInternal(data, static_cast<size_t>(asset->getLength()), NULL, false, 0, cookie, 3798 copyData); 3799 } 3800 3801 status_t ResTable::add( 3802 Asset* asset, Asset* idmapAsset, const int32_t cookie, bool copyData, 3803 bool appAsLib, bool isSystemAsset) { 3804 const void* data = asset->getBuffer(true); 3805 if (data == NULL) { 3806 ALOGW("Unable to get buffer of resource asset file"); 3807 return UNKNOWN_ERROR; 3808 } 3809 3810 size_t idmapSize = 0; 3811 const void* idmapData = NULL; 3812 if (idmapAsset != NULL) { 3813 idmapData = idmapAsset->getBuffer(true); 3814 if (idmapData == NULL) { 3815 ALOGW("Unable to get buffer of idmap asset file"); 3816 return UNKNOWN_ERROR; 3817 } 3818 idmapSize = static_cast<size_t>(idmapAsset->getLength()); 3819 } 3820 3821 return addInternal(data, static_cast<size_t>(asset->getLength()), 3822 idmapData, idmapSize, appAsLib, cookie, copyData, isSystemAsset); 3823 } 3824 3825 status_t ResTable::add(ResTable* src, bool isSystemAsset) 3826 { 3827 mError = src->mError; 3828 3829 for (size_t i=0; i < src->mHeaders.size(); i++) { 3830 mHeaders.add(src->mHeaders[i]); 3831 } 3832 3833 for (size_t i=0; i < src->mPackageGroups.size(); i++) { 3834 PackageGroup* srcPg = src->mPackageGroups[i]; 3835 PackageGroup* pg = new PackageGroup(this, srcPg->name, srcPg->id, 3836 false /* appAsLib */, isSystemAsset || srcPg->isSystemAsset); 3837 for (size_t j=0; j<srcPg->packages.size(); j++) { 3838 pg->packages.add(srcPg->packages[j]); 3839 } 3840 3841 for (size_t j = 0; j < srcPg->types.size(); j++) { 3842 if (srcPg->types[j].isEmpty()) { 3843 continue; 3844 } 3845 3846 TypeList& typeList = pg->types.editItemAt(j); 3847 typeList.appendVector(srcPg->types[j]); 3848 } 3849 pg->dynamicRefTable.addMappings(srcPg->dynamicRefTable); 3850 pg->largestTypeId = max(pg->largestTypeId, srcPg->largestTypeId); 3851 mPackageGroups.add(pg); 3852 } 3853 3854 memcpy(mPackageMap, src->mPackageMap, sizeof(mPackageMap)); 3855 3856 return mError; 3857 } 3858 3859 status_t ResTable::addEmpty(const int32_t cookie) { 3860 Header* header = new Header(this); 3861 header->index = mHeaders.size(); 3862 header->cookie = cookie; 3863 header->values.setToEmpty(); 3864 header->ownedData = calloc(1, sizeof(ResTable_header)); 3865 3866 ResTable_header* resHeader = (ResTable_header*) header->ownedData; 3867 resHeader->header.type = RES_TABLE_TYPE; 3868 resHeader->header.headerSize = sizeof(ResTable_header); 3869 resHeader->header.size = sizeof(ResTable_header); 3870 3871 header->header = (const ResTable_header*) resHeader; 3872 mHeaders.add(header); 3873 return (mError=NO_ERROR); 3874 } 3875 3876 status_t ResTable::addInternal(const void* data, size_t dataSize, const void* idmapData, size_t idmapDataSize, 3877 bool appAsLib, const int32_t cookie, bool copyData, bool isSystemAsset) 3878 { 3879 if (!data) { 3880 return NO_ERROR; 3881 } 3882 3883 if (dataSize < sizeof(ResTable_header)) { 3884 ALOGE("Invalid data. Size(%d) is smaller than a ResTable_header(%d).", 3885 (int) dataSize, (int) sizeof(ResTable_header)); 3886 return UNKNOWN_ERROR; 3887 } 3888 3889 Header* header = new Header(this); 3890 header->index = mHeaders.size(); 3891 header->cookie = cookie; 3892 if (idmapData != NULL) { 3893 header->resourceIDMap = (uint32_t*) malloc(idmapDataSize); 3894 if (header->resourceIDMap == NULL) { 3895 delete header; 3896 return (mError = NO_MEMORY); 3897 } 3898 memcpy(header->resourceIDMap, idmapData, idmapDataSize); 3899 header->resourceIDMapSize = idmapDataSize; 3900 } 3901 mHeaders.add(header); 3902 3903 const bool notDeviceEndian = htods(0xf0) != 0xf0; 3904 3905 if (kDebugLoadTableNoisy) { 3906 ALOGV("Adding resources to ResTable: data=%p, size=%zu, cookie=%d, copy=%d " 3907 "idmap=%p\n", data, dataSize, cookie, copyData, idmapData); 3908 } 3909 3910 if (copyData || notDeviceEndian) { 3911 header->ownedData = malloc(dataSize); 3912 if (header->ownedData == NULL) { 3913 return (mError=NO_MEMORY); 3914 } 3915 memcpy(header->ownedData, data, dataSize); 3916 data = header->ownedData; 3917 } 3918 3919 header->header = (const ResTable_header*)data; 3920 header->size = dtohl(header->header->header.size); 3921 if (kDebugLoadTableSuperNoisy) { 3922 ALOGI("Got size %zu, again size 0x%x, raw size 0x%x\n", header->size, 3923 dtohl(header->header->header.size), header->header->header.size); 3924 } 3925 if (kDebugLoadTableNoisy) { 3926 ALOGV("Loading ResTable @%p:\n", header->header); 3927 } 3928 if (dtohs(header->header->header.headerSize) > header->size 3929 || header->size > dataSize) { 3930 ALOGW("Bad resource table: header size 0x%x or total size 0x%x is larger than data size 0x%x\n", 3931 (int)dtohs(header->header->header.headerSize), 3932 (int)header->size, (int)dataSize); 3933 return (mError=BAD_TYPE); 3934 } 3935 if (((dtohs(header->header->header.headerSize)|header->size)&0x3) != 0) { 3936 ALOGW("Bad resource table: header size 0x%x or total size 0x%x is not on an integer boundary\n", 3937 (int)dtohs(header->header->header.headerSize), 3938 (int)header->size); 3939 return (mError=BAD_TYPE); 3940 } 3941 header->dataEnd = ((const uint8_t*)header->header) + header->size; 3942 3943 // Iterate through all chunks. 3944 size_t curPackage = 0; 3945 3946 const ResChunk_header* chunk = 3947 (const ResChunk_header*)(((const uint8_t*)header->header) 3948 + dtohs(header->header->header.headerSize)); 3949 while (((const uint8_t*)chunk) <= (header->dataEnd-sizeof(ResChunk_header)) && 3950 ((const uint8_t*)chunk) <= (header->dataEnd-dtohl(chunk->size))) { 3951 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), header->dataEnd, "ResTable"); 3952 if (err != NO_ERROR) { 3953 return (mError=err); 3954 } 3955 if (kDebugTableNoisy) { 3956 ALOGV("Chunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n", 3957 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size), 3958 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header))); 3959 } 3960 const size_t csize = dtohl(chunk->size); 3961 const uint16_t ctype = dtohs(chunk->type); 3962 if (ctype == RES_STRING_POOL_TYPE) { 3963 if (header->values.getError() != NO_ERROR) { 3964 // Only use the first string chunk; ignore any others that 3965 // may appear. 3966 status_t err = header->values.setTo(chunk, csize); 3967 if (err != NO_ERROR) { 3968 return (mError=err); 3969 } 3970 } else { 3971 ALOGW("Multiple string chunks found in resource table."); 3972 } 3973 } else if (ctype == RES_TABLE_PACKAGE_TYPE) { 3974 if (curPackage >= dtohl(header->header->packageCount)) { 3975 ALOGW("More package chunks were found than the %d declared in the header.", 3976 dtohl(header->header->packageCount)); 3977 return (mError=BAD_TYPE); 3978 } 3979 3980 if (parsePackage( 3981 (ResTable_package*)chunk, header, appAsLib, isSystemAsset) != NO_ERROR) { 3982 return mError; 3983 } 3984 curPackage++; 3985 } else { 3986 ALOGW("Unknown chunk type 0x%x in table at %p.\n", 3987 ctype, 3988 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header))); 3989 } 3990 chunk = (const ResChunk_header*) 3991 (((const uint8_t*)chunk) + csize); 3992 } 3993 3994 if (curPackage < dtohl(header->header->packageCount)) { 3995 ALOGW("Fewer package chunks (%d) were found than the %d declared in the header.", 3996 (int)curPackage, dtohl(header->header->packageCount)); 3997 return (mError=BAD_TYPE); 3998 } 3999 mError = header->values.getError(); 4000 if (mError != NO_ERROR) { 4001 ALOGW("No string values found in resource table!"); 4002 } 4003 4004 if (kDebugTableNoisy) { 4005 ALOGV("Returning from add with mError=%d\n", mError); 4006 } 4007 return mError; 4008 } 4009 4010 status_t ResTable::getError() const 4011 { 4012 return mError; 4013 } 4014 4015 void ResTable::uninit() 4016 { 4017 mError = NO_INIT; 4018 size_t N = mPackageGroups.size(); 4019 for (size_t i=0; i<N; i++) { 4020 PackageGroup* g = mPackageGroups[i]; 4021 delete g; 4022 } 4023 N = mHeaders.size(); 4024 for (size_t i=0; i<N; i++) { 4025 Header* header = mHeaders[i]; 4026 if (header->owner == this) { 4027 if (header->ownedData) { 4028 free(header->ownedData); 4029 } 4030 delete header; 4031 } 4032 } 4033 4034 mPackageGroups.clear(); 4035 mHeaders.clear(); 4036 } 4037 4038 bool ResTable::getResourceName(uint32_t resID, bool allowUtf8, resource_name* outName) const 4039 { 4040 if (mError != NO_ERROR) { 4041 return false; 4042 } 4043 4044 const ssize_t p = getResourcePackageIndex(resID); 4045 const int t = Res_GETTYPE(resID); 4046 const int e = Res_GETENTRY(resID); 4047 4048 if (p < 0) { 4049 if (Res_GETPACKAGE(resID)+1 == 0) { 4050 ALOGW("No package identifier when getting name for resource number 0x%08x", resID); 4051 } else { 4052 #ifndef STATIC_ANDROIDFW_FOR_TOOLS 4053 ALOGW("No known package when getting name for resource number 0x%08x", resID); 4054 #endif 4055 } 4056 return false; 4057 } 4058 if (t < 0) { 4059 ALOGW("No type identifier when getting name for resource number 0x%08x", resID); 4060 return false; 4061 } 4062 4063 const PackageGroup* const grp = mPackageGroups[p]; 4064 if (grp == NULL) { 4065 ALOGW("Bad identifier when getting name for resource number 0x%08x", resID); 4066 return false; 4067 } 4068 4069 Entry entry; 4070 status_t err = getEntry(grp, t, e, NULL, &entry); 4071 if (err != NO_ERROR) { 4072 return false; 4073 } 4074 4075 outName->package = grp->name.string(); 4076 outName->packageLen = grp->name.size(); 4077 if (allowUtf8) { 4078 outName->type8 = entry.typeStr.string8(&outName->typeLen); 4079 outName->name8 = entry.keyStr.string8(&outName->nameLen); 4080 } else { 4081 outName->type8 = NULL; 4082 outName->name8 = NULL; 4083 } 4084 if (outName->type8 == NULL) { 4085 outName->type = entry.typeStr.string16(&outName->typeLen); 4086 // If we have a bad index for some reason, we should abort. 4087 if (outName->type == NULL) { 4088 return false; 4089 } 4090 } 4091 if (outName->name8 == NULL) { 4092 outName->name = entry.keyStr.string16(&outName->nameLen); 4093 // If we have a bad index for some reason, we should abort. 4094 if (outName->name == NULL) { 4095 return false; 4096 } 4097 } 4098 4099 return true; 4100 } 4101 4102 ssize_t ResTable::getResource(uint32_t resID, Res_value* outValue, bool mayBeBag, uint16_t density, 4103 uint32_t* outSpecFlags, ResTable_config* outConfig) const 4104 { 4105 if (mError != NO_ERROR) { 4106 return mError; 4107 } 4108 4109 const ssize_t p = getResourcePackageIndex(resID); 4110 const int t = Res_GETTYPE(resID); 4111 const int e = Res_GETENTRY(resID); 4112 4113 if (p < 0) { 4114 if (Res_GETPACKAGE(resID)+1 == 0) { 4115 ALOGW("No package identifier when getting value for resource number 0x%08x", resID); 4116 } else { 4117 ALOGW("No known package when getting value for resource number 0x%08x", resID); 4118 } 4119 return BAD_INDEX; 4120 } 4121 if (t < 0) { 4122 ALOGW("No type identifier when getting value for resource number 0x%08x", resID); 4123 return BAD_INDEX; 4124 } 4125 4126 const PackageGroup* const grp = mPackageGroups[p]; 4127 if (grp == NULL) { 4128 ALOGW("Bad identifier when getting value for resource number 0x%08x", resID); 4129 return BAD_INDEX; 4130 } 4131 4132 // Allow overriding density 4133 ResTable_config desiredConfig = mParams; 4134 if (density > 0) { 4135 desiredConfig.density = density; 4136 } 4137 4138 Entry entry; 4139 status_t err = getEntry(grp, t, e, &desiredConfig, &entry); 4140 if (err != NO_ERROR) { 4141 // Only log the failure when we're not running on the host as 4142 // part of a tool. The caller will do its own logging. 4143 #ifndef STATIC_ANDROIDFW_FOR_TOOLS 4144 ALOGW("Failure getting entry for 0x%08x (t=%d e=%d) (error %d)\n", 4145 resID, t, e, err); 4146 #endif 4147 return err; 4148 } 4149 4150 if ((dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) != 0) { 4151 if (!mayBeBag) { 4152 ALOGW("Requesting resource 0x%08x failed because it is complex\n", resID); 4153 } 4154 return BAD_VALUE; 4155 } 4156 4157 const Res_value* value = reinterpret_cast<const Res_value*>( 4158 reinterpret_cast<const uint8_t*>(entry.entry) + entry.entry->size); 4159 4160 outValue->size = dtohs(value->size); 4161 outValue->res0 = value->res0; 4162 outValue->dataType = value->dataType; 4163 outValue->data = dtohl(value->data); 4164 4165 // The reference may be pointing to a resource in a shared library. These 4166 // references have build-time generated package IDs. These ids may not match 4167 // the actual package IDs of the corresponding packages in this ResTable. 4168 // We need to fix the package ID based on a mapping. 4169 if (grp->dynamicRefTable.lookupResourceValue(outValue) != NO_ERROR) { 4170 ALOGW("Failed to resolve referenced package: 0x%08x", outValue->data); 4171 return BAD_VALUE; 4172 } 4173 4174 if (kDebugTableNoisy) { 4175 size_t len; 4176 printf("Found value: pkg=%zu, type=%d, str=%s, int=%d\n", 4177 entry.package->header->index, 4178 outValue->dataType, 4179 outValue->dataType == Res_value::TYPE_STRING ? 4180 String8(entry.package->header->values.stringAt(outValue->data, &len)).string() : 4181 "", 4182 outValue->data); 4183 } 4184 4185 if (outSpecFlags != NULL) { 4186 *outSpecFlags = entry.specFlags; 4187 } 4188 4189 if (outConfig != NULL) { 4190 *outConfig = entry.config; 4191 } 4192 4193 return entry.package->header->index; 4194 } 4195 4196 ssize_t ResTable::resolveReference(Res_value* value, ssize_t blockIndex, 4197 uint32_t* outLastRef, uint32_t* inoutTypeSpecFlags, 4198 ResTable_config* outConfig) const 4199 { 4200 int count=0; 4201 while (blockIndex >= 0 && value->dataType == Res_value::TYPE_REFERENCE 4202 && value->data != 0 && count < 20) { 4203 if (outLastRef) *outLastRef = value->data; 4204 uint32_t newFlags = 0; 4205 const ssize_t newIndex = getResource(value->data, value, true, 0, &newFlags, 4206 outConfig); 4207 if (newIndex == BAD_INDEX) { 4208 return BAD_INDEX; 4209 } 4210 if (kDebugTableTheme) { 4211 ALOGI("Resolving reference 0x%x: newIndex=%d, type=0x%x, data=0x%x\n", 4212 value->data, (int)newIndex, (int)value->dataType, value->data); 4213 } 4214 //printf("Getting reference 0x%08x: newIndex=%d\n", value->data, newIndex); 4215 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newFlags; 4216 if (newIndex < 0) { 4217 // This can fail if the resource being referenced is a style... 4218 // in this case, just return the reference, and expect the 4219 // caller to deal with. 4220 return blockIndex; 4221 } 4222 blockIndex = newIndex; 4223 count++; 4224 } 4225 return blockIndex; 4226 } 4227 4228 const char16_t* ResTable::valueToString( 4229 const Res_value* value, size_t stringBlock, 4230 char16_t /*tmpBuffer*/ [TMP_BUFFER_SIZE], size_t* outLen) const 4231 { 4232 if (!value) { 4233 return NULL; 4234 } 4235 if (value->dataType == value->TYPE_STRING) { 4236 return getTableStringBlock(stringBlock)->stringAt(value->data, outLen); 4237 } 4238 // XXX do int to string conversions. 4239 return NULL; 4240 } 4241 4242 ssize_t ResTable::lockBag(uint32_t resID, const bag_entry** outBag) const 4243 { 4244 mLock.lock(); 4245 ssize_t err = getBagLocked(resID, outBag); 4246 if (err < NO_ERROR) { 4247 //printf("*** get failed! unlocking\n"); 4248 mLock.unlock(); 4249 } 4250 return err; 4251 } 4252 4253 void ResTable::unlockBag(const bag_entry* /*bag*/) const 4254 { 4255 //printf("<<< unlockBag %p\n", this); 4256 mLock.unlock(); 4257 } 4258 4259 void ResTable::lock() const 4260 { 4261 mLock.lock(); 4262 } 4263 4264 void ResTable::unlock() const 4265 { 4266 mLock.unlock(); 4267 } 4268 4269 ssize_t ResTable::getBagLocked(uint32_t resID, const bag_entry** outBag, 4270 uint32_t* outTypeSpecFlags) const 4271 { 4272 if (mError != NO_ERROR) { 4273 return mError; 4274 } 4275 4276 const ssize_t p = getResourcePackageIndex(resID); 4277 const int t = Res_GETTYPE(resID); 4278 const int e = Res_GETENTRY(resID); 4279 4280 if (p < 0) { 4281 ALOGW("Invalid package identifier when getting bag for resource number 0x%08x", resID); 4282 return BAD_INDEX; 4283 } 4284 if (t < 0) { 4285 ALOGW("No type identifier when getting bag for resource number 0x%08x", resID); 4286 return BAD_INDEX; 4287 } 4288 4289 //printf("Get bag: id=0x%08x, p=%d, t=%d\n", resID, p, t); 4290 PackageGroup* const grp = mPackageGroups[p]; 4291 if (grp == NULL) { 4292 ALOGW("Bad identifier when getting bag for resource number 0x%08x", resID); 4293 return BAD_INDEX; 4294 } 4295 4296 const TypeList& typeConfigs = grp->types[t]; 4297 if (typeConfigs.isEmpty()) { 4298 ALOGW("Type identifier 0x%x does not exist.", t+1); 4299 return BAD_INDEX; 4300 } 4301 4302 const size_t NENTRY = typeConfigs[0]->entryCount; 4303 if (e >= (int)NENTRY) { 4304 ALOGW("Entry identifier 0x%x is larger than entry count 0x%x", 4305 e, (int)typeConfigs[0]->entryCount); 4306 return BAD_INDEX; 4307 } 4308 4309 // First see if we've already computed this bag... 4310 TypeCacheEntry& cacheEntry = grp->typeCacheEntries.editItemAt(t); 4311 bag_set** typeSet = cacheEntry.cachedBags; 4312 if (typeSet) { 4313 bag_set* set = typeSet[e]; 4314 if (set) { 4315 if (set != (bag_set*)0xFFFFFFFF) { 4316 if (outTypeSpecFlags != NULL) { 4317 *outTypeSpecFlags = set->typeSpecFlags; 4318 } 4319 *outBag = (bag_entry*)(set+1); 4320 if (kDebugTableSuperNoisy) { 4321 ALOGI("Found existing bag for: 0x%x\n", resID); 4322 } 4323 return set->numAttrs; 4324 } 4325 ALOGW("Attempt to retrieve bag 0x%08x which is invalid or in a cycle.", 4326 resID); 4327 return BAD_INDEX; 4328 } 4329 } 4330 4331 // Bag not found, we need to compute it! 4332 if (!typeSet) { 4333 typeSet = (bag_set**)calloc(NENTRY, sizeof(bag_set*)); 4334 if (!typeSet) return NO_MEMORY; 4335 cacheEntry.cachedBags = typeSet; 4336 } 4337 4338 // Mark that we are currently working on this one. 4339 typeSet[e] = (bag_set*)0xFFFFFFFF; 4340 4341 if (kDebugTableNoisy) { 4342 ALOGI("Building bag: %x\n", resID); 4343 } 4344 4345 // Now collect all bag attributes 4346 Entry entry; 4347 status_t err = getEntry(grp, t, e, &mParams, &entry); 4348 if (err != NO_ERROR) { 4349 return err; 4350 } 4351 4352 const uint16_t entrySize = dtohs(entry.entry->size); 4353 const uint32_t parent = entrySize >= sizeof(ResTable_map_entry) 4354 ? dtohl(((const ResTable_map_entry*)entry.entry)->parent.ident) : 0; 4355 const uint32_t count = entrySize >= sizeof(ResTable_map_entry) 4356 ? dtohl(((const ResTable_map_entry*)entry.entry)->count) : 0; 4357 4358 size_t N = count; 4359 4360 if (kDebugTableNoisy) { 4361 ALOGI("Found map: size=%x parent=%x count=%d\n", entrySize, parent, count); 4362 4363 // If this map inherits from another, we need to start 4364 // with its parent's values. Otherwise start out empty. 4365 ALOGI("Creating new bag, entrySize=0x%08x, parent=0x%08x\n", entrySize, parent); 4366 } 4367 4368 // This is what we are building. 4369 bag_set* set = NULL; 4370 4371 if (parent) { 4372 uint32_t resolvedParent = parent; 4373 4374 // Bags encode a parent reference without using the standard 4375 // Res_value structure. That means we must always try to 4376 // resolve a parent reference in case it is actually a 4377 // TYPE_DYNAMIC_REFERENCE. 4378 status_t err = grp->dynamicRefTable.lookupResourceId(&resolvedParent); 4379 if (err != NO_ERROR) { 4380 ALOGE("Failed resolving bag parent id 0x%08x", parent); 4381 return UNKNOWN_ERROR; 4382 } 4383 4384 const bag_entry* parentBag; 4385 uint32_t parentTypeSpecFlags = 0; 4386 const ssize_t NP = getBagLocked(resolvedParent, &parentBag, &parentTypeSpecFlags); 4387 const size_t NT = ((NP >= 0) ? NP : 0) + N; 4388 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*NT); 4389 if (set == NULL) { 4390 return NO_MEMORY; 4391 } 4392 if (NP > 0) { 4393 memcpy(set+1, parentBag, NP*sizeof(bag_entry)); 4394 set->numAttrs = NP; 4395 if (kDebugTableNoisy) { 4396 ALOGI("Initialized new bag with %zd inherited attributes.\n", NP); 4397 } 4398 } else { 4399 if (kDebugTableNoisy) { 4400 ALOGI("Initialized new bag with no inherited attributes.\n"); 4401 } 4402 set->numAttrs = 0; 4403 } 4404 set->availAttrs = NT; 4405 set->typeSpecFlags = parentTypeSpecFlags; 4406 } else { 4407 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*N); 4408 if (set == NULL) { 4409 return NO_MEMORY; 4410 } 4411 set->numAttrs = 0; 4412 set->availAttrs = N; 4413 set->typeSpecFlags = 0; 4414 } 4415 4416 set->typeSpecFlags |= entry.specFlags; 4417 4418 // Now merge in the new attributes... 4419 size_t curOff = (reinterpret_cast<uintptr_t>(entry.entry) - reinterpret_cast<uintptr_t>(entry.type)) 4420 + dtohs(entry.entry->size); 4421 const ResTable_map* map; 4422 bag_entry* entries = (bag_entry*)(set+1); 4423 size_t curEntry = 0; 4424 uint32_t pos = 0; 4425 if (kDebugTableNoisy) { 4426 ALOGI("Starting with set %p, entries=%p, avail=%zu\n", set, entries, set->availAttrs); 4427 } 4428 while (pos < count) { 4429 if (kDebugTableNoisy) { 4430 ALOGI("Now at %p\n", (void*)curOff); 4431 } 4432 4433 if (curOff > (dtohl(entry.type->header.size)-sizeof(ResTable_map))) { 4434 ALOGW("ResTable_map at %d is beyond type chunk data %d", 4435 (int)curOff, dtohl(entry.type->header.size)); 4436 free(set); 4437 return BAD_TYPE; 4438 } 4439 map = (const ResTable_map*)(((const uint8_t*)entry.type) + curOff); 4440 N++; 4441 4442 uint32_t newName = htodl(map->name.ident); 4443 if (!Res_INTERNALID(newName)) { 4444 // Attributes don't have a resource id as the name. They specify 4445 // other data, which would be wrong to change via a lookup. 4446 if (grp->dynamicRefTable.lookupResourceId(&newName) != NO_ERROR) { 4447 ALOGE("Failed resolving ResTable_map name at %d with ident 0x%08x", 4448 (int) curOff, (int) newName); 4449 free(set); 4450 return UNKNOWN_ERROR; 4451 } 4452 } 4453 4454 bool isInside; 4455 uint32_t oldName = 0; 4456 while ((isInside=(curEntry < set->numAttrs)) 4457 && (oldName=entries[curEntry].map.name.ident) < newName) { 4458 if (kDebugTableNoisy) { 4459 ALOGI("#%zu: Keeping existing attribute: 0x%08x\n", 4460 curEntry, entries[curEntry].map.name.ident); 4461 } 4462 curEntry++; 4463 } 4464 4465 if ((!isInside) || oldName != newName) { 4466 // This is a new attribute... figure out what to do with it. 4467 if (set->numAttrs >= set->availAttrs) { 4468 // Need to alloc more memory... 4469 const size_t newAvail = set->availAttrs+N; 4470 void *oldSet = set; 4471 set = (bag_set*)realloc(set, 4472 sizeof(bag_set) 4473 + sizeof(bag_entry)*newAvail); 4474 if (set == NULL) { 4475 free(oldSet); 4476 return NO_MEMORY; 4477 } 4478 set->availAttrs = newAvail; 4479 entries = (bag_entry*)(set+1); 4480 if (kDebugTableNoisy) { 4481 ALOGI("Reallocated set %p, entries=%p, avail=%zu\n", 4482 set, entries, set->availAttrs); 4483 } 4484 } 4485 if (isInside) { 4486 // Going in the middle, need to make space. 4487 memmove(entries+curEntry+1, entries+curEntry, 4488 sizeof(bag_entry)*(set->numAttrs-curEntry)); 4489 set->numAttrs++; 4490 } 4491 if (kDebugTableNoisy) { 4492 ALOGI("#%zu: Inserting new attribute: 0x%08x\n", curEntry, newName); 4493 } 4494 } else { 4495 if (kDebugTableNoisy) { 4496 ALOGI("#%zu: Replacing existing attribute: 0x%08x\n", curEntry, oldName); 4497 } 4498 } 4499 4500 bag_entry* cur = entries+curEntry; 4501 4502 cur->stringBlock = entry.package->header->index; 4503 cur->map.name.ident = newName; 4504 cur->map.value.copyFrom_dtoh(map->value); 4505 status_t err = grp->dynamicRefTable.lookupResourceValue(&cur->map.value); 4506 if (err != NO_ERROR) { 4507 ALOGE("Reference item(0x%08x) in bag could not be resolved.", cur->map.value.data); 4508 return UNKNOWN_ERROR; 4509 } 4510 4511 if (kDebugTableNoisy) { 4512 ALOGI("Setting entry #%zu %p: block=%zd, name=0x%08d, type=%d, data=0x%08x\n", 4513 curEntry, cur, cur->stringBlock, cur->map.name.ident, 4514 cur->map.value.dataType, cur->map.value.data); 4515 } 4516 4517 // On to the next! 4518 curEntry++; 4519 pos++; 4520 const size_t size = dtohs(map->value.size); 4521 curOff += size + sizeof(*map)-sizeof(map->value); 4522 } 4523 4524 if (curEntry > set->numAttrs) { 4525 set->numAttrs = curEntry; 4526 } 4527 4528 // And this is it... 4529 typeSet[e] = set; 4530 if (set) { 4531 if (outTypeSpecFlags != NULL) { 4532 *outTypeSpecFlags = set->typeSpecFlags; 4533 } 4534 *outBag = (bag_entry*)(set+1); 4535 if (kDebugTableNoisy) { 4536 ALOGI("Returning %zu attrs\n", set->numAttrs); 4537 } 4538 return set->numAttrs; 4539 } 4540 return BAD_INDEX; 4541 } 4542 4543 void ResTable::setParameters(const ResTable_config* params) 4544 { 4545 AutoMutex _lock(mLock); 4546 AutoMutex _lock2(mFilteredConfigLock); 4547 4548 if (kDebugTableGetEntry) { 4549 ALOGI("Setting parameters: %s\n", params->toString().string()); 4550 } 4551 mParams = *params; 4552 for (size_t p = 0; p < mPackageGroups.size(); p++) { 4553 PackageGroup* packageGroup = mPackageGroups.editItemAt(p); 4554 if (kDebugTableNoisy) { 4555 ALOGI("CLEARING BAGS FOR GROUP %zu!", p); 4556 } 4557 packageGroup->clearBagCache(); 4558 4559 // Find which configurations match the set of parameters. This allows for a much 4560 // faster lookup in getEntry() if the set of values is narrowed down. 4561 for (size_t t = 0; t < packageGroup->types.size(); t++) { 4562 if (packageGroup->types[t].isEmpty()) { 4563 continue; 4564 } 4565 4566 TypeList& typeList = packageGroup->types.editItemAt(t); 4567 4568 // Retrieve the cache entry for this type. 4569 TypeCacheEntry& cacheEntry = packageGroup->typeCacheEntries.editItemAt(t); 4570 4571 for (size_t ts = 0; ts < typeList.size(); ts++) { 4572 Type* type = typeList.editItemAt(ts); 4573 4574 std::shared_ptr<Vector<const ResTable_type*>> newFilteredConfigs = 4575 std::make_shared<Vector<const ResTable_type*>>(); 4576 4577 for (size_t ti = 0; ti < type->configs.size(); ti++) { 4578 ResTable_config config; 4579 config.copyFromDtoH(type->configs[ti]->config); 4580 4581 if (config.match(mParams)) { 4582 newFilteredConfigs->add(type->configs[ti]); 4583 } 4584 } 4585 4586 if (kDebugTableNoisy) { 4587 ALOGD("Updating pkg=%zu type=%zu with %zu filtered configs", 4588 p, t, newFilteredConfigs->size()); 4589 } 4590 4591 cacheEntry.filteredConfigs.add(newFilteredConfigs); 4592 } 4593 } 4594 } 4595 } 4596 4597 void ResTable::getParameters(ResTable_config* params) const 4598 { 4599 mLock.lock(); 4600 *params = mParams; 4601 mLock.unlock(); 4602 } 4603 4604 struct id_name_map { 4605 uint32_t id; 4606 size_t len; 4607 char16_t name[6]; 4608 }; 4609 4610 const static id_name_map ID_NAMES[] = { 4611 { ResTable_map::ATTR_TYPE, 5, { '^', 't', 'y', 'p', 'e' } }, 4612 { ResTable_map::ATTR_L10N, 5, { '^', 'l', '1', '0', 'n' } }, 4613 { ResTable_map::ATTR_MIN, 4, { '^', 'm', 'i', 'n' } }, 4614 { ResTable_map::ATTR_MAX, 4, { '^', 'm', 'a', 'x' } }, 4615 { ResTable_map::ATTR_OTHER, 6, { '^', 'o', 't', 'h', 'e', 'r' } }, 4616 { ResTable_map::ATTR_ZERO, 5, { '^', 'z', 'e', 'r', 'o' } }, 4617 { ResTable_map::ATTR_ONE, 4, { '^', 'o', 'n', 'e' } }, 4618 { ResTable_map::ATTR_TWO, 4, { '^', 't', 'w', 'o' } }, 4619 { ResTable_map::ATTR_FEW, 4, { '^', 'f', 'e', 'w' } }, 4620 { ResTable_map::ATTR_MANY, 5, { '^', 'm', 'a', 'n', 'y' } }, 4621 }; 4622 4623 uint32_t ResTable::identifierForName(const char16_t* name, size_t nameLen, 4624 const char16_t* type, size_t typeLen, 4625 const char16_t* package, 4626 size_t packageLen, 4627 uint32_t* outTypeSpecFlags) const 4628 { 4629 if (kDebugTableSuperNoisy) { 4630 printf("Identifier for name: error=%d\n", mError); 4631 } 4632 4633 // Check for internal resource identifier as the very first thing, so 4634 // that we will always find them even when there are no resources. 4635 if (name[0] == '^') { 4636 const int N = (sizeof(ID_NAMES)/sizeof(ID_NAMES[0])); 4637 size_t len; 4638 for (int i=0; i<N; i++) { 4639 const id_name_map* m = ID_NAMES + i; 4640 len = m->len; 4641 if (len != nameLen) { 4642 continue; 4643 } 4644 for (size_t j=1; j<len; j++) { 4645 if (m->name[j] != name[j]) { 4646 goto nope; 4647 } 4648 } 4649 if (outTypeSpecFlags) { 4650 *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC; 4651 } 4652 return m->id; 4653 nope: 4654 ; 4655 } 4656 if (nameLen > 7) { 4657 if (name[1] == 'i' && name[2] == 'n' 4658 && name[3] == 'd' && name[4] == 'e' && name[5] == 'x' 4659 && name[6] == '_') { 4660 int index = atoi(String8(name + 7, nameLen - 7).string()); 4661 if (Res_CHECKID(index)) { 4662 ALOGW("Array resource index: %d is too large.", 4663 index); 4664 return 0; 4665 } 4666 if (outTypeSpecFlags) { 4667 *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC; 4668 } 4669 return Res_MAKEARRAY(index); 4670 } 4671 } 4672 return 0; 4673 } 4674 4675 if (mError != NO_ERROR) { 4676 return 0; 4677 } 4678 4679 bool fakePublic = false; 4680 4681 // Figure out the package and type we are looking in... 4682 4683 const char16_t* packageEnd = NULL; 4684 const char16_t* typeEnd = NULL; 4685 const char16_t* const nameEnd = name+nameLen; 4686 const char16_t* p = name; 4687 while (p < nameEnd) { 4688 if (*p == ':') packageEnd = p; 4689 else if (*p == '/') typeEnd = p; 4690 p++; 4691 } 4692 if (*name == '@') { 4693 name++; 4694 if (*name == '*') { 4695 fakePublic = true; 4696 name++; 4697 } 4698 } 4699 if (name >= nameEnd) { 4700 return 0; 4701 } 4702 4703 if (packageEnd) { 4704 package = name; 4705 packageLen = packageEnd-name; 4706 name = packageEnd+1; 4707 } else if (!package) { 4708 return 0; 4709 } 4710 4711 if (typeEnd) { 4712 type = name; 4713 typeLen = typeEnd-name; 4714 name = typeEnd+1; 4715 } else if (!type) { 4716 return 0; 4717 } 4718 4719 if (name >= nameEnd) { 4720 return 0; 4721 } 4722 nameLen = nameEnd-name; 4723 4724 if (kDebugTableNoisy) { 4725 printf("Looking for identifier: type=%s, name=%s, package=%s\n", 4726 String8(type, typeLen).string(), 4727 String8(name, nameLen).string(), 4728 String8(package, packageLen).string()); 4729 } 4730 4731 const String16 attr("attr"); 4732 const String16 attrPrivate("^attr-private"); 4733 4734 const size_t NG = mPackageGroups.size(); 4735 for (size_t ig=0; ig<NG; ig++) { 4736 const PackageGroup* group = mPackageGroups[ig]; 4737 4738 if (strzcmp16(package, packageLen, 4739 group->name.string(), group->name.size())) { 4740 if (kDebugTableNoisy) { 4741 printf("Skipping package group: %s\n", String8(group->name).string()); 4742 } 4743 continue; 4744 } 4745 4746 const size_t packageCount = group->packages.size(); 4747 for (size_t pi = 0; pi < packageCount; pi++) { 4748 const char16_t* targetType = type; 4749 size_t targetTypeLen = typeLen; 4750 4751 do { 4752 ssize_t ti = group->packages[pi]->typeStrings.indexOfString( 4753 targetType, targetTypeLen); 4754 if (ti < 0) { 4755 continue; 4756 } 4757 4758 ti += group->packages[pi]->typeIdOffset; 4759 4760 const uint32_t identifier = findEntry(group, ti, name, nameLen, 4761 outTypeSpecFlags); 4762 if (identifier != 0) { 4763 if (fakePublic && outTypeSpecFlags) { 4764 *outTypeSpecFlags |= ResTable_typeSpec::SPEC_PUBLIC; 4765 } 4766 return identifier; 4767 } 4768 } while (strzcmp16(attr.string(), attr.size(), targetType, targetTypeLen) == 0 4769 && (targetType = attrPrivate.string()) 4770 && (targetTypeLen = attrPrivate.size()) 4771 ); 4772 } 4773 } 4774 return 0; 4775 } 4776 4777 uint32_t ResTable::findEntry(const PackageGroup* group, ssize_t typeIndex, const char16_t* name, 4778 size_t nameLen, uint32_t* outTypeSpecFlags) const { 4779 const TypeList& typeList = group->types[typeIndex]; 4780 const size_t typeCount = typeList.size(); 4781 for (size_t i = 0; i < typeCount; i++) { 4782 const Type* t = typeList[i]; 4783 const ssize_t ei = t->package->keyStrings.indexOfString(name, nameLen); 4784 if (ei < 0) { 4785 continue; 4786 } 4787 4788 const size_t configCount = t->configs.size(); 4789 for (size_t j = 0; j < configCount; j++) { 4790 const TypeVariant tv(t->configs[j]); 4791 for (TypeVariant::iterator iter = tv.beginEntries(); 4792 iter != tv.endEntries(); 4793 iter++) { 4794 const ResTable_entry* entry = *iter; 4795 if (entry == NULL) { 4796 continue; 4797 } 4798 4799 if (dtohl(entry->key.index) == (size_t) ei) { 4800 uint32_t resId = Res_MAKEID(group->id - 1, typeIndex, iter.index()); 4801 if (outTypeSpecFlags) { 4802 Entry result; 4803 if (getEntry(group, typeIndex, iter.index(), NULL, &result) != NO_ERROR) { 4804 ALOGW("Failed to find spec flags for 0x%08x", resId); 4805 return 0; 4806 } 4807 *outTypeSpecFlags = result.specFlags; 4808 } 4809 return resId; 4810 } 4811 } 4812 } 4813 } 4814 return 0; 4815 } 4816 4817 bool ResTable::expandResourceRef(const char16_t* refStr, size_t refLen, 4818 String16* outPackage, 4819 String16* outType, 4820 String16* outName, 4821 const String16* defType, 4822 const String16* defPackage, 4823 const char** outErrorMsg, 4824 bool* outPublicOnly) 4825 { 4826 const char16_t* packageEnd = NULL; 4827 const char16_t* typeEnd = NULL; 4828 const char16_t* p = refStr; 4829 const char16_t* const end = p + refLen; 4830 while (p < end) { 4831 if (*p == ':') packageEnd = p; 4832 else if (*p == '/') { 4833 typeEnd = p; 4834 break; 4835 } 4836 p++; 4837 } 4838 p = refStr; 4839 if (*p == '@') p++; 4840 4841 if (outPublicOnly != NULL) { 4842 *outPublicOnly = true; 4843 } 4844 if (*p == '*') { 4845 p++; 4846 if (outPublicOnly != NULL) { 4847 *outPublicOnly = false; 4848 } 4849 } 4850 4851 if (packageEnd) { 4852 *outPackage = String16(p, packageEnd-p); 4853 p = packageEnd+1; 4854 } else { 4855 if (!defPackage) { 4856 if (outErrorMsg) { 4857 *outErrorMsg = "No resource package specified"; 4858 } 4859 return false; 4860 } 4861 *outPackage = *defPackage; 4862 } 4863 if (typeEnd) { 4864 *outType = String16(p, typeEnd-p); 4865 p = typeEnd+1; 4866 } else { 4867 if (!defType) { 4868 if (outErrorMsg) { 4869 *outErrorMsg = "No resource type specified"; 4870 } 4871 return false; 4872 } 4873 *outType = *defType; 4874 } 4875 *outName = String16(p, end-p); 4876 if(**outPackage == 0) { 4877 if(outErrorMsg) { 4878 *outErrorMsg = "Resource package cannot be an empty string"; 4879 } 4880 return false; 4881 } 4882 if(**outType == 0) { 4883 if(outErrorMsg) { 4884 *outErrorMsg = "Resource type cannot be an empty string"; 4885 } 4886 return false; 4887 } 4888 if(**outName == 0) { 4889 if(outErrorMsg) { 4890 *outErrorMsg = "Resource id cannot be an empty string"; 4891 } 4892 return false; 4893 } 4894 return true; 4895 } 4896 4897 static uint32_t get_hex(char c, bool* outError) 4898 { 4899 if (c >= '0' && c <= '9') { 4900 return c - '0'; 4901 } else if (c >= 'a' && c <= 'f') { 4902 return c - 'a' + 0xa; 4903 } else if (c >= 'A' && c <= 'F') { 4904 return c - 'A' + 0xa; 4905 } 4906 *outError = true; 4907 return 0; 4908 } 4909 4910 struct unit_entry 4911 { 4912 const char* name; 4913 size_t len; 4914 uint8_t type; 4915 uint32_t unit; 4916 float scale; 4917 }; 4918 4919 static const unit_entry unitNames[] = { 4920 { "px", strlen("px"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PX, 1.0f }, 4921 { "dip", strlen("dip"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f }, 4922 { "dp", strlen("dp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f }, 4923 { "sp", strlen("sp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_SP, 1.0f }, 4924 { "pt", strlen("pt"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PT, 1.0f }, 4925 { "in", strlen("in"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_IN, 1.0f }, 4926 { "mm", strlen("mm"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_MM, 1.0f }, 4927 { "%", strlen("%"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION, 1.0f/100 }, 4928 { "%p", strlen("%p"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION_PARENT, 1.0f/100 }, 4929 { NULL, 0, 0, 0, 0 } 4930 }; 4931 4932 static bool parse_unit(const char* str, Res_value* outValue, 4933 float* outScale, const char** outEnd) 4934 { 4935 const char* end = str; 4936 while (*end != 0 && !isspace((unsigned char)*end)) { 4937 end++; 4938 } 4939 const size_t len = end-str; 4940 4941 const char* realEnd = end; 4942 while (*realEnd != 0 && isspace((unsigned char)*realEnd)) { 4943 realEnd++; 4944 } 4945 if (*realEnd != 0) { 4946 return false; 4947 } 4948 4949 const unit_entry* cur = unitNames; 4950 while (cur->name) { 4951 if (len == cur->len && strncmp(cur->name, str, len) == 0) { 4952 outValue->dataType = cur->type; 4953 outValue->data = cur->unit << Res_value::COMPLEX_UNIT_SHIFT; 4954 *outScale = cur->scale; 4955 *outEnd = end; 4956 //printf("Found unit %s for %s\n", cur->name, str); 4957 return true; 4958 } 4959 cur++; 4960 } 4961 4962 return false; 4963 } 4964 4965 bool U16StringToInt(const char16_t* s, size_t len, Res_value* outValue) 4966 { 4967 while (len > 0 && isspace16(*s)) { 4968 s++; 4969 len--; 4970 } 4971 4972 if (len <= 0) { 4973 return false; 4974 } 4975 4976 size_t i = 0; 4977 int64_t val = 0; 4978 bool neg = false; 4979 4980 if (*s == '-') { 4981 neg = true; 4982 i++; 4983 } 4984 4985 if (s[i] < '0' || s[i] > '9') { 4986 return false; 4987 } 4988 4989 static_assert(std::is_same<uint32_t, Res_value::data_type>::value, 4990 "Res_value::data_type has changed. The range checks in this " 4991 "function are no longer correct."); 4992 4993 // Decimal or hex? 4994 bool isHex; 4995 if (len > 1 && s[i] == '0' && s[i+1] == 'x') { 4996 isHex = true; 4997 i += 2; 4998 4999 if (neg) { 5000 return false; 5001 } 5002 5003 if (i == len) { 5004 // Just u"0x" 5005 return false; 5006 } 5007 5008 bool error = false; 5009 while (i < len && !error) { 5010 val = (val*16) + get_hex(s[i], &error); 5011 i++; 5012 5013 if (val > std::numeric_limits<uint32_t>::max()) { 5014 return false; 5015 } 5016 } 5017 if (error) { 5018 return false; 5019 } 5020 } else { 5021 isHex = false; 5022 while (i < len) { 5023 if (s[i] < '0' || s[i] > '9') { 5024 return false; 5025 } 5026 val = (val*10) + s[i]-'0'; 5027 i++; 5028 5029 if ((neg && -val < std::numeric_limits<int32_t>::min()) || 5030 (!neg && val > std::numeric_limits<int32_t>::max())) { 5031 return false; 5032 } 5033 } 5034 } 5035 5036 if (neg) val = -val; 5037 5038 while (i < len && isspace16(s[i])) { 5039 i++; 5040 } 5041 5042 if (i != len) { 5043 return false; 5044 } 5045 5046 if (outValue) { 5047 outValue->dataType = 5048 isHex ? outValue->TYPE_INT_HEX : outValue->TYPE_INT_DEC; 5049 outValue->data = static_cast<Res_value::data_type>(val); 5050 } 5051 return true; 5052 } 5053 5054 bool ResTable::stringToInt(const char16_t* s, size_t len, Res_value* outValue) 5055 { 5056 return U16StringToInt(s, len, outValue); 5057 } 5058 5059 bool ResTable::stringToFloat(const char16_t* s, size_t len, Res_value* outValue) 5060 { 5061 while (len > 0 && isspace16(*s)) { 5062 s++; 5063 len--; 5064 } 5065 5066 if (len <= 0) { 5067 return false; 5068 } 5069 5070 char buf[128]; 5071 int i=0; 5072 while (len > 0 && *s != 0 && i < 126) { 5073 if (*s > 255) { 5074 return false; 5075 } 5076 buf[i++] = *s++; 5077 len--; 5078 } 5079 5080 if (len > 0) { 5081 return false; 5082 } 5083 if ((buf[0] < '0' || buf[0] > '9') && buf[0] != '.' && buf[0] != '-' && buf[0] != '+') { 5084 return false; 5085 } 5086 5087 buf[i] = 0; 5088 const char* end; 5089 float f = strtof(buf, (char**)&end); 5090 5091 if (*end != 0 && !isspace((unsigned char)*end)) { 5092 // Might be a unit... 5093 float scale; 5094 if (parse_unit(end, outValue, &scale, &end)) { 5095 f *= scale; 5096 const bool neg = f < 0; 5097 if (neg) f = -f; 5098 uint64_t bits = (uint64_t)(f*(1<<23)+.5f); 5099 uint32_t radix; 5100 uint32_t shift; 5101 if ((bits&0x7fffff) == 0) { 5102 // Always use 23p0 if there is no fraction, just to make 5103 // things easier to read. 5104 radix = Res_value::COMPLEX_RADIX_23p0; 5105 shift = 23; 5106 } else if ((bits&0xffffffffff800000LL) == 0) { 5107 // Magnitude is zero -- can fit in 0 bits of precision. 5108 radix = Res_value::COMPLEX_RADIX_0p23; 5109 shift = 0; 5110 } else if ((bits&0xffffffff80000000LL) == 0) { 5111 // Magnitude can fit in 8 bits of precision. 5112 radix = Res_value::COMPLEX_RADIX_8p15; 5113 shift = 8; 5114 } else if ((bits&0xffffff8000000000LL) == 0) { 5115 // Magnitude can fit in 16 bits of precision. 5116 radix = Res_value::COMPLEX_RADIX_16p7; 5117 shift = 16; 5118 } else { 5119 // Magnitude needs entire range, so no fractional part. 5120 radix = Res_value::COMPLEX_RADIX_23p0; 5121 shift = 23; 5122 } 5123 int32_t mantissa = (int32_t)( 5124 (bits>>shift) & Res_value::COMPLEX_MANTISSA_MASK); 5125 if (neg) { 5126 mantissa = (-mantissa) & Res_value::COMPLEX_MANTISSA_MASK; 5127 } 5128 outValue->data |= 5129 (radix<<Res_value::COMPLEX_RADIX_SHIFT) 5130 | (mantissa<<Res_value::COMPLEX_MANTISSA_SHIFT); 5131 //printf("Input value: %f 0x%016Lx, mult: %f, radix: %d, shift: %d, final: 0x%08x\n", 5132 // f * (neg ? -1 : 1), bits, f*(1<<23), 5133 // radix, shift, outValue->data); 5134 return true; 5135 } 5136 return false; 5137 } 5138 5139 while (*end != 0 && isspace((unsigned char)*end)) { 5140 end++; 5141 } 5142 5143 if (*end == 0) { 5144 if (outValue) { 5145 outValue->dataType = outValue->TYPE_FLOAT; 5146 *(float*)(&outValue->data) = f; 5147 return true; 5148 } 5149 } 5150 5151 return false; 5152 } 5153 5154 bool ResTable::stringToValue(Res_value* outValue, String16* outString, 5155 const char16_t* s, size_t len, 5156 bool preserveSpaces, bool coerceType, 5157 uint32_t attrID, 5158 const String16* defType, 5159 const String16* defPackage, 5160 Accessor* accessor, 5161 void* accessorCookie, 5162 uint32_t attrType, 5163 bool enforcePrivate) const 5164 { 5165 bool localizationSetting = accessor != NULL && accessor->getLocalizationSetting(); 5166 const char* errorMsg = NULL; 5167 5168 outValue->size = sizeof(Res_value); 5169 outValue->res0 = 0; 5170 5171 // First strip leading/trailing whitespace. Do this before handling 5172 // escapes, so they can be used to force whitespace into the string. 5173 if (!preserveSpaces) { 5174 while (len > 0 && isspace16(*s)) { 5175 s++; 5176 len--; 5177 } 5178 while (len > 0 && isspace16(s[len-1])) { 5179 len--; 5180 } 5181 // If the string ends with '\', then we keep the space after it. 5182 if (len > 0 && s[len-1] == '\\' && s[len] != 0) { 5183 len++; 5184 } 5185 } 5186 5187 //printf("Value for: %s\n", String8(s, len).string()); 5188 5189 uint32_t l10nReq = ResTable_map::L10N_NOT_REQUIRED; 5190 uint32_t attrMin = 0x80000000, attrMax = 0x7fffffff; 5191 bool fromAccessor = false; 5192 if (attrID != 0 && !Res_INTERNALID(attrID)) { 5193 const ssize_t p = getResourcePackageIndex(attrID); 5194 const bag_entry* bag; 5195 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1; 5196 //printf("For attr 0x%08x got bag of %d\n", attrID, cnt); 5197 if (cnt >= 0) { 5198 while (cnt > 0) { 5199 //printf("Entry 0x%08x = 0x%08x\n", bag->map.name.ident, bag->map.value.data); 5200 switch (bag->map.name.ident) { 5201 case ResTable_map::ATTR_TYPE: 5202 attrType = bag->map.value.data; 5203 break; 5204 case ResTable_map::ATTR_MIN: 5205 attrMin = bag->map.value.data; 5206 break; 5207 case ResTable_map::ATTR_MAX: 5208 attrMax = bag->map.value.data; 5209 break; 5210 case ResTable_map::ATTR_L10N: 5211 l10nReq = bag->map.value.data; 5212 break; 5213 } 5214 bag++; 5215 cnt--; 5216 } 5217 unlockBag(bag); 5218 } else if (accessor && accessor->getAttributeType(attrID, &attrType)) { 5219 fromAccessor = true; 5220 if (attrType == ResTable_map::TYPE_ENUM 5221 || attrType == ResTable_map::TYPE_FLAGS 5222 || attrType == ResTable_map::TYPE_INTEGER) { 5223 accessor->getAttributeMin(attrID, &attrMin); 5224 accessor->getAttributeMax(attrID, &attrMax); 5225 } 5226 if (localizationSetting) { 5227 l10nReq = accessor->getAttributeL10N(attrID); 5228 } 5229 } 5230 } 5231 5232 const bool canStringCoerce = 5233 coerceType && (attrType&ResTable_map::TYPE_STRING) != 0; 5234 5235 if (*s == '@') { 5236 outValue->dataType = outValue->TYPE_REFERENCE; 5237 5238 // Note: we don't check attrType here because the reference can 5239 // be to any other type; we just need to count on the client making 5240 // sure the referenced type is correct. 5241 5242 //printf("Looking up ref: %s\n", String8(s, len).string()); 5243 5244 // It's a reference! 5245 if (len == 5 && s[1]=='n' && s[2]=='u' && s[3]=='l' && s[4]=='l') { 5246 // Special case @null as undefined. This will be converted by 5247 // AssetManager to TYPE_NULL with data DATA_NULL_UNDEFINED. 5248 outValue->data = 0; 5249 return true; 5250 } else if (len == 6 && s[1]=='e' && s[2]=='m' && s[3]=='p' && s[4]=='t' && s[5]=='y') { 5251 // Special case @empty as explicitly defined empty value. 5252 outValue->dataType = Res_value::TYPE_NULL; 5253 outValue->data = Res_value::DATA_NULL_EMPTY; 5254 return true; 5255 } else { 5256 bool createIfNotFound = false; 5257 const char16_t* resourceRefName; 5258 int resourceNameLen; 5259 if (len > 2 && s[1] == '+') { 5260 createIfNotFound = true; 5261 resourceRefName = s + 2; 5262 resourceNameLen = len - 2; 5263 } else if (len > 2 && s[1] == '*') { 5264 enforcePrivate = false; 5265 resourceRefName = s + 2; 5266 resourceNameLen = len - 2; 5267 } else { 5268 createIfNotFound = false; 5269 resourceRefName = s + 1; 5270 resourceNameLen = len - 1; 5271 } 5272 String16 package, type, name; 5273 if (!expandResourceRef(resourceRefName,resourceNameLen, &package, &type, &name, 5274 defType, defPackage, &errorMsg)) { 5275 if (accessor != NULL) { 5276 accessor->reportError(accessorCookie, errorMsg); 5277 } 5278 return false; 5279 } 5280 5281 uint32_t specFlags = 0; 5282 uint32_t rid = identifierForName(name.string(), name.size(), type.string(), 5283 type.size(), package.string(), package.size(), &specFlags); 5284 if (rid != 0) { 5285 if (enforcePrivate) { 5286 if (accessor == NULL || accessor->getAssetsPackage() != package) { 5287 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) { 5288 if (accessor != NULL) { 5289 accessor->reportError(accessorCookie, "Resource is not public."); 5290 } 5291 return false; 5292 } 5293 } 5294 } 5295 5296 if (accessor) { 5297 rid = Res_MAKEID( 5298 accessor->getRemappedPackage(Res_GETPACKAGE(rid)), 5299 Res_GETTYPE(rid), Res_GETENTRY(rid)); 5300 if (kDebugTableNoisy) { 5301 ALOGI("Incl %s:%s/%s: 0x%08x\n", 5302 String8(package).string(), String8(type).string(), 5303 String8(name).string(), rid); 5304 } 5305 } 5306 5307 uint32_t packageId = Res_GETPACKAGE(rid) + 1; 5308 if (packageId != APP_PACKAGE_ID && packageId != SYS_PACKAGE_ID) { 5309 outValue->dataType = Res_value::TYPE_DYNAMIC_REFERENCE; 5310 } 5311 outValue->data = rid; 5312 return true; 5313 } 5314 5315 if (accessor) { 5316 uint32_t rid = accessor->getCustomResourceWithCreation(package, type, name, 5317 createIfNotFound); 5318 if (rid != 0) { 5319 if (kDebugTableNoisy) { 5320 ALOGI("Pckg %s:%s/%s: 0x%08x\n", 5321 String8(package).string(), String8(type).string(), 5322 String8(name).string(), rid); 5323 } 5324 uint32_t packageId = Res_GETPACKAGE(rid) + 1; 5325 if (packageId == 0x00) { 5326 outValue->data = rid; 5327 outValue->dataType = Res_value::TYPE_DYNAMIC_REFERENCE; 5328 return true; 5329 } else if (packageId == APP_PACKAGE_ID || packageId == SYS_PACKAGE_ID) { 5330 // We accept packageId's generated as 0x01 in order to support 5331 // building the android system resources 5332 outValue->data = rid; 5333 return true; 5334 } 5335 } 5336 } 5337 } 5338 5339 if (accessor != NULL) { 5340 accessor->reportError(accessorCookie, "No resource found that matches the given name"); 5341 } 5342 return false; 5343 } 5344 5345 // if we got to here, and localization is required and it's not a reference, 5346 // complain and bail. 5347 if (l10nReq == ResTable_map::L10N_SUGGESTED) { 5348 if (localizationSetting) { 5349 if (accessor != NULL) { 5350 accessor->reportError(accessorCookie, "This attribute must be localized."); 5351 } 5352 } 5353 } 5354 5355 if (*s == '#') { 5356 // It's a color! Convert to an integer of the form 0xaarrggbb. 5357 uint32_t color = 0; 5358 bool error = false; 5359 if (len == 4) { 5360 outValue->dataType = outValue->TYPE_INT_COLOR_RGB4; 5361 color |= 0xFF000000; 5362 color |= get_hex(s[1], &error) << 20; 5363 color |= get_hex(s[1], &error) << 16; 5364 color |= get_hex(s[2], &error) << 12; 5365 color |= get_hex(s[2], &error) << 8; 5366 color |= get_hex(s[3], &error) << 4; 5367 color |= get_hex(s[3], &error); 5368 } else if (len == 5) { 5369 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB4; 5370 color |= get_hex(s[1], &error) << 28; 5371 color |= get_hex(s[1], &error) << 24; 5372 color |= get_hex(s[2], &error) << 20; 5373 color |= get_hex(s[2], &error) << 16; 5374 color |= get_hex(s[3], &error) << 12; 5375 color |= get_hex(s[3], &error) << 8; 5376 color |= get_hex(s[4], &error) << 4; 5377 color |= get_hex(s[4], &error); 5378 } else if (len == 7) { 5379 outValue->dataType = outValue->TYPE_INT_COLOR_RGB8; 5380 color |= 0xFF000000; 5381 color |= get_hex(s[1], &error) << 20; 5382 color |= get_hex(s[2], &error) << 16; 5383 color |= get_hex(s[3], &error) << 12; 5384 color |= get_hex(s[4], &error) << 8; 5385 color |= get_hex(s[5], &error) << 4; 5386 color |= get_hex(s[6], &error); 5387 } else if (len == 9) { 5388 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB8; 5389 color |= get_hex(s[1], &error) << 28; 5390 color |= get_hex(s[2], &error) << 24; 5391 color |= get_hex(s[3], &error) << 20; 5392 color |= get_hex(s[4], &error) << 16; 5393 color |= get_hex(s[5], &error) << 12; 5394 color |= get_hex(s[6], &error) << 8; 5395 color |= get_hex(s[7], &error) << 4; 5396 color |= get_hex(s[8], &error); 5397 } else { 5398 error = true; 5399 } 5400 if (!error) { 5401 if ((attrType&ResTable_map::TYPE_COLOR) == 0) { 5402 if (!canStringCoerce) { 5403 if (accessor != NULL) { 5404 accessor->reportError(accessorCookie, 5405 "Color types not allowed"); 5406 } 5407 return false; 5408 } 5409 } else { 5410 outValue->data = color; 5411 //printf("Color input=%s, output=0x%x\n", String8(s, len).string(), color); 5412 return true; 5413 } 5414 } else { 5415 if ((attrType&ResTable_map::TYPE_COLOR) != 0) { 5416 if (accessor != NULL) { 5417 accessor->reportError(accessorCookie, "Color value not valid --" 5418 " must be #rgb, #argb, #rrggbb, or #aarrggbb"); 5419 } 5420 #if 0 5421 fprintf(stderr, "%s: Color ID %s value %s is not valid\n", 5422 "Resource File", //(const char*)in->getPrintableSource(), 5423 String8(*curTag).string(), 5424 String8(s, len).string()); 5425 #endif 5426 return false; 5427 } 5428 } 5429 } 5430 5431 if (*s == '?') { 5432 outValue->dataType = outValue->TYPE_ATTRIBUTE; 5433 5434 // Note: we don't check attrType here because the reference can 5435 // be to any other type; we just need to count on the client making 5436 // sure the referenced type is correct. 5437 5438 //printf("Looking up attr: %s\n", String8(s, len).string()); 5439 5440 static const String16 attr16("attr"); 5441 String16 package, type, name; 5442 if (!expandResourceRef(s+1, len-1, &package, &type, &name, 5443 &attr16, defPackage, &errorMsg)) { 5444 if (accessor != NULL) { 5445 accessor->reportError(accessorCookie, errorMsg); 5446 } 5447 return false; 5448 } 5449 5450 //printf("Pkg: %s, Type: %s, Name: %s\n", 5451 // String8(package).string(), String8(type).string(), 5452 // String8(name).string()); 5453 uint32_t specFlags = 0; 5454 uint32_t rid = 5455 identifierForName(name.string(), name.size(), 5456 type.string(), type.size(), 5457 package.string(), package.size(), &specFlags); 5458 if (rid != 0) { 5459 if (enforcePrivate) { 5460 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) { 5461 if (accessor != NULL) { 5462 accessor->reportError(accessorCookie, "Attribute is not public."); 5463 } 5464 return false; 5465 } 5466 } 5467 5468 if (accessor) { 5469 rid = Res_MAKEID( 5470 accessor->getRemappedPackage(Res_GETPACKAGE(rid)), 5471 Res_GETTYPE(rid), Res_GETENTRY(rid)); 5472 } 5473 5474 uint32_t packageId = Res_GETPACKAGE(rid) + 1; 5475 if (packageId != APP_PACKAGE_ID && packageId != SYS_PACKAGE_ID) { 5476 outValue->dataType = Res_value::TYPE_DYNAMIC_ATTRIBUTE; 5477 } 5478 outValue->data = rid; 5479 return true; 5480 } 5481 5482 if (accessor) { 5483 uint32_t rid = accessor->getCustomResource(package, type, name); 5484 if (rid != 0) { 5485 uint32_t packageId = Res_GETPACKAGE(rid) + 1; 5486 if (packageId == 0x00) { 5487 outValue->data = rid; 5488 outValue->dataType = Res_value::TYPE_DYNAMIC_ATTRIBUTE; 5489 return true; 5490 } else if (packageId == APP_PACKAGE_ID || packageId == SYS_PACKAGE_ID) { 5491 // We accept packageId's generated as 0x01 in order to support 5492 // building the android system resources 5493 outValue->data = rid; 5494 return true; 5495 } 5496 } 5497 } 5498 5499 if (accessor != NULL) { 5500 accessor->reportError(accessorCookie, "No resource found that matches the given name"); 5501 } 5502 return false; 5503 } 5504 5505 if (stringToInt(s, len, outValue)) { 5506 if ((attrType&ResTable_map::TYPE_INTEGER) == 0) { 5507 // If this type does not allow integers, but does allow floats, 5508 // fall through on this error case because the float type should 5509 // be able to accept any integer value. 5510 if (!canStringCoerce && (attrType&ResTable_map::TYPE_FLOAT) == 0) { 5511 if (accessor != NULL) { 5512 accessor->reportError(accessorCookie, "Integer types not allowed"); 5513 } 5514 return false; 5515 } 5516 } else { 5517 if (((int32_t)outValue->data) < ((int32_t)attrMin) 5518 || ((int32_t)outValue->data) > ((int32_t)attrMax)) { 5519 if (accessor != NULL) { 5520 accessor->reportError(accessorCookie, "Integer value out of range"); 5521 } 5522 return false; 5523 } 5524 return true; 5525 } 5526 } 5527 5528 if (stringToFloat(s, len, outValue)) { 5529 if (outValue->dataType == Res_value::TYPE_DIMENSION) { 5530 if ((attrType&ResTable_map::TYPE_DIMENSION) != 0) { 5531 return true; 5532 } 5533 if (!canStringCoerce) { 5534 if (accessor != NULL) { 5535 accessor->reportError(accessorCookie, "Dimension types not allowed"); 5536 } 5537 return false; 5538 } 5539 } else if (outValue->dataType == Res_value::TYPE_FRACTION) { 5540 if ((attrType&ResTable_map::TYPE_FRACTION) != 0) { 5541 return true; 5542 } 5543 if (!canStringCoerce) { 5544 if (accessor != NULL) { 5545 accessor->reportError(accessorCookie, "Fraction types not allowed"); 5546 } 5547 return false; 5548 } 5549 } else if ((attrType&ResTable_map::TYPE_FLOAT) == 0) { 5550 if (!canStringCoerce) { 5551 if (accessor != NULL) { 5552 accessor->reportError(accessorCookie, "Float types not allowed"); 5553 } 5554 return false; 5555 } 5556 } else { 5557 return true; 5558 } 5559 } 5560 5561 if (len == 4) { 5562 if ((s[0] == 't' || s[0] == 'T') && 5563 (s[1] == 'r' || s[1] == 'R') && 5564 (s[2] == 'u' || s[2] == 'U') && 5565 (s[3] == 'e' || s[3] == 'E')) { 5566 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) { 5567 if (!canStringCoerce) { 5568 if (accessor != NULL) { 5569 accessor->reportError(accessorCookie, "Boolean types not allowed"); 5570 } 5571 return false; 5572 } 5573 } else { 5574 outValue->dataType = outValue->TYPE_INT_BOOLEAN; 5575 outValue->data = (uint32_t)-1; 5576 return true; 5577 } 5578 } 5579 } 5580 5581 if (len == 5) { 5582 if ((s[0] == 'f' || s[0] == 'F') && 5583 (s[1] == 'a' || s[1] == 'A') && 5584 (s[2] == 'l' || s[2] == 'L') && 5585 (s[3] == 's' || s[3] == 'S') && 5586 (s[4] == 'e' || s[4] == 'E')) { 5587 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) { 5588 if (!canStringCoerce) { 5589 if (accessor != NULL) { 5590 accessor->reportError(accessorCookie, "Boolean types not allowed"); 5591 } 5592 return false; 5593 } 5594 } else { 5595 outValue->dataType = outValue->TYPE_INT_BOOLEAN; 5596 outValue->data = 0; 5597 return true; 5598 } 5599 } 5600 } 5601 5602 if ((attrType&ResTable_map::TYPE_ENUM) != 0) { 5603 const ssize_t p = getResourcePackageIndex(attrID); 5604 const bag_entry* bag; 5605 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1; 5606 //printf("Got %d for enum\n", cnt); 5607 if (cnt >= 0) { 5608 resource_name rname; 5609 while (cnt > 0) { 5610 if (!Res_INTERNALID(bag->map.name.ident)) { 5611 //printf("Trying attr #%08x\n", bag->map.name.ident); 5612 if (getResourceName(bag->map.name.ident, false, &rname)) { 5613 #if 0 5614 printf("Matching %s against %s (0x%08x)\n", 5615 String8(s, len).string(), 5616 String8(rname.name, rname.nameLen).string(), 5617 bag->map.name.ident); 5618 #endif 5619 if (strzcmp16(s, len, rname.name, rname.nameLen) == 0) { 5620 outValue->dataType = bag->map.value.dataType; 5621 outValue->data = bag->map.value.data; 5622 unlockBag(bag); 5623 return true; 5624 } 5625 } 5626 5627 } 5628 bag++; 5629 cnt--; 5630 } 5631 unlockBag(bag); 5632 } 5633 5634 if (fromAccessor) { 5635 if (accessor->getAttributeEnum(attrID, s, len, outValue)) { 5636 return true; 5637 } 5638 } 5639 } 5640 5641 if ((attrType&ResTable_map::TYPE_FLAGS) != 0) { 5642 const ssize_t p = getResourcePackageIndex(attrID); 5643 const bag_entry* bag; 5644 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1; 5645 //printf("Got %d for flags\n", cnt); 5646 if (cnt >= 0) { 5647 bool failed = false; 5648 resource_name rname; 5649 outValue->dataType = Res_value::TYPE_INT_HEX; 5650 outValue->data = 0; 5651 const char16_t* end = s + len; 5652 const char16_t* pos = s; 5653 while (pos < end && !failed) { 5654 const char16_t* start = pos; 5655 pos++; 5656 while (pos < end && *pos != '|') { 5657 pos++; 5658 } 5659 //printf("Looking for: %s\n", String8(start, pos-start).string()); 5660 const bag_entry* bagi = bag; 5661 ssize_t i; 5662 for (i=0; i<cnt; i++, bagi++) { 5663 if (!Res_INTERNALID(bagi->map.name.ident)) { 5664 //printf("Trying attr #%08x\n", bagi->map.name.ident); 5665 if (getResourceName(bagi->map.name.ident, false, &rname)) { 5666 #if 0 5667 printf("Matching %s against %s (0x%08x)\n", 5668 String8(start,pos-start).string(), 5669 String8(rname.name, rname.nameLen).string(), 5670 bagi->map.name.ident); 5671 #endif 5672 if (strzcmp16(start, pos-start, rname.name, rname.nameLen) == 0) { 5673 outValue->data |= bagi->map.value.data; 5674 break; 5675 } 5676 } 5677 } 5678 } 5679 if (i >= cnt) { 5680 // Didn't find this flag identifier. 5681 failed = true; 5682 } 5683 if (pos < end) { 5684 pos++; 5685 } 5686 } 5687 unlockBag(bag); 5688 if (!failed) { 5689 //printf("Final flag value: 0x%lx\n", outValue->data); 5690 return true; 5691 } 5692 } 5693 5694 5695 if (fromAccessor) { 5696 if (accessor->getAttributeFlags(attrID, s, len, outValue)) { 5697 //printf("Final flag value: 0x%lx\n", outValue->data); 5698 return true; 5699 } 5700 } 5701 } 5702 5703 if ((attrType&ResTable_map::TYPE_STRING) == 0) { 5704 if (accessor != NULL) { 5705 accessor->reportError(accessorCookie, "String types not allowed"); 5706 } 5707 return false; 5708 } 5709 5710 // Generic string handling... 5711 outValue->dataType = outValue->TYPE_STRING; 5712 if (outString) { 5713 bool failed = collectString(outString, s, len, preserveSpaces, &errorMsg); 5714 if (accessor != NULL) { 5715 accessor->reportError(accessorCookie, errorMsg); 5716 } 5717 return failed; 5718 } 5719 5720 return true; 5721 } 5722 5723 bool ResTable::collectString(String16* outString, 5724 const char16_t* s, size_t len, 5725 bool preserveSpaces, 5726 const char** outErrorMsg, 5727 bool append) 5728 { 5729 String16 tmp; 5730 5731 char quoted = 0; 5732 const char16_t* p = s; 5733 while (p < (s+len)) { 5734 while (p < (s+len)) { 5735 const char16_t c = *p; 5736 if (c == '\\') { 5737 break; 5738 } 5739 if (!preserveSpaces) { 5740 if (quoted == 0 && isspace16(c) 5741 && (c != ' ' || isspace16(*(p+1)))) { 5742 break; 5743 } 5744 if (c == '"' && (quoted == 0 || quoted == '"')) { 5745 break; 5746 } 5747 if (c == '\'' && (quoted == 0 || quoted == '\'')) { 5748 /* 5749 * In practice, when people write ' instead of \' 5750 * in a string, they are doing it by accident 5751 * instead of really meaning to use ' as a quoting 5752 * character. Warn them so they don't lose it. 5753 */ 5754 if (outErrorMsg) { 5755 *outErrorMsg = "Apostrophe not preceded by \\"; 5756 } 5757 return false; 5758 } 5759 } 5760 p++; 5761 } 5762 if (p < (s+len)) { 5763 if (p > s) { 5764 tmp.append(String16(s, p-s)); 5765 } 5766 if (!preserveSpaces && (*p == '"' || *p == '\'')) { 5767 if (quoted == 0) { 5768 quoted = *p; 5769 } else { 5770 quoted = 0; 5771 } 5772 p++; 5773 } else if (!preserveSpaces && isspace16(*p)) { 5774 // Space outside of a quote -- consume all spaces and 5775 // leave a single plain space char. 5776 tmp.append(String16(" ")); 5777 p++; 5778 while (p < (s+len) && isspace16(*p)) { 5779 p++; 5780 } 5781 } else if (*p == '\\') { 5782 p++; 5783 if (p < (s+len)) { 5784 switch (*p) { 5785 case 't': 5786 tmp.append(String16("\t")); 5787 break; 5788 case 'n': 5789 tmp.append(String16("\n")); 5790 break; 5791 case '#': 5792 tmp.append(String16("#")); 5793 break; 5794 case '@': 5795 tmp.append(String16("@")); 5796 break; 5797 case '?': 5798 tmp.append(String16("?")); 5799 break; 5800 case '"': 5801 tmp.append(String16("\"")); 5802 break; 5803 case '\'': 5804 tmp.append(String16("'")); 5805 break; 5806 case '\\': 5807 tmp.append(String16("\\")); 5808 break; 5809 case 'u': 5810 { 5811 char16_t chr = 0; 5812 int i = 0; 5813 while (i < 4 && p[1] != 0) { 5814 p++; 5815 i++; 5816 int c; 5817 if (*p >= '0' && *p <= '9') { 5818 c = *p - '0'; 5819 } else if (*p >= 'a' && *p <= 'f') { 5820 c = *p - 'a' + 10; 5821 } else if (*p >= 'A' && *p <= 'F') { 5822 c = *p - 'A' + 10; 5823 } else { 5824 if (outErrorMsg) { 5825 *outErrorMsg = "Bad character in \\u unicode escape sequence"; 5826 } 5827 return false; 5828 } 5829 chr = (chr<<4) | c; 5830 } 5831 tmp.append(String16(&chr, 1)); 5832 } break; 5833 default: 5834 // ignore unknown escape chars. 5835 break; 5836 } 5837 p++; 5838 } 5839 } 5840 len -= (p-s); 5841 s = p; 5842 } 5843 } 5844 5845 if (tmp.size() != 0) { 5846 if (len > 0) { 5847 tmp.append(String16(s, len)); 5848 } 5849 if (append) { 5850 outString->append(tmp); 5851 } else { 5852 outString->setTo(tmp); 5853 } 5854 } else { 5855 if (append) { 5856 outString->append(String16(s, len)); 5857 } else { 5858 outString->setTo(s, len); 5859 } 5860 } 5861 5862 return true; 5863 } 5864 5865 size_t ResTable::getBasePackageCount() const 5866 { 5867 if (mError != NO_ERROR) { 5868 return 0; 5869 } 5870 return mPackageGroups.size(); 5871 } 5872 5873 const String16 ResTable::getBasePackageName(size_t idx) const 5874 { 5875 if (mError != NO_ERROR) { 5876 return String16(); 5877 } 5878 LOG_FATAL_IF(idx >= mPackageGroups.size(), 5879 "Requested package index %d past package count %d", 5880 (int)idx, (int)mPackageGroups.size()); 5881 return mPackageGroups[idx]->name; 5882 } 5883 5884 uint32_t ResTable::getBasePackageId(size_t idx) const 5885 { 5886 if (mError != NO_ERROR) { 5887 return 0; 5888 } 5889 LOG_FATAL_IF(idx >= mPackageGroups.size(), 5890 "Requested package index %d past package count %d", 5891 (int)idx, (int)mPackageGroups.size()); 5892 return mPackageGroups[idx]->id; 5893 } 5894 5895 uint32_t ResTable::getLastTypeIdForPackage(size_t idx) const 5896 { 5897 if (mError != NO_ERROR) { 5898 return 0; 5899 } 5900 LOG_FATAL_IF(idx >= mPackageGroups.size(), 5901 "Requested package index %d past package count %d", 5902 (int)idx, (int)mPackageGroups.size()); 5903 const PackageGroup* const group = mPackageGroups[idx]; 5904 return group->largestTypeId; 5905 } 5906 5907 size_t ResTable::getTableCount() const 5908 { 5909 return mHeaders.size(); 5910 } 5911 5912 const ResStringPool* ResTable::getTableStringBlock(size_t index) const 5913 { 5914 return &mHeaders[index]->values; 5915 } 5916 5917 int32_t ResTable::getTableCookie(size_t index) const 5918 { 5919 return mHeaders[index]->cookie; 5920 } 5921 5922 const DynamicRefTable* ResTable::getDynamicRefTableForCookie(int32_t cookie) const 5923 { 5924 const size_t N = mPackageGroups.size(); 5925 for (size_t i = 0; i < N; i++) { 5926 const PackageGroup* pg = mPackageGroups[i]; 5927 size_t M = pg->packages.size(); 5928 for (size_t j = 0; j < M; j++) { 5929 if (pg->packages[j]->header->cookie == cookie) { 5930 return &pg->dynamicRefTable; 5931 } 5932 } 5933 } 5934 return NULL; 5935 } 5936 5937 static bool compareResTableConfig(const ResTable_config& a, const ResTable_config& b) { 5938 return a.compare(b) < 0; 5939 } 5940 5941 template <typename Func> 5942 void ResTable::forEachConfiguration(bool ignoreMipmap, bool ignoreAndroidPackage, 5943 bool includeSystemConfigs, const Func& f) const { 5944 const size_t packageCount = mPackageGroups.size(); 5945 const String16 android("android"); 5946 for (size_t i = 0; i < packageCount; i++) { 5947 const PackageGroup* packageGroup = mPackageGroups[i]; 5948 if (ignoreAndroidPackage && android == packageGroup->name) { 5949 continue; 5950 } 5951 if (!includeSystemConfigs && packageGroup->isSystemAsset) { 5952 continue; 5953 } 5954 const size_t typeCount = packageGroup->types.size(); 5955 for (size_t j = 0; j < typeCount; j++) { 5956 const TypeList& typeList = packageGroup->types[j]; 5957 const size_t numTypes = typeList.size(); 5958 for (size_t k = 0; k < numTypes; k++) { 5959 const Type* type = typeList[k]; 5960 const ResStringPool& typeStrings = type->package->typeStrings; 5961 if (ignoreMipmap && typeStrings.string8ObjectAt( 5962 type->typeSpec->id - 1) == "mipmap") { 5963 continue; 5964 } 5965 5966 const size_t numConfigs = type->configs.size(); 5967 for (size_t m = 0; m < numConfigs; m++) { 5968 const ResTable_type* config = type->configs[m]; 5969 ResTable_config cfg; 5970 memset(&cfg, 0, sizeof(ResTable_config)); 5971 cfg.copyFromDtoH(config->config); 5972 5973 f(cfg); 5974 } 5975 } 5976 } 5977 } 5978 } 5979 5980 void ResTable::getConfigurations(Vector<ResTable_config>* configs, bool ignoreMipmap, 5981 bool ignoreAndroidPackage, bool includeSystemConfigs) const { 5982 auto func = [&](const ResTable_config& cfg) { 5983 const auto beginIter = configs->begin(); 5984 const auto endIter = configs->end(); 5985 5986 auto iter = std::lower_bound(beginIter, endIter, cfg, compareResTableConfig); 5987 if (iter == endIter || iter->compare(cfg) != 0) { 5988 configs->insertAt(cfg, std::distance(beginIter, iter)); 5989 } 5990 }; 5991 forEachConfiguration(ignoreMipmap, ignoreAndroidPackage, includeSystemConfigs, func); 5992 } 5993 5994 static bool compareString8AndCString(const String8& str, const char* cStr) { 5995 return strcmp(str.string(), cStr) < 0; 5996 } 5997 5998 void ResTable::getLocales(Vector<String8>* locales, bool includeSystemLocales, 5999 bool mergeEquivalentLangs) const { 6000 char locale[RESTABLE_MAX_LOCALE_LEN]; 6001 6002 forEachConfiguration(false, false, includeSystemLocales, [&](const ResTable_config& cfg) { 6003 cfg.getBcp47Locale(locale, mergeEquivalentLangs /* canonicalize if merging */); 6004 6005 const auto beginIter = locales->begin(); 6006 const auto endIter = locales->end(); 6007 6008 auto iter = std::lower_bound(beginIter, endIter, locale, compareString8AndCString); 6009 if (iter == endIter || strcmp(iter->string(), locale) != 0) { 6010 locales->insertAt(String8(locale), std::distance(beginIter, iter)); 6011 } 6012 }); 6013 } 6014 6015 StringPoolRef::StringPoolRef(const ResStringPool* pool, uint32_t index) 6016 : mPool(pool), mIndex(index) {} 6017 6018 StringPoolRef::StringPoolRef() 6019 : mPool(NULL), mIndex(0) {} 6020 6021 const char* StringPoolRef::string8(size_t* outLen) const { 6022 if (mPool != NULL) { 6023 return mPool->string8At(mIndex, outLen); 6024 } 6025 if (outLen != NULL) { 6026 *outLen = 0; 6027 } 6028 return NULL; 6029 } 6030 6031 const char16_t* StringPoolRef::string16(size_t* outLen) const { 6032 if (mPool != NULL) { 6033 return mPool->stringAt(mIndex, outLen); 6034 } 6035 if (outLen != NULL) { 6036 *outLen = 0; 6037 } 6038 return NULL; 6039 } 6040 6041 bool ResTable::getResourceFlags(uint32_t resID, uint32_t* outFlags) const { 6042 if (mError != NO_ERROR) { 6043 return false; 6044 } 6045 6046 const ssize_t p = getResourcePackageIndex(resID); 6047 const int t = Res_GETTYPE(resID); 6048 const int e = Res_GETENTRY(resID); 6049 6050 if (p < 0) { 6051 if (Res_GETPACKAGE(resID)+1 == 0) { 6052 ALOGW("No package identifier when getting flags for resource number 0x%08x", resID); 6053 } else { 6054 ALOGW("No known package when getting flags for resource number 0x%08x", resID); 6055 } 6056 return false; 6057 } 6058 if (t < 0) { 6059 ALOGW("No type identifier when getting flags for resource number 0x%08x", resID); 6060 return false; 6061 } 6062 6063 const PackageGroup* const grp = mPackageGroups[p]; 6064 if (grp == NULL) { 6065 ALOGW("Bad identifier when getting flags for resource number 0x%08x", resID); 6066 return false; 6067 } 6068 6069 Entry entry; 6070 status_t err = getEntry(grp, t, e, NULL, &entry); 6071 if (err != NO_ERROR) { 6072 return false; 6073 } 6074 6075 *outFlags = entry.specFlags; 6076 return true; 6077 } 6078 6079 static bool keyCompare(const ResTable_sparseTypeEntry& entry , uint16_t entryIdx) { 6080 return dtohs(entry.idx) < entryIdx; 6081 } 6082 6083 status_t ResTable::getEntry( 6084 const PackageGroup* packageGroup, int typeIndex, int entryIndex, 6085 const ResTable_config* config, 6086 Entry* outEntry) const 6087 { 6088 const TypeList& typeList = packageGroup->types[typeIndex]; 6089 if (typeList.isEmpty()) { 6090 ALOGV("Skipping entry type index 0x%02x because type is NULL!\n", typeIndex); 6091 return BAD_TYPE; 6092 } 6093 6094 const ResTable_type* bestType = NULL; 6095 uint32_t bestOffset = ResTable_type::NO_ENTRY; 6096 const Package* bestPackage = NULL; 6097 uint32_t specFlags = 0; 6098 uint8_t actualTypeIndex = typeIndex; 6099 ResTable_config bestConfig; 6100 memset(&bestConfig, 0, sizeof(bestConfig)); 6101 6102 // Iterate over the Types of each package. 6103 const size_t typeCount = typeList.size(); 6104 for (size_t i = 0; i < typeCount; i++) { 6105 const Type* const typeSpec = typeList[i]; 6106 6107 int realEntryIndex = entryIndex; 6108 int realTypeIndex = typeIndex; 6109 bool currentTypeIsOverlay = false; 6110 6111 // Runtime overlay packages provide a mapping of app resource 6112 // ID to package resource ID. 6113 if (typeSpec->idmapEntries.hasEntries()) { 6114 uint16_t overlayEntryIndex; 6115 if (typeSpec->idmapEntries.lookup(entryIndex, &overlayEntryIndex) != NO_ERROR) { 6116 // No such mapping exists 6117 continue; 6118 } 6119 realEntryIndex = overlayEntryIndex; 6120 realTypeIndex = typeSpec->idmapEntries.overlayTypeId() - 1; 6121 currentTypeIsOverlay = true; 6122 } 6123 6124 // Check that the entry idx is within range of the declared entry count (ResTable_typeSpec). 6125 // Particular types (ResTable_type) may be encoded with sparse entries, and so their 6126 // entryCount do not need to match. 6127 if (static_cast<size_t>(realEntryIndex) >= typeSpec->entryCount) { 6128 ALOGW("For resource 0x%08x, entry index(%d) is beyond type entryCount(%d)", 6129 Res_MAKEID(packageGroup->id - 1, typeIndex, entryIndex), 6130 entryIndex, static_cast<int>(typeSpec->entryCount)); 6131 // We should normally abort here, but some legacy apps declare 6132 // resources in the 'android' package (old bug in AAPT). 6133 continue; 6134 } 6135 6136 // Aggregate all the flags for each package that defines this entry. 6137 if (typeSpec->typeSpecFlags != NULL) { 6138 specFlags |= dtohl(typeSpec->typeSpecFlags[realEntryIndex]); 6139 } else { 6140 specFlags = -1; 6141 } 6142 6143 const Vector<const ResTable_type*>* candidateConfigs = &typeSpec->configs; 6144 6145 std::shared_ptr<Vector<const ResTable_type*>> filteredConfigs; 6146 if (config && memcmp(&mParams, config, sizeof(mParams)) == 0) { 6147 // Grab the lock first so we can safely get the current filtered list. 6148 AutoMutex _lock(mFilteredConfigLock); 6149 6150 // This configuration is equal to the one we have previously cached for, 6151 // so use the filtered configs. 6152 6153 const TypeCacheEntry& cacheEntry = packageGroup->typeCacheEntries[typeIndex]; 6154 if (i < cacheEntry.filteredConfigs.size()) { 6155 if (cacheEntry.filteredConfigs[i]) { 6156 // Grab a reference to the shared_ptr so it doesn't get destroyed while 6157 // going through this list. 6158 filteredConfigs = cacheEntry.filteredConfigs[i]; 6159 6160 // Use this filtered list. 6161 candidateConfigs = filteredConfigs.get(); 6162 } 6163 } 6164 } 6165 6166 const size_t numConfigs = candidateConfigs->size(); 6167 for (size_t c = 0; c < numConfigs; c++) { 6168 const ResTable_type* const thisType = candidateConfigs->itemAt(c); 6169 if (thisType == NULL) { 6170 continue; 6171 } 6172 6173 ResTable_config thisConfig; 6174 thisConfig.copyFromDtoH(thisType->config); 6175 6176 // Check to make sure this one is valid for the current parameters. 6177 if (config != NULL && !thisConfig.match(*config)) { 6178 continue; 6179 } 6180 6181 const uint32_t* const eindex = reinterpret_cast<const uint32_t*>( 6182 reinterpret_cast<const uint8_t*>(thisType) + dtohs(thisType->header.headerSize)); 6183 6184 uint32_t thisOffset; 6185 6186 // Check if there is the desired entry in this type. 6187 if (thisType->flags & ResTable_type::FLAG_SPARSE) { 6188 // This is encoded as a sparse map, so perform a binary search. 6189 const ResTable_sparseTypeEntry* sparseIndices = 6190 reinterpret_cast<const ResTable_sparseTypeEntry*>(eindex); 6191 const ResTable_sparseTypeEntry* result = std::lower_bound( 6192 sparseIndices, sparseIndices + dtohl(thisType->entryCount), realEntryIndex, 6193 keyCompare); 6194 if (result == sparseIndices + dtohl(thisType->entryCount) 6195 || dtohs(result->idx) != realEntryIndex) { 6196 // No entry found. 6197 continue; 6198 } 6199 6200 // Extract the offset from the entry. Each offset must be a multiple of 4 6201 // so we store it as the real offset divided by 4. 6202 thisOffset = dtohs(result->offset) * 4u; 6203 } else { 6204 if (static_cast<uint32_t>(realEntryIndex) >= dtohl(thisType->entryCount)) { 6205 // Entry does not exist. 6206 continue; 6207 } 6208 6209 thisOffset = dtohl(eindex[realEntryIndex]); 6210 } 6211 6212 if (thisOffset == ResTable_type::NO_ENTRY) { 6213 // There is no entry for this index and configuration. 6214 continue; 6215 } 6216 6217 if (bestType != NULL) { 6218 // Check if this one is less specific than the last found. If so, 6219 // we will skip it. We check starting with things we most care 6220 // about to those we least care about. 6221 if (!thisConfig.isBetterThan(bestConfig, config)) { 6222 if (!currentTypeIsOverlay || thisConfig.compare(bestConfig) != 0) { 6223 continue; 6224 } 6225 } 6226 } 6227 6228 bestType = thisType; 6229 bestOffset = thisOffset; 6230 bestConfig = thisConfig; 6231 bestPackage = typeSpec->package; 6232 actualTypeIndex = realTypeIndex; 6233 6234 // If no config was specified, any type will do, so skip 6235 if (config == NULL) { 6236 break; 6237 } 6238 } 6239 } 6240 6241 if (bestType == NULL) { 6242 return BAD_INDEX; 6243 } 6244 6245 bestOffset += dtohl(bestType->entriesStart); 6246 6247 if (bestOffset > (dtohl(bestType->header.size)-sizeof(ResTable_entry))) { 6248 ALOGW("ResTable_entry at 0x%x is beyond type chunk data 0x%x", 6249 bestOffset, dtohl(bestType->header.size)); 6250 return BAD_TYPE; 6251 } 6252 if ((bestOffset & 0x3) != 0) { 6253 ALOGW("ResTable_entry at 0x%x is not on an integer boundary", bestOffset); 6254 return BAD_TYPE; 6255 } 6256 6257 const ResTable_entry* const entry = reinterpret_cast<const ResTable_entry*>( 6258 reinterpret_cast<const uint8_t*>(bestType) + bestOffset); 6259 if (dtohs(entry->size) < sizeof(*entry)) { 6260 ALOGW("ResTable_entry size 0x%x is too small", dtohs(entry->size)); 6261 return BAD_TYPE; 6262 } 6263 6264 if (outEntry != NULL) { 6265 outEntry->entry = entry; 6266 outEntry->config = bestConfig; 6267 outEntry->type = bestType; 6268 outEntry->specFlags = specFlags; 6269 outEntry->package = bestPackage; 6270 outEntry->typeStr = StringPoolRef(&bestPackage->typeStrings, actualTypeIndex - bestPackage->typeIdOffset); 6271 outEntry->keyStr = StringPoolRef(&bestPackage->keyStrings, dtohl(entry->key.index)); 6272 } 6273 return NO_ERROR; 6274 } 6275 6276 status_t ResTable::parsePackage(const ResTable_package* const pkg, 6277 const Header* const header, bool appAsLib, bool isSystemAsset) 6278 { 6279 const uint8_t* base = (const uint8_t*)pkg; 6280 status_t err = validate_chunk(&pkg->header, sizeof(*pkg) - sizeof(pkg->typeIdOffset), 6281 header->dataEnd, "ResTable_package"); 6282 if (err != NO_ERROR) { 6283 return (mError=err); 6284 } 6285 6286 const uint32_t pkgSize = dtohl(pkg->header.size); 6287 6288 if (dtohl(pkg->typeStrings) >= pkgSize) { 6289 ALOGW("ResTable_package type strings at 0x%x are past chunk size 0x%x.", 6290 dtohl(pkg->typeStrings), pkgSize); 6291 return (mError=BAD_TYPE); 6292 } 6293 if ((dtohl(pkg->typeStrings)&0x3) != 0) { 6294 ALOGW("ResTable_package type strings at 0x%x is not on an integer boundary.", 6295 dtohl(pkg->typeStrings)); 6296 return (mError=BAD_TYPE); 6297 } 6298 if (dtohl(pkg->keyStrings) >= pkgSize) { 6299 ALOGW("ResTable_package key strings at 0x%x are past chunk size 0x%x.", 6300 dtohl(pkg->keyStrings), pkgSize); 6301 return (mError=BAD_TYPE); 6302 } 6303 if ((dtohl(pkg->keyStrings)&0x3) != 0) { 6304 ALOGW("ResTable_package key strings at 0x%x is not on an integer boundary.", 6305 dtohl(pkg->keyStrings)); 6306 return (mError=BAD_TYPE); 6307 } 6308 6309 uint32_t id = dtohl(pkg->id); 6310 KeyedVector<uint8_t, IdmapEntries> idmapEntries; 6311 6312 if (header->resourceIDMap != NULL) { 6313 uint8_t targetPackageId = 0; 6314 status_t err = parseIdmap(header->resourceIDMap, header->resourceIDMapSize, &targetPackageId, &idmapEntries); 6315 if (err != NO_ERROR) { 6316 ALOGW("Overlay is broken"); 6317 return (mError=err); 6318 } 6319 id = targetPackageId; 6320 } 6321 6322 if (id >= 256) { 6323 LOG_ALWAYS_FATAL("Package id out of range"); 6324 return NO_ERROR; 6325 } else if (id == 0 || (id == 0x7f && appAsLib) || isSystemAsset) { 6326 // This is a library or a system asset, so assign an ID 6327 id = mNextPackageId++; 6328 } 6329 6330 PackageGroup* group = NULL; 6331 Package* package = new Package(this, header, pkg); 6332 if (package == NULL) { 6333 return (mError=NO_MEMORY); 6334 } 6335 6336 err = package->typeStrings.setTo(base+dtohl(pkg->typeStrings), 6337 header->dataEnd-(base+dtohl(pkg->typeStrings))); 6338 if (err != NO_ERROR) { 6339 delete group; 6340 delete package; 6341 return (mError=err); 6342 } 6343 6344 err = package->keyStrings.setTo(base+dtohl(pkg->keyStrings), 6345 header->dataEnd-(base+dtohl(pkg->keyStrings))); 6346 if (err != NO_ERROR) { 6347 delete group; 6348 delete package; 6349 return (mError=err); 6350 } 6351 6352 size_t idx = mPackageMap[id]; 6353 if (idx == 0) { 6354 idx = mPackageGroups.size() + 1; 6355 6356 char16_t tmpName[sizeof(pkg->name)/sizeof(pkg->name[0])]; 6357 strcpy16_dtoh(tmpName, pkg->name, sizeof(pkg->name)/sizeof(pkg->name[0])); 6358 group = new PackageGroup(this, String16(tmpName), id, appAsLib, isSystemAsset); 6359 if (group == NULL) { 6360 delete package; 6361 return (mError=NO_MEMORY); 6362 } 6363 6364 err = mPackageGroups.add(group); 6365 if (err < NO_ERROR) { 6366 return (mError=err); 6367 } 6368 6369 mPackageMap[id] = static_cast<uint8_t>(idx); 6370 6371 // Find all packages that reference this package 6372 size_t N = mPackageGroups.size(); 6373 for (size_t i = 0; i < N; i++) { 6374 mPackageGroups[i]->dynamicRefTable.addMapping( 6375 group->name, static_cast<uint8_t>(group->id)); 6376 } 6377 } else { 6378 group = mPackageGroups.itemAt(idx - 1); 6379 if (group == NULL) { 6380 return (mError=UNKNOWN_ERROR); 6381 } 6382 } 6383 6384 err = group->packages.add(package); 6385 if (err < NO_ERROR) { 6386 return (mError=err); 6387 } 6388 6389 // Iterate through all chunks. 6390 const ResChunk_header* chunk = 6391 (const ResChunk_header*)(((const uint8_t*)pkg) 6392 + dtohs(pkg->header.headerSize)); 6393 const uint8_t* endPos = ((const uint8_t*)pkg) + dtohs(pkg->header.size); 6394 while (((const uint8_t*)chunk) <= (endPos-sizeof(ResChunk_header)) && 6395 ((const uint8_t*)chunk) <= (endPos-dtohl(chunk->size))) { 6396 if (kDebugTableNoisy) { 6397 ALOGV("PackageChunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n", 6398 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size), 6399 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header))); 6400 } 6401 const size_t csize = dtohl(chunk->size); 6402 const uint16_t ctype = dtohs(chunk->type); 6403 if (ctype == RES_TABLE_TYPE_SPEC_TYPE) { 6404 const ResTable_typeSpec* typeSpec = (const ResTable_typeSpec*)(chunk); 6405 err = validate_chunk(&typeSpec->header, sizeof(*typeSpec), 6406 endPos, "ResTable_typeSpec"); 6407 if (err != NO_ERROR) { 6408 return (mError=err); 6409 } 6410 6411 const size_t typeSpecSize = dtohl(typeSpec->header.size); 6412 const size_t newEntryCount = dtohl(typeSpec->entryCount); 6413 6414 if (kDebugLoadTableNoisy) { 6415 ALOGI("TypeSpec off %p: type=0x%x, headerSize=0x%x, size=%p\n", 6416 (void*)(base-(const uint8_t*)chunk), 6417 dtohs(typeSpec->header.type), 6418 dtohs(typeSpec->header.headerSize), 6419 (void*)typeSpecSize); 6420 } 6421 // look for block overrun or int overflow when multiplying by 4 6422 if ((dtohl(typeSpec->entryCount) > (INT32_MAX/sizeof(uint32_t)) 6423 || dtohs(typeSpec->header.headerSize)+(sizeof(uint32_t)*newEntryCount) 6424 > typeSpecSize)) { 6425 ALOGW("ResTable_typeSpec entry index to %p extends beyond chunk end %p.", 6426 (void*)(dtohs(typeSpec->header.headerSize) + (sizeof(uint32_t)*newEntryCount)), 6427 (void*)typeSpecSize); 6428 return (mError=BAD_TYPE); 6429 } 6430 6431 if (typeSpec->id == 0) { 6432 ALOGW("ResTable_type has an id of 0."); 6433 return (mError=BAD_TYPE); 6434 } 6435 6436 if (newEntryCount > 0) { 6437 bool addToType = true; 6438 uint8_t typeIndex = typeSpec->id - 1; 6439 ssize_t idmapIndex = idmapEntries.indexOfKey(typeSpec->id); 6440 if (idmapIndex >= 0) { 6441 typeIndex = idmapEntries[idmapIndex].targetTypeId() - 1; 6442 } else if (header->resourceIDMap != NULL) { 6443 // This is an overlay, but the types in this overlay are not 6444 // overlaying anything according to the idmap. We can skip these 6445 // as they will otherwise conflict with the other resources in the package 6446 // without a mapping. 6447 addToType = false; 6448 } 6449 6450 if (addToType) { 6451 TypeList& typeList = group->types.editItemAt(typeIndex); 6452 if (!typeList.isEmpty()) { 6453 const Type* existingType = typeList[0]; 6454 if (existingType->entryCount != newEntryCount && idmapIndex < 0) { 6455 ALOGW("ResTable_typeSpec entry count inconsistent: " 6456 "given %d, previously %d", 6457 (int) newEntryCount, (int) existingType->entryCount); 6458 // We should normally abort here, but some legacy apps declare 6459 // resources in the 'android' package (old bug in AAPT). 6460 } 6461 } 6462 6463 Type* t = new Type(header, package, newEntryCount); 6464 t->typeSpec = typeSpec; 6465 t->typeSpecFlags = (const uint32_t*)( 6466 ((const uint8_t*)typeSpec) + dtohs(typeSpec->header.headerSize)); 6467 if (idmapIndex >= 0) { 6468 t->idmapEntries = idmapEntries[idmapIndex]; 6469 } 6470 typeList.add(t); 6471 group->largestTypeId = max(group->largestTypeId, typeSpec->id); 6472 } 6473 } else { 6474 ALOGV("Skipping empty ResTable_typeSpec for type %d", typeSpec->id); 6475 } 6476 6477 } else if (ctype == RES_TABLE_TYPE_TYPE) { 6478 const ResTable_type* type = (const ResTable_type*)(chunk); 6479 err = validate_chunk(&type->header, sizeof(*type)-sizeof(ResTable_config)+4, 6480 endPos, "ResTable_type"); 6481 if (err != NO_ERROR) { 6482 return (mError=err); 6483 } 6484 6485 const uint32_t typeSize = dtohl(type->header.size); 6486 const size_t newEntryCount = dtohl(type->entryCount); 6487 6488 if (kDebugLoadTableNoisy) { 6489 printf("Type off %p: type=0x%x, headerSize=0x%x, size=%u\n", 6490 (void*)(base-(const uint8_t*)chunk), 6491 dtohs(type->header.type), 6492 dtohs(type->header.headerSize), 6493 typeSize); 6494 } 6495 if (dtohs(type->header.headerSize)+(sizeof(uint32_t)*newEntryCount) > typeSize) { 6496 ALOGW("ResTable_type entry index to %p extends beyond chunk end 0x%x.", 6497 (void*)(dtohs(type->header.headerSize) + (sizeof(uint32_t)*newEntryCount)), 6498 typeSize); 6499 return (mError=BAD_TYPE); 6500 } 6501 6502 if (newEntryCount != 0 6503 && dtohl(type->entriesStart) > (typeSize-sizeof(ResTable_entry))) { 6504 ALOGW("ResTable_type entriesStart at 0x%x extends beyond chunk end 0x%x.", 6505 dtohl(type->entriesStart), typeSize); 6506 return (mError=BAD_TYPE); 6507 } 6508 6509 if (type->id == 0) { 6510 ALOGW("ResTable_type has an id of 0."); 6511 return (mError=BAD_TYPE); 6512 } 6513 6514 if (newEntryCount > 0) { 6515 bool addToType = true; 6516 uint8_t typeIndex = type->id - 1; 6517 ssize_t idmapIndex = idmapEntries.indexOfKey(type->id); 6518 if (idmapIndex >= 0) { 6519 typeIndex = idmapEntries[idmapIndex].targetTypeId() - 1; 6520 } else if (header->resourceIDMap != NULL) { 6521 // This is an overlay, but the types in this overlay are not 6522 // overlaying anything according to the idmap. We can skip these 6523 // as they will otherwise conflict with the other resources in the package 6524 // without a mapping. 6525 addToType = false; 6526 } 6527 6528 if (addToType) { 6529 TypeList& typeList = group->types.editItemAt(typeIndex); 6530 if (typeList.isEmpty()) { 6531 ALOGE("No TypeSpec for type %d", type->id); 6532 return (mError=BAD_TYPE); 6533 } 6534 6535 Type* t = typeList.editItemAt(typeList.size() - 1); 6536 if (t->package != package) { 6537 ALOGE("No TypeSpec for type %d", type->id); 6538 return (mError=BAD_TYPE); 6539 } 6540 6541 t->configs.add(type); 6542 6543 if (kDebugTableGetEntry) { 6544 ResTable_config thisConfig; 6545 thisConfig.copyFromDtoH(type->config); 6546 ALOGI("Adding config to type %d: %s\n", type->id, 6547 thisConfig.toString().string()); 6548 } 6549 } 6550 } else { 6551 ALOGV("Skipping empty ResTable_type for type %d", type->id); 6552 } 6553 6554 } else if (ctype == RES_TABLE_LIBRARY_TYPE) { 6555 if (group->dynamicRefTable.entries().size() == 0) { 6556 status_t err = group->dynamicRefTable.load((const ResTable_lib_header*) chunk); 6557 if (err != NO_ERROR) { 6558 return (mError=err); 6559 } 6560 6561 // Fill in the reference table with the entries we already know about. 6562 size_t N = mPackageGroups.size(); 6563 for (size_t i = 0; i < N; i++) { 6564 group->dynamicRefTable.addMapping(mPackageGroups[i]->name, mPackageGroups[i]->id); 6565 } 6566 } else { 6567 ALOGW("Found multiple library tables, ignoring..."); 6568 } 6569 } else { 6570 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), 6571 endPos, "ResTable_package:unknown"); 6572 if (err != NO_ERROR) { 6573 return (mError=err); 6574 } 6575 } 6576 chunk = (const ResChunk_header*) 6577 (((const uint8_t*)chunk) + csize); 6578 } 6579 6580 return NO_ERROR; 6581 } 6582 6583 DynamicRefTable::DynamicRefTable() : DynamicRefTable(0, false) {} 6584 6585 DynamicRefTable::DynamicRefTable(uint8_t packageId, bool appAsLib) 6586 : mAssignedPackageId(packageId) 6587 , mAppAsLib(appAsLib) 6588 { 6589 memset(mLookupTable, 0, sizeof(mLookupTable)); 6590 6591 // Reserved package ids 6592 mLookupTable[APP_PACKAGE_ID] = APP_PACKAGE_ID; 6593 mLookupTable[SYS_PACKAGE_ID] = SYS_PACKAGE_ID; 6594 } 6595 6596 status_t DynamicRefTable::load(const ResTable_lib_header* const header) 6597 { 6598 const uint32_t entryCount = dtohl(header->count); 6599 const uint32_t sizeOfEntries = sizeof(ResTable_lib_entry) * entryCount; 6600 const uint32_t expectedSize = dtohl(header->header.size) - dtohl(header->header.headerSize); 6601 if (sizeOfEntries > expectedSize) { 6602 ALOGE("ResTable_lib_header size %u is too small to fit %u entries (x %u).", 6603 expectedSize, entryCount, (uint32_t)sizeof(ResTable_lib_entry)); 6604 return UNKNOWN_ERROR; 6605 } 6606 6607 const ResTable_lib_entry* entry = (const ResTable_lib_entry*)(((uint8_t*) header) + 6608 dtohl(header->header.headerSize)); 6609 for (uint32_t entryIndex = 0; entryIndex < entryCount; entryIndex++) { 6610 uint32_t packageId = dtohl(entry->packageId); 6611 char16_t tmpName[sizeof(entry->packageName) / sizeof(char16_t)]; 6612 strcpy16_dtoh(tmpName, entry->packageName, sizeof(entry->packageName) / sizeof(char16_t)); 6613 if (kDebugLibNoisy) { 6614 ALOGV("Found lib entry %s with id %d\n", String8(tmpName).string(), 6615 dtohl(entry->packageId)); 6616 } 6617 if (packageId >= 256) { 6618 ALOGE("Bad package id 0x%08x", packageId); 6619 return UNKNOWN_ERROR; 6620 } 6621 mEntries.replaceValueFor(String16(tmpName), (uint8_t) packageId); 6622 entry = entry + 1; 6623 } 6624 return NO_ERROR; 6625 } 6626 6627 status_t DynamicRefTable::addMappings(const DynamicRefTable& other) { 6628 if (mAssignedPackageId != other.mAssignedPackageId) { 6629 return UNKNOWN_ERROR; 6630 } 6631 6632 const size_t entryCount = other.mEntries.size(); 6633 for (size_t i = 0; i < entryCount; i++) { 6634 ssize_t index = mEntries.indexOfKey(other.mEntries.keyAt(i)); 6635 if (index < 0) { 6636 mEntries.add(other.mEntries.keyAt(i), other.mEntries[i]); 6637 } else { 6638 if (other.mEntries[i] != mEntries[index]) { 6639 return UNKNOWN_ERROR; 6640 } 6641 } 6642 } 6643 6644 // Merge the lookup table. No entry can conflict 6645 // (value of 0 means not set). 6646 for (size_t i = 0; i < 256; i++) { 6647 if (mLookupTable[i] != other.mLookupTable[i]) { 6648 if (mLookupTable[i] == 0) { 6649 mLookupTable[i] = other.mLookupTable[i]; 6650 } else if (other.mLookupTable[i] != 0) { 6651 return UNKNOWN_ERROR; 6652 } 6653 } 6654 } 6655 return NO_ERROR; 6656 } 6657 6658 status_t DynamicRefTable::addMapping(const String16& packageName, uint8_t packageId) 6659 { 6660 ssize_t index = mEntries.indexOfKey(packageName); 6661 if (index < 0) { 6662 return UNKNOWN_ERROR; 6663 } 6664 mLookupTable[mEntries.valueAt(index)] = packageId; 6665 return NO_ERROR; 6666 } 6667 6668 void DynamicRefTable::addMapping(uint8_t buildPackageId, uint8_t runtimePackageId) { 6669 mLookupTable[buildPackageId] = runtimePackageId; 6670 } 6671 6672 status_t DynamicRefTable::lookupResourceId(uint32_t* resId) const { 6673 uint32_t res = *resId; 6674 size_t packageId = Res_GETPACKAGE(res) + 1; 6675 6676 if (packageId == APP_PACKAGE_ID && !mAppAsLib) { 6677 // No lookup needs to be done, app package IDs are absolute. 6678 return NO_ERROR; 6679 } 6680 6681 if (packageId == 0 || (packageId == APP_PACKAGE_ID && mAppAsLib)) { 6682 // The package ID is 0x00. That means that a shared library is accessing 6683 // its own local resource. 6684 // Or if app resource is loaded as shared library, the resource which has 6685 // app package Id is local resources. 6686 // so we fix up those resources with the calling package ID. 6687 *resId = (0xFFFFFF & (*resId)) | (((uint32_t) mAssignedPackageId) << 24); 6688 return NO_ERROR; 6689 } 6690 6691 // Do a proper lookup. 6692 uint8_t translatedId = mLookupTable[packageId]; 6693 if (translatedId == 0) { 6694 ALOGW("DynamicRefTable(0x%02x): No mapping for build-time package ID 0x%02x.", 6695 (uint8_t)mAssignedPackageId, (uint8_t)packageId); 6696 for (size_t i = 0; i < 256; i++) { 6697 if (mLookupTable[i] != 0) { 6698 ALOGW("e[0x%02x] -> 0x%02x", (uint8_t)i, mLookupTable[i]); 6699 } 6700 } 6701 return UNKNOWN_ERROR; 6702 } 6703 6704 *resId = (res & 0x00ffffff) | (((uint32_t) translatedId) << 24); 6705 return NO_ERROR; 6706 } 6707 6708 status_t DynamicRefTable::lookupResourceValue(Res_value* value) const { 6709 uint8_t resolvedType = Res_value::TYPE_REFERENCE; 6710 switch (value->dataType) { 6711 case Res_value::TYPE_ATTRIBUTE: 6712 resolvedType = Res_value::TYPE_ATTRIBUTE; 6713 // fallthrough 6714 case Res_value::TYPE_REFERENCE: 6715 if (!mAppAsLib) { 6716 return NO_ERROR; 6717 } 6718 6719 // If the package is loaded as shared library, the resource reference 6720 // also need to be fixed. 6721 break; 6722 case Res_value::TYPE_DYNAMIC_ATTRIBUTE: 6723 resolvedType = Res_value::TYPE_ATTRIBUTE; 6724 // fallthrough 6725 case Res_value::TYPE_DYNAMIC_REFERENCE: 6726 break; 6727 default: 6728 return NO_ERROR; 6729 } 6730 6731 status_t err = lookupResourceId(&value->data); 6732 if (err != NO_ERROR) { 6733 return err; 6734 } 6735 6736 value->dataType = resolvedType; 6737 return NO_ERROR; 6738 } 6739 6740 struct IdmapTypeMap { 6741 ssize_t overlayTypeId; 6742 size_t entryOffset; 6743 Vector<uint32_t> entryMap; 6744 }; 6745 6746 status_t ResTable::createIdmap(const ResTable& overlay, 6747 uint32_t targetCrc, uint32_t overlayCrc, 6748 const char* targetPath, const char* overlayPath, 6749 void** outData, size_t* outSize) const 6750 { 6751 // see README for details on the format of map 6752 if (mPackageGroups.size() == 0) { 6753 ALOGW("idmap: target package has no package groups, cannot create idmap\n"); 6754 return UNKNOWN_ERROR; 6755 } 6756 6757 if (mPackageGroups[0]->packages.size() == 0) { 6758 ALOGW("idmap: target package has no packages in its first package group, " 6759 "cannot create idmap\n"); 6760 return UNKNOWN_ERROR; 6761 } 6762 6763 KeyedVector<uint8_t, IdmapTypeMap> map; 6764 6765 // overlaid packages are assumed to contain only one package group 6766 const PackageGroup* pg = mPackageGroups[0]; 6767 6768 // starting size is header 6769 *outSize = ResTable::IDMAP_HEADER_SIZE_BYTES; 6770 6771 // target package id and number of types in map 6772 *outSize += 2 * sizeof(uint16_t); 6773 6774 // overlay packages are assumed to contain only one package group 6775 const ResTable_package* overlayPackageStruct = overlay.mPackageGroups[0]->packages[0]->package; 6776 char16_t tmpName[sizeof(overlayPackageStruct->name)/sizeof(overlayPackageStruct->name[0])]; 6777 strcpy16_dtoh(tmpName, overlayPackageStruct->name, sizeof(overlayPackageStruct->name)/sizeof(overlayPackageStruct->name[0])); 6778 const String16 overlayPackage(tmpName); 6779 6780 for (size_t typeIndex = 0; typeIndex < pg->types.size(); ++typeIndex) { 6781 const TypeList& typeList = pg->types[typeIndex]; 6782 if (typeList.isEmpty()) { 6783 continue; 6784 } 6785 6786 const Type* typeConfigs = typeList[0]; 6787 6788 IdmapTypeMap typeMap; 6789 typeMap.overlayTypeId = -1; 6790 typeMap.entryOffset = 0; 6791 6792 for (size_t entryIndex = 0; entryIndex < typeConfigs->entryCount; ++entryIndex) { 6793 uint32_t resID = Res_MAKEID(pg->id - 1, typeIndex, entryIndex); 6794 resource_name resName; 6795 if (!this->getResourceName(resID, false, &resName)) { 6796 if (typeMap.entryMap.isEmpty()) { 6797 typeMap.entryOffset++; 6798 } 6799 continue; 6800 } 6801 6802 const String16 overlayType(resName.type, resName.typeLen); 6803 const String16 overlayName(resName.name, resName.nameLen); 6804 uint32_t overlayResID = overlay.identifierForName(overlayName.string(), 6805 overlayName.size(), 6806 overlayType.string(), 6807 overlayType.size(), 6808 overlayPackage.string(), 6809 overlayPackage.size()); 6810 if (overlayResID == 0) { 6811 if (typeMap.entryMap.isEmpty()) { 6812 typeMap.entryOffset++; 6813 } 6814 continue; 6815 } 6816 6817 if (typeMap.overlayTypeId == -1) { 6818 typeMap.overlayTypeId = Res_GETTYPE(overlayResID) + 1; 6819 } 6820 6821 if (Res_GETTYPE(overlayResID) + 1 != static_cast<size_t>(typeMap.overlayTypeId)) { 6822 ALOGE("idmap: can't mix type ids in entry map. Resource 0x%08x maps to 0x%08x" 6823 " but entries should map to resources of type %02zx", 6824 resID, overlayResID, typeMap.overlayTypeId); 6825 return BAD_TYPE; 6826 } 6827 6828 if (typeMap.entryOffset + typeMap.entryMap.size() < entryIndex) { 6829 // pad with 0xffffffff's (indicating non-existing entries) before adding this entry 6830 size_t index = typeMap.entryMap.size(); 6831 size_t numItems = entryIndex - (typeMap.entryOffset + index); 6832 if (typeMap.entryMap.insertAt(0xffffffff, index, numItems) < 0) { 6833 return NO_MEMORY; 6834 } 6835 } 6836 typeMap.entryMap.add(Res_GETENTRY(overlayResID)); 6837 } 6838 6839 if (!typeMap.entryMap.isEmpty()) { 6840 if (map.add(static_cast<uint8_t>(typeIndex), typeMap) < 0) { 6841 return NO_MEMORY; 6842 } 6843 *outSize += (4 * sizeof(uint16_t)) + (typeMap.entryMap.size() * sizeof(uint32_t)); 6844 } 6845 } 6846 6847 if (map.isEmpty()) { 6848 ALOGW("idmap: no resources in overlay package present in base package"); 6849 return UNKNOWN_ERROR; 6850 } 6851 6852 if ((*outData = malloc(*outSize)) == NULL) { 6853 return NO_MEMORY; 6854 } 6855 6856 uint32_t* data = (uint32_t*)*outData; 6857 *data++ = htodl(IDMAP_MAGIC); 6858 *data++ = htodl(IDMAP_CURRENT_VERSION); 6859 *data++ = htodl(targetCrc); 6860 *data++ = htodl(overlayCrc); 6861 const char* paths[] = { targetPath, overlayPath }; 6862 for (int j = 0; j < 2; ++j) { 6863 char* p = (char*)data; 6864 const char* path = paths[j]; 6865 const size_t I = strlen(path); 6866 if (I > 255) { 6867 ALOGV("path exceeds expected 255 characters: %s\n", path); 6868 return UNKNOWN_ERROR; 6869 } 6870 for (size_t i = 0; i < 256; ++i) { 6871 *p++ = i < I ? path[i] : '\0'; 6872 } 6873 data += 256 / sizeof(uint32_t); 6874 } 6875 const size_t mapSize = map.size(); 6876 uint16_t* typeData = reinterpret_cast<uint16_t*>(data); 6877 *typeData++ = htods(pg->id); 6878 *typeData++ = htods(mapSize); 6879 for (size_t i = 0; i < mapSize; ++i) { 6880 uint8_t targetTypeId = map.keyAt(i); 6881 const IdmapTypeMap& typeMap = map[i]; 6882 *typeData++ = htods(targetTypeId + 1); 6883 *typeData++ = htods(typeMap.overlayTypeId); 6884 *typeData++ = htods(typeMap.entryMap.size()); 6885 *typeData++ = htods(typeMap.entryOffset); 6886 6887 const size_t entryCount = typeMap.entryMap.size(); 6888 uint32_t* entries = reinterpret_cast<uint32_t*>(typeData); 6889 for (size_t j = 0; j < entryCount; j++) { 6890 entries[j] = htodl(typeMap.entryMap[j]); 6891 } 6892 typeData += entryCount * 2; 6893 } 6894 6895 return NO_ERROR; 6896 } 6897 6898 bool ResTable::getIdmapInfo(const void* idmap, size_t sizeBytes, 6899 uint32_t* pVersion, 6900 uint32_t* pTargetCrc, uint32_t* pOverlayCrc, 6901 String8* pTargetPath, String8* pOverlayPath) 6902 { 6903 const uint32_t* map = (const uint32_t*)idmap; 6904 if (!assertIdmapHeader(map, sizeBytes)) { 6905 return false; 6906 } 6907 if (pVersion) { 6908 *pVersion = dtohl(map[1]); 6909 } 6910 if (pTargetCrc) { 6911 *pTargetCrc = dtohl(map[2]); 6912 } 6913 if (pOverlayCrc) { 6914 *pOverlayCrc = dtohl(map[3]); 6915 } 6916 if (pTargetPath) { 6917 pTargetPath->setTo(reinterpret_cast<const char*>(map + 4)); 6918 } 6919 if (pOverlayPath) { 6920 pOverlayPath->setTo(reinterpret_cast<const char*>(map + 4 + 256 / sizeof(uint32_t))); 6921 } 6922 return true; 6923 } 6924 6925 6926 #define CHAR16_TO_CSTR(c16, len) (String8(String16(c16,len)).string()) 6927 6928 #define CHAR16_ARRAY_EQ(constant, var, len) \ 6929 (((len) == (sizeof(constant)/sizeof((constant)[0]))) && (0 == memcmp((var), (constant), (len)))) 6930 6931 static void print_complex(uint32_t complex, bool isFraction) 6932 { 6933 const float MANTISSA_MULT = 6934 1.0f / (1<<Res_value::COMPLEX_MANTISSA_SHIFT); 6935 const float RADIX_MULTS[] = { 6936 1.0f*MANTISSA_MULT, 1.0f/(1<<7)*MANTISSA_MULT, 6937 1.0f/(1<<15)*MANTISSA_MULT, 1.0f/(1<<23)*MANTISSA_MULT 6938 }; 6939 6940 float value = (complex&(Res_value::COMPLEX_MANTISSA_MASK 6941 <<Res_value::COMPLEX_MANTISSA_SHIFT)) 6942 * RADIX_MULTS[(complex>>Res_value::COMPLEX_RADIX_SHIFT) 6943 & Res_value::COMPLEX_RADIX_MASK]; 6944 printf("%f", value); 6945 6946 if (!isFraction) { 6947 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) { 6948 case Res_value::COMPLEX_UNIT_PX: printf("px"); break; 6949 case Res_value::COMPLEX_UNIT_DIP: printf("dp"); break; 6950 case Res_value::COMPLEX_UNIT_SP: printf("sp"); break; 6951 case Res_value::COMPLEX_UNIT_PT: printf("pt"); break; 6952 case Res_value::COMPLEX_UNIT_IN: printf("in"); break; 6953 case Res_value::COMPLEX_UNIT_MM: printf("mm"); break; 6954 default: printf(" (unknown unit)"); break; 6955 } 6956 } else { 6957 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) { 6958 case Res_value::COMPLEX_UNIT_FRACTION: printf("%%"); break; 6959 case Res_value::COMPLEX_UNIT_FRACTION_PARENT: printf("%%p"); break; 6960 default: printf(" (unknown unit)"); break; 6961 } 6962 } 6963 } 6964 6965 // Normalize a string for output 6966 String8 ResTable::normalizeForOutput( const char *input ) 6967 { 6968 String8 ret; 6969 char buff[2]; 6970 buff[1] = '\0'; 6971 6972 while (*input != '\0') { 6973 switch (*input) { 6974 // All interesting characters are in the ASCII zone, so we are making our own lives 6975 // easier by scanning the string one byte at a time. 6976 case '\\': 6977 ret += "\\\\"; 6978 break; 6979 case '\n': 6980 ret += "\\n"; 6981 break; 6982 case '"': 6983 ret += "\\\""; 6984 break; 6985 default: 6986 buff[0] = *input; 6987 ret += buff; 6988 break; 6989 } 6990 6991 input++; 6992 } 6993 6994 return ret; 6995 } 6996 6997 void ResTable::print_value(const Package* pkg, const Res_value& value) const 6998 { 6999 if (value.dataType == Res_value::TYPE_NULL) { 7000 if (value.data == Res_value::DATA_NULL_UNDEFINED) { 7001 printf("(null)\n"); 7002 } else if (value.data == Res_value::DATA_NULL_EMPTY) { 7003 printf("(null empty)\n"); 7004 } else { 7005 // This should never happen. 7006 printf("(null) 0x%08x\n", value.data); 7007 } 7008 } else if (value.dataType == Res_value::TYPE_REFERENCE) { 7009 printf("(reference) 0x%08x\n", value.data); 7010 } else if (value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE) { 7011 printf("(dynamic reference) 0x%08x\n", value.data); 7012 } else if (value.dataType == Res_value::TYPE_ATTRIBUTE) { 7013 printf("(attribute) 0x%08x\n", value.data); 7014 } else if (value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE) { 7015 printf("(dynamic attribute) 0x%08x\n", value.data); 7016 } else if (value.dataType == Res_value::TYPE_STRING) { 7017 size_t len; 7018 const char* str8 = pkg->header->values.string8At( 7019 value.data, &len); 7020 if (str8 != NULL) { 7021 printf("(string8) \"%s\"\n", normalizeForOutput(str8).string()); 7022 } else { 7023 const char16_t* str16 = pkg->header->values.stringAt( 7024 value.data, &len); 7025 if (str16 != NULL) { 7026 printf("(string16) \"%s\"\n", 7027 normalizeForOutput(String8(str16, len).string()).string()); 7028 } else { 7029 printf("(string) null\n"); 7030 } 7031 } 7032 } else if (value.dataType == Res_value::TYPE_FLOAT) { 7033 printf("(float) %g\n", *(const float*)&value.data); 7034 } else if (value.dataType == Res_value::TYPE_DIMENSION) { 7035 printf("(dimension) "); 7036 print_complex(value.data, false); 7037 printf("\n"); 7038 } else if (value.dataType == Res_value::TYPE_FRACTION) { 7039 printf("(fraction) "); 7040 print_complex(value.data, true); 7041 printf("\n"); 7042 } else if (value.dataType >= Res_value::TYPE_FIRST_COLOR_INT 7043 || value.dataType <= Res_value::TYPE_LAST_COLOR_INT) { 7044 printf("(color) #%08x\n", value.data); 7045 } else if (value.dataType == Res_value::TYPE_INT_BOOLEAN) { 7046 printf("(boolean) %s\n", value.data ? "true" : "false"); 7047 } else if (value.dataType >= Res_value::TYPE_FIRST_INT 7048 || value.dataType <= Res_value::TYPE_LAST_INT) { 7049 printf("(int) 0x%08x or %d\n", value.data, value.data); 7050 } else { 7051 printf("(unknown type) t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)\n", 7052 (int)value.dataType, (int)value.data, 7053 (int)value.size, (int)value.res0); 7054 } 7055 } 7056 7057 void ResTable::print(bool inclValues) const 7058 { 7059 if (mError != 0) { 7060 printf("mError=0x%x (%s)\n", mError, strerror(mError)); 7061 } 7062 size_t pgCount = mPackageGroups.size(); 7063 printf("Package Groups (%d)\n", (int)pgCount); 7064 for (size_t pgIndex=0; pgIndex<pgCount; pgIndex++) { 7065 const PackageGroup* pg = mPackageGroups[pgIndex]; 7066 printf("Package Group %d id=0x%02x packageCount=%d name=%s\n", 7067 (int)pgIndex, pg->id, (int)pg->packages.size(), 7068 String8(pg->name).string()); 7069 7070 const KeyedVector<String16, uint8_t>& refEntries = pg->dynamicRefTable.entries(); 7071 const size_t refEntryCount = refEntries.size(); 7072 if (refEntryCount > 0) { 7073 printf(" DynamicRefTable entryCount=%d:\n", (int) refEntryCount); 7074 for (size_t refIndex = 0; refIndex < refEntryCount; refIndex++) { 7075 printf(" 0x%02x -> %s\n", 7076 refEntries.valueAt(refIndex), 7077 String8(refEntries.keyAt(refIndex)).string()); 7078 } 7079 printf("\n"); 7080 } 7081 7082 int packageId = pg->id; 7083 size_t pkgCount = pg->packages.size(); 7084 for (size_t pkgIndex=0; pkgIndex<pkgCount; pkgIndex++) { 7085 const Package* pkg = pg->packages[pkgIndex]; 7086 // Use a package's real ID, since the ID may have been assigned 7087 // if this package is a shared library. 7088 packageId = pkg->package->id; 7089 char16_t tmpName[sizeof(pkg->package->name)/sizeof(pkg->package->name[0])]; 7090 strcpy16_dtoh(tmpName, pkg->package->name, sizeof(pkg->package->name)/sizeof(pkg->package->name[0])); 7091 printf(" Package %d id=0x%02x name=%s\n", (int)pkgIndex, 7092 pkg->package->id, String8(tmpName).string()); 7093 } 7094 7095 for (size_t typeIndex=0; typeIndex < pg->types.size(); typeIndex++) { 7096 const TypeList& typeList = pg->types[typeIndex]; 7097 if (typeList.isEmpty()) { 7098 continue; 7099 } 7100 const Type* typeConfigs = typeList[0]; 7101 const size_t NTC = typeConfigs->configs.size(); 7102 printf(" type %d configCount=%d entryCount=%d\n", 7103 (int)typeIndex, (int)NTC, (int)typeConfigs->entryCount); 7104 if (typeConfigs->typeSpecFlags != NULL) { 7105 for (size_t entryIndex=0; entryIndex<typeConfigs->entryCount; entryIndex++) { 7106 uint32_t resID = (0xff000000 & ((packageId)<<24)) 7107 | (0x00ff0000 & ((typeIndex+1)<<16)) 7108 | (0x0000ffff & (entryIndex)); 7109 // Since we are creating resID without actually 7110 // iterating over them, we have no idea which is a 7111 // dynamic reference. We must check. 7112 if (packageId == 0) { 7113 pg->dynamicRefTable.lookupResourceId(&resID); 7114 } 7115 7116 resource_name resName; 7117 if (this->getResourceName(resID, true, &resName)) { 7118 String8 type8; 7119 String8 name8; 7120 if (resName.type8 != NULL) { 7121 type8 = String8(resName.type8, resName.typeLen); 7122 } else { 7123 type8 = String8(resName.type, resName.typeLen); 7124 } 7125 if (resName.name8 != NULL) { 7126 name8 = String8(resName.name8, resName.nameLen); 7127 } else { 7128 name8 = String8(resName.name, resName.nameLen); 7129 } 7130 printf(" spec resource 0x%08x %s:%s/%s: flags=0x%08x\n", 7131 resID, 7132 CHAR16_TO_CSTR(resName.package, resName.packageLen), 7133 type8.string(), name8.string(), 7134 dtohl(typeConfigs->typeSpecFlags[entryIndex])); 7135 } else { 7136 printf(" INVALID TYPE CONFIG FOR RESOURCE 0x%08x\n", resID); 7137 } 7138 } 7139 } 7140 for (size_t configIndex=0; configIndex<NTC; configIndex++) { 7141 const ResTable_type* type = typeConfigs->configs[configIndex]; 7142 if ((((uint64_t)type)&0x3) != 0) { 7143 printf(" NON-INTEGER ResTable_type ADDRESS: %p\n", type); 7144 continue; 7145 } 7146 7147 // Always copy the config, as fields get added and we need to 7148 // set the defaults. 7149 ResTable_config thisConfig; 7150 thisConfig.copyFromDtoH(type->config); 7151 7152 String8 configStr = thisConfig.toString(); 7153 printf(" config %s", configStr.size() > 0 7154 ? configStr.string() : "(default)"); 7155 if (type->flags != 0u) { 7156 printf(" flags=0x%02x", type->flags); 7157 if (type->flags & ResTable_type::FLAG_SPARSE) { 7158 printf(" [sparse]"); 7159 } 7160 } 7161 7162 printf(":\n"); 7163 7164 size_t entryCount = dtohl(type->entryCount); 7165 uint32_t entriesStart = dtohl(type->entriesStart); 7166 if ((entriesStart&0x3) != 0) { 7167 printf(" NON-INTEGER ResTable_type entriesStart OFFSET: 0x%x\n", entriesStart); 7168 continue; 7169 } 7170 uint32_t typeSize = dtohl(type->header.size); 7171 if ((typeSize&0x3) != 0) { 7172 printf(" NON-INTEGER ResTable_type header.size: 0x%x\n", typeSize); 7173 continue; 7174 } 7175 7176 const uint32_t* const eindex = (const uint32_t*) 7177 (((const uint8_t*)type) + dtohs(type->header.headerSize)); 7178 for (size_t entryIndex=0; entryIndex<entryCount; entryIndex++) { 7179 size_t entryId; 7180 uint32_t thisOffset; 7181 if (type->flags & ResTable_type::FLAG_SPARSE) { 7182 const ResTable_sparseTypeEntry* entry = 7183 reinterpret_cast<const ResTable_sparseTypeEntry*>( 7184 eindex + entryIndex); 7185 entryId = dtohs(entry->idx); 7186 // Offsets are encoded as divided by 4. 7187 thisOffset = static_cast<uint32_t>(dtohs(entry->offset)) * 4u; 7188 } else { 7189 entryId = entryIndex; 7190 thisOffset = dtohl(eindex[entryIndex]); 7191 if (thisOffset == ResTable_type::NO_ENTRY) { 7192 continue; 7193 } 7194 } 7195 7196 uint32_t resID = (0xff000000 & ((packageId)<<24)) 7197 | (0x00ff0000 & ((typeIndex+1)<<16)) 7198 | (0x0000ffff & (entryId)); 7199 if (packageId == 0) { 7200 pg->dynamicRefTable.lookupResourceId(&resID); 7201 } 7202 resource_name resName; 7203 if (this->getResourceName(resID, true, &resName)) { 7204 String8 type8; 7205 String8 name8; 7206 if (resName.type8 != NULL) { 7207 type8 = String8(resName.type8, resName.typeLen); 7208 } else { 7209 type8 = String8(resName.type, resName.typeLen); 7210 } 7211 if (resName.name8 != NULL) { 7212 name8 = String8(resName.name8, resName.nameLen); 7213 } else { 7214 name8 = String8(resName.name, resName.nameLen); 7215 } 7216 printf(" resource 0x%08x %s:%s/%s: ", resID, 7217 CHAR16_TO_CSTR(resName.package, resName.packageLen), 7218 type8.string(), name8.string()); 7219 } else { 7220 printf(" INVALID RESOURCE 0x%08x: ", resID); 7221 } 7222 if ((thisOffset&0x3) != 0) { 7223 printf("NON-INTEGER OFFSET: 0x%x\n", thisOffset); 7224 continue; 7225 } 7226 if ((thisOffset+sizeof(ResTable_entry)) > typeSize) { 7227 printf("OFFSET OUT OF BOUNDS: 0x%x+0x%x (size is 0x%x)\n", 7228 entriesStart, thisOffset, typeSize); 7229 continue; 7230 } 7231 7232 const ResTable_entry* ent = (const ResTable_entry*) 7233 (((const uint8_t*)type) + entriesStart + thisOffset); 7234 if (((entriesStart + thisOffset)&0x3) != 0) { 7235 printf("NON-INTEGER ResTable_entry OFFSET: 0x%x\n", 7236 (entriesStart + thisOffset)); 7237 continue; 7238 } 7239 7240 uintptr_t esize = dtohs(ent->size); 7241 if ((esize&0x3) != 0) { 7242 printf("NON-INTEGER ResTable_entry SIZE: %p\n", (void *)esize); 7243 continue; 7244 } 7245 if ((thisOffset+esize) > typeSize) { 7246 printf("ResTable_entry OUT OF BOUNDS: 0x%x+0x%x+%p (size is 0x%x)\n", 7247 entriesStart, thisOffset, (void *)esize, typeSize); 7248 continue; 7249 } 7250 7251 const Res_value* valuePtr = NULL; 7252 const ResTable_map_entry* bagPtr = NULL; 7253 Res_value value; 7254 if ((dtohs(ent->flags)&ResTable_entry::FLAG_COMPLEX) != 0) { 7255 printf("<bag>"); 7256 bagPtr = (const ResTable_map_entry*)ent; 7257 } else { 7258 valuePtr = (const Res_value*) 7259 (((const uint8_t*)ent) + esize); 7260 value.copyFrom_dtoh(*valuePtr); 7261 printf("t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)", 7262 (int)value.dataType, (int)value.data, 7263 (int)value.size, (int)value.res0); 7264 } 7265 7266 if ((dtohs(ent->flags)&ResTable_entry::FLAG_PUBLIC) != 0) { 7267 printf(" (PUBLIC)"); 7268 } 7269 printf("\n"); 7270 7271 if (inclValues) { 7272 if (valuePtr != NULL) { 7273 printf(" "); 7274 print_value(typeConfigs->package, value); 7275 } else if (bagPtr != NULL) { 7276 const int N = dtohl(bagPtr->count); 7277 const uint8_t* baseMapPtr = (const uint8_t*)ent; 7278 size_t mapOffset = esize; 7279 const ResTable_map* mapPtr = (ResTable_map*)(baseMapPtr+mapOffset); 7280 const uint32_t parent = dtohl(bagPtr->parent.ident); 7281 uint32_t resolvedParent = parent; 7282 if (Res_GETPACKAGE(resolvedParent) + 1 == 0) { 7283 status_t err = pg->dynamicRefTable.lookupResourceId(&resolvedParent); 7284 if (err != NO_ERROR) { 7285 resolvedParent = 0; 7286 } 7287 } 7288 printf(" Parent=0x%08x(Resolved=0x%08x), Count=%d\n", 7289 parent, resolvedParent, N); 7290 for (int i=0; i<N && mapOffset < (typeSize-sizeof(ResTable_map)); i++) { 7291 printf(" #%i (Key=0x%08x): ", 7292 i, dtohl(mapPtr->name.ident)); 7293 value.copyFrom_dtoh(mapPtr->value); 7294 print_value(typeConfigs->package, value); 7295 const size_t size = dtohs(mapPtr->value.size); 7296 mapOffset += size + sizeof(*mapPtr)-sizeof(mapPtr->value); 7297 mapPtr = (ResTable_map*)(baseMapPtr+mapOffset); 7298 } 7299 } 7300 } 7301 } 7302 } 7303 } 7304 } 7305 } 7306 7307 } // namespace android 7308