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