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