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