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