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