2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #define LOG_TAG "ResourceType"
18 //#define LOG_NDEBUG 0
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>
36 #define INT32_MAX ((int32_t)(2147483647))
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
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)
66 static void printToLogFunc(void* cookie, const char* txt)
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.
74 inline int isspace16(char16_t c) {
75 return (c < 0x0080 && isspace(c));
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.
81 static void strcpy16_dtoh(uint16_t* dst, const uint16_t* src, size_t avail)
83 uint16_t* last = dst + avail - 1;
84 while (*src && (dst < last)) {
85 char16_t s = dtohs(*src);
92 static status_t validate_chunk(const ResChunk_header* chunk,
94 const uint8_t* dataEnd,
97 const uint16_t headerSize = dtohs(chunk->headerSize);
98 const uint32_t size = dtohl(chunk->size);
100 if (headerSize >= minSize) {
101 if (headerSize <= size) {
102 if (((headerSize|size)&0x3) == 0) {
103 if ((ssize_t)size <= (dataEnd-((const uint8_t*)chunk))) {
106 LOGW("%s data size %p extends beyond resource end %p.",
108 (void*)(dataEnd-((const uint8_t*)chunk)));
111 LOGW("%s size 0x%x or headerSize 0x%x is not on an integer boundary.",
112 name, (int)size, (int)headerSize);
115 LOGW("%s size %p is smaller than header size %p.",
116 name, (void*)size, (void*)(int)headerSize);
119 LOGW("%s header size %p is too small.",
120 name, (void*)(int)headerSize);
124 inline void Res_value::copyFrom_dtoh(const Res_value& src)
126 size = dtohs(src.size);
128 dataType = src.dataType;
129 data = dtohl(src.data);
132 void Res_png_9patch::deviceToFile()
134 for (int i = 0; i < numXDivs; i++) {
135 xDivs[i] = htonl(xDivs[i]);
137 for (int i = 0; i < numYDivs; i++) {
138 yDivs[i] = htonl(yDivs[i]);
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]);
149 void Res_png_9patch::fileToDevice()
151 for (int i = 0; i < numXDivs; i++) {
152 xDivs[i] = ntohl(xDivs[i]);
154 for (int i = 0; i < numYDivs; i++) {
155 yDivs[i] = ntohl(yDivs[i]);
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]);
166 size_t Res_png_9patch::serializedSize()
168 // The size of this struct is 32 bytes on the 32-bit target system
173 + numXDivs * sizeof(int32_t)
174 + numYDivs * sizeof(int32_t)
175 + numColors * sizeof(uint32_t);
178 void* Res_png_9patch::serialize()
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());
187 void Res_png_9patch::serialize(void * outData)
189 char* data = (char*) outData;
190 memmove(data, &wasDeserialized, 4); // copy wasDeserialized, numXDivs, numYDivs, numColors
191 memmove(data + 12, &paddingLeft, 16); // copy paddingXXXX
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));
201 static 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
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;
217 Res_png_9patch* Res_png_9patch::deserialize(const void* inData)
219 if (sizeof(void*) != sizeof(int32_t)) {
220 LOGE("Cannot deserialize on non 32-bit system\n");
223 deserializeInternal(inData, (Res_png_9patch*) inData);
224 return (Res_png_9patch*) inData;
227 // --------------------------------------------------------------------
228 // --------------------------------------------------------------------
229 // --------------------------------------------------------------------
231 ResStringPool::ResStringPool()
232 : mError(NO_INIT), mOwnedData(NULL), mHeader(NULL), mCache(NULL)
236 ResStringPool::ResStringPool(const void* data, size_t size, bool copyData)
237 : mError(NO_INIT), mOwnedData(NULL), mHeader(NULL), mCache(NULL)
239 setTo(data, size, copyData);
242 ResStringPool::~ResStringPool()
247 status_t ResStringPool::setTo(const void* data, size_t size, bool copyData)
249 if (!data || !size) {
250 return (mError=BAD_TYPE);
255 const bool notDeviceEndian = htods(0xf0) != 0xf0;
257 if (copyData || notDeviceEndian) {
258 mOwnedData = malloc(size);
259 if (mOwnedData == NULL) {
260 return (mError=NO_MEMORY);
262 memcpy(mOwnedData, data, size);
266 mHeader = (const ResStringPool_header*)data;
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);
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);
286 mSize = mHeader->header.size;
287 mEntries = (const uint32_t*)
288 (((const uint8_t*)data)+mHeader->header.headerSize);
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)))
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))),
297 return (mError=BAD_TYPE);
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);
306 charSize = sizeof(char16_t);
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);
316 if (mHeader->styleCount == 0) {
318 (mHeader->header.size-mHeader->stringsStart)/charSize;
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);
327 (mHeader->stylesStart-mHeader->stringsStart)/charSize;
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);
336 if (notDeviceEndian) {
338 uint32_t* e = const_cast<uint32_t*>(mEntries);
339 for (i=0; i<mHeader->stringCount; i++) {
340 e[i] = dtohl(mEntries[i]);
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]);
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);
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);
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),
375 return (mError=BAD_TYPE);
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);
385 (mHeader->header.size-mHeader->stylesStart)/sizeof(uint32_t);
387 if (notDeviceEndian) {
389 uint32_t* e = const_cast<uint32_t*>(mEntryStyles);
390 for (i=0; i<mHeader->styleCount; i++) {
391 e[i] = dtohl(mEntryStyles[i]);
393 uint32_t* s = const_cast<uint32_t*>(mStyles);
394 for (i=0; i<mStylePoolSize; i++) {
395 s[i] = dtohl(mStyles[i]);
399 const ResStringPool_span endSpan = {
400 { htodl(ResStringPool_span::END) },
401 htodl(ResStringPool_span::END), htodl(ResStringPool_span::END)
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);
414 return (mError=NO_ERROR);
417 status_t ResStringPool::getError() const
422 void ResStringPool::uninit()
429 if (mHeader != NULL && mCache != NULL) {
430 for (size_t x = 0; x < mHeader->stringCount; x++) {
431 if (mCache[x] != NULL) {
441 #define DECODE_LENGTH(str, chrsz, len) \
443 if (*(str)&(1<<(chrsz*8-1))) { \
445 len = (((len)&((1<<(chrsz*8-1))-1))<<(chrsz*8)) + *(str); \
449 const uint16_t* ResStringPool::stringAt(size_t idx, size_t* outLen) const
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)) {
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) {
462 LOGW("Bad string block: string #%d extends to %d, past end at %d\n",
463 (int)idx, (int)(str+*outLen-strings), (int)mStringPoolSize);
466 const uint8_t* strings = (uint8_t*)mStrings;
467 const uint8_t* str = strings+off;
468 DECODE_LENGTH(str, sizeof(uint8_t), *outLen)
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) {
476 char16_t *u16str = (char16_t *)calloc(*outLen+1, sizeof(char16_t));
478 LOGW("No memory when trying to allocate decode cache for string #%d\n",
482 const unsigned char *u8src = reinterpret_cast<const unsigned char *>(str);
483 utf8_to_utf16(u8src, encLen, u16str, *outLen);
484 mCache[idx] = u16str;
487 LOGW("Bad string block: string #%d extends to %d, past end at %d\n",
488 (int)idx, (int)(str+encLen-strings), (int)mStringPoolSize);
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)));
500 const char* ResStringPool::string8At(size_t idx, size_t* outLen) const
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)) {
507 const uint8_t* strings = (uint8_t*)mStrings;
508 const uint8_t* str = strings+off;
509 DECODE_LENGTH(str, sizeof(uint8_t), *outLen)
511 DECODE_LENGTH(str, sizeof(uint8_t), encLen)
512 if ((uint32_t)(str+encLen-strings) < mStringPoolSize) {
513 return (const char*)str;
515 LOGW("Bad string block: string #%d extends to %d, past end at %d\n",
516 (int)idx, (int)(str+encLen-strings), (int)mStringPoolSize);
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)));
528 const ResStringPool_span* ResStringPool::styleAt(const ResStringPool_ref& ref) const
530 return styleAt(ref.index);
533 const ResStringPool_span* ResStringPool::styleAt(size_t idx) const
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);
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)));
548 ssize_t ResStringPool::indexOfString(const char16_t* str, size_t strLen) const
550 if (mError != NO_ERROR) {
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.
560 if (mHeader->flags&ResStringPool_header::SORTED_FLAG) {
561 // Do a binary search for the string...
563 ssize_t h = mHeader->stringCount-1;
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(),
573 c, (int)l, (int)mid, (int)h));
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(),
593 if (s && strzcmp16(s, len, str, strLen) == 0) {
599 return NAME_NOT_FOUND;
602 size_t ResStringPool::size() const
604 return (mError == NO_ERROR) ? mHeader->stringCount : 0;
607 #ifndef HAVE_ANDROID_OS
608 bool ResStringPool::isUTF8() const
610 return (mHeader->flags&ResStringPool_header::UTF8_FLAG)!=0;
614 // --------------------------------------------------------------------
615 // --------------------------------------------------------------------
616 // --------------------------------------------------------------------
618 ResXMLParser::ResXMLParser(const ResXMLTree& tree)
619 : mTree(tree), mEventCode(BAD_DOCUMENT)
623 void ResXMLParser::restart()
626 mEventCode = mTree.mError == NO_ERROR ? START_DOCUMENT : BAD_DOCUMENT;
628 const ResStringPool& ResXMLParser::getStrings() const
630 return mTree.mStrings;
633 ResXMLParser::event_code_t ResXMLParser::getEventType() const
638 ResXMLParser::event_code_t ResXMLParser::next()
640 if (mEventCode == START_DOCUMENT) {
641 mCurNode = mTree.mRootNode;
642 mCurExt = mTree.mRootExt;
643 return (mEventCode=mTree.mRootCode);
644 } else if (mEventCode >= FIRST_CHUNK_CODE) {
650 int32_t ResXMLParser::getCommentID() const
652 return mCurNode != NULL ? dtohl(mCurNode->comment.index) : -1;
655 const uint16_t* ResXMLParser::getComment(size_t* outLen) const
657 int32_t id = getCommentID();
658 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
661 uint32_t ResXMLParser::getLineNumber() const
663 return mCurNode != NULL ? dtohl(mCurNode->lineNumber) : -1;
666 int32_t ResXMLParser::getTextID() const
668 if (mEventCode == TEXT) {
669 return dtohl(((const ResXMLTree_cdataExt*)mCurExt)->data.index);
674 const uint16_t* ResXMLParser::getText(size_t* outLen) const
676 int32_t id = getTextID();
677 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
680 ssize_t ResXMLParser::getTextValue(Res_value* outValue) const
682 if (mEventCode == TEXT) {
683 outValue->copyFrom_dtoh(((const ResXMLTree_cdataExt*)mCurExt)->typedData);
684 return sizeof(Res_value);
689 int32_t ResXMLParser::getNamespacePrefixID() const
691 if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) {
692 return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->prefix.index);
697 const uint16_t* ResXMLParser::getNamespacePrefix(size_t* outLen) const
699 int32_t id = getNamespacePrefixID();
700 //printf("prefix=%d event=%p\n", id, mEventCode);
701 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
704 int32_t ResXMLParser::getNamespaceUriID() const
706 if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) {
707 return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->uri.index);
712 const uint16_t* ResXMLParser::getNamespaceUri(size_t* outLen) const
714 int32_t id = getNamespaceUriID();
715 //printf("uri=%d event=%p\n", id, mEventCode);
716 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
719 int32_t ResXMLParser::getElementNamespaceID() const
721 if (mEventCode == START_TAG) {
722 return dtohl(((const ResXMLTree_attrExt*)mCurExt)->ns.index);
724 if (mEventCode == END_TAG) {
725 return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->ns.index);
730 const uint16_t* ResXMLParser::getElementNamespace(size_t* outLen) const
732 int32_t id = getElementNamespaceID();
733 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
736 int32_t ResXMLParser::getElementNameID() const
738 if (mEventCode == START_TAG) {
739 return dtohl(((const ResXMLTree_attrExt*)mCurExt)->name.index);
741 if (mEventCode == END_TAG) {
742 return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->name.index);
747 const uint16_t* ResXMLParser::getElementName(size_t* outLen) const
749 int32_t id = getElementNameID();
750 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
753 size_t ResXMLParser::getAttributeCount() const
755 if (mEventCode == START_TAG) {
756 return dtohs(((const ResXMLTree_attrExt*)mCurExt)->attributeCount);
761 int32_t ResXMLParser::getAttributeNamespaceID(size_t idx) const
763 if (mEventCode == START_TAG) {
764 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
765 if (idx < dtohs(tag->attributeCount)) {
766 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
767 (((const uint8_t*)tag)
768 + dtohs(tag->attributeStart)
769 + (dtohs(tag->attributeSize)*idx));
770 return dtohl(attr->ns.index);
776 const uint16_t* ResXMLParser::getAttributeNamespace(size_t idx, size_t* outLen) const
778 int32_t id = getAttributeNamespaceID(idx);
779 //printf("attribute namespace=%d idx=%d event=%p\n", id, idx, mEventCode);
780 //XML_NOISY(printf("getAttributeNamespace 0x%x=0x%x\n", idx, id));
781 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
784 int32_t ResXMLParser::getAttributeNameID(size_t idx) const
786 if (mEventCode == START_TAG) {
787 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
788 if (idx < dtohs(tag->attributeCount)) {
789 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
790 (((const uint8_t*)tag)
791 + dtohs(tag->attributeStart)
792 + (dtohs(tag->attributeSize)*idx));
793 return dtohl(attr->name.index);
799 const uint16_t* ResXMLParser::getAttributeName(size_t idx, size_t* outLen) const
801 int32_t id = getAttributeNameID(idx);
802 //printf("attribute name=%d idx=%d event=%p\n", id, idx, mEventCode);
803 //XML_NOISY(printf("getAttributeName 0x%x=0x%x\n", idx, id));
804 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
807 uint32_t ResXMLParser::getAttributeNameResID(size_t idx) const
809 int32_t id = getAttributeNameID(idx);
810 if (id >= 0 && (size_t)id < mTree.mNumResIds) {
811 return dtohl(mTree.mResIds[id]);
816 int32_t ResXMLParser::getAttributeValueStringID(size_t idx) const
818 if (mEventCode == START_TAG) {
819 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
820 if (idx < dtohs(tag->attributeCount)) {
821 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
822 (((const uint8_t*)tag)
823 + dtohs(tag->attributeStart)
824 + (dtohs(tag->attributeSize)*idx));
825 return dtohl(attr->rawValue.index);
831 const uint16_t* ResXMLParser::getAttributeStringValue(size_t idx, size_t* outLen) const
833 int32_t id = getAttributeValueStringID(idx);
834 //XML_NOISY(printf("getAttributeValue 0x%x=0x%x\n", idx, id));
835 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
838 int32_t ResXMLParser::getAttributeDataType(size_t idx) const
840 if (mEventCode == START_TAG) {
841 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
842 if (idx < dtohs(tag->attributeCount)) {
843 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
844 (((const uint8_t*)tag)
845 + dtohs(tag->attributeStart)
846 + (dtohs(tag->attributeSize)*idx));
847 return attr->typedValue.dataType;
850 return Res_value::TYPE_NULL;
853 int32_t ResXMLParser::getAttributeData(size_t idx) const
855 if (mEventCode == START_TAG) {
856 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
857 if (idx < dtohs(tag->attributeCount)) {
858 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
859 (((const uint8_t*)tag)
860 + dtohs(tag->attributeStart)
861 + (dtohs(tag->attributeSize)*idx));
862 return dtohl(attr->typedValue.data);
868 ssize_t ResXMLParser::getAttributeValue(size_t idx, Res_value* outValue) const
870 if (mEventCode == START_TAG) {
871 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
872 if (idx < dtohs(tag->attributeCount)) {
873 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
874 (((const uint8_t*)tag)
875 + dtohs(tag->attributeStart)
876 + (dtohs(tag->attributeSize)*idx));
877 outValue->copyFrom_dtoh(attr->typedValue);
878 return sizeof(Res_value);
884 ssize_t ResXMLParser::indexOfAttribute(const char* ns, const char* attr) const
886 String16 nsStr(ns != NULL ? ns : "");
887 String16 attrStr(attr);
888 return indexOfAttribute(ns ? nsStr.string() : NULL, ns ? nsStr.size() : 0,
889 attrStr.string(), attrStr.size());
892 ssize_t ResXMLParser::indexOfAttribute(const char16_t* ns, size_t nsLen,
893 const char16_t* attr, size_t attrLen) const
895 if (mEventCode == START_TAG) {
896 const size_t N = getAttributeCount();
897 for (size_t i=0; i<N; i++) {
898 size_t curNsLen, curAttrLen;
899 const char16_t* curNs = getAttributeNamespace(i, &curNsLen);
900 const char16_t* curAttr = getAttributeName(i, &curAttrLen);
901 //printf("%d: ns=%p attr=%p curNs=%p curAttr=%p\n",
902 // i, ns, attr, curNs, curAttr);
903 //printf(" --> attr=%s, curAttr=%s\n",
904 // String8(attr).string(), String8(curAttr).string());
905 if (attr && curAttr && (strzcmp16(attr, attrLen, curAttr, curAttrLen) == 0)) {
907 if (curNs == NULL) return i;
908 } else if (curNs != NULL) {
909 //printf(" --> ns=%s, curNs=%s\n",
910 // String8(ns).string(), String8(curNs).string());
911 if (strzcmp16(ns, nsLen, curNs, curNsLen) == 0) return i;
917 return NAME_NOT_FOUND;
920 ssize_t ResXMLParser::indexOfID() const
922 if (mEventCode == START_TAG) {
923 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->idIndex);
924 if (idx > 0) return (idx-1);
926 return NAME_NOT_FOUND;
929 ssize_t ResXMLParser::indexOfClass() const
931 if (mEventCode == START_TAG) {
932 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->classIndex);
933 if (idx > 0) return (idx-1);
935 return NAME_NOT_FOUND;
938 ssize_t ResXMLParser::indexOfStyle() const
940 if (mEventCode == START_TAG) {
941 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->styleIndex);
942 if (idx > 0) return (idx-1);
944 return NAME_NOT_FOUND;
947 ResXMLParser::event_code_t ResXMLParser::nextNode()
949 if (mEventCode < 0) {
954 const ResXMLTree_node* next = (const ResXMLTree_node*)
955 (((const uint8_t*)mCurNode) + dtohl(mCurNode->header.size));
956 //LOGW("Next node: prev=%p, next=%p\n", mCurNode, next);
958 if (((const uint8_t*)next) >= mTree.mDataEnd) {
960 return (mEventCode=END_DOCUMENT);
963 if (mTree.validateNode(next) != NO_ERROR) {
965 return (mEventCode=BAD_DOCUMENT);
969 const uint16_t headerSize = dtohs(next->header.headerSize);
970 const uint32_t totalSize = dtohl(next->header.size);
971 mCurExt = ((const uint8_t*)next) + headerSize;
972 size_t minExtSize = 0;
973 event_code_t eventCode = (event_code_t)dtohs(next->header.type);
974 switch ((mEventCode=eventCode)) {
975 case RES_XML_START_NAMESPACE_TYPE:
976 case RES_XML_END_NAMESPACE_TYPE:
977 minExtSize = sizeof(ResXMLTree_namespaceExt);
979 case RES_XML_START_ELEMENT_TYPE:
980 minExtSize = sizeof(ResXMLTree_attrExt);
982 case RES_XML_END_ELEMENT_TYPE:
983 minExtSize = sizeof(ResXMLTree_endElementExt);
985 case RES_XML_CDATA_TYPE:
986 minExtSize = sizeof(ResXMLTree_cdataExt);
989 LOGW("Unknown XML block: header type %d in node at %d\n",
990 (int)dtohs(next->header.type),
991 (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)));
995 if ((totalSize-headerSize) < minExtSize) {
996 LOGW("Bad XML block: header type 0x%x in node at 0x%x has size %d, need %d\n",
997 (int)dtohs(next->header.type),
998 (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)),
999 (int)(totalSize-headerSize), (int)minExtSize);
1000 return (mEventCode=BAD_DOCUMENT);
1003 //printf("CurNode=%p, CurExt=%p, headerSize=%d, minExtSize=%d\n",
1004 // mCurNode, mCurExt, headerSize, minExtSize);
1010 void ResXMLParser::getPosition(ResXMLParser::ResXMLPosition* pos) const
1012 pos->eventCode = mEventCode;
1013 pos->curNode = mCurNode;
1014 pos->curExt = mCurExt;
1017 void ResXMLParser::setPosition(const ResXMLParser::ResXMLPosition& pos)
1019 mEventCode = pos.eventCode;
1020 mCurNode = pos.curNode;
1021 mCurExt = pos.curExt;
1025 // --------------------------------------------------------------------
1027 static volatile int32_t gCount = 0;
1029 ResXMLTree::ResXMLTree()
1030 : ResXMLParser(*this)
1031 , mError(NO_INIT), mOwnedData(NULL)
1033 //LOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1);
1037 ResXMLTree::ResXMLTree(const void* data, size_t size, bool copyData)
1038 : ResXMLParser(*this)
1039 , mError(NO_INIT), mOwnedData(NULL)
1041 //LOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1);
1042 setTo(data, size, copyData);
1045 ResXMLTree::~ResXMLTree()
1047 //LOGI("Destroying ResXMLTree in %p #%d\n", this, android_atomic_dec(&gCount)-1);
1051 status_t ResXMLTree::setTo(const void* data, size_t size, bool copyData)
1054 mEventCode = START_DOCUMENT;
1057 mOwnedData = malloc(size);
1058 if (mOwnedData == NULL) {
1059 return (mError=NO_MEMORY);
1061 memcpy(mOwnedData, data, size);
1065 mHeader = (const ResXMLTree_header*)data;
1066 mSize = dtohl(mHeader->header.size);
1067 if (dtohs(mHeader->header.headerSize) > mSize || mSize > size) {
1068 LOGW("Bad XML block: header size %d or total size %d is larger than data size %d\n",
1069 (int)dtohs(mHeader->header.headerSize),
1070 (int)dtohl(mHeader->header.size), (int)size);
1075 mDataEnd = ((const uint8_t*)mHeader) + mSize;
1082 // First look for a couple interesting chunks: the string block
1083 // and first XML node.
1084 const ResChunk_header* chunk =
1085 (const ResChunk_header*)(((const uint8_t*)mHeader) + dtohs(mHeader->header.headerSize));
1086 const ResChunk_header* lastChunk = chunk;
1087 while (((const uint8_t*)chunk) < (mDataEnd-sizeof(ResChunk_header)) &&
1088 ((const uint8_t*)chunk) < (mDataEnd-dtohl(chunk->size))) {
1089 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), mDataEnd, "XML");
1090 if (err != NO_ERROR) {
1094 const uint16_t type = dtohs(chunk->type);
1095 const size_t size = dtohl(chunk->size);
1096 XML_NOISY(printf("Scanning @ %p: type=0x%x, size=0x%x\n",
1097 (void*)(((uint32_t)chunk)-((uint32_t)mHeader)), type, size));
1098 if (type == RES_STRING_POOL_TYPE) {
1099 mStrings.setTo(chunk, size);
1100 } else if (type == RES_XML_RESOURCE_MAP_TYPE) {
1101 mResIds = (const uint32_t*)
1102 (((const uint8_t*)chunk)+dtohs(chunk->headerSize));
1103 mNumResIds = (dtohl(chunk->size)-dtohs(chunk->headerSize))/sizeof(uint32_t);
1104 } else if (type >= RES_XML_FIRST_CHUNK_TYPE
1105 && type <= RES_XML_LAST_CHUNK_TYPE) {
1106 if (validateNode((const ResXMLTree_node*)chunk) != NO_ERROR) {
1110 mCurNode = (const ResXMLTree_node*)lastChunk;
1111 if (nextNode() == BAD_DOCUMENT) {
1115 mRootNode = mCurNode;
1117 mRootCode = mEventCode;
1120 XML_NOISY(printf("Skipping unknown chunk!\n"));
1123 chunk = (const ResChunk_header*)
1124 (((const uint8_t*)chunk) + size);
1127 if (mRootNode == NULL) {
1128 LOGW("Bad XML block: no root element node found\n");
1133 mError = mStrings.getError();
1140 status_t ResXMLTree::getError() const
1145 void ResXMLTree::uninit()
1156 status_t ResXMLTree::validateNode(const ResXMLTree_node* node) const
1158 const uint16_t eventCode = dtohs(node->header.type);
1160 status_t err = validate_chunk(
1161 &node->header, sizeof(ResXMLTree_node),
1162 mDataEnd, "ResXMLTree_node");
1164 if (err >= NO_ERROR) {
1165 // Only perform additional validation on START nodes
1166 if (eventCode != RES_XML_START_ELEMENT_TYPE) {
1170 const uint16_t headerSize = dtohs(node->header.headerSize);
1171 const uint32_t size = dtohl(node->header.size);
1172 const ResXMLTree_attrExt* attrExt = (const ResXMLTree_attrExt*)
1173 (((const uint8_t*)node) + headerSize);
1174 // check for sensical values pulled out of the stream so far...
1175 if ((size >= headerSize + sizeof(ResXMLTree_attrExt))
1176 && ((void*)attrExt > (void*)node)) {
1177 const size_t attrSize = ((size_t)dtohs(attrExt->attributeSize))
1178 * dtohs(attrExt->attributeCount);
1179 if ((dtohs(attrExt->attributeStart)+attrSize) <= (size-headerSize)) {
1182 LOGW("Bad XML block: node attributes use 0x%x bytes, only have 0x%x bytes\n",
1183 (unsigned int)(dtohs(attrExt->attributeStart)+attrSize),
1184 (unsigned int)(size-headerSize));
1187 LOGW("Bad XML start block: node header size 0x%x, size 0x%x\n",
1188 (unsigned int)headerSize, (unsigned int)size);
1196 const bool isStart = dtohs(node->header.type) == RES_XML_START_ELEMENT_TYPE;
1198 const uint16_t headerSize = dtohs(node->header.headerSize);
1199 const uint32_t size = dtohl(node->header.size);
1201 if (headerSize >= (isStart ? sizeof(ResXMLTree_attrNode) : sizeof(ResXMLTree_node))) {
1202 if (size >= headerSize) {
1203 if (((const uint8_t*)node) <= (mDataEnd-size)) {
1207 if ((((size_t)dtohs(node->attributeSize))*dtohs(node->attributeCount))
1208 <= (size-headerSize)) {
1211 LOGW("Bad XML block: node attributes use 0x%x bytes, only have 0x%x bytes\n",
1212 ((int)dtohs(node->attributeSize))*dtohs(node->attributeCount),
1213 (int)(size-headerSize));
1216 LOGW("Bad XML block: node at 0x%x extends beyond data end 0x%x\n",
1217 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)), (int)mSize);
1220 LOGW("Bad XML block: node at 0x%x header size 0x%x smaller than total size 0x%x\n",
1221 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)),
1222 (int)headerSize, (int)size);
1225 LOGW("Bad XML block: node at 0x%x header size 0x%x too small\n",
1226 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)),
1232 // --------------------------------------------------------------------
1233 // --------------------------------------------------------------------
1234 // --------------------------------------------------------------------
1236 struct ResTable::Header
1238 Header(ResTable* _owner) : owner(_owner), ownedData(NULL), header(NULL) { }
1240 ResTable* const owner;
1242 const ResTable_header* header;
1244 const uint8_t* dataEnd;
1248 ResStringPool values;
1251 struct ResTable::Type
1253 Type(const Header* _header, const Package* _package, size_t count)
1254 : header(_header), package(_package), entryCount(count),
1255 typeSpec(NULL), typeSpecFlags(NULL) { }
1256 const Header* const header;
1257 const Package* const package;
1258 const size_t entryCount;
1259 const ResTable_typeSpec* typeSpec;
1260 const uint32_t* typeSpecFlags;
1261 Vector<const ResTable_type*> configs;
1264 struct ResTable::Package
1266 Package(ResTable* _owner, const Header* _header, const ResTable_package* _package)
1267 : owner(_owner), header(_header), package(_package) { }
1270 size_t i = types.size();
1277 ResTable* const owner;
1278 const Header* const header;
1279 const ResTable_package* const package;
1280 Vector<Type*> types;
1282 ResStringPool typeStrings;
1283 ResStringPool keyStrings;
1285 const Type* getType(size_t idx) const {
1286 return idx < types.size() ? types[idx] : NULL;
1290 // A group of objects describing a particular resource package.
1291 // The first in 'package' is always the root object (from the resource
1292 // table that defined the package); the ones after are skins on top of it.
1293 struct ResTable::PackageGroup
1295 PackageGroup(ResTable* _owner, const String16& _name, uint32_t _id)
1296 : owner(_owner), name(_name), id(_id), typeCount(0), bags(NULL) { }
1299 const size_t N = packages.size();
1300 for (size_t i=0; i<N; i++) {
1301 Package* pkg = packages[i];
1302 if (pkg->owner == owner) {
1308 void clearBagCache() {
1310 TABLE_NOISY(printf("bags=%p\n", bags));
1311 Package* pkg = packages[0];
1312 TABLE_NOISY(printf("typeCount=%x\n", typeCount));
1313 for (size_t i=0; i<typeCount; i++) {
1314 TABLE_NOISY(printf("type=%d\n", i));
1315 const Type* type = pkg->getType(i);
1317 bag_set** typeBags = bags[i];
1318 TABLE_NOISY(printf("typeBags=%p\n", typeBags));
1320 TABLE_NOISY(printf("type->entryCount=%x\n", type->entryCount));
1321 const size_t N = type->entryCount;
1322 for (size_t j=0; j<N; j++) {
1323 if (typeBags[j] && typeBags[j] != (bag_set*)0xFFFFFFFF)
1335 ResTable* const owner;
1336 String16 const name;
1338 Vector<Package*> packages;
1340 // This is for finding typeStrings and other common package stuff.
1341 Package* basePackage;
1343 // For quick access.
1346 // Computed attribute bags, first indexed by the type and second
1347 // by the entry in that type.
1351 struct ResTable::bag_set
1353 size_t numAttrs; // number in array
1354 size_t availAttrs; // total space in array
1355 uint32_t typeSpecFlags;
1356 // Followed by 'numAttr' bag_entry structures.
1359 ResTable::Theme::Theme(const ResTable& table)
1362 memset(mPackages, 0, sizeof(mPackages));
1365 ResTable::Theme::~Theme()
1367 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
1368 package_info* pi = mPackages[i];
1375 void ResTable::Theme::free_package(package_info* pi)
1377 for (size_t j=0; j<pi->numTypes; j++) {
1378 theme_entry* te = pi->types[j].entries;
1386 ResTable::Theme::package_info* ResTable::Theme::copy_package(package_info* pi)
1388 package_info* newpi = (package_info*)malloc(
1389 sizeof(package_info) + (pi->numTypes*sizeof(type_info)));
1390 newpi->numTypes = pi->numTypes;
1391 for (size_t j=0; j<newpi->numTypes; j++) {
1392 size_t cnt = pi->types[j].numEntries;
1393 newpi->types[j].numEntries = cnt;
1394 theme_entry* te = pi->types[j].entries;
1396 theme_entry* newte = (theme_entry*)malloc(cnt*sizeof(theme_entry));
1397 newpi->types[j].entries = newte;
1398 memcpy(newte, te, cnt*sizeof(theme_entry));
1400 newpi->types[j].entries = NULL;
1406 status_t ResTable::Theme::applyStyle(uint32_t resID, bool force)
1408 const bag_entry* bag;
1409 uint32_t bagTypeSpecFlags = 0;
1411 const ssize_t N = mTable.getBagLocked(resID, &bag, &bagTypeSpecFlags);
1412 TABLE_NOISY(LOGV("Applying style 0x%08x to theme %p, count=%d", resID, this, N));
1418 uint32_t curPackage = 0xffffffff;
1419 ssize_t curPackageIndex = 0;
1420 package_info* curPI = NULL;
1421 uint32_t curType = 0xffffffff;
1422 size_t numEntries = 0;
1423 theme_entry* curEntries = NULL;
1425 const bag_entry* end = bag + N;
1427 const uint32_t attrRes = bag->map.name.ident;
1428 const uint32_t p = Res_GETPACKAGE(attrRes);
1429 const uint32_t t = Res_GETTYPE(attrRes);
1430 const uint32_t e = Res_GETENTRY(attrRes);
1432 if (curPackage != p) {
1433 const ssize_t pidx = mTable.getResourcePackageIndex(attrRes);
1435 LOGE("Style contains key with bad package: 0x%08x\n", attrRes);
1440 curPackageIndex = pidx;
1441 curPI = mPackages[pidx];
1442 if (curPI == NULL) {
1443 PackageGroup* const grp = mTable.mPackageGroups[pidx];
1444 int cnt = grp->typeCount;
1445 curPI = (package_info*)malloc(
1446 sizeof(package_info) + (cnt*sizeof(type_info)));
1447 curPI->numTypes = cnt;
1448 memset(curPI->types, 0, cnt*sizeof(type_info));
1449 mPackages[pidx] = curPI;
1451 curType = 0xffffffff;
1454 if (t >= curPI->numTypes) {
1455 LOGE("Style contains key with bad type: 0x%08x\n", attrRes);
1460 curEntries = curPI->types[t].entries;
1461 if (curEntries == NULL) {
1462 PackageGroup* const grp = mTable.mPackageGroups[curPackageIndex];
1463 const Type* type = grp->packages[0]->getType(t);
1464 int cnt = type != NULL ? type->entryCount : 0;
1465 curEntries = (theme_entry*)malloc(cnt*sizeof(theme_entry));
1466 memset(curEntries, Res_value::TYPE_NULL, cnt*sizeof(theme_entry));
1467 curPI->types[t].numEntries = cnt;
1468 curPI->types[t].entries = curEntries;
1470 numEntries = curPI->types[t].numEntries;
1472 if (e >= numEntries) {
1473 LOGE("Style contains key with bad entry: 0x%08x\n", attrRes);
1477 theme_entry* curEntry = curEntries + e;
1478 TABLE_NOISY(LOGV("Attr 0x%08x: type=0x%x, data=0x%08x; curType=0x%x",
1479 attrRes, bag->map.value.dataType, bag->map.value.data,
1480 curEntry->value.dataType));
1481 if (force || curEntry->value.dataType == Res_value::TYPE_NULL) {
1482 curEntry->stringBlock = bag->stringBlock;
1483 curEntry->typeSpecFlags |= bagTypeSpecFlags;
1484 curEntry->value = bag->map.value;
1492 //LOGI("Applying style 0x%08x (force=%d) theme %p...\n", resID, force, this);
1498 status_t ResTable::Theme::setTo(const Theme& other)
1500 //LOGI("Setting theme %p from theme %p...\n", this, &other);
1502 //other.dumpToLog();
1504 if (&mTable == &other.mTable) {
1505 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
1506 if (mPackages[i] != NULL) {
1507 free_package(mPackages[i]);
1509 if (other.mPackages[i] != NULL) {
1510 mPackages[i] = copy_package(other.mPackages[i]);
1512 mPackages[i] = NULL;
1516 // @todo: need to really implement this, not just copy
1517 // the system package (which is still wrong because it isn't
1518 // fixing up resource references).
1519 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
1520 if (mPackages[i] != NULL) {
1521 free_package(mPackages[i]);
1523 if (i == 0 && other.mPackages[i] != NULL) {
1524 mPackages[i] = copy_package(other.mPackages[i]);
1526 mPackages[i] = NULL;
1531 //LOGI("Final theme:");
1537 ssize_t ResTable::Theme::getAttribute(uint32_t resID, Res_value* outValue,
1538 uint32_t* outTypeSpecFlags) const
1542 if (outTypeSpecFlags != NULL) *outTypeSpecFlags = 0;
1545 const ssize_t p = mTable.getResourcePackageIndex(resID);
1546 const uint32_t t = Res_GETTYPE(resID);
1547 const uint32_t e = Res_GETENTRY(resID);
1549 TABLE_THEME(LOGI("Looking up attr 0x%08x in theme %p", resID, this));
1552 const package_info* const pi = mPackages[p];
1553 TABLE_THEME(LOGI("Found package: %p", pi));
1555 TABLE_THEME(LOGI("Desired type index is %ld in avail %d", t, pi->numTypes));
1556 if (t < pi->numTypes) {
1557 const type_info& ti = pi->types[t];
1558 TABLE_THEME(LOGI("Desired entry index is %ld in avail %d", e, ti.numEntries));
1559 if (e < ti.numEntries) {
1560 const theme_entry& te = ti.entries[e];
1561 if (outTypeSpecFlags != NULL) {
1562 *outTypeSpecFlags |= te.typeSpecFlags;
1564 TABLE_THEME(LOGI("Theme value: type=0x%x, data=0x%08x",
1565 te.value.dataType, te.value.data));
1566 const uint8_t type = te.value.dataType;
1567 if (type == Res_value::TYPE_ATTRIBUTE) {
1570 resID = te.value.data;
1573 LOGW("Too many attribute references, stopped at: 0x%08x\n", resID);
1575 } else if (type != Res_value::TYPE_NULL) {
1576 *outValue = te.value;
1577 return te.stringBlock;
1591 ssize_t ResTable::Theme::resolveAttributeReference(Res_value* inOutValue,
1592 ssize_t blockIndex, uint32_t* outLastRef,
1593 uint32_t* inoutTypeSpecFlags, ResTable_config* inoutConfig) const
1595 //printf("Resolving type=0x%x\n", inOutValue->dataType);
1596 if (inOutValue->dataType == Res_value::TYPE_ATTRIBUTE) {
1597 uint32_t newTypeSpecFlags;
1598 blockIndex = getAttribute(inOutValue->data, inOutValue, &newTypeSpecFlags);
1599 TABLE_THEME(LOGI("Resolving attr reference: blockIndex=%d, type=0x%x, data=%p\n",
1600 (int)blockIndex, (int)inOutValue->dataType, (void*)inOutValue->data));
1601 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newTypeSpecFlags;
1602 //printf("Retrieved attribute new type=0x%x\n", inOutValue->dataType);
1603 if (blockIndex < 0) {
1607 return mTable.resolveReference(inOutValue, blockIndex, outLastRef,
1608 inoutTypeSpecFlags, inoutConfig);
1611 void ResTable::Theme::dumpToLog() const
1613 LOGI("Theme %p:\n", this);
1614 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
1615 package_info* pi = mPackages[i];
1616 if (pi == NULL) continue;
1618 LOGI(" Package #0x%02x:\n", (int)(i+1));
1619 for (size_t j=0; j<pi->numTypes; j++) {
1620 type_info& ti = pi->types[j];
1621 if (ti.numEntries == 0) continue;
1623 LOGI(" Type #0x%02x:\n", (int)(j+1));
1624 for (size_t k=0; k<ti.numEntries; k++) {
1625 theme_entry& te = ti.entries[k];
1626 if (te.value.dataType == Res_value::TYPE_NULL) continue;
1627 LOGI(" 0x%08x: t=0x%x, d=0x%08x (block=%d)\n",
1628 (int)Res_MAKEID(i, j, k),
1629 te.value.dataType, (int)te.value.data, (int)te.stringBlock);
1635 ResTable::ResTable()
1638 memset(&mParams, 0, sizeof(mParams));
1639 memset(mPackageMap, 0, sizeof(mPackageMap));
1640 //LOGI("Creating ResTable %p\n", this);
1643 ResTable::ResTable(const void* data, size_t size, void* cookie, bool copyData)
1646 memset(&mParams, 0, sizeof(mParams));
1647 memset(mPackageMap, 0, sizeof(mPackageMap));
1648 add(data, size, cookie, copyData);
1649 LOG_FATAL_IF(mError != NO_ERROR, "Error parsing resource table");
1650 //LOGI("Creating ResTable %p\n", this);
1653 ResTable::~ResTable()
1655 //LOGI("Destroying ResTable in %p\n", this);
1659 inline ssize_t ResTable::getResourcePackageIndex(uint32_t resID) const
1661 return ((ssize_t)mPackageMap[Res_GETPACKAGE(resID)+1])-1;
1664 status_t ResTable::add(const void* data, size_t size, void* cookie, bool copyData)
1666 return add(data, size, cookie, NULL, copyData);
1669 status_t ResTable::add(Asset* asset, void* cookie, bool copyData)
1671 const void* data = asset->getBuffer(true);
1673 LOGW("Unable to get buffer of resource asset file");
1674 return UNKNOWN_ERROR;
1676 size_t size = (size_t)asset->getLength();
1677 return add(data, size, cookie, asset, copyData);
1680 status_t ResTable::add(ResTable* src)
1682 mError = src->mError;
1684 for (size_t i=0; i<src->mHeaders.size(); i++) {
1685 mHeaders.add(src->mHeaders[i]);
1688 for (size_t i=0; i<src->mPackageGroups.size(); i++) {
1689 PackageGroup* srcPg = src->mPackageGroups[i];
1690 PackageGroup* pg = new PackageGroup(this, srcPg->name, srcPg->id);
1691 for (size_t j=0; j<srcPg->packages.size(); j++) {
1692 pg->packages.add(srcPg->packages[j]);
1694 pg->basePackage = srcPg->basePackage;
1695 pg->typeCount = srcPg->typeCount;
1696 mPackageGroups.add(pg);
1699 memcpy(mPackageMap, src->mPackageMap, sizeof(mPackageMap));
1704 status_t ResTable::add(const void* data, size_t size, void* cookie,
1705 Asset* asset, bool copyData)
1707 if (!data) return NO_ERROR;
1708 Header* header = new Header(this);
1709 header->index = mHeaders.size();
1710 header->cookie = cookie;
1711 mHeaders.add(header);
1713 const bool notDeviceEndian = htods(0xf0) != 0xf0;
1716 LOGV("Adding resources to ResTable: data=%p, size=0x%x, cookie=%p, asset=%p, copy=%d\n",
1717 data, size, cookie, asset, copyData));
1719 if (copyData || notDeviceEndian) {
1720 header->ownedData = malloc(size);
1721 if (header->ownedData == NULL) {
1722 return (mError=NO_MEMORY);
1724 memcpy(header->ownedData, data, size);
1725 data = header->ownedData;
1728 header->header = (const ResTable_header*)data;
1729 header->size = dtohl(header->header->header.size);
1730 //LOGI("Got size 0x%x, again size 0x%x, raw size 0x%x\n", header->size,
1731 // dtohl(header->header->header.size), header->header->header.size);
1732 LOAD_TABLE_NOISY(LOGV("Loading ResTable @%p:\n", header->header));
1733 LOAD_TABLE_NOISY(printHexData(2, header->header, header->size < 256 ? header->size : 256,
1734 16, 16, 0, false, printToLogFunc));
1735 if (dtohs(header->header->header.headerSize) > header->size
1736 || header->size > size) {
1737 LOGW("Bad resource table: header size 0x%x or total size 0x%x is larger than data size 0x%x\n",
1738 (int)dtohs(header->header->header.headerSize),
1739 (int)header->size, (int)size);
1740 return (mError=BAD_TYPE);
1742 if (((dtohs(header->header->header.headerSize)|header->size)&0x3) != 0) {
1743 LOGW("Bad resource table: header size 0x%x or total size 0x%x is not on an integer boundary\n",
1744 (int)dtohs(header->header->header.headerSize),
1746 return (mError=BAD_TYPE);
1748 header->dataEnd = ((const uint8_t*)header->header) + header->size;
1750 // Iterate through all chunks.
1751 size_t curPackage = 0;
1753 const ResChunk_header* chunk =
1754 (const ResChunk_header*)(((const uint8_t*)header->header)
1755 + dtohs(header->header->header.headerSize));
1756 while (((const uint8_t*)chunk) <= (header->dataEnd-sizeof(ResChunk_header)) &&
1757 ((const uint8_t*)chunk) <= (header->dataEnd-dtohl(chunk->size))) {
1758 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), header->dataEnd, "ResTable");
1759 if (err != NO_ERROR) {
1760 return (mError=err);
1762 TABLE_NOISY(LOGV("Chunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n",
1763 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
1764 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header))));
1765 const size_t csize = dtohl(chunk->size);
1766 const uint16_t ctype = dtohs(chunk->type);
1767 if (ctype == RES_STRING_POOL_TYPE) {
1768 if (header->values.getError() != NO_ERROR) {
1769 // Only use the first string chunk; ignore any others that
1771 status_t err = header->values.setTo(chunk, csize);
1772 if (err != NO_ERROR) {
1773 return (mError=err);
1776 LOGW("Multiple string chunks found in resource table.");
1778 } else if (ctype == RES_TABLE_PACKAGE_TYPE) {
1779 if (curPackage >= dtohl(header->header->packageCount)) {
1780 LOGW("More package chunks were found than the %d declared in the header.",
1781 dtohl(header->header->packageCount));
1782 return (mError=BAD_TYPE);
1784 if (parsePackage((ResTable_package*)chunk, header) != NO_ERROR) {
1789 LOGW("Unknown chunk type %p in table at %p.\n",
1790 (void*)(int)(ctype),
1791 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)));
1793 chunk = (const ResChunk_header*)
1794 (((const uint8_t*)chunk) + csize);
1797 if (curPackage < dtohl(header->header->packageCount)) {
1798 LOGW("Fewer package chunks (%d) were found than the %d declared in the header.",
1799 (int)curPackage, dtohl(header->header->packageCount));
1800 return (mError=BAD_TYPE);
1802 mError = header->values.getError();
1803 if (mError != NO_ERROR) {
1804 LOGW("No string values found in resource table!");
1806 TABLE_NOISY(LOGV("Returning from add with mError=%d\n", mError));
1810 status_t ResTable::getError() const
1815 void ResTable::uninit()
1818 size_t N = mPackageGroups.size();
1819 for (size_t i=0; i<N; i++) {
1820 PackageGroup* g = mPackageGroups[i];
1823 N = mHeaders.size();
1824 for (size_t i=0; i<N; i++) {
1825 Header* header = mHeaders[i];
1826 if (header->owner == this) {
1827 if (header->ownedData) {
1828 free(header->ownedData);
1834 mPackageGroups.clear();
1838 bool ResTable::getResourceName(uint32_t resID, resource_name* outName) const
1840 if (mError != NO_ERROR) {
1844 const ssize_t p = getResourcePackageIndex(resID);
1845 const int t = Res_GETTYPE(resID);
1846 const int e = Res_GETENTRY(resID);
1849 if (Res_GETPACKAGE(resID)+1 == 0) {
1850 LOGW("No package identifier when getting name for resource number 0x%08x", resID);
1852 LOGW("No known package when getting name for resource number 0x%08x", resID);
1857 LOGW("No type identifier when getting name for resource number 0x%08x", resID);
1861 const PackageGroup* const grp = mPackageGroups[p];
1863 LOGW("Bad identifier when getting name for resource number 0x%08x", resID);
1866 if (grp->packages.size() > 0) {
1867 const Package* const package = grp->packages[0];
1869 const ResTable_type* type;
1870 const ResTable_entry* entry;
1871 ssize_t offset = getEntry(package, t, e, NULL, &type, &entry, NULL);
1876 outName->package = grp->name.string();
1877 outName->packageLen = grp->name.size();
1878 outName->type = grp->basePackage->typeStrings.stringAt(t, &outName->typeLen);
1879 outName->name = grp->basePackage->keyStrings.stringAt(
1880 dtohl(entry->key.index), &outName->nameLen);
1887 ssize_t ResTable::getResource(uint32_t resID, Res_value* outValue, bool mayBeBag,
1888 uint32_t* outSpecFlags, ResTable_config* outConfig) const
1890 if (mError != NO_ERROR) {
1894 const ssize_t p = getResourcePackageIndex(resID);
1895 const int t = Res_GETTYPE(resID);
1896 const int e = Res_GETENTRY(resID);
1899 if (Res_GETPACKAGE(resID)+1 == 0) {
1900 LOGW("No package identifier when getting value for resource number 0x%08x", resID);
1902 LOGW("No known package when getting value for resource number 0x%08x", resID);
1907 LOGW("No type identifier when getting value for resource number 0x%08x", resID);
1911 const Res_value* bestValue = NULL;
1912 const Package* bestPackage = NULL;
1913 ResTable_config bestItem;
1914 memset(&bestItem, 0, sizeof(bestItem)); // make the compiler shut up
1916 if (outSpecFlags != NULL) *outSpecFlags = 0;
1918 // Look through all resource packages, starting with the most
1920 const PackageGroup* const grp = mPackageGroups[p];
1922 LOGW("Bad identifier when getting value for resource number 0x%08x", resID);
1925 size_t ip = grp->packages.size();
1929 const Package* const package = grp->packages[ip];
1931 const ResTable_type* type;
1932 const ResTable_entry* entry;
1933 const Type* typeClass;
1934 ssize_t offset = getEntry(package, t, e, &mParams, &type, &entry, &typeClass);
1937 LOGW("Failure getting entry for 0x%08x (t=%d e=%d) in package %zd (error %d)\n",
1938 resID, t, e, ip, (int)offset);
1944 if ((dtohs(entry->flags)&entry->FLAG_COMPLEX) != 0) {
1946 LOGW("Requesting resource %p failed because it is complex\n",
1952 TABLE_NOISY(aout << "Resource type data: "
1953 << HexDump(type, dtohl(type->header.size)) << endl);
1955 if ((size_t)offset > (dtohl(type->header.size)-sizeof(Res_value))) {
1956 LOGW("ResTable_item at %d is beyond type chunk data %d",
1957 (int)offset, dtohl(type->header.size));
1961 const Res_value* item =
1962 (const Res_value*)(((const uint8_t*)type) + offset);
1963 ResTable_config thisConfig;
1964 thisConfig.copyFromDtoH(type->config);
1966 if (outSpecFlags != NULL) {
1967 if (typeClass->typeSpecFlags != NULL) {
1968 *outSpecFlags |= dtohl(typeClass->typeSpecFlags[e]);
1974 if (bestPackage != NULL && bestItem.isMoreSpecificThan(thisConfig)) {
1978 bestItem = thisConfig;
1980 bestPackage = package;
1983 TABLE_NOISY(printf("Found result: package %p\n", bestPackage));
1986 outValue->size = dtohs(bestValue->size);
1987 outValue->res0 = bestValue->res0;
1988 outValue->dataType = bestValue->dataType;
1989 outValue->data = dtohl(bestValue->data);
1990 if (outConfig != NULL) {
1991 *outConfig = bestItem;
1993 TABLE_NOISY(size_t len;
1994 printf("Found value: pkg=%d, type=%d, str=%s, int=%d\n",
1995 bestPackage->header->index,
1997 outValue->dataType == bestValue->TYPE_STRING
1998 ? String8(bestPackage->header->values.stringAt(
1999 outValue->data, &len)).string()
2002 return bestPackage->header->index;
2008 ssize_t ResTable::resolveReference(Res_value* value, ssize_t blockIndex,
2009 uint32_t* outLastRef, uint32_t* inoutTypeSpecFlags,
2010 ResTable_config* outConfig) const
2013 while (blockIndex >= 0 && value->dataType == value->TYPE_REFERENCE
2014 && value->data != 0 && count < 20) {
2015 if (outLastRef) *outLastRef = value->data;
2016 uint32_t lastRef = value->data;
2017 uint32_t newFlags = 0;
2018 const ssize_t newIndex = getResource(value->data, value, true, &newFlags,
2020 if (newIndex == BAD_INDEX) {
2023 TABLE_THEME(LOGI("Resolving reference %p: newIndex=%d, type=0x%x, data=%p\n",
2024 (void*)lastRef, (int)newIndex, (int)value->dataType, (void*)value->data));
2025 //printf("Getting reference 0x%08x: newIndex=%d\n", value->data, newIndex);
2026 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newFlags;
2028 // This can fail if the resource being referenced is a style...
2029 // in this case, just return the reference, and expect the
2030 // caller to deal with.
2033 blockIndex = newIndex;
2039 const char16_t* ResTable::valueToString(
2040 const Res_value* value, size_t stringBlock,
2041 char16_t tmpBuffer[TMP_BUFFER_SIZE], size_t* outLen)
2046 if (value->dataType == value->TYPE_STRING) {
2047 return getTableStringBlock(stringBlock)->stringAt(value->data, outLen);
2049 // XXX do int to string conversions.
2053 ssize_t ResTable::lockBag(uint32_t resID, const bag_entry** outBag) const
2056 ssize_t err = getBagLocked(resID, outBag);
2057 if (err < NO_ERROR) {
2058 //printf("*** get failed! unlocking\n");
2064 void ResTable::unlockBag(const bag_entry* bag) const
2066 //printf("<<< unlockBag %p\n", this);
2070 void ResTable::lock() const
2075 void ResTable::unlock() const
2080 ssize_t ResTable::getBagLocked(uint32_t resID, const bag_entry** outBag,
2081 uint32_t* outTypeSpecFlags) const
2083 if (mError != NO_ERROR) {
2087 const ssize_t p = getResourcePackageIndex(resID);
2088 const int t = Res_GETTYPE(resID);
2089 const int e = Res_GETENTRY(resID);
2092 LOGW("Invalid package identifier when getting bag for resource number 0x%08x", resID);
2096 LOGW("No type identifier when getting bag for resource number 0x%08x", resID);
2100 //printf("Get bag: id=0x%08x, p=%d, t=%d\n", resID, p, t);
2101 PackageGroup* const grp = mPackageGroups[p];
2103 LOGW("Bad identifier when getting bag for resource number 0x%08x", resID);
2107 if (t >= (int)grp->typeCount) {
2108 LOGW("Type identifier 0x%x is larger than type count 0x%x",
2109 t+1, (int)grp->typeCount);
2113 const Package* const basePackage = grp->packages[0];
2115 const Type* const typeConfigs = basePackage->getType(t);
2117 const size_t NENTRY = typeConfigs->entryCount;
2118 if (e >= (int)NENTRY) {
2119 LOGW("Entry identifier 0x%x is larger than entry count 0x%x",
2120 e, (int)typeConfigs->entryCount);
2124 // First see if we've already computed this bag...
2126 bag_set** typeSet = grp->bags[t];
2128 bag_set* set = typeSet[e];
2130 if (set != (bag_set*)0xFFFFFFFF) {
2131 if (outTypeSpecFlags != NULL) {
2132 *outTypeSpecFlags = set->typeSpecFlags;
2134 *outBag = (bag_entry*)(set+1);
2135 //LOGI("Found existing bag for: %p\n", (void*)resID);
2136 return set->numAttrs;
2138 LOGW("Attempt to retrieve bag 0x%08x which is invalid or in a cycle.",
2145 // Bag not found, we need to compute it!
2147 grp->bags = (bag_set***)malloc(sizeof(bag_set*)*grp->typeCount);
2148 if (!grp->bags) return NO_MEMORY;
2149 memset(grp->bags, 0, sizeof(bag_set*)*grp->typeCount);
2152 bag_set** typeSet = grp->bags[t];
2154 typeSet = (bag_set**)malloc(sizeof(bag_set*)*NENTRY);
2155 if (!typeSet) return NO_MEMORY;
2156 memset(typeSet, 0, sizeof(bag_set*)*NENTRY);
2157 grp->bags[t] = typeSet;
2160 // Mark that we are currently working on this one.
2161 typeSet[e] = (bag_set*)0xFFFFFFFF;
2163 // This is what we are building.
2164 bag_set* set = NULL;
2166 TABLE_NOISY(LOGI("Building bag: %p\n", (void*)resID));
2168 // Now collect all bag attributes from all packages.
2169 size_t ip = grp->packages.size();
2173 const Package* const package = grp->packages[ip];
2175 const ResTable_type* type;
2176 const ResTable_entry* entry;
2177 const Type* typeClass;
2178 LOGV("Getting entry pkg=%p, t=%d, e=%d\n", package, t, e);
2179 ssize_t offset = getEntry(package, t, e, &mParams, &type, &entry, &typeClass);
2180 LOGV("Resulting offset=%d\n", offset);
2189 if ((dtohs(entry->flags)&entry->FLAG_COMPLEX) == 0) {
2190 LOGW("Skipping entry %p in package table %d because it is not complex!\n",
2191 (void*)resID, (int)ip);
2195 const uint16_t entrySize = dtohs(entry->size);
2196 const uint32_t parent = entrySize >= sizeof(ResTable_map_entry)
2197 ? dtohl(((const ResTable_map_entry*)entry)->parent.ident) : 0;
2198 const uint32_t count = entrySize >= sizeof(ResTable_map_entry)
2199 ? dtohl(((const ResTable_map_entry*)entry)->count) : 0;
2203 TABLE_NOISY(LOGI("Found map: size=%p parent=%p count=%d\n",
2204 entrySize, parent, count));
2207 // If this map inherits from another, we need to start
2208 // with its parent's values. Otherwise start out empty.
2209 TABLE_NOISY(printf("Creating new bag, entrySize=0x%08x, parent=0x%08x\n",
2210 entrySize, parent));
2212 const bag_entry* parentBag;
2213 uint32_t parentTypeSpecFlags = 0;
2214 const ssize_t NP = getBagLocked(parent, &parentBag, &parentTypeSpecFlags);
2215 const size_t NT = ((NP >= 0) ? NP : 0) + N;
2216 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*NT);
2221 memcpy(set+1, parentBag, NP*sizeof(bag_entry));
2223 TABLE_NOISY(LOGI("Initialized new bag with %d inherited attributes.\n", NP));
2225 TABLE_NOISY(LOGI("Initialized new bag with no inherited attributes.\n"));
2228 set->availAttrs = NT;
2229 set->typeSpecFlags = parentTypeSpecFlags;
2231 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*N);
2236 set->availAttrs = N;
2237 set->typeSpecFlags = 0;
2241 if (typeClass->typeSpecFlags != NULL) {
2242 set->typeSpecFlags |= dtohl(typeClass->typeSpecFlags[e]);
2244 set->typeSpecFlags = -1;
2247 // Now merge in the new attributes...
2248 ssize_t curOff = offset;
2249 const ResTable_map* map;
2250 bag_entry* entries = (bag_entry*)(set+1);
2251 size_t curEntry = 0;
2253 TABLE_NOISY(LOGI("Starting with set %p, entries=%p, avail=%d\n",
2254 set, entries, set->availAttrs));
2255 while (pos < count) {
2256 TABLE_NOISY(printf("Now at %p\n", (void*)curOff));
2258 if ((size_t)curOff > (dtohl(type->header.size)-sizeof(ResTable_map))) {
2259 LOGW("ResTable_map at %d is beyond type chunk data %d",
2260 (int)curOff, dtohl(type->header.size));
2263 map = (const ResTable_map*)(((const uint8_t*)type) + curOff);
2266 const uint32_t newName = htodl(map->name.ident);
2268 uint32_t oldName = 0;
2269 while ((isInside=(curEntry < set->numAttrs))
2270 && (oldName=entries[curEntry].map.name.ident) < newName) {
2271 TABLE_NOISY(printf("#%d: Keeping existing attribute: 0x%08x\n",
2272 curEntry, entries[curEntry].map.name.ident));
2276 if ((!isInside) || oldName != newName) {
2277 // This is a new attribute... figure out what to do with it.
2278 if (set->numAttrs >= set->availAttrs) {
2279 // Need to alloc more memory...
2280 const size_t newAvail = set->availAttrs+N;
2281 set = (bag_set*)realloc(set,
2283 + sizeof(bag_entry)*newAvail);
2287 set->availAttrs = newAvail;
2288 entries = (bag_entry*)(set+1);
2289 TABLE_NOISY(printf("Reallocated set %p, entries=%p, avail=%d\n",
2290 set, entries, set->availAttrs));
2293 // Going in the middle, need to make space.
2294 memmove(entries+curEntry+1, entries+curEntry,
2295 sizeof(bag_entry)*(set->numAttrs-curEntry));
2298 TABLE_NOISY(printf("#%d: Inserting new attribute: 0x%08x\n",
2299 curEntry, newName));
2301 TABLE_NOISY(printf("#%d: Replacing existing attribute: 0x%08x\n",
2302 curEntry, oldName));
2305 bag_entry* cur = entries+curEntry;
2307 cur->stringBlock = package->header->index;
2308 cur->map.name.ident = newName;
2309 cur->map.value.copyFrom_dtoh(map->value);
2310 TABLE_NOISY(printf("Setting entry #%d %p: block=%d, name=0x%08x, type=%d, data=0x%08x\n",
2311 curEntry, cur, cur->stringBlock, cur->map.name.ident,
2312 cur->map.value.dataType, cur->map.value.data));
2317 const size_t size = dtohs(map->value.size);
2318 curOff += size + sizeof(*map)-sizeof(map->value);
2320 if (curEntry > set->numAttrs) {
2321 set->numAttrs = curEntry;
2325 // And this is it...
2328 if (outTypeSpecFlags != NULL) {
2329 *outTypeSpecFlags = set->typeSpecFlags;
2331 *outBag = (bag_entry*)(set+1);
2332 TABLE_NOISY(LOGI("Returning %d attrs\n", set->numAttrs));
2333 return set->numAttrs;
2338 void ResTable::setParameters(const ResTable_config* params)
2341 TABLE_GETENTRY(LOGI("Setting parameters: imsi:%d/%d lang:%c%c cnt:%c%c "
2342 "orien:%d touch:%d density:%d key:%d inp:%d nav:%d w:%d h:%d\n",
2343 params->mcc, params->mnc,
2344 params->language[0] ? params->language[0] : '-',
2345 params->language[1] ? params->language[1] : '-',
2346 params->country[0] ? params->country[0] : '-',
2347 params->country[1] ? params->country[1] : '-',
2348 params->orientation,
2349 params->touchscreen,
2354 params->screenWidth,
2355 params->screenHeight));
2357 for (size_t i=0; i<mPackageGroups.size(); i++) {
2358 TABLE_NOISY(LOGI("CLEARING BAGS FOR GROUP %d!", i));
2359 mPackageGroups[i]->clearBagCache();
2364 void ResTable::getParameters(ResTable_config* params) const
2371 struct id_name_map {
2377 const static id_name_map ID_NAMES[] = {
2378 { ResTable_map::ATTR_TYPE, 5, { '^', 't', 'y', 'p', 'e' } },
2379 { ResTable_map::ATTR_L10N, 5, { '^', 'l', '1', '0', 'n' } },
2380 { ResTable_map::ATTR_MIN, 4, { '^', 'm', 'i', 'n' } },
2381 { ResTable_map::ATTR_MAX, 4, { '^', 'm', 'a', 'x' } },
2382 { ResTable_map::ATTR_OTHER, 6, { '^', 'o', 't', 'h', 'e', 'r' } },
2383 { ResTable_map::ATTR_ZERO, 5, { '^', 'z', 'e', 'r', 'o' } },
2384 { ResTable_map::ATTR_ONE, 4, { '^', 'o', 'n', 'e' } },
2385 { ResTable_map::ATTR_TWO, 4, { '^', 't', 'w', 'o' } },
2386 { ResTable_map::ATTR_FEW, 4, { '^', 'f', 'e', 'w' } },
2387 { ResTable_map::ATTR_MANY, 5, { '^', 'm', 'a', 'n', 'y' } },
2390 uint32_t ResTable::identifierForName(const char16_t* name, size_t nameLen,
2391 const char16_t* type, size_t typeLen,
2392 const char16_t* package,
2394 uint32_t* outTypeSpecFlags) const
2396 TABLE_SUPER_NOISY(printf("Identifier for name: error=%d\n", mError));
2398 // Check for internal resource identifier as the very first thing, so
2399 // that we will always find them even when there are no resources.
2400 if (name[0] == '^') {
2401 const int N = (sizeof(ID_NAMES)/sizeof(ID_NAMES[0]));
2403 for (int i=0; i<N; i++) {
2404 const id_name_map* m = ID_NAMES + i;
2406 if (len != nameLen) {
2409 for (size_t j=1; j<len; j++) {
2410 if (m->name[j] != name[j]) {
2419 if (name[1] == 'i' && name[2] == 'n'
2420 && name[3] == 'd' && name[4] == 'e' && name[5] == 'x'
2421 && name[6] == '_') {
2422 int index = atoi(String8(name + 7, nameLen - 7).string());
2423 if (Res_CHECKID(index)) {
2424 LOGW("Array resource index: %d is too large.",
2428 return Res_MAKEARRAY(index);
2434 if (mError != NO_ERROR) {
2438 // Figure out the package and type we are looking in...
2440 const char16_t* packageEnd = NULL;
2441 const char16_t* typeEnd = NULL;
2442 const char16_t* const nameEnd = name+nameLen;
2443 const char16_t* p = name;
2444 while (p < nameEnd) {
2445 if (*p == ':') packageEnd = p;
2446 else if (*p == '/') typeEnd = p;
2449 if (*name == '@') name++;
2450 if (name >= nameEnd) {
2456 packageLen = packageEnd-name;
2457 name = packageEnd+1;
2458 } else if (!package) {
2464 typeLen = typeEnd-name;
2470 if (name >= nameEnd) {
2473 nameLen = nameEnd-name;
2475 TABLE_NOISY(printf("Looking for identifier: type=%s, name=%s, package=%s\n",
2476 String8(type, typeLen).string(),
2477 String8(name, nameLen).string(),
2478 String8(package, packageLen).string()));
2480 const size_t NG = mPackageGroups.size();
2481 for (size_t ig=0; ig<NG; ig++) {
2482 const PackageGroup* group = mPackageGroups[ig];
2484 if (strzcmp16(package, packageLen,
2485 group->name.string(), group->name.size())) {
2486 TABLE_NOISY(printf("Skipping package group: %s\n", String8(group->name).string()));
2490 const ssize_t ti = group->basePackage->typeStrings.indexOfString(type, typeLen);
2492 TABLE_NOISY(printf("Type not found in package %s\n", String8(group->name).string()));
2496 const ssize_t ei = group->basePackage->keyStrings.indexOfString(name, nameLen);
2498 TABLE_NOISY(printf("Name not found in package %s\n", String8(group->name).string()));
2502 TABLE_NOISY(printf("Search indices: type=%d, name=%d\n", ti, ei));
2504 const Type* const typeConfigs = group->packages[0]->getType(ti);
2505 if (typeConfigs == NULL || typeConfigs->configs.size() <= 0) {
2506 TABLE_NOISY(printf("Expected type structure not found in package %s for idnex %d\n",
2507 String8(group->name).string(), ti));
2510 size_t NTC = typeConfigs->configs.size();
2511 for (size_t tci=0; tci<NTC; tci++) {
2512 const ResTable_type* const ty = typeConfigs->configs[tci];
2513 const uint32_t typeOffset = dtohl(ty->entriesStart);
2515 const uint8_t* const end = ((const uint8_t*)ty) + dtohl(ty->header.size);
2516 const uint32_t* const eindex = (const uint32_t*)
2517 (((const uint8_t*)ty) + dtohs(ty->header.headerSize));
2519 const size_t NE = dtohl(ty->entryCount);
2520 for (size_t i=0; i<NE; i++) {
2521 uint32_t offset = dtohl(eindex[i]);
2522 if (offset == ResTable_type::NO_ENTRY) {
2526 offset += typeOffset;
2528 if (offset > (dtohl(ty->header.size)-sizeof(ResTable_entry))) {
2529 LOGW("ResTable_entry at %d is beyond type chunk data %d",
2530 offset, dtohl(ty->header.size));
2533 if ((offset&0x3) != 0) {
2534 LOGW("ResTable_entry at %d (pkg=%d type=%d ent=%d) is not on an integer boundary when looking for %s:%s/%s",
2535 (int)offset, (int)group->id, (int)ti+1, (int)i,
2536 String8(package, packageLen).string(),
2537 String8(type, typeLen).string(),
2538 String8(name, nameLen).string());
2542 const ResTable_entry* const entry = (const ResTable_entry*)
2543 (((const uint8_t*)ty) + offset);
2544 if (dtohs(entry->size) < sizeof(*entry)) {
2545 LOGW("ResTable_entry size %d is too small", dtohs(entry->size));
2549 TABLE_SUPER_NOISY(printf("Looking at entry #%d: want str %d, have %d\n",
2550 i, ei, dtohl(entry->key.index)));
2551 if (dtohl(entry->key.index) == (size_t)ei) {
2552 if (outTypeSpecFlags) {
2553 *outTypeSpecFlags = typeConfigs->typeSpecFlags[i];
2555 return Res_MAKEID(group->id-1, ti, i);
2564 bool ResTable::expandResourceRef(const uint16_t* refStr, size_t refLen,
2565 String16* outPackage,
2568 const String16* defType,
2569 const String16* defPackage,
2570 const char** outErrorMsg)
2572 const char16_t* packageEnd = NULL;
2573 const char16_t* typeEnd = NULL;
2574 const char16_t* p = refStr;
2575 const char16_t* const end = p + refLen;
2577 if (*p == ':') packageEnd = p;
2578 else if (*p == '/') {
2588 *outPackage = String16(p, packageEnd-p);
2593 *outErrorMsg = "No resource package specified";
2597 *outPackage = *defPackage;
2600 *outType = String16(p, typeEnd-p);
2605 *outErrorMsg = "No resource type specified";
2609 *outType = *defType;
2611 *outName = String16(p, end-p);
2615 static uint32_t get_hex(char c, bool* outError)
2617 if (c >= '0' && c <= '9') {
2619 } else if (c >= 'a' && c <= 'f') {
2620 return c - 'a' + 0xa;
2621 } else if (c >= 'A' && c <= 'F') {
2622 return c - 'A' + 0xa;
2637 static const unit_entry unitNames[] = {
2638 { "px", strlen("px"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PX, 1.0f },
2639 { "dip", strlen("dip"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
2640 { "dp", strlen("dp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
2641 { "sp", strlen("sp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_SP, 1.0f },
2642 { "pt", strlen("pt"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PT, 1.0f },
2643 { "in", strlen("in"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_IN, 1.0f },
2644 { "mm", strlen("mm"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_MM, 1.0f },
2645 { "%", strlen("%"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION, 1.0f/100 },
2646 { "%p", strlen("%p"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION_PARENT, 1.0f/100 },
2647 { NULL, 0, 0, 0, 0 }
2650 static bool parse_unit(const char* str, Res_value* outValue,
2651 float* outScale, const char** outEnd)
2653 const char* end = str;
2654 while (*end != 0 && !isspace((unsigned char)*end)) {
2657 const size_t len = end-str;
2659 const char* realEnd = end;
2660 while (*realEnd != 0 && isspace((unsigned char)*realEnd)) {
2663 if (*realEnd != 0) {
2667 const unit_entry* cur = unitNames;
2669 if (len == cur->len && strncmp(cur->name, str, len) == 0) {
2670 outValue->dataType = cur->type;
2671 outValue->data = cur->unit << Res_value::COMPLEX_UNIT_SHIFT;
2672 *outScale = cur->scale;
2674 //printf("Found unit %s for %s\n", cur->name, str);
2684 bool ResTable::stringToInt(const char16_t* s, size_t len, Res_value* outValue)
2686 while (len > 0 && isspace16(*s)) {
2704 if (s[i] < '0' || s[i] > '9') {
2709 if (s[i] == '0' && s[i+1] == 'x') {
2711 outValue->dataType = outValue->TYPE_INT_HEX;
2714 while (i < len && !error) {
2715 val = (val*16) + get_hex(s[i], &error);
2723 outValue->dataType = outValue->TYPE_INT_DEC;
2725 if (s[i] < '0' || s[i] > '9') {
2728 val = (val*10) + s[i]-'0';
2733 if (neg) val = -val;
2735 while (i < len && isspace16(s[i])) {
2741 outValue->data = val;
2748 bool ResTable::stringToFloat(const char16_t* s, size_t len, Res_value* outValue)
2750 while (len > 0 && isspace16(*s)) {
2761 while (len > 0 && *s != 0 && i < 126) {
2772 if (buf[0] < '0' && buf[0] > '9' && buf[0] != '.') {
2778 float f = strtof(buf, (char**)&end);
2780 if (*end != 0 && !isspace((unsigned char)*end)) {
2781 // Might be a unit...
2783 if (parse_unit(end, outValue, &scale, &end)) {
2785 const bool neg = f < 0;
2787 uint64_t bits = (uint64_t)(f*(1<<23)+.5f);
2790 if ((bits&0x7fffff) == 0) {
2791 // Always use 23p0 if there is no fraction, just to make
2792 // things easier to read.
2793 radix = Res_value::COMPLEX_RADIX_23p0;
2795 } else if ((bits&0xffffffffff800000LL) == 0) {
2796 // Magnitude is zero -- can fit in 0 bits of precision.
2797 radix = Res_value::COMPLEX_RADIX_0p23;
2799 } else if ((bits&0xffffffff80000000LL) == 0) {
2800 // Magnitude can fit in 8 bits of precision.
2801 radix = Res_value::COMPLEX_RADIX_8p15;
2803 } else if ((bits&0xffffff8000000000LL) == 0) {
2804 // Magnitude can fit in 16 bits of precision.
2805 radix = Res_value::COMPLEX_RADIX_16p7;
2808 // Magnitude needs entire range, so no fractional part.
2809 radix = Res_value::COMPLEX_RADIX_23p0;
2812 int32_t mantissa = (int32_t)(
2813 (bits>>shift) & Res_value::COMPLEX_MANTISSA_MASK);
2815 mantissa = (-mantissa) & Res_value::COMPLEX_MANTISSA_MASK;
2818 (radix<<Res_value::COMPLEX_RADIX_SHIFT)
2819 | (mantissa<<Res_value::COMPLEX_MANTISSA_SHIFT);
2820 //printf("Input value: %f 0x%016Lx, mult: %f, radix: %d, shift: %d, final: 0x%08x\n",
2821 // f * (neg ? -1 : 1), bits, f*(1<<23),
2822 // radix, shift, outValue->data);
2828 while (*end != 0 && isspace((unsigned char)*end)) {
2834 outValue->dataType = outValue->TYPE_FLOAT;
2835 *(float*)(&outValue->data) = f;
2843 bool ResTable::stringToValue(Res_value* outValue, String16* outString,
2844 const char16_t* s, size_t len,
2845 bool preserveSpaces, bool coerceType,
2847 const String16* defType,
2848 const String16* defPackage,
2850 void* accessorCookie,
2852 bool enforcePrivate) const
2854 bool localizationSetting = accessor != NULL && accessor->getLocalizationSetting();
2855 const char* errorMsg = NULL;
2857 outValue->size = sizeof(Res_value);
2860 // First strip leading/trailing whitespace. Do this before handling
2861 // escapes, so they can be used to force whitespace into the string.
2862 if (!preserveSpaces) {
2863 while (len > 0 && isspace16(*s)) {
2867 while (len > 0 && isspace16(s[len-1])) {
2870 // If the string ends with '\', then we keep the space after it.
2871 if (len > 0 && s[len-1] == '\\' && s[len] != 0) {
2876 //printf("Value for: %s\n", String8(s, len).string());
2878 uint32_t l10nReq = ResTable_map::L10N_NOT_REQUIRED;
2879 uint32_t attrMin = 0x80000000, attrMax = 0x7fffffff;
2880 bool fromAccessor = false;
2881 if (attrID != 0 && !Res_INTERNALID(attrID)) {
2882 const ssize_t p = getResourcePackageIndex(attrID);
2883 const bag_entry* bag;
2884 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
2885 //printf("For attr 0x%08x got bag of %d\n", attrID, cnt);
2888 //printf("Entry 0x%08x = 0x%08x\n", bag->map.name.ident, bag->map.value.data);
2889 switch (bag->map.name.ident) {
2890 case ResTable_map::ATTR_TYPE:
2891 attrType = bag->map.value.data;
2893 case ResTable_map::ATTR_MIN:
2894 attrMin = bag->map.value.data;
2896 case ResTable_map::ATTR_MAX:
2897 attrMax = bag->map.value.data;
2899 case ResTable_map::ATTR_L10N:
2900 l10nReq = bag->map.value.data;
2907 } else if (accessor && accessor->getAttributeType(attrID, &attrType)) {
2908 fromAccessor = true;
2909 if (attrType == ResTable_map::TYPE_ENUM
2910 || attrType == ResTable_map::TYPE_FLAGS
2911 || attrType == ResTable_map::TYPE_INTEGER) {
2912 accessor->getAttributeMin(attrID, &attrMin);
2913 accessor->getAttributeMax(attrID, &attrMax);
2915 if (localizationSetting) {
2916 l10nReq = accessor->getAttributeL10N(attrID);
2921 const bool canStringCoerce =
2922 coerceType && (attrType&ResTable_map::TYPE_STRING) != 0;
2925 outValue->dataType = outValue->TYPE_REFERENCE;
2927 // Note: we don't check attrType here because the reference can
2928 // be to any other type; we just need to count on the client making
2929 // sure the referenced type is correct.
2931 //printf("Looking up ref: %s\n", String8(s, len).string());
2933 // It's a reference!
2934 if (len == 5 && s[1]=='n' && s[2]=='u' && s[3]=='l' && s[4]=='l') {
2938 bool createIfNotFound = false;
2939 const char16_t* resourceRefName;
2940 int resourceNameLen;
2941 if (len > 2 && s[1] == '+') {
2942 createIfNotFound = true;
2943 resourceRefName = s + 2;
2944 resourceNameLen = len - 2;
2945 } else if (len > 2 && s[1] == '*') {
2946 enforcePrivate = false;
2947 resourceRefName = s + 2;
2948 resourceNameLen = len - 2;
2950 createIfNotFound = false;
2951 resourceRefName = s + 1;
2952 resourceNameLen = len - 1;
2954 String16 package, type, name;
2955 if (!expandResourceRef(resourceRefName,resourceNameLen, &package, &type, &name,
2956 defType, defPackage, &errorMsg)) {
2957 if (accessor != NULL) {
2958 accessor->reportError(accessorCookie, errorMsg);
2963 uint32_t specFlags = 0;
2964 uint32_t rid = identifierForName(name.string(), name.size(), type.string(),
2965 type.size(), package.string(), package.size(), &specFlags);
2967 if (enforcePrivate) {
2968 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
2969 if (accessor != NULL) {
2970 accessor->reportError(accessorCookie, "Resource is not public.");
2976 outValue->data = rid;
2980 accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
2981 Res_GETTYPE(rid), Res_GETENTRY(rid));
2982 TABLE_NOISY(printf("Incl %s:%s/%s: 0x%08x\n",
2983 String8(package).string(), String8(type).string(),
2984 String8(name).string(), rid));
2985 outValue->data = rid;
2990 uint32_t rid = accessor->getCustomResourceWithCreation(package, type, name,
2993 TABLE_NOISY(printf("Pckg %s:%s/%s: 0x%08x\n",
2994 String8(package).string(), String8(type).string(),
2995 String8(name).string(), rid));
2996 outValue->data = rid;
3002 if (accessor != NULL) {
3003 accessor->reportError(accessorCookie, "No resource found that matches the given name");
3008 // if we got to here, and localization is required and it's not a reference,
3009 // complain and bail.
3010 if (l10nReq == ResTable_map::L10N_SUGGESTED) {
3011 if (localizationSetting) {
3012 if (accessor != NULL) {
3013 accessor->reportError(accessorCookie, "This attribute must be localized.");
3019 // It's a color! Convert to an integer of the form 0xaarrggbb.
3023 outValue->dataType = outValue->TYPE_INT_COLOR_RGB4;
3024 color |= 0xFF000000;
3025 color |= get_hex(s[1], &error) << 20;
3026 color |= get_hex(s[1], &error) << 16;
3027 color |= get_hex(s[2], &error) << 12;
3028 color |= get_hex(s[2], &error) << 8;
3029 color |= get_hex(s[3], &error) << 4;
3030 color |= get_hex(s[3], &error);
3031 } else if (len == 5) {
3032 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB4;
3033 color |= get_hex(s[1], &error) << 28;
3034 color |= get_hex(s[1], &error) << 24;
3035 color |= get_hex(s[2], &error) << 20;
3036 color |= get_hex(s[2], &error) << 16;
3037 color |= get_hex(s[3], &error) << 12;
3038 color |= get_hex(s[3], &error) << 8;
3039 color |= get_hex(s[4], &error) << 4;
3040 color |= get_hex(s[4], &error);
3041 } else if (len == 7) {
3042 outValue->dataType = outValue->TYPE_INT_COLOR_RGB8;
3043 color |= 0xFF000000;
3044 color |= get_hex(s[1], &error) << 20;
3045 color |= get_hex(s[2], &error) << 16;
3046 color |= get_hex(s[3], &error) << 12;
3047 color |= get_hex(s[4], &error) << 8;
3048 color |= get_hex(s[5], &error) << 4;
3049 color |= get_hex(s[6], &error);
3050 } else if (len == 9) {
3051 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB8;
3052 color |= get_hex(s[1], &error) << 28;
3053 color |= get_hex(s[2], &error) << 24;
3054 color |= get_hex(s[3], &error) << 20;
3055 color |= get_hex(s[4], &error) << 16;
3056 color |= get_hex(s[5], &error) << 12;
3057 color |= get_hex(s[6], &error) << 8;
3058 color |= get_hex(s[7], &error) << 4;
3059 color |= get_hex(s[8], &error);
3064 if ((attrType&ResTable_map::TYPE_COLOR) == 0) {
3065 if (!canStringCoerce) {
3066 if (accessor != NULL) {
3067 accessor->reportError(accessorCookie,
3068 "Color types not allowed");
3073 outValue->data = color;
3074 //printf("Color input=%s, output=0x%x\n", String8(s, len).string(), color);
3078 if ((attrType&ResTable_map::TYPE_COLOR) != 0) {
3079 if (accessor != NULL) {
3080 accessor->reportError(accessorCookie, "Color value not valid --"
3081 " must be #rgb, #argb, #rrggbb, or #aarrggbb");
3084 fprintf(stderr, "%s: Color ID %s value %s is not valid\n",
3085 "Resource File", //(const char*)in->getPrintableSource(),
3086 String8(*curTag).string(),
3087 String8(s, len).string());
3095 outValue->dataType = outValue->TYPE_ATTRIBUTE;
3097 // Note: we don't check attrType here because the reference can
3098 // be to any other type; we just need to count on the client making
3099 // sure the referenced type is correct.
3101 //printf("Looking up attr: %s\n", String8(s, len).string());
3103 static const String16 attr16("attr");
3104 String16 package, type, name;
3105 if (!expandResourceRef(s+1, len-1, &package, &type, &name,
3106 &attr16, defPackage, &errorMsg)) {
3107 if (accessor != NULL) {
3108 accessor->reportError(accessorCookie, errorMsg);
3113 //printf("Pkg: %s, Type: %s, Name: %s\n",
3114 // String8(package).string(), String8(type).string(),
3115 // String8(name).string());
3116 uint32_t specFlags = 0;
3118 identifierForName(name.string(), name.size(),
3119 type.string(), type.size(),
3120 package.string(), package.size(), &specFlags);
3122 if (enforcePrivate) {
3123 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
3124 if (accessor != NULL) {
3125 accessor->reportError(accessorCookie, "Attribute is not public.");
3131 outValue->data = rid;
3135 accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
3136 Res_GETTYPE(rid), Res_GETENTRY(rid));
3137 //printf("Incl %s:%s/%s: 0x%08x\n",
3138 // String8(package).string(), String8(type).string(),
3139 // String8(name).string(), rid);
3140 outValue->data = rid;
3145 uint32_t rid = accessor->getCustomResource(package, type, name);
3147 //printf("Mine %s:%s/%s: 0x%08x\n",
3148 // String8(package).string(), String8(type).string(),
3149 // String8(name).string(), rid);
3150 outValue->data = rid;
3155 if (accessor != NULL) {
3156 accessor->reportError(accessorCookie, "No resource found that matches the given name");
3161 if (stringToInt(s, len, outValue)) {
3162 if ((attrType&ResTable_map::TYPE_INTEGER) == 0) {
3163 // If this type does not allow integers, but does allow floats,
3164 // fall through on this error case because the float type should
3165 // be able to accept any integer value.
3166 if (!canStringCoerce && (attrType&ResTable_map::TYPE_FLOAT) == 0) {
3167 if (accessor != NULL) {
3168 accessor->reportError(accessorCookie, "Integer types not allowed");
3173 if (((int32_t)outValue->data) < ((int32_t)attrMin)
3174 || ((int32_t)outValue->data) > ((int32_t)attrMax)) {
3175 if (accessor != NULL) {
3176 accessor->reportError(accessorCookie, "Integer value out of range");
3184 if (stringToFloat(s, len, outValue)) {
3185 if (outValue->dataType == Res_value::TYPE_DIMENSION) {
3186 if ((attrType&ResTable_map::TYPE_DIMENSION) != 0) {
3189 if (!canStringCoerce) {
3190 if (accessor != NULL) {
3191 accessor->reportError(accessorCookie, "Dimension types not allowed");
3195 } else if (outValue->dataType == Res_value::TYPE_FRACTION) {
3196 if ((attrType&ResTable_map::TYPE_FRACTION) != 0) {
3199 if (!canStringCoerce) {
3200 if (accessor != NULL) {
3201 accessor->reportError(accessorCookie, "Fraction types not allowed");
3205 } else if ((attrType&ResTable_map::TYPE_FLOAT) == 0) {
3206 if (!canStringCoerce) {
3207 if (accessor != NULL) {
3208 accessor->reportError(accessorCookie, "Float types not allowed");
3218 if ((s[0] == 't' || s[0] == 'T') &&
3219 (s[1] == 'r' || s[1] == 'R') &&
3220 (s[2] == 'u' || s[2] == 'U') &&
3221 (s[3] == 'e' || s[3] == 'E')) {
3222 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
3223 if (!canStringCoerce) {
3224 if (accessor != NULL) {
3225 accessor->reportError(accessorCookie, "Boolean types not allowed");
3230 outValue->dataType = outValue->TYPE_INT_BOOLEAN;
3231 outValue->data = (uint32_t)-1;
3238 if ((s[0] == 'f' || s[0] == 'F') &&
3239 (s[1] == 'a' || s[1] == 'A') &&
3240 (s[2] == 'l' || s[2] == 'L') &&
3241 (s[3] == 's' || s[3] == 'S') &&
3242 (s[4] == 'e' || s[4] == 'E')) {
3243 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
3244 if (!canStringCoerce) {
3245 if (accessor != NULL) {
3246 accessor->reportError(accessorCookie, "Boolean types not allowed");
3251 outValue->dataType = outValue->TYPE_INT_BOOLEAN;
3258 if ((attrType&ResTable_map::TYPE_ENUM) != 0) {
3259 const ssize_t p = getResourcePackageIndex(attrID);
3260 const bag_entry* bag;
3261 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
3262 //printf("Got %d for enum\n", cnt);
3264 resource_name rname;
3266 if (!Res_INTERNALID(bag->map.name.ident)) {
3267 //printf("Trying attr #%08x\n", bag->map.name.ident);
3268 if (getResourceName(bag->map.name.ident, &rname)) {
3270 printf("Matching %s against %s (0x%08x)\n",
3271 String8(s, len).string(),
3272 String8(rname.name, rname.nameLen).string(),
3273 bag->map.name.ident);
3275 if (strzcmp16(s, len, rname.name, rname.nameLen) == 0) {
3276 outValue->dataType = bag->map.value.dataType;
3277 outValue->data = bag->map.value.data;
3291 if (accessor->getAttributeEnum(attrID, s, len, outValue)) {
3297 if ((attrType&ResTable_map::TYPE_FLAGS) != 0) {
3298 const ssize_t p = getResourcePackageIndex(attrID);
3299 const bag_entry* bag;
3300 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
3301 //printf("Got %d for flags\n", cnt);
3303 bool failed = false;
3304 resource_name rname;
3305 outValue->dataType = Res_value::TYPE_INT_HEX;
3307 const char16_t* end = s + len;
3308 const char16_t* pos = s;
3309 while (pos < end && !failed) {
3310 const char16_t* start = pos;
3312 while (pos < end && *pos != '|') {
3315 //printf("Looking for: %s\n", String8(start, pos-start).string());
3316 const bag_entry* bagi = bag;
3318 for (i=0; i<cnt; i++, bagi++) {
3319 if (!Res_INTERNALID(bagi->map.name.ident)) {
3320 //printf("Trying attr #%08x\n", bagi->map.name.ident);
3321 if (getResourceName(bagi->map.name.ident, &rname)) {
3323 printf("Matching %s against %s (0x%08x)\n",
3324 String8(start,pos-start).string(),
3325 String8(rname.name, rname.nameLen).string(),
3326 bagi->map.name.ident);
3328 if (strzcmp16(start, pos-start, rname.name, rname.nameLen) == 0) {
3329 outValue->data |= bagi->map.value.data;
3336 // Didn't find this flag identifier.
3345 //printf("Final flag value: 0x%lx\n", outValue->data);
3352 if (accessor->getAttributeFlags(attrID, s, len, outValue)) {
3353 //printf("Final flag value: 0x%lx\n", outValue->data);
3359 if ((attrType&ResTable_map::TYPE_STRING) == 0) {
3360 if (accessor != NULL) {
3361 accessor->reportError(accessorCookie, "String types not allowed");
3366 // Generic string handling...
3367 outValue->dataType = outValue->TYPE_STRING;
3369 bool failed = collectString(outString, s, len, preserveSpaces, &errorMsg);
3370 if (accessor != NULL) {
3371 accessor->reportError(accessorCookie, errorMsg);
3379 bool ResTable::collectString(String16* outString,
3380 const char16_t* s, size_t len,
3381 bool preserveSpaces,
3382 const char** outErrorMsg,
3388 const char16_t* p = s;
3389 while (p < (s+len)) {
3390 while (p < (s+len)) {
3391 const char16_t c = *p;
3395 if (!preserveSpaces) {
3396 if (quoted == 0 && isspace16(c)
3397 && (c != ' ' || isspace16(*(p+1)))) {
3400 if (c == '"' && (quoted == 0 || quoted == '"')) {
3403 if (c == '\'' && (quoted == 0 || quoted == '\'')) {
3405 * In practice, when people write ' instead of \'
3406 * in a string, they are doing it by accident
3407 * instead of really meaning to use ' as a quoting
3408 * character. Warn them so they don't lose it.
3411 *outErrorMsg = "Apostrophe not preceded by \\";
3420 tmp.append(String16(s, p-s));
3422 if (!preserveSpaces && (*p == '"' || *p == '\'')) {
3429 } else if (!preserveSpaces && isspace16(*p)) {
3430 // Space outside of a quote -- consume all spaces and
3431 // leave a single plain space char.
3432 tmp.append(String16(" "));
3434 while (p < (s+len) && isspace16(*p)) {
3437 } else if (*p == '\\') {
3442 tmp.append(String16("\t"));
3445 tmp.append(String16("\n"));
3448 tmp.append(String16("#"));
3451 tmp.append(String16("@"));
3454 tmp.append(String16("?"));
3457 tmp.append(String16("\""));
3460 tmp.append(String16("'"));
3463 tmp.append(String16("\\"));
3469 while (i < 4 && p[1] != 0) {
3473 if (*p >= '0' && *p <= '9') {
3475 } else if (*p >= 'a' && *p <= 'f') {
3477 } else if (*p >= 'A' && *p <= 'F') {
3481 *outErrorMsg = "Bad character in \\u unicode escape sequence";
3487 tmp.append(String16(&chr, 1));
3490 // ignore unknown escape chars.
3501 if (tmp.size() != 0) {
3503 tmp.append(String16(s, len));
3506 outString->append(tmp);
3508 outString->setTo(tmp);
3512 outString->append(String16(s, len));
3514 outString->setTo(s, len);
3521 size_t ResTable::getBasePackageCount() const
3523 if (mError != NO_ERROR) {
3526 return mPackageGroups.size();
3529 const char16_t* ResTable::getBasePackageName(size_t idx) const
3531 if (mError != NO_ERROR) {
3534 LOG_FATAL_IF(idx >= mPackageGroups.size(),
3535 "Requested package index %d past package count %d",
3536 (int)idx, (int)mPackageGroups.size());
3537 return mPackageGroups[idx]->name.string();
3540 uint32_t ResTable::getBasePackageId(size_t idx) const
3542 if (mError != NO_ERROR) {
3545 LOG_FATAL_IF(idx >= mPackageGroups.size(),
3546 "Requested package index %d past package count %d",
3547 (int)idx, (int)mPackageGroups.size());
3548 return mPackageGroups[idx]->id;
3551 size_t ResTable::getTableCount() const
3553 return mHeaders.size();
3556 const ResStringPool* ResTable::getTableStringBlock(size_t index) const
3558 return &mHeaders[index]->values;
3561 void* ResTable::getTableCookie(size_t index) const
3563 return mHeaders[index]->cookie;
3566 void ResTable::getConfigurations(Vector<ResTable_config>* configs) const
3568 const size_t I = mPackageGroups.size();
3569 for (size_t i=0; i<I; i++) {
3570 const PackageGroup* packageGroup = mPackageGroups[i];
3571 const size_t J = packageGroup->packages.size();
3572 for (size_t j=0; j<J; j++) {
3573 const Package* package = packageGroup->packages[j];
3574 const size_t K = package->types.size();
3575 for (size_t k=0; k<K; k++) {
3576 const Type* type = package->types[k];
3577 if (type == NULL) continue;
3578 const size_t L = type->configs.size();
3579 for (size_t l=0; l<L; l++) {
3580 const ResTable_type* config = type->configs[l];
3581 const ResTable_config* cfg = &config->config;
3582 // only insert unique
3583 const size_t M = configs->size();
3585 for (m=0; m<M; m++) {
3586 if (0 == (*configs)[m].compare(*cfg)) {
3590 // if we didn't find it
3600 void ResTable::getLocales(Vector<String8>* locales) const
3602 Vector<ResTable_config> configs;
3603 LOGD("calling getConfigurations");
3604 getConfigurations(&configs);
3605 LOGD("called getConfigurations size=%d", (int)configs.size());
3606 const size_t I = configs.size();
3607 for (size_t i=0; i<I; i++) {
3609 configs[i].getLocale(locale);
3610 const size_t J = locales->size();
3612 for (j=0; j<J; j++) {
3613 if (0 == strcmp(locale, (*locales)[j].string())) {
3618 locales->add(String8(locale));
3623 ssize_t ResTable::getEntry(
3624 const Package* package, int typeIndex, int entryIndex,
3625 const ResTable_config* config,
3626 const ResTable_type** outType, const ResTable_entry** outEntry,
3627 const Type** outTypeClass) const
3629 LOGV("Getting entry from package %p\n", package);
3630 const ResTable_package* const pkg = package->package;
3632 const Type* allTypes = package->getType(typeIndex);
3633 LOGV("allTypes=%p\n", allTypes);
3634 if (allTypes == NULL) {
3635 LOGV("Skipping entry type index 0x%02x because type is NULL!\n", typeIndex);
3639 if ((size_t)entryIndex >= allTypes->entryCount) {
3640 LOGW("getEntry failing because entryIndex %d is beyond type entryCount %d",
3641 entryIndex, (int)allTypes->entryCount);
3645 const ResTable_type* type = NULL;
3646 uint32_t offset = ResTable_type::NO_ENTRY;
3647 ResTable_config bestConfig;
3648 memset(&bestConfig, 0, sizeof(bestConfig)); // make the compiler shut up
3650 const size_t NT = allTypes->configs.size();
3651 for (size_t i=0; i<NT; i++) {
3652 const ResTable_type* const thisType = allTypes->configs[i];
3653 if (thisType == NULL) continue;
3655 ResTable_config thisConfig;
3656 thisConfig.copyFromDtoH(thisType->config);
3658 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 "
3659 "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",
3660 entryIndex, typeIndex+1, dtohl(thisType->config.size),
3661 thisConfig.mcc, thisConfig.mnc,
3662 config ? config->mcc : 0, config ? config->mnc : 0,
3663 thisConfig.language[0] ? thisConfig.language[0] : '-',
3664 thisConfig.language[1] ? thisConfig.language[1] : '-',
3665 config && config->language[0] ? config->language[0] : '-',
3666 config && config->language[1] ? config->language[1] : '-',
3667 thisConfig.country[0] ? thisConfig.country[0] : '-',
3668 thisConfig.country[1] ? thisConfig.country[1] : '-',
3669 config && config->country[0] ? config->country[0] : '-',
3670 config && config->country[1] ? config->country[1] : '-',
3671 thisConfig.orientation,
3672 config ? config->orientation : 0,
3673 thisConfig.touchscreen,
3674 config ? config->touchscreen : 0,
3676 config ? config->density : 0,
3677 thisConfig.keyboard,
3678 config ? config->keyboard : 0,
3679 thisConfig.inputFlags,
3680 config ? config->inputFlags : 0,
3681 thisConfig.navigation,
3682 config ? config->navigation : 0,
3683 thisConfig.screenWidth,
3684 config ? config->screenWidth : 0,
3685 thisConfig.screenHeight,
3686 config ? config->screenHeight : 0));
3688 // Check to make sure this one is valid for the current parameters.
3689 if (config && !thisConfig.match(*config)) {
3690 TABLE_GETENTRY(LOGI("Does not match config!\n"));
3694 // Check if there is the desired entry in this type.
3696 const uint8_t* const end = ((const uint8_t*)thisType)
3697 + dtohl(thisType->header.size);
3698 const uint32_t* const eindex = (const uint32_t*)
3699 (((const uint8_t*)thisType) + dtohs(thisType->header.headerSize));
3701 uint32_t thisOffset = dtohl(eindex[entryIndex]);
3702 if (thisOffset == ResTable_type::NO_ENTRY) {
3703 TABLE_GETENTRY(LOGI("Skipping because it is not defined!\n"));
3708 // Check if this one is less specific than the last found. If so,
3709 // we will skip it. We check starting with things we most care
3710 // about to those we least care about.
3711 if (!thisConfig.isBetterThan(bestConfig, config)) {
3712 TABLE_GETENTRY(LOGI("This config is worse than last!\n"));
3718 offset = thisOffset;
3719 bestConfig = thisConfig;
3720 TABLE_GETENTRY(LOGI("Best entry so far -- using it!\n"));
3725 TABLE_GETENTRY(LOGI("No value found for requested entry!\n"));
3729 offset += dtohl(type->entriesStart);
3730 TABLE_NOISY(aout << "Looking in resource table " << package->header->header
3732 << (void*)(((const char*)type)-((const char*)package->header->header))
3733 << ", offset=" << (void*)offset << endl);
3735 if (offset > (dtohl(type->header.size)-sizeof(ResTable_entry))) {
3736 LOGW("ResTable_entry at 0x%x is beyond type chunk data 0x%x",
3737 offset, dtohl(type->header.size));
3740 if ((offset&0x3) != 0) {
3741 LOGW("ResTable_entry at 0x%x is not on an integer boundary",
3746 const ResTable_entry* const entry = (const ResTable_entry*)
3747 (((const uint8_t*)type) + offset);
3748 if (dtohs(entry->size) < sizeof(*entry)) {
3749 LOGW("ResTable_entry size 0x%x is too small", dtohs(entry->size));
3755 if (outTypeClass != NULL) {
3756 *outTypeClass = allTypes;
3758 return offset + dtohs(entry->size);
3761 status_t ResTable::parsePackage(const ResTable_package* const pkg,
3762 const Header* const header)
3764 const uint8_t* base = (const uint8_t*)pkg;
3765 status_t err = validate_chunk(&pkg->header, sizeof(*pkg),
3766 header->dataEnd, "ResTable_package");
3767 if (err != NO_ERROR) {
3768 return (mError=err);
3771 const size_t pkgSize = dtohl(pkg->header.size);
3773 if (dtohl(pkg->typeStrings) >= pkgSize) {
3774 LOGW("ResTable_package type strings at %p are past chunk size %p.",
3775 (void*)dtohl(pkg->typeStrings), (void*)pkgSize);
3776 return (mError=BAD_TYPE);
3778 if ((dtohl(pkg->typeStrings)&0x3) != 0) {
3779 LOGW("ResTable_package type strings at %p is not on an integer boundary.",
3780 (void*)dtohl(pkg->typeStrings));
3781 return (mError=BAD_TYPE);
3783 if (dtohl(pkg->keyStrings) >= pkgSize) {
3784 LOGW("ResTable_package key strings at %p are past chunk size %p.",
3785 (void*)dtohl(pkg->keyStrings), (void*)pkgSize);
3786 return (mError=BAD_TYPE);
3788 if ((dtohl(pkg->keyStrings)&0x3) != 0) {
3789 LOGW("ResTable_package key strings at %p is not on an integer boundary.",
3790 (void*)dtohl(pkg->keyStrings));
3791 return (mError=BAD_TYPE);
3794 Package* package = NULL;
3795 PackageGroup* group = NULL;
3796 uint32_t id = dtohl(pkg->id);
3797 if (id != 0 && id < 256) {
3799 package = new Package(this, header, pkg);
3800 if (package == NULL) {
3801 return (mError=NO_MEMORY);
3804 size_t idx = mPackageMap[id];
3806 idx = mPackageGroups.size()+1;
3808 char16_t tmpName[sizeof(pkg->name)/sizeof(char16_t)];
3809 strcpy16_dtoh(tmpName, pkg->name, sizeof(pkg->name)/sizeof(char16_t));
3810 group = new PackageGroup(this, String16(tmpName), id);
3811 if (group == NULL) {
3813 return (mError=NO_MEMORY);
3816 err = package->typeStrings.setTo(base+dtohl(pkg->typeStrings),
3817 header->dataEnd-(base+dtohl(pkg->typeStrings)));
3818 if (err != NO_ERROR) {
3821 return (mError=err);
3823 err = package->keyStrings.setTo(base+dtohl(pkg->keyStrings),
3824 header->dataEnd-(base+dtohl(pkg->keyStrings)));
3825 if (err != NO_ERROR) {
3828 return (mError=err);
3831 //printf("Adding new package id %d at index %d\n", id, idx);
3832 err = mPackageGroups.add(group);
3833 if (err < NO_ERROR) {
3834 return (mError=err);
3836 group->basePackage = package;
3838 mPackageMap[id] = (uint8_t)idx;
3840 group = mPackageGroups.itemAt(idx-1);
3841 if (group == NULL) {
3842 return (mError=UNKNOWN_ERROR);
3845 err = group->packages.add(package);
3846 if (err < NO_ERROR) {
3847 return (mError=err);
3850 LOG_ALWAYS_FATAL("Skins not supported!");
3855 // Iterate through all chunks.
3856 size_t curPackage = 0;
3858 const ResChunk_header* chunk =
3859 (const ResChunk_header*)(((const uint8_t*)pkg)
3860 + dtohs(pkg->header.headerSize));
3861 const uint8_t* endPos = ((const uint8_t*)pkg) + dtohs(pkg->header.size);
3862 while (((const uint8_t*)chunk) <= (endPos-sizeof(ResChunk_header)) &&
3863 ((const uint8_t*)chunk) <= (endPos-dtohl(chunk->size))) {
3864 TABLE_NOISY(LOGV("PackageChunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n",
3865 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
3866 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header))));
3867 const size_t csize = dtohl(chunk->size);
3868 const uint16_t ctype = dtohs(chunk->type);
3869 if (ctype == RES_TABLE_TYPE_SPEC_TYPE) {
3870 const ResTable_typeSpec* typeSpec = (const ResTable_typeSpec*)(chunk);
3871 err = validate_chunk(&typeSpec->header, sizeof(*typeSpec),
3872 endPos, "ResTable_typeSpec");
3873 if (err != NO_ERROR) {
3874 return (mError=err);
3877 const size_t typeSpecSize = dtohl(typeSpec->header.size);
3879 LOAD_TABLE_NOISY(printf("TypeSpec off %p: type=0x%x, headerSize=0x%x, size=%p\n",
3880 (void*)(base-(const uint8_t*)chunk),
3881 dtohs(typeSpec->header.type),
3882 dtohs(typeSpec->header.headerSize),
3884 // look for block overrun or int overflow when multiplying by 4
3885 if ((dtohl(typeSpec->entryCount) > (INT32_MAX/sizeof(uint32_t))
3886 || dtohs(typeSpec->header.headerSize)+(sizeof(uint32_t)*dtohl(typeSpec->entryCount))
3888 LOGW("ResTable_typeSpec entry index to %p extends beyond chunk end %p.",
3889 (void*)(dtohs(typeSpec->header.headerSize)
3890 +(sizeof(uint32_t)*dtohl(typeSpec->entryCount))),
3891 (void*)typeSpecSize);
3892 return (mError=BAD_TYPE);
3895 if (typeSpec->id == 0) {
3896 LOGW("ResTable_type has an id of 0.");
3897 return (mError=BAD_TYPE);
3900 while (package->types.size() < typeSpec->id) {
3901 package->types.add(NULL);
3903 Type* t = package->types[typeSpec->id-1];
3905 t = new Type(header, package, dtohl(typeSpec->entryCount));
3906 package->types.editItemAt(typeSpec->id-1) = t;
3907 } else if (dtohl(typeSpec->entryCount) != t->entryCount) {
3908 LOGW("ResTable_typeSpec entry count inconsistent: given %d, previously %d",
3909 (int)dtohl(typeSpec->entryCount), (int)t->entryCount);
3910 return (mError=BAD_TYPE);
3912 t->typeSpecFlags = (const uint32_t*)(
3913 ((const uint8_t*)typeSpec) + dtohs(typeSpec->header.headerSize));
3914 t->typeSpec = typeSpec;
3916 } else if (ctype == RES_TABLE_TYPE_TYPE) {
3917 const ResTable_type* type = (const ResTable_type*)(chunk);
3918 err = validate_chunk(&type->header, sizeof(*type)-sizeof(ResTable_config)+4,
3919 endPos, "ResTable_type");
3920 if (err != NO_ERROR) {
3921 return (mError=err);
3924 const size_t typeSize = dtohl(type->header.size);
3926 LOAD_TABLE_NOISY(printf("Type off %p: type=0x%x, headerSize=0x%x, size=%p\n",
3927 (void*)(base-(const uint8_t*)chunk),
3928 dtohs(type->header.type),
3929 dtohs(type->header.headerSize),
3931 if (dtohs(type->header.headerSize)+(sizeof(uint32_t)*dtohl(type->entryCount))
3933 LOGW("ResTable_type entry index to %p extends beyond chunk end %p.",
3934 (void*)(dtohs(type->header.headerSize)
3935 +(sizeof(uint32_t)*dtohl(type->entryCount))),
3937 return (mError=BAD_TYPE);
3939 if (dtohl(type->entryCount) != 0
3940 && dtohl(type->entriesStart) > (typeSize-sizeof(ResTable_entry))) {
3941 LOGW("ResTable_type entriesStart at %p extends beyond chunk end %p.",
3942 (void*)dtohl(type->entriesStart), (void*)typeSize);
3943 return (mError=BAD_TYPE);
3945 if (type->id == 0) {
3946 LOGW("ResTable_type has an id of 0.");
3947 return (mError=BAD_TYPE);
3950 while (package->types.size() < type->id) {
3951 package->types.add(NULL);
3953 Type* t = package->types[type->id-1];
3955 t = new Type(header, package, dtohl(type->entryCount));
3956 package->types.editItemAt(type->id-1) = t;
3957 } else if (dtohl(type->entryCount) != t->entryCount) {
3958 LOGW("ResTable_type entry count inconsistent: given %d, previously %d",
3959 (int)dtohl(type->entryCount), (int)t->entryCount);
3960 return (mError=BAD_TYPE);
3964 ResTable_config thisConfig;
3965 thisConfig.copyFromDtoH(type->config);
3966 LOGI("Adding config to type %d: imsi:%d/%d lang:%c%c cnt:%c%c "
3967 "orien:%d touch:%d density:%d key:%d inp:%d nav:%d w:%d h:%d\n",
3969 thisConfig.mcc, thisConfig.mnc,
3970 thisConfig.language[0] ? thisConfig.language[0] : '-',
3971 thisConfig.language[1] ? thisConfig.language[1] : '-',
3972 thisConfig.country[0] ? thisConfig.country[0] : '-',
3973 thisConfig.country[1] ? thisConfig.country[1] : '-',
3974 thisConfig.orientation,
3975 thisConfig.touchscreen,
3977 thisConfig.keyboard,
3978 thisConfig.inputFlags,
3979 thisConfig.navigation,
3980 thisConfig.screenWidth,
3981 thisConfig.screenHeight));
3982 t->configs.add(type);
3984 status_t err = validate_chunk(chunk, sizeof(ResChunk_header),
3985 endPos, "ResTable_package:unknown");
3986 if (err != NO_ERROR) {
3987 return (mError=err);
3990 chunk = (const ResChunk_header*)
3991 (((const uint8_t*)chunk) + csize);
3994 if (group->typeCount == 0) {
3995 group->typeCount = package->types.size();
4001 #ifndef HAVE_ANDROID_OS
4002 #define CHAR16_TO_CSTR(c16, len) (String8(String16(c16,len)).string())
4004 #define CHAR16_ARRAY_EQ(constant, var, len) \
4005 ((len == (sizeof(constant)/sizeof(constant[0]))) && (0 == memcmp((var), (constant), (len))))
4007 void print_complex(uint32_t complex, bool isFraction)
4009 const float MANTISSA_MULT =
4010 1.0f / (1<<Res_value::COMPLEX_MANTISSA_SHIFT);
4011 const float RADIX_MULTS[] = {
4012 1.0f*MANTISSA_MULT, 1.0f/(1<<7)*MANTISSA_MULT,
4013 1.0f/(1<<15)*MANTISSA_MULT, 1.0f/(1<<23)*MANTISSA_MULT
4016 float value = (complex&(Res_value::COMPLEX_MANTISSA_MASK
4017 <<Res_value::COMPLEX_MANTISSA_SHIFT))
4018 * RADIX_MULTS[(complex>>Res_value::COMPLEX_RADIX_SHIFT)
4019 & Res_value::COMPLEX_RADIX_MASK];
4020 printf("%f", value);
4023 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
4024 case Res_value::COMPLEX_UNIT_PX: printf("px"); break;
4025 case Res_value::COMPLEX_UNIT_DIP: printf("dp"); break;
4026 case Res_value::COMPLEX_UNIT_SP: printf("sp"); break;
4027 case Res_value::COMPLEX_UNIT_PT: printf("pt"); break;
4028 case Res_value::COMPLEX_UNIT_IN: printf("in"); break;
4029 case Res_value::COMPLEX_UNIT_MM: printf("mm"); break;
4030 default: printf(" (unknown unit)"); break;
4033 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
4034 case Res_value::COMPLEX_UNIT_FRACTION: printf("%%"); break;
4035 case Res_value::COMPLEX_UNIT_FRACTION_PARENT: printf("%%p"); break;
4036 default: printf(" (unknown unit)"); break;
4041 void ResTable::print_value(const Package* pkg, const Res_value& value) const
4043 if (value.dataType == Res_value::TYPE_NULL) {
4045 } else if (value.dataType == Res_value::TYPE_REFERENCE) {
4046 printf("(reference) 0x%08x\n", value.data);
4047 } else if (value.dataType == Res_value::TYPE_ATTRIBUTE) {
4048 printf("(attribute) 0x%08x\n", value.data);
4049 } else if (value.dataType == Res_value::TYPE_STRING) {
4051 const char* str8 = pkg->header->values.string8At(
4054 printf("(string8) \"%s\"\n", str8);
4056 const char16_t* str16 = pkg->header->values.stringAt(
4058 if (str16 != NULL) {
4059 printf("(string16) \"%s\"\n",
4060 String8(str16, len).string());
4062 printf("(string) null\n");
4065 } else if (value.dataType == Res_value::TYPE_FLOAT) {
4066 printf("(float) %g\n", *(const float*)&value.data);
4067 } else if (value.dataType == Res_value::TYPE_DIMENSION) {
4068 printf("(dimension) ");
4069 print_complex(value.data, false);
4071 } else if (value.dataType == Res_value::TYPE_FRACTION) {
4072 printf("(fraction) ");
4073 print_complex(value.data, true);
4075 } else if (value.dataType >= Res_value::TYPE_FIRST_COLOR_INT
4076 || value.dataType <= Res_value::TYPE_LAST_COLOR_INT) {
4077 printf("(color) #%08x\n", value.data);
4078 } else if (value.dataType == Res_value::TYPE_INT_BOOLEAN) {
4079 printf("(boolean) %s\n", value.data ? "true" : "false");
4080 } else if (value.dataType >= Res_value::TYPE_FIRST_INT
4081 || value.dataType <= Res_value::TYPE_LAST_INT) {
4082 printf("(int) 0x%08x or %d\n", value.data, value.data);
4084 printf("(unknown type) t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)\n",
4085 (int)value.dataType, (int)value.data,
4086 (int)value.size, (int)value.res0);
4090 void ResTable::print(bool inclValues) const
4093 printf("mError=0x%x (%s)\n", mError, strerror(mError));
4096 printf("mParams=%c%c-%c%c,\n",
4097 mParams.language[0], mParams.language[1],
4098 mParams.country[0], mParams.country[1]);
4100 size_t pgCount = mPackageGroups.size();
4101 printf("Package Groups (%d)\n", (int)pgCount);
4102 for (size_t pgIndex=0; pgIndex<pgCount; pgIndex++) {
4103 const PackageGroup* pg = mPackageGroups[pgIndex];
4104 printf("Package Group %d id=%d packageCount=%d name=%s\n",
4105 (int)pgIndex, pg->id, (int)pg->packages.size(),
4106 String8(pg->name).string());
4108 size_t pkgCount = pg->packages.size();
4109 for (size_t pkgIndex=0; pkgIndex<pkgCount; pkgIndex++) {
4110 const Package* pkg = pg->packages[pkgIndex];
4111 size_t typeCount = pkg->types.size();
4112 printf(" Package %d id=%d name=%s typeCount=%d\n", (int)pkgIndex,
4113 pkg->package->id, String8(String16(pkg->package->name)).string(),
4115 for (size_t typeIndex=0; typeIndex<typeCount; typeIndex++) {
4116 const Type* typeConfigs = pkg->getType(typeIndex);
4117 if (typeConfigs == NULL) {
4118 printf(" type %d NULL\n", (int)typeIndex);
4121 const size_t NTC = typeConfigs->configs.size();
4122 printf(" type %d configCount=%d entryCount=%d\n",
4123 (int)typeIndex, (int)NTC, (int)typeConfigs->entryCount);
4124 if (typeConfigs->typeSpecFlags != NULL) {
4125 for (size_t entryIndex=0; entryIndex<typeConfigs->entryCount; entryIndex++) {
4126 uint32_t resID = (0xff000000 & ((pkg->package->id)<<24))
4127 | (0x00ff0000 & ((typeIndex+1)<<16))
4128 | (0x0000ffff & (entryIndex));
4129 resource_name resName;
4130 this->getResourceName(resID, &resName);
4131 printf(" spec resource 0x%08x %s:%s/%s: flags=0x%08x\n",
4133 CHAR16_TO_CSTR(resName.package, resName.packageLen),
4134 CHAR16_TO_CSTR(resName.type, resName.typeLen),
4135 CHAR16_TO_CSTR(resName.name, resName.nameLen),
4136 dtohl(typeConfigs->typeSpecFlags[entryIndex]));
4139 for (size_t configIndex=0; configIndex<NTC; configIndex++) {
4140 const ResTable_type* type = typeConfigs->configs[configIndex];
4141 if ((((uint64_t)type)&0x3) != 0) {
4142 printf(" NON-INTEGER ResTable_type ADDRESS: %p\n", type);
4146 uint16_t dval = dtohs(type->config.density);
4147 if (dval == ResTable_config::DENSITY_DEFAULT) {
4148 strcpy(density, "def");
4149 } else if (dval == ResTable_config::DENSITY_NONE) {
4150 strcpy(density, "no");
4152 sprintf(density, "%d", (int)dval);
4154 printf(" config %d", (int)configIndex);
4155 if (type->config.mcc != 0) {
4156 printf(" mcc=%d", dtohs(type->config.mcc));
4158 if (type->config.mnc != 0) {
4159 printf(" mnc=%d", dtohs(type->config.mnc));
4161 if (type->config.locale != 0) {
4162 printf(" lang=%c%c cnt=%c%c",
4163 type->config.language[0] ? type->config.language[0] : '-',
4164 type->config.language[1] ? type->config.language[1] : '-',
4165 type->config.country[0] ? type->config.country[0] : '-',
4166 type->config.country[1] ? type->config.country[1] : '-');
4168 if (type->config.screenLayout != 0) {
4170 type->config.screenLayout&ResTable_config::MASK_SCREENSIZE);
4171 switch (type->config.screenLayout&ResTable_config::MASK_SCREENSIZE) {
4172 case ResTable_config::SCREENSIZE_SMALL:
4175 case ResTable_config::SCREENSIZE_NORMAL:
4176 printf(" (normal)");
4178 case ResTable_config::SCREENSIZE_LARGE:
4181 case ResTable_config::SCREENSIZE_XLARGE:
4182 printf(" (xlarge)");
4186 type->config.screenLayout&ResTable_config::MASK_SCREENLONG);
4187 switch (type->config.screenLayout&ResTable_config::MASK_SCREENLONG) {
4188 case ResTable_config::SCREENLONG_NO:
4189 printf(" (notlong)");
4191 case ResTable_config::SCREENLONG_YES:
4196 if (type->config.orientation != 0) {
4197 printf(" orient=%d", type->config.orientation);
4198 switch (type->config.orientation) {
4199 case ResTable_config::ORIENTATION_PORT:
4202 case ResTable_config::ORIENTATION_LAND:
4205 case ResTable_config::ORIENTATION_SQUARE:
4206 printf(" (square)");
4210 if (type->config.uiMode != 0) {
4212 type->config.uiMode&ResTable_config::MASK_UI_MODE_TYPE);
4213 switch (type->config.uiMode&ResTable_config::MASK_UI_MODE_TYPE) {
4214 case ResTable_config::UI_MODE_TYPE_NORMAL:
4215 printf(" (normal)");
4217 case ResTable_config::UI_MODE_TYPE_CAR:
4222 type->config.uiMode&ResTable_config::MASK_UI_MODE_NIGHT);
4223 switch (type->config.uiMode&ResTable_config::MASK_UI_MODE_NIGHT) {
4224 case ResTable_config::UI_MODE_NIGHT_NO:
4227 case ResTable_config::UI_MODE_NIGHT_YES:
4233 printf(" density=%s", density);
4235 if (type->config.touchscreen != 0) {
4236 printf(" touch=%d", type->config.touchscreen);
4237 switch (type->config.touchscreen) {
4238 case ResTable_config::TOUCHSCREEN_NOTOUCH:
4239 printf(" (notouch)");
4241 case ResTable_config::TOUCHSCREEN_STYLUS:
4242 printf(" (stylus)");
4244 case ResTable_config::TOUCHSCREEN_FINGER:
4245 printf(" (finger)");
4249 if (type->config.inputFlags != 0) {
4250 printf(" keyhid=%d", type->config.inputFlags&ResTable_config::MASK_KEYSHIDDEN);
4251 switch (type->config.inputFlags&ResTable_config::MASK_KEYSHIDDEN) {
4252 case ResTable_config::KEYSHIDDEN_NO:
4255 case ResTable_config::KEYSHIDDEN_YES:
4258 case ResTable_config::KEYSHIDDEN_SOFT:
4262 printf(" navhid=%d", type->config.inputFlags&ResTable_config::MASK_NAVHIDDEN);
4263 switch (type->config.inputFlags&ResTable_config::MASK_NAVHIDDEN) {
4264 case ResTable_config::NAVHIDDEN_NO:
4267 case ResTable_config::NAVHIDDEN_YES:
4272 if (type->config.keyboard != 0) {
4273 printf(" kbd=%d", type->config.keyboard);
4274 switch (type->config.keyboard) {
4275 case ResTable_config::KEYBOARD_NOKEYS:
4276 printf(" (nokeys)");
4278 case ResTable_config::KEYBOARD_QWERTY:
4279 printf(" (qwerty)");
4281 case ResTable_config::KEYBOARD_12KEY:
4286 if (type->config.navigation != 0) {
4287 printf(" nav=%d", type->config.navigation);
4288 switch (type->config.navigation) {
4289 case ResTable_config::NAVIGATION_NONAV:
4292 case ResTable_config::NAVIGATION_DPAD:
4295 case ResTable_config::NAVIGATION_TRACKBALL:
4296 printf(" (trackball)");
4298 case ResTable_config::NAVIGATION_WHEEL:
4303 if (type->config.screenWidth != 0) {
4304 printf(" w=%d", dtohs(type->config.screenWidth));
4306 if (type->config.screenHeight != 0) {
4307 printf(" h=%d", dtohs(type->config.screenHeight));
4309 if (type->config.sdkVersion != 0) {
4310 printf(" sdk=%d", dtohs(type->config.sdkVersion));
4312 if (type->config.minorVersion != 0) {
4313 printf(" mver=%d", dtohs(type->config.minorVersion));
4316 size_t entryCount = dtohl(type->entryCount);
4317 uint32_t entriesStart = dtohl(type->entriesStart);
4318 if ((entriesStart&0x3) != 0) {
4319 printf(" NON-INTEGER ResTable_type entriesStart OFFSET: %p\n", (void*)entriesStart);
4322 uint32_t typeSize = dtohl(type->header.size);
4323 if ((typeSize&0x3) != 0) {
4324 printf(" NON-INTEGER ResTable_type header.size: %p\n", (void*)typeSize);
4327 for (size_t entryIndex=0; entryIndex<entryCount; entryIndex++) {
4329 const uint8_t* const end = ((const uint8_t*)type)
4330 + dtohl(type->header.size);
4331 const uint32_t* const eindex = (const uint32_t*)
4332 (((const uint8_t*)type) + dtohs(type->header.headerSize));
4334 uint32_t thisOffset = dtohl(eindex[entryIndex]);
4335 if (thisOffset == ResTable_type::NO_ENTRY) {
4339 uint32_t resID = (0xff000000 & ((pkg->package->id)<<24))
4340 | (0x00ff0000 & ((typeIndex+1)<<16))
4341 | (0x0000ffff & (entryIndex));
4342 resource_name resName;
4343 this->getResourceName(resID, &resName);
4344 printf(" resource 0x%08x %s:%s/%s: ", resID,
4345 CHAR16_TO_CSTR(resName.package, resName.packageLen),
4346 CHAR16_TO_CSTR(resName.type, resName.typeLen),
4347 CHAR16_TO_CSTR(resName.name, resName.nameLen));
4348 if ((thisOffset&0x3) != 0) {
4349 printf("NON-INTEGER OFFSET: %p\n", (void*)thisOffset);
4352 if ((thisOffset+sizeof(ResTable_entry)) > typeSize) {
4353 printf("OFFSET OUT OF BOUNDS: %p+%p (size is %p)\n",
4354 (void*)entriesStart, (void*)thisOffset,
4359 const ResTable_entry* ent = (const ResTable_entry*)
4360 (((const uint8_t*)type) + entriesStart + thisOffset);
4361 if (((entriesStart + thisOffset)&0x3) != 0) {
4362 printf("NON-INTEGER ResTable_entry OFFSET: %p\n",
4363 (void*)(entriesStart + thisOffset));
4367 uint16_t esize = dtohs(ent->size);
4368 if ((esize&0x3) != 0) {
4369 printf("NON-INTEGER ResTable_entry SIZE: %p\n", (void*)esize);
4372 if ((thisOffset+esize) > typeSize) {
4373 printf("ResTable_entry OUT OF BOUNDS: %p+%p+%p (size is %p)\n",
4374 (void*)entriesStart, (void*)thisOffset,
4375 (void*)esize, (void*)typeSize);
4379 const Res_value* valuePtr = NULL;
4380 const ResTable_map_entry* bagPtr = NULL;
4382 if ((dtohs(ent->flags)&ResTable_entry::FLAG_COMPLEX) != 0) {
4384 bagPtr = (const ResTable_map_entry*)ent;
4386 valuePtr = (const Res_value*)
4387 (((const uint8_t*)ent) + esize);
4388 value.copyFrom_dtoh(*valuePtr);
4389 printf("t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)",
4390 (int)value.dataType, (int)value.data,
4391 (int)value.size, (int)value.res0);
4394 if ((dtohs(ent->flags)&ResTable_entry::FLAG_PUBLIC) != 0) {
4395 printf(" (PUBLIC)");
4400 if (valuePtr != NULL) {
4402 print_value(pkg, value);
4403 } else if (bagPtr != NULL) {
4404 const int N = dtohl(bagPtr->count);
4405 const ResTable_map* mapPtr = (const ResTable_map*)
4406 (((const uint8_t*)ent) + esize);
4407 printf(" Parent=0x%08x, Count=%d\n",
4408 dtohl(bagPtr->parent.ident), N);
4409 for (int i=0; i<N; i++) {
4410 printf(" #%i (Key=0x%08x): ",
4411 i, dtohl(mapPtr->name.ident));
4412 value.copyFrom_dtoh(mapPtr->value);
4413 print_value(pkg, value);
4414 const size_t size = dtohs(mapPtr->value.size);
4415 mapPtr = (ResTable_map*)(((const uint8_t*)mapPtr)
4416 + size + sizeof(*mapPtr)-sizeof(mapPtr->value));
4427 #endif // HAVE_ANDROID_OS
4429 } // namespace android