ResourceTypes.cpp revision d7df9d7b38064b81e1b035893001499e79fc3cc0
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), typeIdOffset(0) { 2859 if (_package != NULL && 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 2869 ResStringPool typeStrings; 2870 ResStringPool keyStrings; 2871 2872 size_t typeIdOffset; 2873}; 2874 2875// A group of objects describing a particular resource package. 2876// The first in 'package' is always the root object (from the resource 2877// table that defined the package); the ones after are skins on top of it. 2878struct ResTable::PackageGroup 2879{ 2880 PackageGroup(ResTable* _owner, const String16& _name, uint32_t _id) 2881 : owner(_owner) 2882 , name(_name) 2883 , id(_id) 2884 , largestTypeId(0) 2885 , bags(NULL) 2886 , dynamicRefTable(static_cast<uint8_t>(_id)) 2887 { } 2888 2889 ~PackageGroup() { 2890 clearBagCache(); 2891 const size_t numTypes = types.size(); 2892 for (size_t i = 0; i < numTypes; i++) { 2893 const TypeList& typeList = types[i]; 2894 const size_t numInnerTypes = typeList.size(); 2895 for (size_t j = 0; j < numInnerTypes; j++) { 2896 if (typeList[j]->package->owner == owner) { 2897 delete typeList[j]; 2898 } 2899 } 2900 } 2901 2902 const size_t N = packages.size(); 2903 for (size_t i=0; i<N; i++) { 2904 Package* pkg = packages[i]; 2905 if (pkg->owner == owner) { 2906 delete pkg; 2907 } 2908 } 2909 } 2910 2911 void clearBagCache() { 2912 if (bags) { 2913 TABLE_NOISY(printf("bags=%p\n", bags)); 2914 for (size_t i = 0; i < bags->size(); i++) { 2915 TABLE_NOISY(printf("type=%d\n", i)); 2916 const TypeList& typeList = types[i]; 2917 if (typeList.isEmpty()) { 2918 bag_set** typeBags = bags->get(i); 2919 TABLE_NOISY(printf("typeBags=%p\n", typeBags)); 2920 if (typeBags) { 2921 const size_t N = typeList[0]->entryCount; 2922 TABLE_NOISY(printf("type->entryCount=%x\n", N)); 2923 for (size_t j=0; j<N; j++) { 2924 if (typeBags[j] && typeBags[j] != (bag_set*)0xFFFFFFFF) 2925 free(typeBags[j]); 2926 } 2927 free(typeBags); 2928 } 2929 } 2930 } 2931 delete bags; 2932 bags = NULL; 2933 } 2934 } 2935 2936 ssize_t findType16(const char16_t* type, size_t len) const { 2937 const size_t N = packages.size(); 2938 for (size_t i = 0; i < N; i++) { 2939 ssize_t index = packages[i]->typeStrings.indexOfString(type, len); 2940 if (index >= 0) { 2941 return index + packages[i]->typeIdOffset; 2942 } 2943 } 2944 return -1; 2945 } 2946 2947 const ResTable* const owner; 2948 String16 const name; 2949 uint32_t const id; 2950 2951 // This is mainly used to keep track of the loaded packages 2952 // and to clean them up properly. Accessing resources happens from 2953 // the 'types' array. 2954 Vector<Package*> packages; 2955 2956 ByteBucketArray<TypeList> types; 2957 2958 uint8_t largestTypeId; 2959 2960 // Computed attribute bags, first indexed by the type and second 2961 // by the entry in that type. 2962 ByteBucketArray<bag_set**>* bags; 2963 2964 // The table mapping dynamic references to resolved references for 2965 // this package group. 2966 // TODO: We may be able to support dynamic references in overlays 2967 // by having these tables in a per-package scope rather than 2968 // per-package-group. 2969 DynamicRefTable dynamicRefTable; 2970}; 2971 2972struct ResTable::bag_set 2973{ 2974 size_t numAttrs; // number in array 2975 size_t availAttrs; // total space in array 2976 uint32_t typeSpecFlags; 2977 // Followed by 'numAttr' bag_entry structures. 2978}; 2979 2980ResTable::Theme::Theme(const ResTable& table) 2981 : mTable(table) 2982{ 2983 memset(mPackages, 0, sizeof(mPackages)); 2984} 2985 2986ResTable::Theme::~Theme() 2987{ 2988 for (size_t i=0; i<Res_MAXPACKAGE; i++) { 2989 package_info* pi = mPackages[i]; 2990 if (pi != NULL) { 2991 free_package(pi); 2992 } 2993 } 2994} 2995 2996void ResTable::Theme::free_package(package_info* pi) 2997{ 2998 for (size_t j = 0; j <= Res_MAXTYPE; j++) { 2999 theme_entry* te = pi->types[j].entries; 3000 if (te != NULL) { 3001 free(te); 3002 } 3003 } 3004 free(pi); 3005} 3006 3007ResTable::Theme::package_info* ResTable::Theme::copy_package(package_info* pi) 3008{ 3009 package_info* newpi = (package_info*)malloc(sizeof(package_info)); 3010 for (size_t j = 0; j <= Res_MAXTYPE; j++) { 3011 size_t cnt = pi->types[j].numEntries; 3012 newpi->types[j].numEntries = cnt; 3013 theme_entry* te = pi->types[j].entries; 3014 if (te != NULL) { 3015 theme_entry* newte = (theme_entry*)malloc(cnt*sizeof(theme_entry)); 3016 newpi->types[j].entries = newte; 3017 memcpy(newte, te, cnt*sizeof(theme_entry)); 3018 } else { 3019 newpi->types[j].entries = NULL; 3020 } 3021 } 3022 return newpi; 3023} 3024 3025status_t ResTable::Theme::applyStyle(uint32_t resID, bool force) 3026{ 3027 const bag_entry* bag; 3028 uint32_t bagTypeSpecFlags = 0; 3029 mTable.lock(); 3030 const ssize_t N = mTable.getBagLocked(resID, &bag, &bagTypeSpecFlags); 3031 TABLE_NOISY(ALOGV("Applying style 0x%08x to theme %p, count=%d", resID, this, N)); 3032 if (N < 0) { 3033 mTable.unlock(); 3034 return N; 3035 } 3036 3037 uint32_t curPackage = 0xffffffff; 3038 ssize_t curPackageIndex = 0; 3039 package_info* curPI = NULL; 3040 uint32_t curType = 0xffffffff; 3041 size_t numEntries = 0; 3042 theme_entry* curEntries = NULL; 3043 3044 const bag_entry* end = bag + N; 3045 while (bag < end) { 3046 const uint32_t attrRes = bag->map.name.ident; 3047 const uint32_t p = Res_GETPACKAGE(attrRes); 3048 const uint32_t t = Res_GETTYPE(attrRes); 3049 const uint32_t e = Res_GETENTRY(attrRes); 3050 3051 if (curPackage != p) { 3052 const ssize_t pidx = mTable.getResourcePackageIndex(attrRes); 3053 if (pidx < 0) { 3054 ALOGE("Style contains key with bad package: 0x%08x\n", attrRes); 3055 bag++; 3056 continue; 3057 } 3058 curPackage = p; 3059 curPackageIndex = pidx; 3060 curPI = mPackages[pidx]; 3061 if (curPI == NULL) { 3062 PackageGroup* const grp = mTable.mPackageGroups[pidx]; 3063 curPI = (package_info*)malloc(sizeof(package_info)); 3064 memset(curPI, 0, sizeof(*curPI)); 3065 mPackages[pidx] = curPI; 3066 } 3067 curType = 0xffffffff; 3068 } 3069 if (curType != t) { 3070 if (t > Res_MAXTYPE) { 3071 ALOGE("Style contains key with bad type: 0x%08x\n", attrRes); 3072 bag++; 3073 continue; 3074 } 3075 curType = t; 3076 curEntries = curPI->types[t].entries; 3077 if (curEntries == NULL) { 3078 PackageGroup* const grp = mTable.mPackageGroups[curPackageIndex]; 3079 const TypeList& typeList = grp->types[t]; 3080 int cnt = typeList.isEmpty() ? 0 : typeList[0]->entryCount; 3081 curEntries = (theme_entry*)malloc(cnt*sizeof(theme_entry)); 3082 memset(curEntries, Res_value::TYPE_NULL, cnt*sizeof(theme_entry)); 3083 curPI->types[t].numEntries = cnt; 3084 curPI->types[t].entries = curEntries; 3085 } 3086 numEntries = curPI->types[t].numEntries; 3087 } 3088 if (e >= numEntries) { 3089 ALOGE("Style contains key with bad entry: 0x%08x\n", attrRes); 3090 bag++; 3091 continue; 3092 } 3093 theme_entry* curEntry = curEntries + e; 3094 TABLE_NOISY(ALOGV("Attr 0x%08x: type=0x%x, data=0x%08x; curType=0x%x", 3095 attrRes, bag->map.value.dataType, bag->map.value.data, 3096 curEntry->value.dataType)); 3097 if (force || curEntry->value.dataType == Res_value::TYPE_NULL) { 3098 curEntry->stringBlock = bag->stringBlock; 3099 curEntry->typeSpecFlags |= bagTypeSpecFlags; 3100 curEntry->value = bag->map.value; 3101 } 3102 3103 bag++; 3104 } 3105 3106 mTable.unlock(); 3107 3108 //ALOGI("Applying style 0x%08x (force=%d) theme %p...\n", resID, force, this); 3109 //dumpToLog(); 3110 3111 return NO_ERROR; 3112} 3113 3114status_t ResTable::Theme::setTo(const Theme& other) 3115{ 3116 //ALOGI("Setting theme %p from theme %p...\n", this, &other); 3117 //dumpToLog(); 3118 //other.dumpToLog(); 3119 3120 if (&mTable == &other.mTable) { 3121 for (size_t i=0; i<Res_MAXPACKAGE; i++) { 3122 if (mPackages[i] != NULL) { 3123 free_package(mPackages[i]); 3124 } 3125 if (other.mPackages[i] != NULL) { 3126 mPackages[i] = copy_package(other.mPackages[i]); 3127 } else { 3128 mPackages[i] = NULL; 3129 } 3130 } 3131 } else { 3132 // @todo: need to really implement this, not just copy 3133 // the system package (which is still wrong because it isn't 3134 // fixing up resource references). 3135 for (size_t i=0; i<Res_MAXPACKAGE; i++) { 3136 if (mPackages[i] != NULL) { 3137 free_package(mPackages[i]); 3138 } 3139 if (i == 0 && other.mPackages[i] != NULL) { 3140 mPackages[i] = copy_package(other.mPackages[i]); 3141 } else { 3142 mPackages[i] = NULL; 3143 } 3144 } 3145 } 3146 3147 //ALOGI("Final theme:"); 3148 //dumpToLog(); 3149 3150 return NO_ERROR; 3151} 3152 3153ssize_t ResTable::Theme::getAttribute(uint32_t resID, Res_value* outValue, 3154 uint32_t* outTypeSpecFlags) const 3155{ 3156 int cnt = 20; 3157 3158 if (outTypeSpecFlags != NULL) *outTypeSpecFlags = 0; 3159 3160 do { 3161 const ssize_t p = mTable.getResourcePackageIndex(resID); 3162 const uint32_t t = Res_GETTYPE(resID); 3163 const uint32_t e = Res_GETENTRY(resID); 3164 3165 TABLE_THEME(ALOGI("Looking up attr 0x%08x in theme %p", resID, this)); 3166 3167 if (p >= 0) { 3168 const package_info* const pi = mPackages[p]; 3169 TABLE_THEME(ALOGI("Found package: %p", pi)); 3170 if (pi != NULL) { 3171 TABLE_THEME(ALOGI("Desired type index is %ld in avail %d", t, Res_MAXTYPE + 1)); 3172 if (t <= Res_MAXTYPE) { 3173 const type_info& ti = pi->types[t]; 3174 TABLE_THEME(ALOGI("Desired entry index is %ld in avail %d", e, ti.numEntries)); 3175 if (e < ti.numEntries) { 3176 const theme_entry& te = ti.entries[e]; 3177 if (outTypeSpecFlags != NULL) { 3178 *outTypeSpecFlags |= te.typeSpecFlags; 3179 } 3180 TABLE_THEME(ALOGI("Theme value: type=0x%x, data=0x%08x", 3181 te.value.dataType, te.value.data)); 3182 const uint8_t type = te.value.dataType; 3183 if (type == Res_value::TYPE_ATTRIBUTE) { 3184 if (cnt > 0) { 3185 cnt--; 3186 resID = te.value.data; 3187 continue; 3188 } 3189 ALOGW("Too many attribute references, stopped at: 0x%08x\n", resID); 3190 return BAD_INDEX; 3191 } else if (type != Res_value::TYPE_NULL) { 3192 *outValue = te.value; 3193 return te.stringBlock; 3194 } 3195 return BAD_INDEX; 3196 } 3197 } 3198 } 3199 } 3200 break; 3201 3202 } while (true); 3203 3204 return BAD_INDEX; 3205} 3206 3207ssize_t ResTable::Theme::resolveAttributeReference(Res_value* inOutValue, 3208 ssize_t blockIndex, uint32_t* outLastRef, 3209 uint32_t* inoutTypeSpecFlags, ResTable_config* inoutConfig) const 3210{ 3211 //printf("Resolving type=0x%x\n", inOutValue->dataType); 3212 if (inOutValue->dataType == Res_value::TYPE_ATTRIBUTE) { 3213 uint32_t newTypeSpecFlags; 3214 blockIndex = getAttribute(inOutValue->data, inOutValue, &newTypeSpecFlags); 3215 TABLE_THEME(ALOGI("Resolving attr reference: blockIndex=%d, type=0x%x, data=%p\n", 3216 (int)blockIndex, (int)inOutValue->dataType, (void*)inOutValue->data)); 3217 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newTypeSpecFlags; 3218 //printf("Retrieved attribute new type=0x%x\n", inOutValue->dataType); 3219 if (blockIndex < 0) { 3220 return blockIndex; 3221 } 3222 } 3223 return mTable.resolveReference(inOutValue, blockIndex, outLastRef, 3224 inoutTypeSpecFlags, inoutConfig); 3225} 3226 3227void ResTable::Theme::dumpToLog() const 3228{ 3229 ALOGI("Theme %p:\n", this); 3230 for (size_t i=0; i<Res_MAXPACKAGE; i++) { 3231 package_info* pi = mPackages[i]; 3232 if (pi == NULL) continue; 3233 3234 ALOGI(" Package #0x%02x:\n", (int)(i + 1)); 3235 for (size_t j = 0; j <= Res_MAXTYPE; j++) { 3236 type_info& ti = pi->types[j]; 3237 if (ti.numEntries == 0) continue; 3238 ALOGI(" Type #0x%02x:\n", (int)(j + 1)); 3239 for (size_t k = 0; k < ti.numEntries; k++) { 3240 const theme_entry& te = ti.entries[k]; 3241 if (te.value.dataType == Res_value::TYPE_NULL) continue; 3242 ALOGI(" 0x%08x: t=0x%x, d=0x%08x (block=%d)\n", 3243 (int)Res_MAKEID(i, j, k), 3244 te.value.dataType, (int)te.value.data, (int)te.stringBlock); 3245 } 3246 } 3247 } 3248} 3249 3250ResTable::ResTable() 3251 : mError(NO_INIT), mNextPackageId(2) 3252{ 3253 memset(&mParams, 0, sizeof(mParams)); 3254 memset(mPackageMap, 0, sizeof(mPackageMap)); 3255 //ALOGI("Creating ResTable %p\n", this); 3256} 3257 3258ResTable::ResTable(const void* data, size_t size, const int32_t cookie, bool copyData) 3259 : mError(NO_INIT), mNextPackageId(2) 3260{ 3261 memset(&mParams, 0, sizeof(mParams)); 3262 memset(mPackageMap, 0, sizeof(mPackageMap)); 3263 addInternal(data, size, NULL, 0, cookie, copyData); 3264 LOG_FATAL_IF(mError != NO_ERROR, "Error parsing resource table"); 3265 //ALOGI("Creating ResTable %p\n", this); 3266} 3267 3268ResTable::~ResTable() 3269{ 3270 //ALOGI("Destroying ResTable in %p\n", this); 3271 uninit(); 3272} 3273 3274inline ssize_t ResTable::getResourcePackageIndex(uint32_t resID) const 3275{ 3276 return ((ssize_t)mPackageMap[Res_GETPACKAGE(resID)+1])-1; 3277} 3278 3279status_t ResTable::add(const void* data, size_t size, const int32_t cookie, bool copyData) { 3280 return addInternal(data, size, NULL, 0, cookie, copyData); 3281} 3282 3283status_t ResTable::add(const void* data, size_t size, const void* idmapData, size_t idmapDataSize, 3284 const int32_t cookie, bool copyData) { 3285 return addInternal(data, size, idmapData, idmapDataSize, cookie, copyData); 3286} 3287 3288status_t ResTable::add(Asset* asset, const int32_t cookie, bool copyData) { 3289 const void* data = asset->getBuffer(true); 3290 if (data == NULL) { 3291 ALOGW("Unable to get buffer of resource asset file"); 3292 return UNKNOWN_ERROR; 3293 } 3294 3295 return addInternal(data, static_cast<size_t>(asset->getLength()), NULL, 0, cookie, copyData); 3296} 3297 3298status_t ResTable::add(Asset* asset, Asset* idmapAsset, const int32_t cookie, bool copyData) { 3299 const void* data = asset->getBuffer(true); 3300 if (data == NULL) { 3301 ALOGW("Unable to get buffer of resource asset file"); 3302 return UNKNOWN_ERROR; 3303 } 3304 3305 size_t idmapSize = 0; 3306 const void* idmapData = NULL; 3307 if (idmapAsset != NULL) { 3308 idmapData = idmapAsset->getBuffer(true); 3309 if (idmapData == NULL) { 3310 ALOGW("Unable to get buffer of idmap asset file"); 3311 return UNKNOWN_ERROR; 3312 } 3313 idmapSize = static_cast<size_t>(idmapAsset->getLength()); 3314 } 3315 3316 return addInternal(data, static_cast<size_t>(asset->getLength()), 3317 idmapData, idmapSize, cookie, copyData); 3318} 3319 3320status_t ResTable::add(ResTable* src) 3321{ 3322 mError = src->mError; 3323 3324 for (size_t i=0; i<src->mHeaders.size(); i++) { 3325 mHeaders.add(src->mHeaders[i]); 3326 } 3327 3328 for (size_t i=0; i<src->mPackageGroups.size(); i++) { 3329 PackageGroup* srcPg = src->mPackageGroups[i]; 3330 PackageGroup* pg = new PackageGroup(this, srcPg->name, srcPg->id); 3331 for (size_t j=0; j<srcPg->packages.size(); j++) { 3332 pg->packages.add(srcPg->packages[j]); 3333 } 3334 3335 for (size_t j = 0; j < srcPg->types.size(); j++) { 3336 if (srcPg->types[j].isEmpty()) { 3337 continue; 3338 } 3339 3340 TypeList& typeList = pg->types.editItemAt(j); 3341 typeList.appendVector(srcPg->types[j]); 3342 } 3343 pg->largestTypeId = max(pg->largestTypeId, srcPg->largestTypeId); 3344 mPackageGroups.add(pg); 3345 } 3346 3347 memcpy(mPackageMap, src->mPackageMap, sizeof(mPackageMap)); 3348 3349 return mError; 3350} 3351 3352status_t ResTable::addEmpty(const int32_t cookie) { 3353 Header* header = new Header(this); 3354 header->index = mHeaders.size(); 3355 header->cookie = cookie; 3356 header->values.setToEmpty(); 3357 header->ownedData = calloc(1, sizeof(ResTable_header)); 3358 3359 ResTable_header* resHeader = (ResTable_header*) header->ownedData; 3360 resHeader->header.type = RES_TABLE_TYPE; 3361 resHeader->header.headerSize = sizeof(ResTable_header); 3362 resHeader->header.size = sizeof(ResTable_header); 3363 3364 header->header = (const ResTable_header*) resHeader; 3365 mHeaders.add(header); 3366 3367 PackageGroup* pg = new PackageGroup(this, String16(), 0); 3368 pg->packages.add(new Package(this, header, NULL)); 3369 mPackageGroups.add(pg); 3370 return (mError=NO_ERROR); 3371} 3372 3373status_t ResTable::addInternal(const void* data, size_t dataSize, const void* idmapData, size_t idmapDataSize, 3374 const int32_t cookie, bool copyData) 3375{ 3376 if (!data) { 3377 return NO_ERROR; 3378 } 3379 3380 if (dataSize < sizeof(ResTable_header)) { 3381 ALOGE("Invalid data. Size(%d) is smaller than a ResTable_header(%d).", 3382 (int) dataSize, (int) sizeof(ResTable_header)); 3383 return UNKNOWN_ERROR; 3384 } 3385 3386 Header* header = new Header(this); 3387 header->index = mHeaders.size(); 3388 header->cookie = cookie; 3389 if (idmapData != NULL) { 3390 header->resourceIDMap = (uint32_t*) malloc(idmapDataSize); 3391 if (header->resourceIDMap == NULL) { 3392 delete header; 3393 return (mError = NO_MEMORY); 3394 } 3395 memcpy(header->resourceIDMap, idmapData, idmapDataSize); 3396 header->resourceIDMapSize = idmapDataSize; 3397 } 3398 mHeaders.add(header); 3399 3400 const bool notDeviceEndian = htods(0xf0) != 0xf0; 3401 3402 LOAD_TABLE_NOISY( 3403 ALOGV("Adding resources to ResTable: data=%p, size=0x%x, cookie=%d, copy=%d " 3404 "idmap=%p\n", data, dataSize, cookie, copyData, idmap)); 3405 3406 if (copyData || notDeviceEndian) { 3407 header->ownedData = malloc(dataSize); 3408 if (header->ownedData == NULL) { 3409 return (mError=NO_MEMORY); 3410 } 3411 memcpy(header->ownedData, data, dataSize); 3412 data = header->ownedData; 3413 } 3414 3415 header->header = (const ResTable_header*)data; 3416 header->size = dtohl(header->header->header.size); 3417 //ALOGI("Got size 0x%x, again size 0x%x, raw size 0x%x\n", header->size, 3418 // dtohl(header->header->header.size), header->header->header.size); 3419 LOAD_TABLE_NOISY(ALOGV("Loading ResTable @%p:\n", header->header)); 3420 if (dtohs(header->header->header.headerSize) > header->size 3421 || header->size > dataSize) { 3422 ALOGW("Bad resource table: header size 0x%x or total size 0x%x is larger than data size 0x%x\n", 3423 (int)dtohs(header->header->header.headerSize), 3424 (int)header->size, (int)dataSize); 3425 return (mError=BAD_TYPE); 3426 } 3427 if (((dtohs(header->header->header.headerSize)|header->size)&0x3) != 0) { 3428 ALOGW("Bad resource table: header size 0x%x or total size 0x%x is not on an integer boundary\n", 3429 (int)dtohs(header->header->header.headerSize), 3430 (int)header->size); 3431 return (mError=BAD_TYPE); 3432 } 3433 header->dataEnd = ((const uint8_t*)header->header) + header->size; 3434 3435 // Iterate through all chunks. 3436 size_t curPackage = 0; 3437 3438 const ResChunk_header* chunk = 3439 (const ResChunk_header*)(((const uint8_t*)header->header) 3440 + dtohs(header->header->header.headerSize)); 3441 while (((const uint8_t*)chunk) <= (header->dataEnd-sizeof(ResChunk_header)) && 3442 ((const uint8_t*)chunk) <= (header->dataEnd-dtohl(chunk->size))) { 3443 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), header->dataEnd, "ResTable"); 3444 if (err != NO_ERROR) { 3445 return (mError=err); 3446 } 3447 TABLE_NOISY(ALOGV("Chunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n", 3448 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size), 3449 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)))); 3450 const size_t csize = dtohl(chunk->size); 3451 const uint16_t ctype = dtohs(chunk->type); 3452 if (ctype == RES_STRING_POOL_TYPE) { 3453 if (header->values.getError() != NO_ERROR) { 3454 // Only use the first string chunk; ignore any others that 3455 // may appear. 3456 status_t err = header->values.setTo(chunk, csize); 3457 if (err != NO_ERROR) { 3458 return (mError=err); 3459 } 3460 } else { 3461 ALOGW("Multiple string chunks found in resource table."); 3462 } 3463 } else if (ctype == RES_TABLE_PACKAGE_TYPE) { 3464 if (curPackage >= dtohl(header->header->packageCount)) { 3465 ALOGW("More package chunks were found than the %d declared in the header.", 3466 dtohl(header->header->packageCount)); 3467 return (mError=BAD_TYPE); 3468 } 3469 3470 if (parsePackage((ResTable_package*)chunk, header) != NO_ERROR) { 3471 return mError; 3472 } 3473 curPackage++; 3474 } else { 3475 ALOGW("Unknown chunk type 0x%x in table at %p.\n", 3476 ctype, 3477 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header))); 3478 } 3479 chunk = (const ResChunk_header*) 3480 (((const uint8_t*)chunk) + csize); 3481 } 3482 3483 if (curPackage < dtohl(header->header->packageCount)) { 3484 ALOGW("Fewer package chunks (%d) were found than the %d declared in the header.", 3485 (int)curPackage, dtohl(header->header->packageCount)); 3486 return (mError=BAD_TYPE); 3487 } 3488 mError = header->values.getError(); 3489 if (mError != NO_ERROR) { 3490 ALOGW("No string values found in resource table!"); 3491 } 3492 3493 TABLE_NOISY(ALOGV("Returning from add with mError=%d\n", mError)); 3494 return mError; 3495} 3496 3497status_t ResTable::getError() const 3498{ 3499 return mError; 3500} 3501 3502void ResTable::uninit() 3503{ 3504 mError = NO_INIT; 3505 size_t N = mPackageGroups.size(); 3506 for (size_t i=0; i<N; i++) { 3507 PackageGroup* g = mPackageGroups[i]; 3508 delete g; 3509 } 3510 N = mHeaders.size(); 3511 for (size_t i=0; i<N; i++) { 3512 Header* header = mHeaders[i]; 3513 if (header->owner == this) { 3514 if (header->ownedData) { 3515 free(header->ownedData); 3516 } 3517 delete header; 3518 } 3519 } 3520 3521 mPackageGroups.clear(); 3522 mHeaders.clear(); 3523} 3524 3525bool ResTable::getResourceName(uint32_t resID, bool allowUtf8, resource_name* outName) const 3526{ 3527 if (mError != NO_ERROR) { 3528 return false; 3529 } 3530 3531 const ssize_t p = getResourcePackageIndex(resID); 3532 const int t = Res_GETTYPE(resID); 3533 const int e = Res_GETENTRY(resID); 3534 3535 if (p < 0) { 3536 if (Res_GETPACKAGE(resID)+1 == 0) { 3537 ALOGW("No package identifier when getting name for resource number 0x%08x", resID); 3538 } else { 3539 ALOGW("No known package when getting name for resource number 0x%08x", resID); 3540 } 3541 return false; 3542 } 3543 if (t < 0) { 3544 ALOGW("No type identifier when getting name for resource number 0x%08x", resID); 3545 return false; 3546 } 3547 3548 const PackageGroup* const grp = mPackageGroups[p]; 3549 if (grp == NULL) { 3550 ALOGW("Bad identifier when getting name for resource number 0x%08x", resID); 3551 return false; 3552 } 3553 3554 Entry entry; 3555 status_t err = getEntry(grp, t, e, NULL, &entry); 3556 if (err != NO_ERROR) { 3557 return false; 3558 } 3559 3560 outName->package = grp->name.string(); 3561 outName->packageLen = grp->name.size(); 3562 if (allowUtf8) { 3563 outName->type8 = entry.typeStr.string8(&outName->typeLen); 3564 outName->name8 = entry.keyStr.string8(&outName->nameLen); 3565 } else { 3566 outName->type8 = NULL; 3567 outName->name8 = NULL; 3568 } 3569 if (outName->type8 == NULL) { 3570 outName->type = entry.typeStr.string16(&outName->typeLen); 3571 // If we have a bad index for some reason, we should abort. 3572 if (outName->type == NULL) { 3573 return false; 3574 } 3575 } 3576 if (outName->name8 == NULL) { 3577 outName->name = entry.keyStr.string16(&outName->nameLen); 3578 // If we have a bad index for some reason, we should abort. 3579 if (outName->name == NULL) { 3580 return false; 3581 } 3582 } 3583 3584 return true; 3585} 3586 3587ssize_t ResTable::getResource(uint32_t resID, Res_value* outValue, bool mayBeBag, uint16_t density, 3588 uint32_t* outSpecFlags, ResTable_config* outConfig) const 3589{ 3590 if (mError != NO_ERROR) { 3591 return mError; 3592 } 3593 3594 const ssize_t p = getResourcePackageIndex(resID); 3595 const int t = Res_GETTYPE(resID); 3596 const int e = Res_GETENTRY(resID); 3597 3598 if (p < 0) { 3599 if (Res_GETPACKAGE(resID)+1 == 0) { 3600 ALOGW("No package identifier when getting value for resource number 0x%08x", resID); 3601 } else { 3602 ALOGW("No known package when getting value for resource number 0x%08x", resID); 3603 } 3604 return BAD_INDEX; 3605 } 3606 if (t < 0) { 3607 ALOGW("No type identifier when getting value for resource number 0x%08x", resID); 3608 return BAD_INDEX; 3609 } 3610 3611 const PackageGroup* const grp = mPackageGroups[p]; 3612 if (grp == NULL) { 3613 ALOGW("Bad identifier when getting value for resource number 0x%08x", resID); 3614 return BAD_INDEX; 3615 } 3616 3617 // Allow overriding density 3618 ResTable_config desiredConfig = mParams; 3619 if (density > 0) { 3620 desiredConfig.density = density; 3621 } 3622 3623 Entry entry; 3624 status_t err = getEntry(grp, t, e, &desiredConfig, &entry); 3625 if (err != NO_ERROR) { 3626 ALOGW("Failure getting entry for 0x%08x (t=%d e=%d) (error %d)\n", 3627 resID, t, e, err); 3628 return err; 3629 } 3630 3631 if ((dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) != 0) { 3632 if (!mayBeBag) { 3633 ALOGW("Requesting resource 0x%08x failed because it is complex\n", resID); 3634 } 3635 return BAD_VALUE; 3636 } 3637 3638 const Res_value* value = reinterpret_cast<const Res_value*>( 3639 reinterpret_cast<const uint8_t*>(entry.entry) + entry.entry->size); 3640 3641 outValue->size = dtohs(value->size); 3642 outValue->res0 = value->res0; 3643 outValue->dataType = value->dataType; 3644 outValue->data = dtohl(value->data); 3645 3646 // The reference may be pointing to a resource in a shared library. These 3647 // references have build-time generated package IDs. These ids may not match 3648 // the actual package IDs of the corresponding packages in this ResTable. 3649 // We need to fix the package ID based on a mapping. 3650 if (grp->dynamicRefTable.lookupResourceValue(outValue) != NO_ERROR) { 3651 ALOGW("Failed to resolve referenced package: 0x%08x", outValue->data); 3652 return BAD_VALUE; 3653 } 3654 3655 TABLE_NOISY(size_t len; 3656 printf("Found value: pkg=%d, type=%d, str=%s, int=%d\n", 3657 entry.package->header->index, 3658 outValue->dataType, 3659 outValue->dataType == Res_value::TYPE_STRING 3660 ? String8(entry.package->header->values.stringAt( 3661 outValue->data, &len)).string() 3662 : "", 3663 outValue->data)); 3664 3665 if (outSpecFlags != NULL) { 3666 *outSpecFlags = entry.specFlags; 3667 } 3668 3669 if (outConfig != NULL) { 3670 *outConfig = entry.config; 3671 } 3672 3673 return entry.package->header->index; 3674} 3675 3676ssize_t ResTable::resolveReference(Res_value* value, ssize_t blockIndex, 3677 uint32_t* outLastRef, uint32_t* inoutTypeSpecFlags, 3678 ResTable_config* outConfig) const 3679{ 3680 int count=0; 3681 while (blockIndex >= 0 && value->dataType == Res_value::TYPE_REFERENCE 3682 && value->data != 0 && count < 20) { 3683 if (outLastRef) *outLastRef = value->data; 3684 uint32_t lastRef = value->data; 3685 uint32_t newFlags = 0; 3686 const ssize_t newIndex = getResource(value->data, value, true, 0, &newFlags, 3687 outConfig); 3688 if (newIndex == BAD_INDEX) { 3689 return BAD_INDEX; 3690 } 3691 TABLE_THEME(ALOGI("Resolving reference %p: newIndex=%d, type=0x%x, data=%p\n", 3692 (void*)lastRef, (int)newIndex, (int)value->dataType, (void*)value->data)); 3693 //printf("Getting reference 0x%08x: newIndex=%d\n", value->data, newIndex); 3694 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newFlags; 3695 if (newIndex < 0) { 3696 // This can fail if the resource being referenced is a style... 3697 // in this case, just return the reference, and expect the 3698 // caller to deal with. 3699 return blockIndex; 3700 } 3701 blockIndex = newIndex; 3702 count++; 3703 } 3704 return blockIndex; 3705} 3706 3707const char16_t* ResTable::valueToString( 3708 const Res_value* value, size_t stringBlock, 3709 char16_t /*tmpBuffer*/ [TMP_BUFFER_SIZE], size_t* outLen) 3710{ 3711 if (!value) { 3712 return NULL; 3713 } 3714 if (value->dataType == value->TYPE_STRING) { 3715 return getTableStringBlock(stringBlock)->stringAt(value->data, outLen); 3716 } 3717 // XXX do int to string conversions. 3718 return NULL; 3719} 3720 3721ssize_t ResTable::lockBag(uint32_t resID, const bag_entry** outBag) const 3722{ 3723 mLock.lock(); 3724 ssize_t err = getBagLocked(resID, outBag); 3725 if (err < NO_ERROR) { 3726 //printf("*** get failed! unlocking\n"); 3727 mLock.unlock(); 3728 } 3729 return err; 3730} 3731 3732void ResTable::unlockBag(const bag_entry* /*bag*/) const 3733{ 3734 //printf("<<< unlockBag %p\n", this); 3735 mLock.unlock(); 3736} 3737 3738void ResTable::lock() const 3739{ 3740 mLock.lock(); 3741} 3742 3743void ResTable::unlock() const 3744{ 3745 mLock.unlock(); 3746} 3747 3748ssize_t ResTable::getBagLocked(uint32_t resID, const bag_entry** outBag, 3749 uint32_t* outTypeSpecFlags) const 3750{ 3751 if (mError != NO_ERROR) { 3752 return mError; 3753 } 3754 3755 const ssize_t p = getResourcePackageIndex(resID); 3756 const int t = Res_GETTYPE(resID); 3757 const int e = Res_GETENTRY(resID); 3758 3759 if (p < 0) { 3760 ALOGW("Invalid package identifier when getting bag for resource number 0x%08x", resID); 3761 return BAD_INDEX; 3762 } 3763 if (t < 0) { 3764 ALOGW("No type identifier when getting bag for resource number 0x%08x", resID); 3765 return BAD_INDEX; 3766 } 3767 3768 //printf("Get bag: id=0x%08x, p=%d, t=%d\n", resID, p, t); 3769 PackageGroup* const grp = mPackageGroups[p]; 3770 if (grp == NULL) { 3771 ALOGW("Bad identifier when getting bag for resource number 0x%08x", resID); 3772 return BAD_INDEX; 3773 } 3774 3775 const TypeList& typeConfigs = grp->types[t]; 3776 if (typeConfigs.isEmpty()) { 3777 ALOGW("Type identifier 0x%x does not exist.", t+1); 3778 return BAD_INDEX; 3779 } 3780 3781 const size_t NENTRY = typeConfigs[0]->entryCount; 3782 if (e >= (int)NENTRY) { 3783 ALOGW("Entry identifier 0x%x is larger than entry count 0x%x", 3784 e, (int)typeConfigs[0]->entryCount); 3785 return BAD_INDEX; 3786 } 3787 3788 // First see if we've already computed this bag... 3789 if (grp->bags) { 3790 bag_set** typeSet = grp->bags->get(t); 3791 if (typeSet) { 3792 bag_set* set = typeSet[e]; 3793 if (set) { 3794 if (set != (bag_set*)0xFFFFFFFF) { 3795 if (outTypeSpecFlags != NULL) { 3796 *outTypeSpecFlags = set->typeSpecFlags; 3797 } 3798 *outBag = (bag_entry*)(set+1); 3799 //ALOGI("Found existing bag for: %p\n", (void*)resID); 3800 return set->numAttrs; 3801 } 3802 ALOGW("Attempt to retrieve bag 0x%08x which is invalid or in a cycle.", 3803 resID); 3804 return BAD_INDEX; 3805 } 3806 } 3807 } 3808 3809 // Bag not found, we need to compute it! 3810 if (!grp->bags) { 3811 grp->bags = new ByteBucketArray<bag_set**>(); 3812 if (!grp->bags) return NO_MEMORY; 3813 } 3814 3815 bag_set** typeSet = grp->bags->get(t); 3816 if (!typeSet) { 3817 typeSet = (bag_set**)calloc(NENTRY, sizeof(bag_set*)); 3818 if (!typeSet) return NO_MEMORY; 3819 grp->bags->set(t, typeSet); 3820 } 3821 3822 // Mark that we are currently working on this one. 3823 typeSet[e] = (bag_set*)0xFFFFFFFF; 3824 3825 TABLE_NOISY(ALOGI("Building bag: %p\n", (void*)resID)); 3826 3827 // Now collect all bag attributes 3828 Entry entry; 3829 status_t err = getEntry(grp, t, e, &mParams, &entry); 3830 if (err != NO_ERROR) { 3831 return err; 3832 } 3833 3834 const uint16_t entrySize = dtohs(entry.entry->size); 3835 const uint32_t parent = entrySize >= sizeof(ResTable_map_entry) 3836 ? dtohl(((const ResTable_map_entry*)entry.entry)->parent.ident) : 0; 3837 const uint32_t count = entrySize >= sizeof(ResTable_map_entry) 3838 ? dtohl(((const ResTable_map_entry*)entry.entry)->count) : 0; 3839 3840 size_t N = count; 3841 3842 TABLE_NOISY(ALOGI("Found map: size=%p parent=%p count=%d\n", 3843 entrySize, parent, count)); 3844 3845 // If this map inherits from another, we need to start 3846 // with its parent's values. Otherwise start out empty. 3847 TABLE_NOISY(printf("Creating new bag, entrySize=0x%08x, parent=0x%08x\n", 3848 entrySize, parent)); 3849 3850 // This is what we are building. 3851 bag_set* set = NULL; 3852 3853 if (parent) { 3854 uint32_t resolvedParent = parent; 3855 3856 // Bags encode a parent reference without using the standard 3857 // Res_value structure. That means we must always try to 3858 // resolve a parent reference in case it is actually a 3859 // TYPE_DYNAMIC_REFERENCE. 3860 status_t err = grp->dynamicRefTable.lookupResourceId(&resolvedParent); 3861 if (err != NO_ERROR) { 3862 ALOGE("Failed resolving bag parent id 0x%08x", parent); 3863 return UNKNOWN_ERROR; 3864 } 3865 3866 const bag_entry* parentBag; 3867 uint32_t parentTypeSpecFlags = 0; 3868 const ssize_t NP = getBagLocked(resolvedParent, &parentBag, &parentTypeSpecFlags); 3869 const size_t NT = ((NP >= 0) ? NP : 0) + N; 3870 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*NT); 3871 if (set == NULL) { 3872 return NO_MEMORY; 3873 } 3874 if (NP > 0) { 3875 memcpy(set+1, parentBag, NP*sizeof(bag_entry)); 3876 set->numAttrs = NP; 3877 TABLE_NOISY(ALOGI("Initialized new bag with %d inherited attributes.\n", NP)); 3878 } else { 3879 TABLE_NOISY(ALOGI("Initialized new bag with no inherited attributes.\n")); 3880 set->numAttrs = 0; 3881 } 3882 set->availAttrs = NT; 3883 set->typeSpecFlags = parentTypeSpecFlags; 3884 } else { 3885 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*N); 3886 if (set == NULL) { 3887 return NO_MEMORY; 3888 } 3889 set->numAttrs = 0; 3890 set->availAttrs = N; 3891 set->typeSpecFlags = 0; 3892 } 3893 3894 set->typeSpecFlags |= entry.specFlags; 3895 3896 // Now merge in the new attributes... 3897 size_t curOff = (reinterpret_cast<uintptr_t>(entry.entry) - reinterpret_cast<uintptr_t>(entry.type)) 3898 + dtohs(entry.entry->size); 3899 const ResTable_map* map; 3900 bag_entry* entries = (bag_entry*)(set+1); 3901 size_t curEntry = 0; 3902 uint32_t pos = 0; 3903 TABLE_NOISY(ALOGI("Starting with set %p, entries=%p, avail=%d\n", 3904 set, entries, set->availAttrs)); 3905 while (pos < count) { 3906 TABLE_NOISY(printf("Now at %p\n", (void*)curOff)); 3907 3908 if (curOff > (dtohl(entry.type->header.size)-sizeof(ResTable_map))) { 3909 ALOGW("ResTable_map at %d is beyond type chunk data %d", 3910 (int)curOff, dtohl(entry.type->header.size)); 3911 return BAD_TYPE; 3912 } 3913 map = (const ResTable_map*)(((const uint8_t*)entry.type) + curOff); 3914 N++; 3915 3916 uint32_t newName = htodl(map->name.ident); 3917 if (!Res_INTERNALID(newName)) { 3918 // Attributes don't have a resource id as the name. They specify 3919 // other data, which would be wrong to change via a lookup. 3920 if (grp->dynamicRefTable.lookupResourceId(&newName) != NO_ERROR) { 3921 ALOGE("Failed resolving ResTable_map name at %d with ident 0x%08x", 3922 (int) curOff, (int) newName); 3923 return UNKNOWN_ERROR; 3924 } 3925 } 3926 3927 bool isInside; 3928 uint32_t oldName = 0; 3929 while ((isInside=(curEntry < set->numAttrs)) 3930 && (oldName=entries[curEntry].map.name.ident) < newName) { 3931 TABLE_NOISY(printf("#%d: Keeping existing attribute: 0x%08x\n", 3932 curEntry, entries[curEntry].map.name.ident)); 3933 curEntry++; 3934 } 3935 3936 if ((!isInside) || oldName != newName) { 3937 // This is a new attribute... figure out what to do with it. 3938 if (set->numAttrs >= set->availAttrs) { 3939 // Need to alloc more memory... 3940 const size_t newAvail = set->availAttrs+N; 3941 set = (bag_set*)realloc(set, 3942 sizeof(bag_set) 3943 + sizeof(bag_entry)*newAvail); 3944 if (set == NULL) { 3945 return NO_MEMORY; 3946 } 3947 set->availAttrs = newAvail; 3948 entries = (bag_entry*)(set+1); 3949 TABLE_NOISY(printf("Reallocated set %p, entries=%p, avail=%d\n", 3950 set, entries, set->availAttrs)); 3951 } 3952 if (isInside) { 3953 // Going in the middle, need to make space. 3954 memmove(entries+curEntry+1, entries+curEntry, 3955 sizeof(bag_entry)*(set->numAttrs-curEntry)); 3956 set->numAttrs++; 3957 } 3958 TABLE_NOISY(printf("#%d: Inserting new attribute: 0x%08x\n", 3959 curEntry, newName)); 3960 } else { 3961 TABLE_NOISY(printf("#%d: Replacing existing attribute: 0x%08x\n", 3962 curEntry, oldName)); 3963 } 3964 3965 bag_entry* cur = entries+curEntry; 3966 3967 cur->stringBlock = entry.package->header->index; 3968 cur->map.name.ident = newName; 3969 cur->map.value.copyFrom_dtoh(map->value); 3970 status_t err = grp->dynamicRefTable.lookupResourceValue(&cur->map.value); 3971 if (err != NO_ERROR) { 3972 ALOGE("Reference item(0x%08x) in bag could not be resolved.", cur->map.value.data); 3973 return UNKNOWN_ERROR; 3974 } 3975 3976 TABLE_NOISY(printf("Setting entry #%d %p: block=%d, name=0x%08x, type=%d, data=0x%08x\n", 3977 curEntry, cur, cur->stringBlock, cur->map.name.ident, 3978 cur->map.value.dataType, cur->map.value.data)); 3979 3980 // On to the next! 3981 curEntry++; 3982 pos++; 3983 const size_t size = dtohs(map->value.size); 3984 curOff += size + sizeof(*map)-sizeof(map->value); 3985 }; 3986 3987 if (curEntry > set->numAttrs) { 3988 set->numAttrs = curEntry; 3989 } 3990 3991 // And this is it... 3992 typeSet[e] = set; 3993 if (set) { 3994 if (outTypeSpecFlags != NULL) { 3995 *outTypeSpecFlags = set->typeSpecFlags; 3996 } 3997 *outBag = (bag_entry*)(set+1); 3998 TABLE_NOISY(ALOGI("Returning %d attrs\n", set->numAttrs)); 3999 return set->numAttrs; 4000 } 4001 return BAD_INDEX; 4002} 4003 4004void ResTable::setParameters(const ResTable_config* params) 4005{ 4006 mLock.lock(); 4007 TABLE_GETENTRY(ALOGI("Setting parameters: %s\n", params->toString().string())); 4008 mParams = *params; 4009 for (size_t i=0; i<mPackageGroups.size(); i++) { 4010 TABLE_NOISY(ALOGI("CLEARING BAGS FOR GROUP %d!", i)); 4011 mPackageGroups[i]->clearBagCache(); 4012 } 4013 mLock.unlock(); 4014} 4015 4016void ResTable::getParameters(ResTable_config* params) const 4017{ 4018 mLock.lock(); 4019 *params = mParams; 4020 mLock.unlock(); 4021} 4022 4023struct id_name_map { 4024 uint32_t id; 4025 size_t len; 4026 char16_t name[6]; 4027}; 4028 4029const static id_name_map ID_NAMES[] = { 4030 { ResTable_map::ATTR_TYPE, 5, { '^', 't', 'y', 'p', 'e' } }, 4031 { ResTable_map::ATTR_L10N, 5, { '^', 'l', '1', '0', 'n' } }, 4032 { ResTable_map::ATTR_MIN, 4, { '^', 'm', 'i', 'n' } }, 4033 { ResTable_map::ATTR_MAX, 4, { '^', 'm', 'a', 'x' } }, 4034 { ResTable_map::ATTR_OTHER, 6, { '^', 'o', 't', 'h', 'e', 'r' } }, 4035 { ResTable_map::ATTR_ZERO, 5, { '^', 'z', 'e', 'r', 'o' } }, 4036 { ResTable_map::ATTR_ONE, 4, { '^', 'o', 'n', 'e' } }, 4037 { ResTable_map::ATTR_TWO, 4, { '^', 't', 'w', 'o' } }, 4038 { ResTable_map::ATTR_FEW, 4, { '^', 'f', 'e', 'w' } }, 4039 { ResTable_map::ATTR_MANY, 5, { '^', 'm', 'a', 'n', 'y' } }, 4040}; 4041 4042uint32_t ResTable::identifierForName(const char16_t* name, size_t nameLen, 4043 const char16_t* type, size_t typeLen, 4044 const char16_t* package, 4045 size_t packageLen, 4046 uint32_t* outTypeSpecFlags) const 4047{ 4048 TABLE_SUPER_NOISY(printf("Identifier for name: error=%d\n", mError)); 4049 4050 // Check for internal resource identifier as the very first thing, so 4051 // that we will always find them even when there are no resources. 4052 if (name[0] == '^') { 4053 const int N = (sizeof(ID_NAMES)/sizeof(ID_NAMES[0])); 4054 size_t len; 4055 for (int i=0; i<N; i++) { 4056 const id_name_map* m = ID_NAMES + i; 4057 len = m->len; 4058 if (len != nameLen) { 4059 continue; 4060 } 4061 for (size_t j=1; j<len; j++) { 4062 if (m->name[j] != name[j]) { 4063 goto nope; 4064 } 4065 } 4066 if (outTypeSpecFlags) { 4067 *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC; 4068 } 4069 return m->id; 4070nope: 4071 ; 4072 } 4073 if (nameLen > 7) { 4074 if (name[1] == 'i' && name[2] == 'n' 4075 && name[3] == 'd' && name[4] == 'e' && name[5] == 'x' 4076 && name[6] == '_') { 4077 int index = atoi(String8(name + 7, nameLen - 7).string()); 4078 if (Res_CHECKID(index)) { 4079 ALOGW("Array resource index: %d is too large.", 4080 index); 4081 return 0; 4082 } 4083 if (outTypeSpecFlags) { 4084 *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC; 4085 } 4086 return Res_MAKEARRAY(index); 4087 } 4088 } 4089 return 0; 4090 } 4091 4092 if (mError != NO_ERROR) { 4093 return 0; 4094 } 4095 4096 bool fakePublic = false; 4097 4098 // Figure out the package and type we are looking in... 4099 4100 const char16_t* packageEnd = NULL; 4101 const char16_t* typeEnd = NULL; 4102 const char16_t* const nameEnd = name+nameLen; 4103 const char16_t* p = name; 4104 while (p < nameEnd) { 4105 if (*p == ':') packageEnd = p; 4106 else if (*p == '/') typeEnd = p; 4107 p++; 4108 } 4109 if (*name == '@') { 4110 name++; 4111 if (*name == '*') { 4112 fakePublic = true; 4113 name++; 4114 } 4115 } 4116 if (name >= nameEnd) { 4117 return 0; 4118 } 4119 4120 if (packageEnd) { 4121 package = name; 4122 packageLen = packageEnd-name; 4123 name = packageEnd+1; 4124 } else if (!package) { 4125 return 0; 4126 } 4127 4128 if (typeEnd) { 4129 type = name; 4130 typeLen = typeEnd-name; 4131 name = typeEnd+1; 4132 } else if (!type) { 4133 return 0; 4134 } 4135 4136 if (name >= nameEnd) { 4137 return 0; 4138 } 4139 nameLen = nameEnd-name; 4140 4141 TABLE_NOISY(printf("Looking for identifier: type=%s, name=%s, package=%s\n", 4142 String8(type, typeLen).string(), 4143 String8(name, nameLen).string(), 4144 String8(package, packageLen).string())); 4145 4146 const size_t NG = mPackageGroups.size(); 4147 for (size_t ig=0; ig<NG; ig++) { 4148 const PackageGroup* group = mPackageGroups[ig]; 4149 4150 if (strzcmp16(package, packageLen, 4151 group->name.string(), group->name.size())) { 4152 TABLE_NOISY(printf("Skipping package group: %s\n", String8(group->name).string())); 4153 continue; 4154 } 4155 4156 const ssize_t ti = group->findType16(type, typeLen); 4157 if (ti < 0) { 4158 TABLE_NOISY(printf("Type not found in package %s\n", String8(group->name).string())); 4159 continue; 4160 } 4161 4162 const TypeList& typeList = group->types[ti]; 4163 if (typeList.isEmpty()) { 4164 TABLE_NOISY(printf("Expected type structure not found in package %s for index %d\n", 4165 String8(group->name).string(), ti)); 4166 continue; 4167 } 4168 4169 const size_t typeCount = typeList.size(); 4170 for (size_t i = 0; i < typeCount; i++) { 4171 const Type* t = typeList[i]; 4172 const ssize_t ei = t->package->keyStrings.indexOfString(name, nameLen); 4173 if (ei < 0) { 4174 continue; 4175 } 4176 4177 const size_t configCount = t->configs.size(); 4178 for (size_t j = 0; j < configCount; j++) { 4179 const TypeVariant tv(t->configs[j]); 4180 for (TypeVariant::iterator iter = tv.beginEntries(); 4181 iter != tv.endEntries(); 4182 iter++) { 4183 const ResTable_entry* entry = *iter; 4184 if (entry == NULL) { 4185 continue; 4186 } 4187 4188 if (dtohl(entry->key.index) == (size_t) ei) { 4189 uint32_t resId = Res_MAKEID(group->id - 1, ti, iter.index()); 4190 if (outTypeSpecFlags) { 4191 Entry result; 4192 if (getEntry(group, ti, iter.index(), NULL, &result) != NO_ERROR) { 4193 ALOGW("Failed to find spec flags for %s:%s/%s (0x%08x)", 4194 String8(group->name).string(), 4195 String8(String16(type, typeLen)).string(), 4196 String8(String16(name, nameLen)).string(), 4197 resId); 4198 return 0; 4199 } 4200 *outTypeSpecFlags = result.specFlags; 4201 4202 if (fakePublic) { 4203 *outTypeSpecFlags |= ResTable_typeSpec::SPEC_PUBLIC; 4204 } 4205 } 4206 return resId; 4207 } 4208 } 4209 } 4210 } 4211 break; 4212 } 4213 return 0; 4214} 4215 4216bool ResTable::expandResourceRef(const uint16_t* refStr, size_t refLen, 4217 String16* outPackage, 4218 String16* outType, 4219 String16* outName, 4220 const String16* defType, 4221 const String16* defPackage, 4222 const char** outErrorMsg, 4223 bool* outPublicOnly) 4224{ 4225 const char16_t* packageEnd = NULL; 4226 const char16_t* typeEnd = NULL; 4227 const char16_t* p = refStr; 4228 const char16_t* const end = p + refLen; 4229 while (p < end) { 4230 if (*p == ':') packageEnd = p; 4231 else if (*p == '/') { 4232 typeEnd = p; 4233 break; 4234 } 4235 p++; 4236 } 4237 p = refStr; 4238 if (*p == '@') p++; 4239 4240 if (outPublicOnly != NULL) { 4241 *outPublicOnly = true; 4242 } 4243 if (*p == '*') { 4244 p++; 4245 if (outPublicOnly != NULL) { 4246 *outPublicOnly = false; 4247 } 4248 } 4249 4250 if (packageEnd) { 4251 *outPackage = String16(p, packageEnd-p); 4252 p = packageEnd+1; 4253 } else { 4254 if (!defPackage) { 4255 if (outErrorMsg) { 4256 *outErrorMsg = "No resource package specified"; 4257 } 4258 return false; 4259 } 4260 *outPackage = *defPackage; 4261 } 4262 if (typeEnd) { 4263 *outType = String16(p, typeEnd-p); 4264 p = typeEnd+1; 4265 } else { 4266 if (!defType) { 4267 if (outErrorMsg) { 4268 *outErrorMsg = "No resource type specified"; 4269 } 4270 return false; 4271 } 4272 *outType = *defType; 4273 } 4274 *outName = String16(p, end-p); 4275 if(**outPackage == 0) { 4276 if(outErrorMsg) { 4277 *outErrorMsg = "Resource package cannot be an empty string"; 4278 } 4279 return false; 4280 } 4281 if(**outType == 0) { 4282 if(outErrorMsg) { 4283 *outErrorMsg = "Resource type cannot be an empty string"; 4284 } 4285 return false; 4286 } 4287 if(**outName == 0) { 4288 if(outErrorMsg) { 4289 *outErrorMsg = "Resource id cannot be an empty string"; 4290 } 4291 return false; 4292 } 4293 return true; 4294} 4295 4296static uint32_t get_hex(char c, bool* outError) 4297{ 4298 if (c >= '0' && c <= '9') { 4299 return c - '0'; 4300 } else if (c >= 'a' && c <= 'f') { 4301 return c - 'a' + 0xa; 4302 } else if (c >= 'A' && c <= 'F') { 4303 return c - 'A' + 0xa; 4304 } 4305 *outError = true; 4306 return 0; 4307} 4308 4309struct unit_entry 4310{ 4311 const char* name; 4312 size_t len; 4313 uint8_t type; 4314 uint32_t unit; 4315 float scale; 4316}; 4317 4318static const unit_entry unitNames[] = { 4319 { "px", strlen("px"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PX, 1.0f }, 4320 { "dip", strlen("dip"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f }, 4321 { "dp", strlen("dp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f }, 4322 { "sp", strlen("sp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_SP, 1.0f }, 4323 { "pt", strlen("pt"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PT, 1.0f }, 4324 { "in", strlen("in"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_IN, 1.0f }, 4325 { "mm", strlen("mm"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_MM, 1.0f }, 4326 { "%", strlen("%"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION, 1.0f/100 }, 4327 { "%p", strlen("%p"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION_PARENT, 1.0f/100 }, 4328 { NULL, 0, 0, 0, 0 } 4329}; 4330 4331static bool parse_unit(const char* str, Res_value* outValue, 4332 float* outScale, const char** outEnd) 4333{ 4334 const char* end = str; 4335 while (*end != 0 && !isspace((unsigned char)*end)) { 4336 end++; 4337 } 4338 const size_t len = end-str; 4339 4340 const char* realEnd = end; 4341 while (*realEnd != 0 && isspace((unsigned char)*realEnd)) { 4342 realEnd++; 4343 } 4344 if (*realEnd != 0) { 4345 return false; 4346 } 4347 4348 const unit_entry* cur = unitNames; 4349 while (cur->name) { 4350 if (len == cur->len && strncmp(cur->name, str, len) == 0) { 4351 outValue->dataType = cur->type; 4352 outValue->data = cur->unit << Res_value::COMPLEX_UNIT_SHIFT; 4353 *outScale = cur->scale; 4354 *outEnd = end; 4355 //printf("Found unit %s for %s\n", cur->name, str); 4356 return true; 4357 } 4358 cur++; 4359 } 4360 4361 return false; 4362} 4363 4364 4365bool ResTable::stringToInt(const char16_t* s, size_t len, Res_value* outValue) 4366{ 4367 while (len > 0 && isspace16(*s)) { 4368 s++; 4369 len--; 4370 } 4371 4372 if (len <= 0) { 4373 return false; 4374 } 4375 4376 size_t i = 0; 4377 int32_t val = 0; 4378 bool neg = false; 4379 4380 if (*s == '-') { 4381 neg = true; 4382 i++; 4383 } 4384 4385 if (s[i] < '0' || s[i] > '9') { 4386 return false; 4387 } 4388 4389 // Decimal or hex? 4390 if (s[i] == '0' && s[i+1] == 'x') { 4391 if (outValue) 4392 outValue->dataType = outValue->TYPE_INT_HEX; 4393 i += 2; 4394 bool error = false; 4395 while (i < len && !error) { 4396 val = (val*16) + get_hex(s[i], &error); 4397 i++; 4398 } 4399 if (error) { 4400 return false; 4401 } 4402 } else { 4403 if (outValue) 4404 outValue->dataType = outValue->TYPE_INT_DEC; 4405 while (i < len) { 4406 if (s[i] < '0' || s[i] > '9') { 4407 return false; 4408 } 4409 val = (val*10) + s[i]-'0'; 4410 i++; 4411 } 4412 } 4413 4414 if (neg) val = -val; 4415 4416 while (i < len && isspace16(s[i])) { 4417 i++; 4418 } 4419 4420 if (i == len) { 4421 if (outValue) 4422 outValue->data = val; 4423 return true; 4424 } 4425 4426 return false; 4427} 4428 4429bool ResTable::stringToFloat(const char16_t* s, size_t len, Res_value* outValue) 4430{ 4431 while (len > 0 && isspace16(*s)) { 4432 s++; 4433 len--; 4434 } 4435 4436 if (len <= 0) { 4437 return false; 4438 } 4439 4440 char buf[128]; 4441 int i=0; 4442 while (len > 0 && *s != 0 && i < 126) { 4443 if (*s > 255) { 4444 return false; 4445 } 4446 buf[i++] = *s++; 4447 len--; 4448 } 4449 4450 if (len > 0) { 4451 return false; 4452 } 4453 if (buf[0] < '0' && buf[0] > '9' && buf[0] != '.') { 4454 return false; 4455 } 4456 4457 buf[i] = 0; 4458 const char* end; 4459 float f = strtof(buf, (char**)&end); 4460 4461 if (*end != 0 && !isspace((unsigned char)*end)) { 4462 // Might be a unit... 4463 float scale; 4464 if (parse_unit(end, outValue, &scale, &end)) { 4465 f *= scale; 4466 const bool neg = f < 0; 4467 if (neg) f = -f; 4468 uint64_t bits = (uint64_t)(f*(1<<23)+.5f); 4469 uint32_t radix; 4470 uint32_t shift; 4471 if ((bits&0x7fffff) == 0) { 4472 // Always use 23p0 if there is no fraction, just to make 4473 // things easier to read. 4474 radix = Res_value::COMPLEX_RADIX_23p0; 4475 shift = 23; 4476 } else if ((bits&0xffffffffff800000LL) == 0) { 4477 // Magnitude is zero -- can fit in 0 bits of precision. 4478 radix = Res_value::COMPLEX_RADIX_0p23; 4479 shift = 0; 4480 } else if ((bits&0xffffffff80000000LL) == 0) { 4481 // Magnitude can fit in 8 bits of precision. 4482 radix = Res_value::COMPLEX_RADIX_8p15; 4483 shift = 8; 4484 } else if ((bits&0xffffff8000000000LL) == 0) { 4485 // Magnitude can fit in 16 bits of precision. 4486 radix = Res_value::COMPLEX_RADIX_16p7; 4487 shift = 16; 4488 } else { 4489 // Magnitude needs entire range, so no fractional part. 4490 radix = Res_value::COMPLEX_RADIX_23p0; 4491 shift = 23; 4492 } 4493 int32_t mantissa = (int32_t)( 4494 (bits>>shift) & Res_value::COMPLEX_MANTISSA_MASK); 4495 if (neg) { 4496 mantissa = (-mantissa) & Res_value::COMPLEX_MANTISSA_MASK; 4497 } 4498 outValue->data |= 4499 (radix<<Res_value::COMPLEX_RADIX_SHIFT) 4500 | (mantissa<<Res_value::COMPLEX_MANTISSA_SHIFT); 4501 //printf("Input value: %f 0x%016Lx, mult: %f, radix: %d, shift: %d, final: 0x%08x\n", 4502 // f * (neg ? -1 : 1), bits, f*(1<<23), 4503 // radix, shift, outValue->data); 4504 return true; 4505 } 4506 return false; 4507 } 4508 4509 while (*end != 0 && isspace((unsigned char)*end)) { 4510 end++; 4511 } 4512 4513 if (*end == 0) { 4514 if (outValue) { 4515 outValue->dataType = outValue->TYPE_FLOAT; 4516 *(float*)(&outValue->data) = f; 4517 return true; 4518 } 4519 } 4520 4521 return false; 4522} 4523 4524bool ResTable::stringToValue(Res_value* outValue, String16* outString, 4525 const char16_t* s, size_t len, 4526 bool preserveSpaces, bool coerceType, 4527 uint32_t attrID, 4528 const String16* defType, 4529 const String16* defPackage, 4530 Accessor* accessor, 4531 void* accessorCookie, 4532 uint32_t attrType, 4533 bool enforcePrivate) const 4534{ 4535 bool localizationSetting = accessor != NULL && accessor->getLocalizationSetting(); 4536 const char* errorMsg = NULL; 4537 4538 outValue->size = sizeof(Res_value); 4539 outValue->res0 = 0; 4540 4541 // First strip leading/trailing whitespace. Do this before handling 4542 // escapes, so they can be used to force whitespace into the string. 4543 if (!preserveSpaces) { 4544 while (len > 0 && isspace16(*s)) { 4545 s++; 4546 len--; 4547 } 4548 while (len > 0 && isspace16(s[len-1])) { 4549 len--; 4550 } 4551 // If the string ends with '\', then we keep the space after it. 4552 if (len > 0 && s[len-1] == '\\' && s[len] != 0) { 4553 len++; 4554 } 4555 } 4556 4557 //printf("Value for: %s\n", String8(s, len).string()); 4558 4559 uint32_t l10nReq = ResTable_map::L10N_NOT_REQUIRED; 4560 uint32_t attrMin = 0x80000000, attrMax = 0x7fffffff; 4561 bool fromAccessor = false; 4562 if (attrID != 0 && !Res_INTERNALID(attrID)) { 4563 const ssize_t p = getResourcePackageIndex(attrID); 4564 const bag_entry* bag; 4565 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1; 4566 //printf("For attr 0x%08x got bag of %d\n", attrID, cnt); 4567 if (cnt >= 0) { 4568 while (cnt > 0) { 4569 //printf("Entry 0x%08x = 0x%08x\n", bag->map.name.ident, bag->map.value.data); 4570 switch (bag->map.name.ident) { 4571 case ResTable_map::ATTR_TYPE: 4572 attrType = bag->map.value.data; 4573 break; 4574 case ResTable_map::ATTR_MIN: 4575 attrMin = bag->map.value.data; 4576 break; 4577 case ResTable_map::ATTR_MAX: 4578 attrMax = bag->map.value.data; 4579 break; 4580 case ResTable_map::ATTR_L10N: 4581 l10nReq = bag->map.value.data; 4582 break; 4583 } 4584 bag++; 4585 cnt--; 4586 } 4587 unlockBag(bag); 4588 } else if (accessor && accessor->getAttributeType(attrID, &attrType)) { 4589 fromAccessor = true; 4590 if (attrType == ResTable_map::TYPE_ENUM 4591 || attrType == ResTable_map::TYPE_FLAGS 4592 || attrType == ResTable_map::TYPE_INTEGER) { 4593 accessor->getAttributeMin(attrID, &attrMin); 4594 accessor->getAttributeMax(attrID, &attrMax); 4595 } 4596 if (localizationSetting) { 4597 l10nReq = accessor->getAttributeL10N(attrID); 4598 } 4599 } 4600 } 4601 4602 const bool canStringCoerce = 4603 coerceType && (attrType&ResTable_map::TYPE_STRING) != 0; 4604 4605 if (*s == '@') { 4606 outValue->dataType = outValue->TYPE_REFERENCE; 4607 4608 // Note: we don't check attrType here because the reference can 4609 // be to any other type; we just need to count on the client making 4610 // sure the referenced type is correct. 4611 4612 //printf("Looking up ref: %s\n", String8(s, len).string()); 4613 4614 // It's a reference! 4615 if (len == 5 && s[1]=='n' && s[2]=='u' && s[3]=='l' && s[4]=='l') { 4616 outValue->data = 0; 4617 return true; 4618 } else { 4619 bool createIfNotFound = false; 4620 const char16_t* resourceRefName; 4621 int resourceNameLen; 4622 if (len > 2 && s[1] == '+') { 4623 createIfNotFound = true; 4624 resourceRefName = s + 2; 4625 resourceNameLen = len - 2; 4626 } else if (len > 2 && s[1] == '*') { 4627 enforcePrivate = false; 4628 resourceRefName = s + 2; 4629 resourceNameLen = len - 2; 4630 } else { 4631 createIfNotFound = false; 4632 resourceRefName = s + 1; 4633 resourceNameLen = len - 1; 4634 } 4635 String16 package, type, name; 4636 if (!expandResourceRef(resourceRefName,resourceNameLen, &package, &type, &name, 4637 defType, defPackage, &errorMsg)) { 4638 if (accessor != NULL) { 4639 accessor->reportError(accessorCookie, errorMsg); 4640 } 4641 return false; 4642 } 4643 4644 uint32_t specFlags = 0; 4645 uint32_t rid = identifierForName(name.string(), name.size(), type.string(), 4646 type.size(), package.string(), package.size(), &specFlags); 4647 if (rid != 0) { 4648 if (enforcePrivate) { 4649 if (accessor == NULL || accessor->getAssetsPackage() != package) { 4650 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) { 4651 if (accessor != NULL) { 4652 accessor->reportError(accessorCookie, "Resource is not public."); 4653 } 4654 return false; 4655 } 4656 } 4657 } 4658 4659 if (accessor) { 4660 rid = Res_MAKEID( 4661 accessor->getRemappedPackage(Res_GETPACKAGE(rid)), 4662 Res_GETTYPE(rid), Res_GETENTRY(rid)); 4663 TABLE_NOISY(printf("Incl %s:%s/%s: 0x%08x\n", 4664 String8(package).string(), String8(type).string(), 4665 String8(name).string(), rid)); 4666 } 4667 4668 uint32_t packageId = Res_GETPACKAGE(rid) + 1; 4669 if (packageId != APP_PACKAGE_ID && packageId != SYS_PACKAGE_ID) { 4670 outValue->dataType = Res_value::TYPE_DYNAMIC_REFERENCE; 4671 } 4672 outValue->data = rid; 4673 return true; 4674 } 4675 4676 if (accessor) { 4677 uint32_t rid = accessor->getCustomResourceWithCreation(package, type, name, 4678 createIfNotFound); 4679 if (rid != 0) { 4680 TABLE_NOISY(printf("Pckg %s:%s/%s: 0x%08x\n", 4681 String8(package).string(), String8(type).string(), 4682 String8(name).string(), rid)); 4683 uint32_t packageId = Res_GETPACKAGE(rid) + 1; 4684 if (packageId == 0x00) { 4685 outValue->data = rid; 4686 outValue->dataType = Res_value::TYPE_DYNAMIC_REFERENCE; 4687 return true; 4688 } else if (packageId == APP_PACKAGE_ID || packageId == SYS_PACKAGE_ID) { 4689 // We accept packageId's generated as 0x01 in order to support 4690 // building the android system resources 4691 outValue->data = rid; 4692 return true; 4693 } 4694 } 4695 } 4696 } 4697 4698 if (accessor != NULL) { 4699 accessor->reportError(accessorCookie, "No resource found that matches the given name"); 4700 } 4701 return false; 4702 } 4703 4704 // if we got to here, and localization is required and it's not a reference, 4705 // complain and bail. 4706 if (l10nReq == ResTable_map::L10N_SUGGESTED) { 4707 if (localizationSetting) { 4708 if (accessor != NULL) { 4709 accessor->reportError(accessorCookie, "This attribute must be localized."); 4710 } 4711 } 4712 } 4713 4714 if (*s == '#') { 4715 // It's a color! Convert to an integer of the form 0xaarrggbb. 4716 uint32_t color = 0; 4717 bool error = false; 4718 if (len == 4) { 4719 outValue->dataType = outValue->TYPE_INT_COLOR_RGB4; 4720 color |= 0xFF000000; 4721 color |= get_hex(s[1], &error) << 20; 4722 color |= get_hex(s[1], &error) << 16; 4723 color |= get_hex(s[2], &error) << 12; 4724 color |= get_hex(s[2], &error) << 8; 4725 color |= get_hex(s[3], &error) << 4; 4726 color |= get_hex(s[3], &error); 4727 } else if (len == 5) { 4728 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB4; 4729 color |= get_hex(s[1], &error) << 28; 4730 color |= get_hex(s[1], &error) << 24; 4731 color |= get_hex(s[2], &error) << 20; 4732 color |= get_hex(s[2], &error) << 16; 4733 color |= get_hex(s[3], &error) << 12; 4734 color |= get_hex(s[3], &error) << 8; 4735 color |= get_hex(s[4], &error) << 4; 4736 color |= get_hex(s[4], &error); 4737 } else if (len == 7) { 4738 outValue->dataType = outValue->TYPE_INT_COLOR_RGB8; 4739 color |= 0xFF000000; 4740 color |= get_hex(s[1], &error) << 20; 4741 color |= get_hex(s[2], &error) << 16; 4742 color |= get_hex(s[3], &error) << 12; 4743 color |= get_hex(s[4], &error) << 8; 4744 color |= get_hex(s[5], &error) << 4; 4745 color |= get_hex(s[6], &error); 4746 } else if (len == 9) { 4747 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB8; 4748 color |= get_hex(s[1], &error) << 28; 4749 color |= get_hex(s[2], &error) << 24; 4750 color |= get_hex(s[3], &error) << 20; 4751 color |= get_hex(s[4], &error) << 16; 4752 color |= get_hex(s[5], &error) << 12; 4753 color |= get_hex(s[6], &error) << 8; 4754 color |= get_hex(s[7], &error) << 4; 4755 color |= get_hex(s[8], &error); 4756 } else { 4757 error = true; 4758 } 4759 if (!error) { 4760 if ((attrType&ResTable_map::TYPE_COLOR) == 0) { 4761 if (!canStringCoerce) { 4762 if (accessor != NULL) { 4763 accessor->reportError(accessorCookie, 4764 "Color types not allowed"); 4765 } 4766 return false; 4767 } 4768 } else { 4769 outValue->data = color; 4770 //printf("Color input=%s, output=0x%x\n", String8(s, len).string(), color); 4771 return true; 4772 } 4773 } else { 4774 if ((attrType&ResTable_map::TYPE_COLOR) != 0) { 4775 if (accessor != NULL) { 4776 accessor->reportError(accessorCookie, "Color value not valid --" 4777 " must be #rgb, #argb, #rrggbb, or #aarrggbb"); 4778 } 4779 #if 0 4780 fprintf(stderr, "%s: Color ID %s value %s is not valid\n", 4781 "Resource File", //(const char*)in->getPrintableSource(), 4782 String8(*curTag).string(), 4783 String8(s, len).string()); 4784 #endif 4785 return false; 4786 } 4787 } 4788 } 4789 4790 if (*s == '?') { 4791 outValue->dataType = outValue->TYPE_ATTRIBUTE; 4792 4793 // Note: we don't check attrType here because the reference can 4794 // be to any other type; we just need to count on the client making 4795 // sure the referenced type is correct. 4796 4797 //printf("Looking up attr: %s\n", String8(s, len).string()); 4798 4799 static const String16 attr16("attr"); 4800 String16 package, type, name; 4801 if (!expandResourceRef(s+1, len-1, &package, &type, &name, 4802 &attr16, defPackage, &errorMsg)) { 4803 if (accessor != NULL) { 4804 accessor->reportError(accessorCookie, errorMsg); 4805 } 4806 return false; 4807 } 4808 4809 //printf("Pkg: %s, Type: %s, Name: %s\n", 4810 // String8(package).string(), String8(type).string(), 4811 // String8(name).string()); 4812 uint32_t specFlags = 0; 4813 uint32_t rid = 4814 identifierForName(name.string(), name.size(), 4815 type.string(), type.size(), 4816 package.string(), package.size(), &specFlags); 4817 if (rid != 0) { 4818 if (enforcePrivate) { 4819 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) { 4820 if (accessor != NULL) { 4821 accessor->reportError(accessorCookie, "Attribute is not public."); 4822 } 4823 return false; 4824 } 4825 } 4826 if (!accessor) { 4827 outValue->data = rid; 4828 return true; 4829 } 4830 rid = Res_MAKEID( 4831 accessor->getRemappedPackage(Res_GETPACKAGE(rid)), 4832 Res_GETTYPE(rid), Res_GETENTRY(rid)); 4833 //printf("Incl %s:%s/%s: 0x%08x\n", 4834 // String8(package).string(), String8(type).string(), 4835 // String8(name).string(), rid); 4836 outValue->data = rid; 4837 return true; 4838 } 4839 4840 if (accessor) { 4841 uint32_t rid = accessor->getCustomResource(package, type, name); 4842 if (rid != 0) { 4843 //printf("Mine %s:%s/%s: 0x%08x\n", 4844 // String8(package).string(), String8(type).string(), 4845 // String8(name).string(), rid); 4846 outValue->data = rid; 4847 return true; 4848 } 4849 } 4850 4851 if (accessor != NULL) { 4852 accessor->reportError(accessorCookie, "No resource found that matches the given name"); 4853 } 4854 return false; 4855 } 4856 4857 if (stringToInt(s, len, outValue)) { 4858 if ((attrType&ResTable_map::TYPE_INTEGER) == 0) { 4859 // If this type does not allow integers, but does allow floats, 4860 // fall through on this error case because the float type should 4861 // be able to accept any integer value. 4862 if (!canStringCoerce && (attrType&ResTable_map::TYPE_FLOAT) == 0) { 4863 if (accessor != NULL) { 4864 accessor->reportError(accessorCookie, "Integer types not allowed"); 4865 } 4866 return false; 4867 } 4868 } else { 4869 if (((int32_t)outValue->data) < ((int32_t)attrMin) 4870 || ((int32_t)outValue->data) > ((int32_t)attrMax)) { 4871 if (accessor != NULL) { 4872 accessor->reportError(accessorCookie, "Integer value out of range"); 4873 } 4874 return false; 4875 } 4876 return true; 4877 } 4878 } 4879 4880 if (stringToFloat(s, len, outValue)) { 4881 if (outValue->dataType == Res_value::TYPE_DIMENSION) { 4882 if ((attrType&ResTable_map::TYPE_DIMENSION) != 0) { 4883 return true; 4884 } 4885 if (!canStringCoerce) { 4886 if (accessor != NULL) { 4887 accessor->reportError(accessorCookie, "Dimension types not allowed"); 4888 } 4889 return false; 4890 } 4891 } else if (outValue->dataType == Res_value::TYPE_FRACTION) { 4892 if ((attrType&ResTable_map::TYPE_FRACTION) != 0) { 4893 return true; 4894 } 4895 if (!canStringCoerce) { 4896 if (accessor != NULL) { 4897 accessor->reportError(accessorCookie, "Fraction types not allowed"); 4898 } 4899 return false; 4900 } 4901 } else if ((attrType&ResTable_map::TYPE_FLOAT) == 0) { 4902 if (!canStringCoerce) { 4903 if (accessor != NULL) { 4904 accessor->reportError(accessorCookie, "Float types not allowed"); 4905 } 4906 return false; 4907 } 4908 } else { 4909 return true; 4910 } 4911 } 4912 4913 if (len == 4) { 4914 if ((s[0] == 't' || s[0] == 'T') && 4915 (s[1] == 'r' || s[1] == 'R') && 4916 (s[2] == 'u' || s[2] == 'U') && 4917 (s[3] == 'e' || s[3] == 'E')) { 4918 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) { 4919 if (!canStringCoerce) { 4920 if (accessor != NULL) { 4921 accessor->reportError(accessorCookie, "Boolean types not allowed"); 4922 } 4923 return false; 4924 } 4925 } else { 4926 outValue->dataType = outValue->TYPE_INT_BOOLEAN; 4927 outValue->data = (uint32_t)-1; 4928 return true; 4929 } 4930 } 4931 } 4932 4933 if (len == 5) { 4934 if ((s[0] == 'f' || s[0] == 'F') && 4935 (s[1] == 'a' || s[1] == 'A') && 4936 (s[2] == 'l' || s[2] == 'L') && 4937 (s[3] == 's' || s[3] == 'S') && 4938 (s[4] == 'e' || s[4] == 'E')) { 4939 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) { 4940 if (!canStringCoerce) { 4941 if (accessor != NULL) { 4942 accessor->reportError(accessorCookie, "Boolean types not allowed"); 4943 } 4944 return false; 4945 } 4946 } else { 4947 outValue->dataType = outValue->TYPE_INT_BOOLEAN; 4948 outValue->data = 0; 4949 return true; 4950 } 4951 } 4952 } 4953 4954 if ((attrType&ResTable_map::TYPE_ENUM) != 0) { 4955 const ssize_t p = getResourcePackageIndex(attrID); 4956 const bag_entry* bag; 4957 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1; 4958 //printf("Got %d for enum\n", cnt); 4959 if (cnt >= 0) { 4960 resource_name rname; 4961 while (cnt > 0) { 4962 if (!Res_INTERNALID(bag->map.name.ident)) { 4963 //printf("Trying attr #%08x\n", bag->map.name.ident); 4964 if (getResourceName(bag->map.name.ident, false, &rname)) { 4965 #if 0 4966 printf("Matching %s against %s (0x%08x)\n", 4967 String8(s, len).string(), 4968 String8(rname.name, rname.nameLen).string(), 4969 bag->map.name.ident); 4970 #endif 4971 if (strzcmp16(s, len, rname.name, rname.nameLen) == 0) { 4972 outValue->dataType = bag->map.value.dataType; 4973 outValue->data = bag->map.value.data; 4974 unlockBag(bag); 4975 return true; 4976 } 4977 } 4978 4979 } 4980 bag++; 4981 cnt--; 4982 } 4983 unlockBag(bag); 4984 } 4985 4986 if (fromAccessor) { 4987 if (accessor->getAttributeEnum(attrID, s, len, outValue)) { 4988 return true; 4989 } 4990 } 4991 } 4992 4993 if ((attrType&ResTable_map::TYPE_FLAGS) != 0) { 4994 const ssize_t p = getResourcePackageIndex(attrID); 4995 const bag_entry* bag; 4996 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1; 4997 //printf("Got %d for flags\n", cnt); 4998 if (cnt >= 0) { 4999 bool failed = false; 5000 resource_name rname; 5001 outValue->dataType = Res_value::TYPE_INT_HEX; 5002 outValue->data = 0; 5003 const char16_t* end = s + len; 5004 const char16_t* pos = s; 5005 while (pos < end && !failed) { 5006 const char16_t* start = pos; 5007 pos++; 5008 while (pos < end && *pos != '|') { 5009 pos++; 5010 } 5011 //printf("Looking for: %s\n", String8(start, pos-start).string()); 5012 const bag_entry* bagi = bag; 5013 ssize_t i; 5014 for (i=0; i<cnt; i++, bagi++) { 5015 if (!Res_INTERNALID(bagi->map.name.ident)) { 5016 //printf("Trying attr #%08x\n", bagi->map.name.ident); 5017 if (getResourceName(bagi->map.name.ident, false, &rname)) { 5018 #if 0 5019 printf("Matching %s against %s (0x%08x)\n", 5020 String8(start,pos-start).string(), 5021 String8(rname.name, rname.nameLen).string(), 5022 bagi->map.name.ident); 5023 #endif 5024 if (strzcmp16(start, pos-start, rname.name, rname.nameLen) == 0) { 5025 outValue->data |= bagi->map.value.data; 5026 break; 5027 } 5028 } 5029 } 5030 } 5031 if (i >= cnt) { 5032 // Didn't find this flag identifier. 5033 failed = true; 5034 } 5035 if (pos < end) { 5036 pos++; 5037 } 5038 } 5039 unlockBag(bag); 5040 if (!failed) { 5041 //printf("Final flag value: 0x%lx\n", outValue->data); 5042 return true; 5043 } 5044 } 5045 5046 5047 if (fromAccessor) { 5048 if (accessor->getAttributeFlags(attrID, s, len, outValue)) { 5049 //printf("Final flag value: 0x%lx\n", outValue->data); 5050 return true; 5051 } 5052 } 5053 } 5054 5055 if ((attrType&ResTable_map::TYPE_STRING) == 0) { 5056 if (accessor != NULL) { 5057 accessor->reportError(accessorCookie, "String types not allowed"); 5058 } 5059 return false; 5060 } 5061 5062 // Generic string handling... 5063 outValue->dataType = outValue->TYPE_STRING; 5064 if (outString) { 5065 bool failed = collectString(outString, s, len, preserveSpaces, &errorMsg); 5066 if (accessor != NULL) { 5067 accessor->reportError(accessorCookie, errorMsg); 5068 } 5069 return failed; 5070 } 5071 5072 return true; 5073} 5074 5075bool ResTable::collectString(String16* outString, 5076 const char16_t* s, size_t len, 5077 bool preserveSpaces, 5078 const char** outErrorMsg, 5079 bool append) 5080{ 5081 String16 tmp; 5082 5083 char quoted = 0; 5084 const char16_t* p = s; 5085 while (p < (s+len)) { 5086 while (p < (s+len)) { 5087 const char16_t c = *p; 5088 if (c == '\\') { 5089 break; 5090 } 5091 if (!preserveSpaces) { 5092 if (quoted == 0 && isspace16(c) 5093 && (c != ' ' || isspace16(*(p+1)))) { 5094 break; 5095 } 5096 if (c == '"' && (quoted == 0 || quoted == '"')) { 5097 break; 5098 } 5099 if (c == '\'' && (quoted == 0 || quoted == '\'')) { 5100 /* 5101 * In practice, when people write ' instead of \' 5102 * in a string, they are doing it by accident 5103 * instead of really meaning to use ' as a quoting 5104 * character. Warn them so they don't lose it. 5105 */ 5106 if (outErrorMsg) { 5107 *outErrorMsg = "Apostrophe not preceded by \\"; 5108 } 5109 return false; 5110 } 5111 } 5112 p++; 5113 } 5114 if (p < (s+len)) { 5115 if (p > s) { 5116 tmp.append(String16(s, p-s)); 5117 } 5118 if (!preserveSpaces && (*p == '"' || *p == '\'')) { 5119 if (quoted == 0) { 5120 quoted = *p; 5121 } else { 5122 quoted = 0; 5123 } 5124 p++; 5125 } else if (!preserveSpaces && isspace16(*p)) { 5126 // Space outside of a quote -- consume all spaces and 5127 // leave a single plain space char. 5128 tmp.append(String16(" ")); 5129 p++; 5130 while (p < (s+len) && isspace16(*p)) { 5131 p++; 5132 } 5133 } else if (*p == '\\') { 5134 p++; 5135 if (p < (s+len)) { 5136 switch (*p) { 5137 case 't': 5138 tmp.append(String16("\t")); 5139 break; 5140 case 'n': 5141 tmp.append(String16("\n")); 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 '\\': 5159 tmp.append(String16("\\")); 5160 break; 5161 case 'u': 5162 { 5163 char16_t chr = 0; 5164 int i = 0; 5165 while (i < 4 && p[1] != 0) { 5166 p++; 5167 i++; 5168 int c; 5169 if (*p >= '0' && *p <= '9') { 5170 c = *p - '0'; 5171 } else if (*p >= 'a' && *p <= 'f') { 5172 c = *p - 'a' + 10; 5173 } else if (*p >= 'A' && *p <= 'F') { 5174 c = *p - 'A' + 10; 5175 } else { 5176 if (outErrorMsg) { 5177 *outErrorMsg = "Bad character in \\u unicode escape sequence"; 5178 } 5179 return false; 5180 } 5181 chr = (chr<<4) | c; 5182 } 5183 tmp.append(String16(&chr, 1)); 5184 } break; 5185 default: 5186 // ignore unknown escape chars. 5187 break; 5188 } 5189 p++; 5190 } 5191 } 5192 len -= (p-s); 5193 s = p; 5194 } 5195 } 5196 5197 if (tmp.size() != 0) { 5198 if (len > 0) { 5199 tmp.append(String16(s, len)); 5200 } 5201 if (append) { 5202 outString->append(tmp); 5203 } else { 5204 outString->setTo(tmp); 5205 } 5206 } else { 5207 if (append) { 5208 outString->append(String16(s, len)); 5209 } else { 5210 outString->setTo(s, len); 5211 } 5212 } 5213 5214 return true; 5215} 5216 5217size_t ResTable::getBasePackageCount() const 5218{ 5219 if (mError != NO_ERROR) { 5220 return 0; 5221 } 5222 return mPackageGroups.size(); 5223} 5224 5225const String16 ResTable::getBasePackageName(size_t idx) const 5226{ 5227 if (mError != NO_ERROR) { 5228 return String16(); 5229 } 5230 LOG_FATAL_IF(idx >= mPackageGroups.size(), 5231 "Requested package index %d past package count %d", 5232 (int)idx, (int)mPackageGroups.size()); 5233 return mPackageGroups[idx]->name; 5234} 5235 5236uint32_t ResTable::getBasePackageId(size_t idx) const 5237{ 5238 if (mError != NO_ERROR) { 5239 return 0; 5240 } 5241 LOG_FATAL_IF(idx >= mPackageGroups.size(), 5242 "Requested package index %d past package count %d", 5243 (int)idx, (int)mPackageGroups.size()); 5244 return mPackageGroups[idx]->id; 5245} 5246 5247uint32_t ResTable::getLastTypeIdForPackage(size_t idx) const 5248{ 5249 if (mError != NO_ERROR) { 5250 return 0; 5251 } 5252 LOG_FATAL_IF(idx >= mPackageGroups.size(), 5253 "Requested package index %d past package count %d", 5254 (int)idx, (int)mPackageGroups.size()); 5255 const PackageGroup* const group = mPackageGroups[idx]; 5256 return group->largestTypeId; 5257} 5258 5259size_t ResTable::getTableCount() const 5260{ 5261 return mHeaders.size(); 5262} 5263 5264const ResStringPool* ResTable::getTableStringBlock(size_t index) const 5265{ 5266 return &mHeaders[index]->values; 5267} 5268 5269int32_t ResTable::getTableCookie(size_t index) const 5270{ 5271 return mHeaders[index]->cookie; 5272} 5273 5274const DynamicRefTable* ResTable::getDynamicRefTableForCookie(int32_t cookie) const 5275{ 5276 const size_t N = mPackageGroups.size(); 5277 for (size_t i = 0; i < N; i++) { 5278 const PackageGroup* pg = mPackageGroups[i]; 5279 size_t M = pg->packages.size(); 5280 for (size_t j = 0; j < M; j++) { 5281 if (pg->packages[j]->header->cookie == cookie) { 5282 return &pg->dynamicRefTable; 5283 } 5284 } 5285 } 5286 return NULL; 5287} 5288 5289void ResTable::getConfigurations(Vector<ResTable_config>* configs) const 5290{ 5291 const size_t packageCount = mPackageGroups.size(); 5292 for (size_t i = 0; i < packageCount; i++) { 5293 const PackageGroup* packageGroup = mPackageGroups[i]; 5294 const size_t typeCount = packageGroup->types.size(); 5295 for (size_t j = 0; j < typeCount; j++) { 5296 const TypeList& typeList = packageGroup->types[j]; 5297 const size_t numTypes = typeList.size(); 5298 for (size_t k = 0; k < numTypes; k++) { 5299 const Type* type = typeList[k]; 5300 const size_t numConfigs = type->configs.size(); 5301 for (size_t m = 0; m < numConfigs; m++) { 5302 const ResTable_type* config = type->configs[m]; 5303 ResTable_config cfg; 5304 memset(&cfg, 0, sizeof(ResTable_config)); 5305 cfg.copyFromDtoH(config->config); 5306 // only insert unique 5307 const size_t N = configs->size(); 5308 size_t n; 5309 for (n = 0; n < N; n++) { 5310 if (0 == (*configs)[n].compare(cfg)) { 5311 break; 5312 } 5313 } 5314 // if we didn't find it 5315 if (n == N) { 5316 configs->add(cfg); 5317 } 5318 } 5319 } 5320 } 5321 } 5322} 5323 5324void ResTable::getLocales(Vector<String8>* locales) const 5325{ 5326 Vector<ResTable_config> configs; 5327 ALOGV("calling getConfigurations"); 5328 getConfigurations(&configs); 5329 ALOGV("called getConfigurations size=%d", (int)configs.size()); 5330 const size_t I = configs.size(); 5331 5332 char locale[RESTABLE_MAX_LOCALE_LEN]; 5333 for (size_t i=0; i<I; i++) { 5334 configs[i].getBcp47Locale(locale); 5335 const size_t J = locales->size(); 5336 size_t j; 5337 for (j=0; j<J; j++) { 5338 if (0 == strcmp(locale, (*locales)[j].string())) { 5339 break; 5340 } 5341 } 5342 if (j == J) { 5343 locales->add(String8(locale)); 5344 } 5345 } 5346} 5347 5348StringPoolRef::StringPoolRef(const ResStringPool* pool, uint32_t index) 5349 : mPool(pool), mIndex(index) {} 5350 5351StringPoolRef::StringPoolRef() 5352 : mPool(NULL), mIndex(0) {} 5353 5354const char* StringPoolRef::string8(size_t* outLen) const { 5355 if (mPool != NULL) { 5356 return mPool->string8At(mIndex, outLen); 5357 } 5358 if (outLen != NULL) { 5359 *outLen = 0; 5360 } 5361 return NULL; 5362} 5363 5364const char16_t* StringPoolRef::string16(size_t* outLen) const { 5365 if (mPool != NULL) { 5366 return mPool->stringAt(mIndex, outLen); 5367 } 5368 if (outLen != NULL) { 5369 *outLen = 0; 5370 } 5371 return NULL; 5372} 5373 5374status_t ResTable::getEntry( 5375 const PackageGroup* packageGroup, int typeIndex, int entryIndex, 5376 const ResTable_config* config, 5377 Entry* outEntry) const 5378{ 5379 const TypeList& typeList = packageGroup->types[typeIndex]; 5380 if (typeList.isEmpty()) { 5381 ALOGV("Skipping entry type index 0x%02x because type is NULL!\n", typeIndex); 5382 return BAD_TYPE; 5383 } 5384 5385 const ResTable_type* bestType = NULL; 5386 uint32_t bestOffset = ResTable_type::NO_ENTRY; 5387 const Package* bestPackage = NULL; 5388 uint32_t specFlags = 0; 5389 uint8_t actualTypeIndex = typeIndex; 5390 ResTable_config bestConfig; 5391 memset(&bestConfig, 0, sizeof(bestConfig)); 5392 5393 // Iterate over the Types of each package. 5394 const size_t typeCount = typeList.size(); 5395 for (size_t i = 0; i < typeCount; i++) { 5396 const Type* const typeSpec = typeList[i]; 5397 5398 int realEntryIndex = entryIndex; 5399 int realTypeIndex = typeIndex; 5400 bool currentTypeIsOverlay = false; 5401 5402 // Runtime overlay packages provide a mapping of app resource 5403 // ID to package resource ID. 5404 if (typeSpec->idmapEntries.hasEntries()) { 5405 uint16_t overlayEntryIndex; 5406 if (typeSpec->idmapEntries.lookup(entryIndex, &overlayEntryIndex) != NO_ERROR) { 5407 // No such mapping exists 5408 continue; 5409 } 5410 realEntryIndex = overlayEntryIndex; 5411 realTypeIndex = typeSpec->idmapEntries.overlayTypeId() - 1; 5412 currentTypeIsOverlay = true; 5413 } 5414 5415 if (static_cast<size_t>(realEntryIndex) >= typeSpec->entryCount) { 5416 ALOGW("For resource 0x%08x, entry index(%d) is beyond type entryCount(%d)", 5417 Res_MAKEID(packageGroup->id - 1, typeIndex, entryIndex), 5418 entryIndex, static_cast<int>(typeSpec->entryCount)); 5419 // We should normally abort here, but some legacy apps declare 5420 // resources in the 'android' package (old bug in AAPT). 5421 continue; 5422 } 5423 5424 // Aggregate all the flags for each package that defines this entry. 5425 if (typeSpec->typeSpecFlags != NULL) { 5426 specFlags |= dtohl(typeSpec->typeSpecFlags[realEntryIndex]); 5427 } else { 5428 specFlags = -1; 5429 } 5430 5431 const size_t numConfigs = typeSpec->configs.size(); 5432 for (size_t c = 0; c < numConfigs; c++) { 5433 const ResTable_type* const thisType = typeSpec->configs[c]; 5434 if (thisType == NULL) { 5435 continue; 5436 } 5437 5438 ResTable_config thisConfig; 5439 thisConfig.copyFromDtoH(thisType->config); 5440 5441 // Check to make sure this one is valid for the current parameters. 5442 if (config != NULL && !thisConfig.match(*config)) { 5443 continue; 5444 } 5445 5446 // Check if there is the desired entry in this type. 5447 const uint8_t* const end = reinterpret_cast<const uint8_t*>(thisType) 5448 + dtohl(thisType->header.size); 5449 const uint32_t* const eindex = reinterpret_cast<const uint32_t*>( 5450 reinterpret_cast<const uint8_t*>(thisType) + dtohs(thisType->header.headerSize)); 5451 5452 uint32_t thisOffset = dtohl(eindex[realEntryIndex]); 5453 if (thisOffset == ResTable_type::NO_ENTRY) { 5454 // There is no entry for this index and configuration. 5455 continue; 5456 } 5457 5458 if (bestType != NULL) { 5459 // Check if this one is less specific than the last found. If so, 5460 // we will skip it. We check starting with things we most care 5461 // about to those we least care about. 5462 if (!thisConfig.isBetterThan(bestConfig, config)) { 5463 if (!currentTypeIsOverlay || thisConfig.compare(bestConfig) != 0) { 5464 continue; 5465 } 5466 } 5467 } 5468 5469 bestType = thisType; 5470 bestOffset = thisOffset; 5471 bestConfig = thisConfig; 5472 bestPackage = typeSpec->package; 5473 actualTypeIndex = realTypeIndex; 5474 5475 // If no config was specified, any type will do, so skip 5476 if (config == NULL) { 5477 break; 5478 } 5479 } 5480 } 5481 5482 if (bestType == NULL) { 5483 return BAD_INDEX; 5484 } 5485 5486 bestOffset += dtohl(bestType->entriesStart); 5487 5488 if (bestOffset > (dtohl(bestType->header.size)-sizeof(ResTable_entry))) { 5489 ALOGW("ResTable_entry at 0x%x is beyond type chunk data 0x%x", 5490 bestOffset, dtohl(bestType->header.size)); 5491 return BAD_TYPE; 5492 } 5493 if ((bestOffset & 0x3) != 0) { 5494 ALOGW("ResTable_entry at 0x%x is not on an integer boundary", bestOffset); 5495 return BAD_TYPE; 5496 } 5497 5498 const ResTable_entry* const entry = reinterpret_cast<const ResTable_entry*>( 5499 reinterpret_cast<const uint8_t*>(bestType) + bestOffset); 5500 if (dtohs(entry->size) < sizeof(*entry)) { 5501 ALOGW("ResTable_entry size 0x%x is too small", dtohs(entry->size)); 5502 return BAD_TYPE; 5503 } 5504 5505 if (outEntry != NULL) { 5506 outEntry->entry = entry; 5507 outEntry->config = bestConfig; 5508 outEntry->type = bestType; 5509 outEntry->specFlags = specFlags; 5510 outEntry->package = bestPackage; 5511 outEntry->typeStr = StringPoolRef(&bestPackage->typeStrings, actualTypeIndex - bestPackage->typeIdOffset); 5512 outEntry->keyStr = StringPoolRef(&bestPackage->keyStrings, dtohl(entry->key.index)); 5513 } 5514 return NO_ERROR; 5515} 5516 5517status_t ResTable::parsePackage(const ResTable_package* const pkg, 5518 const Header* const header) 5519{ 5520 const uint8_t* base = (const uint8_t*)pkg; 5521 status_t err = validate_chunk(&pkg->header, sizeof(*pkg) - sizeof(pkg->typeIdOffset), 5522 header->dataEnd, "ResTable_package"); 5523 if (err != NO_ERROR) { 5524 return (mError=err); 5525 } 5526 5527 const uint32_t pkgSize = dtohl(pkg->header.size); 5528 5529 if (dtohl(pkg->typeStrings) >= pkgSize) { 5530 ALOGW("ResTable_package type strings at 0x%x are past chunk size 0x%x.", 5531 dtohl(pkg->typeStrings), pkgSize); 5532 return (mError=BAD_TYPE); 5533 } 5534 if ((dtohl(pkg->typeStrings)&0x3) != 0) { 5535 ALOGW("ResTable_package type strings at 0x%x is not on an integer boundary.", 5536 dtohl(pkg->typeStrings)); 5537 return (mError=BAD_TYPE); 5538 } 5539 if (dtohl(pkg->keyStrings) >= pkgSize) { 5540 ALOGW("ResTable_package key strings at 0x%x are past chunk size 0x%x.", 5541 dtohl(pkg->keyStrings), pkgSize); 5542 return (mError=BAD_TYPE); 5543 } 5544 if ((dtohl(pkg->keyStrings)&0x3) != 0) { 5545 ALOGW("ResTable_package key strings at 0x%x is not on an integer boundary.", 5546 dtohl(pkg->keyStrings)); 5547 return (mError=BAD_TYPE); 5548 } 5549 5550 uint32_t id = dtohl(pkg->id); 5551 KeyedVector<uint8_t, IdmapEntries> idmapEntries; 5552 5553 if (header->resourceIDMap != NULL) { 5554 uint8_t targetPackageId = 0; 5555 status_t err = parseIdmap(header->resourceIDMap, header->resourceIDMapSize, &targetPackageId, &idmapEntries); 5556 if (err != NO_ERROR) { 5557 ALOGW("Overlay is broken"); 5558 return (mError=err); 5559 } 5560 id = targetPackageId; 5561 } 5562 5563 if (id >= 256) { 5564 LOG_ALWAYS_FATAL("Package id out of range"); 5565 return NO_ERROR; 5566 } else if (id == 0) { 5567 // This is a library so assign an ID 5568 id = mNextPackageId++; 5569 } 5570 5571 PackageGroup* group = NULL; 5572 Package* package = new Package(this, header, pkg); 5573 if (package == NULL) { 5574 return (mError=NO_MEMORY); 5575 } 5576 5577 err = package->typeStrings.setTo(base+dtohl(pkg->typeStrings), 5578 header->dataEnd-(base+dtohl(pkg->typeStrings))); 5579 if (err != NO_ERROR) { 5580 delete group; 5581 delete package; 5582 return (mError=err); 5583 } 5584 5585 err = package->keyStrings.setTo(base+dtohl(pkg->keyStrings), 5586 header->dataEnd-(base+dtohl(pkg->keyStrings))); 5587 if (err != NO_ERROR) { 5588 delete group; 5589 delete package; 5590 return (mError=err); 5591 } 5592 5593 size_t idx = mPackageMap[id]; 5594 if (idx == 0) { 5595 idx = mPackageGroups.size() + 1; 5596 5597 char16_t tmpName[sizeof(pkg->name)/sizeof(char16_t)]; 5598 strcpy16_dtoh(tmpName, pkg->name, sizeof(pkg->name)/sizeof(char16_t)); 5599 group = new PackageGroup(this, String16(tmpName), id); 5600 if (group == NULL) { 5601 delete package; 5602 return (mError=NO_MEMORY); 5603 } 5604 5605 //printf("Adding new package id %d at index %d\n", id, idx); 5606 err = mPackageGroups.add(group); 5607 if (err < NO_ERROR) { 5608 return (mError=err); 5609 } 5610 5611 mPackageMap[id] = static_cast<uint8_t>(idx); 5612 5613 // Find all packages that reference this package 5614 size_t N = mPackageGroups.size(); 5615 for (size_t i = 0; i < N; i++) { 5616 mPackageGroups[i]->dynamicRefTable.addMapping( 5617 group->name, static_cast<uint8_t>(group->id)); 5618 } 5619 } else { 5620 group = mPackageGroups.itemAt(idx - 1); 5621 if (group == NULL) { 5622 return (mError=UNKNOWN_ERROR); 5623 } 5624 } 5625 5626 err = group->packages.add(package); 5627 if (err < NO_ERROR) { 5628 return (mError=err); 5629 } 5630 5631 // Iterate through all chunks. 5632 const ResChunk_header* chunk = 5633 (const ResChunk_header*)(((const uint8_t*)pkg) 5634 + dtohs(pkg->header.headerSize)); 5635 const uint8_t* endPos = ((const uint8_t*)pkg) + dtohs(pkg->header.size); 5636 while (((const uint8_t*)chunk) <= (endPos-sizeof(ResChunk_header)) && 5637 ((const uint8_t*)chunk) <= (endPos-dtohl(chunk->size))) { 5638 TABLE_NOISY(ALOGV("PackageChunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n", 5639 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size), 5640 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)))); 5641 const size_t csize = dtohl(chunk->size); 5642 const uint16_t ctype = dtohs(chunk->type); 5643 if (ctype == RES_TABLE_TYPE_SPEC_TYPE) { 5644 const ResTable_typeSpec* typeSpec = (const ResTable_typeSpec*)(chunk); 5645 err = validate_chunk(&typeSpec->header, sizeof(*typeSpec), 5646 endPos, "ResTable_typeSpec"); 5647 if (err != NO_ERROR) { 5648 return (mError=err); 5649 } 5650 5651 const size_t typeSpecSize = dtohl(typeSpec->header.size); 5652 const size_t newEntryCount = dtohl(typeSpec->entryCount); 5653 5654 LOAD_TABLE_NOISY(printf("TypeSpec off %p: type=0x%x, headerSize=0x%x, size=%p\n", 5655 (void*)(base-(const uint8_t*)chunk), 5656 dtohs(typeSpec->header.type), 5657 dtohs(typeSpec->header.headerSize), 5658 (void*)typeSpecSize)); 5659 // look for block overrun or int overflow when multiplying by 4 5660 if ((dtohl(typeSpec->entryCount) > (INT32_MAX/sizeof(uint32_t)) 5661 || dtohs(typeSpec->header.headerSize)+(sizeof(uint32_t)*newEntryCount) 5662 > typeSpecSize)) { 5663 ALOGW("ResTable_typeSpec entry index to %p extends beyond chunk end %p.", 5664 (void*)(dtohs(typeSpec->header.headerSize) + (sizeof(uint32_t)*newEntryCount)), 5665 (void*)typeSpecSize); 5666 return (mError=BAD_TYPE); 5667 } 5668 5669 if (typeSpec->id == 0) { 5670 ALOGW("ResTable_type has an id of 0."); 5671 return (mError=BAD_TYPE); 5672 } 5673 5674 if (newEntryCount > 0) { 5675 uint8_t typeIndex = typeSpec->id - 1; 5676 ssize_t idmapIndex = idmapEntries.indexOfKey(typeSpec->id); 5677 if (idmapIndex >= 0) { 5678 typeIndex = idmapEntries[idmapIndex].targetTypeId() - 1; 5679 } 5680 5681 TypeList& typeList = group->types.editItemAt(typeIndex); 5682 if (!typeList.isEmpty()) { 5683 const Type* existingType = typeList[0]; 5684 if (existingType->entryCount != newEntryCount && idmapIndex < 0) { 5685 ALOGW("ResTable_typeSpec entry count inconsistent: given %d, previously %d", 5686 (int) newEntryCount, (int) existingType->entryCount); 5687 // We should normally abort here, but some legacy apps declare 5688 // resources in the 'android' package (old bug in AAPT). 5689 } 5690 } 5691 5692 Type* t = new Type(header, package, newEntryCount); 5693 t->typeSpec = typeSpec; 5694 t->typeSpecFlags = (const uint32_t*)( 5695 ((const uint8_t*)typeSpec) + dtohs(typeSpec->header.headerSize)); 5696 if (idmapIndex >= 0) { 5697 t->idmapEntries = idmapEntries[idmapIndex]; 5698 } 5699 typeList.add(t); 5700 group->largestTypeId = max(group->largestTypeId, typeSpec->id); 5701 } else { 5702 ALOGV("Skipping empty ResTable_typeSpec for type %d", typeSpec->id); 5703 } 5704 5705 } else if (ctype == RES_TABLE_TYPE_TYPE) { 5706 const ResTable_type* type = (const ResTable_type*)(chunk); 5707 err = validate_chunk(&type->header, sizeof(*type)-sizeof(ResTable_config)+4, 5708 endPos, "ResTable_type"); 5709 if (err != NO_ERROR) { 5710 return (mError=err); 5711 } 5712 5713 const uint32_t typeSize = dtohl(type->header.size); 5714 const size_t newEntryCount = dtohl(type->entryCount); 5715 5716 LOAD_TABLE_NOISY(printf("Type off %p: type=0x%x, headerSize=0x%x, size=%p\n", 5717 (void*)(base-(const uint8_t*)chunk), 5718 dtohs(type->header.type), 5719 dtohs(type->header.headerSize), 5720 (void*)typeSize)); 5721 if (dtohs(type->header.headerSize)+(sizeof(uint32_t)*newEntryCount) 5722 > typeSize) { 5723 ALOGW("ResTable_type entry index to %p extends beyond chunk end 0x%x.", 5724 (void*)(dtohs(type->header.headerSize) + (sizeof(uint32_t)*newEntryCount)), 5725 typeSize); 5726 return (mError=BAD_TYPE); 5727 } 5728 5729 if (newEntryCount != 0 5730 && dtohl(type->entriesStart) > (typeSize-sizeof(ResTable_entry))) { 5731 ALOGW("ResTable_type entriesStart at 0x%x extends beyond chunk end 0x%x.", 5732 dtohl(type->entriesStart), typeSize); 5733 return (mError=BAD_TYPE); 5734 } 5735 5736 if (type->id == 0) { 5737 ALOGW("ResTable_type has an id of 0."); 5738 return (mError=BAD_TYPE); 5739 } 5740 5741 if (newEntryCount > 0) { 5742 uint8_t typeIndex = type->id - 1; 5743 ssize_t idmapIndex = idmapEntries.indexOfKey(type->id); 5744 if (idmapIndex >= 0) { 5745 typeIndex = idmapEntries[idmapIndex].targetTypeId() - 1; 5746 } 5747 5748 TypeList& typeList = group->types.editItemAt(typeIndex); 5749 if (typeList.isEmpty()) { 5750 ALOGE("No TypeSpec for type %d", type->id); 5751 return (mError=BAD_TYPE); 5752 } 5753 5754 Type* t = typeList.editItemAt(typeList.size() - 1); 5755 if (newEntryCount != t->entryCount) { 5756 ALOGE("ResTable_type entry count inconsistent: given %d, previously %d", 5757 (int)newEntryCount, (int)t->entryCount); 5758 return (mError=BAD_TYPE); 5759 } 5760 5761 if (t->package != package) { 5762 ALOGE("No TypeSpec for type %d", type->id); 5763 return (mError=BAD_TYPE); 5764 } 5765 5766 t->configs.add(type); 5767 5768 TABLE_GETENTRY( 5769 ResTable_config thisConfig; 5770 thisConfig.copyFromDtoH(type->config); 5771 ALOGI("Adding config to type %d: %s\n", 5772 type->id, thisConfig.toString().string())); 5773 } else { 5774 ALOGV("Skipping empty ResTable_type for type %d", type->id); 5775 } 5776 5777 } else if (ctype == RES_TABLE_LIBRARY_TYPE) { 5778 if (group->dynamicRefTable.entries().size() == 0) { 5779 status_t err = group->dynamicRefTable.load((const ResTable_lib_header*) chunk); 5780 if (err != NO_ERROR) { 5781 return (mError=err); 5782 } 5783 5784 // Fill in the reference table with the entries we already know about. 5785 size_t N = mPackageGroups.size(); 5786 for (size_t i = 0; i < N; i++) { 5787 group->dynamicRefTable.addMapping(mPackageGroups[i]->name, mPackageGroups[i]->id); 5788 } 5789 } else { 5790 ALOGW("Found multiple library tables, ignoring..."); 5791 } 5792 } else { 5793 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), 5794 endPos, "ResTable_package:unknown"); 5795 if (err != NO_ERROR) { 5796 return (mError=err); 5797 } 5798 } 5799 chunk = (const ResChunk_header*) 5800 (((const uint8_t*)chunk) + csize); 5801 } 5802 5803 return NO_ERROR; 5804} 5805 5806DynamicRefTable::DynamicRefTable(uint8_t packageId) 5807 : mAssignedPackageId(packageId) 5808{ 5809 memset(mLookupTable, 0, sizeof(mLookupTable)); 5810 5811 // Reserved package ids 5812 mLookupTable[APP_PACKAGE_ID] = APP_PACKAGE_ID; 5813 mLookupTable[SYS_PACKAGE_ID] = SYS_PACKAGE_ID; 5814} 5815 5816status_t DynamicRefTable::load(const ResTable_lib_header* const header) 5817{ 5818 const uint32_t entryCount = dtohl(header->count); 5819 const uint32_t sizeOfEntries = sizeof(ResTable_lib_entry) * entryCount; 5820 const uint32_t expectedSize = dtohl(header->header.size) - dtohl(header->header.headerSize); 5821 if (sizeOfEntries > expectedSize) { 5822 ALOGE("ResTable_lib_header size %u is too small to fit %u entries (x %u).", 5823 expectedSize, entryCount, (uint32_t)sizeof(ResTable_lib_entry)); 5824 return UNKNOWN_ERROR; 5825 } 5826 5827 const ResTable_lib_entry* entry = (const ResTable_lib_entry*)(((uint8_t*) header) + 5828 dtohl(header->header.headerSize)); 5829 for (uint32_t entryIndex = 0; entryIndex < entryCount; entryIndex++) { 5830 uint32_t packageId = dtohl(entry->packageId); 5831 char16_t tmpName[sizeof(entry->packageName) / sizeof(char16_t)]; 5832 strcpy16_dtoh(tmpName, entry->packageName, sizeof(entry->packageName) / sizeof(char16_t)); 5833 LIB_NOISY(ALOGV("Found lib entry %s with id %d\n", String8(tmpName).string(), 5834 dtohl(entry->packageId))); 5835 if (packageId >= 256) { 5836 ALOGE("Bad package id 0x%08x", packageId); 5837 return UNKNOWN_ERROR; 5838 } 5839 mEntries.replaceValueFor(String16(tmpName), (uint8_t) packageId); 5840 entry = entry + 1; 5841 } 5842 return NO_ERROR; 5843} 5844 5845status_t DynamicRefTable::addMapping(const String16& packageName, uint8_t packageId) 5846{ 5847 ssize_t index = mEntries.indexOfKey(packageName); 5848 if (index < 0) { 5849 return UNKNOWN_ERROR; 5850 } 5851 mLookupTable[mEntries.valueAt(index)] = packageId; 5852 return NO_ERROR; 5853} 5854 5855status_t DynamicRefTable::lookupResourceId(uint32_t* resId) const { 5856 uint32_t res = *resId; 5857 size_t packageId = Res_GETPACKAGE(res) + 1; 5858 5859 if (packageId == APP_PACKAGE_ID) { 5860 // No lookup needs to be done, app package IDs are absolute. 5861 return NO_ERROR; 5862 } 5863 5864 if (packageId == 0) { 5865 // The package ID is 0x00. That means that a shared library is accessing 5866 // its own local resource, so we fix up the resource with the calling 5867 // package ID. 5868 *resId |= ((uint32_t) mAssignedPackageId) << 24; 5869 return NO_ERROR; 5870 } 5871 5872 // Do a proper lookup. 5873 uint8_t translatedId = mLookupTable[packageId]; 5874 if (translatedId == 0) { 5875 ALOGE("DynamicRefTable(0x%02x): No mapping for build-time package ID 0x%02x.", 5876 (uint8_t)mAssignedPackageId, (uint8_t)packageId); 5877 for (size_t i = 0; i < 256; i++) { 5878 if (mLookupTable[i] != 0) { 5879 ALOGE("e[0x%02x] -> 0x%02x", (uint8_t)i, mLookupTable[i]); 5880 } 5881 } 5882 return UNKNOWN_ERROR; 5883 } 5884 5885 *resId = (res & 0x00ffffff) | (((uint32_t) translatedId) << 24); 5886 return NO_ERROR; 5887} 5888 5889status_t DynamicRefTable::lookupResourceValue(Res_value* value) const { 5890 if (value->dataType != Res_value::TYPE_DYNAMIC_REFERENCE) { 5891 return NO_ERROR; 5892 } 5893 5894 status_t err = lookupResourceId(&value->data); 5895 if (err != NO_ERROR) { 5896 return err; 5897 } 5898 5899 value->dataType = Res_value::TYPE_REFERENCE; 5900 return NO_ERROR; 5901} 5902 5903struct IdmapTypeMap { 5904 ssize_t overlayTypeId; 5905 size_t entryOffset; 5906 Vector<uint32_t> entryMap; 5907}; 5908 5909status_t ResTable::createIdmap(const ResTable& overlay, 5910 uint32_t targetCrc, uint32_t overlayCrc, 5911 const char* targetPath, const char* overlayPath, 5912 void** outData, size_t* outSize) const 5913{ 5914 // see README for details on the format of map 5915 if (mPackageGroups.size() == 0) { 5916 ALOGW("idmap: target package has no package groups, cannot create idmap\n"); 5917 return UNKNOWN_ERROR; 5918 } 5919 5920 if (mPackageGroups[0]->packages.size() == 0) { 5921 ALOGW("idmap: target package has no packages in its first package group, " 5922 "cannot create idmap\n"); 5923 return UNKNOWN_ERROR; 5924 } 5925 5926 KeyedVector<uint8_t, IdmapTypeMap> map; 5927 5928 // overlaid packages are assumed to contain only one package group 5929 const PackageGroup* pg = mPackageGroups[0]; 5930 5931 // starting size is header 5932 *outSize = ResTable::IDMAP_HEADER_SIZE_BYTES; 5933 5934 // target package id and number of types in map 5935 *outSize += 2 * sizeof(uint16_t); 5936 5937 // overlay packages are assumed to contain only one package group 5938 const String16 overlayPackage(overlay.mPackageGroups[0]->name); 5939 5940 for (size_t typeIndex = 0; typeIndex < pg->types.size(); ++typeIndex) { 5941 const TypeList& typeList = pg->types[typeIndex]; 5942 if (typeList.isEmpty()) { 5943 continue; 5944 } 5945 5946 const Type* typeConfigs = typeList[0]; 5947 5948 IdmapTypeMap typeMap; 5949 typeMap.overlayTypeId = -1; 5950 typeMap.entryOffset = 0; 5951 5952 for (size_t entryIndex = 0; entryIndex < typeConfigs->entryCount; ++entryIndex) { 5953 uint32_t resID = Res_MAKEID(pg->id - 1, typeIndex, entryIndex); 5954 resource_name resName; 5955 if (!this->getResourceName(resID, false, &resName)) { 5956 if (typeMap.entryMap.isEmpty()) { 5957 typeMap.entryOffset++; 5958 } 5959 continue; 5960 } 5961 5962 const String16 overlayType(resName.type, resName.typeLen); 5963 const String16 overlayName(resName.name, resName.nameLen); 5964 uint32_t overlayResID = overlay.identifierForName(overlayName.string(), 5965 overlayName.size(), 5966 overlayType.string(), 5967 overlayType.size(), 5968 overlayPackage.string(), 5969 overlayPackage.size()); 5970 if (overlayResID == 0) { 5971 if (typeMap.entryMap.isEmpty()) { 5972 typeMap.entryOffset++; 5973 } 5974 continue; 5975 } 5976 5977 if (typeMap.overlayTypeId == -1) { 5978 typeMap.overlayTypeId = Res_GETTYPE(overlayResID) + 1; 5979 } 5980 5981 if (Res_GETTYPE(overlayResID) + 1 != static_cast<size_t>(typeMap.overlayTypeId)) { 5982 ALOGE("idmap: can't mix type ids in entry map. Resource 0x%08x maps to 0x%08x" 5983 " but entries should map to resources of type %02x", 5984 resID, overlayResID, typeMap.overlayTypeId); 5985 return BAD_TYPE; 5986 } 5987 5988 if (typeMap.entryOffset + typeMap.entryMap.size() < entryIndex) { 5989 // Resize to accomodate this entry and the 0's in between. 5990 if (typeMap.entryMap.resize((entryIndex - typeMap.entryOffset) + 1) < 0) { 5991 return NO_MEMORY; 5992 } 5993 typeMap.entryMap.editTop() = Res_GETENTRY(overlayResID); 5994 } else { 5995 typeMap.entryMap.add(Res_GETENTRY(overlayResID)); 5996 } 5997 } 5998 5999 if (!typeMap.entryMap.isEmpty()) { 6000 if (map.add(static_cast<uint8_t>(typeIndex), typeMap) < 0) { 6001 return NO_MEMORY; 6002 } 6003 *outSize += (4 * sizeof(uint16_t)) + (typeMap.entryMap.size() * sizeof(uint32_t)); 6004 } 6005 } 6006 6007 if (map.isEmpty()) { 6008 ALOGW("idmap: no resources in overlay package present in base package"); 6009 return UNKNOWN_ERROR; 6010 } 6011 6012 if ((*outData = malloc(*outSize)) == NULL) { 6013 return NO_MEMORY; 6014 } 6015 6016 uint32_t* data = (uint32_t*)*outData; 6017 *data++ = htodl(IDMAP_MAGIC); 6018 *data++ = htodl(IDMAP_CURRENT_VERSION); 6019 *data++ = htodl(targetCrc); 6020 *data++ = htodl(overlayCrc); 6021 const char* paths[] = { targetPath, overlayPath }; 6022 for (int j = 0; j < 2; ++j) { 6023 char* p = (char*)data; 6024 const char* path = paths[j]; 6025 const size_t I = strlen(path); 6026 if (I > 255) { 6027 ALOGV("path exceeds expected 255 characters: %s\n", path); 6028 return UNKNOWN_ERROR; 6029 } 6030 for (size_t i = 0; i < 256; ++i) { 6031 *p++ = i < I ? path[i] : '\0'; 6032 } 6033 data += 256 / sizeof(uint32_t); 6034 } 6035 const size_t mapSize = map.size(); 6036 uint16_t* typeData = reinterpret_cast<uint16_t*>(data); 6037 *typeData++ = htods(pg->id); 6038 *typeData++ = htods(mapSize); 6039 for (size_t i = 0; i < mapSize; ++i) { 6040 uint8_t targetTypeId = map.keyAt(i); 6041 const IdmapTypeMap& typeMap = map[i]; 6042 *typeData++ = htods(targetTypeId + 1); 6043 *typeData++ = htods(typeMap.overlayTypeId); 6044 *typeData++ = htods(typeMap.entryMap.size()); 6045 *typeData++ = htods(typeMap.entryOffset); 6046 6047 const size_t entryCount = typeMap.entryMap.size(); 6048 uint32_t* entries = reinterpret_cast<uint32_t*>(typeData); 6049 for (size_t j = 0; j < entryCount; j++) { 6050 entries[j] = htodl(typeMap.entryMap[j]); 6051 } 6052 typeData += entryCount * 2; 6053 } 6054 6055 return NO_ERROR; 6056} 6057 6058bool ResTable::getIdmapInfo(const void* idmap, size_t sizeBytes, 6059 uint32_t* pVersion, 6060 uint32_t* pTargetCrc, uint32_t* pOverlayCrc, 6061 String8* pTargetPath, String8* pOverlayPath) 6062{ 6063 const uint32_t* map = (const uint32_t*)idmap; 6064 if (!assertIdmapHeader(map, sizeBytes)) { 6065 return false; 6066 } 6067 if (pVersion) { 6068 *pVersion = dtohl(map[1]); 6069 } 6070 if (pTargetCrc) { 6071 *pTargetCrc = dtohl(map[2]); 6072 } 6073 if (pOverlayCrc) { 6074 *pOverlayCrc = dtohl(map[3]); 6075 } 6076 if (pTargetPath) { 6077 pTargetPath->setTo(reinterpret_cast<const char*>(map + 4)); 6078 } 6079 if (pOverlayPath) { 6080 pOverlayPath->setTo(reinterpret_cast<const char*>(map + 4 + 256 / sizeof(uint32_t))); 6081 } 6082 return true; 6083} 6084 6085 6086#define CHAR16_TO_CSTR(c16, len) (String8(String16(c16,len)).string()) 6087 6088#define CHAR16_ARRAY_EQ(constant, var, len) \ 6089 ((len == (sizeof(constant)/sizeof(constant[0]))) && (0 == memcmp((var), (constant), (len)))) 6090 6091static void print_complex(uint32_t complex, bool isFraction) 6092{ 6093 const float MANTISSA_MULT = 6094 1.0f / (1<<Res_value::COMPLEX_MANTISSA_SHIFT); 6095 const float RADIX_MULTS[] = { 6096 1.0f*MANTISSA_MULT, 1.0f/(1<<7)*MANTISSA_MULT, 6097 1.0f/(1<<15)*MANTISSA_MULT, 1.0f/(1<<23)*MANTISSA_MULT 6098 }; 6099 6100 float value = (complex&(Res_value::COMPLEX_MANTISSA_MASK 6101 <<Res_value::COMPLEX_MANTISSA_SHIFT)) 6102 * RADIX_MULTS[(complex>>Res_value::COMPLEX_RADIX_SHIFT) 6103 & Res_value::COMPLEX_RADIX_MASK]; 6104 printf("%f", value); 6105 6106 if (!isFraction) { 6107 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) { 6108 case Res_value::COMPLEX_UNIT_PX: printf("px"); break; 6109 case Res_value::COMPLEX_UNIT_DIP: printf("dp"); break; 6110 case Res_value::COMPLEX_UNIT_SP: printf("sp"); break; 6111 case Res_value::COMPLEX_UNIT_PT: printf("pt"); break; 6112 case Res_value::COMPLEX_UNIT_IN: printf("in"); break; 6113 case Res_value::COMPLEX_UNIT_MM: printf("mm"); break; 6114 default: printf(" (unknown unit)"); break; 6115 } 6116 } else { 6117 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) { 6118 case Res_value::COMPLEX_UNIT_FRACTION: printf("%%"); break; 6119 case Res_value::COMPLEX_UNIT_FRACTION_PARENT: printf("%%p"); break; 6120 default: printf(" (unknown unit)"); break; 6121 } 6122 } 6123} 6124 6125// Normalize a string for output 6126String8 ResTable::normalizeForOutput( const char *input ) 6127{ 6128 String8 ret; 6129 char buff[2]; 6130 buff[1] = '\0'; 6131 6132 while (*input != '\0') { 6133 switch (*input) { 6134 // All interesting characters are in the ASCII zone, so we are making our own lives 6135 // easier by scanning the string one byte at a time. 6136 case '\\': 6137 ret += "\\\\"; 6138 break; 6139 case '\n': 6140 ret += "\\n"; 6141 break; 6142 case '"': 6143 ret += "\\\""; 6144 break; 6145 default: 6146 buff[0] = *input; 6147 ret += buff; 6148 break; 6149 } 6150 6151 input++; 6152 } 6153 6154 return ret; 6155} 6156 6157void ResTable::print_value(const Package* pkg, const Res_value& value) const 6158{ 6159 if (value.dataType == Res_value::TYPE_NULL) { 6160 printf("(null)\n"); 6161 } else if (value.dataType == Res_value::TYPE_REFERENCE) { 6162 printf("(reference) 0x%08x\n", value.data); 6163 } else if (value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE) { 6164 printf("(dynamic reference) 0x%08x\n", value.data); 6165 } else if (value.dataType == Res_value::TYPE_ATTRIBUTE) { 6166 printf("(attribute) 0x%08x\n", value.data); 6167 } else if (value.dataType == Res_value::TYPE_STRING) { 6168 size_t len; 6169 const char* str8 = pkg->header->values.string8At( 6170 value.data, &len); 6171 if (str8 != NULL) { 6172 printf("(string8) \"%s\"\n", normalizeForOutput(str8).string()); 6173 } else { 6174 const char16_t* str16 = pkg->header->values.stringAt( 6175 value.data, &len); 6176 if (str16 != NULL) { 6177 printf("(string16) \"%s\"\n", 6178 normalizeForOutput(String8(str16, len).string()).string()); 6179 } else { 6180 printf("(string) null\n"); 6181 } 6182 } 6183 } else if (value.dataType == Res_value::TYPE_FLOAT) { 6184 printf("(float) %g\n", *(const float*)&value.data); 6185 } else if (value.dataType == Res_value::TYPE_DIMENSION) { 6186 printf("(dimension) "); 6187 print_complex(value.data, false); 6188 printf("\n"); 6189 } else if (value.dataType == Res_value::TYPE_FRACTION) { 6190 printf("(fraction) "); 6191 print_complex(value.data, true); 6192 printf("\n"); 6193 } else if (value.dataType >= Res_value::TYPE_FIRST_COLOR_INT 6194 || value.dataType <= Res_value::TYPE_LAST_COLOR_INT) { 6195 printf("(color) #%08x\n", value.data); 6196 } else if (value.dataType == Res_value::TYPE_INT_BOOLEAN) { 6197 printf("(boolean) %s\n", value.data ? "true" : "false"); 6198 } else if (value.dataType >= Res_value::TYPE_FIRST_INT 6199 || value.dataType <= Res_value::TYPE_LAST_INT) { 6200 printf("(int) 0x%08x or %d\n", value.data, value.data); 6201 } else { 6202 printf("(unknown type) t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)\n", 6203 (int)value.dataType, (int)value.data, 6204 (int)value.size, (int)value.res0); 6205 } 6206} 6207 6208void ResTable::print(bool inclValues) const 6209{ 6210 if (mError != 0) { 6211 printf("mError=0x%x (%s)\n", mError, strerror(mError)); 6212 } 6213 size_t pgCount = mPackageGroups.size(); 6214 printf("Package Groups (%d)\n", (int)pgCount); 6215 for (size_t pgIndex=0; pgIndex<pgCount; pgIndex++) { 6216 const PackageGroup* pg = mPackageGroups[pgIndex]; 6217 printf("Package Group %d id=%d packageCount=%d name=%s\n", 6218 (int)pgIndex, pg->id, (int)pg->packages.size(), 6219 String8(pg->name).string()); 6220 6221 for (size_t typeIndex=0; typeIndex < pg->types.size(); typeIndex++) { 6222 const TypeList& typeList = pg->types[typeIndex]; 6223 if (typeList.isEmpty()) { 6224 //printf(" type %d NULL\n", (int)typeIndex); 6225 continue; 6226 } 6227 const Type* typeConfigs = typeList[0]; 6228 const size_t NTC = typeConfigs->configs.size(); 6229 printf(" type %d configCount=%d entryCount=%d\n", 6230 (int)typeIndex, (int)NTC, (int)typeConfigs->entryCount); 6231 if (typeConfigs->typeSpecFlags != NULL) { 6232 for (size_t entryIndex=0; entryIndex<typeConfigs->entryCount; entryIndex++) { 6233 uint32_t resID = (0xff000000 & ((pg->id)<<24)) 6234 | (0x00ff0000 & ((typeIndex+1)<<16)) 6235 | (0x0000ffff & (entryIndex)); 6236 // Since we are creating resID without actually 6237 // iterating over them, we have no idea which is a 6238 // dynamic reference. We must check. 6239 pg->dynamicRefTable.lookupResourceId(&resID); 6240 6241 resource_name resName; 6242 if (this->getResourceName(resID, true, &resName)) { 6243 String8 type8; 6244 String8 name8; 6245 if (resName.type8 != NULL) { 6246 type8 = String8(resName.type8, resName.typeLen); 6247 } else { 6248 type8 = String8(resName.type, resName.typeLen); 6249 } 6250 if (resName.name8 != NULL) { 6251 name8 = String8(resName.name8, resName.nameLen); 6252 } else { 6253 name8 = String8(resName.name, resName.nameLen); 6254 } 6255 printf(" spec resource 0x%08x %s:%s/%s: flags=0x%08x\n", 6256 resID, 6257 CHAR16_TO_CSTR(resName.package, resName.packageLen), 6258 type8.string(), name8.string(), 6259 dtohl(typeConfigs->typeSpecFlags[entryIndex])); 6260 } else { 6261 printf(" INVALID TYPE CONFIG FOR RESOURCE 0x%08x\n", resID); 6262 } 6263 } 6264 } 6265 for (size_t configIndex=0; configIndex<NTC; configIndex++) { 6266 const ResTable_type* type = typeConfigs->configs[configIndex]; 6267 if ((((uint64_t)type)&0x3) != 0) { 6268 printf(" NON-INTEGER ResTable_type ADDRESS: %p\n", type); 6269 continue; 6270 } 6271 String8 configStr = type->config.toString(); 6272 printf(" config %s:\n", configStr.size() > 0 6273 ? configStr.string() : "(default)"); 6274 size_t entryCount = dtohl(type->entryCount); 6275 uint32_t entriesStart = dtohl(type->entriesStart); 6276 if ((entriesStart&0x3) != 0) { 6277 printf(" NON-INTEGER ResTable_type entriesStart OFFSET: 0x%x\n", entriesStart); 6278 continue; 6279 } 6280 uint32_t typeSize = dtohl(type->header.size); 6281 if ((typeSize&0x3) != 0) { 6282 printf(" NON-INTEGER ResTable_type header.size: 0x%x\n", typeSize); 6283 continue; 6284 } 6285 for (size_t entryIndex=0; entryIndex<entryCount; entryIndex++) { 6286 6287 const uint8_t* const end = ((const uint8_t*)type) 6288 + dtohl(type->header.size); 6289 const uint32_t* const eindex = (const uint32_t*) 6290 (((const uint8_t*)type) + dtohs(type->header.headerSize)); 6291 6292 uint32_t thisOffset = dtohl(eindex[entryIndex]); 6293 if (thisOffset == ResTable_type::NO_ENTRY) { 6294 continue; 6295 } 6296 6297 uint32_t resID = (0xff000000 & ((pg->id)<<24)) 6298 | (0x00ff0000 & ((typeIndex+1)<<16)) 6299 | (0x0000ffff & (entryIndex)); 6300 pg->dynamicRefTable.lookupResourceId(&resID); 6301 resource_name resName; 6302 if (this->getResourceName(resID, true, &resName)) { 6303 String8 type8; 6304 String8 name8; 6305 if (resName.type8 != NULL) { 6306 type8 = String8(resName.type8, resName.typeLen); 6307 } else { 6308 type8 = String8(resName.type, resName.typeLen); 6309 } 6310 if (resName.name8 != NULL) { 6311 name8 = String8(resName.name8, resName.nameLen); 6312 } else { 6313 name8 = String8(resName.name, resName.nameLen); 6314 } 6315 printf(" resource 0x%08x %s:%s/%s: ", resID, 6316 CHAR16_TO_CSTR(resName.package, resName.packageLen), 6317 type8.string(), name8.string()); 6318 } else { 6319 printf(" INVALID RESOURCE 0x%08x: ", resID); 6320 } 6321 if ((thisOffset&0x3) != 0) { 6322 printf("NON-INTEGER OFFSET: 0x%x\n", thisOffset); 6323 continue; 6324 } 6325 if ((thisOffset+sizeof(ResTable_entry)) > typeSize) { 6326 printf("OFFSET OUT OF BOUNDS: 0x%x+0x%x (size is 0x%x)\n", 6327 entriesStart, thisOffset, typeSize); 6328 continue; 6329 } 6330 6331 const ResTable_entry* ent = (const ResTable_entry*) 6332 (((const uint8_t*)type) + entriesStart + thisOffset); 6333 if (((entriesStart + thisOffset)&0x3) != 0) { 6334 printf("NON-INTEGER ResTable_entry OFFSET: 0x%x\n", 6335 (entriesStart + thisOffset)); 6336 continue; 6337 } 6338 6339 uintptr_t esize = dtohs(ent->size); 6340 if ((esize&0x3) != 0) { 6341 printf("NON-INTEGER ResTable_entry SIZE: %p\n", (void *)esize); 6342 continue; 6343 } 6344 if ((thisOffset+esize) > typeSize) { 6345 printf("ResTable_entry OUT OF BOUNDS: 0x%x+0x%x+%p (size is 0x%x)\n", 6346 entriesStart, thisOffset, (void *)esize, typeSize); 6347 continue; 6348 } 6349 6350 const Res_value* valuePtr = NULL; 6351 const ResTable_map_entry* bagPtr = NULL; 6352 Res_value value; 6353 if ((dtohs(ent->flags)&ResTable_entry::FLAG_COMPLEX) != 0) { 6354 printf("<bag>"); 6355 bagPtr = (const ResTable_map_entry*)ent; 6356 } else { 6357 valuePtr = (const Res_value*) 6358 (((const uint8_t*)ent) + esize); 6359 value.copyFrom_dtoh(*valuePtr); 6360 printf("t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)", 6361 (int)value.dataType, (int)value.data, 6362 (int)value.size, (int)value.res0); 6363 } 6364 6365 if ((dtohs(ent->flags)&ResTable_entry::FLAG_PUBLIC) != 0) { 6366 printf(" (PUBLIC)"); 6367 } 6368 printf("\n"); 6369 6370 if (inclValues) { 6371 if (valuePtr != NULL) { 6372 printf(" "); 6373 print_value(typeConfigs->package, value); 6374 } else if (bagPtr != NULL) { 6375 const int N = dtohl(bagPtr->count); 6376 const uint8_t* baseMapPtr = (const uint8_t*)ent; 6377 size_t mapOffset = esize; 6378 const ResTable_map* mapPtr = (ResTable_map*)(baseMapPtr+mapOffset); 6379 const uint32_t parent = dtohl(bagPtr->parent.ident); 6380 uint32_t resolvedParent = parent; 6381 status_t err = pg->dynamicRefTable.lookupResourceId(&resolvedParent); 6382 if (err != NO_ERROR) { 6383 resolvedParent = 0; 6384 } 6385 printf(" Parent=0x%08x(Resolved=0x%08x), Count=%d\n", 6386 parent, resolvedParent, N); 6387 for (int i=0; i<N && mapOffset < (typeSize-sizeof(ResTable_map)); i++) { 6388 printf(" #%i (Key=0x%08x): ", 6389 i, dtohl(mapPtr->name.ident)); 6390 value.copyFrom_dtoh(mapPtr->value); 6391 print_value(typeConfigs->package, value); 6392 const size_t size = dtohs(mapPtr->value.size); 6393 mapOffset += size + sizeof(*mapPtr)-sizeof(mapPtr->value); 6394 mapPtr = (ResTable_map*)(baseMapPtr+mapOffset); 6395 } 6396 } 6397 } 6398 } 6399 } 6400 } 6401 } 6402} 6403 6404} // namespace android 6405