ResourceTypes.cpp revision 780d2a1b714724d85227141c76b3c64f543f00b4
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 <utils/Atomic.h> 21#include <utils/ByteOrder.h> 22#include <utils/Debug.h> 23#include <utils/ResourceTypes.h> 24#include <utils/String16.h> 25#include <utils/String8.h> 26#include <utils/TextOutput.h> 27#include <utils/Log.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 66static void printToLogFunc(void* cookie, const char* txt) 67{ 68 LOGV("%s", txt); 69} 70 71// Standard C isspace() is only required to look at the low byte of its input, so 72// produces incorrect results for UTF-16 characters. For safety's sake, assume that 73// any high-byte UTF-16 code point is not whitespace. 74inline int isspace16(char16_t c) { 75 return (c < 0x0080 && isspace(c)); 76} 77 78// range checked; guaranteed to NUL-terminate within the stated number of available slots 79// NOTE: if this truncates the dst string due to running out of space, no attempt is 80// made to avoid splitting surrogate pairs. 81static void strcpy16_dtoh(uint16_t* dst, const uint16_t* src, size_t avail) 82{ 83 uint16_t* last = dst + avail - 1; 84 while (*src && (dst < last)) { 85 char16_t s = dtohs(*src); 86 *dst++ = s; 87 src++; 88 } 89 *dst = 0; 90} 91 92static status_t validate_chunk(const ResChunk_header* chunk, 93 size_t minSize, 94 const uint8_t* dataEnd, 95 const char* name) 96{ 97 const uint16_t headerSize = dtohs(chunk->headerSize); 98 const uint32_t size = dtohl(chunk->size); 99 100 if (headerSize >= minSize) { 101 if (headerSize <= size) { 102 if (((headerSize|size)&0x3) == 0) { 103 if ((ssize_t)size <= (dataEnd-((const uint8_t*)chunk))) { 104 return NO_ERROR; 105 } 106 LOGW("%s data size %p extends beyond resource end %p.", 107 name, (void*)size, 108 (void*)(dataEnd-((const uint8_t*)chunk))); 109 return BAD_TYPE; 110 } 111 LOGW("%s size 0x%x or headerSize 0x%x is not on an integer boundary.", 112 name, (int)size, (int)headerSize); 113 return BAD_TYPE; 114 } 115 LOGW("%s size %p is smaller than header size %p.", 116 name, (void*)size, (void*)(int)headerSize); 117 return BAD_TYPE; 118 } 119 LOGW("%s header size %p is too small.", 120 name, (void*)(int)headerSize); 121 return BAD_TYPE; 122} 123 124inline void Res_value::copyFrom_dtoh(const Res_value& src) 125{ 126 size = dtohs(src.size); 127 res0 = src.res0; 128 dataType = src.dataType; 129 data = dtohl(src.data); 130} 131 132void Res_png_9patch::deviceToFile() 133{ 134 for (int i = 0; i < numXDivs; i++) { 135 xDivs[i] = htonl(xDivs[i]); 136 } 137 for (int i = 0; i < numYDivs; i++) { 138 yDivs[i] = htonl(yDivs[i]); 139 } 140 paddingLeft = htonl(paddingLeft); 141 paddingRight = htonl(paddingRight); 142 paddingTop = htonl(paddingTop); 143 paddingBottom = htonl(paddingBottom); 144 for (int i=0; i<numColors; i++) { 145 colors[i] = htonl(colors[i]); 146 } 147} 148 149void Res_png_9patch::fileToDevice() 150{ 151 for (int i = 0; i < numXDivs; i++) { 152 xDivs[i] = ntohl(xDivs[i]); 153 } 154 for (int i = 0; i < numYDivs; i++) { 155 yDivs[i] = ntohl(yDivs[i]); 156 } 157 paddingLeft = ntohl(paddingLeft); 158 paddingRight = ntohl(paddingRight); 159 paddingTop = ntohl(paddingTop); 160 paddingBottom = ntohl(paddingBottom); 161 for (int i=0; i<numColors; i++) { 162 colors[i] = ntohl(colors[i]); 163 } 164} 165 166size_t Res_png_9patch::serializedSize() 167{ 168 // The size of this struct is 32 bytes on the 32-bit target system 169 // 4 * int8_t 170 // 4 * int32_t 171 // 3 * pointer 172 return 32 173 + numXDivs * sizeof(int32_t) 174 + numYDivs * sizeof(int32_t) 175 + numColors * sizeof(uint32_t); 176} 177 178void* Res_png_9patch::serialize() 179{ 180 // Use calloc since we're going to leave a few holes in the data 181 // and want this to run cleanly under valgrind 182 void* newData = calloc(1, serializedSize()); 183 serialize(newData); 184 return newData; 185} 186 187void Res_png_9patch::serialize(void * outData) 188{ 189 char* data = (char*) outData; 190 memmove(data, &wasDeserialized, 4); // copy wasDeserialized, numXDivs, numYDivs, numColors 191 memmove(data + 12, &paddingLeft, 16); // copy paddingXXXX 192 data += 32; 193 194 memmove(data, this->xDivs, numXDivs * sizeof(int32_t)); 195 data += numXDivs * sizeof(int32_t); 196 memmove(data, this->yDivs, numYDivs * sizeof(int32_t)); 197 data += numYDivs * sizeof(int32_t); 198 memmove(data, this->colors, numColors * sizeof(uint32_t)); 199} 200 201static void deserializeInternal(const void* inData, Res_png_9patch* outData) { 202 char* patch = (char*) inData; 203 if (inData != outData) { 204 memmove(&outData->wasDeserialized, patch, 4); // copy wasDeserialized, numXDivs, numYDivs, numColors 205 memmove(&outData->paddingLeft, patch + 12, 4); // copy wasDeserialized, numXDivs, numYDivs, numColors 206 } 207 outData->wasDeserialized = true; 208 char* data = (char*)outData; 209 data += sizeof(Res_png_9patch); 210 outData->xDivs = (int32_t*) data; 211 data += outData->numXDivs * sizeof(int32_t); 212 outData->yDivs = (int32_t*) data; 213 data += outData->numYDivs * sizeof(int32_t); 214 outData->colors = (uint32_t*) data; 215} 216 217Res_png_9patch* Res_png_9patch::deserialize(const void* inData) 218{ 219 if (sizeof(void*) != sizeof(int32_t)) { 220 LOGE("Cannot deserialize on non 32-bit system\n"); 221 return NULL; 222 } 223 deserializeInternal(inData, (Res_png_9patch*) inData); 224 return (Res_png_9patch*) inData; 225} 226 227// -------------------------------------------------------------------- 228// -------------------------------------------------------------------- 229// -------------------------------------------------------------------- 230 231ResStringPool::ResStringPool() 232 : mError(NO_INIT), mOwnedData(NULL), mHeader(NULL), mCache(NULL) 233{ 234} 235 236ResStringPool::ResStringPool(const void* data, size_t size, bool copyData) 237 : mError(NO_INIT), mOwnedData(NULL), mHeader(NULL), mCache(NULL) 238{ 239 setTo(data, size, copyData); 240} 241 242ResStringPool::~ResStringPool() 243{ 244 uninit(); 245} 246 247status_t ResStringPool::setTo(const void* data, size_t size, bool copyData) 248{ 249 if (!data || !size) { 250 return (mError=BAD_TYPE); 251 } 252 253 uninit(); 254 255 const bool notDeviceEndian = htods(0xf0) != 0xf0; 256 257 if (copyData || notDeviceEndian) { 258 mOwnedData = malloc(size); 259 if (mOwnedData == NULL) { 260 return (mError=NO_MEMORY); 261 } 262 memcpy(mOwnedData, data, size); 263 data = mOwnedData; 264 } 265 266 mHeader = (const ResStringPool_header*)data; 267 268 if (notDeviceEndian) { 269 ResStringPool_header* h = const_cast<ResStringPool_header*>(mHeader); 270 h->header.headerSize = dtohs(mHeader->header.headerSize); 271 h->header.type = dtohs(mHeader->header.type); 272 h->header.size = dtohl(mHeader->header.size); 273 h->stringCount = dtohl(mHeader->stringCount); 274 h->styleCount = dtohl(mHeader->styleCount); 275 h->flags = dtohl(mHeader->flags); 276 h->stringsStart = dtohl(mHeader->stringsStart); 277 h->stylesStart = dtohl(mHeader->stylesStart); 278 } 279 280 if (mHeader->header.headerSize > mHeader->header.size 281 || mHeader->header.size > size) { 282 LOGW("Bad string block: header size %d or total size %d is larger than data size %d\n", 283 (int)mHeader->header.headerSize, (int)mHeader->header.size, (int)size); 284 return (mError=BAD_TYPE); 285 } 286 mSize = mHeader->header.size; 287 mEntries = (const uint32_t*) 288 (((const uint8_t*)data)+mHeader->header.headerSize); 289 290 if (mHeader->stringCount > 0) { 291 if ((mHeader->stringCount*sizeof(uint32_t) < mHeader->stringCount) // uint32 overflow? 292 || (mHeader->header.headerSize+(mHeader->stringCount*sizeof(uint32_t))) 293 > size) { 294 LOGW("Bad string block: entry of %d items extends past data size %d\n", 295 (int)(mHeader->header.headerSize+(mHeader->stringCount*sizeof(uint32_t))), 296 (int)size); 297 return (mError=BAD_TYPE); 298 } 299 300 size_t charSize; 301 if (mHeader->flags&ResStringPool_header::UTF8_FLAG) { 302 charSize = sizeof(uint8_t); 303 mCache = (char16_t**)malloc(sizeof(char16_t**)*mHeader->stringCount); 304 memset(mCache, 0, sizeof(char16_t**)*mHeader->stringCount); 305 } else { 306 charSize = sizeof(char16_t); 307 } 308 309 mStrings = (const void*) 310 (((const uint8_t*)data)+mHeader->stringsStart); 311 if (mHeader->stringsStart >= (mHeader->header.size-sizeof(uint16_t))) { 312 LOGW("Bad string block: string pool starts at %d, after total size %d\n", 313 (int)mHeader->stringsStart, (int)mHeader->header.size); 314 return (mError=BAD_TYPE); 315 } 316 if (mHeader->styleCount == 0) { 317 mStringPoolSize = 318 (mHeader->header.size-mHeader->stringsStart)/charSize; 319 } else { 320 // check invariant: styles follow the strings 321 if (mHeader->stylesStart <= mHeader->stringsStart) { 322 LOGW("Bad style block: style block starts at %d, before strings at %d\n", 323 (int)mHeader->stylesStart, (int)mHeader->stringsStart); 324 return (mError=BAD_TYPE); 325 } 326 mStringPoolSize = 327 (mHeader->stylesStart-mHeader->stringsStart)/charSize; 328 } 329 330 // check invariant: stringCount > 0 requires a string pool to exist 331 if (mStringPoolSize == 0) { 332 LOGW("Bad string block: stringCount is %d but pool size is 0\n", (int)mHeader->stringCount); 333 return (mError=BAD_TYPE); 334 } 335 336 if (notDeviceEndian) { 337 size_t i; 338 uint32_t* e = const_cast<uint32_t*>(mEntries); 339 for (i=0; i<mHeader->stringCount; i++) { 340 e[i] = dtohl(mEntries[i]); 341 } 342 if (!(mHeader->flags&ResStringPool_header::UTF8_FLAG)) { 343 const char16_t* strings = (const char16_t*)mStrings; 344 char16_t* s = const_cast<char16_t*>(strings); 345 for (i=0; i<mStringPoolSize; i++) { 346 s[i] = dtohs(strings[i]); 347 } 348 } 349 } 350 351 if ((mHeader->flags&ResStringPool_header::UTF8_FLAG && 352 ((uint8_t*)mStrings)[mStringPoolSize-1] != 0) || 353 (!mHeader->flags&ResStringPool_header::UTF8_FLAG && 354 ((char16_t*)mStrings)[mStringPoolSize-1] != 0)) { 355 LOGW("Bad string block: last string is not 0-terminated\n"); 356 return (mError=BAD_TYPE); 357 } 358 } else { 359 mStrings = NULL; 360 mStringPoolSize = 0; 361 } 362 363 if (mHeader->styleCount > 0) { 364 mEntryStyles = mEntries + mHeader->stringCount; 365 // invariant: integer overflow in calculating mEntryStyles 366 if (mEntryStyles < mEntries) { 367 LOGW("Bad string block: integer overflow finding styles\n"); 368 return (mError=BAD_TYPE); 369 } 370 371 if (((const uint8_t*)mEntryStyles-(const uint8_t*)mHeader) > (int)size) { 372 LOGW("Bad string block: entry of %d styles extends past data size %d\n", 373 (int)((const uint8_t*)mEntryStyles-(const uint8_t*)mHeader), 374 (int)size); 375 return (mError=BAD_TYPE); 376 } 377 mStyles = (const uint32_t*) 378 (((const uint8_t*)data)+mHeader->stylesStart); 379 if (mHeader->stylesStart >= mHeader->header.size) { 380 LOGW("Bad string block: style pool starts %d, after total size %d\n", 381 (int)mHeader->stylesStart, (int)mHeader->header.size); 382 return (mError=BAD_TYPE); 383 } 384 mStylePoolSize = 385 (mHeader->header.size-mHeader->stylesStart)/sizeof(uint32_t); 386 387 if (notDeviceEndian) { 388 size_t i; 389 uint32_t* e = const_cast<uint32_t*>(mEntryStyles); 390 for (i=0; i<mHeader->styleCount; i++) { 391 e[i] = dtohl(mEntryStyles[i]); 392 } 393 uint32_t* s = const_cast<uint32_t*>(mStyles); 394 for (i=0; i<mStylePoolSize; i++) { 395 s[i] = dtohl(mStyles[i]); 396 } 397 } 398 399 const ResStringPool_span endSpan = { 400 { htodl(ResStringPool_span::END) }, 401 htodl(ResStringPool_span::END), htodl(ResStringPool_span::END) 402 }; 403 if (memcmp(&mStyles[mStylePoolSize-(sizeof(endSpan)/sizeof(uint32_t))], 404 &endSpan, sizeof(endSpan)) != 0) { 405 LOGW("Bad string block: last style is not 0xFFFFFFFF-terminated\n"); 406 return (mError=BAD_TYPE); 407 } 408 } else { 409 mEntryStyles = NULL; 410 mStyles = NULL; 411 mStylePoolSize = 0; 412 } 413 414 return (mError=NO_ERROR); 415} 416 417status_t ResStringPool::getError() const 418{ 419 return mError; 420} 421 422void ResStringPool::uninit() 423{ 424 mError = NO_INIT; 425 if (mOwnedData) { 426 free(mOwnedData); 427 mOwnedData = NULL; 428 } 429 if (mHeader != NULL && mCache != NULL) { 430 for (size_t x = 0; x < mHeader->stringCount; x++) { 431 if (mCache[x] != NULL) { 432 free(mCache[x]); 433 mCache[x] = NULL; 434 } 435 } 436 free(mCache); 437 mCache = NULL; 438 } 439} 440 441#define DECODE_LENGTH(str, chrsz, len) \ 442 len = *(str); \ 443 if (*(str)&(1<<(chrsz*8-1))) { \ 444 (str)++; \ 445 len = (((len)&((1<<(chrsz*8-1))-1))<<(chrsz*8)) + *(str); \ 446 } \ 447 (str)++; 448 449const uint16_t* ResStringPool::stringAt(size_t idx, size_t* outLen) const 450{ 451 if (mError == NO_ERROR && idx < mHeader->stringCount) { 452 const bool isUTF8 = (mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0; 453 const uint32_t off = mEntries[idx]/(isUTF8?sizeof(char):sizeof(char16_t)); 454 if (off < (mStringPoolSize-1)) { 455 if (!isUTF8) { 456 const char16_t* strings = (char16_t*)mStrings; 457 const char16_t* str = strings+off; 458 DECODE_LENGTH(str, sizeof(char16_t), *outLen) 459 if ((uint32_t)(str+*outLen-strings) < mStringPoolSize) { 460 return str; 461 } else { 462 LOGW("Bad string block: string #%d extends to %d, past end at %d\n", 463 (int)idx, (int)(str+*outLen-strings), (int)mStringPoolSize); 464 } 465 } else { 466 const uint8_t* strings = (uint8_t*)mStrings; 467 const uint8_t* str = strings+off; 468 DECODE_LENGTH(str, sizeof(uint8_t), *outLen) 469 size_t encLen; 470 DECODE_LENGTH(str, sizeof(uint8_t), encLen) 471 if ((uint32_t)(str+encLen-strings) < mStringPoolSize) { 472 AutoMutex lock(mDecodeLock); 473 if (mCache[idx] != NULL) { 474 return mCache[idx]; 475 } 476 char16_t *u16str = (char16_t *)calloc(*outLen+1, sizeof(char16_t)); 477 if (!u16str) { 478 LOGW("No memory when trying to allocate decode cache for string #%d\n", 479 (int)idx); 480 return NULL; 481 } 482 const unsigned char *u8src = reinterpret_cast<const unsigned char *>(str); 483 utf8_to_utf16(u8src, encLen, u16str, *outLen); 484 mCache[idx] = u16str; 485 return u16str; 486 } else { 487 LOGW("Bad string block: string #%d extends to %d, past end at %d\n", 488 (int)idx, (int)(str+encLen-strings), (int)mStringPoolSize); 489 } 490 } 491 } else { 492 LOGW("Bad string block: string #%d entry is at %d, past end at %d\n", 493 (int)idx, (int)(off*sizeof(uint16_t)), 494 (int)(mStringPoolSize*sizeof(uint16_t))); 495 } 496 } 497 return NULL; 498} 499 500const char* ResStringPool::string8At(size_t idx, size_t* outLen) const 501{ 502 if (mError == NO_ERROR && idx < mHeader->stringCount) { 503 const bool isUTF8 = (mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0; 504 const uint32_t off = mEntries[idx]/(isUTF8?sizeof(char):sizeof(char16_t)); 505 if (off < (mStringPoolSize-1)) { 506 if (isUTF8) { 507 const uint8_t* strings = (uint8_t*)mStrings; 508 const uint8_t* str = strings+off; 509 DECODE_LENGTH(str, sizeof(uint8_t), *outLen) 510 size_t encLen; 511 DECODE_LENGTH(str, sizeof(uint8_t), encLen) 512 if ((uint32_t)(str+encLen-strings) < mStringPoolSize) { 513 return (const char*)str; 514 } else { 515 LOGW("Bad string block: string #%d extends to %d, past end at %d\n", 516 (int)idx, (int)(str+encLen-strings), (int)mStringPoolSize); 517 } 518 } 519 } else { 520 LOGW("Bad string block: string #%d entry is at %d, past end at %d\n", 521 (int)idx, (int)(off*sizeof(uint16_t)), 522 (int)(mStringPoolSize*sizeof(uint16_t))); 523 } 524 } 525 return NULL; 526} 527 528const ResStringPool_span* ResStringPool::styleAt(const ResStringPool_ref& ref) const 529{ 530 return styleAt(ref.index); 531} 532 533const ResStringPool_span* ResStringPool::styleAt(size_t idx) const 534{ 535 if (mError == NO_ERROR && idx < mHeader->styleCount) { 536 const uint32_t off = (mEntryStyles[idx]/sizeof(uint32_t)); 537 if (off < mStylePoolSize) { 538 return (const ResStringPool_span*)(mStyles+off); 539 } else { 540 LOGW("Bad string block: style #%d entry is at %d, past end at %d\n", 541 (int)idx, (int)(off*sizeof(uint32_t)), 542 (int)(mStylePoolSize*sizeof(uint32_t))); 543 } 544 } 545 return NULL; 546} 547 548ssize_t ResStringPool::indexOfString(const char16_t* str, size_t strLen) const 549{ 550 if (mError != NO_ERROR) { 551 return mError; 552 } 553 554 size_t len; 555 556 // TODO optimize searching for UTF-8 strings taking into account 557 // the cache fill to determine when to convert the searched-for 558 // string key to UTF-8. 559 560 if (mHeader->flags&ResStringPool_header::SORTED_FLAG) { 561 // Do a binary search for the string... 562 ssize_t l = 0; 563 ssize_t h = mHeader->stringCount-1; 564 565 ssize_t mid; 566 while (l <= h) { 567 mid = l + (h - l)/2; 568 const char16_t* s = stringAt(mid, &len); 569 int c = s ? strzcmp16(s, len, str, strLen) : -1; 570 POOL_NOISY(printf("Looking for %s, at %s, cmp=%d, l/mid/h=%d/%d/%d\n", 571 String8(str).string(), 572 String8(s).string(), 573 c, (int)l, (int)mid, (int)h)); 574 if (c == 0) { 575 return mid; 576 } else if (c < 0) { 577 l = mid + 1; 578 } else { 579 h = mid - 1; 580 } 581 } 582 } else { 583 // It is unusual to get the ID from an unsorted string block... 584 // most often this happens because we want to get IDs for style 585 // span tags; since those always appear at the end of the string 586 // block, start searching at the back. 587 for (int i=mHeader->stringCount-1; i>=0; i--) { 588 const char16_t* s = stringAt(i, &len); 589 POOL_NOISY(printf("Looking for %s, at %s, i=%d\n", 590 String8(str, strLen).string(), 591 String8(s).string(), 592 i)); 593 if (s && strzcmp16(s, len, str, strLen) == 0) { 594 return i; 595 } 596 } 597 } 598 599 return NAME_NOT_FOUND; 600} 601 602size_t ResStringPool::size() const 603{ 604 return (mError == NO_ERROR) ? mHeader->stringCount : 0; 605} 606 607#ifndef HAVE_ANDROID_OS 608bool ResStringPool::isUTF8() const 609{ 610 return (mHeader->flags&ResStringPool_header::UTF8_FLAG)!=0; 611} 612#endif 613 614// -------------------------------------------------------------------- 615// -------------------------------------------------------------------- 616// -------------------------------------------------------------------- 617 618ResXMLParser::ResXMLParser(const ResXMLTree& tree) 619 : mTree(tree), mEventCode(BAD_DOCUMENT) 620{ 621} 622 623void ResXMLParser::restart() 624{ 625 mCurNode = NULL; 626 mEventCode = mTree.mError == NO_ERROR ? START_DOCUMENT : BAD_DOCUMENT; 627} 628 629ResXMLParser::event_code_t ResXMLParser::getEventType() const 630{ 631 return mEventCode; 632} 633 634ResXMLParser::event_code_t ResXMLParser::next() 635{ 636 if (mEventCode == START_DOCUMENT) { 637 mCurNode = mTree.mRootNode; 638 mCurExt = mTree.mRootExt; 639 return (mEventCode=mTree.mRootCode); 640 } else if (mEventCode >= FIRST_CHUNK_CODE) { 641 return nextNode(); 642 } 643 return mEventCode; 644} 645 646int32_t ResXMLParser::getCommentID() const 647{ 648 return mCurNode != NULL ? dtohl(mCurNode->comment.index) : -1; 649} 650 651const uint16_t* ResXMLParser::getComment(size_t* outLen) const 652{ 653 int32_t id = getCommentID(); 654 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL; 655} 656 657uint32_t ResXMLParser::getLineNumber() const 658{ 659 return mCurNode != NULL ? dtohl(mCurNode->lineNumber) : -1; 660} 661 662int32_t ResXMLParser::getTextID() const 663{ 664 if (mEventCode == TEXT) { 665 return dtohl(((const ResXMLTree_cdataExt*)mCurExt)->data.index); 666 } 667 return -1; 668} 669 670const uint16_t* ResXMLParser::getText(size_t* outLen) const 671{ 672 int32_t id = getTextID(); 673 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL; 674} 675 676ssize_t ResXMLParser::getTextValue(Res_value* outValue) const 677{ 678 if (mEventCode == TEXT) { 679 outValue->copyFrom_dtoh(((const ResXMLTree_cdataExt*)mCurExt)->typedData); 680 return sizeof(Res_value); 681 } 682 return BAD_TYPE; 683} 684 685int32_t ResXMLParser::getNamespacePrefixID() const 686{ 687 if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) { 688 return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->prefix.index); 689 } 690 return -1; 691} 692 693const uint16_t* ResXMLParser::getNamespacePrefix(size_t* outLen) const 694{ 695 int32_t id = getNamespacePrefixID(); 696 //printf("prefix=%d event=%p\n", id, mEventCode); 697 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL; 698} 699 700int32_t ResXMLParser::getNamespaceUriID() const 701{ 702 if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) { 703 return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->uri.index); 704 } 705 return -1; 706} 707 708const uint16_t* ResXMLParser::getNamespaceUri(size_t* outLen) const 709{ 710 int32_t id = getNamespaceUriID(); 711 //printf("uri=%d event=%p\n", id, mEventCode); 712 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL; 713} 714 715int32_t ResXMLParser::getElementNamespaceID() const 716{ 717 if (mEventCode == START_TAG) { 718 return dtohl(((const ResXMLTree_attrExt*)mCurExt)->ns.index); 719 } 720 if (mEventCode == END_TAG) { 721 return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->ns.index); 722 } 723 return -1; 724} 725 726const uint16_t* ResXMLParser::getElementNamespace(size_t* outLen) const 727{ 728 int32_t id = getElementNamespaceID(); 729 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL; 730} 731 732int32_t ResXMLParser::getElementNameID() const 733{ 734 if (mEventCode == START_TAG) { 735 return dtohl(((const ResXMLTree_attrExt*)mCurExt)->name.index); 736 } 737 if (mEventCode == END_TAG) { 738 return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->name.index); 739 } 740 return -1; 741} 742 743const uint16_t* ResXMLParser::getElementName(size_t* outLen) const 744{ 745 int32_t id = getElementNameID(); 746 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL; 747} 748 749size_t ResXMLParser::getAttributeCount() const 750{ 751 if (mEventCode == START_TAG) { 752 return dtohs(((const ResXMLTree_attrExt*)mCurExt)->attributeCount); 753 } 754 return 0; 755} 756 757int32_t ResXMLParser::getAttributeNamespaceID(size_t idx) const 758{ 759 if (mEventCode == START_TAG) { 760 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt; 761 if (idx < dtohs(tag->attributeCount)) { 762 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*) 763 (((const uint8_t*)tag) 764 + dtohs(tag->attributeStart) 765 + (dtohs(tag->attributeSize)*idx)); 766 return dtohl(attr->ns.index); 767 } 768 } 769 return -2; 770} 771 772const uint16_t* ResXMLParser::getAttributeNamespace(size_t idx, size_t* outLen) const 773{ 774 int32_t id = getAttributeNamespaceID(idx); 775 //printf("attribute namespace=%d idx=%d event=%p\n", id, idx, mEventCode); 776 //XML_NOISY(printf("getAttributeNamespace 0x%x=0x%x\n", idx, id)); 777 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL; 778} 779 780int32_t ResXMLParser::getAttributeNameID(size_t idx) const 781{ 782 if (mEventCode == START_TAG) { 783 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt; 784 if (idx < dtohs(tag->attributeCount)) { 785 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*) 786 (((const uint8_t*)tag) 787 + dtohs(tag->attributeStart) 788 + (dtohs(tag->attributeSize)*idx)); 789 return dtohl(attr->name.index); 790 } 791 } 792 return -1; 793} 794 795const uint16_t* ResXMLParser::getAttributeName(size_t idx, size_t* outLen) const 796{ 797 int32_t id = getAttributeNameID(idx); 798 //printf("attribute name=%d idx=%d event=%p\n", id, idx, mEventCode); 799 //XML_NOISY(printf("getAttributeName 0x%x=0x%x\n", idx, id)); 800 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL; 801} 802 803uint32_t ResXMLParser::getAttributeNameResID(size_t idx) const 804{ 805 int32_t id = getAttributeNameID(idx); 806 if (id >= 0 && (size_t)id < mTree.mNumResIds) { 807 return dtohl(mTree.mResIds[id]); 808 } 809 return 0; 810} 811 812int32_t ResXMLParser::getAttributeValueStringID(size_t idx) const 813{ 814 if (mEventCode == START_TAG) { 815 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt; 816 if (idx < dtohs(tag->attributeCount)) { 817 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*) 818 (((const uint8_t*)tag) 819 + dtohs(tag->attributeStart) 820 + (dtohs(tag->attributeSize)*idx)); 821 return dtohl(attr->rawValue.index); 822 } 823 } 824 return -1; 825} 826 827const uint16_t* ResXMLParser::getAttributeStringValue(size_t idx, size_t* outLen) const 828{ 829 int32_t id = getAttributeValueStringID(idx); 830 //XML_NOISY(printf("getAttributeValue 0x%x=0x%x\n", idx, id)); 831 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL; 832} 833 834int32_t ResXMLParser::getAttributeDataType(size_t idx) const 835{ 836 if (mEventCode == START_TAG) { 837 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt; 838 if (idx < dtohs(tag->attributeCount)) { 839 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*) 840 (((const uint8_t*)tag) 841 + dtohs(tag->attributeStart) 842 + (dtohs(tag->attributeSize)*idx)); 843 return attr->typedValue.dataType; 844 } 845 } 846 return Res_value::TYPE_NULL; 847} 848 849int32_t ResXMLParser::getAttributeData(size_t idx) const 850{ 851 if (mEventCode == START_TAG) { 852 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt; 853 if (idx < dtohs(tag->attributeCount)) { 854 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*) 855 (((const uint8_t*)tag) 856 + dtohs(tag->attributeStart) 857 + (dtohs(tag->attributeSize)*idx)); 858 return dtohl(attr->typedValue.data); 859 } 860 } 861 return 0; 862} 863 864ssize_t ResXMLParser::getAttributeValue(size_t idx, Res_value* outValue) const 865{ 866 if (mEventCode == START_TAG) { 867 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt; 868 if (idx < dtohs(tag->attributeCount)) { 869 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*) 870 (((const uint8_t*)tag) 871 + dtohs(tag->attributeStart) 872 + (dtohs(tag->attributeSize)*idx)); 873 outValue->copyFrom_dtoh(attr->typedValue); 874 return sizeof(Res_value); 875 } 876 } 877 return BAD_TYPE; 878} 879 880ssize_t ResXMLParser::indexOfAttribute(const char* ns, const char* attr) const 881{ 882 String16 nsStr(ns != NULL ? ns : ""); 883 String16 attrStr(attr); 884 return indexOfAttribute(ns ? nsStr.string() : NULL, ns ? nsStr.size() : 0, 885 attrStr.string(), attrStr.size()); 886} 887 888ssize_t ResXMLParser::indexOfAttribute(const char16_t* ns, size_t nsLen, 889 const char16_t* attr, size_t attrLen) const 890{ 891 if (mEventCode == START_TAG) { 892 const size_t N = getAttributeCount(); 893 for (size_t i=0; i<N; i++) { 894 size_t curNsLen, curAttrLen; 895 const char16_t* curNs = getAttributeNamespace(i, &curNsLen); 896 const char16_t* curAttr = getAttributeName(i, &curAttrLen); 897 //printf("%d: ns=%p attr=%p curNs=%p curAttr=%p\n", 898 // i, ns, attr, curNs, curAttr); 899 //printf(" --> attr=%s, curAttr=%s\n", 900 // String8(attr).string(), String8(curAttr).string()); 901 if (attr && curAttr && (strzcmp16(attr, attrLen, curAttr, curAttrLen) == 0)) { 902 if (ns == NULL) { 903 if (curNs == NULL) return i; 904 } else if (curNs != NULL) { 905 //printf(" --> ns=%s, curNs=%s\n", 906 // String8(ns).string(), String8(curNs).string()); 907 if (strzcmp16(ns, nsLen, curNs, curNsLen) == 0) return i; 908 } 909 } 910 } 911 } 912 913 return NAME_NOT_FOUND; 914} 915 916ssize_t ResXMLParser::indexOfID() const 917{ 918 if (mEventCode == START_TAG) { 919 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->idIndex); 920 if (idx > 0) return (idx-1); 921 } 922 return NAME_NOT_FOUND; 923} 924 925ssize_t ResXMLParser::indexOfClass() const 926{ 927 if (mEventCode == START_TAG) { 928 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->classIndex); 929 if (idx > 0) return (idx-1); 930 } 931 return NAME_NOT_FOUND; 932} 933 934ssize_t ResXMLParser::indexOfStyle() const 935{ 936 if (mEventCode == START_TAG) { 937 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->styleIndex); 938 if (idx > 0) return (idx-1); 939 } 940 return NAME_NOT_FOUND; 941} 942 943ResXMLParser::event_code_t ResXMLParser::nextNode() 944{ 945 if (mEventCode < 0) { 946 return mEventCode; 947 } 948 949 do { 950 const ResXMLTree_node* next = (const ResXMLTree_node*) 951 (((const uint8_t*)mCurNode) + dtohl(mCurNode->header.size)); 952 //LOGW("Next node: prev=%p, next=%p\n", mCurNode, next); 953 954 if (((const uint8_t*)next) >= mTree.mDataEnd) { 955 mCurNode = NULL; 956 return (mEventCode=END_DOCUMENT); 957 } 958 959 if (mTree.validateNode(next) != NO_ERROR) { 960 mCurNode = NULL; 961 return (mEventCode=BAD_DOCUMENT); 962 } 963 964 mCurNode = next; 965 const uint16_t headerSize = dtohs(next->header.headerSize); 966 const uint32_t totalSize = dtohl(next->header.size); 967 mCurExt = ((const uint8_t*)next) + headerSize; 968 size_t minExtSize = 0; 969 event_code_t eventCode = (event_code_t)dtohs(next->header.type); 970 switch ((mEventCode=eventCode)) { 971 case RES_XML_START_NAMESPACE_TYPE: 972 case RES_XML_END_NAMESPACE_TYPE: 973 minExtSize = sizeof(ResXMLTree_namespaceExt); 974 break; 975 case RES_XML_START_ELEMENT_TYPE: 976 minExtSize = sizeof(ResXMLTree_attrExt); 977 break; 978 case RES_XML_END_ELEMENT_TYPE: 979 minExtSize = sizeof(ResXMLTree_endElementExt); 980 break; 981 case RES_XML_CDATA_TYPE: 982 minExtSize = sizeof(ResXMLTree_cdataExt); 983 break; 984 default: 985 LOGW("Unknown XML block: header type %d in node at %d\n", 986 (int)dtohs(next->header.type), 987 (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader))); 988 continue; 989 } 990 991 if ((totalSize-headerSize) < minExtSize) { 992 LOGW("Bad XML block: header type 0x%x in node at 0x%x has size %d, need %d\n", 993 (int)dtohs(next->header.type), 994 (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)), 995 (int)(totalSize-headerSize), (int)minExtSize); 996 return (mEventCode=BAD_DOCUMENT); 997 } 998 999 //printf("CurNode=%p, CurExt=%p, headerSize=%d, minExtSize=%d\n", 1000 // mCurNode, mCurExt, headerSize, minExtSize); 1001 1002 return eventCode; 1003 } while (true); 1004} 1005 1006void ResXMLParser::getPosition(ResXMLParser::ResXMLPosition* pos) const 1007{ 1008 pos->eventCode = mEventCode; 1009 pos->curNode = mCurNode; 1010 pos->curExt = mCurExt; 1011} 1012 1013void ResXMLParser::setPosition(const ResXMLParser::ResXMLPosition& pos) 1014{ 1015 mEventCode = pos.eventCode; 1016 mCurNode = pos.curNode; 1017 mCurExt = pos.curExt; 1018} 1019 1020 1021// -------------------------------------------------------------------- 1022 1023static volatile int32_t gCount = 0; 1024 1025ResXMLTree::ResXMLTree() 1026 : ResXMLParser(*this) 1027 , mError(NO_INIT), mOwnedData(NULL) 1028{ 1029 //LOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1); 1030 restart(); 1031} 1032 1033ResXMLTree::ResXMLTree(const void* data, size_t size, bool copyData) 1034 : ResXMLParser(*this) 1035 , mError(NO_INIT), mOwnedData(NULL) 1036{ 1037 //LOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1); 1038 setTo(data, size, copyData); 1039} 1040 1041ResXMLTree::~ResXMLTree() 1042{ 1043 //LOGI("Destroying ResXMLTree in %p #%d\n", this, android_atomic_dec(&gCount)-1); 1044 uninit(); 1045} 1046 1047status_t ResXMLTree::setTo(const void* data, size_t size, bool copyData) 1048{ 1049 uninit(); 1050 mEventCode = START_DOCUMENT; 1051 1052 if (copyData) { 1053 mOwnedData = malloc(size); 1054 if (mOwnedData == NULL) { 1055 return (mError=NO_MEMORY); 1056 } 1057 memcpy(mOwnedData, data, size); 1058 data = mOwnedData; 1059 } 1060 1061 mHeader = (const ResXMLTree_header*)data; 1062 mSize = dtohl(mHeader->header.size); 1063 if (dtohs(mHeader->header.headerSize) > mSize || mSize > size) { 1064 LOGW("Bad XML block: header size %d or total size %d is larger than data size %d\n", 1065 (int)dtohs(mHeader->header.headerSize), 1066 (int)dtohl(mHeader->header.size), (int)size); 1067 mError = BAD_TYPE; 1068 restart(); 1069 return mError; 1070 } 1071 mDataEnd = ((const uint8_t*)mHeader) + mSize; 1072 1073 mStrings.uninit(); 1074 mRootNode = NULL; 1075 mResIds = NULL; 1076 mNumResIds = 0; 1077 1078 // First look for a couple interesting chunks: the string block 1079 // and first XML node. 1080 const ResChunk_header* chunk = 1081 (const ResChunk_header*)(((const uint8_t*)mHeader) + dtohs(mHeader->header.headerSize)); 1082 const ResChunk_header* lastChunk = chunk; 1083 while (((const uint8_t*)chunk) < (mDataEnd-sizeof(ResChunk_header)) && 1084 ((const uint8_t*)chunk) < (mDataEnd-dtohl(chunk->size))) { 1085 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), mDataEnd, "XML"); 1086 if (err != NO_ERROR) { 1087 mError = err; 1088 goto done; 1089 } 1090 const uint16_t type = dtohs(chunk->type); 1091 const size_t size = dtohl(chunk->size); 1092 XML_NOISY(printf("Scanning @ %p: type=0x%x, size=0x%x\n", 1093 (void*)(((uint32_t)chunk)-((uint32_t)mHeader)), type, size)); 1094 if (type == RES_STRING_POOL_TYPE) { 1095 mStrings.setTo(chunk, size); 1096 } else if (type == RES_XML_RESOURCE_MAP_TYPE) { 1097 mResIds = (const uint32_t*) 1098 (((const uint8_t*)chunk)+dtohs(chunk->headerSize)); 1099 mNumResIds = (dtohl(chunk->size)-dtohs(chunk->headerSize))/sizeof(uint32_t); 1100 } else if (type >= RES_XML_FIRST_CHUNK_TYPE 1101 && type <= RES_XML_LAST_CHUNK_TYPE) { 1102 if (validateNode((const ResXMLTree_node*)chunk) != NO_ERROR) { 1103 mError = BAD_TYPE; 1104 goto done; 1105 } 1106 mCurNode = (const ResXMLTree_node*)lastChunk; 1107 if (nextNode() == BAD_DOCUMENT) { 1108 mError = BAD_TYPE; 1109 goto done; 1110 } 1111 mRootNode = mCurNode; 1112 mRootExt = mCurExt; 1113 mRootCode = mEventCode; 1114 break; 1115 } else { 1116 XML_NOISY(printf("Skipping unknown chunk!\n")); 1117 } 1118 lastChunk = chunk; 1119 chunk = (const ResChunk_header*) 1120 (((const uint8_t*)chunk) + size); 1121 } 1122 1123 if (mRootNode == NULL) { 1124 LOGW("Bad XML block: no root element node found\n"); 1125 mError = BAD_TYPE; 1126 goto done; 1127 } 1128 1129 mError = mStrings.getError(); 1130 1131done: 1132 restart(); 1133 return mError; 1134} 1135 1136status_t ResXMLTree::getError() const 1137{ 1138 return mError; 1139} 1140 1141void ResXMLTree::uninit() 1142{ 1143 mError = NO_INIT; 1144 mStrings.uninit(); 1145 if (mOwnedData) { 1146 free(mOwnedData); 1147 mOwnedData = NULL; 1148 } 1149 restart(); 1150} 1151 1152const ResStringPool& ResXMLTree::getStrings() const 1153{ 1154 return mStrings; 1155} 1156 1157status_t ResXMLTree::validateNode(const ResXMLTree_node* node) const 1158{ 1159 const uint16_t eventCode = dtohs(node->header.type); 1160 1161 status_t err = validate_chunk( 1162 &node->header, sizeof(ResXMLTree_node), 1163 mDataEnd, "ResXMLTree_node"); 1164 1165 if (err >= NO_ERROR) { 1166 // Only perform additional validation on START nodes 1167 if (eventCode != RES_XML_START_ELEMENT_TYPE) { 1168 return NO_ERROR; 1169 } 1170 1171 const uint16_t headerSize = dtohs(node->header.headerSize); 1172 const uint32_t size = dtohl(node->header.size); 1173 const ResXMLTree_attrExt* attrExt = (const ResXMLTree_attrExt*) 1174 (((const uint8_t*)node) + headerSize); 1175 // check for sensical values pulled out of the stream so far... 1176 if ((size >= headerSize + sizeof(ResXMLTree_attrExt)) 1177 && ((void*)attrExt > (void*)node)) { 1178 const size_t attrSize = ((size_t)dtohs(attrExt->attributeSize)) 1179 * dtohs(attrExt->attributeCount); 1180 if ((dtohs(attrExt->attributeStart)+attrSize) <= (size-headerSize)) { 1181 return NO_ERROR; 1182 } 1183 LOGW("Bad XML block: node attributes use 0x%x bytes, only have 0x%x bytes\n", 1184 (unsigned int)(dtohs(attrExt->attributeStart)+attrSize), 1185 (unsigned int)(size-headerSize)); 1186 } 1187 else { 1188 LOGW("Bad XML start block: node header size 0x%x, size 0x%x\n", 1189 (unsigned int)headerSize, (unsigned int)size); 1190 } 1191 return BAD_TYPE; 1192 } 1193 1194 return err; 1195 1196#if 0 1197 const bool isStart = dtohs(node->header.type) == RES_XML_START_ELEMENT_TYPE; 1198 1199 const uint16_t headerSize = dtohs(node->header.headerSize); 1200 const uint32_t size = dtohl(node->header.size); 1201 1202 if (headerSize >= (isStart ? sizeof(ResXMLTree_attrNode) : sizeof(ResXMLTree_node))) { 1203 if (size >= headerSize) { 1204 if (((const uint8_t*)node) <= (mDataEnd-size)) { 1205 if (!isStart) { 1206 return NO_ERROR; 1207 } 1208 if ((((size_t)dtohs(node->attributeSize))*dtohs(node->attributeCount)) 1209 <= (size-headerSize)) { 1210 return NO_ERROR; 1211 } 1212 LOGW("Bad XML block: node attributes use 0x%x bytes, only have 0x%x bytes\n", 1213 ((int)dtohs(node->attributeSize))*dtohs(node->attributeCount), 1214 (int)(size-headerSize)); 1215 return BAD_TYPE; 1216 } 1217 LOGW("Bad XML block: node at 0x%x extends beyond data end 0x%x\n", 1218 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)), (int)mSize); 1219 return BAD_TYPE; 1220 } 1221 LOGW("Bad XML block: node at 0x%x header size 0x%x smaller than total size 0x%x\n", 1222 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)), 1223 (int)headerSize, (int)size); 1224 return BAD_TYPE; 1225 } 1226 LOGW("Bad XML block: node at 0x%x header size 0x%x too small\n", 1227 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)), 1228 (int)headerSize); 1229 return BAD_TYPE; 1230#endif 1231} 1232 1233// -------------------------------------------------------------------- 1234// -------------------------------------------------------------------- 1235// -------------------------------------------------------------------- 1236 1237struct ResTable::Header 1238{ 1239 Header(ResTable* _owner) : owner(_owner), ownedData(NULL), header(NULL) { } 1240 1241 ResTable* const owner; 1242 void* ownedData; 1243 const ResTable_header* header; 1244 size_t size; 1245 const uint8_t* dataEnd; 1246 size_t index; 1247 void* cookie; 1248 1249 ResStringPool values; 1250}; 1251 1252struct ResTable::Type 1253{ 1254 Type(const Header* _header, const Package* _package, size_t count) 1255 : header(_header), package(_package), entryCount(count), 1256 typeSpec(NULL), typeSpecFlags(NULL) { } 1257 const Header* const header; 1258 const Package* const package; 1259 const size_t entryCount; 1260 const ResTable_typeSpec* typeSpec; 1261 const uint32_t* typeSpecFlags; 1262 Vector<const ResTable_type*> configs; 1263}; 1264 1265struct ResTable::Package 1266{ 1267 Package(ResTable* _owner, const Header* _header, const ResTable_package* _package) 1268 : owner(_owner), header(_header), package(_package) { } 1269 ~Package() 1270 { 1271 size_t i = types.size(); 1272 while (i > 0) { 1273 i--; 1274 delete types[i]; 1275 } 1276 } 1277 1278 ResTable* const owner; 1279 const Header* const header; 1280 const ResTable_package* const package; 1281 Vector<Type*> types; 1282 1283 ResStringPool typeStrings; 1284 ResStringPool keyStrings; 1285 1286 const Type* getType(size_t idx) const { 1287 return idx < types.size() ? types[idx] : NULL; 1288 } 1289}; 1290 1291// A group of objects describing a particular resource package. 1292// The first in 'package' is always the root object (from the resource 1293// table that defined the package); the ones after are skins on top of it. 1294struct ResTable::PackageGroup 1295{ 1296 PackageGroup(ResTable* _owner, const String16& _name, uint32_t _id) 1297 : owner(_owner), name(_name), id(_id), typeCount(0), bags(NULL) { } 1298 ~PackageGroup() { 1299 clearBagCache(); 1300 const size_t N = packages.size(); 1301 for (size_t i=0; i<N; i++) { 1302 Package* pkg = packages[i]; 1303 if (pkg->owner == owner) { 1304 delete pkg; 1305 } 1306 } 1307 } 1308 1309 void clearBagCache() { 1310 if (bags) { 1311 TABLE_NOISY(printf("bags=%p\n", bags)); 1312 Package* pkg = packages[0]; 1313 TABLE_NOISY(printf("typeCount=%x\n", typeCount)); 1314 for (size_t i=0; i<typeCount; i++) { 1315 TABLE_NOISY(printf("type=%d\n", i)); 1316 const Type* type = pkg->getType(i); 1317 if (type != NULL) { 1318 bag_set** typeBags = bags[i]; 1319 TABLE_NOISY(printf("typeBags=%p\n", typeBags)); 1320 if (typeBags) { 1321 TABLE_NOISY(printf("type->entryCount=%x\n", type->entryCount)); 1322 const size_t N = type->entryCount; 1323 for (size_t j=0; j<N; j++) { 1324 if (typeBags[j] && typeBags[j] != (bag_set*)0xFFFFFFFF) 1325 free(typeBags[j]); 1326 } 1327 free(typeBags); 1328 } 1329 } 1330 } 1331 free(bags); 1332 bags = NULL; 1333 } 1334 } 1335 1336 ResTable* const owner; 1337 String16 const name; 1338 uint32_t const id; 1339 Vector<Package*> packages; 1340 1341 // This is for finding typeStrings and other common package stuff. 1342 Package* basePackage; 1343 1344 // For quick access. 1345 size_t typeCount; 1346 1347 // Computed attribute bags, first indexed by the type and second 1348 // by the entry in that type. 1349 bag_set*** bags; 1350}; 1351 1352struct ResTable::bag_set 1353{ 1354 size_t numAttrs; // number in array 1355 size_t availAttrs; // total space in array 1356 uint32_t typeSpecFlags; 1357 // Followed by 'numAttr' bag_entry structures. 1358}; 1359 1360ResTable::Theme::Theme(const ResTable& table) 1361 : mTable(table) 1362{ 1363 memset(mPackages, 0, sizeof(mPackages)); 1364} 1365 1366ResTable::Theme::~Theme() 1367{ 1368 for (size_t i=0; i<Res_MAXPACKAGE; i++) { 1369 package_info* pi = mPackages[i]; 1370 if (pi != NULL) { 1371 free_package(pi); 1372 } 1373 } 1374} 1375 1376void ResTable::Theme::free_package(package_info* pi) 1377{ 1378 for (size_t j=0; j<pi->numTypes; j++) { 1379 theme_entry* te = pi->types[j].entries; 1380 if (te != NULL) { 1381 free(te); 1382 } 1383 } 1384 free(pi); 1385} 1386 1387ResTable::Theme::package_info* ResTable::Theme::copy_package(package_info* pi) 1388{ 1389 package_info* newpi = (package_info*)malloc( 1390 sizeof(package_info) + (pi->numTypes*sizeof(type_info))); 1391 newpi->numTypes = pi->numTypes; 1392 for (size_t j=0; j<newpi->numTypes; j++) { 1393 size_t cnt = pi->types[j].numEntries; 1394 newpi->types[j].numEntries = cnt; 1395 theme_entry* te = pi->types[j].entries; 1396 if (te != NULL) { 1397 theme_entry* newte = (theme_entry*)malloc(cnt*sizeof(theme_entry)); 1398 newpi->types[j].entries = newte; 1399 memcpy(newte, te, cnt*sizeof(theme_entry)); 1400 } else { 1401 newpi->types[j].entries = NULL; 1402 } 1403 } 1404 return newpi; 1405} 1406 1407status_t ResTable::Theme::applyStyle(uint32_t resID, bool force) 1408{ 1409 const bag_entry* bag; 1410 uint32_t bagTypeSpecFlags = 0; 1411 mTable.lock(); 1412 const ssize_t N = mTable.getBagLocked(resID, &bag, &bagTypeSpecFlags); 1413 TABLE_NOISY(LOGV("Applying style 0x%08x to theme %p, count=%d", resID, this, N)); 1414 if (N < 0) { 1415 mTable.unlock(); 1416 return N; 1417 } 1418 1419 uint32_t curPackage = 0xffffffff; 1420 ssize_t curPackageIndex = 0; 1421 package_info* curPI = NULL; 1422 uint32_t curType = 0xffffffff; 1423 size_t numEntries = 0; 1424 theme_entry* curEntries = NULL; 1425 1426 const bag_entry* end = bag + N; 1427 while (bag < end) { 1428 const uint32_t attrRes = bag->map.name.ident; 1429 const uint32_t p = Res_GETPACKAGE(attrRes); 1430 const uint32_t t = Res_GETTYPE(attrRes); 1431 const uint32_t e = Res_GETENTRY(attrRes); 1432 1433 if (curPackage != p) { 1434 const ssize_t pidx = mTable.getResourcePackageIndex(attrRes); 1435 if (pidx < 0) { 1436 LOGE("Style contains key with bad package: 0x%08x\n", attrRes); 1437 bag++; 1438 continue; 1439 } 1440 curPackage = p; 1441 curPackageIndex = pidx; 1442 curPI = mPackages[pidx]; 1443 if (curPI == NULL) { 1444 PackageGroup* const grp = mTable.mPackageGroups[pidx]; 1445 int cnt = grp->typeCount; 1446 curPI = (package_info*)malloc( 1447 sizeof(package_info) + (cnt*sizeof(type_info))); 1448 curPI->numTypes = cnt; 1449 memset(curPI->types, 0, cnt*sizeof(type_info)); 1450 mPackages[pidx] = curPI; 1451 } 1452 curType = 0xffffffff; 1453 } 1454 if (curType != t) { 1455 if (t >= curPI->numTypes) { 1456 LOGE("Style contains key with bad type: 0x%08x\n", attrRes); 1457 bag++; 1458 continue; 1459 } 1460 curType = t; 1461 curEntries = curPI->types[t].entries; 1462 if (curEntries == NULL) { 1463 PackageGroup* const grp = mTable.mPackageGroups[curPackageIndex]; 1464 const Type* type = grp->packages[0]->getType(t); 1465 int cnt = type != NULL ? type->entryCount : 0; 1466 curEntries = (theme_entry*)malloc(cnt*sizeof(theme_entry)); 1467 memset(curEntries, Res_value::TYPE_NULL, cnt*sizeof(theme_entry)); 1468 curPI->types[t].numEntries = cnt; 1469 curPI->types[t].entries = curEntries; 1470 } 1471 numEntries = curPI->types[t].numEntries; 1472 } 1473 if (e >= numEntries) { 1474 LOGE("Style contains key with bad entry: 0x%08x\n", attrRes); 1475 bag++; 1476 continue; 1477 } 1478 theme_entry* curEntry = curEntries + e; 1479 TABLE_NOISY(LOGV("Attr 0x%08x: type=0x%x, data=0x%08x; curType=0x%x", 1480 attrRes, bag->map.value.dataType, bag->map.value.data, 1481 curEntry->value.dataType)); 1482 if (force || curEntry->value.dataType == Res_value::TYPE_NULL) { 1483 curEntry->stringBlock = bag->stringBlock; 1484 curEntry->typeSpecFlags |= bagTypeSpecFlags; 1485 curEntry->value = bag->map.value; 1486 } 1487 1488 bag++; 1489 } 1490 1491 mTable.unlock(); 1492 1493 //LOGI("Applying style 0x%08x (force=%d) theme %p...\n", resID, force, this); 1494 //dumpToLog(); 1495 1496 return NO_ERROR; 1497} 1498 1499status_t ResTable::Theme::setTo(const Theme& other) 1500{ 1501 //LOGI("Setting theme %p from theme %p...\n", this, &other); 1502 //dumpToLog(); 1503 //other.dumpToLog(); 1504 1505 if (&mTable == &other.mTable) { 1506 for (size_t i=0; i<Res_MAXPACKAGE; i++) { 1507 if (mPackages[i] != NULL) { 1508 free_package(mPackages[i]); 1509 } 1510 if (other.mPackages[i] != NULL) { 1511 mPackages[i] = copy_package(other.mPackages[i]); 1512 } else { 1513 mPackages[i] = NULL; 1514 } 1515 } 1516 } else { 1517 // @todo: need to really implement this, not just copy 1518 // the system package (which is still wrong because it isn't 1519 // fixing up resource references). 1520 for (size_t i=0; i<Res_MAXPACKAGE; i++) { 1521 if (mPackages[i] != NULL) { 1522 free_package(mPackages[i]); 1523 } 1524 if (i == 0 && other.mPackages[i] != NULL) { 1525 mPackages[i] = copy_package(other.mPackages[i]); 1526 } else { 1527 mPackages[i] = NULL; 1528 } 1529 } 1530 } 1531 1532 //LOGI("Final theme:"); 1533 //dumpToLog(); 1534 1535 return NO_ERROR; 1536} 1537 1538ssize_t ResTable::Theme::getAttribute(uint32_t resID, Res_value* outValue, 1539 uint32_t* outTypeSpecFlags) const 1540{ 1541 int cnt = 20; 1542 1543 if (outTypeSpecFlags != NULL) *outTypeSpecFlags = 0; 1544 1545 do { 1546 const ssize_t p = mTable.getResourcePackageIndex(resID); 1547 const uint32_t t = Res_GETTYPE(resID); 1548 const uint32_t e = Res_GETENTRY(resID); 1549 1550 TABLE_THEME(LOGI("Looking up attr 0x%08x in theme %p", resID, this)); 1551 1552 if (p >= 0) { 1553 const package_info* const pi = mPackages[p]; 1554 TABLE_THEME(LOGI("Found package: %p", pi)); 1555 if (pi != NULL) { 1556 TABLE_THEME(LOGI("Desired type index is %ld in avail %d", t, pi->numTypes)); 1557 if (t < pi->numTypes) { 1558 const type_info& ti = pi->types[t]; 1559 TABLE_THEME(LOGI("Desired entry index is %ld in avail %d", e, ti.numEntries)); 1560 if (e < ti.numEntries) { 1561 const theme_entry& te = ti.entries[e]; 1562 if (outTypeSpecFlags != NULL) { 1563 *outTypeSpecFlags |= te.typeSpecFlags; 1564 } 1565 TABLE_THEME(LOGI("Theme value: type=0x%x, data=0x%08x", 1566 te.value.dataType, te.value.data)); 1567 const uint8_t type = te.value.dataType; 1568 if (type == Res_value::TYPE_ATTRIBUTE) { 1569 if (cnt > 0) { 1570 cnt--; 1571 resID = te.value.data; 1572 continue; 1573 } 1574 LOGW("Too many attribute references, stopped at: 0x%08x\n", resID); 1575 return BAD_INDEX; 1576 } else if (type != Res_value::TYPE_NULL) { 1577 *outValue = te.value; 1578 return te.stringBlock; 1579 } 1580 return BAD_INDEX; 1581 } 1582 } 1583 } 1584 } 1585 break; 1586 1587 } while (true); 1588 1589 return BAD_INDEX; 1590} 1591 1592ssize_t ResTable::Theme::resolveAttributeReference(Res_value* inOutValue, 1593 ssize_t blockIndex, uint32_t* outLastRef, 1594 uint32_t* inoutTypeSpecFlags, ResTable_config* inoutConfig) const 1595{ 1596 //printf("Resolving type=0x%x\n", inOutValue->dataType); 1597 if (inOutValue->dataType == Res_value::TYPE_ATTRIBUTE) { 1598 uint32_t newTypeSpecFlags; 1599 blockIndex = getAttribute(inOutValue->data, inOutValue, &newTypeSpecFlags); 1600 TABLE_THEME(LOGI("Resolving attr reference: blockIndex=%d, type=0x%x, data=%p\n", 1601 (int)blockIndex, (int)inOutValue->dataType, (void*)inOutValue->data)); 1602 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newTypeSpecFlags; 1603 //printf("Retrieved attribute new type=0x%x\n", inOutValue->dataType); 1604 if (blockIndex < 0) { 1605 return blockIndex; 1606 } 1607 } 1608 return mTable.resolveReference(inOutValue, blockIndex, outLastRef, 1609 inoutTypeSpecFlags, inoutConfig); 1610} 1611 1612void ResTable::Theme::dumpToLog() const 1613{ 1614 LOGI("Theme %p:\n", this); 1615 for (size_t i=0; i<Res_MAXPACKAGE; i++) { 1616 package_info* pi = mPackages[i]; 1617 if (pi == NULL) continue; 1618 1619 LOGI(" Package #0x%02x:\n", (int)(i+1)); 1620 for (size_t j=0; j<pi->numTypes; j++) { 1621 type_info& ti = pi->types[j]; 1622 if (ti.numEntries == 0) continue; 1623 1624 LOGI(" Type #0x%02x:\n", (int)(j+1)); 1625 for (size_t k=0; k<ti.numEntries; k++) { 1626 theme_entry& te = ti.entries[k]; 1627 if (te.value.dataType == Res_value::TYPE_NULL) continue; 1628 LOGI(" 0x%08x: t=0x%x, d=0x%08x (block=%d)\n", 1629 (int)Res_MAKEID(i, j, k), 1630 te.value.dataType, (int)te.value.data, (int)te.stringBlock); 1631 } 1632 } 1633 } 1634} 1635 1636ResTable::ResTable() 1637 : mError(NO_INIT) 1638{ 1639 memset(&mParams, 0, sizeof(mParams)); 1640 memset(mPackageMap, 0, sizeof(mPackageMap)); 1641 //LOGI("Creating ResTable %p\n", this); 1642} 1643 1644ResTable::ResTable(const void* data, size_t size, void* cookie, bool copyData) 1645 : mError(NO_INIT) 1646{ 1647 memset(&mParams, 0, sizeof(mParams)); 1648 memset(mPackageMap, 0, sizeof(mPackageMap)); 1649 add(data, size, cookie, copyData); 1650 LOG_FATAL_IF(mError != NO_ERROR, "Error parsing resource table"); 1651 //LOGI("Creating ResTable %p\n", this); 1652} 1653 1654ResTable::~ResTable() 1655{ 1656 //LOGI("Destroying ResTable in %p\n", this); 1657 uninit(); 1658} 1659 1660inline ssize_t ResTable::getResourcePackageIndex(uint32_t resID) const 1661{ 1662 return ((ssize_t)mPackageMap[Res_GETPACKAGE(resID)+1])-1; 1663} 1664 1665status_t ResTable::add(const void* data, size_t size, void* cookie, bool copyData) 1666{ 1667 return add(data, size, cookie, NULL, copyData); 1668} 1669 1670status_t ResTable::add(Asset* asset, void* cookie, bool copyData) 1671{ 1672 const void* data = asset->getBuffer(true); 1673 if (data == NULL) { 1674 LOGW("Unable to get buffer of resource asset file"); 1675 return UNKNOWN_ERROR; 1676 } 1677 size_t size = (size_t)asset->getLength(); 1678 return add(data, size, cookie, asset, copyData); 1679} 1680 1681status_t ResTable::add(ResTable* src) 1682{ 1683 mError = src->mError; 1684 1685 for (size_t i=0; i<src->mHeaders.size(); i++) { 1686 mHeaders.add(src->mHeaders[i]); 1687 } 1688 1689 for (size_t i=0; i<src->mPackageGroups.size(); i++) { 1690 PackageGroup* srcPg = src->mPackageGroups[i]; 1691 PackageGroup* pg = new PackageGroup(this, srcPg->name, srcPg->id); 1692 for (size_t j=0; j<srcPg->packages.size(); j++) { 1693 pg->packages.add(srcPg->packages[j]); 1694 } 1695 pg->basePackage = srcPg->basePackage; 1696 pg->typeCount = srcPg->typeCount; 1697 mPackageGroups.add(pg); 1698 } 1699 1700 memcpy(mPackageMap, src->mPackageMap, sizeof(mPackageMap)); 1701 1702 return mError; 1703} 1704 1705status_t ResTable::add(const void* data, size_t size, void* cookie, 1706 Asset* asset, bool copyData) 1707{ 1708 if (!data) return NO_ERROR; 1709 Header* header = new Header(this); 1710 header->index = mHeaders.size(); 1711 header->cookie = cookie; 1712 mHeaders.add(header); 1713 1714 const bool notDeviceEndian = htods(0xf0) != 0xf0; 1715 1716 LOAD_TABLE_NOISY( 1717 LOGV("Adding resources to ResTable: data=%p, size=0x%x, cookie=%p, asset=%p, copy=%d\n", 1718 data, size, cookie, asset, copyData)); 1719 1720 if (copyData || notDeviceEndian) { 1721 header->ownedData = malloc(size); 1722 if (header->ownedData == NULL) { 1723 return (mError=NO_MEMORY); 1724 } 1725 memcpy(header->ownedData, data, size); 1726 data = header->ownedData; 1727 } 1728 1729 header->header = (const ResTable_header*)data; 1730 header->size = dtohl(header->header->header.size); 1731 //LOGI("Got size 0x%x, again size 0x%x, raw size 0x%x\n", header->size, 1732 // dtohl(header->header->header.size), header->header->header.size); 1733 LOAD_TABLE_NOISY(LOGV("Loading ResTable @%p:\n", header->header)); 1734 LOAD_TABLE_NOISY(printHexData(2, header->header, header->size < 256 ? header->size : 256, 1735 16, 16, 0, false, printToLogFunc)); 1736 if (dtohs(header->header->header.headerSize) > header->size 1737 || header->size > size) { 1738 LOGW("Bad resource table: header size 0x%x or total size 0x%x is larger than data size 0x%x\n", 1739 (int)dtohs(header->header->header.headerSize), 1740 (int)header->size, (int)size); 1741 return (mError=BAD_TYPE); 1742 } 1743 if (((dtohs(header->header->header.headerSize)|header->size)&0x3) != 0) { 1744 LOGW("Bad resource table: header size 0x%x or total size 0x%x is not on an integer boundary\n", 1745 (int)dtohs(header->header->header.headerSize), 1746 (int)header->size); 1747 return (mError=BAD_TYPE); 1748 } 1749 header->dataEnd = ((const uint8_t*)header->header) + header->size; 1750 1751 // Iterate through all chunks. 1752 size_t curPackage = 0; 1753 1754 const ResChunk_header* chunk = 1755 (const ResChunk_header*)(((const uint8_t*)header->header) 1756 + dtohs(header->header->header.headerSize)); 1757 while (((const uint8_t*)chunk) <= (header->dataEnd-sizeof(ResChunk_header)) && 1758 ((const uint8_t*)chunk) <= (header->dataEnd-dtohl(chunk->size))) { 1759 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), header->dataEnd, "ResTable"); 1760 if (err != NO_ERROR) { 1761 return (mError=err); 1762 } 1763 TABLE_NOISY(LOGV("Chunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n", 1764 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size), 1765 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)))); 1766 const size_t csize = dtohl(chunk->size); 1767 const uint16_t ctype = dtohs(chunk->type); 1768 if (ctype == RES_STRING_POOL_TYPE) { 1769 if (header->values.getError() != NO_ERROR) { 1770 // Only use the first string chunk; ignore any others that 1771 // may appear. 1772 status_t err = header->values.setTo(chunk, csize); 1773 if (err != NO_ERROR) { 1774 return (mError=err); 1775 } 1776 } else { 1777 LOGW("Multiple string chunks found in resource table."); 1778 } 1779 } else if (ctype == RES_TABLE_PACKAGE_TYPE) { 1780 if (curPackage >= dtohl(header->header->packageCount)) { 1781 LOGW("More package chunks were found than the %d declared in the header.", 1782 dtohl(header->header->packageCount)); 1783 return (mError=BAD_TYPE); 1784 } 1785 if (parsePackage((ResTable_package*)chunk, header) != NO_ERROR) { 1786 return mError; 1787 } 1788 curPackage++; 1789 } else { 1790 LOGW("Unknown chunk type %p in table at %p.\n", 1791 (void*)(int)(ctype), 1792 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header))); 1793 } 1794 chunk = (const ResChunk_header*) 1795 (((const uint8_t*)chunk) + csize); 1796 } 1797 1798 if (curPackage < dtohl(header->header->packageCount)) { 1799 LOGW("Fewer package chunks (%d) were found than the %d declared in the header.", 1800 (int)curPackage, dtohl(header->header->packageCount)); 1801 return (mError=BAD_TYPE); 1802 } 1803 mError = header->values.getError(); 1804 if (mError != NO_ERROR) { 1805 LOGW("No string values found in resource table!"); 1806 } 1807 TABLE_NOISY(LOGV("Returning from add with mError=%d\n", mError)); 1808 return mError; 1809} 1810 1811status_t ResTable::getError() const 1812{ 1813 return mError; 1814} 1815 1816void ResTable::uninit() 1817{ 1818 mError = NO_INIT; 1819 size_t N = mPackageGroups.size(); 1820 for (size_t i=0; i<N; i++) { 1821 PackageGroup* g = mPackageGroups[i]; 1822 delete g; 1823 } 1824 N = mHeaders.size(); 1825 for (size_t i=0; i<N; i++) { 1826 Header* header = mHeaders[i]; 1827 if (header->owner == this) { 1828 if (header->ownedData) { 1829 free(header->ownedData); 1830 } 1831 delete header; 1832 } 1833 } 1834 1835 mPackageGroups.clear(); 1836 mHeaders.clear(); 1837} 1838 1839bool ResTable::getResourceName(uint32_t resID, resource_name* outName) const 1840{ 1841 if (mError != NO_ERROR) { 1842 return false; 1843 } 1844 1845 const ssize_t p = getResourcePackageIndex(resID); 1846 const int t = Res_GETTYPE(resID); 1847 const int e = Res_GETENTRY(resID); 1848 1849 if (p < 0) { 1850 if (Res_GETPACKAGE(resID)+1 == 0) { 1851 LOGW("No package identifier when getting name for resource number 0x%08x", resID); 1852 } else { 1853 LOGW("Resources don't contain package for resource number 0x%08x", resID); 1854 } 1855 return false; 1856 } 1857 if (t < 0) { 1858 LOGW("No type identifier when getting name for resource number 0x%08x", resID); 1859 return false; 1860 } 1861 1862 const PackageGroup* const grp = mPackageGroups[p]; 1863 if (grp == NULL) { 1864 LOGW("Bad identifier when getting name for resource number 0x%08x", resID); 1865 return false; 1866 } 1867 if (grp->packages.size() > 0) { 1868 const Package* const package = grp->packages[0]; 1869 1870 const ResTable_type* type; 1871 const ResTable_entry* entry; 1872 ssize_t offset = getEntry(package, t, e, NULL, &type, &entry, NULL); 1873 if (offset <= 0) { 1874 return false; 1875 } 1876 1877 outName->package = grp->name.string(); 1878 outName->packageLen = grp->name.size(); 1879 outName->type = grp->basePackage->typeStrings.stringAt(t, &outName->typeLen); 1880 outName->name = grp->basePackage->keyStrings.stringAt( 1881 dtohl(entry->key.index), &outName->nameLen); 1882 return true; 1883 } 1884 1885 return false; 1886} 1887 1888ssize_t ResTable::getResource(uint32_t resID, Res_value* outValue, bool mayBeBag, 1889 uint32_t* outSpecFlags, ResTable_config* outConfig) const 1890{ 1891 if (mError != NO_ERROR) { 1892 return mError; 1893 } 1894 1895 const ssize_t p = getResourcePackageIndex(resID); 1896 const int t = Res_GETTYPE(resID); 1897 const int e = Res_GETENTRY(resID); 1898 1899 if (p < 0) { 1900 if (Res_GETPACKAGE(resID)+1 == 0) { 1901 LOGW("No package identifier when getting name for resource number 0x%08x", resID); 1902 } else { 1903 LOGW("Resources don't contain package for resource number 0x%08x", resID); 1904 } 1905 return BAD_INDEX; 1906 } 1907 if (t < 0) { 1908 LOGW("No type identifier when getting value for resource number 0x%08x", resID); 1909 return BAD_INDEX; 1910 } 1911 1912 const Res_value* bestValue = NULL; 1913 const Package* bestPackage = NULL; 1914 ResTable_config bestItem; 1915 memset(&bestItem, 0, sizeof(bestItem)); // make the compiler shut up 1916 1917 if (outSpecFlags != NULL) *outSpecFlags = 0; 1918 1919 // Look through all resource packages, starting with the most 1920 // recently added. 1921 const PackageGroup* const grp = mPackageGroups[p]; 1922 if (grp == NULL) { 1923 LOGW("Bad identifier when getting value for resource number 0x%08x", resID); 1924 return false; 1925 } 1926 size_t ip = grp->packages.size(); 1927 while (ip > 0) { 1928 ip--; 1929 1930 const Package* const package = grp->packages[ip]; 1931 1932 const ResTable_type* type; 1933 const ResTable_entry* entry; 1934 const Type* typeClass; 1935 ssize_t offset = getEntry(package, t, e, &mParams, &type, &entry, &typeClass); 1936 if (offset <= 0) { 1937 if (offset < 0) { 1938 LOGW("Failure getting entry for 0x%08x (t=%d e=%d) in package %d: 0x%08x\n", 1939 resID, t, e, (int)ip, (int)offset); 1940 return offset; 1941 } 1942 continue; 1943 } 1944 1945 if ((dtohs(entry->flags)&entry->FLAG_COMPLEX) != 0) { 1946 if (!mayBeBag) { 1947 LOGW("Requesting resource %p failed because it is complex\n", 1948 (void*)resID); 1949 } 1950 continue; 1951 } 1952 1953 TABLE_NOISY(aout << "Resource type data: " 1954 << HexDump(type, dtohl(type->header.size)) << endl); 1955 1956 if ((size_t)offset > (dtohl(type->header.size)-sizeof(Res_value))) { 1957 LOGW("ResTable_item at %d is beyond type chunk data %d", 1958 (int)offset, dtohl(type->header.size)); 1959 return BAD_TYPE; 1960 } 1961 1962 const Res_value* item = 1963 (const Res_value*)(((const uint8_t*)type) + offset); 1964 ResTable_config thisConfig; 1965 thisConfig.copyFromDtoH(type->config); 1966 1967 if (outSpecFlags != NULL) { 1968 if (typeClass->typeSpecFlags != NULL) { 1969 *outSpecFlags |= dtohl(typeClass->typeSpecFlags[e]); 1970 } else { 1971 *outSpecFlags = -1; 1972 } 1973 } 1974 1975 if (bestPackage != NULL && bestItem.isMoreSpecificThan(thisConfig)) { 1976 continue; 1977 } 1978 1979 bestItem = thisConfig; 1980 bestValue = item; 1981 bestPackage = package; 1982 } 1983 1984 TABLE_NOISY(printf("Found result: package %p\n", bestPackage)); 1985 1986 if (bestValue) { 1987 outValue->size = dtohs(bestValue->size); 1988 outValue->res0 = bestValue->res0; 1989 outValue->dataType = bestValue->dataType; 1990 outValue->data = dtohl(bestValue->data); 1991 if (outConfig != NULL) { 1992 *outConfig = bestItem; 1993 } 1994 TABLE_NOISY(size_t len; 1995 printf("Found value: pkg=%d, type=%d, str=%s, int=%d\n", 1996 bestPackage->header->index, 1997 outValue->dataType, 1998 outValue->dataType == bestValue->TYPE_STRING 1999 ? String8(bestPackage->header->values.stringAt( 2000 outValue->data, &len)).string() 2001 : "", 2002 outValue->data)); 2003 return bestPackage->header->index; 2004 } 2005 2006 return BAD_INDEX; 2007} 2008 2009ssize_t ResTable::resolveReference(Res_value* value, ssize_t blockIndex, 2010 uint32_t* outLastRef, uint32_t* inoutTypeSpecFlags, 2011 ResTable_config* outConfig) const 2012{ 2013 int count=0; 2014 while (blockIndex >= 0 && value->dataType == value->TYPE_REFERENCE 2015 && value->data != 0 && count < 20) { 2016 if (outLastRef) *outLastRef = value->data; 2017 uint32_t lastRef = value->data; 2018 uint32_t newFlags = 0; 2019 const ssize_t newIndex = getResource(value->data, value, true, &newFlags, 2020 outConfig); 2021 TABLE_THEME(LOGI("Resolving reference %p: newIndex=%d, type=0x%x, data=%p\n", 2022 (void*)lastRef, (int)newIndex, (int)value->dataType, (void*)value->data)); 2023 //printf("Getting reference 0x%08x: newIndex=%d\n", value->data, newIndex); 2024 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newFlags; 2025 if (newIndex < 0) { 2026 // This can fail if the resource being referenced is a style... 2027 // in this case, just return the reference, and expect the 2028 // caller to deal with. 2029 return blockIndex; 2030 } 2031 blockIndex = newIndex; 2032 count++; 2033 } 2034 return blockIndex; 2035} 2036 2037const char16_t* ResTable::valueToString( 2038 const Res_value* value, size_t stringBlock, 2039 char16_t tmpBuffer[TMP_BUFFER_SIZE], size_t* outLen) 2040{ 2041 if (!value) { 2042 return NULL; 2043 } 2044 if (value->dataType == value->TYPE_STRING) { 2045 return getTableStringBlock(stringBlock)->stringAt(value->data, outLen); 2046 } 2047 // XXX do int to string conversions. 2048 return NULL; 2049} 2050 2051ssize_t ResTable::lockBag(uint32_t resID, const bag_entry** outBag) const 2052{ 2053 mLock.lock(); 2054 ssize_t err = getBagLocked(resID, outBag); 2055 if (err < NO_ERROR) { 2056 //printf("*** get failed! unlocking\n"); 2057 mLock.unlock(); 2058 } 2059 return err; 2060} 2061 2062void ResTable::unlockBag(const bag_entry* bag) const 2063{ 2064 //printf("<<< unlockBag %p\n", this); 2065 mLock.unlock(); 2066} 2067 2068void ResTable::lock() const 2069{ 2070 mLock.lock(); 2071} 2072 2073void ResTable::unlock() const 2074{ 2075 mLock.unlock(); 2076} 2077 2078ssize_t ResTable::getBagLocked(uint32_t resID, const bag_entry** outBag, 2079 uint32_t* outTypeSpecFlags) const 2080{ 2081 if (mError != NO_ERROR) { 2082 return mError; 2083 } 2084 2085 const ssize_t p = getResourcePackageIndex(resID); 2086 const int t = Res_GETTYPE(resID); 2087 const int e = Res_GETENTRY(resID); 2088 2089 if (p < 0) { 2090 LOGW("Invalid package identifier when getting bag for resource number 0x%08x", resID); 2091 return BAD_INDEX; 2092 } 2093 if (t < 0) { 2094 LOGW("No type identifier when getting bag for resource number 0x%08x", resID); 2095 return BAD_INDEX; 2096 } 2097 2098 //printf("Get bag: id=0x%08x, p=%d, t=%d\n", resID, p, t); 2099 PackageGroup* const grp = mPackageGroups[p]; 2100 if (grp == NULL) { 2101 LOGW("Bad identifier when getting bag for resource number 0x%08x", resID); 2102 return false; 2103 } 2104 2105 if (t >= (int)grp->typeCount) { 2106 LOGW("Type identifier 0x%x is larger than type count 0x%x", 2107 t+1, (int)grp->typeCount); 2108 return BAD_INDEX; 2109 } 2110 2111 const Package* const basePackage = grp->packages[0]; 2112 2113 const Type* const typeConfigs = basePackage->getType(t); 2114 2115 const size_t NENTRY = typeConfigs->entryCount; 2116 if (e >= (int)NENTRY) { 2117 LOGW("Entry identifier 0x%x is larger than entry count 0x%x", 2118 e, (int)typeConfigs->entryCount); 2119 return BAD_INDEX; 2120 } 2121 2122 // First see if we've already computed this bag... 2123 if (grp->bags) { 2124 bag_set** typeSet = grp->bags[t]; 2125 if (typeSet) { 2126 bag_set* set = typeSet[e]; 2127 if (set) { 2128 if (set != (bag_set*)0xFFFFFFFF) { 2129 if (outTypeSpecFlags != NULL) { 2130 *outTypeSpecFlags = set->typeSpecFlags; 2131 } 2132 *outBag = (bag_entry*)(set+1); 2133 //LOGI("Found existing bag for: %p\n", (void*)resID); 2134 return set->numAttrs; 2135 } 2136 LOGW("Attempt to retrieve bag 0x%08x which is invalid or in a cycle.", 2137 resID); 2138 return BAD_INDEX; 2139 } 2140 } 2141 } 2142 2143 // Bag not found, we need to compute it! 2144 if (!grp->bags) { 2145 grp->bags = (bag_set***)malloc(sizeof(bag_set*)*grp->typeCount); 2146 if (!grp->bags) return NO_MEMORY; 2147 memset(grp->bags, 0, sizeof(bag_set*)*grp->typeCount); 2148 } 2149 2150 bag_set** typeSet = grp->bags[t]; 2151 if (!typeSet) { 2152 typeSet = (bag_set**)malloc(sizeof(bag_set*)*NENTRY); 2153 if (!typeSet) return NO_MEMORY; 2154 memset(typeSet, 0, sizeof(bag_set*)*NENTRY); 2155 grp->bags[t] = typeSet; 2156 } 2157 2158 // Mark that we are currently working on this one. 2159 typeSet[e] = (bag_set*)0xFFFFFFFF; 2160 2161 // This is what we are building. 2162 bag_set* set = NULL; 2163 2164 TABLE_NOISY(LOGI("Building bag: %p\n", (void*)resID)); 2165 2166 // Now collect all bag attributes from all packages. 2167 size_t ip = grp->packages.size(); 2168 while (ip > 0) { 2169 ip--; 2170 2171 const Package* const package = grp->packages[ip]; 2172 2173 const ResTable_type* type; 2174 const ResTable_entry* entry; 2175 const Type* typeClass; 2176 LOGV("Getting entry pkg=%p, t=%d, e=%d\n", package, t, e); 2177 ssize_t offset = getEntry(package, t, e, &mParams, &type, &entry, &typeClass); 2178 LOGV("Resulting offset=%d\n", offset); 2179 if (offset <= 0) { 2180 if (offset < 0) { 2181 if (set) free(set); 2182 return offset; 2183 } 2184 continue; 2185 } 2186 2187 if ((dtohs(entry->flags)&entry->FLAG_COMPLEX) == 0) { 2188 LOGW("Skipping entry %p in package table %d because it is not complex!\n", 2189 (void*)resID, (int)ip); 2190 continue; 2191 } 2192 2193 const uint16_t entrySize = dtohs(entry->size); 2194 const uint32_t parent = entrySize >= sizeof(ResTable_map_entry) 2195 ? dtohl(((const ResTable_map_entry*)entry)->parent.ident) : 0; 2196 const uint32_t count = entrySize >= sizeof(ResTable_map_entry) 2197 ? dtohl(((const ResTable_map_entry*)entry)->count) : 0; 2198 2199 size_t N = count; 2200 2201 TABLE_NOISY(LOGI("Found map: size=%p parent=%p count=%d\n", 2202 entrySize, parent, count)); 2203 2204 if (set == NULL) { 2205 // If this map inherits from another, we need to start 2206 // with its parent's values. Otherwise start out empty. 2207 TABLE_NOISY(printf("Creating new bag, entrySize=0x%08x, parent=0x%08x\n", 2208 entrySize, parent)); 2209 if (parent) { 2210 const bag_entry* parentBag; 2211 uint32_t parentTypeSpecFlags = 0; 2212 const ssize_t NP = getBagLocked(parent, &parentBag, &parentTypeSpecFlags); 2213 const size_t NT = ((NP >= 0) ? NP : 0) + N; 2214 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*NT); 2215 if (set == NULL) { 2216 return NO_MEMORY; 2217 } 2218 if (NP > 0) { 2219 memcpy(set+1, parentBag, NP*sizeof(bag_entry)); 2220 set->numAttrs = NP; 2221 TABLE_NOISY(LOGI("Initialized new bag with %d inherited attributes.\n", NP)); 2222 } else { 2223 TABLE_NOISY(LOGI("Initialized new bag with no inherited attributes.\n")); 2224 set->numAttrs = 0; 2225 } 2226 set->availAttrs = NT; 2227 set->typeSpecFlags = parentTypeSpecFlags; 2228 } else { 2229 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*N); 2230 if (set == NULL) { 2231 return NO_MEMORY; 2232 } 2233 set->numAttrs = 0; 2234 set->availAttrs = N; 2235 set->typeSpecFlags = 0; 2236 } 2237 } 2238 2239 if (typeClass->typeSpecFlags != NULL) { 2240 set->typeSpecFlags |= dtohl(typeClass->typeSpecFlags[e]); 2241 } else { 2242 set->typeSpecFlags = -1; 2243 } 2244 2245 // Now merge in the new attributes... 2246 ssize_t curOff = offset; 2247 const ResTable_map* map; 2248 bag_entry* entries = (bag_entry*)(set+1); 2249 size_t curEntry = 0; 2250 uint32_t pos = 0; 2251 TABLE_NOISY(LOGI("Starting with set %p, entries=%p, avail=%d\n", 2252 set, entries, set->availAttrs)); 2253 while (pos < count) { 2254 TABLE_NOISY(printf("Now at %p\n", (void*)curOff)); 2255 2256 if ((size_t)curOff > (dtohl(type->header.size)-sizeof(ResTable_map))) { 2257 LOGW("ResTable_map at %d is beyond type chunk data %d", 2258 (int)curOff, dtohl(type->header.size)); 2259 return BAD_TYPE; 2260 } 2261 map = (const ResTable_map*)(((const uint8_t*)type) + curOff); 2262 N++; 2263 2264 const uint32_t newName = htodl(map->name.ident); 2265 bool isInside; 2266 uint32_t oldName = 0; 2267 while ((isInside=(curEntry < set->numAttrs)) 2268 && (oldName=entries[curEntry].map.name.ident) < newName) { 2269 TABLE_NOISY(printf("#%d: Keeping existing attribute: 0x%08x\n", 2270 curEntry, entries[curEntry].map.name.ident)); 2271 curEntry++; 2272 } 2273 2274 if ((!isInside) || oldName != newName) { 2275 // This is a new attribute... figure out what to do with it. 2276 if (set->numAttrs >= set->availAttrs) { 2277 // Need to alloc more memory... 2278 const size_t newAvail = set->availAttrs+N; 2279 set = (bag_set*)realloc(set, 2280 sizeof(bag_set) 2281 + sizeof(bag_entry)*newAvail); 2282 if (set == NULL) { 2283 return NO_MEMORY; 2284 } 2285 set->availAttrs = newAvail; 2286 entries = (bag_entry*)(set+1); 2287 TABLE_NOISY(printf("Reallocated set %p, entries=%p, avail=%d\n", 2288 set, entries, set->availAttrs)); 2289 } 2290 if (isInside) { 2291 // Going in the middle, need to make space. 2292 memmove(entries+curEntry+1, entries+curEntry, 2293 sizeof(bag_entry)*(set->numAttrs-curEntry)); 2294 set->numAttrs++; 2295 } 2296 TABLE_NOISY(printf("#%d: Inserting new attribute: 0x%08x\n", 2297 curEntry, newName)); 2298 } else { 2299 TABLE_NOISY(printf("#%d: Replacing existing attribute: 0x%08x\n", 2300 curEntry, oldName)); 2301 } 2302 2303 bag_entry* cur = entries+curEntry; 2304 2305 cur->stringBlock = package->header->index; 2306 cur->map.name.ident = newName; 2307 cur->map.value.copyFrom_dtoh(map->value); 2308 TABLE_NOISY(printf("Setting entry #%d %p: block=%d, name=0x%08x, type=%d, data=0x%08x\n", 2309 curEntry, cur, cur->stringBlock, cur->map.name.ident, 2310 cur->map.value.dataType, cur->map.value.data)); 2311 2312 // On to the next! 2313 curEntry++; 2314 pos++; 2315 const size_t size = dtohs(map->value.size); 2316 curOff += size + sizeof(*map)-sizeof(map->value); 2317 }; 2318 if (curEntry > set->numAttrs) { 2319 set->numAttrs = curEntry; 2320 } 2321 } 2322 2323 // And this is it... 2324 typeSet[e] = set; 2325 if (set) { 2326 if (outTypeSpecFlags != NULL) { 2327 *outTypeSpecFlags = set->typeSpecFlags; 2328 } 2329 *outBag = (bag_entry*)(set+1); 2330 TABLE_NOISY(LOGI("Returning %d attrs\n", set->numAttrs)); 2331 return set->numAttrs; 2332 } 2333 return BAD_INDEX; 2334} 2335 2336void ResTable::setParameters(const ResTable_config* params) 2337{ 2338 mLock.lock(); 2339 TABLE_GETENTRY(LOGI("Setting parameters: imsi:%d/%d lang:%c%c cnt:%c%c " 2340 "orien:%d touch:%d density:%d key:%d inp:%d nav:%d w:%d h:%d\n", 2341 params->mcc, params->mnc, 2342 params->language[0] ? params->language[0] : '-', 2343 params->language[1] ? params->language[1] : '-', 2344 params->country[0] ? params->country[0] : '-', 2345 params->country[1] ? params->country[1] : '-', 2346 params->orientation, 2347 params->touchscreen, 2348 params->density, 2349 params->keyboard, 2350 params->inputFlags, 2351 params->navigation, 2352 params->screenWidth, 2353 params->screenHeight)); 2354 mParams = *params; 2355 for (size_t i=0; i<mPackageGroups.size(); i++) { 2356 TABLE_NOISY(LOGI("CLEARING BAGS FOR GROUP %d!", i)); 2357 mPackageGroups[i]->clearBagCache(); 2358 } 2359 mLock.unlock(); 2360} 2361 2362void ResTable::getParameters(ResTable_config* params) const 2363{ 2364 mLock.lock(); 2365 *params = mParams; 2366 mLock.unlock(); 2367} 2368 2369struct id_name_map { 2370 uint32_t id; 2371 size_t len; 2372 char16_t name[6]; 2373}; 2374 2375const static id_name_map ID_NAMES[] = { 2376 { ResTable_map::ATTR_TYPE, 5, { '^', 't', 'y', 'p', 'e' } }, 2377 { ResTable_map::ATTR_L10N, 5, { '^', 'l', '1', '0', 'n' } }, 2378 { ResTable_map::ATTR_MIN, 4, { '^', 'm', 'i', 'n' } }, 2379 { ResTable_map::ATTR_MAX, 4, { '^', 'm', 'a', 'x' } }, 2380 { ResTable_map::ATTR_OTHER, 6, { '^', 'o', 't', 'h', 'e', 'r' } }, 2381 { ResTable_map::ATTR_ZERO, 5, { '^', 'z', 'e', 'r', 'o' } }, 2382 { ResTable_map::ATTR_ONE, 4, { '^', 'o', 'n', 'e' } }, 2383 { ResTable_map::ATTR_TWO, 4, { '^', 't', 'w', 'o' } }, 2384 { ResTable_map::ATTR_FEW, 4, { '^', 'f', 'e', 'w' } }, 2385 { ResTable_map::ATTR_MANY, 5, { '^', 'm', 'a', 'n', 'y' } }, 2386}; 2387 2388uint32_t ResTable::identifierForName(const char16_t* name, size_t nameLen, 2389 const char16_t* type, size_t typeLen, 2390 const char16_t* package, 2391 size_t packageLen, 2392 uint32_t* outTypeSpecFlags) const 2393{ 2394 TABLE_SUPER_NOISY(printf("Identifier for name: error=%d\n", mError)); 2395 2396 // Check for internal resource identifier as the very first thing, so 2397 // that we will always find them even when there are no resources. 2398 if (name[0] == '^') { 2399 const int N = (sizeof(ID_NAMES)/sizeof(ID_NAMES[0])); 2400 size_t len; 2401 for (int i=0; i<N; i++) { 2402 const id_name_map* m = ID_NAMES + i; 2403 len = m->len; 2404 if (len != nameLen) { 2405 continue; 2406 } 2407 for (size_t j=1; j<len; j++) { 2408 if (m->name[j] != name[j]) { 2409 goto nope; 2410 } 2411 } 2412 return m->id; 2413nope: 2414 ; 2415 } 2416 if (nameLen > 7) { 2417 if (name[1] == 'i' && name[2] == 'n' 2418 && name[3] == 'd' && name[4] == 'e' && name[5] == 'x' 2419 && name[6] == '_') { 2420 int index = atoi(String8(name + 7, nameLen - 7).string()); 2421 if (Res_CHECKID(index)) { 2422 LOGW("Array resource index: %d is too large.", 2423 index); 2424 return 0; 2425 } 2426 return Res_MAKEARRAY(index); 2427 } 2428 } 2429 return 0; 2430 } 2431 2432 if (mError != NO_ERROR) { 2433 return 0; 2434 } 2435 2436 // Figure out the package and type we are looking in... 2437 2438 const char16_t* packageEnd = NULL; 2439 const char16_t* typeEnd = NULL; 2440 const char16_t* const nameEnd = name+nameLen; 2441 const char16_t* p = name; 2442 while (p < nameEnd) { 2443 if (*p == ':') packageEnd = p; 2444 else if (*p == '/') typeEnd = p; 2445 p++; 2446 } 2447 if (*name == '@') name++; 2448 if (name >= nameEnd) { 2449 return 0; 2450 } 2451 2452 if (packageEnd) { 2453 package = name; 2454 packageLen = packageEnd-name; 2455 name = packageEnd+1; 2456 } else if (!package) { 2457 return 0; 2458 } 2459 2460 if (typeEnd) { 2461 type = name; 2462 typeLen = typeEnd-name; 2463 name = typeEnd+1; 2464 } else if (!type) { 2465 return 0; 2466 } 2467 2468 if (name >= nameEnd) { 2469 return 0; 2470 } 2471 nameLen = nameEnd-name; 2472 2473 TABLE_NOISY(printf("Looking for identifier: type=%s, name=%s, package=%s\n", 2474 String8(type, typeLen).string(), 2475 String8(name, nameLen).string(), 2476 String8(package, packageLen).string())); 2477 2478 const size_t NG = mPackageGroups.size(); 2479 for (size_t ig=0; ig<NG; ig++) { 2480 const PackageGroup* group = mPackageGroups[ig]; 2481 2482 if (strzcmp16(package, packageLen, 2483 group->name.string(), group->name.size())) { 2484 TABLE_NOISY(printf("Skipping package group: %s\n", String8(group->name).string())); 2485 continue; 2486 } 2487 2488 const ssize_t ti = group->basePackage->typeStrings.indexOfString(type, typeLen); 2489 if (ti < 0) { 2490 TABLE_NOISY(printf("Type not found in package %s\n", String8(group->name).string())); 2491 continue; 2492 } 2493 2494 const ssize_t ei = group->basePackage->keyStrings.indexOfString(name, nameLen); 2495 if (ei < 0) { 2496 TABLE_NOISY(printf("Name not found in package %s\n", String8(group->name).string())); 2497 continue; 2498 } 2499 2500 TABLE_NOISY(printf("Search indices: type=%d, name=%d\n", ti, ei)); 2501 2502 const Type* const typeConfigs = group->packages[0]->getType(ti); 2503 if (typeConfigs == NULL || typeConfigs->configs.size() <= 0) { 2504 TABLE_NOISY(printf("Expected type structure not found in package %s for idnex %d\n", 2505 String8(group->name).string(), ti)); 2506 } 2507 2508 size_t NTC = typeConfigs->configs.size(); 2509 for (size_t tci=0; tci<NTC; tci++) { 2510 const ResTable_type* const ty = typeConfigs->configs[tci]; 2511 const uint32_t typeOffset = dtohl(ty->entriesStart); 2512 2513 const uint8_t* const end = ((const uint8_t*)ty) + dtohl(ty->header.size); 2514 const uint32_t* const eindex = (const uint32_t*) 2515 (((const uint8_t*)ty) + dtohs(ty->header.headerSize)); 2516 2517 const size_t NE = dtohl(ty->entryCount); 2518 for (size_t i=0; i<NE; i++) { 2519 uint32_t offset = dtohl(eindex[i]); 2520 if (offset == ResTable_type::NO_ENTRY) { 2521 continue; 2522 } 2523 2524 offset += typeOffset; 2525 2526 if (offset > (dtohl(ty->header.size)-sizeof(ResTable_entry))) { 2527 LOGW("ResTable_entry at %d is beyond type chunk data %d", 2528 offset, dtohl(ty->header.size)); 2529 return 0; 2530 } 2531 if ((offset&0x3) != 0) { 2532 LOGW("ResTable_entry at %d (pkg=%d type=%d ent=%d) is not on an integer boundary when looking for %s:%s/%s", 2533 (int)offset, (int)group->id, (int)ti+1, (int)i, 2534 String8(package, packageLen).string(), 2535 String8(type, typeLen).string(), 2536 String8(name, nameLen).string()); 2537 return 0; 2538 } 2539 2540 const ResTable_entry* const entry = (const ResTable_entry*) 2541 (((const uint8_t*)ty) + offset); 2542 if (dtohs(entry->size) < sizeof(*entry)) { 2543 LOGW("ResTable_entry size %d is too small", dtohs(entry->size)); 2544 return BAD_TYPE; 2545 } 2546 2547 TABLE_SUPER_NOISY(printf("Looking at entry #%d: want str %d, have %d\n", 2548 i, ei, dtohl(entry->key.index))); 2549 if (dtohl(entry->key.index) == (size_t)ei) { 2550 if (outTypeSpecFlags) { 2551 *outTypeSpecFlags = typeConfigs->typeSpecFlags[i]; 2552 } 2553 return Res_MAKEID(group->id-1, ti, i); 2554 } 2555 } 2556 } 2557 } 2558 2559 return 0; 2560} 2561 2562bool ResTable::expandResourceRef(const uint16_t* refStr, size_t refLen, 2563 String16* outPackage, 2564 String16* outType, 2565 String16* outName, 2566 const String16* defType, 2567 const String16* defPackage, 2568 const char** outErrorMsg) 2569{ 2570 const char16_t* packageEnd = NULL; 2571 const char16_t* typeEnd = NULL; 2572 const char16_t* p = refStr; 2573 const char16_t* const end = p + refLen; 2574 while (p < end) { 2575 if (*p == ':') packageEnd = p; 2576 else if (*p == '/') { 2577 typeEnd = p; 2578 break; 2579 } 2580 p++; 2581 } 2582 p = refStr; 2583 if (*p == '@') p++; 2584 2585 if (packageEnd) { 2586 *outPackage = String16(p, packageEnd-p); 2587 p = packageEnd+1; 2588 } else { 2589 if (!defPackage) { 2590 if (outErrorMsg) { 2591 *outErrorMsg = "No resource package specified"; 2592 } 2593 return false; 2594 } 2595 *outPackage = *defPackage; 2596 } 2597 if (typeEnd) { 2598 *outType = String16(p, typeEnd-p); 2599 p = typeEnd+1; 2600 } else { 2601 if (!defType) { 2602 if (outErrorMsg) { 2603 *outErrorMsg = "No resource type specified"; 2604 } 2605 return false; 2606 } 2607 *outType = *defType; 2608 } 2609 *outName = String16(p, end-p); 2610 return true; 2611} 2612 2613static uint32_t get_hex(char c, bool* outError) 2614{ 2615 if (c >= '0' && c <= '9') { 2616 return c - '0'; 2617 } else if (c >= 'a' && c <= 'f') { 2618 return c - 'a' + 0xa; 2619 } else if (c >= 'A' && c <= 'F') { 2620 return c - 'A' + 0xa; 2621 } 2622 *outError = true; 2623 return 0; 2624} 2625 2626struct unit_entry 2627{ 2628 const char* name; 2629 size_t len; 2630 uint8_t type; 2631 uint32_t unit; 2632 float scale; 2633}; 2634 2635static const unit_entry unitNames[] = { 2636 { "px", strlen("px"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PX, 1.0f }, 2637 { "dip", strlen("dip"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f }, 2638 { "dp", strlen("dp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f }, 2639 { "sp", strlen("sp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_SP, 1.0f }, 2640 { "pt", strlen("pt"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PT, 1.0f }, 2641 { "in", strlen("in"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_IN, 1.0f }, 2642 { "mm", strlen("mm"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_MM, 1.0f }, 2643 { "%", strlen("%"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION, 1.0f/100 }, 2644 { "%p", strlen("%p"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION_PARENT, 1.0f/100 }, 2645 { NULL, 0, 0, 0, 0 } 2646}; 2647 2648static bool parse_unit(const char* str, Res_value* outValue, 2649 float* outScale, const char** outEnd) 2650{ 2651 const char* end = str; 2652 while (*end != 0 && !isspace((unsigned char)*end)) { 2653 end++; 2654 } 2655 const size_t len = end-str; 2656 2657 const char* realEnd = end; 2658 while (*realEnd != 0 && isspace((unsigned char)*realEnd)) { 2659 realEnd++; 2660 } 2661 if (*realEnd != 0) { 2662 return false; 2663 } 2664 2665 const unit_entry* cur = unitNames; 2666 while (cur->name) { 2667 if (len == cur->len && strncmp(cur->name, str, len) == 0) { 2668 outValue->dataType = cur->type; 2669 outValue->data = cur->unit << Res_value::COMPLEX_UNIT_SHIFT; 2670 *outScale = cur->scale; 2671 *outEnd = end; 2672 //printf("Found unit %s for %s\n", cur->name, str); 2673 return true; 2674 } 2675 cur++; 2676 } 2677 2678 return false; 2679} 2680 2681 2682bool ResTable::stringToInt(const char16_t* s, size_t len, Res_value* outValue) 2683{ 2684 while (len > 0 && isspace16(*s)) { 2685 s++; 2686 len--; 2687 } 2688 2689 if (len <= 0) { 2690 return false; 2691 } 2692 2693 size_t i = 0; 2694 int32_t val = 0; 2695 bool neg = false; 2696 2697 if (*s == '-') { 2698 neg = true; 2699 i++; 2700 } 2701 2702 if (s[i] < '0' || s[i] > '9') { 2703 return false; 2704 } 2705 2706 // Decimal or hex? 2707 if (s[i] == '0' && s[i+1] == 'x') { 2708 if (outValue) 2709 outValue->dataType = outValue->TYPE_INT_HEX; 2710 i += 2; 2711 bool error = false; 2712 while (i < len && !error) { 2713 val = (val*16) + get_hex(s[i], &error); 2714 i++; 2715 } 2716 if (error) { 2717 return false; 2718 } 2719 } else { 2720 if (outValue) 2721 outValue->dataType = outValue->TYPE_INT_DEC; 2722 while (i < len) { 2723 if (s[i] < '0' || s[i] > '9') { 2724 return false; 2725 } 2726 val = (val*10) + s[i]-'0'; 2727 i++; 2728 } 2729 } 2730 2731 if (neg) val = -val; 2732 2733 while (i < len && isspace16(s[i])) { 2734 i++; 2735 } 2736 2737 if (i == len) { 2738 if (outValue) 2739 outValue->data = val; 2740 return true; 2741 } 2742 2743 return false; 2744} 2745 2746bool ResTable::stringToFloat(const char16_t* s, size_t len, Res_value* outValue) 2747{ 2748 while (len > 0 && isspace16(*s)) { 2749 s++; 2750 len--; 2751 } 2752 2753 if (len <= 0) { 2754 return false; 2755 } 2756 2757 char buf[128]; 2758 int i=0; 2759 while (len > 0 && *s != 0 && i < 126) { 2760 if (*s > 255) { 2761 return false; 2762 } 2763 buf[i++] = *s++; 2764 len--; 2765 } 2766 2767 if (len > 0) { 2768 return false; 2769 } 2770 if (buf[0] < '0' && buf[0] > '9' && buf[0] != '.') { 2771 return false; 2772 } 2773 2774 buf[i] = 0; 2775 const char* end; 2776 float f = strtof(buf, (char**)&end); 2777 2778 if (*end != 0 && !isspace((unsigned char)*end)) { 2779 // Might be a unit... 2780 float scale; 2781 if (parse_unit(end, outValue, &scale, &end)) { 2782 f *= scale; 2783 const bool neg = f < 0; 2784 if (neg) f = -f; 2785 uint64_t bits = (uint64_t)(f*(1<<23)+.5f); 2786 uint32_t radix; 2787 uint32_t shift; 2788 if ((bits&0x7fffff) == 0) { 2789 // Always use 23p0 if there is no fraction, just to make 2790 // things easier to read. 2791 radix = Res_value::COMPLEX_RADIX_23p0; 2792 shift = 23; 2793 } else if ((bits&0xffffffffff800000LL) == 0) { 2794 // Magnitude is zero -- can fit in 0 bits of precision. 2795 radix = Res_value::COMPLEX_RADIX_0p23; 2796 shift = 0; 2797 } else if ((bits&0xffffffff80000000LL) == 0) { 2798 // Magnitude can fit in 8 bits of precision. 2799 radix = Res_value::COMPLEX_RADIX_8p15; 2800 shift = 8; 2801 } else if ((bits&0xffffff8000000000LL) == 0) { 2802 // Magnitude can fit in 16 bits of precision. 2803 radix = Res_value::COMPLEX_RADIX_16p7; 2804 shift = 16; 2805 } else { 2806 // Magnitude needs entire range, so no fractional part. 2807 radix = Res_value::COMPLEX_RADIX_23p0; 2808 shift = 23; 2809 } 2810 int32_t mantissa = (int32_t)( 2811 (bits>>shift) & Res_value::COMPLEX_MANTISSA_MASK); 2812 if (neg) { 2813 mantissa = (-mantissa) & Res_value::COMPLEX_MANTISSA_MASK; 2814 } 2815 outValue->data |= 2816 (radix<<Res_value::COMPLEX_RADIX_SHIFT) 2817 | (mantissa<<Res_value::COMPLEX_MANTISSA_SHIFT); 2818 //printf("Input value: %f 0x%016Lx, mult: %f, radix: %d, shift: %d, final: 0x%08x\n", 2819 // f * (neg ? -1 : 1), bits, f*(1<<23), 2820 // radix, shift, outValue->data); 2821 return true; 2822 } 2823 return false; 2824 } 2825 2826 while (*end != 0 && isspace((unsigned char)*end)) { 2827 end++; 2828 } 2829 2830 if (*end == 0) { 2831 if (outValue) { 2832 outValue->dataType = outValue->TYPE_FLOAT; 2833 *(float*)(&outValue->data) = f; 2834 return true; 2835 } 2836 } 2837 2838 return false; 2839} 2840 2841bool ResTable::stringToValue(Res_value* outValue, String16* outString, 2842 const char16_t* s, size_t len, 2843 bool preserveSpaces, bool coerceType, 2844 uint32_t attrID, 2845 const String16* defType, 2846 const String16* defPackage, 2847 Accessor* accessor, 2848 void* accessorCookie, 2849 uint32_t attrType, 2850 bool enforcePrivate) const 2851{ 2852 bool localizationSetting = accessor != NULL && accessor->getLocalizationSetting(); 2853 const char* errorMsg = NULL; 2854 2855 outValue->size = sizeof(Res_value); 2856 outValue->res0 = 0; 2857 2858 // First strip leading/trailing whitespace. Do this before handling 2859 // escapes, so they can be used to force whitespace into the string. 2860 if (!preserveSpaces) { 2861 while (len > 0 && isspace16(*s)) { 2862 s++; 2863 len--; 2864 } 2865 while (len > 0 && isspace16(s[len-1])) { 2866 len--; 2867 } 2868 // If the string ends with '\', then we keep the space after it. 2869 if (len > 0 && s[len-1] == '\\' && s[len] != 0) { 2870 len++; 2871 } 2872 } 2873 2874 //printf("Value for: %s\n", String8(s, len).string()); 2875 2876 uint32_t l10nReq = ResTable_map::L10N_NOT_REQUIRED; 2877 uint32_t attrMin = 0x80000000, attrMax = 0x7fffffff; 2878 bool fromAccessor = false; 2879 if (attrID != 0 && !Res_INTERNALID(attrID)) { 2880 const ssize_t p = getResourcePackageIndex(attrID); 2881 const bag_entry* bag; 2882 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1; 2883 //printf("For attr 0x%08x got bag of %d\n", attrID, cnt); 2884 if (cnt >= 0) { 2885 while (cnt > 0) { 2886 //printf("Entry 0x%08x = 0x%08x\n", bag->map.name.ident, bag->map.value.data); 2887 switch (bag->map.name.ident) { 2888 case ResTable_map::ATTR_TYPE: 2889 attrType = bag->map.value.data; 2890 break; 2891 case ResTable_map::ATTR_MIN: 2892 attrMin = bag->map.value.data; 2893 break; 2894 case ResTable_map::ATTR_MAX: 2895 attrMax = bag->map.value.data; 2896 break; 2897 case ResTable_map::ATTR_L10N: 2898 l10nReq = bag->map.value.data; 2899 break; 2900 } 2901 bag++; 2902 cnt--; 2903 } 2904 unlockBag(bag); 2905 } else if (accessor && accessor->getAttributeType(attrID, &attrType)) { 2906 fromAccessor = true; 2907 if (attrType == ResTable_map::TYPE_ENUM 2908 || attrType == ResTable_map::TYPE_FLAGS 2909 || attrType == ResTable_map::TYPE_INTEGER) { 2910 accessor->getAttributeMin(attrID, &attrMin); 2911 accessor->getAttributeMax(attrID, &attrMax); 2912 } 2913 if (localizationSetting) { 2914 l10nReq = accessor->getAttributeL10N(attrID); 2915 } 2916 } 2917 } 2918 2919 const bool canStringCoerce = 2920 coerceType && (attrType&ResTable_map::TYPE_STRING) != 0; 2921 2922 if (*s == '@') { 2923 outValue->dataType = outValue->TYPE_REFERENCE; 2924 2925 // Note: we don't check attrType here because the reference can 2926 // be to any other type; we just need to count on the client making 2927 // sure the referenced type is correct. 2928 2929 //printf("Looking up ref: %s\n", String8(s, len).string()); 2930 2931 // It's a reference! 2932 if (len == 5 && s[1]=='n' && s[2]=='u' && s[3]=='l' && s[4]=='l') { 2933 outValue->data = 0; 2934 return true; 2935 } else { 2936 bool createIfNotFound = false; 2937 const char16_t* resourceRefName; 2938 int resourceNameLen; 2939 if (len > 2 && s[1] == '+') { 2940 createIfNotFound = true; 2941 resourceRefName = s + 2; 2942 resourceNameLen = len - 2; 2943 } else if (len > 2 && s[1] == '*') { 2944 enforcePrivate = false; 2945 resourceRefName = s + 2; 2946 resourceNameLen = len - 2; 2947 } else { 2948 createIfNotFound = false; 2949 resourceRefName = s + 1; 2950 resourceNameLen = len - 1; 2951 } 2952 String16 package, type, name; 2953 if (!expandResourceRef(resourceRefName,resourceNameLen, &package, &type, &name, 2954 defType, defPackage, &errorMsg)) { 2955 if (accessor != NULL) { 2956 accessor->reportError(accessorCookie, errorMsg); 2957 } 2958 return false; 2959 } 2960 2961 uint32_t specFlags = 0; 2962 uint32_t rid = identifierForName(name.string(), name.size(), type.string(), 2963 type.size(), package.string(), package.size(), &specFlags); 2964 if (rid != 0) { 2965 if (enforcePrivate) { 2966 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) { 2967 if (accessor != NULL) { 2968 accessor->reportError(accessorCookie, "Resource is not public."); 2969 } 2970 return false; 2971 } 2972 } 2973 if (!accessor) { 2974 outValue->data = rid; 2975 return true; 2976 } 2977 rid = Res_MAKEID( 2978 accessor->getRemappedPackage(Res_GETPACKAGE(rid)), 2979 Res_GETTYPE(rid), Res_GETENTRY(rid)); 2980 TABLE_NOISY(printf("Incl %s:%s/%s: 0x%08x\n", 2981 String8(package).string(), String8(type).string(), 2982 String8(name).string(), rid)); 2983 outValue->data = rid; 2984 return true; 2985 } 2986 2987 if (accessor) { 2988 uint32_t rid = accessor->getCustomResourceWithCreation(package, type, name, 2989 createIfNotFound); 2990 if (rid != 0) { 2991 TABLE_NOISY(printf("Pckg %s:%s/%s: 0x%08x\n", 2992 String8(package).string(), String8(type).string(), 2993 String8(name).string(), rid)); 2994 outValue->data = rid; 2995 return true; 2996 } 2997 } 2998 } 2999 3000 if (accessor != NULL) { 3001 accessor->reportError(accessorCookie, "No resource found that matches the given name"); 3002 } 3003 return false; 3004 } 3005 3006 // if we got to here, and localization is required and it's not a reference, 3007 // complain and bail. 3008 if (l10nReq == ResTable_map::L10N_SUGGESTED) { 3009 if (localizationSetting) { 3010 if (accessor != NULL) { 3011 accessor->reportError(accessorCookie, "This attribute must be localized."); 3012 } 3013 } 3014 } 3015 3016 if (*s == '#') { 3017 // It's a color! Convert to an integer of the form 0xaarrggbb. 3018 uint32_t color = 0; 3019 bool error = false; 3020 if (len == 4) { 3021 outValue->dataType = outValue->TYPE_INT_COLOR_RGB4; 3022 color |= 0xFF000000; 3023 color |= get_hex(s[1], &error) << 20; 3024 color |= get_hex(s[1], &error) << 16; 3025 color |= get_hex(s[2], &error) << 12; 3026 color |= get_hex(s[2], &error) << 8; 3027 color |= get_hex(s[3], &error) << 4; 3028 color |= get_hex(s[3], &error); 3029 } else if (len == 5) { 3030 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB4; 3031 color |= get_hex(s[1], &error) << 28; 3032 color |= get_hex(s[1], &error) << 24; 3033 color |= get_hex(s[2], &error) << 20; 3034 color |= get_hex(s[2], &error) << 16; 3035 color |= get_hex(s[3], &error) << 12; 3036 color |= get_hex(s[3], &error) << 8; 3037 color |= get_hex(s[4], &error) << 4; 3038 color |= get_hex(s[4], &error); 3039 } else if (len == 7) { 3040 outValue->dataType = outValue->TYPE_INT_COLOR_RGB8; 3041 color |= 0xFF000000; 3042 color |= get_hex(s[1], &error) << 20; 3043 color |= get_hex(s[2], &error) << 16; 3044 color |= get_hex(s[3], &error) << 12; 3045 color |= get_hex(s[4], &error) << 8; 3046 color |= get_hex(s[5], &error) << 4; 3047 color |= get_hex(s[6], &error); 3048 } else if (len == 9) { 3049 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB8; 3050 color |= get_hex(s[1], &error) << 28; 3051 color |= get_hex(s[2], &error) << 24; 3052 color |= get_hex(s[3], &error) << 20; 3053 color |= get_hex(s[4], &error) << 16; 3054 color |= get_hex(s[5], &error) << 12; 3055 color |= get_hex(s[6], &error) << 8; 3056 color |= get_hex(s[7], &error) << 4; 3057 color |= get_hex(s[8], &error); 3058 } else { 3059 error = true; 3060 } 3061 if (!error) { 3062 if ((attrType&ResTable_map::TYPE_COLOR) == 0) { 3063 if (!canStringCoerce) { 3064 if (accessor != NULL) { 3065 accessor->reportError(accessorCookie, 3066 "Color types not allowed"); 3067 } 3068 return false; 3069 } 3070 } else { 3071 outValue->data = color; 3072 //printf("Color input=%s, output=0x%x\n", String8(s, len).string(), color); 3073 return true; 3074 } 3075 } else { 3076 if ((attrType&ResTable_map::TYPE_COLOR) != 0) { 3077 if (accessor != NULL) { 3078 accessor->reportError(accessorCookie, "Color value not valid --" 3079 " must be #rgb, #argb, #rrggbb, or #aarrggbb"); 3080 } 3081 #if 0 3082 fprintf(stderr, "%s: Color ID %s value %s is not valid\n", 3083 "Resource File", //(const char*)in->getPrintableSource(), 3084 String8(*curTag).string(), 3085 String8(s, len).string()); 3086 #endif 3087 return false; 3088 } 3089 } 3090 } 3091 3092 if (*s == '?') { 3093 outValue->dataType = outValue->TYPE_ATTRIBUTE; 3094 3095 // Note: we don't check attrType here because the reference can 3096 // be to any other type; we just need to count on the client making 3097 // sure the referenced type is correct. 3098 3099 //printf("Looking up attr: %s\n", String8(s, len).string()); 3100 3101 static const String16 attr16("attr"); 3102 String16 package, type, name; 3103 if (!expandResourceRef(s+1, len-1, &package, &type, &name, 3104 &attr16, defPackage, &errorMsg)) { 3105 if (accessor != NULL) { 3106 accessor->reportError(accessorCookie, errorMsg); 3107 } 3108 return false; 3109 } 3110 3111 //printf("Pkg: %s, Type: %s, Name: %s\n", 3112 // String8(package).string(), String8(type).string(), 3113 // String8(name).string()); 3114 uint32_t specFlags = 0; 3115 uint32_t rid = 3116 identifierForName(name.string(), name.size(), 3117 type.string(), type.size(), 3118 package.string(), package.size(), &specFlags); 3119 if (rid != 0) { 3120 if (enforcePrivate) { 3121 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) { 3122 if (accessor != NULL) { 3123 accessor->reportError(accessorCookie, "Attribute is not public."); 3124 } 3125 return false; 3126 } 3127 } 3128 if (!accessor) { 3129 outValue->data = rid; 3130 return true; 3131 } 3132 rid = Res_MAKEID( 3133 accessor->getRemappedPackage(Res_GETPACKAGE(rid)), 3134 Res_GETTYPE(rid), Res_GETENTRY(rid)); 3135 //printf("Incl %s:%s/%s: 0x%08x\n", 3136 // String8(package).string(), String8(type).string(), 3137 // String8(name).string(), rid); 3138 outValue->data = rid; 3139 return true; 3140 } 3141 3142 if (accessor) { 3143 uint32_t rid = accessor->getCustomResource(package, type, name); 3144 if (rid != 0) { 3145 //printf("Mine %s:%s/%s: 0x%08x\n", 3146 // String8(package).string(), String8(type).string(), 3147 // String8(name).string(), rid); 3148 outValue->data = rid; 3149 return true; 3150 } 3151 } 3152 3153 if (accessor != NULL) { 3154 accessor->reportError(accessorCookie, "No resource found that matches the given name"); 3155 } 3156 return false; 3157 } 3158 3159 if (stringToInt(s, len, outValue)) { 3160 if ((attrType&ResTable_map::TYPE_INTEGER) == 0) { 3161 // If this type does not allow integers, but does allow floats, 3162 // fall through on this error case because the float type should 3163 // be able to accept any integer value. 3164 if (!canStringCoerce && (attrType&ResTable_map::TYPE_FLOAT) == 0) { 3165 if (accessor != NULL) { 3166 accessor->reportError(accessorCookie, "Integer types not allowed"); 3167 } 3168 return false; 3169 } 3170 } else { 3171 if (((int32_t)outValue->data) < ((int32_t)attrMin) 3172 || ((int32_t)outValue->data) > ((int32_t)attrMax)) { 3173 if (accessor != NULL) { 3174 accessor->reportError(accessorCookie, "Integer value out of range"); 3175 } 3176 return false; 3177 } 3178 return true; 3179 } 3180 } 3181 3182 if (stringToFloat(s, len, outValue)) { 3183 if (outValue->dataType == Res_value::TYPE_DIMENSION) { 3184 if ((attrType&ResTable_map::TYPE_DIMENSION) != 0) { 3185 return true; 3186 } 3187 if (!canStringCoerce) { 3188 if (accessor != NULL) { 3189 accessor->reportError(accessorCookie, "Dimension types not allowed"); 3190 } 3191 return false; 3192 } 3193 } else if (outValue->dataType == Res_value::TYPE_FRACTION) { 3194 if ((attrType&ResTable_map::TYPE_FRACTION) != 0) { 3195 return true; 3196 } 3197 if (!canStringCoerce) { 3198 if (accessor != NULL) { 3199 accessor->reportError(accessorCookie, "Fraction types not allowed"); 3200 } 3201 return false; 3202 } 3203 } else if ((attrType&ResTable_map::TYPE_FLOAT) == 0) { 3204 if (!canStringCoerce) { 3205 if (accessor != NULL) { 3206 accessor->reportError(accessorCookie, "Float types not allowed"); 3207 } 3208 return false; 3209 } 3210 } else { 3211 return true; 3212 } 3213 } 3214 3215 if (len == 4) { 3216 if ((s[0] == 't' || s[0] == 'T') && 3217 (s[1] == 'r' || s[1] == 'R') && 3218 (s[2] == 'u' || s[2] == 'U') && 3219 (s[3] == 'e' || s[3] == 'E')) { 3220 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) { 3221 if (!canStringCoerce) { 3222 if (accessor != NULL) { 3223 accessor->reportError(accessorCookie, "Boolean types not allowed"); 3224 } 3225 return false; 3226 } 3227 } else { 3228 outValue->dataType = outValue->TYPE_INT_BOOLEAN; 3229 outValue->data = (uint32_t)-1; 3230 return true; 3231 } 3232 } 3233 } 3234 3235 if (len == 5) { 3236 if ((s[0] == 'f' || s[0] == 'F') && 3237 (s[1] == 'a' || s[1] == 'A') && 3238 (s[2] == 'l' || s[2] == 'L') && 3239 (s[3] == 's' || s[3] == 'S') && 3240 (s[4] == 'e' || s[4] == 'E')) { 3241 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) { 3242 if (!canStringCoerce) { 3243 if (accessor != NULL) { 3244 accessor->reportError(accessorCookie, "Boolean types not allowed"); 3245 } 3246 return false; 3247 } 3248 } else { 3249 outValue->dataType = outValue->TYPE_INT_BOOLEAN; 3250 outValue->data = 0; 3251 return true; 3252 } 3253 } 3254 } 3255 3256 if ((attrType&ResTable_map::TYPE_ENUM) != 0) { 3257 const ssize_t p = getResourcePackageIndex(attrID); 3258 const bag_entry* bag; 3259 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1; 3260 //printf("Got %d for enum\n", cnt); 3261 if (cnt >= 0) { 3262 resource_name rname; 3263 while (cnt > 0) { 3264 if (!Res_INTERNALID(bag->map.name.ident)) { 3265 //printf("Trying attr #%08x\n", bag->map.name.ident); 3266 if (getResourceName(bag->map.name.ident, &rname)) { 3267 #if 0 3268 printf("Matching %s against %s (0x%08x)\n", 3269 String8(s, len).string(), 3270 String8(rname.name, rname.nameLen).string(), 3271 bag->map.name.ident); 3272 #endif 3273 if (strzcmp16(s, len, rname.name, rname.nameLen) == 0) { 3274 outValue->dataType = bag->map.value.dataType; 3275 outValue->data = bag->map.value.data; 3276 unlockBag(bag); 3277 return true; 3278 } 3279 } 3280 3281 } 3282 bag++; 3283 cnt--; 3284 } 3285 unlockBag(bag); 3286 } 3287 3288 if (fromAccessor) { 3289 if (accessor->getAttributeEnum(attrID, s, len, outValue)) { 3290 return true; 3291 } 3292 } 3293 } 3294 3295 if ((attrType&ResTable_map::TYPE_FLAGS) != 0) { 3296 const ssize_t p = getResourcePackageIndex(attrID); 3297 const bag_entry* bag; 3298 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1; 3299 //printf("Got %d for flags\n", cnt); 3300 if (cnt >= 0) { 3301 bool failed = false; 3302 resource_name rname; 3303 outValue->dataType = Res_value::TYPE_INT_HEX; 3304 outValue->data = 0; 3305 const char16_t* end = s + len; 3306 const char16_t* pos = s; 3307 while (pos < end && !failed) { 3308 const char16_t* start = pos; 3309 pos++; 3310 while (pos < end && *pos != '|') { 3311 pos++; 3312 } 3313 //printf("Looking for: %s\n", String8(start, pos-start).string()); 3314 const bag_entry* bagi = bag; 3315 ssize_t i; 3316 for (i=0; i<cnt; i++, bagi++) { 3317 if (!Res_INTERNALID(bagi->map.name.ident)) { 3318 //printf("Trying attr #%08x\n", bagi->map.name.ident); 3319 if (getResourceName(bagi->map.name.ident, &rname)) { 3320 #if 0 3321 printf("Matching %s against %s (0x%08x)\n", 3322 String8(start,pos-start).string(), 3323 String8(rname.name, rname.nameLen).string(), 3324 bagi->map.name.ident); 3325 #endif 3326 if (strzcmp16(start, pos-start, rname.name, rname.nameLen) == 0) { 3327 outValue->data |= bagi->map.value.data; 3328 break; 3329 } 3330 } 3331 } 3332 } 3333 if (i >= cnt) { 3334 // Didn't find this flag identifier. 3335 failed = true; 3336 } 3337 if (pos < end) { 3338 pos++; 3339 } 3340 } 3341 unlockBag(bag); 3342 if (!failed) { 3343 //printf("Final flag value: 0x%lx\n", outValue->data); 3344 return true; 3345 } 3346 } 3347 3348 3349 if (fromAccessor) { 3350 if (accessor->getAttributeFlags(attrID, s, len, outValue)) { 3351 //printf("Final flag value: 0x%lx\n", outValue->data); 3352 return true; 3353 } 3354 } 3355 } 3356 3357 if ((attrType&ResTable_map::TYPE_STRING) == 0) { 3358 if (accessor != NULL) { 3359 accessor->reportError(accessorCookie, "String types not allowed"); 3360 } 3361 return false; 3362 } 3363 3364 // Generic string handling... 3365 outValue->dataType = outValue->TYPE_STRING; 3366 if (outString) { 3367 bool failed = collectString(outString, s, len, preserveSpaces, &errorMsg); 3368 if (accessor != NULL) { 3369 accessor->reportError(accessorCookie, errorMsg); 3370 } 3371 return failed; 3372 } 3373 3374 return true; 3375} 3376 3377bool ResTable::collectString(String16* outString, 3378 const char16_t* s, size_t len, 3379 bool preserveSpaces, 3380 const char** outErrorMsg, 3381 bool append) 3382{ 3383 String16 tmp; 3384 3385 char quoted = 0; 3386 const char16_t* p = s; 3387 while (p < (s+len)) { 3388 while (p < (s+len)) { 3389 const char16_t c = *p; 3390 if (c == '\\') { 3391 break; 3392 } 3393 if (!preserveSpaces) { 3394 if (quoted == 0 && isspace16(c) 3395 && (c != ' ' || isspace16(*(p+1)))) { 3396 break; 3397 } 3398 if (c == '"' && (quoted == 0 || quoted == '"')) { 3399 break; 3400 } 3401 if (c == '\'' && (quoted == 0 || quoted == '\'')) { 3402 /* 3403 * In practice, when people write ' instead of \' 3404 * in a string, they are doing it by accident 3405 * instead of really meaning to use ' as a quoting 3406 * character. Warn them so they don't lose it. 3407 */ 3408 if (outErrorMsg) { 3409 *outErrorMsg = "Apostrophe not preceded by \\"; 3410 } 3411 return false; 3412 } 3413 } 3414 p++; 3415 } 3416 if (p < (s+len)) { 3417 if (p > s) { 3418 tmp.append(String16(s, p-s)); 3419 } 3420 if (!preserveSpaces && (*p == '"' || *p == '\'')) { 3421 if (quoted == 0) { 3422 quoted = *p; 3423 } else { 3424 quoted = 0; 3425 } 3426 p++; 3427 } else if (!preserveSpaces && isspace16(*p)) { 3428 // Space outside of a quote -- consume all spaces and 3429 // leave a single plain space char. 3430 tmp.append(String16(" ")); 3431 p++; 3432 while (p < (s+len) && isspace16(*p)) { 3433 p++; 3434 } 3435 } else if (*p == '\\') { 3436 p++; 3437 if (p < (s+len)) { 3438 switch (*p) { 3439 case 't': 3440 tmp.append(String16("\t")); 3441 break; 3442 case 'n': 3443 tmp.append(String16("\n")); 3444 break; 3445 case '#': 3446 tmp.append(String16("#")); 3447 break; 3448 case '@': 3449 tmp.append(String16("@")); 3450 break; 3451 case '?': 3452 tmp.append(String16("?")); 3453 break; 3454 case '"': 3455 tmp.append(String16("\"")); 3456 break; 3457 case '\'': 3458 tmp.append(String16("'")); 3459 break; 3460 case '\\': 3461 tmp.append(String16("\\")); 3462 break; 3463 case 'u': 3464 { 3465 char16_t chr = 0; 3466 int i = 0; 3467 while (i < 4 && p[1] != 0) { 3468 p++; 3469 i++; 3470 int c; 3471 if (*p >= '0' && *p <= '9') { 3472 c = *p - '0'; 3473 } else if (*p >= 'a' && *p <= 'f') { 3474 c = *p - 'a' + 10; 3475 } else if (*p >= 'A' && *p <= 'F') { 3476 c = *p - 'A' + 10; 3477 } else { 3478 if (outErrorMsg) { 3479 *outErrorMsg = "Bad character in \\u unicode escape sequence"; 3480 } 3481 return false; 3482 } 3483 chr = (chr<<4) | c; 3484 } 3485 tmp.append(String16(&chr, 1)); 3486 } break; 3487 default: 3488 // ignore unknown escape chars. 3489 break; 3490 } 3491 p++; 3492 } 3493 } 3494 len -= (p-s); 3495 s = p; 3496 } 3497 } 3498 3499 if (tmp.size() != 0) { 3500 if (len > 0) { 3501 tmp.append(String16(s, len)); 3502 } 3503 if (append) { 3504 outString->append(tmp); 3505 } else { 3506 outString->setTo(tmp); 3507 } 3508 } else { 3509 if (append) { 3510 outString->append(String16(s, len)); 3511 } else { 3512 outString->setTo(s, len); 3513 } 3514 } 3515 3516 return true; 3517} 3518 3519size_t ResTable::getBasePackageCount() const 3520{ 3521 if (mError != NO_ERROR) { 3522 return 0; 3523 } 3524 return mPackageGroups.size(); 3525} 3526 3527const char16_t* ResTable::getBasePackageName(size_t idx) const 3528{ 3529 if (mError != NO_ERROR) { 3530 return 0; 3531 } 3532 LOG_FATAL_IF(idx >= mPackageGroups.size(), 3533 "Requested package index %d past package count %d", 3534 (int)idx, (int)mPackageGroups.size()); 3535 return mPackageGroups[idx]->name.string(); 3536} 3537 3538uint32_t ResTable::getBasePackageId(size_t idx) const 3539{ 3540 if (mError != NO_ERROR) { 3541 return 0; 3542 } 3543 LOG_FATAL_IF(idx >= mPackageGroups.size(), 3544 "Requested package index %d past package count %d", 3545 (int)idx, (int)mPackageGroups.size()); 3546 return mPackageGroups[idx]->id; 3547} 3548 3549size_t ResTable::getTableCount() const 3550{ 3551 return mHeaders.size(); 3552} 3553 3554const ResStringPool* ResTable::getTableStringBlock(size_t index) const 3555{ 3556 return &mHeaders[index]->values; 3557} 3558 3559void* ResTable::getTableCookie(size_t index) const 3560{ 3561 return mHeaders[index]->cookie; 3562} 3563 3564void ResTable::getConfigurations(Vector<ResTable_config>* configs) const 3565{ 3566 const size_t I = mPackageGroups.size(); 3567 for (size_t i=0; i<I; i++) { 3568 const PackageGroup* packageGroup = mPackageGroups[i]; 3569 const size_t J = packageGroup->packages.size(); 3570 for (size_t j=0; j<J; j++) { 3571 const Package* package = packageGroup->packages[j]; 3572 const size_t K = package->types.size(); 3573 for (size_t k=0; k<K; k++) { 3574 const Type* type = package->types[k]; 3575 if (type == NULL) continue; 3576 const size_t L = type->configs.size(); 3577 for (size_t l=0; l<L; l++) { 3578 const ResTable_type* config = type->configs[l]; 3579 const ResTable_config* cfg = &config->config; 3580 // only insert unique 3581 const size_t M = configs->size(); 3582 size_t m; 3583 for (m=0; m<M; m++) { 3584 if (0 == (*configs)[m].compare(*cfg)) { 3585 break; 3586 } 3587 } 3588 // if we didn't find it 3589 if (m == M) { 3590 configs->add(*cfg); 3591 } 3592 } 3593 } 3594 } 3595 } 3596} 3597 3598void ResTable::getLocales(Vector<String8>* locales) const 3599{ 3600 Vector<ResTable_config> configs; 3601 LOGD("calling getConfigurations"); 3602 getConfigurations(&configs); 3603 LOGD("called getConfigurations size=%d", (int)configs.size()); 3604 const size_t I = configs.size(); 3605 for (size_t i=0; i<I; i++) { 3606 char locale[6]; 3607 configs[i].getLocale(locale); 3608 const size_t J = locales->size(); 3609 size_t j; 3610 for (j=0; j<J; j++) { 3611 if (0 == strcmp(locale, (*locales)[j].string())) { 3612 break; 3613 } 3614 } 3615 if (j == J) { 3616 locales->add(String8(locale)); 3617 } 3618 } 3619} 3620 3621ssize_t ResTable::getEntry( 3622 const Package* package, int typeIndex, int entryIndex, 3623 const ResTable_config* config, 3624 const ResTable_type** outType, const ResTable_entry** outEntry, 3625 const Type** outTypeClass) const 3626{ 3627 LOGV("Getting entry from package %p\n", package); 3628 const ResTable_package* const pkg = package->package; 3629 3630 const Type* allTypes = package->getType(typeIndex); 3631 LOGV("allTypes=%p\n", allTypes); 3632 if (allTypes == NULL) { 3633 LOGV("Skipping entry type index 0x%02x because type is NULL!\n", typeIndex); 3634 return 0; 3635 } 3636 3637 if ((size_t)entryIndex >= allTypes->entryCount) { 3638 LOGW("getEntry failing because entryIndex %d is beyond type entryCount %d", 3639 entryIndex, (int)allTypes->entryCount); 3640 return BAD_TYPE; 3641 } 3642 3643 const ResTable_type* type = NULL; 3644 uint32_t offset = ResTable_type::NO_ENTRY; 3645 ResTable_config bestConfig; 3646 memset(&bestConfig, 0, sizeof(bestConfig)); // make the compiler shut up 3647 3648 const size_t NT = allTypes->configs.size(); 3649 for (size_t i=0; i<NT; i++) { 3650 const ResTable_type* const thisType = allTypes->configs[i]; 3651 if (thisType == NULL) continue; 3652 3653 ResTable_config thisConfig; 3654 thisConfig.copyFromDtoH(thisType->config); 3655 3656 TABLE_GETENTRY(LOGI("Match entry 0x%x in type 0x%x (sz 0x%x): imsi:%d/%d=%d/%d lang:%c%c=%c%c cnt:%c%c=%c%c " 3657 "orien:%d=%d touch:%d=%d density:%d=%d key:%d=%d inp:%d=%d nav:%d=%d w:%d=%d h:%d=%d\n", 3658 entryIndex, typeIndex+1, dtohl(thisType->config.size), 3659 thisConfig.mcc, thisConfig.mnc, 3660 config ? config->mcc : 0, config ? config->mnc : 0, 3661 thisConfig.language[0] ? thisConfig.language[0] : '-', 3662 thisConfig.language[1] ? thisConfig.language[1] : '-', 3663 config && config->language[0] ? config->language[0] : '-', 3664 config && config->language[1] ? config->language[1] : '-', 3665 thisConfig.country[0] ? thisConfig.country[0] : '-', 3666 thisConfig.country[1] ? thisConfig.country[1] : '-', 3667 config && config->country[0] ? config->country[0] : '-', 3668 config && config->country[1] ? config->country[1] : '-', 3669 thisConfig.orientation, 3670 config ? config->orientation : 0, 3671 thisConfig.touchscreen, 3672 config ? config->touchscreen : 0, 3673 thisConfig.density, 3674 config ? config->density : 0, 3675 thisConfig.keyboard, 3676 config ? config->keyboard : 0, 3677 thisConfig.inputFlags, 3678 config ? config->inputFlags : 0, 3679 thisConfig.navigation, 3680 config ? config->navigation : 0, 3681 thisConfig.screenWidth, 3682 config ? config->screenWidth : 0, 3683 thisConfig.screenHeight, 3684 config ? config->screenHeight : 0)); 3685 3686 // Check to make sure this one is valid for the current parameters. 3687 if (config && !thisConfig.match(*config)) { 3688 TABLE_GETENTRY(LOGI("Does not match config!\n")); 3689 continue; 3690 } 3691 3692 // Check if there is the desired entry in this type. 3693 3694 const uint8_t* const end = ((const uint8_t*)thisType) 3695 + dtohl(thisType->header.size); 3696 const uint32_t* const eindex = (const uint32_t*) 3697 (((const uint8_t*)thisType) + dtohs(thisType->header.headerSize)); 3698 3699 uint32_t thisOffset = dtohl(eindex[entryIndex]); 3700 if (thisOffset == ResTable_type::NO_ENTRY) { 3701 TABLE_GETENTRY(LOGI("Skipping because it is not defined!\n")); 3702 continue; 3703 } 3704 3705 if (type != NULL) { 3706 // Check if this one is less specific than the last found. If so, 3707 // we will skip it. We check starting with things we most care 3708 // about to those we least care about. 3709 if (!thisConfig.isBetterThan(bestConfig, config)) { 3710 TABLE_GETENTRY(LOGI("This config is worse than last!\n")); 3711 continue; 3712 } 3713 } 3714 3715 type = thisType; 3716 offset = thisOffset; 3717 bestConfig = thisConfig; 3718 TABLE_GETENTRY(LOGI("Best entry so far -- using it!\n")); 3719 if (!config) break; 3720 } 3721 3722 if (type == NULL) { 3723 TABLE_GETENTRY(LOGI("No value found for requested entry!\n")); 3724 return BAD_INDEX; 3725 } 3726 3727 offset += dtohl(type->entriesStart); 3728 TABLE_NOISY(aout << "Looking in resource table " << package->header->header 3729 << ", typeOff=" 3730 << (void*)(((const char*)type)-((const char*)package->header->header)) 3731 << ", offset=" << (void*)offset << endl); 3732 3733 if (offset > (dtohl(type->header.size)-sizeof(ResTable_entry))) { 3734 LOGW("ResTable_entry at 0x%x is beyond type chunk data 0x%x", 3735 offset, dtohl(type->header.size)); 3736 return BAD_TYPE; 3737 } 3738 if ((offset&0x3) != 0) { 3739 LOGW("ResTable_entry at 0x%x is not on an integer boundary", 3740 offset); 3741 return BAD_TYPE; 3742 } 3743 3744 const ResTable_entry* const entry = (const ResTable_entry*) 3745 (((const uint8_t*)type) + offset); 3746 if (dtohs(entry->size) < sizeof(*entry)) { 3747 LOGW("ResTable_entry size 0x%x is too small", dtohs(entry->size)); 3748 return BAD_TYPE; 3749 } 3750 3751 *outType = type; 3752 *outEntry = entry; 3753 if (outTypeClass != NULL) { 3754 *outTypeClass = allTypes; 3755 } 3756 return offset + dtohs(entry->size); 3757} 3758 3759status_t ResTable::parsePackage(const ResTable_package* const pkg, 3760 const Header* const header) 3761{ 3762 const uint8_t* base = (const uint8_t*)pkg; 3763 status_t err = validate_chunk(&pkg->header, sizeof(*pkg), 3764 header->dataEnd, "ResTable_package"); 3765 if (err != NO_ERROR) { 3766 return (mError=err); 3767 } 3768 3769 const size_t pkgSize = dtohl(pkg->header.size); 3770 3771 if (dtohl(pkg->typeStrings) >= pkgSize) { 3772 LOGW("ResTable_package type strings at %p are past chunk size %p.", 3773 (void*)dtohl(pkg->typeStrings), (void*)pkgSize); 3774 return (mError=BAD_TYPE); 3775 } 3776 if ((dtohl(pkg->typeStrings)&0x3) != 0) { 3777 LOGW("ResTable_package type strings at %p is not on an integer boundary.", 3778 (void*)dtohl(pkg->typeStrings)); 3779 return (mError=BAD_TYPE); 3780 } 3781 if (dtohl(pkg->keyStrings) >= pkgSize) { 3782 LOGW("ResTable_package key strings at %p are past chunk size %p.", 3783 (void*)dtohl(pkg->keyStrings), (void*)pkgSize); 3784 return (mError=BAD_TYPE); 3785 } 3786 if ((dtohl(pkg->keyStrings)&0x3) != 0) { 3787 LOGW("ResTable_package key strings at %p is not on an integer boundary.", 3788 (void*)dtohl(pkg->keyStrings)); 3789 return (mError=BAD_TYPE); 3790 } 3791 3792 Package* package = NULL; 3793 PackageGroup* group = NULL; 3794 uint32_t id = dtohl(pkg->id); 3795 if (id != 0 && id < 256) { 3796 3797 package = new Package(this, header, pkg); 3798 if (package == NULL) { 3799 return (mError=NO_MEMORY); 3800 } 3801 3802 size_t idx = mPackageMap[id]; 3803 if (idx == 0) { 3804 idx = mPackageGroups.size()+1; 3805 3806 char16_t tmpName[sizeof(pkg->name)/sizeof(char16_t)]; 3807 strcpy16_dtoh(tmpName, pkg->name, sizeof(pkg->name)/sizeof(char16_t)); 3808 group = new PackageGroup(this, String16(tmpName), id); 3809 if (group == NULL) { 3810 delete package; 3811 return (mError=NO_MEMORY); 3812 } 3813 3814 err = package->typeStrings.setTo(base+dtohl(pkg->typeStrings), 3815 header->dataEnd-(base+dtohl(pkg->typeStrings))); 3816 if (err != NO_ERROR) { 3817 delete group; 3818 delete package; 3819 return (mError=err); 3820 } 3821 err = package->keyStrings.setTo(base+dtohl(pkg->keyStrings), 3822 header->dataEnd-(base+dtohl(pkg->keyStrings))); 3823 if (err != NO_ERROR) { 3824 delete group; 3825 delete package; 3826 return (mError=err); 3827 } 3828 3829 //printf("Adding new package id %d at index %d\n", id, idx); 3830 err = mPackageGroups.add(group); 3831 if (err < NO_ERROR) { 3832 return (mError=err); 3833 } 3834 group->basePackage = package; 3835 3836 mPackageMap[id] = (uint8_t)idx; 3837 } else { 3838 group = mPackageGroups.itemAt(idx-1); 3839 if (group == NULL) { 3840 return (mError=UNKNOWN_ERROR); 3841 } 3842 } 3843 err = group->packages.add(package); 3844 if (err < NO_ERROR) { 3845 return (mError=err); 3846 } 3847 } else { 3848 LOG_ALWAYS_FATAL("Skins not supported!"); 3849 return NO_ERROR; 3850 } 3851 3852 3853 // Iterate through all chunks. 3854 size_t curPackage = 0; 3855 3856 const ResChunk_header* chunk = 3857 (const ResChunk_header*)(((const uint8_t*)pkg) 3858 + dtohs(pkg->header.headerSize)); 3859 const uint8_t* endPos = ((const uint8_t*)pkg) + dtohs(pkg->header.size); 3860 while (((const uint8_t*)chunk) <= (endPos-sizeof(ResChunk_header)) && 3861 ((const uint8_t*)chunk) <= (endPos-dtohl(chunk->size))) { 3862 TABLE_NOISY(LOGV("PackageChunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n", 3863 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size), 3864 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)))); 3865 const size_t csize = dtohl(chunk->size); 3866 const uint16_t ctype = dtohs(chunk->type); 3867 if (ctype == RES_TABLE_TYPE_SPEC_TYPE) { 3868 const ResTable_typeSpec* typeSpec = (const ResTable_typeSpec*)(chunk); 3869 err = validate_chunk(&typeSpec->header, sizeof(*typeSpec), 3870 endPos, "ResTable_typeSpec"); 3871 if (err != NO_ERROR) { 3872 return (mError=err); 3873 } 3874 3875 const size_t typeSpecSize = dtohl(typeSpec->header.size); 3876 3877 LOAD_TABLE_NOISY(printf("TypeSpec off %p: type=0x%x, headerSize=0x%x, size=%p\n", 3878 (void*)(base-(const uint8_t*)chunk), 3879 dtohs(typeSpec->header.type), 3880 dtohs(typeSpec->header.headerSize), 3881 (void*)typeSize)); 3882 // look for block overrun or int overflow when multiplying by 4 3883 if ((dtohl(typeSpec->entryCount) > (INT32_MAX/sizeof(uint32_t)) 3884 || dtohs(typeSpec->header.headerSize)+(sizeof(uint32_t)*dtohl(typeSpec->entryCount)) 3885 > typeSpecSize)) { 3886 LOGW("ResTable_typeSpec entry index to %p extends beyond chunk end %p.", 3887 (void*)(dtohs(typeSpec->header.headerSize) 3888 +(sizeof(uint32_t)*dtohl(typeSpec->entryCount))), 3889 (void*)typeSpecSize); 3890 return (mError=BAD_TYPE); 3891 } 3892 3893 if (typeSpec->id == 0) { 3894 LOGW("ResTable_type has an id of 0."); 3895 return (mError=BAD_TYPE); 3896 } 3897 3898 while (package->types.size() < typeSpec->id) { 3899 package->types.add(NULL); 3900 } 3901 Type* t = package->types[typeSpec->id-1]; 3902 if (t == NULL) { 3903 t = new Type(header, package, dtohl(typeSpec->entryCount)); 3904 package->types.editItemAt(typeSpec->id-1) = t; 3905 } else if (dtohl(typeSpec->entryCount) != t->entryCount) { 3906 LOGW("ResTable_typeSpec entry count inconsistent: given %d, previously %d", 3907 (int)dtohl(typeSpec->entryCount), (int)t->entryCount); 3908 return (mError=BAD_TYPE); 3909 } 3910 t->typeSpecFlags = (const uint32_t*)( 3911 ((const uint8_t*)typeSpec) + dtohs(typeSpec->header.headerSize)); 3912 t->typeSpec = typeSpec; 3913 3914 } else if (ctype == RES_TABLE_TYPE_TYPE) { 3915 const ResTable_type* type = (const ResTable_type*)(chunk); 3916 err = validate_chunk(&type->header, sizeof(*type)-sizeof(ResTable_config)+4, 3917 endPos, "ResTable_type"); 3918 if (err != NO_ERROR) { 3919 return (mError=err); 3920 } 3921 3922 const size_t typeSize = dtohl(type->header.size); 3923 3924 LOAD_TABLE_NOISY(printf("Type off %p: type=0x%x, headerSize=0x%x, size=%p\n", 3925 (void*)(base-(const uint8_t*)chunk), 3926 dtohs(type->header.type), 3927 dtohs(type->header.headerSize), 3928 (void*)typeSize)); 3929 if (dtohs(type->header.headerSize)+(sizeof(uint32_t)*dtohl(type->entryCount)) 3930 > typeSize) { 3931 LOGW("ResTable_type entry index to %p extends beyond chunk end %p.", 3932 (void*)(dtohs(type->header.headerSize) 3933 +(sizeof(uint32_t)*dtohl(type->entryCount))), 3934 (void*)typeSize); 3935 return (mError=BAD_TYPE); 3936 } 3937 if (dtohl(type->entryCount) != 0 3938 && dtohl(type->entriesStart) > (typeSize-sizeof(ResTable_entry))) { 3939 LOGW("ResTable_type entriesStart at %p extends beyond chunk end %p.", 3940 (void*)dtohl(type->entriesStart), (void*)typeSize); 3941 return (mError=BAD_TYPE); 3942 } 3943 if (type->id == 0) { 3944 LOGW("ResTable_type has an id of 0."); 3945 return (mError=BAD_TYPE); 3946 } 3947 3948 while (package->types.size() < type->id) { 3949 package->types.add(NULL); 3950 } 3951 Type* t = package->types[type->id-1]; 3952 if (t == NULL) { 3953 t = new Type(header, package, dtohl(type->entryCount)); 3954 package->types.editItemAt(type->id-1) = t; 3955 } else if (dtohl(type->entryCount) != t->entryCount) { 3956 LOGW("ResTable_type entry count inconsistent: given %d, previously %d", 3957 (int)dtohl(type->entryCount), (int)t->entryCount); 3958 return (mError=BAD_TYPE); 3959 } 3960 3961 TABLE_GETENTRY( 3962 ResTable_config thisConfig; 3963 thisConfig.copyFromDtoH(type->config); 3964 LOGI("Adding config to type %d: imsi:%d/%d lang:%c%c cnt:%c%c " 3965 "orien:%d touch:%d density:%d key:%d inp:%d nav:%d w:%d h:%d\n", 3966 type->id, 3967 thisConfig.mcc, thisConfig.mnc, 3968 thisConfig.language[0] ? thisConfig.language[0] : '-', 3969 thisConfig.language[1] ? thisConfig.language[1] : '-', 3970 thisConfig.country[0] ? thisConfig.country[0] : '-', 3971 thisConfig.country[1] ? thisConfig.country[1] : '-', 3972 thisConfig.orientation, 3973 thisConfig.touchscreen, 3974 thisConfig.density, 3975 thisConfig.keyboard, 3976 thisConfig.inputFlags, 3977 thisConfig.navigation, 3978 thisConfig.screenWidth, 3979 thisConfig.screenHeight)); 3980 t->configs.add(type); 3981 } else { 3982 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), 3983 endPos, "ResTable_package:unknown"); 3984 if (err != NO_ERROR) { 3985 return (mError=err); 3986 } 3987 } 3988 chunk = (const ResChunk_header*) 3989 (((const uint8_t*)chunk) + csize); 3990 } 3991 3992 if (group->typeCount == 0) { 3993 group->typeCount = package->types.size(); 3994 } 3995 3996 return NO_ERROR; 3997} 3998 3999#ifndef HAVE_ANDROID_OS 4000#define CHAR16_TO_CSTR(c16, len) (String8(String16(c16,len)).string()) 4001 4002#define CHAR16_ARRAY_EQ(constant, var, len) \ 4003 ((len == (sizeof(constant)/sizeof(constant[0]))) && (0 == memcmp((var), (constant), (len)))) 4004 4005void print_complex(uint32_t complex, bool isFraction) 4006{ 4007 const float MANTISSA_MULT = 4008 1.0f / (1<<Res_value::COMPLEX_MANTISSA_SHIFT); 4009 const float RADIX_MULTS[] = { 4010 1.0f*MANTISSA_MULT, 1.0f/(1<<7)*MANTISSA_MULT, 4011 1.0f/(1<<15)*MANTISSA_MULT, 1.0f/(1<<23)*MANTISSA_MULT 4012 }; 4013 4014 float value = (complex&(Res_value::COMPLEX_MANTISSA_MASK 4015 <<Res_value::COMPLEX_MANTISSA_SHIFT)) 4016 * RADIX_MULTS[(complex>>Res_value::COMPLEX_RADIX_SHIFT) 4017 & Res_value::COMPLEX_RADIX_MASK]; 4018 printf("%f", value); 4019 4020 if (!isFraction) { 4021 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) { 4022 case Res_value::COMPLEX_UNIT_PX: printf("px"); break; 4023 case Res_value::COMPLEX_UNIT_DIP: printf("dp"); break; 4024 case Res_value::COMPLEX_UNIT_SP: printf("sp"); break; 4025 case Res_value::COMPLEX_UNIT_PT: printf("pt"); break; 4026 case Res_value::COMPLEX_UNIT_IN: printf("in"); break; 4027 case Res_value::COMPLEX_UNIT_MM: printf("mm"); break; 4028 default: printf(" (unknown unit)"); break; 4029 } 4030 } else { 4031 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) { 4032 case Res_value::COMPLEX_UNIT_FRACTION: printf("%%"); break; 4033 case Res_value::COMPLEX_UNIT_FRACTION_PARENT: printf("%%p"); break; 4034 default: printf(" (unknown unit)"); break; 4035 } 4036 } 4037} 4038 4039void ResTable::print_value(const Package* pkg, const Res_value& value) const 4040{ 4041 if (value.dataType == Res_value::TYPE_NULL) { 4042 printf("(null)\n"); 4043 } else if (value.dataType == Res_value::TYPE_REFERENCE) { 4044 printf("(reference) 0x%08x\n", value.data); 4045 } else if (value.dataType == Res_value::TYPE_ATTRIBUTE) { 4046 printf("(attribute) 0x%08x\n", value.data); 4047 } else if (value.dataType == Res_value::TYPE_STRING) { 4048 size_t len; 4049 const char* str8 = pkg->header->values.string8At( 4050 value.data, &len); 4051 if (str8 != NULL) { 4052 printf("(string8) \"%s\"\n", str8); 4053 } else { 4054 const char16_t* str16 = pkg->header->values.stringAt( 4055 value.data, &len); 4056 if (str16 != NULL) { 4057 printf("(string16) \"%s\"\n", 4058 String8(str16, len).string()); 4059 } else { 4060 printf("(string) null\n"); 4061 } 4062 } 4063 } else if (value.dataType == Res_value::TYPE_FLOAT) { 4064 printf("(float) %g\n", *(const float*)&value.data); 4065 } else if (value.dataType == Res_value::TYPE_DIMENSION) { 4066 printf("(dimension) "); 4067 print_complex(value.data, false); 4068 printf("\n"); 4069 } else if (value.dataType == Res_value::TYPE_FRACTION) { 4070 printf("(fraction) "); 4071 print_complex(value.data, true); 4072 printf("\n"); 4073 } else if (value.dataType >= Res_value::TYPE_FIRST_COLOR_INT 4074 || value.dataType <= Res_value::TYPE_LAST_COLOR_INT) { 4075 printf("(color) #%08x\n", value.data); 4076 } else if (value.dataType == Res_value::TYPE_INT_BOOLEAN) { 4077 printf("(boolean) %s\n", value.data ? "true" : "false"); 4078 } else if (value.dataType >= Res_value::TYPE_FIRST_INT 4079 || value.dataType <= Res_value::TYPE_LAST_INT) { 4080 printf("(int) 0x%08x or %d\n", value.data, value.data); 4081 } else { 4082 printf("(unknown type) t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)\n", 4083 (int)value.dataType, (int)value.data, 4084 (int)value.size, (int)value.res0); 4085 } 4086} 4087 4088void ResTable::print(bool inclValues) const 4089{ 4090 if (mError != 0) { 4091 printf("mError=0x%x (%s)\n", mError, strerror(mError)); 4092 } 4093#if 0 4094 printf("mParams=%c%c-%c%c,\n", 4095 mParams.language[0], mParams.language[1], 4096 mParams.country[0], mParams.country[1]); 4097#endif 4098 size_t pgCount = mPackageGroups.size(); 4099 printf("Package Groups (%d)\n", (int)pgCount); 4100 for (size_t pgIndex=0; pgIndex<pgCount; pgIndex++) { 4101 const PackageGroup* pg = mPackageGroups[pgIndex]; 4102 printf("Package Group %d id=%d packageCount=%d name=%s\n", 4103 (int)pgIndex, pg->id, (int)pg->packages.size(), 4104 String8(pg->name).string()); 4105 4106 size_t pkgCount = pg->packages.size(); 4107 for (size_t pkgIndex=0; pkgIndex<pkgCount; pkgIndex++) { 4108 const Package* pkg = pg->packages[pkgIndex]; 4109 size_t typeCount = pkg->types.size(); 4110 printf(" Package %d id=%d name=%s typeCount=%d\n", (int)pkgIndex, 4111 pkg->package->id, String8(String16(pkg->package->name)).string(), 4112 (int)typeCount); 4113 for (size_t typeIndex=0; typeIndex<typeCount; typeIndex++) { 4114 const Type* typeConfigs = pkg->getType(typeIndex); 4115 if (typeConfigs == NULL) { 4116 printf(" type %d NULL\n", (int)typeIndex); 4117 continue; 4118 } 4119 const size_t NTC = typeConfigs->configs.size(); 4120 printf(" type %d configCount=%d entryCount=%d\n", 4121 (int)typeIndex, (int)NTC, (int)typeConfigs->entryCount); 4122 if (typeConfigs->typeSpecFlags != NULL) { 4123 for (size_t entryIndex=0; entryIndex<typeConfigs->entryCount; entryIndex++) { 4124 uint32_t resID = (0xff000000 & ((pkg->package->id)<<24)) 4125 | (0x00ff0000 & ((typeIndex+1)<<16)) 4126 | (0x0000ffff & (entryIndex)); 4127 resource_name resName; 4128 this->getResourceName(resID, &resName); 4129 printf(" spec resource 0x%08x %s:%s/%s: flags=0x%08x\n", 4130 resID, 4131 CHAR16_TO_CSTR(resName.package, resName.packageLen), 4132 CHAR16_TO_CSTR(resName.type, resName.typeLen), 4133 CHAR16_TO_CSTR(resName.name, resName.nameLen), 4134 dtohl(typeConfigs->typeSpecFlags[entryIndex])); 4135 } 4136 } 4137 for (size_t configIndex=0; configIndex<NTC; configIndex++) { 4138 const ResTable_type* type = typeConfigs->configs[configIndex]; 4139 if ((((uint64_t)type)&0x3) != 0) { 4140 printf(" NON-INTEGER ResTable_type ADDRESS: %p\n", type); 4141 continue; 4142 } 4143 char density[16]; 4144 uint16_t dval = dtohs(type->config.density); 4145 if (dval == ResTable_config::DENSITY_DEFAULT) { 4146 strcpy(density, "def"); 4147 } else if (dval == ResTable_config::DENSITY_NONE) { 4148 strcpy(density, "no"); 4149 } else { 4150 sprintf(density, "%d", (int)dval); 4151 } 4152 printf(" config %d lang=%c%c cnt=%c%c orien=%d touch=%d density=%s key=%d infl=%d nav=%d w=%d h=%d sz=%d lng=%d\n", 4153 (int)configIndex, 4154 type->config.language[0] ? type->config.language[0] : '-', 4155 type->config.language[1] ? type->config.language[1] : '-', 4156 type->config.country[0] ? type->config.country[0] : '-', 4157 type->config.country[1] ? type->config.country[1] : '-', 4158 type->config.orientation, 4159 type->config.touchscreen, 4160 density, 4161 type->config.keyboard, 4162 type->config.inputFlags, 4163 type->config.navigation, 4164 dtohs(type->config.screenWidth), 4165 dtohs(type->config.screenHeight), 4166 type->config.screenLayout&ResTable_config::MASK_SCREENSIZE, 4167 type->config.screenLayout&ResTable_config::MASK_SCREENLONG); 4168 size_t entryCount = dtohl(type->entryCount); 4169 uint32_t entriesStart = dtohl(type->entriesStart); 4170 if ((entriesStart&0x3) != 0) { 4171 printf(" NON-INTEGER ResTable_type entriesStart OFFSET: %p\n", (void*)entriesStart); 4172 continue; 4173 } 4174 uint32_t typeSize = dtohl(type->header.size); 4175 if ((typeSize&0x3) != 0) { 4176 printf(" NON-INTEGER ResTable_type header.size: %p\n", (void*)typeSize); 4177 continue; 4178 } 4179 for (size_t entryIndex=0; entryIndex<entryCount; entryIndex++) { 4180 4181 const uint8_t* const end = ((const uint8_t*)type) 4182 + dtohl(type->header.size); 4183 const uint32_t* const eindex = (const uint32_t*) 4184 (((const uint8_t*)type) + dtohs(type->header.headerSize)); 4185 4186 uint32_t thisOffset = dtohl(eindex[entryIndex]); 4187 if (thisOffset == ResTable_type::NO_ENTRY) { 4188 continue; 4189 } 4190 4191 uint32_t resID = (0xff000000 & ((pkg->package->id)<<24)) 4192 | (0x00ff0000 & ((typeIndex+1)<<16)) 4193 | (0x0000ffff & (entryIndex)); 4194 resource_name resName; 4195 this->getResourceName(resID, &resName); 4196 printf(" resource 0x%08x %s:%s/%s: ", resID, 4197 CHAR16_TO_CSTR(resName.package, resName.packageLen), 4198 CHAR16_TO_CSTR(resName.type, resName.typeLen), 4199 CHAR16_TO_CSTR(resName.name, resName.nameLen)); 4200 if ((thisOffset&0x3) != 0) { 4201 printf("NON-INTEGER OFFSET: %p\n", (void*)thisOffset); 4202 continue; 4203 } 4204 if ((thisOffset+sizeof(ResTable_entry)) > typeSize) { 4205 printf("OFFSET OUT OF BOUNDS: %p+%p (size is %p)\n", 4206 (void*)entriesStart, (void*)thisOffset, 4207 (void*)typeSize); 4208 continue; 4209 } 4210 4211 const ResTable_entry* ent = (const ResTable_entry*) 4212 (((const uint8_t*)type) + entriesStart + thisOffset); 4213 if (((entriesStart + thisOffset)&0x3) != 0) { 4214 printf("NON-INTEGER ResTable_entry OFFSET: %p\n", 4215 (void*)(entriesStart + thisOffset)); 4216 continue; 4217 } 4218 4219 uint16_t esize = dtohs(ent->size); 4220 if ((esize&0x3) != 0) { 4221 printf("NON-INTEGER ResTable_entry SIZE: %p\n", (void*)esize); 4222 continue; 4223 } 4224 if ((thisOffset+esize) > typeSize) { 4225 printf("ResTable_entry OUT OF BOUNDS: %p+%p+%p (size is %p)\n", 4226 (void*)entriesStart, (void*)thisOffset, 4227 (void*)esize, (void*)typeSize); 4228 continue; 4229 } 4230 4231 const Res_value* valuePtr = NULL; 4232 const ResTable_map_entry* bagPtr = NULL; 4233 Res_value value; 4234 if ((dtohs(ent->flags)&ResTable_entry::FLAG_COMPLEX) != 0) { 4235 printf("<bag>"); 4236 bagPtr = (const ResTable_map_entry*)ent; 4237 } else { 4238 valuePtr = (const Res_value*) 4239 (((const uint8_t*)ent) + esize); 4240 value.copyFrom_dtoh(*valuePtr); 4241 printf("t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)", 4242 (int)value.dataType, (int)value.data, 4243 (int)value.size, (int)value.res0); 4244 } 4245 4246 if ((dtohs(ent->flags)&ResTable_entry::FLAG_PUBLIC) != 0) { 4247 printf(" (PUBLIC)"); 4248 } 4249 printf("\n"); 4250 4251 if (inclValues) { 4252 if (valuePtr != NULL) { 4253 printf(" "); 4254 print_value(pkg, value); 4255 } else if (bagPtr != NULL) { 4256 const int N = dtohl(bagPtr->count); 4257 const ResTable_map* mapPtr = (const ResTable_map*) 4258 (((const uint8_t*)ent) + esize); 4259 printf(" Parent=0x%08x, Count=%d\n", 4260 dtohl(bagPtr->parent.ident), N); 4261 for (int i=0; i<N; i++) { 4262 printf(" #%i (Key=0x%08x): ", 4263 i, dtohl(mapPtr->name.ident)); 4264 value.copyFrom_dtoh(mapPtr->value); 4265 print_value(pkg, value); 4266 const size_t size = dtohs(mapPtr->value.size); 4267 mapPtr = (ResTable_map*)(((const uint8_t*)mapPtr) 4268 + size + sizeof(*mapPtr)-sizeof(mapPtr->value)); 4269 } 4270 } 4271 } 4272 } 4273 } 4274 } 4275 } 4276 } 4277} 4278 4279#endif // HAVE_ANDROID_OS 4280 4281} // namespace android 4282