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