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