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