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