ResourceTypes.cpp revision 1a6acdbb86c3e72bdb0a4dcab3bda58cbc4ea34c
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 case ResTable_config::UI_MODE_TYPE_VR_HEADSET: 2998 res.append("vrheadset"); 2999 break; 3000 default: 3001 res.appendFormat("uiModeType=%d", 3002 dtohs(screenLayout&ResTable_config::MASK_UI_MODE_TYPE)); 3003 break; 3004 } 3005 } 3006 if ((uiMode&MASK_UI_MODE_NIGHT) != 0) { 3007 if (res.size() > 0) res.append("-"); 3008 switch (uiMode&ResTable_config::MASK_UI_MODE_NIGHT) { 3009 case ResTable_config::UI_MODE_NIGHT_NO: 3010 res.append("notnight"); 3011 break; 3012 case ResTable_config::UI_MODE_NIGHT_YES: 3013 res.append("night"); 3014 break; 3015 default: 3016 res.appendFormat("uiModeNight=%d", 3017 dtohs(uiMode&MASK_UI_MODE_NIGHT)); 3018 break; 3019 } 3020 } 3021 if (density != DENSITY_DEFAULT) { 3022 if (res.size() > 0) res.append("-"); 3023 switch (density) { 3024 case ResTable_config::DENSITY_LOW: 3025 res.append("ldpi"); 3026 break; 3027 case ResTable_config::DENSITY_MEDIUM: 3028 res.append("mdpi"); 3029 break; 3030 case ResTable_config::DENSITY_TV: 3031 res.append("tvdpi"); 3032 break; 3033 case ResTable_config::DENSITY_HIGH: 3034 res.append("hdpi"); 3035 break; 3036 case ResTable_config::DENSITY_XHIGH: 3037 res.append("xhdpi"); 3038 break; 3039 case ResTable_config::DENSITY_XXHIGH: 3040 res.append("xxhdpi"); 3041 break; 3042 case ResTable_config::DENSITY_XXXHIGH: 3043 res.append("xxxhdpi"); 3044 break; 3045 case ResTable_config::DENSITY_NONE: 3046 res.append("nodpi"); 3047 break; 3048 case ResTable_config::DENSITY_ANY: 3049 res.append("anydpi"); 3050 break; 3051 default: 3052 res.appendFormat("%ddpi", dtohs(density)); 3053 break; 3054 } 3055 } 3056 if (touchscreen != TOUCHSCREEN_ANY) { 3057 if (res.size() > 0) res.append("-"); 3058 switch (touchscreen) { 3059 case ResTable_config::TOUCHSCREEN_NOTOUCH: 3060 res.append("notouch"); 3061 break; 3062 case ResTable_config::TOUCHSCREEN_FINGER: 3063 res.append("finger"); 3064 break; 3065 case ResTable_config::TOUCHSCREEN_STYLUS: 3066 res.append("stylus"); 3067 break; 3068 default: 3069 res.appendFormat("touchscreen=%d", dtohs(touchscreen)); 3070 break; 3071 } 3072 } 3073 if ((inputFlags&MASK_KEYSHIDDEN) != 0) { 3074 if (res.size() > 0) res.append("-"); 3075 switch (inputFlags&MASK_KEYSHIDDEN) { 3076 case ResTable_config::KEYSHIDDEN_NO: 3077 res.append("keysexposed"); 3078 break; 3079 case ResTable_config::KEYSHIDDEN_YES: 3080 res.append("keyshidden"); 3081 break; 3082 case ResTable_config::KEYSHIDDEN_SOFT: 3083 res.append("keyssoft"); 3084 break; 3085 } 3086 } 3087 if (keyboard != KEYBOARD_ANY) { 3088 if (res.size() > 0) res.append("-"); 3089 switch (keyboard) { 3090 case ResTable_config::KEYBOARD_NOKEYS: 3091 res.append("nokeys"); 3092 break; 3093 case ResTable_config::KEYBOARD_QWERTY: 3094 res.append("qwerty"); 3095 break; 3096 case ResTable_config::KEYBOARD_12KEY: 3097 res.append("12key"); 3098 break; 3099 default: 3100 res.appendFormat("keyboard=%d", dtohs(keyboard)); 3101 break; 3102 } 3103 } 3104 if ((inputFlags&MASK_NAVHIDDEN) != 0) { 3105 if (res.size() > 0) res.append("-"); 3106 switch (inputFlags&MASK_NAVHIDDEN) { 3107 case ResTable_config::NAVHIDDEN_NO: 3108 res.append("navexposed"); 3109 break; 3110 case ResTable_config::NAVHIDDEN_YES: 3111 res.append("navhidden"); 3112 break; 3113 default: 3114 res.appendFormat("inputFlagsNavHidden=%d", 3115 dtohs(inputFlags&MASK_NAVHIDDEN)); 3116 break; 3117 } 3118 } 3119 if (navigation != NAVIGATION_ANY) { 3120 if (res.size() > 0) res.append("-"); 3121 switch (navigation) { 3122 case ResTable_config::NAVIGATION_NONAV: 3123 res.append("nonav"); 3124 break; 3125 case ResTable_config::NAVIGATION_DPAD: 3126 res.append("dpad"); 3127 break; 3128 case ResTable_config::NAVIGATION_TRACKBALL: 3129 res.append("trackball"); 3130 break; 3131 case ResTable_config::NAVIGATION_WHEEL: 3132 res.append("wheel"); 3133 break; 3134 default: 3135 res.appendFormat("navigation=%d", dtohs(navigation)); 3136 break; 3137 } 3138 } 3139 if (screenSize != 0) { 3140 if (res.size() > 0) res.append("-"); 3141 res.appendFormat("%dx%d", dtohs(screenWidth), dtohs(screenHeight)); 3142 } 3143 if (version != 0) { 3144 if (res.size() > 0) res.append("-"); 3145 res.appendFormat("v%d", dtohs(sdkVersion)); 3146 if (minorVersion != 0) { 3147 res.appendFormat(".%d", dtohs(minorVersion)); 3148 } 3149 } 3150 3151 return res; 3152} 3153 3154// -------------------------------------------------------------------- 3155// -------------------------------------------------------------------- 3156// -------------------------------------------------------------------- 3157 3158struct ResTable::Header 3159{ 3160 explicit Header(ResTable* _owner) : owner(_owner), ownedData(NULL), header(NULL), 3161 resourceIDMap(NULL), resourceIDMapSize(0) { } 3162 3163 ~Header() 3164 { 3165 free(resourceIDMap); 3166 } 3167 3168 const ResTable* const owner; 3169 void* ownedData; 3170 const ResTable_header* header; 3171 size_t size; 3172 const uint8_t* dataEnd; 3173 size_t index; 3174 int32_t cookie; 3175 3176 ResStringPool values; 3177 uint32_t* resourceIDMap; 3178 size_t resourceIDMapSize; 3179}; 3180 3181struct ResTable::Entry { 3182 ResTable_config config; 3183 const ResTable_entry* entry; 3184 const ResTable_type* type; 3185 uint32_t specFlags; 3186 const Package* package; 3187 3188 StringPoolRef typeStr; 3189 StringPoolRef keyStr; 3190}; 3191 3192struct ResTable::Type 3193{ 3194 Type(const Header* _header, const Package* _package, size_t count) 3195 : header(_header), package(_package), entryCount(count), 3196 typeSpec(NULL), typeSpecFlags(NULL) { } 3197 const Header* const header; 3198 const Package* const package; 3199 const size_t entryCount; 3200 const ResTable_typeSpec* typeSpec; 3201 const uint32_t* typeSpecFlags; 3202 IdmapEntries idmapEntries; 3203 Vector<const ResTable_type*> configs; 3204}; 3205 3206struct ResTable::Package 3207{ 3208 Package(ResTable* _owner, const Header* _header, const ResTable_package* _package) 3209 : owner(_owner), header(_header), package(_package), typeIdOffset(0) { 3210 if (dtohs(package->header.headerSize) == sizeof(*package)) { 3211 // The package structure is the same size as the definition. 3212 // This means it contains the typeIdOffset field. 3213 typeIdOffset = package->typeIdOffset; 3214 } 3215 } 3216 3217 const ResTable* const owner; 3218 const Header* const header; 3219 const ResTable_package* const package; 3220 3221 ResStringPool typeStrings; 3222 ResStringPool keyStrings; 3223 3224 size_t typeIdOffset; 3225}; 3226 3227// A group of objects describing a particular resource package. 3228// The first in 'package' is always the root object (from the resource 3229// table that defined the package); the ones after are skins on top of it. 3230struct ResTable::PackageGroup 3231{ 3232 PackageGroup( 3233 ResTable* _owner, const String16& _name, uint32_t _id, 3234 bool appAsLib, bool _isSystemAsset) 3235 : owner(_owner) 3236 , name(_name) 3237 , id(_id) 3238 , largestTypeId(0) 3239 , dynamicRefTable(static_cast<uint8_t>(_id), appAsLib) 3240 , isSystemAsset(_isSystemAsset) 3241 { } 3242 3243 ~PackageGroup() { 3244 clearBagCache(); 3245 const size_t numTypes = types.size(); 3246 for (size_t i = 0; i < numTypes; i++) { 3247 const TypeList& typeList = types[i]; 3248 const size_t numInnerTypes = typeList.size(); 3249 for (size_t j = 0; j < numInnerTypes; j++) { 3250 if (typeList[j]->package->owner == owner) { 3251 delete typeList[j]; 3252 } 3253 } 3254 } 3255 3256 const size_t N = packages.size(); 3257 for (size_t i=0; i<N; i++) { 3258 Package* pkg = packages[i]; 3259 if (pkg->owner == owner) { 3260 delete pkg; 3261 } 3262 } 3263 } 3264 3265 /** 3266 * Clear all cache related data that depends on parameters/configuration. 3267 * This includes the bag caches and filtered types. 3268 */ 3269 void clearBagCache() { 3270 for (size_t i = 0; i < typeCacheEntries.size(); i++) { 3271 if (kDebugTableNoisy) { 3272 printf("type=%zu\n", i); 3273 } 3274 const TypeList& typeList = types[i]; 3275 if (!typeList.isEmpty()) { 3276 TypeCacheEntry& cacheEntry = typeCacheEntries.editItemAt(i); 3277 3278 // Reset the filtered configurations. 3279 cacheEntry.filteredConfigs.clear(); 3280 3281 bag_set** typeBags = cacheEntry.cachedBags; 3282 if (kDebugTableNoisy) { 3283 printf("typeBags=%p\n", typeBags); 3284 } 3285 3286 if (typeBags) { 3287 const size_t N = typeList[0]->entryCount; 3288 if (kDebugTableNoisy) { 3289 printf("type->entryCount=%zu\n", N); 3290 } 3291 for (size_t j = 0; j < N; j++) { 3292 if (typeBags[j] && typeBags[j] != (bag_set*)0xFFFFFFFF) { 3293 free(typeBags[j]); 3294 } 3295 } 3296 free(typeBags); 3297 cacheEntry.cachedBags = NULL; 3298 } 3299 } 3300 } 3301 } 3302 3303 ssize_t findType16(const char16_t* type, size_t len) const { 3304 const size_t N = packages.size(); 3305 for (size_t i = 0; i < N; i++) { 3306 ssize_t index = packages[i]->typeStrings.indexOfString(type, len); 3307 if (index >= 0) { 3308 return index + packages[i]->typeIdOffset; 3309 } 3310 } 3311 return -1; 3312 } 3313 3314 const ResTable* const owner; 3315 String16 const name; 3316 uint32_t const id; 3317 3318 // This is mainly used to keep track of the loaded packages 3319 // and to clean them up properly. Accessing resources happens from 3320 // the 'types' array. 3321 Vector<Package*> packages; 3322 3323 ByteBucketArray<TypeList> types; 3324 3325 uint8_t largestTypeId; 3326 3327 // Cached objects dependent on the parameters/configuration of this ResTable. 3328 // Gets cleared whenever the parameters/configuration changes. 3329 // These are stored here in a parallel structure because the data in `types` may 3330 // be shared by other ResTable's (framework resources are shared this way). 3331 ByteBucketArray<TypeCacheEntry> typeCacheEntries; 3332 3333 // The table mapping dynamic references to resolved references for 3334 // this package group. 3335 // TODO: We may be able to support dynamic references in overlays 3336 // by having these tables in a per-package scope rather than 3337 // per-package-group. 3338 DynamicRefTable dynamicRefTable; 3339 3340 // If the package group comes from a system asset. Used in 3341 // determining non-system locales. 3342 const bool isSystemAsset; 3343}; 3344 3345ResTable::Theme::Theme(const ResTable& table) 3346 : mTable(table) 3347 , mTypeSpecFlags(0) 3348{ 3349 memset(mPackages, 0, sizeof(mPackages)); 3350} 3351 3352ResTable::Theme::~Theme() 3353{ 3354 for (size_t i=0; i<Res_MAXPACKAGE; i++) { 3355 package_info* pi = mPackages[i]; 3356 if (pi != NULL) { 3357 free_package(pi); 3358 } 3359 } 3360} 3361 3362void ResTable::Theme::free_package(package_info* pi) 3363{ 3364 for (size_t j = 0; j <= Res_MAXTYPE; j++) { 3365 theme_entry* te = pi->types[j].entries; 3366 if (te != NULL) { 3367 free(te); 3368 } 3369 } 3370 free(pi); 3371} 3372 3373ResTable::Theme::package_info* ResTable::Theme::copy_package(package_info* pi) 3374{ 3375 package_info* newpi = (package_info*)malloc(sizeof(package_info)); 3376 for (size_t j = 0; j <= Res_MAXTYPE; j++) { 3377 size_t cnt = pi->types[j].numEntries; 3378 newpi->types[j].numEntries = cnt; 3379 theme_entry* te = pi->types[j].entries; 3380 size_t cnt_max = SIZE_MAX / sizeof(theme_entry); 3381 if (te != NULL && (cnt < 0xFFFFFFFF-1) && (cnt < cnt_max)) { 3382 theme_entry* newte = (theme_entry*)malloc(cnt*sizeof(theme_entry)); 3383 newpi->types[j].entries = newte; 3384 memcpy(newte, te, cnt*sizeof(theme_entry)); 3385 } else { 3386 newpi->types[j].entries = NULL; 3387 } 3388 } 3389 return newpi; 3390} 3391 3392status_t ResTable::Theme::applyStyle(uint32_t resID, bool force) 3393{ 3394 const bag_entry* bag; 3395 uint32_t bagTypeSpecFlags = 0; 3396 mTable.lock(); 3397 const ssize_t N = mTable.getBagLocked(resID, &bag, &bagTypeSpecFlags); 3398 if (kDebugTableNoisy) { 3399 ALOGV("Applying style 0x%08x to theme %p, count=%zu", resID, this, N); 3400 } 3401 if (N < 0) { 3402 mTable.unlock(); 3403 return N; 3404 } 3405 3406 mTypeSpecFlags |= bagTypeSpecFlags; 3407 3408 uint32_t curPackage = 0xffffffff; 3409 ssize_t curPackageIndex = 0; 3410 package_info* curPI = NULL; 3411 uint32_t curType = 0xffffffff; 3412 size_t numEntries = 0; 3413 theme_entry* curEntries = NULL; 3414 3415 const bag_entry* end = bag + N; 3416 while (bag < end) { 3417 const uint32_t attrRes = bag->map.name.ident; 3418 const uint32_t p = Res_GETPACKAGE(attrRes); 3419 const uint32_t t = Res_GETTYPE(attrRes); 3420 const uint32_t e = Res_GETENTRY(attrRes); 3421 3422 if (curPackage != p) { 3423 const ssize_t pidx = mTable.getResourcePackageIndex(attrRes); 3424 if (pidx < 0) { 3425 ALOGE("Style contains key with bad package: 0x%08x\n", attrRes); 3426 bag++; 3427 continue; 3428 } 3429 curPackage = p; 3430 curPackageIndex = pidx; 3431 curPI = mPackages[pidx]; 3432 if (curPI == NULL) { 3433 curPI = (package_info*)malloc(sizeof(package_info)); 3434 memset(curPI, 0, sizeof(*curPI)); 3435 mPackages[pidx] = curPI; 3436 } 3437 curType = 0xffffffff; 3438 } 3439 if (curType != t) { 3440 if (t > Res_MAXTYPE) { 3441 ALOGE("Style contains key with bad type: 0x%08x\n", attrRes); 3442 bag++; 3443 continue; 3444 } 3445 curType = t; 3446 curEntries = curPI->types[t].entries; 3447 if (curEntries == NULL) { 3448 PackageGroup* const grp = mTable.mPackageGroups[curPackageIndex]; 3449 const TypeList& typeList = grp->types[t]; 3450 size_t cnt = typeList.isEmpty() ? 0 : typeList[0]->entryCount; 3451 size_t cnt_max = SIZE_MAX / sizeof(theme_entry); 3452 size_t buff_size = (cnt < cnt_max && cnt < 0xFFFFFFFF-1) ? 3453 cnt*sizeof(theme_entry) : 0; 3454 curEntries = (theme_entry*)malloc(buff_size); 3455 memset(curEntries, Res_value::TYPE_NULL, buff_size); 3456 curPI->types[t].numEntries = cnt; 3457 curPI->types[t].entries = curEntries; 3458 } 3459 numEntries = curPI->types[t].numEntries; 3460 } 3461 if (e >= numEntries) { 3462 ALOGE("Style contains key with bad entry: 0x%08x\n", attrRes); 3463 bag++; 3464 continue; 3465 } 3466 theme_entry* curEntry = curEntries + e; 3467 if (kDebugTableNoisy) { 3468 ALOGV("Attr 0x%08x: type=0x%x, data=0x%08x; curType=0x%x", 3469 attrRes, bag->map.value.dataType, bag->map.value.data, 3470 curEntry->value.dataType); 3471 } 3472 if (force || curEntry->value.dataType == Res_value::TYPE_NULL) { 3473 curEntry->stringBlock = bag->stringBlock; 3474 curEntry->typeSpecFlags |= bagTypeSpecFlags; 3475 curEntry->value = bag->map.value; 3476 } 3477 3478 bag++; 3479 } 3480 3481 mTable.unlock(); 3482 3483 if (kDebugTableTheme) { 3484 ALOGI("Applying style 0x%08x (force=%d) theme %p...\n", resID, force, this); 3485 dumpToLog(); 3486 } 3487 3488 return NO_ERROR; 3489} 3490 3491status_t ResTable::Theme::setTo(const Theme& other) 3492{ 3493 if (kDebugTableTheme) { 3494 ALOGI("Setting theme %p from theme %p...\n", this, &other); 3495 dumpToLog(); 3496 other.dumpToLog(); 3497 } 3498 3499 if (&mTable == &other.mTable) { 3500 for (size_t i=0; i<Res_MAXPACKAGE; i++) { 3501 if (mPackages[i] != NULL) { 3502 free_package(mPackages[i]); 3503 } 3504 if (other.mPackages[i] != NULL) { 3505 mPackages[i] = copy_package(other.mPackages[i]); 3506 } else { 3507 mPackages[i] = NULL; 3508 } 3509 } 3510 } else { 3511 // @todo: need to really implement this, not just copy 3512 // the system package (which is still wrong because it isn't 3513 // fixing up resource references). 3514 for (size_t i=0; i<Res_MAXPACKAGE; i++) { 3515 if (mPackages[i] != NULL) { 3516 free_package(mPackages[i]); 3517 } 3518 if (i == 0 && other.mPackages[i] != NULL) { 3519 mPackages[i] = copy_package(other.mPackages[i]); 3520 } else { 3521 mPackages[i] = NULL; 3522 } 3523 } 3524 } 3525 3526 mTypeSpecFlags = other.mTypeSpecFlags; 3527 3528 if (kDebugTableTheme) { 3529 ALOGI("Final theme:"); 3530 dumpToLog(); 3531 } 3532 3533 return NO_ERROR; 3534} 3535 3536status_t ResTable::Theme::clear() 3537{ 3538 if (kDebugTableTheme) { 3539 ALOGI("Clearing theme %p...\n", this); 3540 dumpToLog(); 3541 } 3542 3543 for (size_t i = 0; i < Res_MAXPACKAGE; i++) { 3544 if (mPackages[i] != NULL) { 3545 free_package(mPackages[i]); 3546 mPackages[i] = NULL; 3547 } 3548 } 3549 3550 mTypeSpecFlags = 0; 3551 3552 if (kDebugTableTheme) { 3553 ALOGI("Final theme:"); 3554 dumpToLog(); 3555 } 3556 3557 return NO_ERROR; 3558} 3559 3560ssize_t ResTable::Theme::getAttribute(uint32_t resID, Res_value* outValue, 3561 uint32_t* outTypeSpecFlags) const 3562{ 3563 int cnt = 20; 3564 3565 if (outTypeSpecFlags != NULL) *outTypeSpecFlags = 0; 3566 3567 do { 3568 const ssize_t p = mTable.getResourcePackageIndex(resID); 3569 const uint32_t t = Res_GETTYPE(resID); 3570 const uint32_t e = Res_GETENTRY(resID); 3571 3572 if (kDebugTableTheme) { 3573 ALOGI("Looking up attr 0x%08x in theme %p", resID, this); 3574 } 3575 3576 if (p >= 0) { 3577 const package_info* const pi = mPackages[p]; 3578 if (kDebugTableTheme) { 3579 ALOGI("Found package: %p", pi); 3580 } 3581 if (pi != NULL) { 3582 if (kDebugTableTheme) { 3583 ALOGI("Desired type index is %u in avail %zu", t, Res_MAXTYPE + 1); 3584 } 3585 if (t <= Res_MAXTYPE) { 3586 const type_info& ti = pi->types[t]; 3587 if (kDebugTableTheme) { 3588 ALOGI("Desired entry index is %u in avail %zu", e, ti.numEntries); 3589 } 3590 if (e < ti.numEntries) { 3591 const theme_entry& te = ti.entries[e]; 3592 if (outTypeSpecFlags != NULL) { 3593 *outTypeSpecFlags |= te.typeSpecFlags; 3594 } 3595 if (kDebugTableTheme) { 3596 ALOGI("Theme value: type=0x%x, data=0x%08x", 3597 te.value.dataType, te.value.data); 3598 } 3599 const uint8_t type = te.value.dataType; 3600 if (type == Res_value::TYPE_ATTRIBUTE) { 3601 if (cnt > 0) { 3602 cnt--; 3603 resID = te.value.data; 3604 continue; 3605 } 3606 ALOGW("Too many attribute references, stopped at: 0x%08x\n", resID); 3607 return BAD_INDEX; 3608 } else if (type != Res_value::TYPE_NULL) { 3609 *outValue = te.value; 3610 return te.stringBlock; 3611 } 3612 return BAD_INDEX; 3613 } 3614 } 3615 } 3616 } 3617 break; 3618 3619 } while (true); 3620 3621 return BAD_INDEX; 3622} 3623 3624ssize_t ResTable::Theme::resolveAttributeReference(Res_value* inOutValue, 3625 ssize_t blockIndex, uint32_t* outLastRef, 3626 uint32_t* inoutTypeSpecFlags, ResTable_config* inoutConfig) const 3627{ 3628 //printf("Resolving type=0x%x\n", inOutValue->dataType); 3629 if (inOutValue->dataType == Res_value::TYPE_ATTRIBUTE) { 3630 uint32_t newTypeSpecFlags; 3631 blockIndex = getAttribute(inOutValue->data, inOutValue, &newTypeSpecFlags); 3632 if (kDebugTableTheme) { 3633 ALOGI("Resolving attr reference: blockIndex=%d, type=0x%x, data=0x%x\n", 3634 (int)blockIndex, (int)inOutValue->dataType, inOutValue->data); 3635 } 3636 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newTypeSpecFlags; 3637 //printf("Retrieved attribute new type=0x%x\n", inOutValue->dataType); 3638 if (blockIndex < 0) { 3639 return blockIndex; 3640 } 3641 } 3642 return mTable.resolveReference(inOutValue, blockIndex, outLastRef, 3643 inoutTypeSpecFlags, inoutConfig); 3644} 3645 3646uint32_t ResTable::Theme::getChangingConfigurations() const 3647{ 3648 return mTypeSpecFlags; 3649} 3650 3651void ResTable::Theme::dumpToLog() const 3652{ 3653 ALOGI("Theme %p:\n", this); 3654 for (size_t i=0; i<Res_MAXPACKAGE; i++) { 3655 package_info* pi = mPackages[i]; 3656 if (pi == NULL) continue; 3657 3658 ALOGI(" Package #0x%02x:\n", (int)(i + 1)); 3659 for (size_t j = 0; j <= Res_MAXTYPE; j++) { 3660 type_info& ti = pi->types[j]; 3661 if (ti.numEntries == 0) continue; 3662 ALOGI(" Type #0x%02x:\n", (int)(j + 1)); 3663 for (size_t k = 0; k < ti.numEntries; k++) { 3664 const theme_entry& te = ti.entries[k]; 3665 if (te.value.dataType == Res_value::TYPE_NULL) continue; 3666 ALOGI(" 0x%08x: t=0x%x, d=0x%08x (block=%d)\n", 3667 (int)Res_MAKEID(i, j, k), 3668 te.value.dataType, (int)te.value.data, (int)te.stringBlock); 3669 } 3670 } 3671 } 3672} 3673 3674ResTable::ResTable() 3675 : mError(NO_INIT), mNextPackageId(2) 3676{ 3677 memset(&mParams, 0, sizeof(mParams)); 3678 memset(mPackageMap, 0, sizeof(mPackageMap)); 3679 if (kDebugTableSuperNoisy) { 3680 ALOGI("Creating ResTable %p\n", this); 3681 } 3682} 3683 3684ResTable::ResTable(const void* data, size_t size, const int32_t cookie, bool copyData) 3685 : mError(NO_INIT), mNextPackageId(2) 3686{ 3687 memset(&mParams, 0, sizeof(mParams)); 3688 memset(mPackageMap, 0, sizeof(mPackageMap)); 3689 addInternal(data, size, NULL, 0, false, cookie, copyData); 3690 LOG_FATAL_IF(mError != NO_ERROR, "Error parsing resource table"); 3691 if (kDebugTableSuperNoisy) { 3692 ALOGI("Creating ResTable %p\n", this); 3693 } 3694} 3695 3696ResTable::~ResTable() 3697{ 3698 if (kDebugTableSuperNoisy) { 3699 ALOGI("Destroying ResTable in %p\n", this); 3700 } 3701 uninit(); 3702} 3703 3704inline ssize_t ResTable::getResourcePackageIndex(uint32_t resID) const 3705{ 3706 return ((ssize_t)mPackageMap[Res_GETPACKAGE(resID)+1])-1; 3707} 3708 3709status_t ResTable::add(const void* data, size_t size, const int32_t cookie, bool copyData) { 3710 return addInternal(data, size, NULL, 0, false, cookie, copyData); 3711} 3712 3713status_t ResTable::add(const void* data, size_t size, const void* idmapData, size_t idmapDataSize, 3714 const int32_t cookie, bool copyData, bool appAsLib) { 3715 return addInternal(data, size, idmapData, idmapDataSize, appAsLib, cookie, copyData); 3716} 3717 3718status_t ResTable::add(Asset* asset, const int32_t cookie, bool copyData) { 3719 const void* data = asset->getBuffer(true); 3720 if (data == NULL) { 3721 ALOGW("Unable to get buffer of resource asset file"); 3722 return UNKNOWN_ERROR; 3723 } 3724 3725 return addInternal(data, static_cast<size_t>(asset->getLength()), NULL, false, 0, cookie, 3726 copyData); 3727} 3728 3729status_t ResTable::add( 3730 Asset* asset, Asset* idmapAsset, const int32_t cookie, bool copyData, 3731 bool appAsLib, bool isSystemAsset) { 3732 const void* data = asset->getBuffer(true); 3733 if (data == NULL) { 3734 ALOGW("Unable to get buffer of resource asset file"); 3735 return UNKNOWN_ERROR; 3736 } 3737 3738 size_t idmapSize = 0; 3739 const void* idmapData = NULL; 3740 if (idmapAsset != NULL) { 3741 idmapData = idmapAsset->getBuffer(true); 3742 if (idmapData == NULL) { 3743 ALOGW("Unable to get buffer of idmap asset file"); 3744 return UNKNOWN_ERROR; 3745 } 3746 idmapSize = static_cast<size_t>(idmapAsset->getLength()); 3747 } 3748 3749 return addInternal(data, static_cast<size_t>(asset->getLength()), 3750 idmapData, idmapSize, appAsLib, cookie, copyData, isSystemAsset); 3751} 3752 3753status_t ResTable::add(ResTable* src, bool isSystemAsset) 3754{ 3755 mError = src->mError; 3756 3757 for (size_t i=0; i < src->mHeaders.size(); i++) { 3758 mHeaders.add(src->mHeaders[i]); 3759 } 3760 3761 for (size_t i=0; i < src->mPackageGroups.size(); i++) { 3762 PackageGroup* srcPg = src->mPackageGroups[i]; 3763 PackageGroup* pg = new PackageGroup(this, srcPg->name, srcPg->id, 3764 false /* appAsLib */, isSystemAsset || srcPg->isSystemAsset); 3765 for (size_t j=0; j<srcPg->packages.size(); j++) { 3766 pg->packages.add(srcPg->packages[j]); 3767 } 3768 3769 for (size_t j = 0; j < srcPg->types.size(); j++) { 3770 if (srcPg->types[j].isEmpty()) { 3771 continue; 3772 } 3773 3774 TypeList& typeList = pg->types.editItemAt(j); 3775 typeList.appendVector(srcPg->types[j]); 3776 } 3777 pg->dynamicRefTable.addMappings(srcPg->dynamicRefTable); 3778 pg->largestTypeId = max(pg->largestTypeId, srcPg->largestTypeId); 3779 mPackageGroups.add(pg); 3780 } 3781 3782 memcpy(mPackageMap, src->mPackageMap, sizeof(mPackageMap)); 3783 3784 return mError; 3785} 3786 3787status_t ResTable::addEmpty(const int32_t cookie) { 3788 Header* header = new Header(this); 3789 header->index = mHeaders.size(); 3790 header->cookie = cookie; 3791 header->values.setToEmpty(); 3792 header->ownedData = calloc(1, sizeof(ResTable_header)); 3793 3794 ResTable_header* resHeader = (ResTable_header*) header->ownedData; 3795 resHeader->header.type = RES_TABLE_TYPE; 3796 resHeader->header.headerSize = sizeof(ResTable_header); 3797 resHeader->header.size = sizeof(ResTable_header); 3798 3799 header->header = (const ResTable_header*) resHeader; 3800 mHeaders.add(header); 3801 return (mError=NO_ERROR); 3802} 3803 3804status_t ResTable::addInternal(const void* data, size_t dataSize, const void* idmapData, size_t idmapDataSize, 3805 bool appAsLib, const int32_t cookie, bool copyData, bool isSystemAsset) 3806{ 3807 if (!data) { 3808 return NO_ERROR; 3809 } 3810 3811 if (dataSize < sizeof(ResTable_header)) { 3812 ALOGE("Invalid data. Size(%d) is smaller than a ResTable_header(%d).", 3813 (int) dataSize, (int) sizeof(ResTable_header)); 3814 return UNKNOWN_ERROR; 3815 } 3816 3817 Header* header = new Header(this); 3818 header->index = mHeaders.size(); 3819 header->cookie = cookie; 3820 if (idmapData != NULL) { 3821 header->resourceIDMap = (uint32_t*) malloc(idmapDataSize); 3822 if (header->resourceIDMap == NULL) { 3823 delete header; 3824 return (mError = NO_MEMORY); 3825 } 3826 memcpy(header->resourceIDMap, idmapData, idmapDataSize); 3827 header->resourceIDMapSize = idmapDataSize; 3828 } 3829 mHeaders.add(header); 3830 3831 const bool notDeviceEndian = htods(0xf0) != 0xf0; 3832 3833 if (kDebugLoadTableNoisy) { 3834 ALOGV("Adding resources to ResTable: data=%p, size=%zu, cookie=%d, copy=%d " 3835 "idmap=%p\n", data, dataSize, cookie, copyData, idmapData); 3836 } 3837 3838 if (copyData || notDeviceEndian) { 3839 header->ownedData = malloc(dataSize); 3840 if (header->ownedData == NULL) { 3841 return (mError=NO_MEMORY); 3842 } 3843 memcpy(header->ownedData, data, dataSize); 3844 data = header->ownedData; 3845 } 3846 3847 header->header = (const ResTable_header*)data; 3848 header->size = dtohl(header->header->header.size); 3849 if (kDebugLoadTableSuperNoisy) { 3850 ALOGI("Got size %zu, again size 0x%x, raw size 0x%x\n", header->size, 3851 dtohl(header->header->header.size), header->header->header.size); 3852 } 3853 if (kDebugLoadTableNoisy) { 3854 ALOGV("Loading ResTable @%p:\n", header->header); 3855 } 3856 if (dtohs(header->header->header.headerSize) > header->size 3857 || header->size > dataSize) { 3858 ALOGW("Bad resource table: header size 0x%x or total size 0x%x is larger than data size 0x%x\n", 3859 (int)dtohs(header->header->header.headerSize), 3860 (int)header->size, (int)dataSize); 3861 return (mError=BAD_TYPE); 3862 } 3863 if (((dtohs(header->header->header.headerSize)|header->size)&0x3) != 0) { 3864 ALOGW("Bad resource table: header size 0x%x or total size 0x%x is not on an integer boundary\n", 3865 (int)dtohs(header->header->header.headerSize), 3866 (int)header->size); 3867 return (mError=BAD_TYPE); 3868 } 3869 header->dataEnd = ((const uint8_t*)header->header) + header->size; 3870 3871 // Iterate through all chunks. 3872 size_t curPackage = 0; 3873 3874 const ResChunk_header* chunk = 3875 (const ResChunk_header*)(((const uint8_t*)header->header) 3876 + dtohs(header->header->header.headerSize)); 3877 while (((const uint8_t*)chunk) <= (header->dataEnd-sizeof(ResChunk_header)) && 3878 ((const uint8_t*)chunk) <= (header->dataEnd-dtohl(chunk->size))) { 3879 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), header->dataEnd, "ResTable"); 3880 if (err != NO_ERROR) { 3881 return (mError=err); 3882 } 3883 if (kDebugTableNoisy) { 3884 ALOGV("Chunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n", 3885 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size), 3886 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header))); 3887 } 3888 const size_t csize = dtohl(chunk->size); 3889 const uint16_t ctype = dtohs(chunk->type); 3890 if (ctype == RES_STRING_POOL_TYPE) { 3891 if (header->values.getError() != NO_ERROR) { 3892 // Only use the first string chunk; ignore any others that 3893 // may appear. 3894 status_t err = header->values.setTo(chunk, csize); 3895 if (err != NO_ERROR) { 3896 return (mError=err); 3897 } 3898 } else { 3899 ALOGW("Multiple string chunks found in resource table."); 3900 } 3901 } else if (ctype == RES_TABLE_PACKAGE_TYPE) { 3902 if (curPackage >= dtohl(header->header->packageCount)) { 3903 ALOGW("More package chunks were found than the %d declared in the header.", 3904 dtohl(header->header->packageCount)); 3905 return (mError=BAD_TYPE); 3906 } 3907 3908 if (parsePackage( 3909 (ResTable_package*)chunk, header, appAsLib, isSystemAsset) != NO_ERROR) { 3910 return mError; 3911 } 3912 curPackage++; 3913 } else { 3914 ALOGW("Unknown chunk type 0x%x in table at %p.\n", 3915 ctype, 3916 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header))); 3917 } 3918 chunk = (const ResChunk_header*) 3919 (((const uint8_t*)chunk) + csize); 3920 } 3921 3922 if (curPackage < dtohl(header->header->packageCount)) { 3923 ALOGW("Fewer package chunks (%d) were found than the %d declared in the header.", 3924 (int)curPackage, dtohl(header->header->packageCount)); 3925 return (mError=BAD_TYPE); 3926 } 3927 mError = header->values.getError(); 3928 if (mError != NO_ERROR) { 3929 ALOGW("No string values found in resource table!"); 3930 } 3931 3932 if (kDebugTableNoisy) { 3933 ALOGV("Returning from add with mError=%d\n", mError); 3934 } 3935 return mError; 3936} 3937 3938status_t ResTable::getError() const 3939{ 3940 return mError; 3941} 3942 3943void ResTable::uninit() 3944{ 3945 mError = NO_INIT; 3946 size_t N = mPackageGroups.size(); 3947 for (size_t i=0; i<N; i++) { 3948 PackageGroup* g = mPackageGroups[i]; 3949 delete g; 3950 } 3951 N = mHeaders.size(); 3952 for (size_t i=0; i<N; i++) { 3953 Header* header = mHeaders[i]; 3954 if (header->owner == this) { 3955 if (header->ownedData) { 3956 free(header->ownedData); 3957 } 3958 delete header; 3959 } 3960 } 3961 3962 mPackageGroups.clear(); 3963 mHeaders.clear(); 3964} 3965 3966bool ResTable::getResourceName(uint32_t resID, bool allowUtf8, resource_name* outName) const 3967{ 3968 if (mError != NO_ERROR) { 3969 return false; 3970 } 3971 3972 const ssize_t p = getResourcePackageIndex(resID); 3973 const int t = Res_GETTYPE(resID); 3974 const int e = Res_GETENTRY(resID); 3975 3976 if (p < 0) { 3977 if (Res_GETPACKAGE(resID)+1 == 0) { 3978 ALOGW("No package identifier when getting name for resource number 0x%08x", resID); 3979 } else { 3980#ifndef STATIC_ANDROIDFW_FOR_TOOLS 3981 ALOGW("No known package when getting name for resource number 0x%08x", resID); 3982#endif 3983 } 3984 return false; 3985 } 3986 if (t < 0) { 3987 ALOGW("No type identifier when getting name for resource number 0x%08x", resID); 3988 return false; 3989 } 3990 3991 const PackageGroup* const grp = mPackageGroups[p]; 3992 if (grp == NULL) { 3993 ALOGW("Bad identifier when getting name for resource number 0x%08x", resID); 3994 return false; 3995 } 3996 3997 Entry entry; 3998 status_t err = getEntry(grp, t, e, NULL, &entry); 3999 if (err != NO_ERROR) { 4000 return false; 4001 } 4002 4003 outName->package = grp->name.string(); 4004 outName->packageLen = grp->name.size(); 4005 if (allowUtf8) { 4006 outName->type8 = entry.typeStr.string8(&outName->typeLen); 4007 outName->name8 = entry.keyStr.string8(&outName->nameLen); 4008 } else { 4009 outName->type8 = NULL; 4010 outName->name8 = NULL; 4011 } 4012 if (outName->type8 == NULL) { 4013 outName->type = entry.typeStr.string16(&outName->typeLen); 4014 // If we have a bad index for some reason, we should abort. 4015 if (outName->type == NULL) { 4016 return false; 4017 } 4018 } 4019 if (outName->name8 == NULL) { 4020 outName->name = entry.keyStr.string16(&outName->nameLen); 4021 // If we have a bad index for some reason, we should abort. 4022 if (outName->name == NULL) { 4023 return false; 4024 } 4025 } 4026 4027 return true; 4028} 4029 4030ssize_t ResTable::getResource(uint32_t resID, Res_value* outValue, bool mayBeBag, uint16_t density, 4031 uint32_t* outSpecFlags, ResTable_config* outConfig) const 4032{ 4033 if (mError != NO_ERROR) { 4034 return mError; 4035 } 4036 4037 const ssize_t p = getResourcePackageIndex(resID); 4038 const int t = Res_GETTYPE(resID); 4039 const int e = Res_GETENTRY(resID); 4040 4041 if (p < 0) { 4042 if (Res_GETPACKAGE(resID)+1 == 0) { 4043 ALOGW("No package identifier when getting value for resource number 0x%08x", resID); 4044 } else { 4045 ALOGW("No known package when getting value for resource number 0x%08x", resID); 4046 } 4047 return BAD_INDEX; 4048 } 4049 if (t < 0) { 4050 ALOGW("No type identifier when getting value for resource number 0x%08x", resID); 4051 return BAD_INDEX; 4052 } 4053 4054 const PackageGroup* const grp = mPackageGroups[p]; 4055 if (grp == NULL) { 4056 ALOGW("Bad identifier when getting value for resource number 0x%08x", resID); 4057 return BAD_INDEX; 4058 } 4059 4060 // Allow overriding density 4061 ResTable_config desiredConfig = mParams; 4062 if (density > 0) { 4063 desiredConfig.density = density; 4064 } 4065 4066 Entry entry; 4067 status_t err = getEntry(grp, t, e, &desiredConfig, &entry); 4068 if (err != NO_ERROR) { 4069 // Only log the failure when we're not running on the host as 4070 // part of a tool. The caller will do its own logging. 4071#ifndef STATIC_ANDROIDFW_FOR_TOOLS 4072 ALOGW("Failure getting entry for 0x%08x (t=%d e=%d) (error %d)\n", 4073 resID, t, e, err); 4074#endif 4075 return err; 4076 } 4077 4078 if ((dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) != 0) { 4079 if (!mayBeBag) { 4080 ALOGW("Requesting resource 0x%08x failed because it is complex\n", resID); 4081 } 4082 return BAD_VALUE; 4083 } 4084 4085 const Res_value* value = reinterpret_cast<const Res_value*>( 4086 reinterpret_cast<const uint8_t*>(entry.entry) + entry.entry->size); 4087 4088 outValue->size = dtohs(value->size); 4089 outValue->res0 = value->res0; 4090 outValue->dataType = value->dataType; 4091 outValue->data = dtohl(value->data); 4092 4093 // The reference may be pointing to a resource in a shared library. These 4094 // references have build-time generated package IDs. These ids may not match 4095 // the actual package IDs of the corresponding packages in this ResTable. 4096 // We need to fix the package ID based on a mapping. 4097 if (grp->dynamicRefTable.lookupResourceValue(outValue) != NO_ERROR) { 4098 ALOGW("Failed to resolve referenced package: 0x%08x", outValue->data); 4099 return BAD_VALUE; 4100 } 4101 4102 if (kDebugTableNoisy) { 4103 size_t len; 4104 printf("Found value: pkg=%zu, type=%d, str=%s, int=%d\n", 4105 entry.package->header->index, 4106 outValue->dataType, 4107 outValue->dataType == Res_value::TYPE_STRING ? 4108 String8(entry.package->header->values.stringAt(outValue->data, &len)).string() : 4109 "", 4110 outValue->data); 4111 } 4112 4113 if (outSpecFlags != NULL) { 4114 *outSpecFlags = entry.specFlags; 4115 } 4116 4117 if (outConfig != NULL) { 4118 *outConfig = entry.config; 4119 } 4120 4121 return entry.package->header->index; 4122} 4123 4124ssize_t ResTable::resolveReference(Res_value* value, ssize_t blockIndex, 4125 uint32_t* outLastRef, uint32_t* inoutTypeSpecFlags, 4126 ResTable_config* outConfig) const 4127{ 4128 int count=0; 4129 while (blockIndex >= 0 && value->dataType == Res_value::TYPE_REFERENCE 4130 && value->data != 0 && count < 20) { 4131 if (outLastRef) *outLastRef = value->data; 4132 uint32_t newFlags = 0; 4133 const ssize_t newIndex = getResource(value->data, value, true, 0, &newFlags, 4134 outConfig); 4135 if (newIndex == BAD_INDEX) { 4136 return BAD_INDEX; 4137 } 4138 if (kDebugTableTheme) { 4139 ALOGI("Resolving reference 0x%x: newIndex=%d, type=0x%x, data=0x%x\n", 4140 value->data, (int)newIndex, (int)value->dataType, value->data); 4141 } 4142 //printf("Getting reference 0x%08x: newIndex=%d\n", value->data, newIndex); 4143 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newFlags; 4144 if (newIndex < 0) { 4145 // This can fail if the resource being referenced is a style... 4146 // in this case, just return the reference, and expect the 4147 // caller to deal with. 4148 return blockIndex; 4149 } 4150 blockIndex = newIndex; 4151 count++; 4152 } 4153 return blockIndex; 4154} 4155 4156const char16_t* ResTable::valueToString( 4157 const Res_value* value, size_t stringBlock, 4158 char16_t /*tmpBuffer*/ [TMP_BUFFER_SIZE], size_t* outLen) const 4159{ 4160 if (!value) { 4161 return NULL; 4162 } 4163 if (value->dataType == value->TYPE_STRING) { 4164 return getTableStringBlock(stringBlock)->stringAt(value->data, outLen); 4165 } 4166 // XXX do int to string conversions. 4167 return NULL; 4168} 4169 4170ssize_t ResTable::lockBag(uint32_t resID, const bag_entry** outBag) const 4171{ 4172 mLock.lock(); 4173 ssize_t err = getBagLocked(resID, outBag); 4174 if (err < NO_ERROR) { 4175 //printf("*** get failed! unlocking\n"); 4176 mLock.unlock(); 4177 } 4178 return err; 4179} 4180 4181void ResTable::unlockBag(const bag_entry* /*bag*/) const 4182{ 4183 //printf("<<< unlockBag %p\n", this); 4184 mLock.unlock(); 4185} 4186 4187void ResTable::lock() const 4188{ 4189 mLock.lock(); 4190} 4191 4192void ResTable::unlock() const 4193{ 4194 mLock.unlock(); 4195} 4196 4197ssize_t ResTable::getBagLocked(uint32_t resID, const bag_entry** outBag, 4198 uint32_t* outTypeSpecFlags) const 4199{ 4200 if (mError != NO_ERROR) { 4201 return mError; 4202 } 4203 4204 const ssize_t p = getResourcePackageIndex(resID); 4205 const int t = Res_GETTYPE(resID); 4206 const int e = Res_GETENTRY(resID); 4207 4208 if (p < 0) { 4209 ALOGW("Invalid package identifier when getting bag for resource number 0x%08x", resID); 4210 return BAD_INDEX; 4211 } 4212 if (t < 0) { 4213 ALOGW("No type identifier when getting bag for resource number 0x%08x", resID); 4214 return BAD_INDEX; 4215 } 4216 4217 //printf("Get bag: id=0x%08x, p=%d, t=%d\n", resID, p, t); 4218 PackageGroup* const grp = mPackageGroups[p]; 4219 if (grp == NULL) { 4220 ALOGW("Bad identifier when getting bag for resource number 0x%08x", resID); 4221 return BAD_INDEX; 4222 } 4223 4224 const TypeList& typeConfigs = grp->types[t]; 4225 if (typeConfigs.isEmpty()) { 4226 ALOGW("Type identifier 0x%x does not exist.", t+1); 4227 return BAD_INDEX; 4228 } 4229 4230 const size_t NENTRY = typeConfigs[0]->entryCount; 4231 if (e >= (int)NENTRY) { 4232 ALOGW("Entry identifier 0x%x is larger than entry count 0x%x", 4233 e, (int)typeConfigs[0]->entryCount); 4234 return BAD_INDEX; 4235 } 4236 4237 // First see if we've already computed this bag... 4238 TypeCacheEntry& cacheEntry = grp->typeCacheEntries.editItemAt(t); 4239 bag_set** typeSet = cacheEntry.cachedBags; 4240 if (typeSet) { 4241 bag_set* set = typeSet[e]; 4242 if (set) { 4243 if (set != (bag_set*)0xFFFFFFFF) { 4244 if (outTypeSpecFlags != NULL) { 4245 *outTypeSpecFlags = set->typeSpecFlags; 4246 } 4247 *outBag = (bag_entry*)(set+1); 4248 if (kDebugTableSuperNoisy) { 4249 ALOGI("Found existing bag for: 0x%x\n", resID); 4250 } 4251 return set->numAttrs; 4252 } 4253 ALOGW("Attempt to retrieve bag 0x%08x which is invalid or in a cycle.", 4254 resID); 4255 return BAD_INDEX; 4256 } 4257 } 4258 4259 // Bag not found, we need to compute it! 4260 if (!typeSet) { 4261 typeSet = (bag_set**)calloc(NENTRY, sizeof(bag_set*)); 4262 if (!typeSet) return NO_MEMORY; 4263 cacheEntry.cachedBags = typeSet; 4264 } 4265 4266 // Mark that we are currently working on this one. 4267 typeSet[e] = (bag_set*)0xFFFFFFFF; 4268 4269 if (kDebugTableNoisy) { 4270 ALOGI("Building bag: %x\n", resID); 4271 } 4272 4273 // Now collect all bag attributes 4274 Entry entry; 4275 status_t err = getEntry(grp, t, e, &mParams, &entry); 4276 if (err != NO_ERROR) { 4277 return err; 4278 } 4279 4280 const uint16_t entrySize = dtohs(entry.entry->size); 4281 const uint32_t parent = entrySize >= sizeof(ResTable_map_entry) 4282 ? dtohl(((const ResTable_map_entry*)entry.entry)->parent.ident) : 0; 4283 const uint32_t count = entrySize >= sizeof(ResTable_map_entry) 4284 ? dtohl(((const ResTable_map_entry*)entry.entry)->count) : 0; 4285 4286 size_t N = count; 4287 4288 if (kDebugTableNoisy) { 4289 ALOGI("Found map: size=%x parent=%x count=%d\n", entrySize, parent, count); 4290 4291 // If this map inherits from another, we need to start 4292 // with its parent's values. Otherwise start out empty. 4293 ALOGI("Creating new bag, entrySize=0x%08x, parent=0x%08x\n", entrySize, parent); 4294 } 4295 4296 // This is what we are building. 4297 bag_set* set = NULL; 4298 4299 if (parent) { 4300 uint32_t resolvedParent = parent; 4301 4302 // Bags encode a parent reference without using the standard 4303 // Res_value structure. That means we must always try to 4304 // resolve a parent reference in case it is actually a 4305 // TYPE_DYNAMIC_REFERENCE. 4306 status_t err = grp->dynamicRefTable.lookupResourceId(&resolvedParent); 4307 if (err != NO_ERROR) { 4308 ALOGE("Failed resolving bag parent id 0x%08x", parent); 4309 return UNKNOWN_ERROR; 4310 } 4311 4312 const bag_entry* parentBag; 4313 uint32_t parentTypeSpecFlags = 0; 4314 const ssize_t NP = getBagLocked(resolvedParent, &parentBag, &parentTypeSpecFlags); 4315 const size_t NT = ((NP >= 0) ? NP : 0) + N; 4316 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*NT); 4317 if (set == NULL) { 4318 return NO_MEMORY; 4319 } 4320 if (NP > 0) { 4321 memcpy(set+1, parentBag, NP*sizeof(bag_entry)); 4322 set->numAttrs = NP; 4323 if (kDebugTableNoisy) { 4324 ALOGI("Initialized new bag with %zd inherited attributes.\n", NP); 4325 } 4326 } else { 4327 if (kDebugTableNoisy) { 4328 ALOGI("Initialized new bag with no inherited attributes.\n"); 4329 } 4330 set->numAttrs = 0; 4331 } 4332 set->availAttrs = NT; 4333 set->typeSpecFlags = parentTypeSpecFlags; 4334 } else { 4335 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*N); 4336 if (set == NULL) { 4337 return NO_MEMORY; 4338 } 4339 set->numAttrs = 0; 4340 set->availAttrs = N; 4341 set->typeSpecFlags = 0; 4342 } 4343 4344 set->typeSpecFlags |= entry.specFlags; 4345 4346 // Now merge in the new attributes... 4347 size_t curOff = (reinterpret_cast<uintptr_t>(entry.entry) - reinterpret_cast<uintptr_t>(entry.type)) 4348 + dtohs(entry.entry->size); 4349 const ResTable_map* map; 4350 bag_entry* entries = (bag_entry*)(set+1); 4351 size_t curEntry = 0; 4352 uint32_t pos = 0; 4353 if (kDebugTableNoisy) { 4354 ALOGI("Starting with set %p, entries=%p, avail=%zu\n", set, entries, set->availAttrs); 4355 } 4356 while (pos < count) { 4357 if (kDebugTableNoisy) { 4358 ALOGI("Now at %p\n", (void*)curOff); 4359 } 4360 4361 if (curOff > (dtohl(entry.type->header.size)-sizeof(ResTable_map))) { 4362 ALOGW("ResTable_map at %d is beyond type chunk data %d", 4363 (int)curOff, dtohl(entry.type->header.size)); 4364 return BAD_TYPE; 4365 } 4366 map = (const ResTable_map*)(((const uint8_t*)entry.type) + curOff); 4367 N++; 4368 4369 uint32_t newName = htodl(map->name.ident); 4370 if (!Res_INTERNALID(newName)) { 4371 // Attributes don't have a resource id as the name. They specify 4372 // other data, which would be wrong to change via a lookup. 4373 if (grp->dynamicRefTable.lookupResourceId(&newName) != NO_ERROR) { 4374 ALOGE("Failed resolving ResTable_map name at %d with ident 0x%08x", 4375 (int) curOff, (int) newName); 4376 return UNKNOWN_ERROR; 4377 } 4378 } 4379 4380 bool isInside; 4381 uint32_t oldName = 0; 4382 while ((isInside=(curEntry < set->numAttrs)) 4383 && (oldName=entries[curEntry].map.name.ident) < newName) { 4384 if (kDebugTableNoisy) { 4385 ALOGI("#%zu: Keeping existing attribute: 0x%08x\n", 4386 curEntry, entries[curEntry].map.name.ident); 4387 } 4388 curEntry++; 4389 } 4390 4391 if ((!isInside) || oldName != newName) { 4392 // This is a new attribute... figure out what to do with it. 4393 if (set->numAttrs >= set->availAttrs) { 4394 // Need to alloc more memory... 4395 const size_t newAvail = set->availAttrs+N; 4396 void *oldSet = set; 4397 set = (bag_set*)realloc(set, 4398 sizeof(bag_set) 4399 + sizeof(bag_entry)*newAvail); 4400 if (set == NULL) { 4401 free(oldSet); 4402 return NO_MEMORY; 4403 } 4404 set->availAttrs = newAvail; 4405 entries = (bag_entry*)(set+1); 4406 if (kDebugTableNoisy) { 4407 ALOGI("Reallocated set %p, entries=%p, avail=%zu\n", 4408 set, entries, set->availAttrs); 4409 } 4410 } 4411 if (isInside) { 4412 // Going in the middle, need to make space. 4413 memmove(entries+curEntry+1, entries+curEntry, 4414 sizeof(bag_entry)*(set->numAttrs-curEntry)); 4415 set->numAttrs++; 4416 } 4417 if (kDebugTableNoisy) { 4418 ALOGI("#%zu: Inserting new attribute: 0x%08x\n", curEntry, newName); 4419 } 4420 } else { 4421 if (kDebugTableNoisy) { 4422 ALOGI("#%zu: Replacing existing attribute: 0x%08x\n", curEntry, oldName); 4423 } 4424 } 4425 4426 bag_entry* cur = entries+curEntry; 4427 4428 cur->stringBlock = entry.package->header->index; 4429 cur->map.name.ident = newName; 4430 cur->map.value.copyFrom_dtoh(map->value); 4431 status_t err = grp->dynamicRefTable.lookupResourceValue(&cur->map.value); 4432 if (err != NO_ERROR) { 4433 ALOGE("Reference item(0x%08x) in bag could not be resolved.", cur->map.value.data); 4434 return UNKNOWN_ERROR; 4435 } 4436 4437 if (kDebugTableNoisy) { 4438 ALOGI("Setting entry #%zu %p: block=%zd, name=0x%08d, type=%d, data=0x%08x\n", 4439 curEntry, cur, cur->stringBlock, cur->map.name.ident, 4440 cur->map.value.dataType, cur->map.value.data); 4441 } 4442 4443 // On to the next! 4444 curEntry++; 4445 pos++; 4446 const size_t size = dtohs(map->value.size); 4447 curOff += size + sizeof(*map)-sizeof(map->value); 4448 } 4449 4450 if (curEntry > set->numAttrs) { 4451 set->numAttrs = curEntry; 4452 } 4453 4454 // And this is it... 4455 typeSet[e] = set; 4456 if (set) { 4457 if (outTypeSpecFlags != NULL) { 4458 *outTypeSpecFlags = set->typeSpecFlags; 4459 } 4460 *outBag = (bag_entry*)(set+1); 4461 if (kDebugTableNoisy) { 4462 ALOGI("Returning %zu attrs\n", set->numAttrs); 4463 } 4464 return set->numAttrs; 4465 } 4466 return BAD_INDEX; 4467} 4468 4469void ResTable::setParameters(const ResTable_config* params) 4470{ 4471 AutoMutex _lock(mLock); 4472 AutoMutex _lock2(mFilteredConfigLock); 4473 4474 if (kDebugTableGetEntry) { 4475 ALOGI("Setting parameters: %s\n", params->toString().string()); 4476 } 4477 mParams = *params; 4478 for (size_t p = 0; p < mPackageGroups.size(); p++) { 4479 PackageGroup* packageGroup = mPackageGroups.editItemAt(p); 4480 if (kDebugTableNoisy) { 4481 ALOGI("CLEARING BAGS FOR GROUP %zu!", p); 4482 } 4483 packageGroup->clearBagCache(); 4484 4485 // Find which configurations match the set of parameters. This allows for a much 4486 // faster lookup in getEntry() if the set of values is narrowed down. 4487 for (size_t t = 0; t < packageGroup->types.size(); t++) { 4488 if (packageGroup->types[t].isEmpty()) { 4489 continue; 4490 } 4491 4492 TypeList& typeList = packageGroup->types.editItemAt(t); 4493 4494 // Retrieve the cache entry for this type. 4495 TypeCacheEntry& cacheEntry = packageGroup->typeCacheEntries.editItemAt(t); 4496 4497 for (size_t ts = 0; ts < typeList.size(); ts++) { 4498 Type* type = typeList.editItemAt(ts); 4499 4500 std::shared_ptr<Vector<const ResTable_type*>> newFilteredConfigs = 4501 std::make_shared<Vector<const ResTable_type*>>(); 4502 4503 for (size_t ti = 0; ti < type->configs.size(); ti++) { 4504 ResTable_config config; 4505 config.copyFromDtoH(type->configs[ti]->config); 4506 4507 if (config.match(mParams)) { 4508 newFilteredConfigs->add(type->configs[ti]); 4509 } 4510 } 4511 4512 if (kDebugTableNoisy) { 4513 ALOGD("Updating pkg=%zu type=%zu with %zu filtered configs", 4514 p, t, newFilteredConfigs->size()); 4515 } 4516 4517 cacheEntry.filteredConfigs.add(newFilteredConfigs); 4518 } 4519 } 4520 } 4521} 4522 4523void ResTable::getParameters(ResTable_config* params) const 4524{ 4525 mLock.lock(); 4526 *params = mParams; 4527 mLock.unlock(); 4528} 4529 4530struct id_name_map { 4531 uint32_t id; 4532 size_t len; 4533 char16_t name[6]; 4534}; 4535 4536const static id_name_map ID_NAMES[] = { 4537 { ResTable_map::ATTR_TYPE, 5, { '^', 't', 'y', 'p', 'e' } }, 4538 { ResTable_map::ATTR_L10N, 5, { '^', 'l', '1', '0', 'n' } }, 4539 { ResTable_map::ATTR_MIN, 4, { '^', 'm', 'i', 'n' } }, 4540 { ResTable_map::ATTR_MAX, 4, { '^', 'm', 'a', 'x' } }, 4541 { ResTable_map::ATTR_OTHER, 6, { '^', 'o', 't', 'h', 'e', 'r' } }, 4542 { ResTable_map::ATTR_ZERO, 5, { '^', 'z', 'e', 'r', 'o' } }, 4543 { ResTable_map::ATTR_ONE, 4, { '^', 'o', 'n', 'e' } }, 4544 { ResTable_map::ATTR_TWO, 4, { '^', 't', 'w', 'o' } }, 4545 { ResTable_map::ATTR_FEW, 4, { '^', 'f', 'e', 'w' } }, 4546 { ResTable_map::ATTR_MANY, 5, { '^', 'm', 'a', 'n', 'y' } }, 4547}; 4548 4549uint32_t ResTable::identifierForName(const char16_t* name, size_t nameLen, 4550 const char16_t* type, size_t typeLen, 4551 const char16_t* package, 4552 size_t packageLen, 4553 uint32_t* outTypeSpecFlags) const 4554{ 4555 if (kDebugTableSuperNoisy) { 4556 printf("Identifier for name: error=%d\n", mError); 4557 } 4558 4559 // Check for internal resource identifier as the very first thing, so 4560 // that we will always find them even when there are no resources. 4561 if (name[0] == '^') { 4562 const int N = (sizeof(ID_NAMES)/sizeof(ID_NAMES[0])); 4563 size_t len; 4564 for (int i=0; i<N; i++) { 4565 const id_name_map* m = ID_NAMES + i; 4566 len = m->len; 4567 if (len != nameLen) { 4568 continue; 4569 } 4570 for (size_t j=1; j<len; j++) { 4571 if (m->name[j] != name[j]) { 4572 goto nope; 4573 } 4574 } 4575 if (outTypeSpecFlags) { 4576 *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC; 4577 } 4578 return m->id; 4579nope: 4580 ; 4581 } 4582 if (nameLen > 7) { 4583 if (name[1] == 'i' && name[2] == 'n' 4584 && name[3] == 'd' && name[4] == 'e' && name[5] == 'x' 4585 && name[6] == '_') { 4586 int index = atoi(String8(name + 7, nameLen - 7).string()); 4587 if (Res_CHECKID(index)) { 4588 ALOGW("Array resource index: %d is too large.", 4589 index); 4590 return 0; 4591 } 4592 if (outTypeSpecFlags) { 4593 *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC; 4594 } 4595 return Res_MAKEARRAY(index); 4596 } 4597 } 4598 return 0; 4599 } 4600 4601 if (mError != NO_ERROR) { 4602 return 0; 4603 } 4604 4605 bool fakePublic = false; 4606 4607 // Figure out the package and type we are looking in... 4608 4609 const char16_t* packageEnd = NULL; 4610 const char16_t* typeEnd = NULL; 4611 const char16_t* const nameEnd = name+nameLen; 4612 const char16_t* p = name; 4613 while (p < nameEnd) { 4614 if (*p == ':') packageEnd = p; 4615 else if (*p == '/') typeEnd = p; 4616 p++; 4617 } 4618 if (*name == '@') { 4619 name++; 4620 if (*name == '*') { 4621 fakePublic = true; 4622 name++; 4623 } 4624 } 4625 if (name >= nameEnd) { 4626 return 0; 4627 } 4628 4629 if (packageEnd) { 4630 package = name; 4631 packageLen = packageEnd-name; 4632 name = packageEnd+1; 4633 } else if (!package) { 4634 return 0; 4635 } 4636 4637 if (typeEnd) { 4638 type = name; 4639 typeLen = typeEnd-name; 4640 name = typeEnd+1; 4641 } else if (!type) { 4642 return 0; 4643 } 4644 4645 if (name >= nameEnd) { 4646 return 0; 4647 } 4648 nameLen = nameEnd-name; 4649 4650 if (kDebugTableNoisy) { 4651 printf("Looking for identifier: type=%s, name=%s, package=%s\n", 4652 String8(type, typeLen).string(), 4653 String8(name, nameLen).string(), 4654 String8(package, packageLen).string()); 4655 } 4656 4657 const String16 attr("attr"); 4658 const String16 attrPrivate("^attr-private"); 4659 4660 const size_t NG = mPackageGroups.size(); 4661 for (size_t ig=0; ig<NG; ig++) { 4662 const PackageGroup* group = mPackageGroups[ig]; 4663 4664 if (strzcmp16(package, packageLen, 4665 group->name.string(), group->name.size())) { 4666 if (kDebugTableNoisy) { 4667 printf("Skipping package group: %s\n", String8(group->name).string()); 4668 } 4669 continue; 4670 } 4671 4672 const size_t packageCount = group->packages.size(); 4673 for (size_t pi = 0; pi < packageCount; pi++) { 4674 const char16_t* targetType = type; 4675 size_t targetTypeLen = typeLen; 4676 4677 do { 4678 ssize_t ti = group->packages[pi]->typeStrings.indexOfString( 4679 targetType, targetTypeLen); 4680 if (ti < 0) { 4681 continue; 4682 } 4683 4684 ti += group->packages[pi]->typeIdOffset; 4685 4686 const uint32_t identifier = findEntry(group, ti, name, nameLen, 4687 outTypeSpecFlags); 4688 if (identifier != 0) { 4689 if (fakePublic && outTypeSpecFlags) { 4690 *outTypeSpecFlags |= ResTable_typeSpec::SPEC_PUBLIC; 4691 } 4692 return identifier; 4693 } 4694 } while (strzcmp16(attr.string(), attr.size(), targetType, targetTypeLen) == 0 4695 && (targetType = attrPrivate.string()) 4696 && (targetTypeLen = attrPrivate.size()) 4697 ); 4698 } 4699 break; 4700 } 4701 return 0; 4702} 4703 4704uint32_t ResTable::findEntry(const PackageGroup* group, ssize_t typeIndex, const char16_t* name, 4705 size_t nameLen, uint32_t* outTypeSpecFlags) const { 4706 const TypeList& typeList = group->types[typeIndex]; 4707 const size_t typeCount = typeList.size(); 4708 for (size_t i = 0; i < typeCount; i++) { 4709 const Type* t = typeList[i]; 4710 const ssize_t ei = t->package->keyStrings.indexOfString(name, nameLen); 4711 if (ei < 0) { 4712 continue; 4713 } 4714 4715 const size_t configCount = t->configs.size(); 4716 for (size_t j = 0; j < configCount; j++) { 4717 const TypeVariant tv(t->configs[j]); 4718 for (TypeVariant::iterator iter = tv.beginEntries(); 4719 iter != tv.endEntries(); 4720 iter++) { 4721 const ResTable_entry* entry = *iter; 4722 if (entry == NULL) { 4723 continue; 4724 } 4725 4726 if (dtohl(entry->key.index) == (size_t) ei) { 4727 uint32_t resId = Res_MAKEID(group->id - 1, typeIndex, iter.index()); 4728 if (outTypeSpecFlags) { 4729 Entry result; 4730 if (getEntry(group, typeIndex, iter.index(), NULL, &result) != NO_ERROR) { 4731 ALOGW("Failed to find spec flags for 0x%08x", resId); 4732 return 0; 4733 } 4734 *outTypeSpecFlags = result.specFlags; 4735 } 4736 return resId; 4737 } 4738 } 4739 } 4740 } 4741 return 0; 4742} 4743 4744bool ResTable::expandResourceRef(const char16_t* refStr, size_t refLen, 4745 String16* outPackage, 4746 String16* outType, 4747 String16* outName, 4748 const String16* defType, 4749 const String16* defPackage, 4750 const char** outErrorMsg, 4751 bool* outPublicOnly) 4752{ 4753 const char16_t* packageEnd = NULL; 4754 const char16_t* typeEnd = NULL; 4755 const char16_t* p = refStr; 4756 const char16_t* const end = p + refLen; 4757 while (p < end) { 4758 if (*p == ':') packageEnd = p; 4759 else if (*p == '/') { 4760 typeEnd = p; 4761 break; 4762 } 4763 p++; 4764 } 4765 p = refStr; 4766 if (*p == '@') p++; 4767 4768 if (outPublicOnly != NULL) { 4769 *outPublicOnly = true; 4770 } 4771 if (*p == '*') { 4772 p++; 4773 if (outPublicOnly != NULL) { 4774 *outPublicOnly = false; 4775 } 4776 } 4777 4778 if (packageEnd) { 4779 *outPackage = String16(p, packageEnd-p); 4780 p = packageEnd+1; 4781 } else { 4782 if (!defPackage) { 4783 if (outErrorMsg) { 4784 *outErrorMsg = "No resource package specified"; 4785 } 4786 return false; 4787 } 4788 *outPackage = *defPackage; 4789 } 4790 if (typeEnd) { 4791 *outType = String16(p, typeEnd-p); 4792 p = typeEnd+1; 4793 } else { 4794 if (!defType) { 4795 if (outErrorMsg) { 4796 *outErrorMsg = "No resource type specified"; 4797 } 4798 return false; 4799 } 4800 *outType = *defType; 4801 } 4802 *outName = String16(p, end-p); 4803 if(**outPackage == 0) { 4804 if(outErrorMsg) { 4805 *outErrorMsg = "Resource package cannot be an empty string"; 4806 } 4807 return false; 4808 } 4809 if(**outType == 0) { 4810 if(outErrorMsg) { 4811 *outErrorMsg = "Resource type cannot be an empty string"; 4812 } 4813 return false; 4814 } 4815 if(**outName == 0) { 4816 if(outErrorMsg) { 4817 *outErrorMsg = "Resource id cannot be an empty string"; 4818 } 4819 return false; 4820 } 4821 return true; 4822} 4823 4824static uint32_t get_hex(char c, bool* outError) 4825{ 4826 if (c >= '0' && c <= '9') { 4827 return c - '0'; 4828 } else if (c >= 'a' && c <= 'f') { 4829 return c - 'a' + 0xa; 4830 } else if (c >= 'A' && c <= 'F') { 4831 return c - 'A' + 0xa; 4832 } 4833 *outError = true; 4834 return 0; 4835} 4836 4837struct unit_entry 4838{ 4839 const char* name; 4840 size_t len; 4841 uint8_t type; 4842 uint32_t unit; 4843 float scale; 4844}; 4845 4846static const unit_entry unitNames[] = { 4847 { "px", strlen("px"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PX, 1.0f }, 4848 { "dip", strlen("dip"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f }, 4849 { "dp", strlen("dp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f }, 4850 { "sp", strlen("sp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_SP, 1.0f }, 4851 { "pt", strlen("pt"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PT, 1.0f }, 4852 { "in", strlen("in"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_IN, 1.0f }, 4853 { "mm", strlen("mm"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_MM, 1.0f }, 4854 { "%", strlen("%"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION, 1.0f/100 }, 4855 { "%p", strlen("%p"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION_PARENT, 1.0f/100 }, 4856 { NULL, 0, 0, 0, 0 } 4857}; 4858 4859static bool parse_unit(const char* str, Res_value* outValue, 4860 float* outScale, const char** outEnd) 4861{ 4862 const char* end = str; 4863 while (*end != 0 && !isspace((unsigned char)*end)) { 4864 end++; 4865 } 4866 const size_t len = end-str; 4867 4868 const char* realEnd = end; 4869 while (*realEnd != 0 && isspace((unsigned char)*realEnd)) { 4870 realEnd++; 4871 } 4872 if (*realEnd != 0) { 4873 return false; 4874 } 4875 4876 const unit_entry* cur = unitNames; 4877 while (cur->name) { 4878 if (len == cur->len && strncmp(cur->name, str, len) == 0) { 4879 outValue->dataType = cur->type; 4880 outValue->data = cur->unit << Res_value::COMPLEX_UNIT_SHIFT; 4881 *outScale = cur->scale; 4882 *outEnd = end; 4883 //printf("Found unit %s for %s\n", cur->name, str); 4884 return true; 4885 } 4886 cur++; 4887 } 4888 4889 return false; 4890} 4891 4892bool U16StringToInt(const char16_t* s, size_t len, Res_value* outValue) 4893{ 4894 while (len > 0 && isspace16(*s)) { 4895 s++; 4896 len--; 4897 } 4898 4899 if (len <= 0) { 4900 return false; 4901 } 4902 4903 size_t i = 0; 4904 int64_t val = 0; 4905 bool neg = false; 4906 4907 if (*s == '-') { 4908 neg = true; 4909 i++; 4910 } 4911 4912 if (s[i] < '0' || s[i] > '9') { 4913 return false; 4914 } 4915 4916 static_assert(std::is_same<uint32_t, Res_value::data_type>::value, 4917 "Res_value::data_type has changed. The range checks in this " 4918 "function are no longer correct."); 4919 4920 // Decimal or hex? 4921 bool isHex; 4922 if (len > 1 && s[i] == '0' && s[i+1] == 'x') { 4923 isHex = true; 4924 i += 2; 4925 4926 if (neg) { 4927 return false; 4928 } 4929 4930 if (i == len) { 4931 // Just u"0x" 4932 return false; 4933 } 4934 4935 bool error = false; 4936 while (i < len && !error) { 4937 val = (val*16) + get_hex(s[i], &error); 4938 i++; 4939 4940 if (val > std::numeric_limits<uint32_t>::max()) { 4941 return false; 4942 } 4943 } 4944 if (error) { 4945 return false; 4946 } 4947 } else { 4948 isHex = false; 4949 while (i < len) { 4950 if (s[i] < '0' || s[i] > '9') { 4951 return false; 4952 } 4953 val = (val*10) + s[i]-'0'; 4954 i++; 4955 4956 if ((neg && -val < std::numeric_limits<int32_t>::min()) || 4957 (!neg && val > std::numeric_limits<int32_t>::max())) { 4958 return false; 4959 } 4960 } 4961 } 4962 4963 if (neg) val = -val; 4964 4965 while (i < len && isspace16(s[i])) { 4966 i++; 4967 } 4968 4969 if (i != len) { 4970 return false; 4971 } 4972 4973 if (outValue) { 4974 outValue->dataType = 4975 isHex ? outValue->TYPE_INT_HEX : outValue->TYPE_INT_DEC; 4976 outValue->data = static_cast<Res_value::data_type>(val); 4977 } 4978 return true; 4979} 4980 4981bool ResTable::stringToInt(const char16_t* s, size_t len, Res_value* outValue) 4982{ 4983 return U16StringToInt(s, len, outValue); 4984} 4985 4986bool ResTable::stringToFloat(const char16_t* s, size_t len, Res_value* outValue) 4987{ 4988 while (len > 0 && isspace16(*s)) { 4989 s++; 4990 len--; 4991 } 4992 4993 if (len <= 0) { 4994 return false; 4995 } 4996 4997 char buf[128]; 4998 int i=0; 4999 while (len > 0 && *s != 0 && i < 126) { 5000 if (*s > 255) { 5001 return false; 5002 } 5003 buf[i++] = *s++; 5004 len--; 5005 } 5006 5007 if (len > 0) { 5008 return false; 5009 } 5010 if ((buf[0] < '0' || buf[0] > '9') && buf[0] != '.' && buf[0] != '-' && buf[0] != '+') { 5011 return false; 5012 } 5013 5014 buf[i] = 0; 5015 const char* end; 5016 float f = strtof(buf, (char**)&end); 5017 5018 if (*end != 0 && !isspace((unsigned char)*end)) { 5019 // Might be a unit... 5020 float scale; 5021 if (parse_unit(end, outValue, &scale, &end)) { 5022 f *= scale; 5023 const bool neg = f < 0; 5024 if (neg) f = -f; 5025 uint64_t bits = (uint64_t)(f*(1<<23)+.5f); 5026 uint32_t radix; 5027 uint32_t shift; 5028 if ((bits&0x7fffff) == 0) { 5029 // Always use 23p0 if there is no fraction, just to make 5030 // things easier to read. 5031 radix = Res_value::COMPLEX_RADIX_23p0; 5032 shift = 23; 5033 } else if ((bits&0xffffffffff800000LL) == 0) { 5034 // Magnitude is zero -- can fit in 0 bits of precision. 5035 radix = Res_value::COMPLEX_RADIX_0p23; 5036 shift = 0; 5037 } else if ((bits&0xffffffff80000000LL) == 0) { 5038 // Magnitude can fit in 8 bits of precision. 5039 radix = Res_value::COMPLEX_RADIX_8p15; 5040 shift = 8; 5041 } else if ((bits&0xffffff8000000000LL) == 0) { 5042 // Magnitude can fit in 16 bits of precision. 5043 radix = Res_value::COMPLEX_RADIX_16p7; 5044 shift = 16; 5045 } else { 5046 // Magnitude needs entire range, so no fractional part. 5047 radix = Res_value::COMPLEX_RADIX_23p0; 5048 shift = 23; 5049 } 5050 int32_t mantissa = (int32_t)( 5051 (bits>>shift) & Res_value::COMPLEX_MANTISSA_MASK); 5052 if (neg) { 5053 mantissa = (-mantissa) & Res_value::COMPLEX_MANTISSA_MASK; 5054 } 5055 outValue->data |= 5056 (radix<<Res_value::COMPLEX_RADIX_SHIFT) 5057 | (mantissa<<Res_value::COMPLEX_MANTISSA_SHIFT); 5058 //printf("Input value: %f 0x%016Lx, mult: %f, radix: %d, shift: %d, final: 0x%08x\n", 5059 // f * (neg ? -1 : 1), bits, f*(1<<23), 5060 // radix, shift, outValue->data); 5061 return true; 5062 } 5063 return false; 5064 } 5065 5066 while (*end != 0 && isspace((unsigned char)*end)) { 5067 end++; 5068 } 5069 5070 if (*end == 0) { 5071 if (outValue) { 5072 outValue->dataType = outValue->TYPE_FLOAT; 5073 *(float*)(&outValue->data) = f; 5074 return true; 5075 } 5076 } 5077 5078 return false; 5079} 5080 5081bool ResTable::stringToValue(Res_value* outValue, String16* outString, 5082 const char16_t* s, size_t len, 5083 bool preserveSpaces, bool coerceType, 5084 uint32_t attrID, 5085 const String16* defType, 5086 const String16* defPackage, 5087 Accessor* accessor, 5088 void* accessorCookie, 5089 uint32_t attrType, 5090 bool enforcePrivate) const 5091{ 5092 bool localizationSetting = accessor != NULL && accessor->getLocalizationSetting(); 5093 const char* errorMsg = NULL; 5094 5095 outValue->size = sizeof(Res_value); 5096 outValue->res0 = 0; 5097 5098 // First strip leading/trailing whitespace. Do this before handling 5099 // escapes, so they can be used to force whitespace into the string. 5100 if (!preserveSpaces) { 5101 while (len > 0 && isspace16(*s)) { 5102 s++; 5103 len--; 5104 } 5105 while (len > 0 && isspace16(s[len-1])) { 5106 len--; 5107 } 5108 // If the string ends with '\', then we keep the space after it. 5109 if (len > 0 && s[len-1] == '\\' && s[len] != 0) { 5110 len++; 5111 } 5112 } 5113 5114 //printf("Value for: %s\n", String8(s, len).string()); 5115 5116 uint32_t l10nReq = ResTable_map::L10N_NOT_REQUIRED; 5117 uint32_t attrMin = 0x80000000, attrMax = 0x7fffffff; 5118 bool fromAccessor = false; 5119 if (attrID != 0 && !Res_INTERNALID(attrID)) { 5120 const ssize_t p = getResourcePackageIndex(attrID); 5121 const bag_entry* bag; 5122 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1; 5123 //printf("For attr 0x%08x got bag of %d\n", attrID, cnt); 5124 if (cnt >= 0) { 5125 while (cnt > 0) { 5126 //printf("Entry 0x%08x = 0x%08x\n", bag->map.name.ident, bag->map.value.data); 5127 switch (bag->map.name.ident) { 5128 case ResTable_map::ATTR_TYPE: 5129 attrType = bag->map.value.data; 5130 break; 5131 case ResTable_map::ATTR_MIN: 5132 attrMin = bag->map.value.data; 5133 break; 5134 case ResTable_map::ATTR_MAX: 5135 attrMax = bag->map.value.data; 5136 break; 5137 case ResTable_map::ATTR_L10N: 5138 l10nReq = bag->map.value.data; 5139 break; 5140 } 5141 bag++; 5142 cnt--; 5143 } 5144 unlockBag(bag); 5145 } else if (accessor && accessor->getAttributeType(attrID, &attrType)) { 5146 fromAccessor = true; 5147 if (attrType == ResTable_map::TYPE_ENUM 5148 || attrType == ResTable_map::TYPE_FLAGS 5149 || attrType == ResTable_map::TYPE_INTEGER) { 5150 accessor->getAttributeMin(attrID, &attrMin); 5151 accessor->getAttributeMax(attrID, &attrMax); 5152 } 5153 if (localizationSetting) { 5154 l10nReq = accessor->getAttributeL10N(attrID); 5155 } 5156 } 5157 } 5158 5159 const bool canStringCoerce = 5160 coerceType && (attrType&ResTable_map::TYPE_STRING) != 0; 5161 5162 if (*s == '@') { 5163 outValue->dataType = outValue->TYPE_REFERENCE; 5164 5165 // Note: we don't check attrType here because the reference can 5166 // be to any other type; we just need to count on the client making 5167 // sure the referenced type is correct. 5168 5169 //printf("Looking up ref: %s\n", String8(s, len).string()); 5170 5171 // It's a reference! 5172 if (len == 5 && s[1]=='n' && s[2]=='u' && s[3]=='l' && s[4]=='l') { 5173 // Special case @null as undefined. This will be converted by 5174 // AssetManager to TYPE_NULL with data DATA_NULL_UNDEFINED. 5175 outValue->data = 0; 5176 return true; 5177 } else if (len == 6 && s[1]=='e' && s[2]=='m' && s[3]=='p' && s[4]=='t' && s[5]=='y') { 5178 // Special case @empty as explicitly defined empty value. 5179 outValue->dataType = Res_value::TYPE_NULL; 5180 outValue->data = Res_value::DATA_NULL_EMPTY; 5181 return true; 5182 } else { 5183 bool createIfNotFound = false; 5184 const char16_t* resourceRefName; 5185 int resourceNameLen; 5186 if (len > 2 && s[1] == '+') { 5187 createIfNotFound = true; 5188 resourceRefName = s + 2; 5189 resourceNameLen = len - 2; 5190 } else if (len > 2 && s[1] == '*') { 5191 enforcePrivate = false; 5192 resourceRefName = s + 2; 5193 resourceNameLen = len - 2; 5194 } else { 5195 createIfNotFound = false; 5196 resourceRefName = s + 1; 5197 resourceNameLen = len - 1; 5198 } 5199 String16 package, type, name; 5200 if (!expandResourceRef(resourceRefName,resourceNameLen, &package, &type, &name, 5201 defType, defPackage, &errorMsg)) { 5202 if (accessor != NULL) { 5203 accessor->reportError(accessorCookie, errorMsg); 5204 } 5205 return false; 5206 } 5207 5208 uint32_t specFlags = 0; 5209 uint32_t rid = identifierForName(name.string(), name.size(), type.string(), 5210 type.size(), package.string(), package.size(), &specFlags); 5211 if (rid != 0) { 5212 if (enforcePrivate) { 5213 if (accessor == NULL || accessor->getAssetsPackage() != package) { 5214 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) { 5215 if (accessor != NULL) { 5216 accessor->reportError(accessorCookie, "Resource is not public."); 5217 } 5218 return false; 5219 } 5220 } 5221 } 5222 5223 if (accessor) { 5224 rid = Res_MAKEID( 5225 accessor->getRemappedPackage(Res_GETPACKAGE(rid)), 5226 Res_GETTYPE(rid), Res_GETENTRY(rid)); 5227 if (kDebugTableNoisy) { 5228 ALOGI("Incl %s:%s/%s: 0x%08x\n", 5229 String8(package).string(), String8(type).string(), 5230 String8(name).string(), rid); 5231 } 5232 } 5233 5234 uint32_t packageId = Res_GETPACKAGE(rid) + 1; 5235 if (packageId != APP_PACKAGE_ID && packageId != SYS_PACKAGE_ID) { 5236 outValue->dataType = Res_value::TYPE_DYNAMIC_REFERENCE; 5237 } 5238 outValue->data = rid; 5239 return true; 5240 } 5241 5242 if (accessor) { 5243 uint32_t rid = accessor->getCustomResourceWithCreation(package, type, name, 5244 createIfNotFound); 5245 if (rid != 0) { 5246 if (kDebugTableNoisy) { 5247 ALOGI("Pckg %s:%s/%s: 0x%08x\n", 5248 String8(package).string(), String8(type).string(), 5249 String8(name).string(), rid); 5250 } 5251 uint32_t packageId = Res_GETPACKAGE(rid) + 1; 5252 if (packageId == 0x00) { 5253 outValue->data = rid; 5254 outValue->dataType = Res_value::TYPE_DYNAMIC_REFERENCE; 5255 return true; 5256 } else if (packageId == APP_PACKAGE_ID || packageId == SYS_PACKAGE_ID) { 5257 // We accept packageId's generated as 0x01 in order to support 5258 // building the android system resources 5259 outValue->data = rid; 5260 return true; 5261 } 5262 } 5263 } 5264 } 5265 5266 if (accessor != NULL) { 5267 accessor->reportError(accessorCookie, "No resource found that matches the given name"); 5268 } 5269 return false; 5270 } 5271 5272 // if we got to here, and localization is required and it's not a reference, 5273 // complain and bail. 5274 if (l10nReq == ResTable_map::L10N_SUGGESTED) { 5275 if (localizationSetting) { 5276 if (accessor != NULL) { 5277 accessor->reportError(accessorCookie, "This attribute must be localized."); 5278 } 5279 } 5280 } 5281 5282 if (*s == '#') { 5283 // It's a color! Convert to an integer of the form 0xaarrggbb. 5284 uint32_t color = 0; 5285 bool error = false; 5286 if (len == 4) { 5287 outValue->dataType = outValue->TYPE_INT_COLOR_RGB4; 5288 color |= 0xFF000000; 5289 color |= get_hex(s[1], &error) << 20; 5290 color |= get_hex(s[1], &error) << 16; 5291 color |= get_hex(s[2], &error) << 12; 5292 color |= get_hex(s[2], &error) << 8; 5293 color |= get_hex(s[3], &error) << 4; 5294 color |= get_hex(s[3], &error); 5295 } else if (len == 5) { 5296 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB4; 5297 color |= get_hex(s[1], &error) << 28; 5298 color |= get_hex(s[1], &error) << 24; 5299 color |= get_hex(s[2], &error) << 20; 5300 color |= get_hex(s[2], &error) << 16; 5301 color |= get_hex(s[3], &error) << 12; 5302 color |= get_hex(s[3], &error) << 8; 5303 color |= get_hex(s[4], &error) << 4; 5304 color |= get_hex(s[4], &error); 5305 } else if (len == 7) { 5306 outValue->dataType = outValue->TYPE_INT_COLOR_RGB8; 5307 color |= 0xFF000000; 5308 color |= get_hex(s[1], &error) << 20; 5309 color |= get_hex(s[2], &error) << 16; 5310 color |= get_hex(s[3], &error) << 12; 5311 color |= get_hex(s[4], &error) << 8; 5312 color |= get_hex(s[5], &error) << 4; 5313 color |= get_hex(s[6], &error); 5314 } else if (len == 9) { 5315 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB8; 5316 color |= get_hex(s[1], &error) << 28; 5317 color |= get_hex(s[2], &error) << 24; 5318 color |= get_hex(s[3], &error) << 20; 5319 color |= get_hex(s[4], &error) << 16; 5320 color |= get_hex(s[5], &error) << 12; 5321 color |= get_hex(s[6], &error) << 8; 5322 color |= get_hex(s[7], &error) << 4; 5323 color |= get_hex(s[8], &error); 5324 } else { 5325 error = true; 5326 } 5327 if (!error) { 5328 if ((attrType&ResTable_map::TYPE_COLOR) == 0) { 5329 if (!canStringCoerce) { 5330 if (accessor != NULL) { 5331 accessor->reportError(accessorCookie, 5332 "Color types not allowed"); 5333 } 5334 return false; 5335 } 5336 } else { 5337 outValue->data = color; 5338 //printf("Color input=%s, output=0x%x\n", String8(s, len).string(), color); 5339 return true; 5340 } 5341 } else { 5342 if ((attrType&ResTable_map::TYPE_COLOR) != 0) { 5343 if (accessor != NULL) { 5344 accessor->reportError(accessorCookie, "Color value not valid --" 5345 " must be #rgb, #argb, #rrggbb, or #aarrggbb"); 5346 } 5347 #if 0 5348 fprintf(stderr, "%s: Color ID %s value %s is not valid\n", 5349 "Resource File", //(const char*)in->getPrintableSource(), 5350 String8(*curTag).string(), 5351 String8(s, len).string()); 5352 #endif 5353 return false; 5354 } 5355 } 5356 } 5357 5358 if (*s == '?') { 5359 outValue->dataType = outValue->TYPE_ATTRIBUTE; 5360 5361 // Note: we don't check attrType here because the reference can 5362 // be to any other type; we just need to count on the client making 5363 // sure the referenced type is correct. 5364 5365 //printf("Looking up attr: %s\n", String8(s, len).string()); 5366 5367 static const String16 attr16("attr"); 5368 String16 package, type, name; 5369 if (!expandResourceRef(s+1, len-1, &package, &type, &name, 5370 &attr16, defPackage, &errorMsg)) { 5371 if (accessor != NULL) { 5372 accessor->reportError(accessorCookie, errorMsg); 5373 } 5374 return false; 5375 } 5376 5377 //printf("Pkg: %s, Type: %s, Name: %s\n", 5378 // String8(package).string(), String8(type).string(), 5379 // String8(name).string()); 5380 uint32_t specFlags = 0; 5381 uint32_t rid = 5382 identifierForName(name.string(), name.size(), 5383 type.string(), type.size(), 5384 package.string(), package.size(), &specFlags); 5385 if (rid != 0) { 5386 if (enforcePrivate) { 5387 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) { 5388 if (accessor != NULL) { 5389 accessor->reportError(accessorCookie, "Attribute is not public."); 5390 } 5391 return false; 5392 } 5393 } 5394 5395 if (accessor) { 5396 rid = Res_MAKEID( 5397 accessor->getRemappedPackage(Res_GETPACKAGE(rid)), 5398 Res_GETTYPE(rid), Res_GETENTRY(rid)); 5399 } 5400 5401 uint32_t packageId = Res_GETPACKAGE(rid) + 1; 5402 if (packageId != APP_PACKAGE_ID && packageId != SYS_PACKAGE_ID) { 5403 outValue->dataType = Res_value::TYPE_DYNAMIC_ATTRIBUTE; 5404 } 5405 outValue->data = rid; 5406 return true; 5407 } 5408 5409 if (accessor) { 5410 uint32_t rid = accessor->getCustomResource(package, type, name); 5411 if (rid != 0) { 5412 uint32_t packageId = Res_GETPACKAGE(rid) + 1; 5413 if (packageId == 0x00) { 5414 outValue->data = rid; 5415 outValue->dataType = Res_value::TYPE_DYNAMIC_ATTRIBUTE; 5416 return true; 5417 } else if (packageId == APP_PACKAGE_ID || packageId == SYS_PACKAGE_ID) { 5418 // We accept packageId's generated as 0x01 in order to support 5419 // building the android system resources 5420 outValue->data = rid; 5421 return true; 5422 } 5423 } 5424 } 5425 5426 if (accessor != NULL) { 5427 accessor->reportError(accessorCookie, "No resource found that matches the given name"); 5428 } 5429 return false; 5430 } 5431 5432 if (stringToInt(s, len, outValue)) { 5433 if ((attrType&ResTable_map::TYPE_INTEGER) == 0) { 5434 // If this type does not allow integers, but does allow floats, 5435 // fall through on this error case because the float type should 5436 // be able to accept any integer value. 5437 if (!canStringCoerce && (attrType&ResTable_map::TYPE_FLOAT) == 0) { 5438 if (accessor != NULL) { 5439 accessor->reportError(accessorCookie, "Integer types not allowed"); 5440 } 5441 return false; 5442 } 5443 } else { 5444 if (((int32_t)outValue->data) < ((int32_t)attrMin) 5445 || ((int32_t)outValue->data) > ((int32_t)attrMax)) { 5446 if (accessor != NULL) { 5447 accessor->reportError(accessorCookie, "Integer value out of range"); 5448 } 5449 return false; 5450 } 5451 return true; 5452 } 5453 } 5454 5455 if (stringToFloat(s, len, outValue)) { 5456 if (outValue->dataType == Res_value::TYPE_DIMENSION) { 5457 if ((attrType&ResTable_map::TYPE_DIMENSION) != 0) { 5458 return true; 5459 } 5460 if (!canStringCoerce) { 5461 if (accessor != NULL) { 5462 accessor->reportError(accessorCookie, "Dimension types not allowed"); 5463 } 5464 return false; 5465 } 5466 } else if (outValue->dataType == Res_value::TYPE_FRACTION) { 5467 if ((attrType&ResTable_map::TYPE_FRACTION) != 0) { 5468 return true; 5469 } 5470 if (!canStringCoerce) { 5471 if (accessor != NULL) { 5472 accessor->reportError(accessorCookie, "Fraction types not allowed"); 5473 } 5474 return false; 5475 } 5476 } else if ((attrType&ResTable_map::TYPE_FLOAT) == 0) { 5477 if (!canStringCoerce) { 5478 if (accessor != NULL) { 5479 accessor->reportError(accessorCookie, "Float types not allowed"); 5480 } 5481 return false; 5482 } 5483 } else { 5484 return true; 5485 } 5486 } 5487 5488 if (len == 4) { 5489 if ((s[0] == 't' || s[0] == 'T') && 5490 (s[1] == 'r' || s[1] == 'R') && 5491 (s[2] == 'u' || s[2] == 'U') && 5492 (s[3] == 'e' || s[3] == 'E')) { 5493 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) { 5494 if (!canStringCoerce) { 5495 if (accessor != NULL) { 5496 accessor->reportError(accessorCookie, "Boolean types not allowed"); 5497 } 5498 return false; 5499 } 5500 } else { 5501 outValue->dataType = outValue->TYPE_INT_BOOLEAN; 5502 outValue->data = (uint32_t)-1; 5503 return true; 5504 } 5505 } 5506 } 5507 5508 if (len == 5) { 5509 if ((s[0] == 'f' || s[0] == 'F') && 5510 (s[1] == 'a' || s[1] == 'A') && 5511 (s[2] == 'l' || s[2] == 'L') && 5512 (s[3] == 's' || s[3] == 'S') && 5513 (s[4] == 'e' || s[4] == 'E')) { 5514 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) { 5515 if (!canStringCoerce) { 5516 if (accessor != NULL) { 5517 accessor->reportError(accessorCookie, "Boolean types not allowed"); 5518 } 5519 return false; 5520 } 5521 } else { 5522 outValue->dataType = outValue->TYPE_INT_BOOLEAN; 5523 outValue->data = 0; 5524 return true; 5525 } 5526 } 5527 } 5528 5529 if ((attrType&ResTable_map::TYPE_ENUM) != 0) { 5530 const ssize_t p = getResourcePackageIndex(attrID); 5531 const bag_entry* bag; 5532 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1; 5533 //printf("Got %d for enum\n", cnt); 5534 if (cnt >= 0) { 5535 resource_name rname; 5536 while (cnt > 0) { 5537 if (!Res_INTERNALID(bag->map.name.ident)) { 5538 //printf("Trying attr #%08x\n", bag->map.name.ident); 5539 if (getResourceName(bag->map.name.ident, false, &rname)) { 5540 #if 0 5541 printf("Matching %s against %s (0x%08x)\n", 5542 String8(s, len).string(), 5543 String8(rname.name, rname.nameLen).string(), 5544 bag->map.name.ident); 5545 #endif 5546 if (strzcmp16(s, len, rname.name, rname.nameLen) == 0) { 5547 outValue->dataType = bag->map.value.dataType; 5548 outValue->data = bag->map.value.data; 5549 unlockBag(bag); 5550 return true; 5551 } 5552 } 5553 5554 } 5555 bag++; 5556 cnt--; 5557 } 5558 unlockBag(bag); 5559 } 5560 5561 if (fromAccessor) { 5562 if (accessor->getAttributeEnum(attrID, s, len, outValue)) { 5563 return true; 5564 } 5565 } 5566 } 5567 5568 if ((attrType&ResTable_map::TYPE_FLAGS) != 0) { 5569 const ssize_t p = getResourcePackageIndex(attrID); 5570 const bag_entry* bag; 5571 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1; 5572 //printf("Got %d for flags\n", cnt); 5573 if (cnt >= 0) { 5574 bool failed = false; 5575 resource_name rname; 5576 outValue->dataType = Res_value::TYPE_INT_HEX; 5577 outValue->data = 0; 5578 const char16_t* end = s + len; 5579 const char16_t* pos = s; 5580 while (pos < end && !failed) { 5581 const char16_t* start = pos; 5582 pos++; 5583 while (pos < end && *pos != '|') { 5584 pos++; 5585 } 5586 //printf("Looking for: %s\n", String8(start, pos-start).string()); 5587 const bag_entry* bagi = bag; 5588 ssize_t i; 5589 for (i=0; i<cnt; i++, bagi++) { 5590 if (!Res_INTERNALID(bagi->map.name.ident)) { 5591 //printf("Trying attr #%08x\n", bagi->map.name.ident); 5592 if (getResourceName(bagi->map.name.ident, false, &rname)) { 5593 #if 0 5594 printf("Matching %s against %s (0x%08x)\n", 5595 String8(start,pos-start).string(), 5596 String8(rname.name, rname.nameLen).string(), 5597 bagi->map.name.ident); 5598 #endif 5599 if (strzcmp16(start, pos-start, rname.name, rname.nameLen) == 0) { 5600 outValue->data |= bagi->map.value.data; 5601 break; 5602 } 5603 } 5604 } 5605 } 5606 if (i >= cnt) { 5607 // Didn't find this flag identifier. 5608 failed = true; 5609 } 5610 if (pos < end) { 5611 pos++; 5612 } 5613 } 5614 unlockBag(bag); 5615 if (!failed) { 5616 //printf("Final flag value: 0x%lx\n", outValue->data); 5617 return true; 5618 } 5619 } 5620 5621 5622 if (fromAccessor) { 5623 if (accessor->getAttributeFlags(attrID, s, len, outValue)) { 5624 //printf("Final flag value: 0x%lx\n", outValue->data); 5625 return true; 5626 } 5627 } 5628 } 5629 5630 if ((attrType&ResTable_map::TYPE_STRING) == 0) { 5631 if (accessor != NULL) { 5632 accessor->reportError(accessorCookie, "String types not allowed"); 5633 } 5634 return false; 5635 } 5636 5637 // Generic string handling... 5638 outValue->dataType = outValue->TYPE_STRING; 5639 if (outString) { 5640 bool failed = collectString(outString, s, len, preserveSpaces, &errorMsg); 5641 if (accessor != NULL) { 5642 accessor->reportError(accessorCookie, errorMsg); 5643 } 5644 return failed; 5645 } 5646 5647 return true; 5648} 5649 5650bool ResTable::collectString(String16* outString, 5651 const char16_t* s, size_t len, 5652 bool preserveSpaces, 5653 const char** outErrorMsg, 5654 bool append) 5655{ 5656 String16 tmp; 5657 5658 char quoted = 0; 5659 const char16_t* p = s; 5660 while (p < (s+len)) { 5661 while (p < (s+len)) { 5662 const char16_t c = *p; 5663 if (c == '\\') { 5664 break; 5665 } 5666 if (!preserveSpaces) { 5667 if (quoted == 0 && isspace16(c) 5668 && (c != ' ' || isspace16(*(p+1)))) { 5669 break; 5670 } 5671 if (c == '"' && (quoted == 0 || quoted == '"')) { 5672 break; 5673 } 5674 if (c == '\'' && (quoted == 0 || quoted == '\'')) { 5675 /* 5676 * In practice, when people write ' instead of \' 5677 * in a string, they are doing it by accident 5678 * instead of really meaning to use ' as a quoting 5679 * character. Warn them so they don't lose it. 5680 */ 5681 if (outErrorMsg) { 5682 *outErrorMsg = "Apostrophe not preceded by \\"; 5683 } 5684 return false; 5685 } 5686 } 5687 p++; 5688 } 5689 if (p < (s+len)) { 5690 if (p > s) { 5691 tmp.append(String16(s, p-s)); 5692 } 5693 if (!preserveSpaces && (*p == '"' || *p == '\'')) { 5694 if (quoted == 0) { 5695 quoted = *p; 5696 } else { 5697 quoted = 0; 5698 } 5699 p++; 5700 } else if (!preserveSpaces && isspace16(*p)) { 5701 // Space outside of a quote -- consume all spaces and 5702 // leave a single plain space char. 5703 tmp.append(String16(" ")); 5704 p++; 5705 while (p < (s+len) && isspace16(*p)) { 5706 p++; 5707 } 5708 } else if (*p == '\\') { 5709 p++; 5710 if (p < (s+len)) { 5711 switch (*p) { 5712 case 't': 5713 tmp.append(String16("\t")); 5714 break; 5715 case 'n': 5716 tmp.append(String16("\n")); 5717 break; 5718 case '#': 5719 tmp.append(String16("#")); 5720 break; 5721 case '@': 5722 tmp.append(String16("@")); 5723 break; 5724 case '?': 5725 tmp.append(String16("?")); 5726 break; 5727 case '"': 5728 tmp.append(String16("\"")); 5729 break; 5730 case '\'': 5731 tmp.append(String16("'")); 5732 break; 5733 case '\\': 5734 tmp.append(String16("\\")); 5735 break; 5736 case 'u': 5737 { 5738 char16_t chr = 0; 5739 int i = 0; 5740 while (i < 4 && p[1] != 0) { 5741 p++; 5742 i++; 5743 int c; 5744 if (*p >= '0' && *p <= '9') { 5745 c = *p - '0'; 5746 } else if (*p >= 'a' && *p <= 'f') { 5747 c = *p - 'a' + 10; 5748 } else if (*p >= 'A' && *p <= 'F') { 5749 c = *p - 'A' + 10; 5750 } else { 5751 if (outErrorMsg) { 5752 *outErrorMsg = "Bad character in \\u unicode escape sequence"; 5753 } 5754 return false; 5755 } 5756 chr = (chr<<4) | c; 5757 } 5758 tmp.append(String16(&chr, 1)); 5759 } break; 5760 default: 5761 // ignore unknown escape chars. 5762 break; 5763 } 5764 p++; 5765 } 5766 } 5767 len -= (p-s); 5768 s = p; 5769 } 5770 } 5771 5772 if (tmp.size() != 0) { 5773 if (len > 0) { 5774 tmp.append(String16(s, len)); 5775 } 5776 if (append) { 5777 outString->append(tmp); 5778 } else { 5779 outString->setTo(tmp); 5780 } 5781 } else { 5782 if (append) { 5783 outString->append(String16(s, len)); 5784 } else { 5785 outString->setTo(s, len); 5786 } 5787 } 5788 5789 return true; 5790} 5791 5792size_t ResTable::getBasePackageCount() const 5793{ 5794 if (mError != NO_ERROR) { 5795 return 0; 5796 } 5797 return mPackageGroups.size(); 5798} 5799 5800const String16 ResTable::getBasePackageName(size_t idx) const 5801{ 5802 if (mError != NO_ERROR) { 5803 return String16(); 5804 } 5805 LOG_FATAL_IF(idx >= mPackageGroups.size(), 5806 "Requested package index %d past package count %d", 5807 (int)idx, (int)mPackageGroups.size()); 5808 return mPackageGroups[idx]->name; 5809} 5810 5811uint32_t ResTable::getBasePackageId(size_t idx) const 5812{ 5813 if (mError != NO_ERROR) { 5814 return 0; 5815 } 5816 LOG_FATAL_IF(idx >= mPackageGroups.size(), 5817 "Requested package index %d past package count %d", 5818 (int)idx, (int)mPackageGroups.size()); 5819 return mPackageGroups[idx]->id; 5820} 5821 5822uint32_t ResTable::getLastTypeIdForPackage(size_t idx) const 5823{ 5824 if (mError != NO_ERROR) { 5825 return 0; 5826 } 5827 LOG_FATAL_IF(idx >= mPackageGroups.size(), 5828 "Requested package index %d past package count %d", 5829 (int)idx, (int)mPackageGroups.size()); 5830 const PackageGroup* const group = mPackageGroups[idx]; 5831 return group->largestTypeId; 5832} 5833 5834size_t ResTable::getTableCount() const 5835{ 5836 return mHeaders.size(); 5837} 5838 5839const ResStringPool* ResTable::getTableStringBlock(size_t index) const 5840{ 5841 return &mHeaders[index]->values; 5842} 5843 5844int32_t ResTable::getTableCookie(size_t index) const 5845{ 5846 return mHeaders[index]->cookie; 5847} 5848 5849const DynamicRefTable* ResTable::getDynamicRefTableForCookie(int32_t cookie) const 5850{ 5851 const size_t N = mPackageGroups.size(); 5852 for (size_t i = 0; i < N; i++) { 5853 const PackageGroup* pg = mPackageGroups[i]; 5854 size_t M = pg->packages.size(); 5855 for (size_t j = 0; j < M; j++) { 5856 if (pg->packages[j]->header->cookie == cookie) { 5857 return &pg->dynamicRefTable; 5858 } 5859 } 5860 } 5861 return NULL; 5862} 5863 5864static bool compareResTableConfig(const ResTable_config& a, const ResTable_config& b) { 5865 return a.compare(b) < 0; 5866} 5867 5868template <typename Func> 5869void ResTable::forEachConfiguration(bool ignoreMipmap, bool ignoreAndroidPackage, 5870 bool includeSystemConfigs, const Func& f) const { 5871 const size_t packageCount = mPackageGroups.size(); 5872 const String16 android("android"); 5873 for (size_t i = 0; i < packageCount; i++) { 5874 const PackageGroup* packageGroup = mPackageGroups[i]; 5875 if (ignoreAndroidPackage && android == packageGroup->name) { 5876 continue; 5877 } 5878 if (!includeSystemConfigs && packageGroup->isSystemAsset) { 5879 continue; 5880 } 5881 const size_t typeCount = packageGroup->types.size(); 5882 for (size_t j = 0; j < typeCount; j++) { 5883 const TypeList& typeList = packageGroup->types[j]; 5884 const size_t numTypes = typeList.size(); 5885 for (size_t k = 0; k < numTypes; k++) { 5886 const Type* type = typeList[k]; 5887 const ResStringPool& typeStrings = type->package->typeStrings; 5888 if (ignoreMipmap && typeStrings.string8ObjectAt( 5889 type->typeSpec->id - 1) == "mipmap") { 5890 continue; 5891 } 5892 5893 const size_t numConfigs = type->configs.size(); 5894 for (size_t m = 0; m < numConfigs; m++) { 5895 const ResTable_type* config = type->configs[m]; 5896 ResTable_config cfg; 5897 memset(&cfg, 0, sizeof(ResTable_config)); 5898 cfg.copyFromDtoH(config->config); 5899 5900 f(cfg); 5901 } 5902 } 5903 } 5904 } 5905} 5906 5907void ResTable::getConfigurations(Vector<ResTable_config>* configs, bool ignoreMipmap, 5908 bool ignoreAndroidPackage, bool includeSystemConfigs) const { 5909 auto func = [&](const ResTable_config& cfg) { 5910 const auto beginIter = configs->begin(); 5911 const auto endIter = configs->end(); 5912 5913 auto iter = std::lower_bound(beginIter, endIter, cfg, compareResTableConfig); 5914 if (iter == endIter || iter->compare(cfg) != 0) { 5915 configs->insertAt(cfg, std::distance(beginIter, iter)); 5916 } 5917 }; 5918 forEachConfiguration(ignoreMipmap, ignoreAndroidPackage, includeSystemConfigs, func); 5919} 5920 5921static bool compareString8AndCString(const String8& str, const char* cStr) { 5922 return strcmp(str.string(), cStr) < 0; 5923} 5924 5925void ResTable::getLocales(Vector<String8>* locales, bool includeSystemLocales, 5926 bool mergeEquivalentLangs) const { 5927 char locale[RESTABLE_MAX_LOCALE_LEN]; 5928 5929 forEachConfiguration(false, false, includeSystemLocales, [&](const ResTable_config& cfg) { 5930 if (cfg.locale != 0) { 5931 cfg.getBcp47Locale(locale, mergeEquivalentLangs /* canonicalize if merging */); 5932 5933 const auto beginIter = locales->begin(); 5934 const auto endIter = locales->end(); 5935 5936 auto iter = std::lower_bound(beginIter, endIter, locale, compareString8AndCString); 5937 if (iter == endIter || strcmp(iter->string(), locale) != 0) { 5938 locales->insertAt(String8(locale), std::distance(beginIter, iter)); 5939 } 5940 } 5941 }); 5942} 5943 5944StringPoolRef::StringPoolRef(const ResStringPool* pool, uint32_t index) 5945 : mPool(pool), mIndex(index) {} 5946 5947StringPoolRef::StringPoolRef() 5948 : mPool(NULL), mIndex(0) {} 5949 5950const char* StringPoolRef::string8(size_t* outLen) const { 5951 if (mPool != NULL) { 5952 return mPool->string8At(mIndex, outLen); 5953 } 5954 if (outLen != NULL) { 5955 *outLen = 0; 5956 } 5957 return NULL; 5958} 5959 5960const char16_t* StringPoolRef::string16(size_t* outLen) const { 5961 if (mPool != NULL) { 5962 return mPool->stringAt(mIndex, outLen); 5963 } 5964 if (outLen != NULL) { 5965 *outLen = 0; 5966 } 5967 return NULL; 5968} 5969 5970bool ResTable::getResourceFlags(uint32_t resID, uint32_t* outFlags) const { 5971 if (mError != NO_ERROR) { 5972 return false; 5973 } 5974 5975 const ssize_t p = getResourcePackageIndex(resID); 5976 const int t = Res_GETTYPE(resID); 5977 const int e = Res_GETENTRY(resID); 5978 5979 if (p < 0) { 5980 if (Res_GETPACKAGE(resID)+1 == 0) { 5981 ALOGW("No package identifier when getting flags for resource number 0x%08x", resID); 5982 } else { 5983 ALOGW("No known package when getting flags for resource number 0x%08x", resID); 5984 } 5985 return false; 5986 } 5987 if (t < 0) { 5988 ALOGW("No type identifier when getting flags for resource number 0x%08x", resID); 5989 return false; 5990 } 5991 5992 const PackageGroup* const grp = mPackageGroups[p]; 5993 if (grp == NULL) { 5994 ALOGW("Bad identifier when getting flags for resource number 0x%08x", resID); 5995 return false; 5996 } 5997 5998 Entry entry; 5999 status_t err = getEntry(grp, t, e, NULL, &entry); 6000 if (err != NO_ERROR) { 6001 return false; 6002 } 6003 6004 *outFlags = entry.specFlags; 6005 return true; 6006} 6007 6008status_t ResTable::getEntry( 6009 const PackageGroup* packageGroup, int typeIndex, int entryIndex, 6010 const ResTable_config* config, 6011 Entry* outEntry) const 6012{ 6013 const TypeList& typeList = packageGroup->types[typeIndex]; 6014 if (typeList.isEmpty()) { 6015 ALOGV("Skipping entry type index 0x%02x because type is NULL!\n", typeIndex); 6016 return BAD_TYPE; 6017 } 6018 6019 const ResTable_type* bestType = NULL; 6020 uint32_t bestOffset = ResTable_type::NO_ENTRY; 6021 const Package* bestPackage = NULL; 6022 uint32_t specFlags = 0; 6023 uint8_t actualTypeIndex = typeIndex; 6024 ResTable_config bestConfig; 6025 memset(&bestConfig, 0, sizeof(bestConfig)); 6026 6027 // Iterate over the Types of each package. 6028 const size_t typeCount = typeList.size(); 6029 for (size_t i = 0; i < typeCount; i++) { 6030 const Type* const typeSpec = typeList[i]; 6031 6032 int realEntryIndex = entryIndex; 6033 int realTypeIndex = typeIndex; 6034 bool currentTypeIsOverlay = false; 6035 6036 // Runtime overlay packages provide a mapping of app resource 6037 // ID to package resource ID. 6038 if (typeSpec->idmapEntries.hasEntries()) { 6039 uint16_t overlayEntryIndex; 6040 if (typeSpec->idmapEntries.lookup(entryIndex, &overlayEntryIndex) != NO_ERROR) { 6041 // No such mapping exists 6042 continue; 6043 } 6044 realEntryIndex = overlayEntryIndex; 6045 realTypeIndex = typeSpec->idmapEntries.overlayTypeId() - 1; 6046 currentTypeIsOverlay = true; 6047 } 6048 6049 if (static_cast<size_t>(realEntryIndex) >= typeSpec->entryCount) { 6050 ALOGW("For resource 0x%08x, entry index(%d) is beyond type entryCount(%d)", 6051 Res_MAKEID(packageGroup->id - 1, typeIndex, entryIndex), 6052 entryIndex, static_cast<int>(typeSpec->entryCount)); 6053 // We should normally abort here, but some legacy apps declare 6054 // resources in the 'android' package (old bug in AAPT). 6055 continue; 6056 } 6057 6058 // Aggregate all the flags for each package that defines this entry. 6059 if (typeSpec->typeSpecFlags != NULL) { 6060 specFlags |= dtohl(typeSpec->typeSpecFlags[realEntryIndex]); 6061 } else { 6062 specFlags = -1; 6063 } 6064 6065 const Vector<const ResTable_type*>* candidateConfigs = &typeSpec->configs; 6066 6067 std::shared_ptr<Vector<const ResTable_type*>> filteredConfigs; 6068 if (config && memcmp(&mParams, config, sizeof(mParams)) == 0) { 6069 // Grab the lock first so we can safely get the current filtered list. 6070 AutoMutex _lock(mFilteredConfigLock); 6071 6072 // This configuration is equal to the one we have previously cached for, 6073 // so use the filtered configs. 6074 6075 const TypeCacheEntry& cacheEntry = packageGroup->typeCacheEntries[typeIndex]; 6076 if (i < cacheEntry.filteredConfigs.size()) { 6077 if (cacheEntry.filteredConfigs[i]) { 6078 // Grab a reference to the shared_ptr so it doesn't get destroyed while 6079 // going through this list. 6080 filteredConfigs = cacheEntry.filteredConfigs[i]; 6081 6082 // Use this filtered list. 6083 candidateConfigs = filteredConfigs.get(); 6084 } 6085 } 6086 } 6087 6088 const size_t numConfigs = candidateConfigs->size(); 6089 for (size_t c = 0; c < numConfigs; c++) { 6090 const ResTable_type* const thisType = candidateConfigs->itemAt(c); 6091 if (thisType == NULL) { 6092 continue; 6093 } 6094 6095 ResTable_config thisConfig; 6096 thisConfig.copyFromDtoH(thisType->config); 6097 6098 // Check to make sure this one is valid for the current parameters. 6099 if (config != NULL && !thisConfig.match(*config)) { 6100 continue; 6101 } 6102 6103 // Check if there is the desired entry in this type. 6104 const uint32_t* const eindex = reinterpret_cast<const uint32_t*>( 6105 reinterpret_cast<const uint8_t*>(thisType) + dtohs(thisType->header.headerSize)); 6106 6107 uint32_t thisOffset = dtohl(eindex[realEntryIndex]); 6108 if (thisOffset == ResTable_type::NO_ENTRY) { 6109 // There is no entry for this index and configuration. 6110 continue; 6111 } 6112 6113 if (bestType != NULL) { 6114 // Check if this one is less specific than the last found. If so, 6115 // we will skip it. We check starting with things we most care 6116 // about to those we least care about. 6117 if (!thisConfig.isBetterThan(bestConfig, config)) { 6118 if (!currentTypeIsOverlay || thisConfig.compare(bestConfig) != 0) { 6119 continue; 6120 } 6121 } 6122 } 6123 6124 bestType = thisType; 6125 bestOffset = thisOffset; 6126 bestConfig = thisConfig; 6127 bestPackage = typeSpec->package; 6128 actualTypeIndex = realTypeIndex; 6129 6130 // If no config was specified, any type will do, so skip 6131 if (config == NULL) { 6132 break; 6133 } 6134 } 6135 } 6136 6137 if (bestType == NULL) { 6138 return BAD_INDEX; 6139 } 6140 6141 bestOffset += dtohl(bestType->entriesStart); 6142 6143 if (bestOffset > (dtohl(bestType->header.size)-sizeof(ResTable_entry))) { 6144 ALOGW("ResTable_entry at 0x%x is beyond type chunk data 0x%x", 6145 bestOffset, dtohl(bestType->header.size)); 6146 return BAD_TYPE; 6147 } 6148 if ((bestOffset & 0x3) != 0) { 6149 ALOGW("ResTable_entry at 0x%x is not on an integer boundary", bestOffset); 6150 return BAD_TYPE; 6151 } 6152 6153 const ResTable_entry* const entry = reinterpret_cast<const ResTable_entry*>( 6154 reinterpret_cast<const uint8_t*>(bestType) + bestOffset); 6155 if (dtohs(entry->size) < sizeof(*entry)) { 6156 ALOGW("ResTable_entry size 0x%x is too small", dtohs(entry->size)); 6157 return BAD_TYPE; 6158 } 6159 6160 if (outEntry != NULL) { 6161 outEntry->entry = entry; 6162 outEntry->config = bestConfig; 6163 outEntry->type = bestType; 6164 outEntry->specFlags = specFlags; 6165 outEntry->package = bestPackage; 6166 outEntry->typeStr = StringPoolRef(&bestPackage->typeStrings, actualTypeIndex - bestPackage->typeIdOffset); 6167 outEntry->keyStr = StringPoolRef(&bestPackage->keyStrings, dtohl(entry->key.index)); 6168 } 6169 return NO_ERROR; 6170} 6171 6172status_t ResTable::parsePackage(const ResTable_package* const pkg, 6173 const Header* const header, bool appAsLib, bool isSystemAsset) 6174{ 6175 const uint8_t* base = (const uint8_t*)pkg; 6176 status_t err = validate_chunk(&pkg->header, sizeof(*pkg) - sizeof(pkg->typeIdOffset), 6177 header->dataEnd, "ResTable_package"); 6178 if (err != NO_ERROR) { 6179 return (mError=err); 6180 } 6181 6182 const uint32_t pkgSize = dtohl(pkg->header.size); 6183 6184 if (dtohl(pkg->typeStrings) >= pkgSize) { 6185 ALOGW("ResTable_package type strings at 0x%x are past chunk size 0x%x.", 6186 dtohl(pkg->typeStrings), pkgSize); 6187 return (mError=BAD_TYPE); 6188 } 6189 if ((dtohl(pkg->typeStrings)&0x3) != 0) { 6190 ALOGW("ResTable_package type strings at 0x%x is not on an integer boundary.", 6191 dtohl(pkg->typeStrings)); 6192 return (mError=BAD_TYPE); 6193 } 6194 if (dtohl(pkg->keyStrings) >= pkgSize) { 6195 ALOGW("ResTable_package key strings at 0x%x are past chunk size 0x%x.", 6196 dtohl(pkg->keyStrings), pkgSize); 6197 return (mError=BAD_TYPE); 6198 } 6199 if ((dtohl(pkg->keyStrings)&0x3) != 0) { 6200 ALOGW("ResTable_package key strings at 0x%x is not on an integer boundary.", 6201 dtohl(pkg->keyStrings)); 6202 return (mError=BAD_TYPE); 6203 } 6204 6205 uint32_t id = dtohl(pkg->id); 6206 KeyedVector<uint8_t, IdmapEntries> idmapEntries; 6207 6208 if (header->resourceIDMap != NULL) { 6209 uint8_t targetPackageId = 0; 6210 status_t err = parseIdmap(header->resourceIDMap, header->resourceIDMapSize, &targetPackageId, &idmapEntries); 6211 if (err != NO_ERROR) { 6212 ALOGW("Overlay is broken"); 6213 return (mError=err); 6214 } 6215 id = targetPackageId; 6216 } 6217 6218 if (id >= 256) { 6219 LOG_ALWAYS_FATAL("Package id out of range"); 6220 return NO_ERROR; 6221 } else if (id == 0 || (id == 0x7f && appAsLib) || isSystemAsset) { 6222 // This is a library or a system asset, so assign an ID 6223 id = mNextPackageId++; 6224 } 6225 6226 PackageGroup* group = NULL; 6227 Package* package = new Package(this, header, pkg); 6228 if (package == NULL) { 6229 return (mError=NO_MEMORY); 6230 } 6231 6232 err = package->typeStrings.setTo(base+dtohl(pkg->typeStrings), 6233 header->dataEnd-(base+dtohl(pkg->typeStrings))); 6234 if (err != NO_ERROR) { 6235 delete group; 6236 delete package; 6237 return (mError=err); 6238 } 6239 6240 err = package->keyStrings.setTo(base+dtohl(pkg->keyStrings), 6241 header->dataEnd-(base+dtohl(pkg->keyStrings))); 6242 if (err != NO_ERROR) { 6243 delete group; 6244 delete package; 6245 return (mError=err); 6246 } 6247 6248 size_t idx = mPackageMap[id]; 6249 if (idx == 0) { 6250 idx = mPackageGroups.size() + 1; 6251 6252 char16_t tmpName[sizeof(pkg->name)/sizeof(pkg->name[0])]; 6253 strcpy16_dtoh(tmpName, pkg->name, sizeof(pkg->name)/sizeof(pkg->name[0])); 6254 group = new PackageGroup(this, String16(tmpName), id, appAsLib, isSystemAsset); 6255 if (group == NULL) { 6256 delete package; 6257 return (mError=NO_MEMORY); 6258 } 6259 6260 err = mPackageGroups.add(group); 6261 if (err < NO_ERROR) { 6262 return (mError=err); 6263 } 6264 6265 mPackageMap[id] = static_cast<uint8_t>(idx); 6266 6267 // Find all packages that reference this package 6268 size_t N = mPackageGroups.size(); 6269 for (size_t i = 0; i < N; i++) { 6270 mPackageGroups[i]->dynamicRefTable.addMapping( 6271 group->name, static_cast<uint8_t>(group->id)); 6272 } 6273 } else { 6274 group = mPackageGroups.itemAt(idx - 1); 6275 if (group == NULL) { 6276 return (mError=UNKNOWN_ERROR); 6277 } 6278 } 6279 6280 err = group->packages.add(package); 6281 if (err < NO_ERROR) { 6282 return (mError=err); 6283 } 6284 6285 // Iterate through all chunks. 6286 const ResChunk_header* chunk = 6287 (const ResChunk_header*)(((const uint8_t*)pkg) 6288 + dtohs(pkg->header.headerSize)); 6289 const uint8_t* endPos = ((const uint8_t*)pkg) + dtohs(pkg->header.size); 6290 while (((const uint8_t*)chunk) <= (endPos-sizeof(ResChunk_header)) && 6291 ((const uint8_t*)chunk) <= (endPos-dtohl(chunk->size))) { 6292 if (kDebugTableNoisy) { 6293 ALOGV("PackageChunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n", 6294 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size), 6295 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header))); 6296 } 6297 const size_t csize = dtohl(chunk->size); 6298 const uint16_t ctype = dtohs(chunk->type); 6299 if (ctype == RES_TABLE_TYPE_SPEC_TYPE) { 6300 const ResTable_typeSpec* typeSpec = (const ResTable_typeSpec*)(chunk); 6301 err = validate_chunk(&typeSpec->header, sizeof(*typeSpec), 6302 endPos, "ResTable_typeSpec"); 6303 if (err != NO_ERROR) { 6304 return (mError=err); 6305 } 6306 6307 const size_t typeSpecSize = dtohl(typeSpec->header.size); 6308 const size_t newEntryCount = dtohl(typeSpec->entryCount); 6309 6310 if (kDebugLoadTableNoisy) { 6311 ALOGI("TypeSpec off %p: type=0x%x, headerSize=0x%x, size=%p\n", 6312 (void*)(base-(const uint8_t*)chunk), 6313 dtohs(typeSpec->header.type), 6314 dtohs(typeSpec->header.headerSize), 6315 (void*)typeSpecSize); 6316 } 6317 // look for block overrun or int overflow when multiplying by 4 6318 if ((dtohl(typeSpec->entryCount) > (INT32_MAX/sizeof(uint32_t)) 6319 || dtohs(typeSpec->header.headerSize)+(sizeof(uint32_t)*newEntryCount) 6320 > typeSpecSize)) { 6321 ALOGW("ResTable_typeSpec entry index to %p extends beyond chunk end %p.", 6322 (void*)(dtohs(typeSpec->header.headerSize) + (sizeof(uint32_t)*newEntryCount)), 6323 (void*)typeSpecSize); 6324 return (mError=BAD_TYPE); 6325 } 6326 6327 if (typeSpec->id == 0) { 6328 ALOGW("ResTable_type has an id of 0."); 6329 return (mError=BAD_TYPE); 6330 } 6331 6332 if (newEntryCount > 0) { 6333 uint8_t typeIndex = typeSpec->id - 1; 6334 ssize_t idmapIndex = idmapEntries.indexOfKey(typeSpec->id); 6335 if (idmapIndex >= 0) { 6336 typeIndex = idmapEntries[idmapIndex].targetTypeId() - 1; 6337 } 6338 6339 TypeList& typeList = group->types.editItemAt(typeIndex); 6340 if (!typeList.isEmpty()) { 6341 const Type* existingType = typeList[0]; 6342 if (existingType->entryCount != newEntryCount && idmapIndex < 0) { 6343 ALOGW("ResTable_typeSpec entry count inconsistent: given %d, previously %d", 6344 (int) newEntryCount, (int) existingType->entryCount); 6345 // We should normally abort here, but some legacy apps declare 6346 // resources in the 'android' package (old bug in AAPT). 6347 } 6348 } 6349 6350 Type* t = new Type(header, package, newEntryCount); 6351 t->typeSpec = typeSpec; 6352 t->typeSpecFlags = (const uint32_t*)( 6353 ((const uint8_t*)typeSpec) + dtohs(typeSpec->header.headerSize)); 6354 if (idmapIndex >= 0) { 6355 t->idmapEntries = idmapEntries[idmapIndex]; 6356 } 6357 typeList.add(t); 6358 group->largestTypeId = max(group->largestTypeId, typeSpec->id); 6359 } else { 6360 ALOGV("Skipping empty ResTable_typeSpec for type %d", typeSpec->id); 6361 } 6362 6363 } else if (ctype == RES_TABLE_TYPE_TYPE) { 6364 const ResTable_type* type = (const ResTable_type*)(chunk); 6365 err = validate_chunk(&type->header, sizeof(*type)-sizeof(ResTable_config)+4, 6366 endPos, "ResTable_type"); 6367 if (err != NO_ERROR) { 6368 return (mError=err); 6369 } 6370 6371 const uint32_t typeSize = dtohl(type->header.size); 6372 const size_t newEntryCount = dtohl(type->entryCount); 6373 6374 if (kDebugLoadTableNoisy) { 6375 printf("Type off %p: type=0x%x, headerSize=0x%x, size=%u\n", 6376 (void*)(base-(const uint8_t*)chunk), 6377 dtohs(type->header.type), 6378 dtohs(type->header.headerSize), 6379 typeSize); 6380 } 6381 if (dtohs(type->header.headerSize)+(sizeof(uint32_t)*newEntryCount) > typeSize) { 6382 ALOGW("ResTable_type entry index to %p extends beyond chunk end 0x%x.", 6383 (void*)(dtohs(type->header.headerSize) + (sizeof(uint32_t)*newEntryCount)), 6384 typeSize); 6385 return (mError=BAD_TYPE); 6386 } 6387 6388 if (newEntryCount != 0 6389 && dtohl(type->entriesStart) > (typeSize-sizeof(ResTable_entry))) { 6390 ALOGW("ResTable_type entriesStart at 0x%x extends beyond chunk end 0x%x.", 6391 dtohl(type->entriesStart), typeSize); 6392 return (mError=BAD_TYPE); 6393 } 6394 6395 if (type->id == 0) { 6396 ALOGW("ResTable_type has an id of 0."); 6397 return (mError=BAD_TYPE); 6398 } 6399 6400 if (newEntryCount > 0) { 6401 uint8_t typeIndex = type->id - 1; 6402 ssize_t idmapIndex = idmapEntries.indexOfKey(type->id); 6403 if (idmapIndex >= 0) { 6404 typeIndex = idmapEntries[idmapIndex].targetTypeId() - 1; 6405 } 6406 6407 TypeList& typeList = group->types.editItemAt(typeIndex); 6408 if (typeList.isEmpty()) { 6409 ALOGE("No TypeSpec for type %d", type->id); 6410 return (mError=BAD_TYPE); 6411 } 6412 6413 Type* t = typeList.editItemAt(typeList.size() - 1); 6414 if (newEntryCount != t->entryCount) { 6415 ALOGE("ResTable_type entry count inconsistent: given %d, previously %d", 6416 (int)newEntryCount, (int)t->entryCount); 6417 return (mError=BAD_TYPE); 6418 } 6419 6420 if (t->package != package) { 6421 ALOGE("No TypeSpec for type %d", type->id); 6422 return (mError=BAD_TYPE); 6423 } 6424 6425 t->configs.add(type); 6426 6427 if (kDebugTableGetEntry) { 6428 ResTable_config thisConfig; 6429 thisConfig.copyFromDtoH(type->config); 6430 ALOGI("Adding config to type %d: %s\n", type->id, 6431 thisConfig.toString().string()); 6432 } 6433 } else { 6434 ALOGV("Skipping empty ResTable_type for type %d", type->id); 6435 } 6436 6437 } else if (ctype == RES_TABLE_LIBRARY_TYPE) { 6438 if (group->dynamicRefTable.entries().size() == 0) { 6439 status_t err = group->dynamicRefTable.load((const ResTable_lib_header*) chunk); 6440 if (err != NO_ERROR) { 6441 return (mError=err); 6442 } 6443 6444 // Fill in the reference table with the entries we already know about. 6445 size_t N = mPackageGroups.size(); 6446 for (size_t i = 0; i < N; i++) { 6447 group->dynamicRefTable.addMapping(mPackageGroups[i]->name, mPackageGroups[i]->id); 6448 } 6449 } else { 6450 ALOGW("Found multiple library tables, ignoring..."); 6451 } 6452 } else { 6453 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), 6454 endPos, "ResTable_package:unknown"); 6455 if (err != NO_ERROR) { 6456 return (mError=err); 6457 } 6458 } 6459 chunk = (const ResChunk_header*) 6460 (((const uint8_t*)chunk) + csize); 6461 } 6462 6463 return NO_ERROR; 6464} 6465 6466DynamicRefTable::DynamicRefTable(uint8_t packageId, bool appAsLib) 6467 : mAssignedPackageId(packageId) 6468 , mAppAsLib(appAsLib) 6469{ 6470 memset(mLookupTable, 0, sizeof(mLookupTable)); 6471 6472 // Reserved package ids 6473 mLookupTable[APP_PACKAGE_ID] = APP_PACKAGE_ID; 6474 mLookupTable[SYS_PACKAGE_ID] = SYS_PACKAGE_ID; 6475} 6476 6477status_t DynamicRefTable::load(const ResTable_lib_header* const header) 6478{ 6479 const uint32_t entryCount = dtohl(header->count); 6480 const uint32_t sizeOfEntries = sizeof(ResTable_lib_entry) * entryCount; 6481 const uint32_t expectedSize = dtohl(header->header.size) - dtohl(header->header.headerSize); 6482 if (sizeOfEntries > expectedSize) { 6483 ALOGE("ResTable_lib_header size %u is too small to fit %u entries (x %u).", 6484 expectedSize, entryCount, (uint32_t)sizeof(ResTable_lib_entry)); 6485 return UNKNOWN_ERROR; 6486 } 6487 6488 const ResTable_lib_entry* entry = (const ResTable_lib_entry*)(((uint8_t*) header) + 6489 dtohl(header->header.headerSize)); 6490 for (uint32_t entryIndex = 0; entryIndex < entryCount; entryIndex++) { 6491 uint32_t packageId = dtohl(entry->packageId); 6492 char16_t tmpName[sizeof(entry->packageName) / sizeof(char16_t)]; 6493 strcpy16_dtoh(tmpName, entry->packageName, sizeof(entry->packageName) / sizeof(char16_t)); 6494 if (kDebugLibNoisy) { 6495 ALOGV("Found lib entry %s with id %d\n", String8(tmpName).string(), 6496 dtohl(entry->packageId)); 6497 } 6498 if (packageId >= 256) { 6499 ALOGE("Bad package id 0x%08x", packageId); 6500 return UNKNOWN_ERROR; 6501 } 6502 mEntries.replaceValueFor(String16(tmpName), (uint8_t) packageId); 6503 entry = entry + 1; 6504 } 6505 return NO_ERROR; 6506} 6507 6508status_t DynamicRefTable::addMappings(const DynamicRefTable& other) { 6509 if (mAssignedPackageId != other.mAssignedPackageId) { 6510 return UNKNOWN_ERROR; 6511 } 6512 6513 const size_t entryCount = other.mEntries.size(); 6514 for (size_t i = 0; i < entryCount; i++) { 6515 ssize_t index = mEntries.indexOfKey(other.mEntries.keyAt(i)); 6516 if (index < 0) { 6517 mEntries.add(other.mEntries.keyAt(i), other.mEntries[i]); 6518 } else { 6519 if (other.mEntries[i] != mEntries[index]) { 6520 return UNKNOWN_ERROR; 6521 } 6522 } 6523 } 6524 6525 // Merge the lookup table. No entry can conflict 6526 // (value of 0 means not set). 6527 for (size_t i = 0; i < 256; i++) { 6528 if (mLookupTable[i] != other.mLookupTable[i]) { 6529 if (mLookupTable[i] == 0) { 6530 mLookupTable[i] = other.mLookupTable[i]; 6531 } else if (other.mLookupTable[i] != 0) { 6532 return UNKNOWN_ERROR; 6533 } 6534 } 6535 } 6536 return NO_ERROR; 6537} 6538 6539status_t DynamicRefTable::addMapping(const String16& packageName, uint8_t packageId) 6540{ 6541 ssize_t index = mEntries.indexOfKey(packageName); 6542 if (index < 0) { 6543 return UNKNOWN_ERROR; 6544 } 6545 mLookupTable[mEntries.valueAt(index)] = packageId; 6546 return NO_ERROR; 6547} 6548 6549status_t DynamicRefTable::lookupResourceId(uint32_t* resId) const { 6550 uint32_t res = *resId; 6551 size_t packageId = Res_GETPACKAGE(res) + 1; 6552 6553 if (packageId == APP_PACKAGE_ID && !mAppAsLib) { 6554 // No lookup needs to be done, app package IDs are absolute. 6555 return NO_ERROR; 6556 } 6557 6558 if (packageId == 0 || (packageId == APP_PACKAGE_ID && mAppAsLib)) { 6559 // The package ID is 0x00. That means that a shared library is accessing 6560 // its own local resource. 6561 // Or if app resource is loaded as shared library, the resource which has 6562 // app package Id is local resources. 6563 // so we fix up those resources with the calling package ID. 6564 *resId = (0xFFFFFF & (*resId)) | (((uint32_t) mAssignedPackageId) << 24); 6565 return NO_ERROR; 6566 } 6567 6568 // Do a proper lookup. 6569 uint8_t translatedId = mLookupTable[packageId]; 6570 if (translatedId == 0) { 6571 ALOGV("DynamicRefTable(0x%02x): No mapping for build-time package ID 0x%02x.", 6572 (uint8_t)mAssignedPackageId, (uint8_t)packageId); 6573 for (size_t i = 0; i < 256; i++) { 6574 if (mLookupTable[i] != 0) { 6575 ALOGV("e[0x%02x] -> 0x%02x", (uint8_t)i, mLookupTable[i]); 6576 } 6577 } 6578 return UNKNOWN_ERROR; 6579 } 6580 6581 *resId = (res & 0x00ffffff) | (((uint32_t) translatedId) << 24); 6582 return NO_ERROR; 6583} 6584 6585status_t DynamicRefTable::lookupResourceValue(Res_value* value) const { 6586 uint8_t resolvedType = Res_value::TYPE_REFERENCE; 6587 switch (value->dataType) { 6588 case Res_value::TYPE_ATTRIBUTE: 6589 resolvedType = Res_value::TYPE_ATTRIBUTE; 6590 // fallthrough 6591 case Res_value::TYPE_REFERENCE: 6592 if (!mAppAsLib) { 6593 return NO_ERROR; 6594 } 6595 6596 // If the package is loaded as shared library, the resource reference 6597 // also need to be fixed. 6598 break; 6599 case Res_value::TYPE_DYNAMIC_ATTRIBUTE: 6600 resolvedType = Res_value::TYPE_ATTRIBUTE; 6601 // fallthrough 6602 case Res_value::TYPE_DYNAMIC_REFERENCE: 6603 break; 6604 default: 6605 return NO_ERROR; 6606 } 6607 6608 status_t err = lookupResourceId(&value->data); 6609 if (err != NO_ERROR) { 6610 return err; 6611 } 6612 6613 value->dataType = resolvedType; 6614 return NO_ERROR; 6615} 6616 6617struct IdmapTypeMap { 6618 ssize_t overlayTypeId; 6619 size_t entryOffset; 6620 Vector<uint32_t> entryMap; 6621}; 6622 6623status_t ResTable::createIdmap(const ResTable& overlay, 6624 uint32_t targetCrc, uint32_t overlayCrc, 6625 const char* targetPath, const char* overlayPath, 6626 void** outData, size_t* outSize) const 6627{ 6628 // see README for details on the format of map 6629 if (mPackageGroups.size() == 0) { 6630 ALOGW("idmap: target package has no package groups, cannot create idmap\n"); 6631 return UNKNOWN_ERROR; 6632 } 6633 6634 if (mPackageGroups[0]->packages.size() == 0) { 6635 ALOGW("idmap: target package has no packages in its first package group, " 6636 "cannot create idmap\n"); 6637 return UNKNOWN_ERROR; 6638 } 6639 6640 KeyedVector<uint8_t, IdmapTypeMap> map; 6641 6642 // overlaid packages are assumed to contain only one package group 6643 const PackageGroup* pg = mPackageGroups[0]; 6644 6645 // starting size is header 6646 *outSize = ResTable::IDMAP_HEADER_SIZE_BYTES; 6647 6648 // target package id and number of types in map 6649 *outSize += 2 * sizeof(uint16_t); 6650 6651 // overlay packages are assumed to contain only one package group 6652 const ResTable_package* overlayPackageStruct = overlay.mPackageGroups[0]->packages[0]->package; 6653 char16_t tmpName[sizeof(overlayPackageStruct->name)/sizeof(overlayPackageStruct->name[0])]; 6654 strcpy16_dtoh(tmpName, overlayPackageStruct->name, sizeof(overlayPackageStruct->name)/sizeof(overlayPackageStruct->name[0])); 6655 const String16 overlayPackage(tmpName); 6656 6657 for (size_t typeIndex = 0; typeIndex < pg->types.size(); ++typeIndex) { 6658 const TypeList& typeList = pg->types[typeIndex]; 6659 if (typeList.isEmpty()) { 6660 continue; 6661 } 6662 6663 const Type* typeConfigs = typeList[0]; 6664 6665 IdmapTypeMap typeMap; 6666 typeMap.overlayTypeId = -1; 6667 typeMap.entryOffset = 0; 6668 6669 for (size_t entryIndex = 0; entryIndex < typeConfigs->entryCount; ++entryIndex) { 6670 uint32_t resID = Res_MAKEID(pg->id - 1, typeIndex, entryIndex); 6671 resource_name resName; 6672 if (!this->getResourceName(resID, false, &resName)) { 6673 if (typeMap.entryMap.isEmpty()) { 6674 typeMap.entryOffset++; 6675 } 6676 continue; 6677 } 6678 6679 const String16 overlayType(resName.type, resName.typeLen); 6680 const String16 overlayName(resName.name, resName.nameLen); 6681 uint32_t overlayResID = overlay.identifierForName(overlayName.string(), 6682 overlayName.size(), 6683 overlayType.string(), 6684 overlayType.size(), 6685 overlayPackage.string(), 6686 overlayPackage.size()); 6687 if (overlayResID == 0) { 6688 if (typeMap.entryMap.isEmpty()) { 6689 typeMap.entryOffset++; 6690 } 6691 continue; 6692 } 6693 6694 if (typeMap.overlayTypeId == -1) { 6695 typeMap.overlayTypeId = Res_GETTYPE(overlayResID) + 1; 6696 } 6697 6698 if (Res_GETTYPE(overlayResID) + 1 != static_cast<size_t>(typeMap.overlayTypeId)) { 6699 ALOGE("idmap: can't mix type ids in entry map. Resource 0x%08x maps to 0x%08x" 6700 " but entries should map to resources of type %02zx", 6701 resID, overlayResID, typeMap.overlayTypeId); 6702 return BAD_TYPE; 6703 } 6704 6705 if (typeMap.entryOffset + typeMap.entryMap.size() < entryIndex) { 6706 // pad with 0xffffffff's (indicating non-existing entries) before adding this entry 6707 size_t index = typeMap.entryMap.size(); 6708 size_t numItems = entryIndex - (typeMap.entryOffset + index); 6709 if (typeMap.entryMap.insertAt(0xffffffff, index, numItems) < 0) { 6710 return NO_MEMORY; 6711 } 6712 } 6713 typeMap.entryMap.add(Res_GETENTRY(overlayResID)); 6714 } 6715 6716 if (!typeMap.entryMap.isEmpty()) { 6717 if (map.add(static_cast<uint8_t>(typeIndex), typeMap) < 0) { 6718 return NO_MEMORY; 6719 } 6720 *outSize += (4 * sizeof(uint16_t)) + (typeMap.entryMap.size() * sizeof(uint32_t)); 6721 } 6722 } 6723 6724 if (map.isEmpty()) { 6725 ALOGW("idmap: no resources in overlay package present in base package"); 6726 return UNKNOWN_ERROR; 6727 } 6728 6729 if ((*outData = malloc(*outSize)) == NULL) { 6730 return NO_MEMORY; 6731 } 6732 6733 uint32_t* data = (uint32_t*)*outData; 6734 *data++ = htodl(IDMAP_MAGIC); 6735 *data++ = htodl(IDMAP_CURRENT_VERSION); 6736 *data++ = htodl(targetCrc); 6737 *data++ = htodl(overlayCrc); 6738 const char* paths[] = { targetPath, overlayPath }; 6739 for (int j = 0; j < 2; ++j) { 6740 char* p = (char*)data; 6741 const char* path = paths[j]; 6742 const size_t I = strlen(path); 6743 if (I > 255) { 6744 ALOGV("path exceeds expected 255 characters: %s\n", path); 6745 return UNKNOWN_ERROR; 6746 } 6747 for (size_t i = 0; i < 256; ++i) { 6748 *p++ = i < I ? path[i] : '\0'; 6749 } 6750 data += 256 / sizeof(uint32_t); 6751 } 6752 const size_t mapSize = map.size(); 6753 uint16_t* typeData = reinterpret_cast<uint16_t*>(data); 6754 *typeData++ = htods(pg->id); 6755 *typeData++ = htods(mapSize); 6756 for (size_t i = 0; i < mapSize; ++i) { 6757 uint8_t targetTypeId = map.keyAt(i); 6758 const IdmapTypeMap& typeMap = map[i]; 6759 *typeData++ = htods(targetTypeId + 1); 6760 *typeData++ = htods(typeMap.overlayTypeId); 6761 *typeData++ = htods(typeMap.entryMap.size()); 6762 *typeData++ = htods(typeMap.entryOffset); 6763 6764 const size_t entryCount = typeMap.entryMap.size(); 6765 uint32_t* entries = reinterpret_cast<uint32_t*>(typeData); 6766 for (size_t j = 0; j < entryCount; j++) { 6767 entries[j] = htodl(typeMap.entryMap[j]); 6768 } 6769 typeData += entryCount * 2; 6770 } 6771 6772 return NO_ERROR; 6773} 6774 6775bool ResTable::getIdmapInfo(const void* idmap, size_t sizeBytes, 6776 uint32_t* pVersion, 6777 uint32_t* pTargetCrc, uint32_t* pOverlayCrc, 6778 String8* pTargetPath, String8* pOverlayPath) 6779{ 6780 const uint32_t* map = (const uint32_t*)idmap; 6781 if (!assertIdmapHeader(map, sizeBytes)) { 6782 return false; 6783 } 6784 if (pVersion) { 6785 *pVersion = dtohl(map[1]); 6786 } 6787 if (pTargetCrc) { 6788 *pTargetCrc = dtohl(map[2]); 6789 } 6790 if (pOverlayCrc) { 6791 *pOverlayCrc = dtohl(map[3]); 6792 } 6793 if (pTargetPath) { 6794 pTargetPath->setTo(reinterpret_cast<const char*>(map + 4)); 6795 } 6796 if (pOverlayPath) { 6797 pOverlayPath->setTo(reinterpret_cast<const char*>(map + 4 + 256 / sizeof(uint32_t))); 6798 } 6799 return true; 6800} 6801 6802 6803#define CHAR16_TO_CSTR(c16, len) (String8(String16(c16,len)).string()) 6804 6805#define CHAR16_ARRAY_EQ(constant, var, len) \ 6806 (((len) == (sizeof(constant)/sizeof((constant)[0]))) && (0 == memcmp((var), (constant), (len)))) 6807 6808static void print_complex(uint32_t complex, bool isFraction) 6809{ 6810 const float MANTISSA_MULT = 6811 1.0f / (1<<Res_value::COMPLEX_MANTISSA_SHIFT); 6812 const float RADIX_MULTS[] = { 6813 1.0f*MANTISSA_MULT, 1.0f/(1<<7)*MANTISSA_MULT, 6814 1.0f/(1<<15)*MANTISSA_MULT, 1.0f/(1<<23)*MANTISSA_MULT 6815 }; 6816 6817 float value = (complex&(Res_value::COMPLEX_MANTISSA_MASK 6818 <<Res_value::COMPLEX_MANTISSA_SHIFT)) 6819 * RADIX_MULTS[(complex>>Res_value::COMPLEX_RADIX_SHIFT) 6820 & Res_value::COMPLEX_RADIX_MASK]; 6821 printf("%f", value); 6822 6823 if (!isFraction) { 6824 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) { 6825 case Res_value::COMPLEX_UNIT_PX: printf("px"); break; 6826 case Res_value::COMPLEX_UNIT_DIP: printf("dp"); break; 6827 case Res_value::COMPLEX_UNIT_SP: printf("sp"); break; 6828 case Res_value::COMPLEX_UNIT_PT: printf("pt"); break; 6829 case Res_value::COMPLEX_UNIT_IN: printf("in"); break; 6830 case Res_value::COMPLEX_UNIT_MM: printf("mm"); break; 6831 default: printf(" (unknown unit)"); break; 6832 } 6833 } else { 6834 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) { 6835 case Res_value::COMPLEX_UNIT_FRACTION: printf("%%"); break; 6836 case Res_value::COMPLEX_UNIT_FRACTION_PARENT: printf("%%p"); break; 6837 default: printf(" (unknown unit)"); break; 6838 } 6839 } 6840} 6841 6842// Normalize a string for output 6843String8 ResTable::normalizeForOutput( const char *input ) 6844{ 6845 String8 ret; 6846 char buff[2]; 6847 buff[1] = '\0'; 6848 6849 while (*input != '\0') { 6850 switch (*input) { 6851 // All interesting characters are in the ASCII zone, so we are making our own lives 6852 // easier by scanning the string one byte at a time. 6853 case '\\': 6854 ret += "\\\\"; 6855 break; 6856 case '\n': 6857 ret += "\\n"; 6858 break; 6859 case '"': 6860 ret += "\\\""; 6861 break; 6862 default: 6863 buff[0] = *input; 6864 ret += buff; 6865 break; 6866 } 6867 6868 input++; 6869 } 6870 6871 return ret; 6872} 6873 6874void ResTable::print_value(const Package* pkg, const Res_value& value) const 6875{ 6876 if (value.dataType == Res_value::TYPE_NULL) { 6877 if (value.data == Res_value::DATA_NULL_UNDEFINED) { 6878 printf("(null)\n"); 6879 } else if (value.data == Res_value::DATA_NULL_EMPTY) { 6880 printf("(null empty)\n"); 6881 } else { 6882 // This should never happen. 6883 printf("(null) 0x%08x\n", value.data); 6884 } 6885 } else if (value.dataType == Res_value::TYPE_REFERENCE) { 6886 printf("(reference) 0x%08x\n", value.data); 6887 } else if (value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE) { 6888 printf("(dynamic reference) 0x%08x\n", value.data); 6889 } else if (value.dataType == Res_value::TYPE_ATTRIBUTE) { 6890 printf("(attribute) 0x%08x\n", value.data); 6891 } else if (value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE) { 6892 printf("(dynamic attribute) 0x%08x\n", value.data); 6893 } else if (value.dataType == Res_value::TYPE_STRING) { 6894 size_t len; 6895 const char* str8 = pkg->header->values.string8At( 6896 value.data, &len); 6897 if (str8 != NULL) { 6898 printf("(string8) \"%s\"\n", normalizeForOutput(str8).string()); 6899 } else { 6900 const char16_t* str16 = pkg->header->values.stringAt( 6901 value.data, &len); 6902 if (str16 != NULL) { 6903 printf("(string16) \"%s\"\n", 6904 normalizeForOutput(String8(str16, len).string()).string()); 6905 } else { 6906 printf("(string) null\n"); 6907 } 6908 } 6909 } else if (value.dataType == Res_value::TYPE_FLOAT) { 6910 printf("(float) %g\n", *(const float*)&value.data); 6911 } else if (value.dataType == Res_value::TYPE_DIMENSION) { 6912 printf("(dimension) "); 6913 print_complex(value.data, false); 6914 printf("\n"); 6915 } else if (value.dataType == Res_value::TYPE_FRACTION) { 6916 printf("(fraction) "); 6917 print_complex(value.data, true); 6918 printf("\n"); 6919 } else if (value.dataType >= Res_value::TYPE_FIRST_COLOR_INT 6920 || value.dataType <= Res_value::TYPE_LAST_COLOR_INT) { 6921 printf("(color) #%08x\n", value.data); 6922 } else if (value.dataType == Res_value::TYPE_INT_BOOLEAN) { 6923 printf("(boolean) %s\n", value.data ? "true" : "false"); 6924 } else if (value.dataType >= Res_value::TYPE_FIRST_INT 6925 || value.dataType <= Res_value::TYPE_LAST_INT) { 6926 printf("(int) 0x%08x or %d\n", value.data, value.data); 6927 } else { 6928 printf("(unknown type) t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)\n", 6929 (int)value.dataType, (int)value.data, 6930 (int)value.size, (int)value.res0); 6931 } 6932} 6933 6934void ResTable::print(bool inclValues) const 6935{ 6936 if (mError != 0) { 6937 printf("mError=0x%x (%s)\n", mError, strerror(mError)); 6938 } 6939 size_t pgCount = mPackageGroups.size(); 6940 printf("Package Groups (%d)\n", (int)pgCount); 6941 for (size_t pgIndex=0; pgIndex<pgCount; pgIndex++) { 6942 const PackageGroup* pg = mPackageGroups[pgIndex]; 6943 printf("Package Group %d id=0x%02x packageCount=%d name=%s\n", 6944 (int)pgIndex, pg->id, (int)pg->packages.size(), 6945 String8(pg->name).string()); 6946 6947 const KeyedVector<String16, uint8_t>& refEntries = pg->dynamicRefTable.entries(); 6948 const size_t refEntryCount = refEntries.size(); 6949 if (refEntryCount > 0) { 6950 printf(" DynamicRefTable entryCount=%d:\n", (int) refEntryCount); 6951 for (size_t refIndex = 0; refIndex < refEntryCount; refIndex++) { 6952 printf(" 0x%02x -> %s\n", 6953 refEntries.valueAt(refIndex), 6954 String8(refEntries.keyAt(refIndex)).string()); 6955 } 6956 printf("\n"); 6957 } 6958 6959 int packageId = pg->id; 6960 size_t pkgCount = pg->packages.size(); 6961 for (size_t pkgIndex=0; pkgIndex<pkgCount; pkgIndex++) { 6962 const Package* pkg = pg->packages[pkgIndex]; 6963 // Use a package's real ID, since the ID may have been assigned 6964 // if this package is a shared library. 6965 packageId = pkg->package->id; 6966 char16_t tmpName[sizeof(pkg->package->name)/sizeof(pkg->package->name[0])]; 6967 strcpy16_dtoh(tmpName, pkg->package->name, sizeof(pkg->package->name)/sizeof(pkg->package->name[0])); 6968 printf(" Package %d id=0x%02x name=%s\n", (int)pkgIndex, 6969 pkg->package->id, String8(tmpName).string()); 6970 } 6971 6972 for (size_t typeIndex=0; typeIndex < pg->types.size(); typeIndex++) { 6973 const TypeList& typeList = pg->types[typeIndex]; 6974 if (typeList.isEmpty()) { 6975 continue; 6976 } 6977 const Type* typeConfigs = typeList[0]; 6978 const size_t NTC = typeConfigs->configs.size(); 6979 printf(" type %d configCount=%d entryCount=%d\n", 6980 (int)typeIndex, (int)NTC, (int)typeConfigs->entryCount); 6981 if (typeConfigs->typeSpecFlags != NULL) { 6982 for (size_t entryIndex=0; entryIndex<typeConfigs->entryCount; entryIndex++) { 6983 uint32_t resID = (0xff000000 & ((packageId)<<24)) 6984 | (0x00ff0000 & ((typeIndex+1)<<16)) 6985 | (0x0000ffff & (entryIndex)); 6986 // Since we are creating resID without actually 6987 // iterating over them, we have no idea which is a 6988 // dynamic reference. We must check. 6989 if (packageId == 0) { 6990 pg->dynamicRefTable.lookupResourceId(&resID); 6991 } 6992 6993 resource_name resName; 6994 if (this->getResourceName(resID, true, &resName)) { 6995 String8 type8; 6996 String8 name8; 6997 if (resName.type8 != NULL) { 6998 type8 = String8(resName.type8, resName.typeLen); 6999 } else { 7000 type8 = String8(resName.type, resName.typeLen); 7001 } 7002 if (resName.name8 != NULL) { 7003 name8 = String8(resName.name8, resName.nameLen); 7004 } else { 7005 name8 = String8(resName.name, resName.nameLen); 7006 } 7007 printf(" spec resource 0x%08x %s:%s/%s: flags=0x%08x\n", 7008 resID, 7009 CHAR16_TO_CSTR(resName.package, resName.packageLen), 7010 type8.string(), name8.string(), 7011 dtohl(typeConfigs->typeSpecFlags[entryIndex])); 7012 } else { 7013 printf(" INVALID TYPE CONFIG FOR RESOURCE 0x%08x\n", resID); 7014 } 7015 } 7016 } 7017 for (size_t configIndex=0; configIndex<NTC; configIndex++) { 7018 const ResTable_type* type = typeConfigs->configs[configIndex]; 7019 if ((((uint64_t)type)&0x3) != 0) { 7020 printf(" NON-INTEGER ResTable_type ADDRESS: %p\n", type); 7021 continue; 7022 } 7023 7024 // Always copy the config, as fields get added and we need to 7025 // set the defaults. 7026 ResTable_config thisConfig; 7027 thisConfig.copyFromDtoH(type->config); 7028 7029 String8 configStr = thisConfig.toString(); 7030 printf(" config %s:\n", configStr.size() > 0 7031 ? configStr.string() : "(default)"); 7032 size_t entryCount = dtohl(type->entryCount); 7033 uint32_t entriesStart = dtohl(type->entriesStart); 7034 if ((entriesStart&0x3) != 0) { 7035 printf(" NON-INTEGER ResTable_type entriesStart OFFSET: 0x%x\n", entriesStart); 7036 continue; 7037 } 7038 uint32_t typeSize = dtohl(type->header.size); 7039 if ((typeSize&0x3) != 0) { 7040 printf(" NON-INTEGER ResTable_type header.size: 0x%x\n", typeSize); 7041 continue; 7042 } 7043 for (size_t entryIndex=0; entryIndex<entryCount; entryIndex++) { 7044 const uint32_t* const eindex = (const uint32_t*) 7045 (((const uint8_t*)type) + dtohs(type->header.headerSize)); 7046 7047 uint32_t thisOffset = dtohl(eindex[entryIndex]); 7048 if (thisOffset == ResTable_type::NO_ENTRY) { 7049 continue; 7050 } 7051 7052 uint32_t resID = (0xff000000 & ((packageId)<<24)) 7053 | (0x00ff0000 & ((typeIndex+1)<<16)) 7054 | (0x0000ffff & (entryIndex)); 7055 if (packageId == 0) { 7056 pg->dynamicRefTable.lookupResourceId(&resID); 7057 } 7058 resource_name resName; 7059 if (this->getResourceName(resID, true, &resName)) { 7060 String8 type8; 7061 String8 name8; 7062 if (resName.type8 != NULL) { 7063 type8 = String8(resName.type8, resName.typeLen); 7064 } else { 7065 type8 = String8(resName.type, resName.typeLen); 7066 } 7067 if (resName.name8 != NULL) { 7068 name8 = String8(resName.name8, resName.nameLen); 7069 } else { 7070 name8 = String8(resName.name, resName.nameLen); 7071 } 7072 printf(" resource 0x%08x %s:%s/%s: ", resID, 7073 CHAR16_TO_CSTR(resName.package, resName.packageLen), 7074 type8.string(), name8.string()); 7075 } else { 7076 printf(" INVALID RESOURCE 0x%08x: ", resID); 7077 } 7078 if ((thisOffset&0x3) != 0) { 7079 printf("NON-INTEGER OFFSET: 0x%x\n", thisOffset); 7080 continue; 7081 } 7082 if ((thisOffset+sizeof(ResTable_entry)) > typeSize) { 7083 printf("OFFSET OUT OF BOUNDS: 0x%x+0x%x (size is 0x%x)\n", 7084 entriesStart, thisOffset, typeSize); 7085 continue; 7086 } 7087 7088 const ResTable_entry* ent = (const ResTable_entry*) 7089 (((const uint8_t*)type) + entriesStart + thisOffset); 7090 if (((entriesStart + thisOffset)&0x3) != 0) { 7091 printf("NON-INTEGER ResTable_entry OFFSET: 0x%x\n", 7092 (entriesStart + thisOffset)); 7093 continue; 7094 } 7095 7096 uintptr_t esize = dtohs(ent->size); 7097 if ((esize&0x3) != 0) { 7098 printf("NON-INTEGER ResTable_entry SIZE: %p\n", (void *)esize); 7099 continue; 7100 } 7101 if ((thisOffset+esize) > typeSize) { 7102 printf("ResTable_entry OUT OF BOUNDS: 0x%x+0x%x+%p (size is 0x%x)\n", 7103 entriesStart, thisOffset, (void *)esize, typeSize); 7104 continue; 7105 } 7106 7107 const Res_value* valuePtr = NULL; 7108 const ResTable_map_entry* bagPtr = NULL; 7109 Res_value value; 7110 if ((dtohs(ent->flags)&ResTable_entry::FLAG_COMPLEX) != 0) { 7111 printf("<bag>"); 7112 bagPtr = (const ResTable_map_entry*)ent; 7113 } else { 7114 valuePtr = (const Res_value*) 7115 (((const uint8_t*)ent) + esize); 7116 value.copyFrom_dtoh(*valuePtr); 7117 printf("t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)", 7118 (int)value.dataType, (int)value.data, 7119 (int)value.size, (int)value.res0); 7120 } 7121 7122 if ((dtohs(ent->flags)&ResTable_entry::FLAG_PUBLIC) != 0) { 7123 printf(" (PUBLIC)"); 7124 } 7125 printf("\n"); 7126 7127 if (inclValues) { 7128 if (valuePtr != NULL) { 7129 printf(" "); 7130 print_value(typeConfigs->package, value); 7131 } else if (bagPtr != NULL) { 7132 const int N = dtohl(bagPtr->count); 7133 const uint8_t* baseMapPtr = (const uint8_t*)ent; 7134 size_t mapOffset = esize; 7135 const ResTable_map* mapPtr = (ResTable_map*)(baseMapPtr+mapOffset); 7136 const uint32_t parent = dtohl(bagPtr->parent.ident); 7137 uint32_t resolvedParent = parent; 7138 if (Res_GETPACKAGE(resolvedParent) + 1 == 0) { 7139 status_t err = pg->dynamicRefTable.lookupResourceId(&resolvedParent); 7140 if (err != NO_ERROR) { 7141 resolvedParent = 0; 7142 } 7143 } 7144 printf(" Parent=0x%08x(Resolved=0x%08x), Count=%d\n", 7145 parent, resolvedParent, N); 7146 for (int i=0; i<N && mapOffset < (typeSize-sizeof(ResTable_map)); i++) { 7147 printf(" #%i (Key=0x%08x): ", 7148 i, dtohl(mapPtr->name.ident)); 7149 value.copyFrom_dtoh(mapPtr->value); 7150 print_value(typeConfigs->package, value); 7151 const size_t size = dtohs(mapPtr->value.size); 7152 mapOffset += size + sizeof(*mapPtr)-sizeof(mapPtr->value); 7153 mapPtr = (ResTable_map*)(baseMapPtr+mapOffset); 7154 } 7155 } 7156 } 7157 } 7158 } 7159 } 7160 } 7161} 7162 7163} // namespace android 7164