blob: 51aa24bcce574575107dd57d783f697c78bf8db0 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "ResourceType"
18//#define LOG_NDEBUG 0
19
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -070020#include <androidfw/ByteBucketArray.h>
Mathias Agopianb13b9bd2012-02-17 18:27:36 -080021#include <androidfw/ResourceTypes.h>
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -070022#include <androidfw/TypeWrappers.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023#include <utils/Atomic.h>
24#include <utils/ByteOrder.h>
25#include <utils/Debug.h>
Mathias Agopianb13b9bd2012-02-17 18:27:36 -080026#include <utils/Log.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027#include <utils/String16.h>
28#include <utils/String8.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029
30#include <stdlib.h>
31#include <string.h>
32#include <memory.h>
33#include <ctype.h>
34#include <stdint.h>
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -070035#include <stddef.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036
37#ifndef INT32_MAX
38#define INT32_MAX ((int32_t)(2147483647))
39#endif
40
Dianne Hackbornd45c68d2013-07-31 12:14:24 -070041#define STRING_POOL_NOISY(x) //x
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042#define XML_NOISY(x) //x
43#define TABLE_NOISY(x) //x
44#define TABLE_GETENTRY(x) //x
45#define TABLE_SUPER_NOISY(x) //x
46#define LOAD_TABLE_NOISY(x) //x
Dianne Hackbornb8d81672009-11-20 14:26:42 -080047#define TABLE_THEME(x) //x
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -070048#define LIB_NOISY(x) //x
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049
50namespace android {
51
52#ifdef HAVE_WINSOCK
53#undef nhtol
54#undef htonl
55
56#ifdef HAVE_LITTLE_ENDIAN
57#define ntohl(x) ( ((x) << 24) | (((x) >> 24) & 255) | (((x) << 8) & 0xff0000) | (((x) >> 8) & 0xff00) )
58#define htonl(x) ntohl(x)
59#define ntohs(x) ( (((x) << 8) & 0xff00) | (((x) >> 8) & 255) )
60#define htons(x) ntohs(x)
61#else
62#define ntohl(x) (x)
63#define htonl(x) (x)
64#define ntohs(x) (x)
65#define htons(x) (x)
66#endif
67#endif
68
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -070069#define IDMAP_MAGIC 0x504D4449
70#define IDMAP_CURRENT_VERSION 0x00000001
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +010071
Adam Lesinskide898ff2014-01-29 18:20:45 -080072#define APP_PACKAGE_ID 0x7f
73#define SYS_PACKAGE_ID 0x01
74
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075// Standard C isspace() is only required to look at the low byte of its input, so
76// produces incorrect results for UTF-16 characters. For safety's sake, assume that
77// any high-byte UTF-16 code point is not whitespace.
78inline int isspace16(char16_t c) {
79 return (c < 0x0080 && isspace(c));
80}
81
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -070082template<typename T>
83inline static T max(T a, T b) {
84 return a > b ? a : b;
85}
86
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087// range checked; guaranteed to NUL-terminate within the stated number of available slots
88// NOTE: if this truncates the dst string due to running out of space, no attempt is
89// made to avoid splitting surrogate pairs.
Adam Lesinski4bf58102014-11-03 11:21:19 -080090static void strcpy16_dtoh(char16_t* dst, const uint16_t* src, size_t avail)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091{
Adam Lesinski4bf58102014-11-03 11:21:19 -080092 char16_t* last = dst + avail - 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 while (*src && (dst < last)) {
Adam Lesinski4bf58102014-11-03 11:21:19 -080094 char16_t s = dtohs(static_cast<char16_t>(*src));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095 *dst++ = s;
96 src++;
97 }
98 *dst = 0;
99}
100
101static status_t validate_chunk(const ResChunk_header* chunk,
102 size_t minSize,
103 const uint8_t* dataEnd,
104 const char* name)
105{
106 const uint16_t headerSize = dtohs(chunk->headerSize);
107 const uint32_t size = dtohl(chunk->size);
108
109 if (headerSize >= minSize) {
110 if (headerSize <= size) {
111 if (((headerSize|size)&0x3) == 0) {
Adam Lesinski7322ea72014-05-14 11:43:26 -0700112 if ((size_t)size <= (size_t)(dataEnd-((const uint8_t*)chunk))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 return NO_ERROR;
114 }
Patrik Bannura443dd932014-02-12 13:38:54 +0100115 ALOGW("%s data size 0x%x extends beyond resource end %p.",
116 name, size, (void*)(dataEnd-((const uint8_t*)chunk)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 return BAD_TYPE;
118 }
Steve Block8564c8d2012-01-05 23:22:43 +0000119 ALOGW("%s size 0x%x or headerSize 0x%x is not on an integer boundary.",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120 name, (int)size, (int)headerSize);
121 return BAD_TYPE;
122 }
Patrik Bannura443dd932014-02-12 13:38:54 +0100123 ALOGW("%s size 0x%x is smaller than header size 0x%x.",
124 name, size, headerSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125 return BAD_TYPE;
126 }
Adam Lesinskide898ff2014-01-29 18:20:45 -0800127 ALOGW("%s header size 0x%04x is too small.",
Patrik Bannura443dd932014-02-12 13:38:54 +0100128 name, headerSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129 return BAD_TYPE;
130}
131
Narayan Kamath6381dd42014-03-03 17:12:03 +0000132static void fill9patchOffsets(Res_png_9patch* patch) {
133 patch->xDivsOffset = sizeof(Res_png_9patch);
134 patch->yDivsOffset = patch->xDivsOffset + (patch->numXDivs * sizeof(int32_t));
135 patch->colorsOffset = patch->yDivsOffset + (patch->numYDivs * sizeof(int32_t));
136}
137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138inline void Res_value::copyFrom_dtoh(const Res_value& src)
139{
140 size = dtohs(src.size);
141 res0 = src.res0;
142 dataType = src.dataType;
143 data = dtohl(src.data);
144}
145
146void Res_png_9patch::deviceToFile()
147{
Narayan Kamath6381dd42014-03-03 17:12:03 +0000148 int32_t* xDivs = getXDivs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149 for (int i = 0; i < numXDivs; i++) {
150 xDivs[i] = htonl(xDivs[i]);
151 }
Narayan Kamath6381dd42014-03-03 17:12:03 +0000152 int32_t* yDivs = getYDivs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153 for (int i = 0; i < numYDivs; i++) {
154 yDivs[i] = htonl(yDivs[i]);
155 }
156 paddingLeft = htonl(paddingLeft);
157 paddingRight = htonl(paddingRight);
158 paddingTop = htonl(paddingTop);
159 paddingBottom = htonl(paddingBottom);
Narayan Kamath6381dd42014-03-03 17:12:03 +0000160 uint32_t* colors = getColors();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 for (int i=0; i<numColors; i++) {
162 colors[i] = htonl(colors[i]);
163 }
164}
165
166void Res_png_9patch::fileToDevice()
167{
Narayan Kamath6381dd42014-03-03 17:12:03 +0000168 int32_t* xDivs = getXDivs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169 for (int i = 0; i < numXDivs; i++) {
170 xDivs[i] = ntohl(xDivs[i]);
171 }
Narayan Kamath6381dd42014-03-03 17:12:03 +0000172 int32_t* yDivs = getYDivs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173 for (int i = 0; i < numYDivs; i++) {
174 yDivs[i] = ntohl(yDivs[i]);
175 }
176 paddingLeft = ntohl(paddingLeft);
177 paddingRight = ntohl(paddingRight);
178 paddingTop = ntohl(paddingTop);
179 paddingBottom = ntohl(paddingBottom);
Narayan Kamath6381dd42014-03-03 17:12:03 +0000180 uint32_t* colors = getColors();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 for (int i=0; i<numColors; i++) {
182 colors[i] = ntohl(colors[i]);
183 }
184}
185
Narayan Kamath6381dd42014-03-03 17:12:03 +0000186size_t Res_png_9patch::serializedSize() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187{
188 // The size of this struct is 32 bytes on the 32-bit target system
189 // 4 * int8_t
190 // 4 * int32_t
Narayan Kamath6381dd42014-03-03 17:12:03 +0000191 // 3 * uint32_t
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 return 32
193 + numXDivs * sizeof(int32_t)
194 + numYDivs * sizeof(int32_t)
195 + numColors * sizeof(uint32_t);
196}
197
Narayan Kamath6381dd42014-03-03 17:12:03 +0000198void* Res_png_9patch::serialize(const Res_png_9patch& patch, const int32_t* xDivs,
199 const int32_t* yDivs, const uint32_t* colors)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200{
The Android Open Source Project4df24232009-03-05 14:34:35 -0800201 // Use calloc since we're going to leave a few holes in the data
202 // and want this to run cleanly under valgrind
Narayan Kamath6381dd42014-03-03 17:12:03 +0000203 void* newData = calloc(1, patch.serializedSize());
204 serialize(patch, xDivs, yDivs, colors, newData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 return newData;
206}
207
Narayan Kamath6381dd42014-03-03 17:12:03 +0000208void Res_png_9patch::serialize(const Res_png_9patch& patch, const int32_t* xDivs,
209 const int32_t* yDivs, const uint32_t* colors, void* outData)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210{
Narayan Kamath6381dd42014-03-03 17:12:03 +0000211 uint8_t* data = (uint8_t*) outData;
212 memcpy(data, &patch.wasDeserialized, 4); // copy wasDeserialized, numXDivs, numYDivs, numColors
213 memcpy(data + 12, &patch.paddingLeft, 16); // copy paddingXXXX
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214 data += 32;
215
Narayan Kamath6381dd42014-03-03 17:12:03 +0000216 memcpy(data, xDivs, patch.numXDivs * sizeof(int32_t));
217 data += patch.numXDivs * sizeof(int32_t);
218 memcpy(data, yDivs, patch.numYDivs * sizeof(int32_t));
219 data += patch.numYDivs * sizeof(int32_t);
220 memcpy(data, colors, patch.numColors * sizeof(uint32_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221
Narayan Kamath6381dd42014-03-03 17:12:03 +0000222 fill9patchOffsets(reinterpret_cast<Res_png_9patch*>(outData));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223}
224
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700225static bool assertIdmapHeader(const void* idmap, size_t size) {
226 if (reinterpret_cast<uintptr_t>(idmap) & 0x03) {
227 ALOGE("idmap: header is not word aligned");
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +0100228 return false;
229 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700230
231 if (size < ResTable::IDMAP_HEADER_SIZE_BYTES) {
232 ALOGW("idmap: header too small (%d bytes)", (uint32_t) size);
233 return false;
234 }
235
236 const uint32_t magic = htodl(*reinterpret_cast<const uint32_t*>(idmap));
237 if (magic != IDMAP_MAGIC) {
238 ALOGW("idmap: no magic found in header (is 0x%08x, expected 0x%08x)",
239 magic, IDMAP_MAGIC);
240 return false;
241 }
242
243 const uint32_t version = htodl(*(reinterpret_cast<const uint32_t*>(idmap) + 1));
244 if (version != IDMAP_CURRENT_VERSION) {
245 // We are strict about versions because files with this format are
246 // auto-generated and don't need backwards compatibility.
247 ALOGW("idmap: version mismatch in header (is 0x%08x, expected 0x%08x)",
248 version, IDMAP_CURRENT_VERSION);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +0100249 return false;
250 }
251 return true;
252}
253
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700254class IdmapEntries {
255public:
256 IdmapEntries() : mData(NULL) {}
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +0100257
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700258 bool hasEntries() const {
259 if (mData == NULL) {
260 return false;
261 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +0100262
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700263 return (dtohs(*mData) > 0);
264 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +0100265
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700266 size_t byteSize() const {
267 if (mData == NULL) {
268 return 0;
269 }
270 uint16_t entryCount = dtohs(mData[2]);
271 return (sizeof(uint16_t) * 4) + (sizeof(uint32_t) * static_cast<size_t>(entryCount));
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +0100272 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700273
274 uint8_t targetTypeId() const {
275 if (mData == NULL) {
276 return 0;
277 }
278 return dtohs(mData[0]);
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +0100279 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700280
281 uint8_t overlayTypeId() const {
282 if (mData == NULL) {
283 return 0;
284 }
285 return dtohs(mData[1]);
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +0100286 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700287
288 status_t setTo(const void* entryHeader, size_t size) {
289 if (reinterpret_cast<uintptr_t>(entryHeader) & 0x03) {
290 ALOGE("idmap: entry header is not word aligned");
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +0100291 return UNKNOWN_ERROR;
292 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700293
294 if (size < sizeof(uint16_t) * 4) {
295 ALOGE("idmap: entry header is too small (%u bytes)", (uint32_t) size);
296 return UNKNOWN_ERROR;
297 }
298
299 const uint16_t* header = reinterpret_cast<const uint16_t*>(entryHeader);
300 const uint16_t targetTypeId = dtohs(header[0]);
301 const uint16_t overlayTypeId = dtohs(header[1]);
302 if (targetTypeId == 0 || overlayTypeId == 0 || targetTypeId > 255 || overlayTypeId > 255) {
303 ALOGE("idmap: invalid type map (%u -> %u)", targetTypeId, overlayTypeId);
304 return UNKNOWN_ERROR;
305 }
306
307 uint16_t entryCount = dtohs(header[2]);
308 if (size < sizeof(uint32_t) * (entryCount + 2)) {
309 ALOGE("idmap: too small (%u bytes) for the number of entries (%u)",
310 (uint32_t) size, (uint32_t) entryCount);
311 return UNKNOWN_ERROR;
312 }
313 mData = header;
314 return NO_ERROR;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +0100315 }
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +0100316
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700317 status_t lookup(uint16_t entryId, uint16_t* outEntryId) const {
318 uint16_t entryCount = dtohs(mData[2]);
319 uint16_t offset = dtohs(mData[3]);
320
321 if (entryId < offset) {
322 // The entry is not present in this idmap
323 return BAD_INDEX;
324 }
325
326 entryId -= offset;
327
328 if (entryId >= entryCount) {
329 // The entry is not present in this idmap
330 return BAD_INDEX;
331 }
332
333 // It is safe to access the type here without checking the size because
334 // we have checked this when it was first loaded.
335 const uint32_t* entries = reinterpret_cast<const uint32_t*>(mData) + 2;
336 uint32_t mappedEntry = dtohl(entries[entryId]);
337 if (mappedEntry == 0xffffffff) {
338 // This entry is not present in this idmap
339 return BAD_INDEX;
340 }
341 *outEntryId = static_cast<uint16_t>(mappedEntry);
342 return NO_ERROR;
343 }
344
345private:
346 const uint16_t* mData;
347};
348
349status_t parseIdmap(const void* idmap, size_t size, uint8_t* outPackageId, KeyedVector<uint8_t, IdmapEntries>* outMap) {
350 if (!assertIdmapHeader(idmap, size)) {
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +0100351 return UNKNOWN_ERROR;
352 }
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +0100353
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700354 size -= ResTable::IDMAP_HEADER_SIZE_BYTES;
355 if (size < sizeof(uint16_t) * 2) {
356 ALOGE("idmap: too small to contain any mapping");
357 return UNKNOWN_ERROR;
358 }
359
360 const uint16_t* data = reinterpret_cast<const uint16_t*>(
361 reinterpret_cast<const uint8_t*>(idmap) + ResTable::IDMAP_HEADER_SIZE_BYTES);
362
363 uint16_t targetPackageId = dtohs(*(data++));
364 if (targetPackageId == 0 || targetPackageId > 255) {
365 ALOGE("idmap: target package ID is invalid (%02x)", targetPackageId);
366 return UNKNOWN_ERROR;
367 }
368
369 uint16_t mapCount = dtohs(*(data++));
370 if (mapCount == 0) {
371 ALOGE("idmap: no mappings");
372 return UNKNOWN_ERROR;
373 }
374
375 if (mapCount > 255) {
376 ALOGW("idmap: too many mappings. Only 255 are possible but %u are present", (uint32_t) mapCount);
377 }
378
379 while (size > sizeof(uint16_t) * 4) {
380 IdmapEntries entries;
381 status_t err = entries.setTo(data, size);
382 if (err != NO_ERROR) {
383 return err;
384 }
385
386 ssize_t index = outMap->add(entries.overlayTypeId(), entries);
387 if (index < 0) {
388 return NO_MEMORY;
389 }
390
391 data += entries.byteSize() / sizeof(uint16_t);
392 size -= entries.byteSize();
393 }
394
395 if (outPackageId != NULL) {
396 *outPackageId = static_cast<uint8_t>(targetPackageId);
397 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +0100398 return NO_ERROR;
399}
400
Narayan Kamath6381dd42014-03-03 17:12:03 +0000401Res_png_9patch* Res_png_9patch::deserialize(void* inData)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800402{
Narayan Kamath6381dd42014-03-03 17:12:03 +0000403
404 Res_png_9patch* patch = reinterpret_cast<Res_png_9patch*>(inData);
405 patch->wasDeserialized = true;
406 fill9patchOffsets(patch);
407
408 return patch;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800409}
410
411// --------------------------------------------------------------------
412// --------------------------------------------------------------------
413// --------------------------------------------------------------------
414
415ResStringPool::ResStringPool()
Kenny Root19138462009-12-04 09:38:48 -0800416 : mError(NO_INIT), mOwnedData(NULL), mHeader(NULL), mCache(NULL)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800417{
418}
419
420ResStringPool::ResStringPool(const void* data, size_t size, bool copyData)
Kenny Root19138462009-12-04 09:38:48 -0800421 : mError(NO_INIT), mOwnedData(NULL), mHeader(NULL), mCache(NULL)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422{
423 setTo(data, size, copyData);
424}
425
426ResStringPool::~ResStringPool()
427{
428 uninit();
429}
430
Adam Lesinskide898ff2014-01-29 18:20:45 -0800431void ResStringPool::setToEmpty()
432{
433 uninit();
434
435 mOwnedData = calloc(1, sizeof(ResStringPool_header));
436 ResStringPool_header* header = (ResStringPool_header*) mOwnedData;
437 mSize = 0;
438 mEntries = NULL;
439 mStrings = NULL;
440 mStringPoolSize = 0;
441 mEntryStyles = NULL;
442 mStyles = NULL;
443 mStylePoolSize = 0;
444 mHeader = (const ResStringPool_header*) header;
445}
446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447status_t ResStringPool::setTo(const void* data, size_t size, bool copyData)
448{
449 if (!data || !size) {
450 return (mError=BAD_TYPE);
451 }
452
453 uninit();
454
455 const bool notDeviceEndian = htods(0xf0) != 0xf0;
456
457 if (copyData || notDeviceEndian) {
458 mOwnedData = malloc(size);
459 if (mOwnedData == NULL) {
460 return (mError=NO_MEMORY);
461 }
462 memcpy(mOwnedData, data, size);
463 data = mOwnedData;
464 }
465
466 mHeader = (const ResStringPool_header*)data;
467
468 if (notDeviceEndian) {
469 ResStringPool_header* h = const_cast<ResStringPool_header*>(mHeader);
470 h->header.headerSize = dtohs(mHeader->header.headerSize);
471 h->header.type = dtohs(mHeader->header.type);
472 h->header.size = dtohl(mHeader->header.size);
473 h->stringCount = dtohl(mHeader->stringCount);
474 h->styleCount = dtohl(mHeader->styleCount);
475 h->flags = dtohl(mHeader->flags);
476 h->stringsStart = dtohl(mHeader->stringsStart);
477 h->stylesStart = dtohl(mHeader->stylesStart);
478 }
479
480 if (mHeader->header.headerSize > mHeader->header.size
481 || mHeader->header.size > size) {
Steve Block8564c8d2012-01-05 23:22:43 +0000482 ALOGW("Bad string block: header size %d or total size %d is larger than data size %d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483 (int)mHeader->header.headerSize, (int)mHeader->header.size, (int)size);
484 return (mError=BAD_TYPE);
485 }
486 mSize = mHeader->header.size;
487 mEntries = (const uint32_t*)
488 (((const uint8_t*)data)+mHeader->header.headerSize);
489
490 if (mHeader->stringCount > 0) {
491 if ((mHeader->stringCount*sizeof(uint32_t) < mHeader->stringCount) // uint32 overflow?
492 || (mHeader->header.headerSize+(mHeader->stringCount*sizeof(uint32_t)))
493 > size) {
Steve Block8564c8d2012-01-05 23:22:43 +0000494 ALOGW("Bad string block: entry of %d items extends past data size %d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495 (int)(mHeader->header.headerSize+(mHeader->stringCount*sizeof(uint32_t))),
496 (int)size);
497 return (mError=BAD_TYPE);
498 }
Kenny Root19138462009-12-04 09:38:48 -0800499
500 size_t charSize;
501 if (mHeader->flags&ResStringPool_header::UTF8_FLAG) {
502 charSize = sizeof(uint8_t);
Kenny Root19138462009-12-04 09:38:48 -0800503 } else {
Adam Lesinski4bf58102014-11-03 11:21:19 -0800504 charSize = sizeof(uint16_t);
Kenny Root19138462009-12-04 09:38:48 -0800505 }
506
Adam Lesinskif28d5052014-07-25 15:25:04 -0700507 // There should be at least space for the smallest string
508 // (2 bytes length, null terminator).
509 if (mHeader->stringsStart >= (mSize - sizeof(uint16_t))) {
Steve Block8564c8d2012-01-05 23:22:43 +0000510 ALOGW("Bad string block: string pool starts at %d, after total size %d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800511 (int)mHeader->stringsStart, (int)mHeader->header.size);
512 return (mError=BAD_TYPE);
513 }
Adam Lesinskif28d5052014-07-25 15:25:04 -0700514
515 mStrings = (const void*)
516 (((const uint8_t*)data) + mHeader->stringsStart);
517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518 if (mHeader->styleCount == 0) {
Adam Lesinskif28d5052014-07-25 15:25:04 -0700519 mStringPoolSize = (mSize - mHeader->stringsStart) / charSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800520 } else {
Kenny Root5e4d9a02010-06-08 12:34:43 -0700521 // check invariant: styles starts before end of data
Adam Lesinskif28d5052014-07-25 15:25:04 -0700522 if (mHeader->stylesStart >= (mSize - sizeof(uint16_t))) {
Steve Block8564c8d2012-01-05 23:22:43 +0000523 ALOGW("Bad style block: style block starts at %d past data size of %d\n",
Kenny Root5e4d9a02010-06-08 12:34:43 -0700524 (int)mHeader->stylesStart, (int)mHeader->header.size);
525 return (mError=BAD_TYPE);
526 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527 // check invariant: styles follow the strings
528 if (mHeader->stylesStart <= mHeader->stringsStart) {
Steve Block8564c8d2012-01-05 23:22:43 +0000529 ALOGW("Bad style block: style block starts at %d, before strings at %d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 (int)mHeader->stylesStart, (int)mHeader->stringsStart);
531 return (mError=BAD_TYPE);
532 }
533 mStringPoolSize =
Kenny Root19138462009-12-04 09:38:48 -0800534 (mHeader->stylesStart-mHeader->stringsStart)/charSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535 }
536
537 // check invariant: stringCount > 0 requires a string pool to exist
538 if (mStringPoolSize == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +0000539 ALOGW("Bad string block: stringCount is %d but pool size is 0\n", (int)mHeader->stringCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540 return (mError=BAD_TYPE);
541 }
542
543 if (notDeviceEndian) {
544 size_t i;
545 uint32_t* e = const_cast<uint32_t*>(mEntries);
546 for (i=0; i<mHeader->stringCount; i++) {
547 e[i] = dtohl(mEntries[i]);
548 }
Kenny Root19138462009-12-04 09:38:48 -0800549 if (!(mHeader->flags&ResStringPool_header::UTF8_FLAG)) {
Adam Lesinski4bf58102014-11-03 11:21:19 -0800550 const uint16_t* strings = (const uint16_t*)mStrings;
551 uint16_t* s = const_cast<uint16_t*>(strings);
Kenny Root19138462009-12-04 09:38:48 -0800552 for (i=0; i<mStringPoolSize; i++) {
553 s[i] = dtohs(strings[i]);
554 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 }
556 }
557
Kenny Root19138462009-12-04 09:38:48 -0800558 if ((mHeader->flags&ResStringPool_header::UTF8_FLAG &&
559 ((uint8_t*)mStrings)[mStringPoolSize-1] != 0) ||
560 (!mHeader->flags&ResStringPool_header::UTF8_FLAG &&
Adam Lesinski4bf58102014-11-03 11:21:19 -0800561 ((uint16_t*)mStrings)[mStringPoolSize-1] != 0)) {
Steve Block8564c8d2012-01-05 23:22:43 +0000562 ALOGW("Bad string block: last string is not 0-terminated\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800563 return (mError=BAD_TYPE);
564 }
565 } else {
566 mStrings = NULL;
567 mStringPoolSize = 0;
568 }
569
570 if (mHeader->styleCount > 0) {
571 mEntryStyles = mEntries + mHeader->stringCount;
572 // invariant: integer overflow in calculating mEntryStyles
573 if (mEntryStyles < mEntries) {
Steve Block8564c8d2012-01-05 23:22:43 +0000574 ALOGW("Bad string block: integer overflow finding styles\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 return (mError=BAD_TYPE);
576 }
577
578 if (((const uint8_t*)mEntryStyles-(const uint8_t*)mHeader) > (int)size) {
Steve Block8564c8d2012-01-05 23:22:43 +0000579 ALOGW("Bad string block: entry of %d styles extends past data size %d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580 (int)((const uint8_t*)mEntryStyles-(const uint8_t*)mHeader),
581 (int)size);
582 return (mError=BAD_TYPE);
583 }
584 mStyles = (const uint32_t*)
585 (((const uint8_t*)data)+mHeader->stylesStart);
586 if (mHeader->stylesStart >= mHeader->header.size) {
Steve Block8564c8d2012-01-05 23:22:43 +0000587 ALOGW("Bad string block: style pool starts %d, after total size %d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800588 (int)mHeader->stylesStart, (int)mHeader->header.size);
589 return (mError=BAD_TYPE);
590 }
591 mStylePoolSize =
592 (mHeader->header.size-mHeader->stylesStart)/sizeof(uint32_t);
593
594 if (notDeviceEndian) {
595 size_t i;
596 uint32_t* e = const_cast<uint32_t*>(mEntryStyles);
597 for (i=0; i<mHeader->styleCount; i++) {
598 e[i] = dtohl(mEntryStyles[i]);
599 }
600 uint32_t* s = const_cast<uint32_t*>(mStyles);
601 for (i=0; i<mStylePoolSize; i++) {
602 s[i] = dtohl(mStyles[i]);
603 }
604 }
605
606 const ResStringPool_span endSpan = {
607 { htodl(ResStringPool_span::END) },
608 htodl(ResStringPool_span::END), htodl(ResStringPool_span::END)
609 };
610 if (memcmp(&mStyles[mStylePoolSize-(sizeof(endSpan)/sizeof(uint32_t))],
611 &endSpan, sizeof(endSpan)) != 0) {
Steve Block8564c8d2012-01-05 23:22:43 +0000612 ALOGW("Bad string block: last style is not 0xFFFFFFFF-terminated\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 return (mError=BAD_TYPE);
614 }
615 } else {
616 mEntryStyles = NULL;
617 mStyles = NULL;
618 mStylePoolSize = 0;
619 }
620
621 return (mError=NO_ERROR);
622}
623
624status_t ResStringPool::getError() const
625{
626 return mError;
627}
628
629void ResStringPool::uninit()
630{
631 mError = NO_INIT;
Kenny Root19138462009-12-04 09:38:48 -0800632 if (mHeader != NULL && mCache != NULL) {
633 for (size_t x = 0; x < mHeader->stringCount; x++) {
634 if (mCache[x] != NULL) {
635 free(mCache[x]);
636 mCache[x] = NULL;
637 }
638 }
639 free(mCache);
640 mCache = NULL;
641 }
Chris Dearmana1d82ff32012-10-08 12:22:02 -0700642 if (mOwnedData) {
643 free(mOwnedData);
644 mOwnedData = NULL;
645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646}
647
Kenny Root300ba682010-11-09 14:37:23 -0800648/**
649 * Strings in UTF-16 format have length indicated by a length encoded in the
650 * stored data. It is either 1 or 2 characters of length data. This allows a
651 * maximum length of 0x7FFFFFF (2147483647 bytes), but if you're storing that
652 * much data in a string, you're abusing them.
653 *
654 * If the high bit is set, then there are two characters or 4 bytes of length
655 * data encoded. In that case, drop the high bit of the first character and
656 * add it together with the next character.
657 */
658static inline size_t
Adam Lesinski4bf58102014-11-03 11:21:19 -0800659decodeLength(const uint16_t** str)
Kenny Root300ba682010-11-09 14:37:23 -0800660{
661 size_t len = **str;
662 if ((len & 0x8000) != 0) {
663 (*str)++;
664 len = ((len & 0x7FFF) << 16) | **str;
665 }
666 (*str)++;
667 return len;
668}
Kenny Root19138462009-12-04 09:38:48 -0800669
Kenny Root300ba682010-11-09 14:37:23 -0800670/**
671 * Strings in UTF-8 format have length indicated by a length encoded in the
672 * stored data. It is either 1 or 2 characters of length data. This allows a
673 * maximum length of 0x7FFF (32767 bytes), but you should consider storing
674 * text in another way if you're using that much data in a single string.
675 *
676 * If the high bit is set, then there are two characters or 2 bytes of length
677 * data encoded. In that case, drop the high bit of the first character and
678 * add it together with the next character.
679 */
680static inline size_t
681decodeLength(const uint8_t** str)
682{
683 size_t len = **str;
684 if ((len & 0x80) != 0) {
685 (*str)++;
686 len = ((len & 0x7F) << 8) | **str;
687 }
688 (*str)++;
689 return len;
690}
691
Adam Lesinski4bf58102014-11-03 11:21:19 -0800692const char16_t* ResStringPool::stringAt(size_t idx, size_t* u16len) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693{
694 if (mError == NO_ERROR && idx < mHeader->stringCount) {
Kenny Root19138462009-12-04 09:38:48 -0800695 const bool isUTF8 = (mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0;
Adam Lesinski4bf58102014-11-03 11:21:19 -0800696 const uint32_t off = mEntries[idx]/(isUTF8?sizeof(uint8_t):sizeof(uint16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 if (off < (mStringPoolSize-1)) {
Kenny Root19138462009-12-04 09:38:48 -0800698 if (!isUTF8) {
Adam Lesinski4bf58102014-11-03 11:21:19 -0800699 const uint16_t* strings = (uint16_t*)mStrings;
700 const uint16_t* str = strings+off;
Kenny Root300ba682010-11-09 14:37:23 -0800701
702 *u16len = decodeLength(&str);
703 if ((uint32_t)(str+*u16len-strings) < mStringPoolSize) {
Adam Lesinski4bf58102014-11-03 11:21:19 -0800704 return reinterpret_cast<const char16_t*>(str);
Kenny Root19138462009-12-04 09:38:48 -0800705 } else {
Steve Block8564c8d2012-01-05 23:22:43 +0000706 ALOGW("Bad string block: string #%d extends to %d, past end at %d\n",
Kenny Root300ba682010-11-09 14:37:23 -0800707 (int)idx, (int)(str+*u16len-strings), (int)mStringPoolSize);
Kenny Root19138462009-12-04 09:38:48 -0800708 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 } else {
Kenny Root19138462009-12-04 09:38:48 -0800710 const uint8_t* strings = (uint8_t*)mStrings;
Kenny Root300ba682010-11-09 14:37:23 -0800711 const uint8_t* u8str = strings+off;
712
713 *u16len = decodeLength(&u8str);
714 size_t u8len = decodeLength(&u8str);
715
716 // encLen must be less than 0x7FFF due to encoding.
717 if ((uint32_t)(u8str+u8len-strings) < mStringPoolSize) {
Kenny Root19138462009-12-04 09:38:48 -0800718 AutoMutex lock(mDecodeLock);
Kenny Root300ba682010-11-09 14:37:23 -0800719
Dianne Hackbornd45c68d2013-07-31 12:14:24 -0700720 if (mCache == NULL) {
721#ifndef HAVE_ANDROID_OS
722 STRING_POOL_NOISY(ALOGI("CREATING STRING CACHE OF %d bytes",
723 mHeader->stringCount*sizeof(char16_t**)));
724#else
725 // We do not want to be in this case when actually running Android.
726 ALOGW("CREATING STRING CACHE OF %d bytes",
727 mHeader->stringCount*sizeof(char16_t**));
728#endif
729 mCache = (char16_t**)calloc(mHeader->stringCount, sizeof(char16_t**));
730 if (mCache == NULL) {
731 ALOGW("No memory trying to allocate decode cache table of %d bytes\n",
732 (int)(mHeader->stringCount*sizeof(char16_t**)));
733 return NULL;
734 }
735 }
736
Kenny Root19138462009-12-04 09:38:48 -0800737 if (mCache[idx] != NULL) {
738 return mCache[idx];
739 }
Kenny Root300ba682010-11-09 14:37:23 -0800740
741 ssize_t actualLen = utf8_to_utf16_length(u8str, u8len);
742 if (actualLen < 0 || (size_t)actualLen != *u16len) {
Steve Block8564c8d2012-01-05 23:22:43 +0000743 ALOGW("Bad string block: string #%lld decoded length is not correct "
Kenny Root300ba682010-11-09 14:37:23 -0800744 "%lld vs %llu\n",
745 (long long)idx, (long long)actualLen, (long long)*u16len);
746 return NULL;
747 }
748
749 char16_t *u16str = (char16_t *)calloc(*u16len+1, sizeof(char16_t));
Kenny Root19138462009-12-04 09:38:48 -0800750 if (!u16str) {
Steve Block8564c8d2012-01-05 23:22:43 +0000751 ALOGW("No memory when trying to allocate decode cache for string #%d\n",
Kenny Root19138462009-12-04 09:38:48 -0800752 (int)idx);
753 return NULL;
754 }
Kenny Root300ba682010-11-09 14:37:23 -0800755
Dianne Hackbornd45c68d2013-07-31 12:14:24 -0700756 STRING_POOL_NOISY(ALOGI("Caching UTF8 string: %s", u8str));
Kenny Root300ba682010-11-09 14:37:23 -0800757 utf8_to_utf16(u8str, u8len, u16str);
Kenny Root19138462009-12-04 09:38:48 -0800758 mCache[idx] = u16str;
759 return u16str;
760 } else {
Steve Block8564c8d2012-01-05 23:22:43 +0000761 ALOGW("Bad string block: string #%lld extends to %lld, past end at %lld\n",
Kenny Root300ba682010-11-09 14:37:23 -0800762 (long long)idx, (long long)(u8str+u8len-strings),
763 (long long)mStringPoolSize);
Kenny Root19138462009-12-04 09:38:48 -0800764 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 }
766 } else {
Steve Block8564c8d2012-01-05 23:22:43 +0000767 ALOGW("Bad string block: string #%d entry is at %d, past end at %d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 (int)idx, (int)(off*sizeof(uint16_t)),
769 (int)(mStringPoolSize*sizeof(uint16_t)));
770 }
771 }
772 return NULL;
773}
774
Kenny Root780d2a12010-02-22 22:36:26 -0800775const char* ResStringPool::string8At(size_t idx, size_t* outLen) const
776{
777 if (mError == NO_ERROR && idx < mHeader->stringCount) {
Dianne Hackbornd45c68d2013-07-31 12:14:24 -0700778 if ((mHeader->flags&ResStringPool_header::UTF8_FLAG) == 0) {
779 return NULL;
780 }
781 const uint32_t off = mEntries[idx]/sizeof(char);
Kenny Root780d2a12010-02-22 22:36:26 -0800782 if (off < (mStringPoolSize-1)) {
Dianne Hackbornd45c68d2013-07-31 12:14:24 -0700783 const uint8_t* strings = (uint8_t*)mStrings;
784 const uint8_t* str = strings+off;
785 *outLen = decodeLength(&str);
786 size_t encLen = decodeLength(&str);
787 if ((uint32_t)(str+encLen-strings) < mStringPoolSize) {
788 return (const char*)str;
789 } else {
790 ALOGW("Bad string block: string #%d extends to %d, past end at %d\n",
791 (int)idx, (int)(str+encLen-strings), (int)mStringPoolSize);
Kenny Root780d2a12010-02-22 22:36:26 -0800792 }
793 } else {
Steve Block8564c8d2012-01-05 23:22:43 +0000794 ALOGW("Bad string block: string #%d entry is at %d, past end at %d\n",
Kenny Root780d2a12010-02-22 22:36:26 -0800795 (int)idx, (int)(off*sizeof(uint16_t)),
796 (int)(mStringPoolSize*sizeof(uint16_t)));
797 }
798 }
799 return NULL;
800}
801
Dianne Hackborn6c997a92012-01-31 11:27:43 -0800802const String8 ResStringPool::string8ObjectAt(size_t idx) const
803{
804 size_t len;
Adam Lesinski4b2d0f22014-08-14 17:58:37 -0700805 const char *str = string8At(idx, &len);
Dianne Hackborn6c997a92012-01-31 11:27:43 -0800806 if (str != NULL) {
Adam Lesinski4b2d0f22014-08-14 17:58:37 -0700807 return String8(str, len);
Dianne Hackborn6c997a92012-01-31 11:27:43 -0800808 }
Adam Lesinski4b2d0f22014-08-14 17:58:37 -0700809
810 const char16_t *str16 = stringAt(idx, &len);
811 if (str16 != NULL) {
812 return String8(str16, len);
813 }
814 return String8();
Dianne Hackborn6c997a92012-01-31 11:27:43 -0800815}
816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817const ResStringPool_span* ResStringPool::styleAt(const ResStringPool_ref& ref) const
818{
819 return styleAt(ref.index);
820}
821
822const ResStringPool_span* ResStringPool::styleAt(size_t idx) const
823{
824 if (mError == NO_ERROR && idx < mHeader->styleCount) {
825 const uint32_t off = (mEntryStyles[idx]/sizeof(uint32_t));
826 if (off < mStylePoolSize) {
827 return (const ResStringPool_span*)(mStyles+off);
828 } else {
Steve Block8564c8d2012-01-05 23:22:43 +0000829 ALOGW("Bad string block: style #%d entry is at %d, past end at %d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 (int)idx, (int)(off*sizeof(uint32_t)),
831 (int)(mStylePoolSize*sizeof(uint32_t)));
832 }
833 }
834 return NULL;
835}
836
837ssize_t ResStringPool::indexOfString(const char16_t* str, size_t strLen) const
838{
839 if (mError != NO_ERROR) {
840 return mError;
841 }
842
843 size_t len;
844
Dianne Hackbornd45c68d2013-07-31 12:14:24 -0700845 if ((mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0) {
846 STRING_POOL_NOISY(ALOGI("indexOfString UTF-8: %s", String8(str, strLen).string()));
Kenny Root19138462009-12-04 09:38:48 -0800847
Dianne Hackbornd45c68d2013-07-31 12:14:24 -0700848 // The string pool contains UTF 8 strings; we don't want to cause
849 // temporary UTF-16 strings to be created as we search.
850 if (mHeader->flags&ResStringPool_header::SORTED_FLAG) {
851 // Do a binary search for the string... this is a little tricky,
852 // because the strings are sorted with strzcmp16(). So to match
853 // the ordering, we need to convert strings in the pool to UTF-16.
854 // But we don't want to hit the cache, so instead we will have a
855 // local temporary allocation for the conversions.
856 char16_t* convBuffer = (char16_t*)malloc(strLen+4);
857 ssize_t l = 0;
858 ssize_t h = mHeader->stringCount-1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859
Dianne Hackbornd45c68d2013-07-31 12:14:24 -0700860 ssize_t mid;
861 while (l <= h) {
862 mid = l + (h - l)/2;
863 const uint8_t* s = (const uint8_t*)string8At(mid, &len);
864 int c;
865 if (s != NULL) {
866 char16_t* end = utf8_to_utf16_n(s, len, convBuffer, strLen+3);
867 *end = 0;
868 c = strzcmp16(convBuffer, end-convBuffer, str, strLen);
869 } else {
870 c = -1;
871 }
872 STRING_POOL_NOISY(ALOGI("Looking at %s, cmp=%d, l/mid/h=%d/%d/%d\n",
873 (const char*)s, c, (int)l, (int)mid, (int)h));
874 if (c == 0) {
875 STRING_POOL_NOISY(ALOGI("MATCH!"));
876 free(convBuffer);
877 return mid;
878 } else if (c < 0) {
879 l = mid + 1;
880 } else {
881 h = mid - 1;
882 }
883 }
884 free(convBuffer);
885 } else {
886 // It is unusual to get the ID from an unsorted string block...
887 // most often this happens because we want to get IDs for style
888 // span tags; since those always appear at the end of the string
889 // block, start searching at the back.
890 String8 str8(str, strLen);
891 const size_t str8Len = str8.size();
892 for (int i=mHeader->stringCount-1; i>=0; i--) {
893 const char* s = string8At(i, &len);
894 STRING_POOL_NOISY(ALOGI("Looking at %s, i=%d\n",
895 String8(s).string(),
896 i));
897 if (s && str8Len == len && memcmp(s, str8.string(), str8Len) == 0) {
898 STRING_POOL_NOISY(ALOGI("MATCH!"));
899 return i;
900 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 }
902 }
Dianne Hackbornd45c68d2013-07-31 12:14:24 -0700903
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 } else {
Dianne Hackbornd45c68d2013-07-31 12:14:24 -0700905 STRING_POOL_NOISY(ALOGI("indexOfString UTF-16: %s", String8(str, strLen).string()));
906
907 if (mHeader->flags&ResStringPool_header::SORTED_FLAG) {
908 // Do a binary search for the string...
909 ssize_t l = 0;
910 ssize_t h = mHeader->stringCount-1;
911
912 ssize_t mid;
913 while (l <= h) {
914 mid = l + (h - l)/2;
915 const char16_t* s = stringAt(mid, &len);
916 int c = s ? strzcmp16(s, len, str, strLen) : -1;
917 STRING_POOL_NOISY(ALOGI("Looking at %s, cmp=%d, l/mid/h=%d/%d/%d\n",
918 String8(s).string(),
919 c, (int)l, (int)mid, (int)h));
920 if (c == 0) {
921 STRING_POOL_NOISY(ALOGI("MATCH!"));
922 return mid;
923 } else if (c < 0) {
924 l = mid + 1;
925 } else {
926 h = mid - 1;
927 }
928 }
929 } else {
930 // It is unusual to get the ID from an unsorted string block...
931 // most often this happens because we want to get IDs for style
932 // span tags; since those always appear at the end of the string
933 // block, start searching at the back.
934 for (int i=mHeader->stringCount-1; i>=0; i--) {
935 const char16_t* s = stringAt(i, &len);
936 STRING_POOL_NOISY(ALOGI("Looking at %s, i=%d\n",
937 String8(s).string(),
938 i));
939 if (s && strLen == len && strzcmp16(s, len, str, strLen) == 0) {
940 STRING_POOL_NOISY(ALOGI("MATCH!"));
941 return i;
942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800943 }
944 }
945 }
946
947 return NAME_NOT_FOUND;
948}
949
950size_t ResStringPool::size() const
951{
952 return (mError == NO_ERROR) ? mHeader->stringCount : 0;
953}
954
Dianne Hackborn6c997a92012-01-31 11:27:43 -0800955size_t ResStringPool::styleCount() const
956{
957 return (mError == NO_ERROR) ? mHeader->styleCount : 0;
958}
959
960size_t ResStringPool::bytes() const
961{
962 return (mError == NO_ERROR) ? mHeader->header.size : 0;
963}
964
965bool ResStringPool::isSorted() const
966{
967 return (mHeader->flags&ResStringPool_header::SORTED_FLAG)!=0;
968}
969
Kenny Rootbb79f642009-12-10 14:20:15 -0800970bool ResStringPool::isUTF8() const
971{
972 return (mHeader->flags&ResStringPool_header::UTF8_FLAG)!=0;
973}
Kenny Rootbb79f642009-12-10 14:20:15 -0800974
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975// --------------------------------------------------------------------
976// --------------------------------------------------------------------
977// --------------------------------------------------------------------
978
979ResXMLParser::ResXMLParser(const ResXMLTree& tree)
980 : mTree(tree), mEventCode(BAD_DOCUMENT)
981{
982}
983
984void ResXMLParser::restart()
985{
986 mCurNode = NULL;
987 mEventCode = mTree.mError == NO_ERROR ? START_DOCUMENT : BAD_DOCUMENT;
988}
Dianne Hackborncf244ad2010-03-09 15:00:30 -0800989const ResStringPool& ResXMLParser::getStrings() const
990{
991 return mTree.mStrings;
992}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993
994ResXMLParser::event_code_t ResXMLParser::getEventType() const
995{
996 return mEventCode;
997}
998
999ResXMLParser::event_code_t ResXMLParser::next()
1000{
1001 if (mEventCode == START_DOCUMENT) {
1002 mCurNode = mTree.mRootNode;
1003 mCurExt = mTree.mRootExt;
1004 return (mEventCode=mTree.mRootCode);
1005 } else if (mEventCode >= FIRST_CHUNK_CODE) {
1006 return nextNode();
1007 }
1008 return mEventCode;
1009}
1010
Mathias Agopian5f910972009-06-22 02:35:32 -07001011int32_t ResXMLParser::getCommentID() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012{
1013 return mCurNode != NULL ? dtohl(mCurNode->comment.index) : -1;
1014}
1015
Adam Lesinski4bf58102014-11-03 11:21:19 -08001016const char16_t* ResXMLParser::getComment(size_t* outLen) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017{
1018 int32_t id = getCommentID();
1019 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1020}
1021
Mathias Agopian5f910972009-06-22 02:35:32 -07001022uint32_t ResXMLParser::getLineNumber() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023{
1024 return mCurNode != NULL ? dtohl(mCurNode->lineNumber) : -1;
1025}
1026
Mathias Agopian5f910972009-06-22 02:35:32 -07001027int32_t ResXMLParser::getTextID() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028{
1029 if (mEventCode == TEXT) {
1030 return dtohl(((const ResXMLTree_cdataExt*)mCurExt)->data.index);
1031 }
1032 return -1;
1033}
1034
Adam Lesinski4bf58102014-11-03 11:21:19 -08001035const char16_t* ResXMLParser::getText(size_t* outLen) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036{
1037 int32_t id = getTextID();
1038 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1039}
1040
1041ssize_t ResXMLParser::getTextValue(Res_value* outValue) const
1042{
1043 if (mEventCode == TEXT) {
1044 outValue->copyFrom_dtoh(((const ResXMLTree_cdataExt*)mCurExt)->typedData);
1045 return sizeof(Res_value);
1046 }
1047 return BAD_TYPE;
1048}
1049
Mathias Agopian5f910972009-06-22 02:35:32 -07001050int32_t ResXMLParser::getNamespacePrefixID() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051{
1052 if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) {
1053 return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->prefix.index);
1054 }
1055 return -1;
1056}
1057
Adam Lesinski4bf58102014-11-03 11:21:19 -08001058const char16_t* ResXMLParser::getNamespacePrefix(size_t* outLen) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059{
1060 int32_t id = getNamespacePrefixID();
1061 //printf("prefix=%d event=%p\n", id, mEventCode);
1062 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1063}
1064
Mathias Agopian5f910972009-06-22 02:35:32 -07001065int32_t ResXMLParser::getNamespaceUriID() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066{
1067 if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) {
1068 return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->uri.index);
1069 }
1070 return -1;
1071}
1072
Adam Lesinski4bf58102014-11-03 11:21:19 -08001073const char16_t* ResXMLParser::getNamespaceUri(size_t* outLen) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074{
1075 int32_t id = getNamespaceUriID();
1076 //printf("uri=%d event=%p\n", id, mEventCode);
1077 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1078}
1079
Mathias Agopian5f910972009-06-22 02:35:32 -07001080int32_t ResXMLParser::getElementNamespaceID() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081{
1082 if (mEventCode == START_TAG) {
1083 return dtohl(((const ResXMLTree_attrExt*)mCurExt)->ns.index);
1084 }
1085 if (mEventCode == END_TAG) {
1086 return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->ns.index);
1087 }
1088 return -1;
1089}
1090
Adam Lesinski4bf58102014-11-03 11:21:19 -08001091const char16_t* ResXMLParser::getElementNamespace(size_t* outLen) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092{
1093 int32_t id = getElementNamespaceID();
1094 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1095}
1096
Mathias Agopian5f910972009-06-22 02:35:32 -07001097int32_t ResXMLParser::getElementNameID() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098{
1099 if (mEventCode == START_TAG) {
1100 return dtohl(((const ResXMLTree_attrExt*)mCurExt)->name.index);
1101 }
1102 if (mEventCode == END_TAG) {
1103 return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->name.index);
1104 }
1105 return -1;
1106}
1107
Adam Lesinski4bf58102014-11-03 11:21:19 -08001108const char16_t* ResXMLParser::getElementName(size_t* outLen) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109{
1110 int32_t id = getElementNameID();
1111 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1112}
1113
1114size_t ResXMLParser::getAttributeCount() const
1115{
1116 if (mEventCode == START_TAG) {
1117 return dtohs(((const ResXMLTree_attrExt*)mCurExt)->attributeCount);
1118 }
1119 return 0;
1120}
1121
Mathias Agopian5f910972009-06-22 02:35:32 -07001122int32_t ResXMLParser::getAttributeNamespaceID(size_t idx) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123{
1124 if (mEventCode == START_TAG) {
1125 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1126 if (idx < dtohs(tag->attributeCount)) {
1127 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1128 (((const uint8_t*)tag)
1129 + dtohs(tag->attributeStart)
1130 + (dtohs(tag->attributeSize)*idx));
1131 return dtohl(attr->ns.index);
1132 }
1133 }
1134 return -2;
1135}
1136
Adam Lesinski4bf58102014-11-03 11:21:19 -08001137const char16_t* ResXMLParser::getAttributeNamespace(size_t idx, size_t* outLen) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138{
1139 int32_t id = getAttributeNamespaceID(idx);
1140 //printf("attribute namespace=%d idx=%d event=%p\n", id, idx, mEventCode);
1141 //XML_NOISY(printf("getAttributeNamespace 0x%x=0x%x\n", idx, id));
1142 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1143}
1144
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07001145const char* ResXMLParser::getAttributeNamespace8(size_t idx, size_t* outLen) const
1146{
1147 int32_t id = getAttributeNamespaceID(idx);
1148 //printf("attribute namespace=%d idx=%d event=%p\n", id, idx, mEventCode);
1149 //XML_NOISY(printf("getAttributeNamespace 0x%x=0x%x\n", idx, id));
1150 return id >= 0 ? mTree.mStrings.string8At(id, outLen) : NULL;
1151}
1152
Mathias Agopian5f910972009-06-22 02:35:32 -07001153int32_t ResXMLParser::getAttributeNameID(size_t idx) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154{
1155 if (mEventCode == START_TAG) {
1156 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1157 if (idx < dtohs(tag->attributeCount)) {
1158 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1159 (((const uint8_t*)tag)
1160 + dtohs(tag->attributeStart)
1161 + (dtohs(tag->attributeSize)*idx));
1162 return dtohl(attr->name.index);
1163 }
1164 }
1165 return -1;
1166}
1167
Adam Lesinski4bf58102014-11-03 11:21:19 -08001168const char16_t* ResXMLParser::getAttributeName(size_t idx, size_t* outLen) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169{
1170 int32_t id = getAttributeNameID(idx);
1171 //printf("attribute name=%d idx=%d event=%p\n", id, idx, mEventCode);
1172 //XML_NOISY(printf("getAttributeName 0x%x=0x%x\n", idx, id));
1173 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1174}
1175
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07001176const char* ResXMLParser::getAttributeName8(size_t idx, size_t* outLen) const
1177{
1178 int32_t id = getAttributeNameID(idx);
1179 //printf("attribute name=%d idx=%d event=%p\n", id, idx, mEventCode);
1180 //XML_NOISY(printf("getAttributeName 0x%x=0x%x\n", idx, id));
1181 return id >= 0 ? mTree.mStrings.string8At(id, outLen) : NULL;
1182}
1183
Mathias Agopian5f910972009-06-22 02:35:32 -07001184uint32_t ResXMLParser::getAttributeNameResID(size_t idx) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185{
1186 int32_t id = getAttributeNameID(idx);
1187 if (id >= 0 && (size_t)id < mTree.mNumResIds) {
Adam Powell908c7482014-10-01 18:11:18 +00001188 return dtohl(mTree.mResIds[id]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 }
1190 return 0;
1191}
1192
Mathias Agopian5f910972009-06-22 02:35:32 -07001193int32_t ResXMLParser::getAttributeValueStringID(size_t idx) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194{
1195 if (mEventCode == START_TAG) {
1196 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1197 if (idx < dtohs(tag->attributeCount)) {
1198 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1199 (((const uint8_t*)tag)
1200 + dtohs(tag->attributeStart)
1201 + (dtohs(tag->attributeSize)*idx));
1202 return dtohl(attr->rawValue.index);
1203 }
1204 }
1205 return -1;
1206}
1207
Adam Lesinski4bf58102014-11-03 11:21:19 -08001208const char16_t* ResXMLParser::getAttributeStringValue(size_t idx, size_t* outLen) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209{
1210 int32_t id = getAttributeValueStringID(idx);
1211 //XML_NOISY(printf("getAttributeValue 0x%x=0x%x\n", idx, id));
1212 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1213}
1214
1215int32_t ResXMLParser::getAttributeDataType(size_t idx) const
1216{
1217 if (mEventCode == START_TAG) {
1218 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1219 if (idx < dtohs(tag->attributeCount)) {
1220 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1221 (((const uint8_t*)tag)
1222 + dtohs(tag->attributeStart)
1223 + (dtohs(tag->attributeSize)*idx));
Adam Lesinskide898ff2014-01-29 18:20:45 -08001224 uint8_t type = attr->typedValue.dataType;
1225 if (type != Res_value::TYPE_DYNAMIC_REFERENCE) {
1226 return type;
1227 }
1228
1229 // This is a dynamic reference. We adjust those references
1230 // to regular references at this level, so lie to the caller.
1231 return Res_value::TYPE_REFERENCE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 }
1233 }
1234 return Res_value::TYPE_NULL;
1235}
1236
1237int32_t ResXMLParser::getAttributeData(size_t idx) const
1238{
1239 if (mEventCode == START_TAG) {
1240 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1241 if (idx < dtohs(tag->attributeCount)) {
1242 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1243 (((const uint8_t*)tag)
1244 + dtohs(tag->attributeStart)
1245 + (dtohs(tag->attributeSize)*idx));
Adam Lesinskide898ff2014-01-29 18:20:45 -08001246 if (attr->typedValue.dataType != Res_value::TYPE_DYNAMIC_REFERENCE ||
1247 mTree.mDynamicRefTable == NULL) {
1248 return dtohl(attr->typedValue.data);
1249 }
1250
1251 uint32_t data = dtohl(attr->typedValue.data);
1252 if (mTree.mDynamicRefTable->lookupResourceId(&data) == NO_ERROR) {
1253 return data;
1254 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 }
1256 }
1257 return 0;
1258}
1259
1260ssize_t ResXMLParser::getAttributeValue(size_t idx, Res_value* outValue) const
1261{
1262 if (mEventCode == START_TAG) {
1263 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1264 if (idx < dtohs(tag->attributeCount)) {
1265 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1266 (((const uint8_t*)tag)
1267 + dtohs(tag->attributeStart)
1268 + (dtohs(tag->attributeSize)*idx));
1269 outValue->copyFrom_dtoh(attr->typedValue);
Adam Lesinskide898ff2014-01-29 18:20:45 -08001270 if (mTree.mDynamicRefTable != NULL &&
1271 mTree.mDynamicRefTable->lookupResourceValue(outValue) != NO_ERROR) {
1272 return BAD_TYPE;
1273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 return sizeof(Res_value);
1275 }
1276 }
1277 return BAD_TYPE;
1278}
1279
1280ssize_t ResXMLParser::indexOfAttribute(const char* ns, const char* attr) const
1281{
1282 String16 nsStr(ns != NULL ? ns : "");
1283 String16 attrStr(attr);
1284 return indexOfAttribute(ns ? nsStr.string() : NULL, ns ? nsStr.size() : 0,
1285 attrStr.string(), attrStr.size());
1286}
1287
1288ssize_t ResXMLParser::indexOfAttribute(const char16_t* ns, size_t nsLen,
1289 const char16_t* attr, size_t attrLen) const
1290{
1291 if (mEventCode == START_TAG) {
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07001292 if (attr == NULL) {
1293 return NAME_NOT_FOUND;
1294 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 const size_t N = getAttributeCount();
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07001296 if (mTree.mStrings.isUTF8()) {
1297 String8 ns8, attr8;
1298 if (ns != NULL) {
1299 ns8 = String8(ns, nsLen);
1300 }
1301 attr8 = String8(attr, attrLen);
1302 STRING_POOL_NOISY(ALOGI("indexOfAttribute UTF8 %s (%d) / %s (%d)", ns8.string(), nsLen,
1303 attr8.string(), attrLen));
1304 for (size_t i=0; i<N; i++) {
1305 size_t curNsLen = 0, curAttrLen = 0;
1306 const char* curNs = getAttributeNamespace8(i, &curNsLen);
1307 const char* curAttr = getAttributeName8(i, &curAttrLen);
1308 STRING_POOL_NOISY(ALOGI(" curNs=%s (%d), curAttr=%s (%d)", curNs, curNsLen,
1309 curAttr, curAttrLen));
1310 if (curAttr != NULL && curNsLen == nsLen && curAttrLen == attrLen
1311 && memcmp(attr8.string(), curAttr, attrLen) == 0) {
1312 if (ns == NULL) {
1313 if (curNs == NULL) {
1314 STRING_POOL_NOISY(ALOGI(" FOUND!"));
1315 return i;
1316 }
1317 } else if (curNs != NULL) {
1318 //printf(" --> ns=%s, curNs=%s\n",
1319 // String8(ns).string(), String8(curNs).string());
1320 if (memcmp(ns8.string(), curNs, nsLen) == 0) {
1321 STRING_POOL_NOISY(ALOGI(" FOUND!"));
1322 return i;
1323 }
1324 }
1325 }
1326 }
1327 } else {
1328 STRING_POOL_NOISY(ALOGI("indexOfAttribute UTF16 %s (%d) / %s (%d)",
1329 String8(ns, nsLen).string(), nsLen,
1330 String8(attr, attrLen).string(), attrLen));
1331 for (size_t i=0; i<N; i++) {
1332 size_t curNsLen = 0, curAttrLen = 0;
1333 const char16_t* curNs = getAttributeNamespace(i, &curNsLen);
1334 const char16_t* curAttr = getAttributeName(i, &curAttrLen);
1335 STRING_POOL_NOISY(ALOGI(" curNs=%s (%d), curAttr=%s (%d)",
1336 String8(curNs, curNsLen).string(), curNsLen,
1337 String8(curAttr, curAttrLen).string(), curAttrLen));
1338 if (curAttr != NULL && curNsLen == nsLen && curAttrLen == attrLen
1339 && (memcmp(attr, curAttr, attrLen*sizeof(char16_t)) == 0)) {
1340 if (ns == NULL) {
1341 if (curNs == NULL) {
1342 STRING_POOL_NOISY(ALOGI(" FOUND!"));
1343 return i;
1344 }
1345 } else if (curNs != NULL) {
1346 //printf(" --> ns=%s, curNs=%s\n",
1347 // String8(ns).string(), String8(curNs).string());
1348 if (memcmp(ns, curNs, nsLen*sizeof(char16_t)) == 0) {
1349 STRING_POOL_NOISY(ALOGI(" FOUND!"));
1350 return i;
1351 }
1352 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001353 }
1354 }
1355 }
1356 }
1357
1358 return NAME_NOT_FOUND;
1359}
1360
1361ssize_t ResXMLParser::indexOfID() const
1362{
1363 if (mEventCode == START_TAG) {
1364 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->idIndex);
1365 if (idx > 0) return (idx-1);
1366 }
1367 return NAME_NOT_FOUND;
1368}
1369
1370ssize_t ResXMLParser::indexOfClass() const
1371{
1372 if (mEventCode == START_TAG) {
1373 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->classIndex);
1374 if (idx > 0) return (idx-1);
1375 }
1376 return NAME_NOT_FOUND;
1377}
1378
1379ssize_t ResXMLParser::indexOfStyle() const
1380{
1381 if (mEventCode == START_TAG) {
1382 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->styleIndex);
1383 if (idx > 0) return (idx-1);
1384 }
1385 return NAME_NOT_FOUND;
1386}
1387
1388ResXMLParser::event_code_t ResXMLParser::nextNode()
1389{
1390 if (mEventCode < 0) {
1391 return mEventCode;
1392 }
1393
1394 do {
1395 const ResXMLTree_node* next = (const ResXMLTree_node*)
1396 (((const uint8_t*)mCurNode) + dtohl(mCurNode->header.size));
Steve Block8564c8d2012-01-05 23:22:43 +00001397 //ALOGW("Next node: prev=%p, next=%p\n", mCurNode, next);
Mark Salyzyn00adb862014-03-19 11:00:06 -07001398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 if (((const uint8_t*)next) >= mTree.mDataEnd) {
1400 mCurNode = NULL;
1401 return (mEventCode=END_DOCUMENT);
1402 }
1403
1404 if (mTree.validateNode(next) != NO_ERROR) {
1405 mCurNode = NULL;
1406 return (mEventCode=BAD_DOCUMENT);
1407 }
1408
1409 mCurNode = next;
1410 const uint16_t headerSize = dtohs(next->header.headerSize);
1411 const uint32_t totalSize = dtohl(next->header.size);
1412 mCurExt = ((const uint8_t*)next) + headerSize;
1413 size_t minExtSize = 0;
1414 event_code_t eventCode = (event_code_t)dtohs(next->header.type);
1415 switch ((mEventCode=eventCode)) {
1416 case RES_XML_START_NAMESPACE_TYPE:
1417 case RES_XML_END_NAMESPACE_TYPE:
1418 minExtSize = sizeof(ResXMLTree_namespaceExt);
1419 break;
1420 case RES_XML_START_ELEMENT_TYPE:
1421 minExtSize = sizeof(ResXMLTree_attrExt);
1422 break;
1423 case RES_XML_END_ELEMENT_TYPE:
1424 minExtSize = sizeof(ResXMLTree_endElementExt);
1425 break;
1426 case RES_XML_CDATA_TYPE:
1427 minExtSize = sizeof(ResXMLTree_cdataExt);
1428 break;
1429 default:
Steve Block8564c8d2012-01-05 23:22:43 +00001430 ALOGW("Unknown XML block: header type %d in node at %d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 (int)dtohs(next->header.type),
1432 (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)));
1433 continue;
1434 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07001435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 if ((totalSize-headerSize) < minExtSize) {
Steve Block8564c8d2012-01-05 23:22:43 +00001437 ALOGW("Bad XML block: header type 0x%x in node at 0x%x has size %d, need %d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 (int)dtohs(next->header.type),
1439 (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)),
1440 (int)(totalSize-headerSize), (int)minExtSize);
1441 return (mEventCode=BAD_DOCUMENT);
1442 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07001443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 //printf("CurNode=%p, CurExt=%p, headerSize=%d, minExtSize=%d\n",
1445 // mCurNode, mCurExt, headerSize, minExtSize);
Mark Salyzyn00adb862014-03-19 11:00:06 -07001446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 return eventCode;
1448 } while (true);
1449}
1450
1451void ResXMLParser::getPosition(ResXMLParser::ResXMLPosition* pos) const
1452{
1453 pos->eventCode = mEventCode;
1454 pos->curNode = mCurNode;
1455 pos->curExt = mCurExt;
1456}
1457
1458void ResXMLParser::setPosition(const ResXMLParser::ResXMLPosition& pos)
1459{
1460 mEventCode = pos.eventCode;
1461 mCurNode = pos.curNode;
1462 mCurExt = pos.curExt;
1463}
1464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465// --------------------------------------------------------------------
1466
1467static volatile int32_t gCount = 0;
1468
Adam Lesinskide898ff2014-01-29 18:20:45 -08001469ResXMLTree::ResXMLTree(const DynamicRefTable* dynamicRefTable)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 : ResXMLParser(*this)
Adam Lesinskide898ff2014-01-29 18:20:45 -08001471 , mDynamicRefTable(dynamicRefTable)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 , mError(NO_INIT), mOwnedData(NULL)
1473{
Steve Block6215d3f2012-01-04 20:05:49 +00001474 //ALOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 restart();
1476}
1477
Adam Lesinskide898ff2014-01-29 18:20:45 -08001478ResXMLTree::ResXMLTree()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 : ResXMLParser(*this)
Adam Lesinskide898ff2014-01-29 18:20:45 -08001480 , mDynamicRefTable(NULL)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 , mError(NO_INIT), mOwnedData(NULL)
1482{
Steve Block6215d3f2012-01-04 20:05:49 +00001483 //ALOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1);
Adam Lesinskide898ff2014-01-29 18:20:45 -08001484 restart();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485}
1486
1487ResXMLTree::~ResXMLTree()
1488{
Steve Block6215d3f2012-01-04 20:05:49 +00001489 //ALOGI("Destroying ResXMLTree in %p #%d\n", this, android_atomic_dec(&gCount)-1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 uninit();
1491}
1492
1493status_t ResXMLTree::setTo(const void* data, size_t size, bool copyData)
1494{
1495 uninit();
1496 mEventCode = START_DOCUMENT;
1497
Kenny Root32d6aef2012-10-10 10:23:47 -07001498 if (!data || !size) {
1499 return (mError=BAD_TYPE);
1500 }
1501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 if (copyData) {
1503 mOwnedData = malloc(size);
1504 if (mOwnedData == NULL) {
1505 return (mError=NO_MEMORY);
1506 }
1507 memcpy(mOwnedData, data, size);
1508 data = mOwnedData;
1509 }
1510
1511 mHeader = (const ResXMLTree_header*)data;
1512 mSize = dtohl(mHeader->header.size);
1513 if (dtohs(mHeader->header.headerSize) > mSize || mSize > size) {
Steve Block8564c8d2012-01-05 23:22:43 +00001514 ALOGW("Bad XML block: header size %d or total size %d is larger than data size %d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 (int)dtohs(mHeader->header.headerSize),
1516 (int)dtohl(mHeader->header.size), (int)size);
1517 mError = BAD_TYPE;
1518 restart();
1519 return mError;
1520 }
1521 mDataEnd = ((const uint8_t*)mHeader) + mSize;
1522
1523 mStrings.uninit();
1524 mRootNode = NULL;
1525 mResIds = NULL;
1526 mNumResIds = 0;
1527
1528 // First look for a couple interesting chunks: the string block
1529 // and first XML node.
1530 const ResChunk_header* chunk =
1531 (const ResChunk_header*)(((const uint8_t*)mHeader) + dtohs(mHeader->header.headerSize));
1532 const ResChunk_header* lastChunk = chunk;
1533 while (((const uint8_t*)chunk) < (mDataEnd-sizeof(ResChunk_header)) &&
1534 ((const uint8_t*)chunk) < (mDataEnd-dtohl(chunk->size))) {
1535 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), mDataEnd, "XML");
1536 if (err != NO_ERROR) {
1537 mError = err;
1538 goto done;
1539 }
1540 const uint16_t type = dtohs(chunk->type);
1541 const size_t size = dtohl(chunk->size);
1542 XML_NOISY(printf("Scanning @ %p: type=0x%x, size=0x%x\n",
1543 (void*)(((uint32_t)chunk)-((uint32_t)mHeader)), type, size));
1544 if (type == RES_STRING_POOL_TYPE) {
1545 mStrings.setTo(chunk, size);
1546 } else if (type == RES_XML_RESOURCE_MAP_TYPE) {
1547 mResIds = (const uint32_t*)
1548 (((const uint8_t*)chunk)+dtohs(chunk->headerSize));
1549 mNumResIds = (dtohl(chunk->size)-dtohs(chunk->headerSize))/sizeof(uint32_t);
1550 } else if (type >= RES_XML_FIRST_CHUNK_TYPE
1551 && type <= RES_XML_LAST_CHUNK_TYPE) {
1552 if (validateNode((const ResXMLTree_node*)chunk) != NO_ERROR) {
1553 mError = BAD_TYPE;
1554 goto done;
1555 }
1556 mCurNode = (const ResXMLTree_node*)lastChunk;
1557 if (nextNode() == BAD_DOCUMENT) {
1558 mError = BAD_TYPE;
1559 goto done;
1560 }
1561 mRootNode = mCurNode;
1562 mRootExt = mCurExt;
1563 mRootCode = mEventCode;
1564 break;
1565 } else {
1566 XML_NOISY(printf("Skipping unknown chunk!\n"));
1567 }
1568 lastChunk = chunk;
1569 chunk = (const ResChunk_header*)
1570 (((const uint8_t*)chunk) + size);
1571 }
1572
1573 if (mRootNode == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001574 ALOGW("Bad XML block: no root element node found\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 mError = BAD_TYPE;
1576 goto done;
1577 }
1578
1579 mError = mStrings.getError();
1580
1581done:
1582 restart();
1583 return mError;
1584}
1585
1586status_t ResXMLTree::getError() const
1587{
1588 return mError;
1589}
1590
1591void ResXMLTree::uninit()
1592{
1593 mError = NO_INIT;
Kenny Root19138462009-12-04 09:38:48 -08001594 mStrings.uninit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 if (mOwnedData) {
1596 free(mOwnedData);
1597 mOwnedData = NULL;
1598 }
1599 restart();
1600}
1601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602status_t ResXMLTree::validateNode(const ResXMLTree_node* node) const
1603{
1604 const uint16_t eventCode = dtohs(node->header.type);
1605
1606 status_t err = validate_chunk(
1607 &node->header, sizeof(ResXMLTree_node),
1608 mDataEnd, "ResXMLTree_node");
1609
1610 if (err >= NO_ERROR) {
1611 // Only perform additional validation on START nodes
1612 if (eventCode != RES_XML_START_ELEMENT_TYPE) {
1613 return NO_ERROR;
1614 }
1615
1616 const uint16_t headerSize = dtohs(node->header.headerSize);
1617 const uint32_t size = dtohl(node->header.size);
1618 const ResXMLTree_attrExt* attrExt = (const ResXMLTree_attrExt*)
1619 (((const uint8_t*)node) + headerSize);
1620 // check for sensical values pulled out of the stream so far...
1621 if ((size >= headerSize + sizeof(ResXMLTree_attrExt))
1622 && ((void*)attrExt > (void*)node)) {
1623 const size_t attrSize = ((size_t)dtohs(attrExt->attributeSize))
1624 * dtohs(attrExt->attributeCount);
1625 if ((dtohs(attrExt->attributeStart)+attrSize) <= (size-headerSize)) {
1626 return NO_ERROR;
1627 }
Steve Block8564c8d2012-01-05 23:22:43 +00001628 ALOGW("Bad XML block: node attributes use 0x%x bytes, only have 0x%x bytes\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629 (unsigned int)(dtohs(attrExt->attributeStart)+attrSize),
1630 (unsigned int)(size-headerSize));
1631 }
1632 else {
Steve Block8564c8d2012-01-05 23:22:43 +00001633 ALOGW("Bad XML start block: node header size 0x%x, size 0x%x\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 (unsigned int)headerSize, (unsigned int)size);
1635 }
1636 return BAD_TYPE;
1637 }
1638
1639 return err;
1640
1641#if 0
1642 const bool isStart = dtohs(node->header.type) == RES_XML_START_ELEMENT_TYPE;
1643
1644 const uint16_t headerSize = dtohs(node->header.headerSize);
1645 const uint32_t size = dtohl(node->header.size);
1646
1647 if (headerSize >= (isStart ? sizeof(ResXMLTree_attrNode) : sizeof(ResXMLTree_node))) {
1648 if (size >= headerSize) {
1649 if (((const uint8_t*)node) <= (mDataEnd-size)) {
1650 if (!isStart) {
1651 return NO_ERROR;
1652 }
1653 if ((((size_t)dtohs(node->attributeSize))*dtohs(node->attributeCount))
1654 <= (size-headerSize)) {
1655 return NO_ERROR;
1656 }
Steve Block8564c8d2012-01-05 23:22:43 +00001657 ALOGW("Bad XML block: node attributes use 0x%x bytes, only have 0x%x bytes\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 ((int)dtohs(node->attributeSize))*dtohs(node->attributeCount),
1659 (int)(size-headerSize));
1660 return BAD_TYPE;
1661 }
Steve Block8564c8d2012-01-05 23:22:43 +00001662 ALOGW("Bad XML block: node at 0x%x extends beyond data end 0x%x\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)), (int)mSize);
1664 return BAD_TYPE;
1665 }
Steve Block8564c8d2012-01-05 23:22:43 +00001666 ALOGW("Bad XML block: node at 0x%x header size 0x%x smaller than total size 0x%x\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)),
1668 (int)headerSize, (int)size);
1669 return BAD_TYPE;
1670 }
Steve Block8564c8d2012-01-05 23:22:43 +00001671 ALOGW("Bad XML block: node at 0x%x header size 0x%x too small\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)),
1673 (int)headerSize);
1674 return BAD_TYPE;
1675#endif
1676}
1677
1678// --------------------------------------------------------------------
1679// --------------------------------------------------------------------
1680// --------------------------------------------------------------------
1681
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001682void ResTable_config::copyFromDeviceNoSwap(const ResTable_config& o) {
1683 const size_t size = dtohl(o.size);
1684 if (size >= sizeof(ResTable_config)) {
1685 *this = o;
1686 } else {
1687 memcpy(this, &o, size);
1688 memset(((uint8_t*)this)+size, 0, sizeof(ResTable_config)-size);
1689 }
1690}
1691
Narayan Kamath48620f12014-01-20 13:57:11 +00001692/* static */ size_t unpackLanguageOrRegion(const char in[2], const char base,
1693 char out[4]) {
1694 if (in[0] & 0x80) {
1695 // The high bit is "1", which means this is a packed three letter
1696 // language code.
1697
1698 // The smallest 5 bits of the second char are the first alphabet.
1699 const uint8_t first = in[1] & 0x1f;
1700 // The last three bits of the second char and the first two bits
1701 // of the first char are the second alphabet.
1702 const uint8_t second = ((in[1] & 0xe0) >> 5) + ((in[0] & 0x03) << 3);
1703 // Bits 3 to 7 (inclusive) of the first char are the third alphabet.
1704 const uint8_t third = (in[0] & 0x7c) >> 2;
1705
1706 out[0] = first + base;
1707 out[1] = second + base;
1708 out[2] = third + base;
1709 out[3] = 0;
1710
1711 return 3;
1712 }
1713
1714 if (in[0]) {
1715 memcpy(out, in, 2);
1716 memset(out + 2, 0, 2);
1717 return 2;
1718 }
1719
1720 memset(out, 0, 4);
1721 return 0;
1722}
1723
Narayan Kamath788fa412014-01-21 15:32:36 +00001724/* static */ void packLanguageOrRegion(const char* in, const char base,
Narayan Kamath48620f12014-01-20 13:57:11 +00001725 char out[2]) {
Narayan Kamath788fa412014-01-21 15:32:36 +00001726 if (in[2] == 0 || in[2] == '-') {
Narayan Kamath48620f12014-01-20 13:57:11 +00001727 out[0] = in[0];
1728 out[1] = in[1];
1729 } else {
Narayan Kamathb2975912014-06-30 15:59:39 +01001730 uint8_t first = (in[0] - base) & 0x007f;
1731 uint8_t second = (in[1] - base) & 0x007f;
1732 uint8_t third = (in[2] - base) & 0x007f;
Narayan Kamath48620f12014-01-20 13:57:11 +00001733
1734 out[0] = (0x80 | (third << 2) | (second >> 3));
1735 out[1] = ((second << 5) | first);
1736 }
1737}
1738
1739
Narayan Kamath788fa412014-01-21 15:32:36 +00001740void ResTable_config::packLanguage(const char* language) {
Narayan Kamath48620f12014-01-20 13:57:11 +00001741 packLanguageOrRegion(language, 'a', this->language);
1742}
1743
Narayan Kamath788fa412014-01-21 15:32:36 +00001744void ResTable_config::packRegion(const char* region) {
Narayan Kamath48620f12014-01-20 13:57:11 +00001745 packLanguageOrRegion(region, '0', this->country);
1746}
1747
1748size_t ResTable_config::unpackLanguage(char language[4]) const {
1749 return unpackLanguageOrRegion(this->language, 'a', language);
1750}
1751
1752size_t ResTable_config::unpackRegion(char region[4]) const {
1753 return unpackLanguageOrRegion(this->country, '0', region);
1754}
1755
1756
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001757void ResTable_config::copyFromDtoH(const ResTable_config& o) {
1758 copyFromDeviceNoSwap(o);
1759 size = sizeof(ResTable_config);
1760 mcc = dtohs(mcc);
1761 mnc = dtohs(mnc);
1762 density = dtohs(density);
1763 screenWidth = dtohs(screenWidth);
1764 screenHeight = dtohs(screenHeight);
1765 sdkVersion = dtohs(sdkVersion);
1766 minorVersion = dtohs(minorVersion);
1767 smallestScreenWidthDp = dtohs(smallestScreenWidthDp);
1768 screenWidthDp = dtohs(screenWidthDp);
1769 screenHeightDp = dtohs(screenHeightDp);
1770}
1771
1772void ResTable_config::swapHtoD() {
1773 size = htodl(size);
1774 mcc = htods(mcc);
1775 mnc = htods(mnc);
1776 density = htods(density);
1777 screenWidth = htods(screenWidth);
1778 screenHeight = htods(screenHeight);
1779 sdkVersion = htods(sdkVersion);
1780 minorVersion = htods(minorVersion);
1781 smallestScreenWidthDp = htods(smallestScreenWidthDp);
1782 screenWidthDp = htods(screenWidthDp);
1783 screenHeightDp = htods(screenHeightDp);
1784}
1785
Narayan Kamath48620f12014-01-20 13:57:11 +00001786/* static */ inline int compareLocales(const ResTable_config &l, const ResTable_config &r) {
1787 if (l.locale != r.locale) {
1788 // NOTE: This is the old behaviour with respect to comparison orders.
1789 // The diff value here doesn't make much sense (given our bit packing scheme)
1790 // but it's stable, and that's all we need.
1791 return l.locale - r.locale;
1792 }
1793
1794 // The language & region are equal, so compare the scripts and variants.
1795 int script = memcmp(l.localeScript, r.localeScript, sizeof(l.localeScript));
1796 if (script) {
1797 return script;
1798 }
1799
1800 // The language, region and script are equal, so compare variants.
1801 //
1802 // This should happen very infrequently (if at all.)
1803 return memcmp(l.localeVariant, r.localeVariant, sizeof(l.localeVariant));
1804}
1805
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001806int ResTable_config::compare(const ResTable_config& o) const {
1807 int32_t diff = (int32_t)(imsi - o.imsi);
1808 if (diff != 0) return diff;
Narayan Kamath48620f12014-01-20 13:57:11 +00001809 diff = compareLocales(*this, o);
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001810 if (diff != 0) return diff;
1811 diff = (int32_t)(screenType - o.screenType);
1812 if (diff != 0) return diff;
1813 diff = (int32_t)(input - o.input);
1814 if (diff != 0) return diff;
1815 diff = (int32_t)(screenSize - o.screenSize);
1816 if (diff != 0) return diff;
1817 diff = (int32_t)(version - o.version);
1818 if (diff != 0) return diff;
1819 diff = (int32_t)(screenLayout - o.screenLayout);
1820 if (diff != 0) return diff;
1821 diff = (int32_t)(uiMode - o.uiMode);
1822 if (diff != 0) return diff;
1823 diff = (int32_t)(smallestScreenWidthDp - o.smallestScreenWidthDp);
1824 if (diff != 0) return diff;
1825 diff = (int32_t)(screenSizeDp - o.screenSizeDp);
1826 return (int)diff;
1827}
1828
1829int ResTable_config::compareLogical(const ResTable_config& o) const {
1830 if (mcc != o.mcc) {
1831 return mcc < o.mcc ? -1 : 1;
1832 }
1833 if (mnc != o.mnc) {
1834 return mnc < o.mnc ? -1 : 1;
1835 }
Narayan Kamath48620f12014-01-20 13:57:11 +00001836
1837 int diff = compareLocales(*this, o);
1838 if (diff < 0) {
1839 return -1;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001840 }
Narayan Kamath48620f12014-01-20 13:57:11 +00001841 if (diff > 0) {
1842 return 1;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001843 }
Narayan Kamath48620f12014-01-20 13:57:11 +00001844
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07001845 if ((screenLayout & MASK_LAYOUTDIR) != (o.screenLayout & MASK_LAYOUTDIR)) {
1846 return (screenLayout & MASK_LAYOUTDIR) < (o.screenLayout & MASK_LAYOUTDIR) ? -1 : 1;
1847 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001848 if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
1849 return smallestScreenWidthDp < o.smallestScreenWidthDp ? -1 : 1;
1850 }
1851 if (screenWidthDp != o.screenWidthDp) {
1852 return screenWidthDp < o.screenWidthDp ? -1 : 1;
1853 }
1854 if (screenHeightDp != o.screenHeightDp) {
1855 return screenHeightDp < o.screenHeightDp ? -1 : 1;
1856 }
1857 if (screenWidth != o.screenWidth) {
1858 return screenWidth < o.screenWidth ? -1 : 1;
1859 }
1860 if (screenHeight != o.screenHeight) {
1861 return screenHeight < o.screenHeight ? -1 : 1;
1862 }
1863 if (density != o.density) {
1864 return density < o.density ? -1 : 1;
1865 }
1866 if (orientation != o.orientation) {
1867 return orientation < o.orientation ? -1 : 1;
1868 }
1869 if (touchscreen != o.touchscreen) {
1870 return touchscreen < o.touchscreen ? -1 : 1;
1871 }
1872 if (input != o.input) {
1873 return input < o.input ? -1 : 1;
1874 }
1875 if (screenLayout != o.screenLayout) {
1876 return screenLayout < o.screenLayout ? -1 : 1;
1877 }
1878 if (uiMode != o.uiMode) {
1879 return uiMode < o.uiMode ? -1 : 1;
1880 }
1881 if (version != o.version) {
1882 return version < o.version ? -1 : 1;
1883 }
1884 return 0;
1885}
1886
1887int ResTable_config::diff(const ResTable_config& o) const {
1888 int diffs = 0;
1889 if (mcc != o.mcc) diffs |= CONFIG_MCC;
1890 if (mnc != o.mnc) diffs |= CONFIG_MNC;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001891 if (orientation != o.orientation) diffs |= CONFIG_ORIENTATION;
1892 if (density != o.density) diffs |= CONFIG_DENSITY;
1893 if (touchscreen != o.touchscreen) diffs |= CONFIG_TOUCHSCREEN;
1894 if (((inputFlags^o.inputFlags)&(MASK_KEYSHIDDEN|MASK_NAVHIDDEN)) != 0)
1895 diffs |= CONFIG_KEYBOARD_HIDDEN;
1896 if (keyboard != o.keyboard) diffs |= CONFIG_KEYBOARD;
1897 if (navigation != o.navigation) diffs |= CONFIG_NAVIGATION;
1898 if (screenSize != o.screenSize) diffs |= CONFIG_SCREEN_SIZE;
1899 if (version != o.version) diffs |= CONFIG_VERSION;
Fabrice Di Meglio35099352012-12-12 11:52:03 -08001900 if ((screenLayout & MASK_LAYOUTDIR) != (o.screenLayout & MASK_LAYOUTDIR)) diffs |= CONFIG_LAYOUTDIR;
1901 if ((screenLayout & ~MASK_LAYOUTDIR) != (o.screenLayout & ~MASK_LAYOUTDIR)) diffs |= CONFIG_SCREEN_LAYOUT;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001902 if (uiMode != o.uiMode) diffs |= CONFIG_UI_MODE;
1903 if (smallestScreenWidthDp != o.smallestScreenWidthDp) diffs |= CONFIG_SMALLEST_SCREEN_SIZE;
1904 if (screenSizeDp != o.screenSizeDp) diffs |= CONFIG_SCREEN_SIZE;
Narayan Kamath48620f12014-01-20 13:57:11 +00001905
1906 const int diff = compareLocales(*this, o);
1907 if (diff) diffs |= CONFIG_LOCALE;
1908
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001909 return diffs;
1910}
1911
Narayan Kamath48620f12014-01-20 13:57:11 +00001912int ResTable_config::isLocaleMoreSpecificThan(const ResTable_config& o) const {
1913 if (locale || o.locale) {
1914 if (language[0] != o.language[0]) {
1915 if (!language[0]) return -1;
1916 if (!o.language[0]) return 1;
1917 }
1918
1919 if (country[0] != o.country[0]) {
1920 if (!country[0]) return -1;
1921 if (!o.country[0]) return 1;
1922 }
1923 }
1924
1925 // There isn't a well specified "importance" order between variants and
1926 // scripts. We can't easily tell whether, say "en-Latn-US" is more or less
1927 // specific than "en-US-POSIX".
1928 //
1929 // We therefore arbitrarily decide to give priority to variants over
1930 // scripts since it seems more useful to do so. We will consider
1931 // "en-US-POSIX" to be more specific than "en-Latn-US".
1932
1933 const int score = ((localeScript[0] != 0) ? 1 : 0) +
1934 ((localeVariant[0] != 0) ? 2 : 0);
1935
1936 const int oScore = ((o.localeScript[0] != 0) ? 1 : 0) +
1937 ((o.localeVariant[0] != 0) ? 2 : 0);
1938
1939 return score - oScore;
1940
1941}
1942
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001943bool ResTable_config::isMoreSpecificThan(const ResTable_config& o) const {
1944 // The order of the following tests defines the importance of one
1945 // configuration parameter over another. Those tests first are more
1946 // important, trumping any values in those following them.
1947 if (imsi || o.imsi) {
1948 if (mcc != o.mcc) {
1949 if (!mcc) return false;
1950 if (!o.mcc) return true;
1951 }
1952
1953 if (mnc != o.mnc) {
1954 if (!mnc) return false;
1955 if (!o.mnc) return true;
1956 }
1957 }
1958
1959 if (locale || o.locale) {
Narayan Kamath48620f12014-01-20 13:57:11 +00001960 const int diff = isLocaleMoreSpecificThan(o);
1961 if (diff < 0) {
1962 return false;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001963 }
1964
Narayan Kamath48620f12014-01-20 13:57:11 +00001965 if (diff > 0) {
1966 return true;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001967 }
1968 }
1969
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07001970 if (screenLayout || o.screenLayout) {
1971 if (((screenLayout^o.screenLayout) & MASK_LAYOUTDIR) != 0) {
1972 if (!(screenLayout & MASK_LAYOUTDIR)) return false;
1973 if (!(o.screenLayout & MASK_LAYOUTDIR)) return true;
1974 }
1975 }
1976
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001977 if (smallestScreenWidthDp || o.smallestScreenWidthDp) {
1978 if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
1979 if (!smallestScreenWidthDp) return false;
1980 if (!o.smallestScreenWidthDp) return true;
1981 }
1982 }
1983
1984 if (screenSizeDp || o.screenSizeDp) {
1985 if (screenWidthDp != o.screenWidthDp) {
1986 if (!screenWidthDp) return false;
1987 if (!o.screenWidthDp) return true;
1988 }
1989
1990 if (screenHeightDp != o.screenHeightDp) {
1991 if (!screenHeightDp) return false;
1992 if (!o.screenHeightDp) return true;
1993 }
1994 }
1995
1996 if (screenLayout || o.screenLayout) {
1997 if (((screenLayout^o.screenLayout) & MASK_SCREENSIZE) != 0) {
1998 if (!(screenLayout & MASK_SCREENSIZE)) return false;
1999 if (!(o.screenLayout & MASK_SCREENSIZE)) return true;
2000 }
2001 if (((screenLayout^o.screenLayout) & MASK_SCREENLONG) != 0) {
2002 if (!(screenLayout & MASK_SCREENLONG)) return false;
2003 if (!(o.screenLayout & MASK_SCREENLONG)) return true;
2004 }
2005 }
2006
2007 if (orientation != o.orientation) {
2008 if (!orientation) return false;
2009 if (!o.orientation) return true;
2010 }
2011
2012 if (uiMode || o.uiMode) {
2013 if (((uiMode^o.uiMode) & MASK_UI_MODE_TYPE) != 0) {
2014 if (!(uiMode & MASK_UI_MODE_TYPE)) return false;
2015 if (!(o.uiMode & MASK_UI_MODE_TYPE)) return true;
2016 }
2017 if (((uiMode^o.uiMode) & MASK_UI_MODE_NIGHT) != 0) {
2018 if (!(uiMode & MASK_UI_MODE_NIGHT)) return false;
2019 if (!(o.uiMode & MASK_UI_MODE_NIGHT)) return true;
2020 }
2021 }
2022
2023 // density is never 'more specific'
2024 // as the default just equals 160
2025
2026 if (touchscreen != o.touchscreen) {
2027 if (!touchscreen) return false;
2028 if (!o.touchscreen) return true;
2029 }
2030
2031 if (input || o.input) {
2032 if (((inputFlags^o.inputFlags) & MASK_KEYSHIDDEN) != 0) {
2033 if (!(inputFlags & MASK_KEYSHIDDEN)) return false;
2034 if (!(o.inputFlags & MASK_KEYSHIDDEN)) return true;
2035 }
2036
2037 if (((inputFlags^o.inputFlags) & MASK_NAVHIDDEN) != 0) {
2038 if (!(inputFlags & MASK_NAVHIDDEN)) return false;
2039 if (!(o.inputFlags & MASK_NAVHIDDEN)) return true;
2040 }
2041
2042 if (keyboard != o.keyboard) {
2043 if (!keyboard) return false;
2044 if (!o.keyboard) return true;
2045 }
2046
2047 if (navigation != o.navigation) {
2048 if (!navigation) return false;
2049 if (!o.navigation) return true;
2050 }
2051 }
2052
2053 if (screenSize || o.screenSize) {
2054 if (screenWidth != o.screenWidth) {
2055 if (!screenWidth) return false;
2056 if (!o.screenWidth) return true;
2057 }
2058
2059 if (screenHeight != o.screenHeight) {
2060 if (!screenHeight) return false;
2061 if (!o.screenHeight) return true;
2062 }
2063 }
2064
2065 if (version || o.version) {
2066 if (sdkVersion != o.sdkVersion) {
2067 if (!sdkVersion) return false;
2068 if (!o.sdkVersion) return true;
2069 }
2070
2071 if (minorVersion != o.minorVersion) {
2072 if (!minorVersion) return false;
2073 if (!o.minorVersion) return true;
2074 }
2075 }
2076 return false;
2077}
2078
2079bool ResTable_config::isBetterThan(const ResTable_config& o,
2080 const ResTable_config* requested) const {
2081 if (requested) {
2082 if (imsi || o.imsi) {
2083 if ((mcc != o.mcc) && requested->mcc) {
2084 return (mcc);
2085 }
2086
2087 if ((mnc != o.mnc) && requested->mnc) {
2088 return (mnc);
2089 }
2090 }
2091
2092 if (locale || o.locale) {
2093 if ((language[0] != o.language[0]) && requested->language[0]) {
2094 return (language[0]);
2095 }
2096
2097 if ((country[0] != o.country[0]) && requested->country[0]) {
2098 return (country[0]);
2099 }
2100 }
2101
Narayan Kamath48620f12014-01-20 13:57:11 +00002102 if (localeScript[0] || o.localeScript[0]) {
2103 if (localeScript[0] != o.localeScript[0] && requested->localeScript[0]) {
2104 return localeScript[0];
2105 }
2106 }
2107
2108 if (localeVariant[0] || o.localeVariant[0]) {
2109 if (localeVariant[0] != o.localeVariant[0] && requested->localeVariant[0]) {
2110 return localeVariant[0];
2111 }
2112 }
2113
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07002114 if (screenLayout || o.screenLayout) {
2115 if (((screenLayout^o.screenLayout) & MASK_LAYOUTDIR) != 0
2116 && (requested->screenLayout & MASK_LAYOUTDIR)) {
2117 int myLayoutDir = screenLayout & MASK_LAYOUTDIR;
2118 int oLayoutDir = o.screenLayout & MASK_LAYOUTDIR;
2119 return (myLayoutDir > oLayoutDir);
2120 }
2121 }
2122
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002123 if (smallestScreenWidthDp || o.smallestScreenWidthDp) {
2124 // The configuration closest to the actual size is best.
2125 // We assume that larger configs have already been filtered
2126 // out at this point. That means we just want the largest one.
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08002127 if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
2128 return smallestScreenWidthDp > o.smallestScreenWidthDp;
2129 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002130 }
2131
2132 if (screenSizeDp || o.screenSizeDp) {
2133 // "Better" is based on the sum of the difference between both
2134 // width and height from the requested dimensions. We are
2135 // assuming the invalid configs (with smaller dimens) have
2136 // already been filtered. Note that if a particular dimension
2137 // is unspecified, we will end up with a large value (the
2138 // difference between 0 and the requested dimension), which is
2139 // good since we will prefer a config that has specified a
2140 // dimension value.
2141 int myDelta = 0, otherDelta = 0;
2142 if (requested->screenWidthDp) {
2143 myDelta += requested->screenWidthDp - screenWidthDp;
2144 otherDelta += requested->screenWidthDp - o.screenWidthDp;
2145 }
2146 if (requested->screenHeightDp) {
2147 myDelta += requested->screenHeightDp - screenHeightDp;
2148 otherDelta += requested->screenHeightDp - o.screenHeightDp;
2149 }
2150 //ALOGI("Comparing this %dx%d to other %dx%d in %dx%d: myDelta=%d otherDelta=%d",
2151 // screenWidthDp, screenHeightDp, o.screenWidthDp, o.screenHeightDp,
2152 // requested->screenWidthDp, requested->screenHeightDp, myDelta, otherDelta);
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08002153 if (myDelta != otherDelta) {
2154 return myDelta < otherDelta;
2155 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002156 }
2157
2158 if (screenLayout || o.screenLayout) {
2159 if (((screenLayout^o.screenLayout) & MASK_SCREENSIZE) != 0
2160 && (requested->screenLayout & MASK_SCREENSIZE)) {
2161 // A little backwards compatibility here: undefined is
2162 // considered equivalent to normal. But only if the
2163 // requested size is at least normal; otherwise, small
2164 // is better than the default.
2165 int mySL = (screenLayout & MASK_SCREENSIZE);
2166 int oSL = (o.screenLayout & MASK_SCREENSIZE);
2167 int fixedMySL = mySL;
2168 int fixedOSL = oSL;
2169 if ((requested->screenLayout & MASK_SCREENSIZE) >= SCREENSIZE_NORMAL) {
2170 if (fixedMySL == 0) fixedMySL = SCREENSIZE_NORMAL;
2171 if (fixedOSL == 0) fixedOSL = SCREENSIZE_NORMAL;
2172 }
2173 // For screen size, the best match is the one that is
2174 // closest to the requested screen size, but not over
2175 // (the not over part is dealt with in match() below).
2176 if (fixedMySL == fixedOSL) {
2177 // If the two are the same, but 'this' is actually
2178 // undefined, then the other is really a better match.
2179 if (mySL == 0) return false;
2180 return true;
2181 }
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08002182 if (fixedMySL != fixedOSL) {
2183 return fixedMySL > fixedOSL;
2184 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002185 }
2186 if (((screenLayout^o.screenLayout) & MASK_SCREENLONG) != 0
2187 && (requested->screenLayout & MASK_SCREENLONG)) {
2188 return (screenLayout & MASK_SCREENLONG);
2189 }
2190 }
2191
2192 if ((orientation != o.orientation) && requested->orientation) {
2193 return (orientation);
2194 }
2195
2196 if (uiMode || o.uiMode) {
2197 if (((uiMode^o.uiMode) & MASK_UI_MODE_TYPE) != 0
2198 && (requested->uiMode & MASK_UI_MODE_TYPE)) {
2199 return (uiMode & MASK_UI_MODE_TYPE);
2200 }
2201 if (((uiMode^o.uiMode) & MASK_UI_MODE_NIGHT) != 0
2202 && (requested->uiMode & MASK_UI_MODE_NIGHT)) {
2203 return (uiMode & MASK_UI_MODE_NIGHT);
2204 }
2205 }
2206
2207 if (screenType || o.screenType) {
2208 if (density != o.density) {
Adam Lesinski31245b42014-08-22 19:10:56 -07002209 // Use the system default density (DENSITY_MEDIUM, 160dpi) if none specified.
2210 const int thisDensity = density ? density : int(ResTable_config::DENSITY_MEDIUM);
2211 const int otherDensity = o.density ? o.density : int(ResTable_config::DENSITY_MEDIUM);
2212
2213 // We always prefer DENSITY_ANY over scaling a density bucket.
2214 if (thisDensity == ResTable_config::DENSITY_ANY) {
2215 return true;
2216 } else if (otherDensity == ResTable_config::DENSITY_ANY) {
2217 return false;
2218 }
2219
2220 int requestedDensity = requested->density;
2221 if (requested->density == 0 ||
2222 requested->density == ResTable_config::DENSITY_ANY) {
2223 requestedDensity = ResTable_config::DENSITY_MEDIUM;
2224 }
2225
2226 // DENSITY_ANY is now dealt with. We should look to
2227 // pick a density bucket and potentially scale it.
2228 // Any density is potentially useful
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002229 // because the system will scale it. Scaling down
2230 // is generally better than scaling up.
Adam Lesinski31245b42014-08-22 19:10:56 -07002231 int h = thisDensity;
2232 int l = otherDensity;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002233 bool bImBigger = true;
2234 if (l > h) {
2235 int t = h;
2236 h = l;
2237 l = t;
2238 bImBigger = false;
2239 }
2240
Adam Lesinski31245b42014-08-22 19:10:56 -07002241 if (requestedDensity >= h) {
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002242 // requested value higher than both l and h, give h
2243 return bImBigger;
2244 }
Adam Lesinski31245b42014-08-22 19:10:56 -07002245 if (l >= requestedDensity) {
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002246 // requested value lower than both l and h, give l
2247 return !bImBigger;
2248 }
2249 // saying that scaling down is 2x better than up
Adam Lesinski31245b42014-08-22 19:10:56 -07002250 if (((2 * l) - requestedDensity) * h > requestedDensity * requestedDensity) {
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002251 return !bImBigger;
2252 } else {
2253 return bImBigger;
2254 }
2255 }
2256
2257 if ((touchscreen != o.touchscreen) && requested->touchscreen) {
2258 return (touchscreen);
2259 }
2260 }
2261
2262 if (input || o.input) {
2263 const int keysHidden = inputFlags & MASK_KEYSHIDDEN;
2264 const int oKeysHidden = o.inputFlags & MASK_KEYSHIDDEN;
2265 if (keysHidden != oKeysHidden) {
2266 const int reqKeysHidden =
2267 requested->inputFlags & MASK_KEYSHIDDEN;
2268 if (reqKeysHidden) {
2269
2270 if (!keysHidden) return false;
2271 if (!oKeysHidden) return true;
2272 // For compatibility, we count KEYSHIDDEN_NO as being
2273 // the same as KEYSHIDDEN_SOFT. Here we disambiguate
2274 // these by making an exact match more specific.
2275 if (reqKeysHidden == keysHidden) return true;
2276 if (reqKeysHidden == oKeysHidden) return false;
2277 }
2278 }
2279
2280 const int navHidden = inputFlags & MASK_NAVHIDDEN;
2281 const int oNavHidden = o.inputFlags & MASK_NAVHIDDEN;
2282 if (navHidden != oNavHidden) {
2283 const int reqNavHidden =
2284 requested->inputFlags & MASK_NAVHIDDEN;
2285 if (reqNavHidden) {
2286
2287 if (!navHidden) return false;
2288 if (!oNavHidden) return true;
2289 }
2290 }
2291
2292 if ((keyboard != o.keyboard) && requested->keyboard) {
2293 return (keyboard);
2294 }
2295
2296 if ((navigation != o.navigation) && requested->navigation) {
2297 return (navigation);
2298 }
2299 }
2300
2301 if (screenSize || o.screenSize) {
2302 // "Better" is based on the sum of the difference between both
2303 // width and height from the requested dimensions. We are
2304 // assuming the invalid configs (with smaller sizes) have
2305 // already been filtered. Note that if a particular dimension
2306 // is unspecified, we will end up with a large value (the
2307 // difference between 0 and the requested dimension), which is
2308 // good since we will prefer a config that has specified a
2309 // size value.
2310 int myDelta = 0, otherDelta = 0;
2311 if (requested->screenWidth) {
2312 myDelta += requested->screenWidth - screenWidth;
2313 otherDelta += requested->screenWidth - o.screenWidth;
2314 }
2315 if (requested->screenHeight) {
2316 myDelta += requested->screenHeight - screenHeight;
2317 otherDelta += requested->screenHeight - o.screenHeight;
2318 }
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08002319 if (myDelta != otherDelta) {
2320 return myDelta < otherDelta;
2321 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002322 }
2323
2324 if (version || o.version) {
2325 if ((sdkVersion != o.sdkVersion) && requested->sdkVersion) {
2326 return (sdkVersion > o.sdkVersion);
2327 }
2328
2329 if ((minorVersion != o.minorVersion) &&
2330 requested->minorVersion) {
2331 return (minorVersion);
2332 }
2333 }
2334
2335 return false;
2336 }
2337 return isMoreSpecificThan(o);
2338}
2339
2340bool ResTable_config::match(const ResTable_config& settings) const {
2341 if (imsi != 0) {
2342 if (mcc != 0 && mcc != settings.mcc) {
2343 return false;
2344 }
2345 if (mnc != 0 && mnc != settings.mnc) {
2346 return false;
2347 }
2348 }
2349 if (locale != 0) {
Narayan Kamath48620f12014-01-20 13:57:11 +00002350 // Don't consider the script & variants when deciding matches.
2351 //
2352 // If we two configs differ only in their script or language, they
2353 // can be weeded out in the isMoreSpecificThan test.
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002354 if (language[0] != 0
2355 && (language[0] != settings.language[0]
2356 || language[1] != settings.language[1])) {
2357 return false;
2358 }
Narayan Kamath48620f12014-01-20 13:57:11 +00002359
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002360 if (country[0] != 0
2361 && (country[0] != settings.country[0]
2362 || country[1] != settings.country[1])) {
2363 return false;
2364 }
2365 }
Narayan Kamath48620f12014-01-20 13:57:11 +00002366
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002367 if (screenConfig != 0) {
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07002368 const int layoutDir = screenLayout&MASK_LAYOUTDIR;
2369 const int setLayoutDir = settings.screenLayout&MASK_LAYOUTDIR;
2370 if (layoutDir != 0 && layoutDir != setLayoutDir) {
2371 return false;
2372 }
2373
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002374 const int screenSize = screenLayout&MASK_SCREENSIZE;
2375 const int setScreenSize = settings.screenLayout&MASK_SCREENSIZE;
2376 // Any screen sizes for larger screens than the setting do not
2377 // match.
2378 if (screenSize != 0 && screenSize > setScreenSize) {
2379 return false;
2380 }
2381
2382 const int screenLong = screenLayout&MASK_SCREENLONG;
2383 const int setScreenLong = settings.screenLayout&MASK_SCREENLONG;
2384 if (screenLong != 0 && screenLong != setScreenLong) {
2385 return false;
2386 }
2387
2388 const int uiModeType = uiMode&MASK_UI_MODE_TYPE;
2389 const int setUiModeType = settings.uiMode&MASK_UI_MODE_TYPE;
2390 if (uiModeType != 0 && uiModeType != setUiModeType) {
2391 return false;
2392 }
2393
2394 const int uiModeNight = uiMode&MASK_UI_MODE_NIGHT;
2395 const int setUiModeNight = settings.uiMode&MASK_UI_MODE_NIGHT;
2396 if (uiModeNight != 0 && uiModeNight != setUiModeNight) {
2397 return false;
2398 }
2399
2400 if (smallestScreenWidthDp != 0
2401 && smallestScreenWidthDp > settings.smallestScreenWidthDp) {
2402 return false;
2403 }
2404 }
2405 if (screenSizeDp != 0) {
2406 if (screenWidthDp != 0 && screenWidthDp > settings.screenWidthDp) {
2407 //ALOGI("Filtering out width %d in requested %d", screenWidthDp, settings.screenWidthDp);
2408 return false;
2409 }
2410 if (screenHeightDp != 0 && screenHeightDp > settings.screenHeightDp) {
2411 //ALOGI("Filtering out height %d in requested %d", screenHeightDp, settings.screenHeightDp);
2412 return false;
2413 }
2414 }
2415 if (screenType != 0) {
2416 if (orientation != 0 && orientation != settings.orientation) {
2417 return false;
2418 }
2419 // density always matches - we can scale it. See isBetterThan
2420 if (touchscreen != 0 && touchscreen != settings.touchscreen) {
2421 return false;
2422 }
2423 }
2424 if (input != 0) {
2425 const int keysHidden = inputFlags&MASK_KEYSHIDDEN;
2426 const int setKeysHidden = settings.inputFlags&MASK_KEYSHIDDEN;
2427 if (keysHidden != 0 && keysHidden != setKeysHidden) {
2428 // For compatibility, we count a request for KEYSHIDDEN_NO as also
2429 // matching the more recent KEYSHIDDEN_SOFT. Basically
2430 // KEYSHIDDEN_NO means there is some kind of keyboard available.
2431 //ALOGI("Matching keysHidden: have=%d, config=%d\n", keysHidden, setKeysHidden);
2432 if (keysHidden != KEYSHIDDEN_NO || setKeysHidden != KEYSHIDDEN_SOFT) {
2433 //ALOGI("No match!");
2434 return false;
2435 }
2436 }
2437 const int navHidden = inputFlags&MASK_NAVHIDDEN;
2438 const int setNavHidden = settings.inputFlags&MASK_NAVHIDDEN;
2439 if (navHidden != 0 && navHidden != setNavHidden) {
2440 return false;
2441 }
2442 if (keyboard != 0 && keyboard != settings.keyboard) {
2443 return false;
2444 }
2445 if (navigation != 0 && navigation != settings.navigation) {
2446 return false;
2447 }
2448 }
2449 if (screenSize != 0) {
2450 if (screenWidth != 0 && screenWidth > settings.screenWidth) {
2451 return false;
2452 }
2453 if (screenHeight != 0 && screenHeight > settings.screenHeight) {
2454 return false;
2455 }
2456 }
2457 if (version != 0) {
2458 if (sdkVersion != 0 && sdkVersion > settings.sdkVersion) {
2459 return false;
2460 }
2461 if (minorVersion != 0 && minorVersion != settings.minorVersion) {
2462 return false;
2463 }
2464 }
2465 return true;
2466}
2467
Narayan Kamath788fa412014-01-21 15:32:36 +00002468void ResTable_config::getBcp47Locale(char str[RESTABLE_MAX_LOCALE_LEN]) const {
Narayan Kamath48620f12014-01-20 13:57:11 +00002469 memset(str, 0, RESTABLE_MAX_LOCALE_LEN);
2470
2471 // This represents the "any" locale value, which has traditionally been
2472 // represented by the empty string.
2473 if (!language[0] && !country[0]) {
2474 return;
2475 }
2476
2477 size_t charsWritten = 0;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002478 if (language[0]) {
Narayan Kamath788fa412014-01-21 15:32:36 +00002479 charsWritten += unpackLanguage(str);
Narayan Kamath48620f12014-01-20 13:57:11 +00002480 }
2481
2482 if (localeScript[0]) {
2483 if (charsWritten) {
Narayan Kamath788fa412014-01-21 15:32:36 +00002484 str[charsWritten++] = '-';
Narayan Kamath48620f12014-01-20 13:57:11 +00002485 }
2486 memcpy(str + charsWritten, localeScript, sizeof(localeScript));
Narayan Kamath788fa412014-01-21 15:32:36 +00002487 charsWritten += sizeof(localeScript);
2488 }
2489
2490 if (country[0]) {
2491 if (charsWritten) {
2492 str[charsWritten++] = '-';
2493 }
2494 charsWritten += unpackRegion(str + charsWritten);
Narayan Kamath48620f12014-01-20 13:57:11 +00002495 }
2496
2497 if (localeVariant[0]) {
2498 if (charsWritten) {
Narayan Kamath788fa412014-01-21 15:32:36 +00002499 str[charsWritten++] = '-';
Narayan Kamath48620f12014-01-20 13:57:11 +00002500 }
2501 memcpy(str + charsWritten, localeVariant, sizeof(localeVariant));
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002502 }
2503}
2504
Narayan Kamath788fa412014-01-21 15:32:36 +00002505/* static */ inline bool assignLocaleComponent(ResTable_config* config,
2506 const char* start, size_t size) {
2507
2508 switch (size) {
2509 case 0:
2510 return false;
2511 case 2:
2512 case 3:
2513 config->language[0] ? config->packRegion(start) : config->packLanguage(start);
2514 break;
2515 case 4:
2516 config->localeScript[0] = toupper(start[0]);
2517 for (size_t i = 1; i < 4; ++i) {
2518 config->localeScript[i] = tolower(start[i]);
2519 }
2520 break;
2521 case 5:
2522 case 6:
2523 case 7:
2524 case 8:
2525 for (size_t i = 0; i < size; ++i) {
2526 config->localeVariant[i] = tolower(start[i]);
2527 }
2528 break;
2529 default:
2530 return false;
2531 }
2532
2533 return true;
2534}
2535
2536void ResTable_config::setBcp47Locale(const char* in) {
2537 locale = 0;
2538 memset(localeScript, 0, sizeof(localeScript));
2539 memset(localeVariant, 0, sizeof(localeVariant));
2540
2541 const char* separator = in;
2542 const char* start = in;
2543 while ((separator = strchr(start, '-')) != NULL) {
2544 const size_t size = separator - start;
2545 if (!assignLocaleComponent(this, start, size)) {
2546 fprintf(stderr, "Invalid BCP-47 locale string: %s", in);
2547 }
2548
2549 start = (separator + 1);
2550 }
2551
2552 const size_t size = in + strlen(in) - start;
2553 assignLocaleComponent(this, start, size);
2554}
2555
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002556String8 ResTable_config::toString() const {
2557 String8 res;
2558
2559 if (mcc != 0) {
2560 if (res.size() > 0) res.append("-");
Adam Lesinskifab50872014-04-16 14:40:42 -07002561 res.appendFormat("mcc%d", dtohs(mcc));
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002562 }
2563 if (mnc != 0) {
2564 if (res.size() > 0) res.append("-");
Adam Lesinskifab50872014-04-16 14:40:42 -07002565 res.appendFormat("mnc%d", dtohs(mnc));
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002566 }
Adam Lesinskifab50872014-04-16 14:40:42 -07002567
Narayan Kamath48620f12014-01-20 13:57:11 +00002568 char localeStr[RESTABLE_MAX_LOCALE_LEN];
Narayan Kamath788fa412014-01-21 15:32:36 +00002569 getBcp47Locale(localeStr);
Adam Lesinskifab50872014-04-16 14:40:42 -07002570 if (strlen(localeStr) > 0) {
2571 if (res.size() > 0) res.append("-");
2572 res.append(localeStr);
2573 }
Narayan Kamath48620f12014-01-20 13:57:11 +00002574
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07002575 if ((screenLayout&MASK_LAYOUTDIR) != 0) {
2576 if (res.size() > 0) res.append("-");
2577 switch (screenLayout&ResTable_config::MASK_LAYOUTDIR) {
2578 case ResTable_config::LAYOUTDIR_LTR:
Fabrice Di Meglio8a802db2012-09-05 13:12:02 -07002579 res.append("ldltr");
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07002580 break;
2581 case ResTable_config::LAYOUTDIR_RTL:
Fabrice Di Meglio8a802db2012-09-05 13:12:02 -07002582 res.append("ldrtl");
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07002583 break;
2584 default:
2585 res.appendFormat("layoutDir=%d",
2586 dtohs(screenLayout&ResTable_config::MASK_LAYOUTDIR));
2587 break;
2588 }
2589 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002590 if (smallestScreenWidthDp != 0) {
2591 if (res.size() > 0) res.append("-");
2592 res.appendFormat("sw%ddp", dtohs(smallestScreenWidthDp));
2593 }
2594 if (screenWidthDp != 0) {
2595 if (res.size() > 0) res.append("-");
2596 res.appendFormat("w%ddp", dtohs(screenWidthDp));
2597 }
2598 if (screenHeightDp != 0) {
2599 if (res.size() > 0) res.append("-");
2600 res.appendFormat("h%ddp", dtohs(screenHeightDp));
2601 }
2602 if ((screenLayout&MASK_SCREENSIZE) != SCREENSIZE_ANY) {
2603 if (res.size() > 0) res.append("-");
2604 switch (screenLayout&ResTable_config::MASK_SCREENSIZE) {
2605 case ResTable_config::SCREENSIZE_SMALL:
2606 res.append("small");
2607 break;
2608 case ResTable_config::SCREENSIZE_NORMAL:
2609 res.append("normal");
2610 break;
2611 case ResTable_config::SCREENSIZE_LARGE:
2612 res.append("large");
2613 break;
2614 case ResTable_config::SCREENSIZE_XLARGE:
2615 res.append("xlarge");
2616 break;
2617 default:
2618 res.appendFormat("screenLayoutSize=%d",
2619 dtohs(screenLayout&ResTable_config::MASK_SCREENSIZE));
2620 break;
2621 }
2622 }
2623 if ((screenLayout&MASK_SCREENLONG) != 0) {
2624 if (res.size() > 0) res.append("-");
2625 switch (screenLayout&ResTable_config::MASK_SCREENLONG) {
2626 case ResTable_config::SCREENLONG_NO:
2627 res.append("notlong");
2628 break;
2629 case ResTable_config::SCREENLONG_YES:
2630 res.append("long");
2631 break;
2632 default:
2633 res.appendFormat("screenLayoutLong=%d",
2634 dtohs(screenLayout&ResTable_config::MASK_SCREENLONG));
2635 break;
2636 }
2637 }
2638 if (orientation != ORIENTATION_ANY) {
2639 if (res.size() > 0) res.append("-");
2640 switch (orientation) {
2641 case ResTable_config::ORIENTATION_PORT:
2642 res.append("port");
2643 break;
2644 case ResTable_config::ORIENTATION_LAND:
2645 res.append("land");
2646 break;
2647 case ResTable_config::ORIENTATION_SQUARE:
2648 res.append("square");
2649 break;
2650 default:
2651 res.appendFormat("orientation=%d", dtohs(orientation));
2652 break;
2653 }
2654 }
2655 if ((uiMode&MASK_UI_MODE_TYPE) != UI_MODE_TYPE_ANY) {
2656 if (res.size() > 0) res.append("-");
2657 switch (uiMode&ResTable_config::MASK_UI_MODE_TYPE) {
2658 case ResTable_config::UI_MODE_TYPE_DESK:
2659 res.append("desk");
2660 break;
2661 case ResTable_config::UI_MODE_TYPE_CAR:
2662 res.append("car");
2663 break;
2664 case ResTable_config::UI_MODE_TYPE_TELEVISION:
2665 res.append("television");
2666 break;
2667 case ResTable_config::UI_MODE_TYPE_APPLIANCE:
2668 res.append("appliance");
2669 break;
John Spurlock6c191292014-04-03 16:37:27 -04002670 case ResTable_config::UI_MODE_TYPE_WATCH:
2671 res.append("watch");
2672 break;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002673 default:
2674 res.appendFormat("uiModeType=%d",
2675 dtohs(screenLayout&ResTable_config::MASK_UI_MODE_TYPE));
2676 break;
2677 }
2678 }
2679 if ((uiMode&MASK_UI_MODE_NIGHT) != 0) {
2680 if (res.size() > 0) res.append("-");
2681 switch (uiMode&ResTable_config::MASK_UI_MODE_NIGHT) {
2682 case ResTable_config::UI_MODE_NIGHT_NO:
2683 res.append("notnight");
2684 break;
2685 case ResTable_config::UI_MODE_NIGHT_YES:
2686 res.append("night");
2687 break;
2688 default:
2689 res.appendFormat("uiModeNight=%d",
2690 dtohs(uiMode&MASK_UI_MODE_NIGHT));
2691 break;
2692 }
2693 }
2694 if (density != DENSITY_DEFAULT) {
2695 if (res.size() > 0) res.append("-");
2696 switch (density) {
2697 case ResTable_config::DENSITY_LOW:
2698 res.append("ldpi");
2699 break;
2700 case ResTable_config::DENSITY_MEDIUM:
2701 res.append("mdpi");
2702 break;
2703 case ResTable_config::DENSITY_TV:
2704 res.append("tvdpi");
2705 break;
2706 case ResTable_config::DENSITY_HIGH:
2707 res.append("hdpi");
2708 break;
2709 case ResTable_config::DENSITY_XHIGH:
2710 res.append("xhdpi");
2711 break;
2712 case ResTable_config::DENSITY_XXHIGH:
2713 res.append("xxhdpi");
2714 break;
Adam Lesinski8d5667d2014-08-13 21:02:57 -07002715 case ResTable_config::DENSITY_XXXHIGH:
2716 res.append("xxxhdpi");
2717 break;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002718 case ResTable_config::DENSITY_NONE:
2719 res.append("nodpi");
2720 break;
Adam Lesinski31245b42014-08-22 19:10:56 -07002721 case ResTable_config::DENSITY_ANY:
2722 res.append("anydpi");
2723 break;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002724 default:
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08002725 res.appendFormat("%ddpi", dtohs(density));
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002726 break;
2727 }
2728 }
2729 if (touchscreen != TOUCHSCREEN_ANY) {
2730 if (res.size() > 0) res.append("-");
2731 switch (touchscreen) {
2732 case ResTable_config::TOUCHSCREEN_NOTOUCH:
2733 res.append("notouch");
2734 break;
2735 case ResTable_config::TOUCHSCREEN_FINGER:
2736 res.append("finger");
2737 break;
2738 case ResTable_config::TOUCHSCREEN_STYLUS:
2739 res.append("stylus");
2740 break;
2741 default:
2742 res.appendFormat("touchscreen=%d", dtohs(touchscreen));
2743 break;
2744 }
2745 }
Adam Lesinskifab50872014-04-16 14:40:42 -07002746 if ((inputFlags&MASK_KEYSHIDDEN) != 0) {
2747 if (res.size() > 0) res.append("-");
2748 switch (inputFlags&MASK_KEYSHIDDEN) {
2749 case ResTable_config::KEYSHIDDEN_NO:
2750 res.append("keysexposed");
2751 break;
2752 case ResTable_config::KEYSHIDDEN_YES:
2753 res.append("keyshidden");
2754 break;
2755 case ResTable_config::KEYSHIDDEN_SOFT:
2756 res.append("keyssoft");
2757 break;
2758 }
2759 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002760 if (keyboard != KEYBOARD_ANY) {
2761 if (res.size() > 0) res.append("-");
2762 switch (keyboard) {
2763 case ResTable_config::KEYBOARD_NOKEYS:
2764 res.append("nokeys");
2765 break;
2766 case ResTable_config::KEYBOARD_QWERTY:
2767 res.append("qwerty");
2768 break;
2769 case ResTable_config::KEYBOARD_12KEY:
2770 res.append("12key");
2771 break;
2772 default:
2773 res.appendFormat("keyboard=%d", dtohs(keyboard));
2774 break;
2775 }
2776 }
Adam Lesinskifab50872014-04-16 14:40:42 -07002777 if ((inputFlags&MASK_NAVHIDDEN) != 0) {
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002778 if (res.size() > 0) res.append("-");
Adam Lesinskifab50872014-04-16 14:40:42 -07002779 switch (inputFlags&MASK_NAVHIDDEN) {
2780 case ResTable_config::NAVHIDDEN_NO:
2781 res.append("navexposed");
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002782 break;
Adam Lesinskifab50872014-04-16 14:40:42 -07002783 case ResTable_config::NAVHIDDEN_YES:
2784 res.append("navhidden");
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002785 break;
Adam Lesinskifab50872014-04-16 14:40:42 -07002786 default:
2787 res.appendFormat("inputFlagsNavHidden=%d",
2788 dtohs(inputFlags&MASK_NAVHIDDEN));
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002789 break;
2790 }
2791 }
2792 if (navigation != NAVIGATION_ANY) {
2793 if (res.size() > 0) res.append("-");
2794 switch (navigation) {
2795 case ResTable_config::NAVIGATION_NONAV:
2796 res.append("nonav");
2797 break;
2798 case ResTable_config::NAVIGATION_DPAD:
2799 res.append("dpad");
2800 break;
2801 case ResTable_config::NAVIGATION_TRACKBALL:
2802 res.append("trackball");
2803 break;
2804 case ResTable_config::NAVIGATION_WHEEL:
2805 res.append("wheel");
2806 break;
2807 default:
2808 res.appendFormat("navigation=%d", dtohs(navigation));
2809 break;
2810 }
2811 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002812 if (screenSize != 0) {
2813 if (res.size() > 0) res.append("-");
2814 res.appendFormat("%dx%d", dtohs(screenWidth), dtohs(screenHeight));
2815 }
2816 if (version != 0) {
2817 if (res.size() > 0) res.append("-");
2818 res.appendFormat("v%d", dtohs(sdkVersion));
2819 if (minorVersion != 0) {
2820 res.appendFormat(".%d", dtohs(minorVersion));
2821 }
2822 }
2823
2824 return res;
2825}
2826
2827// --------------------------------------------------------------------
2828// --------------------------------------------------------------------
2829// --------------------------------------------------------------------
2830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831struct ResTable::Header
2832{
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01002833 Header(ResTable* _owner) : owner(_owner), ownedData(NULL), header(NULL),
2834 resourceIDMap(NULL), resourceIDMapSize(0) { }
2835
2836 ~Header()
2837 {
2838 free(resourceIDMap);
2839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002840
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002841 const ResTable* const owner;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002842 void* ownedData;
2843 const ResTable_header* header;
2844 size_t size;
2845 const uint8_t* dataEnd;
2846 size_t index;
Narayan Kamath7c4887f2014-01-27 17:32:37 +00002847 int32_t cookie;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848
2849 ResStringPool values;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01002850 uint32_t* resourceIDMap;
2851 size_t resourceIDMapSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002852};
2853
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002854struct ResTable::Entry {
2855 ResTable_config config;
2856 const ResTable_entry* entry;
2857 const ResTable_type* type;
2858 uint32_t specFlags;
2859 const Package* package;
2860
2861 StringPoolRef typeStr;
2862 StringPoolRef keyStr;
2863};
2864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002865struct ResTable::Type
2866{
2867 Type(const Header* _header, const Package* _package, size_t count)
2868 : header(_header), package(_package), entryCount(count),
2869 typeSpec(NULL), typeSpecFlags(NULL) { }
2870 const Header* const header;
2871 const Package* const package;
2872 const size_t entryCount;
2873 const ResTable_typeSpec* typeSpec;
2874 const uint32_t* typeSpecFlags;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002875 IdmapEntries idmapEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002876 Vector<const ResTable_type*> configs;
2877};
2878
2879struct ResTable::Package
2880{
Dianne Hackborn78c40512009-07-06 11:07:40 -07002881 Package(ResTable* _owner, const Header* _header, const ResTable_package* _package)
Adam Lesinski18560882014-08-15 17:18:21 +00002882 : owner(_owner), header(_header), package(_package), typeIdOffset(0) {
2883 if (dtohs(package->header.headerSize) == sizeof(package)) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002884 // The package structure is the same size as the definition.
2885 // This means it contains the typeIdOffset field.
Adam Lesinski18560882014-08-15 17:18:21 +00002886 typeIdOffset = package->typeIdOffset;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002887 }
2888 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07002889
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002890 const ResTable* const owner;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002891 const Header* const header;
Adam Lesinski18560882014-08-15 17:18:21 +00002892 const ResTable_package* const package;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893
Dianne Hackborn78c40512009-07-06 11:07:40 -07002894 ResStringPool typeStrings;
2895 ResStringPool keyStrings;
Mark Salyzyn00adb862014-03-19 11:00:06 -07002896
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002897 size_t typeIdOffset;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002898};
2899
2900// A group of objects describing a particular resource package.
2901// The first in 'package' is always the root object (from the resource
2902// table that defined the package); the ones after are skins on top of it.
2903struct ResTable::PackageGroup
2904{
Dianne Hackborn78c40512009-07-06 11:07:40 -07002905 PackageGroup(ResTable* _owner, const String16& _name, uint32_t _id)
Adam Lesinskide898ff2014-01-29 18:20:45 -08002906 : owner(_owner)
2907 , name(_name)
2908 , id(_id)
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002909 , largestTypeId(0)
Adam Lesinskide898ff2014-01-29 18:20:45 -08002910 , bags(NULL)
2911 , dynamicRefTable(static_cast<uint8_t>(_id))
2912 { }
2913
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002914 ~PackageGroup() {
2915 clearBagCache();
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002916 const size_t numTypes = types.size();
2917 for (size_t i = 0; i < numTypes; i++) {
2918 const TypeList& typeList = types[i];
2919 const size_t numInnerTypes = typeList.size();
2920 for (size_t j = 0; j < numInnerTypes; j++) {
2921 if (typeList[j]->package->owner == owner) {
2922 delete typeList[j];
2923 }
2924 }
2925 }
2926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002927 const size_t N = packages.size();
2928 for (size_t i=0; i<N; i++) {
Dianne Hackborn78c40512009-07-06 11:07:40 -07002929 Package* pkg = packages[i];
2930 if (pkg->owner == owner) {
2931 delete pkg;
2932 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002933 }
2934 }
2935
2936 void clearBagCache() {
2937 if (bags) {
2938 TABLE_NOISY(printf("bags=%p\n", bags));
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002939 for (size_t i = 0; i < bags->size(); i++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 TABLE_NOISY(printf("type=%d\n", i));
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002941 const TypeList& typeList = types[i];
Adam Lesinski7f668d02014-08-28 18:32:32 -07002942 if (!typeList.isEmpty()) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002943 bag_set** typeBags = bags->get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002944 TABLE_NOISY(printf("typeBags=%p\n", typeBags));
2945 if (typeBags) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002946 const size_t N = typeList[0]->entryCount;
2947 TABLE_NOISY(printf("type->entryCount=%x\n", N));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002948 for (size_t j=0; j<N; j++) {
2949 if (typeBags[j] && typeBags[j] != (bag_set*)0xFFFFFFFF)
2950 free(typeBags[j]);
2951 }
2952 free(typeBags);
2953 }
2954 }
2955 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002956 delete bags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002957 bags = NULL;
2958 }
2959 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07002960
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002961 ssize_t findType16(const char16_t* type, size_t len) const {
2962 const size_t N = packages.size();
2963 for (size_t i = 0; i < N; i++) {
2964 ssize_t index = packages[i]->typeStrings.indexOfString(type, len);
2965 if (index >= 0) {
2966 return index + packages[i]->typeIdOffset;
2967 }
2968 }
2969 return -1;
2970 }
2971
2972 const ResTable* const owner;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002973 String16 const name;
2974 uint32_t const id;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002975
2976 // This is mainly used to keep track of the loaded packages
2977 // and to clean them up properly. Accessing resources happens from
2978 // the 'types' array.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002979 Vector<Package*> packages;
Mark Salyzyn00adb862014-03-19 11:00:06 -07002980
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002981 ByteBucketArray<TypeList> types;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002982
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002983 uint8_t largestTypeId;
Mark Salyzyn00adb862014-03-19 11:00:06 -07002984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002985 // Computed attribute bags, first indexed by the type and second
2986 // by the entry in that type.
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002987 ByteBucketArray<bag_set**>* bags;
Adam Lesinskide898ff2014-01-29 18:20:45 -08002988
2989 // The table mapping dynamic references to resolved references for
2990 // this package group.
2991 // TODO: We may be able to support dynamic references in overlays
2992 // by having these tables in a per-package scope rather than
2993 // per-package-group.
2994 DynamicRefTable dynamicRefTable;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002995};
2996
2997struct ResTable::bag_set
2998{
2999 size_t numAttrs; // number in array
3000 size_t availAttrs; // total space in array
3001 uint32_t typeSpecFlags;
3002 // Followed by 'numAttr' bag_entry structures.
3003};
3004
3005ResTable::Theme::Theme(const ResTable& table)
3006 : mTable(table)
3007{
3008 memset(mPackages, 0, sizeof(mPackages));
3009}
3010
3011ResTable::Theme::~Theme()
3012{
3013 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3014 package_info* pi = mPackages[i];
3015 if (pi != NULL) {
3016 free_package(pi);
3017 }
3018 }
3019}
3020
3021void ResTable::Theme::free_package(package_info* pi)
3022{
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003023 for (size_t j = 0; j <= Res_MAXTYPE; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003024 theme_entry* te = pi->types[j].entries;
3025 if (te != NULL) {
3026 free(te);
3027 }
3028 }
3029 free(pi);
3030}
3031
3032ResTable::Theme::package_info* ResTable::Theme::copy_package(package_info* pi)
3033{
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003034 package_info* newpi = (package_info*)malloc(sizeof(package_info));
3035 for (size_t j = 0; j <= Res_MAXTYPE; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003036 size_t cnt = pi->types[j].numEntries;
3037 newpi->types[j].numEntries = cnt;
3038 theme_entry* te = pi->types[j].entries;
3039 if (te != NULL) {
3040 theme_entry* newte = (theme_entry*)malloc(cnt*sizeof(theme_entry));
3041 newpi->types[j].entries = newte;
3042 memcpy(newte, te, cnt*sizeof(theme_entry));
3043 } else {
3044 newpi->types[j].entries = NULL;
3045 }
3046 }
3047 return newpi;
3048}
3049
3050status_t ResTable::Theme::applyStyle(uint32_t resID, bool force)
3051{
3052 const bag_entry* bag;
3053 uint32_t bagTypeSpecFlags = 0;
3054 mTable.lock();
3055 const ssize_t N = mTable.getBagLocked(resID, &bag, &bagTypeSpecFlags);
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08003056 TABLE_NOISY(ALOGV("Applying style 0x%08x to theme %p, count=%d", resID, this, N));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057 if (N < 0) {
3058 mTable.unlock();
3059 return N;
3060 }
3061
3062 uint32_t curPackage = 0xffffffff;
3063 ssize_t curPackageIndex = 0;
3064 package_info* curPI = NULL;
3065 uint32_t curType = 0xffffffff;
3066 size_t numEntries = 0;
3067 theme_entry* curEntries = NULL;
3068
3069 const bag_entry* end = bag + N;
3070 while (bag < end) {
3071 const uint32_t attrRes = bag->map.name.ident;
3072 const uint32_t p = Res_GETPACKAGE(attrRes);
3073 const uint32_t t = Res_GETTYPE(attrRes);
3074 const uint32_t e = Res_GETENTRY(attrRes);
3075
3076 if (curPackage != p) {
3077 const ssize_t pidx = mTable.getResourcePackageIndex(attrRes);
3078 if (pidx < 0) {
Steve Block3762c312012-01-06 19:20:56 +00003079 ALOGE("Style contains key with bad package: 0x%08x\n", attrRes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003080 bag++;
3081 continue;
3082 }
3083 curPackage = p;
3084 curPackageIndex = pidx;
3085 curPI = mPackages[pidx];
3086 if (curPI == NULL) {
3087 PackageGroup* const grp = mTable.mPackageGroups[pidx];
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003088 curPI = (package_info*)malloc(sizeof(package_info));
3089 memset(curPI, 0, sizeof(*curPI));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003090 mPackages[pidx] = curPI;
3091 }
3092 curType = 0xffffffff;
3093 }
3094 if (curType != t) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003095 if (t > Res_MAXTYPE) {
Steve Block3762c312012-01-06 19:20:56 +00003096 ALOGE("Style contains key with bad type: 0x%08x\n", attrRes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003097 bag++;
3098 continue;
3099 }
3100 curType = t;
3101 curEntries = curPI->types[t].entries;
3102 if (curEntries == NULL) {
3103 PackageGroup* const grp = mTable.mPackageGroups[curPackageIndex];
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003104 const TypeList& typeList = grp->types[t];
3105 int cnt = typeList.isEmpty() ? 0 : typeList[0]->entryCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003106 curEntries = (theme_entry*)malloc(cnt*sizeof(theme_entry));
3107 memset(curEntries, Res_value::TYPE_NULL, cnt*sizeof(theme_entry));
3108 curPI->types[t].numEntries = cnt;
3109 curPI->types[t].entries = curEntries;
3110 }
3111 numEntries = curPI->types[t].numEntries;
3112 }
3113 if (e >= numEntries) {
Steve Block3762c312012-01-06 19:20:56 +00003114 ALOGE("Style contains key with bad entry: 0x%08x\n", attrRes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003115 bag++;
3116 continue;
3117 }
3118 theme_entry* curEntry = curEntries + e;
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08003119 TABLE_NOISY(ALOGV("Attr 0x%08x: type=0x%x, data=0x%08x; curType=0x%x",
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003120 attrRes, bag->map.value.dataType, bag->map.value.data,
3121 curEntry->value.dataType));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003122 if (force || curEntry->value.dataType == Res_value::TYPE_NULL) {
3123 curEntry->stringBlock = bag->stringBlock;
3124 curEntry->typeSpecFlags |= bagTypeSpecFlags;
3125 curEntry->value = bag->map.value;
3126 }
3127
3128 bag++;
3129 }
3130
3131 mTable.unlock();
3132
Steve Block6215d3f2012-01-04 20:05:49 +00003133 //ALOGI("Applying style 0x%08x (force=%d) theme %p...\n", resID, force, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003134 //dumpToLog();
Mark Salyzyn00adb862014-03-19 11:00:06 -07003135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136 return NO_ERROR;
3137}
3138
3139status_t ResTable::Theme::setTo(const Theme& other)
3140{
Steve Block6215d3f2012-01-04 20:05:49 +00003141 //ALOGI("Setting theme %p from theme %p...\n", this, &other);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142 //dumpToLog();
3143 //other.dumpToLog();
Mark Salyzyn00adb862014-03-19 11:00:06 -07003144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003145 if (&mTable == &other.mTable) {
3146 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3147 if (mPackages[i] != NULL) {
3148 free_package(mPackages[i]);
3149 }
3150 if (other.mPackages[i] != NULL) {
3151 mPackages[i] = copy_package(other.mPackages[i]);
3152 } else {
3153 mPackages[i] = NULL;
3154 }
3155 }
3156 } else {
3157 // @todo: need to really implement this, not just copy
3158 // the system package (which is still wrong because it isn't
3159 // fixing up resource references).
3160 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3161 if (mPackages[i] != NULL) {
3162 free_package(mPackages[i]);
3163 }
3164 if (i == 0 && other.mPackages[i] != NULL) {
3165 mPackages[i] = copy_package(other.mPackages[i]);
3166 } else {
3167 mPackages[i] = NULL;
3168 }
3169 }
3170 }
3171
Steve Block6215d3f2012-01-04 20:05:49 +00003172 //ALOGI("Final theme:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003173 //dumpToLog();
Mark Salyzyn00adb862014-03-19 11:00:06 -07003174
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003175 return NO_ERROR;
3176}
3177
3178ssize_t ResTable::Theme::getAttribute(uint32_t resID, Res_value* outValue,
3179 uint32_t* outTypeSpecFlags) const
3180{
3181 int cnt = 20;
3182
3183 if (outTypeSpecFlags != NULL) *outTypeSpecFlags = 0;
Mark Salyzyn00adb862014-03-19 11:00:06 -07003184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003185 do {
3186 const ssize_t p = mTable.getResourcePackageIndex(resID);
3187 const uint32_t t = Res_GETTYPE(resID);
3188 const uint32_t e = Res_GETENTRY(resID);
3189
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08003190 TABLE_THEME(ALOGI("Looking up attr 0x%08x in theme %p", resID, this));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003191
3192 if (p >= 0) {
3193 const package_info* const pi = mPackages[p];
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08003194 TABLE_THEME(ALOGI("Found package: %p", pi));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003195 if (pi != NULL) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003196 TABLE_THEME(ALOGI("Desired type index is %ld in avail %d", t, Res_MAXTYPE + 1));
3197 if (t <= Res_MAXTYPE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003198 const type_info& ti = pi->types[t];
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08003199 TABLE_THEME(ALOGI("Desired entry index is %ld in avail %d", e, ti.numEntries));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003200 if (e < ti.numEntries) {
3201 const theme_entry& te = ti.entries[e];
Dianne Hackbornb8d81672009-11-20 14:26:42 -08003202 if (outTypeSpecFlags != NULL) {
3203 *outTypeSpecFlags |= te.typeSpecFlags;
3204 }
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08003205 TABLE_THEME(ALOGI("Theme value: type=0x%x, data=0x%08x",
Dianne Hackbornb8d81672009-11-20 14:26:42 -08003206 te.value.dataType, te.value.data));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003207 const uint8_t type = te.value.dataType;
3208 if (type == Res_value::TYPE_ATTRIBUTE) {
3209 if (cnt > 0) {
3210 cnt--;
3211 resID = te.value.data;
3212 continue;
3213 }
Steve Block8564c8d2012-01-05 23:22:43 +00003214 ALOGW("Too many attribute references, stopped at: 0x%08x\n", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003215 return BAD_INDEX;
3216 } else if (type != Res_value::TYPE_NULL) {
3217 *outValue = te.value;
3218 return te.stringBlock;
3219 }
3220 return BAD_INDEX;
3221 }
3222 }
3223 }
3224 }
3225 break;
3226
3227 } while (true);
3228
3229 return BAD_INDEX;
3230}
3231
3232ssize_t ResTable::Theme::resolveAttributeReference(Res_value* inOutValue,
3233 ssize_t blockIndex, uint32_t* outLastRef,
Dianne Hackborn0d221012009-07-29 15:41:19 -07003234 uint32_t* inoutTypeSpecFlags, ResTable_config* inoutConfig) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003235{
3236 //printf("Resolving type=0x%x\n", inOutValue->dataType);
3237 if (inOutValue->dataType == Res_value::TYPE_ATTRIBUTE) {
3238 uint32_t newTypeSpecFlags;
3239 blockIndex = getAttribute(inOutValue->data, inOutValue, &newTypeSpecFlags);
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08003240 TABLE_THEME(ALOGI("Resolving attr reference: blockIndex=%d, type=0x%x, data=%p\n",
Dianne Hackbornb8d81672009-11-20 14:26:42 -08003241 (int)blockIndex, (int)inOutValue->dataType, (void*)inOutValue->data));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003242 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newTypeSpecFlags;
3243 //printf("Retrieved attribute new type=0x%x\n", inOutValue->dataType);
3244 if (blockIndex < 0) {
3245 return blockIndex;
3246 }
3247 }
Dianne Hackborn0d221012009-07-29 15:41:19 -07003248 return mTable.resolveReference(inOutValue, blockIndex, outLastRef,
3249 inoutTypeSpecFlags, inoutConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003250}
3251
3252void ResTable::Theme::dumpToLog() const
3253{
Steve Block6215d3f2012-01-04 20:05:49 +00003254 ALOGI("Theme %p:\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003255 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3256 package_info* pi = mPackages[i];
3257 if (pi == NULL) continue;
Mark Salyzyn00adb862014-03-19 11:00:06 -07003258
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003259 ALOGI(" Package #0x%02x:\n", (int)(i + 1));
3260 for (size_t j = 0; j <= Res_MAXTYPE; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003261 type_info& ti = pi->types[j];
3262 if (ti.numEntries == 0) continue;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003263 ALOGI(" Type #0x%02x:\n", (int)(j + 1));
3264 for (size_t k = 0; k < ti.numEntries; k++) {
3265 const theme_entry& te = ti.entries[k];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003266 if (te.value.dataType == Res_value::TYPE_NULL) continue;
Steve Block6215d3f2012-01-04 20:05:49 +00003267 ALOGI(" 0x%08x: t=0x%x, d=0x%08x (block=%d)\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003268 (int)Res_MAKEID(i, j, k),
3269 te.value.dataType, (int)te.value.data, (int)te.stringBlock);
3270 }
3271 }
3272 }
3273}
3274
3275ResTable::ResTable()
Adam Lesinskide898ff2014-01-29 18:20:45 -08003276 : mError(NO_INIT), mNextPackageId(2)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003277{
3278 memset(&mParams, 0, sizeof(mParams));
3279 memset(mPackageMap, 0, sizeof(mPackageMap));
Steve Block6215d3f2012-01-04 20:05:49 +00003280 //ALOGI("Creating ResTable %p\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003281}
3282
Narayan Kamath7c4887f2014-01-27 17:32:37 +00003283ResTable::ResTable(const void* data, size_t size, const int32_t cookie, bool copyData)
Adam Lesinskide898ff2014-01-29 18:20:45 -08003284 : mError(NO_INIT), mNextPackageId(2)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285{
3286 memset(&mParams, 0, sizeof(mParams));
3287 memset(mPackageMap, 0, sizeof(mPackageMap));
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003288 addInternal(data, size, NULL, 0, cookie, copyData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 LOG_FATAL_IF(mError != NO_ERROR, "Error parsing resource table");
Steve Block6215d3f2012-01-04 20:05:49 +00003290 //ALOGI("Creating ResTable %p\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003291}
3292
3293ResTable::~ResTable()
3294{
Steve Block6215d3f2012-01-04 20:05:49 +00003295 //ALOGI("Destroying ResTable in %p\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003296 uninit();
3297}
3298
3299inline ssize_t ResTable::getResourcePackageIndex(uint32_t resID) const
3300{
3301 return ((ssize_t)mPackageMap[Res_GETPACKAGE(resID)+1])-1;
3302}
3303
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003304status_t ResTable::add(const void* data, size_t size, const int32_t cookie, bool copyData) {
3305 return addInternal(data, size, NULL, 0, cookie, copyData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003306}
3307
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003308status_t ResTable::add(const void* data, size_t size, const void* idmapData, size_t idmapDataSize,
3309 const int32_t cookie, bool copyData) {
3310 return addInternal(data, size, idmapData, idmapDataSize, cookie, copyData);
3311}
3312
3313status_t ResTable::add(Asset* asset, const int32_t cookie, bool copyData) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003314 const void* data = asset->getBuffer(true);
3315 if (data == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00003316 ALOGW("Unable to get buffer of resource asset file");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003317 return UNKNOWN_ERROR;
3318 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003319
3320 return addInternal(data, static_cast<size_t>(asset->getLength()), NULL, 0, cookie, copyData);
3321}
3322
3323status_t ResTable::add(Asset* asset, Asset* idmapAsset, const int32_t cookie, bool copyData) {
3324 const void* data = asset->getBuffer(true);
3325 if (data == NULL) {
3326 ALOGW("Unable to get buffer of resource asset file");
3327 return UNKNOWN_ERROR;
3328 }
3329
3330 size_t idmapSize = 0;
3331 const void* idmapData = NULL;
3332 if (idmapAsset != NULL) {
3333 idmapData = idmapAsset->getBuffer(true);
3334 if (idmapData == NULL) {
3335 ALOGW("Unable to get buffer of idmap asset file");
3336 return UNKNOWN_ERROR;
3337 }
3338 idmapSize = static_cast<size_t>(idmapAsset->getLength());
3339 }
3340
3341 return addInternal(data, static_cast<size_t>(asset->getLength()),
3342 idmapData, idmapSize, cookie, copyData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003343}
3344
Dianne Hackborn78c40512009-07-06 11:07:40 -07003345status_t ResTable::add(ResTable* src)
3346{
3347 mError = src->mError;
Mark Salyzyn00adb862014-03-19 11:00:06 -07003348
Dianne Hackborn78c40512009-07-06 11:07:40 -07003349 for (size_t i=0; i<src->mHeaders.size(); i++) {
3350 mHeaders.add(src->mHeaders[i]);
3351 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07003352
Dianne Hackborn78c40512009-07-06 11:07:40 -07003353 for (size_t i=0; i<src->mPackageGroups.size(); i++) {
3354 PackageGroup* srcPg = src->mPackageGroups[i];
3355 PackageGroup* pg = new PackageGroup(this, srcPg->name, srcPg->id);
3356 for (size_t j=0; j<srcPg->packages.size(); j++) {
3357 pg->packages.add(srcPg->packages[j]);
3358 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003359
3360 for (size_t j = 0; j < srcPg->types.size(); j++) {
3361 if (srcPg->types[j].isEmpty()) {
3362 continue;
3363 }
3364
3365 TypeList& typeList = pg->types.editItemAt(j);
3366 typeList.appendVector(srcPg->types[j]);
3367 }
Adam Lesinski6022deb2014-08-20 14:59:19 -07003368 pg->dynamicRefTable.addMappings(srcPg->dynamicRefTable);
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003369 pg->largestTypeId = max(pg->largestTypeId, srcPg->largestTypeId);
Dianne Hackborn78c40512009-07-06 11:07:40 -07003370 mPackageGroups.add(pg);
3371 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07003372
Dianne Hackborn78c40512009-07-06 11:07:40 -07003373 memcpy(mPackageMap, src->mPackageMap, sizeof(mPackageMap));
Mark Salyzyn00adb862014-03-19 11:00:06 -07003374
Dianne Hackborn78c40512009-07-06 11:07:40 -07003375 return mError;
3376}
3377
Adam Lesinskide898ff2014-01-29 18:20:45 -08003378status_t ResTable::addEmpty(const int32_t cookie) {
3379 Header* header = new Header(this);
3380 header->index = mHeaders.size();
3381 header->cookie = cookie;
3382 header->values.setToEmpty();
3383 header->ownedData = calloc(1, sizeof(ResTable_header));
3384
3385 ResTable_header* resHeader = (ResTable_header*) header->ownedData;
3386 resHeader->header.type = RES_TABLE_TYPE;
3387 resHeader->header.headerSize = sizeof(ResTable_header);
3388 resHeader->header.size = sizeof(ResTable_header);
3389
3390 header->header = (const ResTable_header*) resHeader;
3391 mHeaders.add(header);
Adam Lesinski961dda72014-06-09 17:10:29 -07003392 return (mError=NO_ERROR);
Adam Lesinskide898ff2014-01-29 18:20:45 -08003393}
3394
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003395status_t ResTable::addInternal(const void* data, size_t dataSize, const void* idmapData, size_t idmapDataSize,
3396 const int32_t cookie, bool copyData)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397{
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003398 if (!data) {
3399 return NO_ERROR;
3400 }
3401
Adam Lesinskif28d5052014-07-25 15:25:04 -07003402 if (dataSize < sizeof(ResTable_header)) {
3403 ALOGE("Invalid data. Size(%d) is smaller than a ResTable_header(%d).",
3404 (int) dataSize, (int) sizeof(ResTable_header));
3405 return UNKNOWN_ERROR;
3406 }
3407
Dianne Hackborn78c40512009-07-06 11:07:40 -07003408 Header* header = new Header(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003409 header->index = mHeaders.size();
3410 header->cookie = cookie;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003411 if (idmapData != NULL) {
3412 header->resourceIDMap = (uint32_t*) malloc(idmapDataSize);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01003413 if (header->resourceIDMap == NULL) {
3414 delete header;
3415 return (mError = NO_MEMORY);
3416 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003417 memcpy(header->resourceIDMap, idmapData, idmapDataSize);
3418 header->resourceIDMapSize = idmapDataSize;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01003419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003420 mHeaders.add(header);
3421
3422 const bool notDeviceEndian = htods(0xf0) != 0xf0;
3423
3424 LOAD_TABLE_NOISY(
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003425 ALOGV("Adding resources to ResTable: data=%p, size=0x%x, cookie=%d, copy=%d "
3426 "idmap=%p\n", data, dataSize, cookie, copyData, idmap));
Mark Salyzyn00adb862014-03-19 11:00:06 -07003427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428 if (copyData || notDeviceEndian) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003429 header->ownedData = malloc(dataSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003430 if (header->ownedData == NULL) {
3431 return (mError=NO_MEMORY);
3432 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003433 memcpy(header->ownedData, data, dataSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003434 data = header->ownedData;
3435 }
3436
3437 header->header = (const ResTable_header*)data;
3438 header->size = dtohl(header->header->header.size);
Steve Block6215d3f2012-01-04 20:05:49 +00003439 //ALOGI("Got size 0x%x, again size 0x%x, raw size 0x%x\n", header->size,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003440 // dtohl(header->header->header.size), header->header->header.size);
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08003441 LOAD_TABLE_NOISY(ALOGV("Loading ResTable @%p:\n", header->header));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003442 if (dtohs(header->header->header.headerSize) > header->size
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003443 || header->size > dataSize) {
Steve Block8564c8d2012-01-05 23:22:43 +00003444 ALOGW("Bad resource table: header size 0x%x or total size 0x%x is larger than data size 0x%x\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003445 (int)dtohs(header->header->header.headerSize),
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003446 (int)header->size, (int)dataSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003447 return (mError=BAD_TYPE);
3448 }
3449 if (((dtohs(header->header->header.headerSize)|header->size)&0x3) != 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003450 ALOGW("Bad resource table: header size 0x%x or total size 0x%x is not on an integer boundary\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003451 (int)dtohs(header->header->header.headerSize),
3452 (int)header->size);
3453 return (mError=BAD_TYPE);
3454 }
3455 header->dataEnd = ((const uint8_t*)header->header) + header->size;
3456
3457 // Iterate through all chunks.
3458 size_t curPackage = 0;
3459
3460 const ResChunk_header* chunk =
3461 (const ResChunk_header*)(((const uint8_t*)header->header)
3462 + dtohs(header->header->header.headerSize));
3463 while (((const uint8_t*)chunk) <= (header->dataEnd-sizeof(ResChunk_header)) &&
3464 ((const uint8_t*)chunk) <= (header->dataEnd-dtohl(chunk->size))) {
3465 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), header->dataEnd, "ResTable");
3466 if (err != NO_ERROR) {
3467 return (mError=err);
3468 }
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08003469 TABLE_NOISY(ALOGV("Chunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003470 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
3471 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header))));
3472 const size_t csize = dtohl(chunk->size);
3473 const uint16_t ctype = dtohs(chunk->type);
3474 if (ctype == RES_STRING_POOL_TYPE) {
3475 if (header->values.getError() != NO_ERROR) {
3476 // Only use the first string chunk; ignore any others that
3477 // may appear.
3478 status_t err = header->values.setTo(chunk, csize);
3479 if (err != NO_ERROR) {
3480 return (mError=err);
3481 }
3482 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003483 ALOGW("Multiple string chunks found in resource table.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003484 }
3485 } else if (ctype == RES_TABLE_PACKAGE_TYPE) {
3486 if (curPackage >= dtohl(header->header->packageCount)) {
Steve Block8564c8d2012-01-05 23:22:43 +00003487 ALOGW("More package chunks were found than the %d declared in the header.",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003488 dtohl(header->header->packageCount));
3489 return (mError=BAD_TYPE);
3490 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003491
3492 if (parsePackage((ResTable_package*)chunk, header) != NO_ERROR) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003493 return mError;
3494 }
3495 curPackage++;
3496 } else {
Patrik Bannura443dd932014-02-12 13:38:54 +01003497 ALOGW("Unknown chunk type 0x%x in table at %p.\n",
3498 ctype,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003499 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)));
3500 }
3501 chunk = (const ResChunk_header*)
3502 (((const uint8_t*)chunk) + csize);
3503 }
3504
3505 if (curPackage < dtohl(header->header->packageCount)) {
Steve Block8564c8d2012-01-05 23:22:43 +00003506 ALOGW("Fewer package chunks (%d) were found than the %d declared in the header.",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003507 (int)curPackage, dtohl(header->header->packageCount));
3508 return (mError=BAD_TYPE);
3509 }
3510 mError = header->values.getError();
3511 if (mError != NO_ERROR) {
Steve Block8564c8d2012-01-05 23:22:43 +00003512 ALOGW("No string values found in resource table!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003513 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01003514
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08003515 TABLE_NOISY(ALOGV("Returning from add with mError=%d\n", mError));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003516 return mError;
3517}
3518
3519status_t ResTable::getError() const
3520{
3521 return mError;
3522}
3523
3524void ResTable::uninit()
3525{
3526 mError = NO_INIT;
3527 size_t N = mPackageGroups.size();
3528 for (size_t i=0; i<N; i++) {
3529 PackageGroup* g = mPackageGroups[i];
3530 delete g;
3531 }
3532 N = mHeaders.size();
3533 for (size_t i=0; i<N; i++) {
3534 Header* header = mHeaders[i];
Dianne Hackborn78c40512009-07-06 11:07:40 -07003535 if (header->owner == this) {
3536 if (header->ownedData) {
3537 free(header->ownedData);
3538 }
3539 delete header;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003540 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003541 }
3542
3543 mPackageGroups.clear();
3544 mHeaders.clear();
3545}
3546
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07003547bool ResTable::getResourceName(uint32_t resID, bool allowUtf8, resource_name* outName) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003548{
3549 if (mError != NO_ERROR) {
3550 return false;
3551 }
3552
3553 const ssize_t p = getResourcePackageIndex(resID);
3554 const int t = Res_GETTYPE(resID);
3555 const int e = Res_GETENTRY(resID);
3556
3557 if (p < 0) {
Dianne Hackborn6cca1592009-09-20 12:40:03 -07003558 if (Res_GETPACKAGE(resID)+1 == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003559 ALOGW("No package identifier when getting name for resource number 0x%08x", resID);
Dianne Hackborn6cca1592009-09-20 12:40:03 -07003560 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003561 ALOGW("No known package when getting name for resource number 0x%08x", resID);
Dianne Hackborn6cca1592009-09-20 12:40:03 -07003562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003563 return false;
3564 }
3565 if (t < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003566 ALOGW("No type identifier when getting name for resource number 0x%08x", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003567 return false;
3568 }
3569
3570 const PackageGroup* const grp = mPackageGroups[p];
3571 if (grp == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00003572 ALOGW("Bad identifier when getting name for resource number 0x%08x", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003573 return false;
3574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003575
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003576 Entry entry;
3577 status_t err = getEntry(grp, t, e, NULL, &entry);
3578 if (err != NO_ERROR) {
3579 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003580 }
3581
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003582 outName->package = grp->name.string();
3583 outName->packageLen = grp->name.size();
3584 if (allowUtf8) {
3585 outName->type8 = entry.typeStr.string8(&outName->typeLen);
3586 outName->name8 = entry.keyStr.string8(&outName->nameLen);
3587 } else {
3588 outName->type8 = NULL;
3589 outName->name8 = NULL;
3590 }
3591 if (outName->type8 == NULL) {
3592 outName->type = entry.typeStr.string16(&outName->typeLen);
3593 // If we have a bad index for some reason, we should abort.
3594 if (outName->type == NULL) {
3595 return false;
3596 }
3597 }
3598 if (outName->name8 == NULL) {
3599 outName->name = entry.keyStr.string16(&outName->nameLen);
3600 // If we have a bad index for some reason, we should abort.
3601 if (outName->name == NULL) {
3602 return false;
3603 }
3604 }
3605
3606 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003607}
3608
Kenny Root55fc8502010-10-28 14:47:01 -07003609ssize_t ResTable::getResource(uint32_t resID, Res_value* outValue, bool mayBeBag, uint16_t density,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003610 uint32_t* outSpecFlags, ResTable_config* outConfig) const
3611{
3612 if (mError != NO_ERROR) {
3613 return mError;
3614 }
3615
3616 const ssize_t p = getResourcePackageIndex(resID);
3617 const int t = Res_GETTYPE(resID);
3618 const int e = Res_GETENTRY(resID);
3619
3620 if (p < 0) {
Dianne Hackborn6cca1592009-09-20 12:40:03 -07003621 if (Res_GETPACKAGE(resID)+1 == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003622 ALOGW("No package identifier when getting value for resource number 0x%08x", resID);
Dianne Hackborn6cca1592009-09-20 12:40:03 -07003623 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003624 ALOGW("No known package when getting value for resource number 0x%08x", resID);
Dianne Hackborn6cca1592009-09-20 12:40:03 -07003625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003626 return BAD_INDEX;
3627 }
3628 if (t < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003629 ALOGW("No type identifier when getting value for resource number 0x%08x", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003630 return BAD_INDEX;
3631 }
3632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003633 const PackageGroup* const grp = mPackageGroups[p];
3634 if (grp == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00003635 ALOGW("Bad identifier when getting value for resource number 0x%08x", resID);
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08003636 return BAD_INDEX;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003637 }
Kenny Root55fc8502010-10-28 14:47:01 -07003638
3639 // Allow overriding density
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003640 ResTable_config desiredConfig = mParams;
Kenny Root55fc8502010-10-28 14:47:01 -07003641 if (density > 0) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003642 desiredConfig.density = density;
Kenny Root55fc8502010-10-28 14:47:01 -07003643 }
3644
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003645 Entry entry;
3646 status_t err = getEntry(grp, t, e, &desiredConfig, &entry);
3647 if (err != NO_ERROR) {
3648 ALOGW("Failure getting entry for 0x%08x (t=%d e=%d) (error %d)\n",
3649 resID, t, e, err);
3650 return err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003651 }
3652
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003653 if ((dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) != 0) {
3654 if (!mayBeBag) {
3655 ALOGW("Requesting resource 0x%08x failed because it is complex\n", resID);
Adam Lesinskide898ff2014-01-29 18:20:45 -08003656 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003657 return BAD_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003658 }
3659
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003660 const Res_value* value = reinterpret_cast<const Res_value*>(
3661 reinterpret_cast<const uint8_t*>(entry.entry) + entry.entry->size);
3662
3663 outValue->size = dtohs(value->size);
3664 outValue->res0 = value->res0;
3665 outValue->dataType = value->dataType;
3666 outValue->data = dtohl(value->data);
3667
3668 // The reference may be pointing to a resource in a shared library. These
3669 // references have build-time generated package IDs. These ids may not match
3670 // the actual package IDs of the corresponding packages in this ResTable.
3671 // We need to fix the package ID based on a mapping.
3672 if (grp->dynamicRefTable.lookupResourceValue(outValue) != NO_ERROR) {
3673 ALOGW("Failed to resolve referenced package: 0x%08x", outValue->data);
3674 return BAD_VALUE;
Kenny Root55fc8502010-10-28 14:47:01 -07003675 }
3676
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003677 TABLE_NOISY(size_t len;
3678 printf("Found value: pkg=%d, type=%d, str=%s, int=%d\n",
3679 entry.package->header->index,
3680 outValue->dataType,
3681 outValue->dataType == Res_value::TYPE_STRING
3682 ? String8(entry.package->header->values.stringAt(
3683 outValue->data, &len)).string()
3684 : "",
3685 outValue->data));
3686
3687 if (outSpecFlags != NULL) {
3688 *outSpecFlags = entry.specFlags;
3689 }
3690
3691 if (outConfig != NULL) {
3692 *outConfig = entry.config;
3693 }
3694
3695 return entry.package->header->index;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003696}
3697
3698ssize_t ResTable::resolveReference(Res_value* value, ssize_t blockIndex,
Dianne Hackborn0d221012009-07-29 15:41:19 -07003699 uint32_t* outLastRef, uint32_t* inoutTypeSpecFlags,
3700 ResTable_config* outConfig) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003701{
3702 int count=0;
Adam Lesinskide898ff2014-01-29 18:20:45 -08003703 while (blockIndex >= 0 && value->dataType == Res_value::TYPE_REFERENCE
3704 && value->data != 0 && count < 20) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003705 if (outLastRef) *outLastRef = value->data;
3706 uint32_t lastRef = value->data;
3707 uint32_t newFlags = 0;
Kenny Root55fc8502010-10-28 14:47:01 -07003708 const ssize_t newIndex = getResource(value->data, value, true, 0, &newFlags,
Dianne Hackborn0d221012009-07-29 15:41:19 -07003709 outConfig);
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08003710 if (newIndex == BAD_INDEX) {
3711 return BAD_INDEX;
3712 }
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08003713 TABLE_THEME(ALOGI("Resolving reference %p: newIndex=%d, type=0x%x, data=%p\n",
Dianne Hackbornb8d81672009-11-20 14:26:42 -08003714 (void*)lastRef, (int)newIndex, (int)value->dataType, (void*)value->data));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715 //printf("Getting reference 0x%08x: newIndex=%d\n", value->data, newIndex);
3716 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newFlags;
3717 if (newIndex < 0) {
3718 // This can fail if the resource being referenced is a style...
3719 // in this case, just return the reference, and expect the
3720 // caller to deal with.
3721 return blockIndex;
3722 }
3723 blockIndex = newIndex;
3724 count++;
3725 }
3726 return blockIndex;
3727}
3728
3729const char16_t* ResTable::valueToString(
3730 const Res_value* value, size_t stringBlock,
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07003731 char16_t /*tmpBuffer*/ [TMP_BUFFER_SIZE], size_t* outLen) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003732{
3733 if (!value) {
3734 return NULL;
3735 }
3736 if (value->dataType == value->TYPE_STRING) {
3737 return getTableStringBlock(stringBlock)->stringAt(value->data, outLen);
3738 }
3739 // XXX do int to string conversions.
3740 return NULL;
3741}
3742
3743ssize_t ResTable::lockBag(uint32_t resID, const bag_entry** outBag) const
3744{
3745 mLock.lock();
3746 ssize_t err = getBagLocked(resID, outBag);
3747 if (err < NO_ERROR) {
3748 //printf("*** get failed! unlocking\n");
3749 mLock.unlock();
3750 }
3751 return err;
3752}
3753
Mark Salyzyn00adb862014-03-19 11:00:06 -07003754void ResTable::unlockBag(const bag_entry* /*bag*/) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003755{
3756 //printf("<<< unlockBag %p\n", this);
3757 mLock.unlock();
3758}
3759
3760void ResTable::lock() const
3761{
3762 mLock.lock();
3763}
3764
3765void ResTable::unlock() const
3766{
3767 mLock.unlock();
3768}
3769
3770ssize_t ResTable::getBagLocked(uint32_t resID, const bag_entry** outBag,
3771 uint32_t* outTypeSpecFlags) const
3772{
3773 if (mError != NO_ERROR) {
3774 return mError;
3775 }
3776
3777 const ssize_t p = getResourcePackageIndex(resID);
3778 const int t = Res_GETTYPE(resID);
3779 const int e = Res_GETENTRY(resID);
3780
3781 if (p < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003782 ALOGW("Invalid package identifier when getting bag for resource number 0x%08x", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003783 return BAD_INDEX;
3784 }
3785 if (t < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003786 ALOGW("No type identifier when getting bag for resource number 0x%08x", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003787 return BAD_INDEX;
3788 }
3789
3790 //printf("Get bag: id=0x%08x, p=%d, t=%d\n", resID, p, t);
3791 PackageGroup* const grp = mPackageGroups[p];
3792 if (grp == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00003793 ALOGW("Bad identifier when getting bag for resource number 0x%08x", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003794 return BAD_INDEX;
3795 }
3796
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003797 const TypeList& typeConfigs = grp->types[t];
3798 if (typeConfigs.isEmpty()) {
3799 ALOGW("Type identifier 0x%x does not exist.", t+1);
3800 return BAD_INDEX;
3801 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003802
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003803 const size_t NENTRY = typeConfigs[0]->entryCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003804 if (e >= (int)NENTRY) {
Steve Block8564c8d2012-01-05 23:22:43 +00003805 ALOGW("Entry identifier 0x%x is larger than entry count 0x%x",
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003806 e, (int)typeConfigs[0]->entryCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003807 return BAD_INDEX;
3808 }
3809
3810 // First see if we've already computed this bag...
3811 if (grp->bags) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003812 bag_set** typeSet = grp->bags->get(t);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003813 if (typeSet) {
3814 bag_set* set = typeSet[e];
3815 if (set) {
3816 if (set != (bag_set*)0xFFFFFFFF) {
3817 if (outTypeSpecFlags != NULL) {
3818 *outTypeSpecFlags = set->typeSpecFlags;
3819 }
3820 *outBag = (bag_entry*)(set+1);
Steve Block6215d3f2012-01-04 20:05:49 +00003821 //ALOGI("Found existing bag for: %p\n", (void*)resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003822 return set->numAttrs;
3823 }
Steve Block8564c8d2012-01-05 23:22:43 +00003824 ALOGW("Attempt to retrieve bag 0x%08x which is invalid or in a cycle.",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003825 resID);
3826 return BAD_INDEX;
3827 }
3828 }
3829 }
3830
3831 // Bag not found, we need to compute it!
3832 if (!grp->bags) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003833 grp->bags = new ByteBucketArray<bag_set**>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003834 if (!grp->bags) return NO_MEMORY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003835 }
3836
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003837 bag_set** typeSet = grp->bags->get(t);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003838 if (!typeSet) {
Iliyan Malchev7e1d3952012-02-17 12:15:58 -08003839 typeSet = (bag_set**)calloc(NENTRY, sizeof(bag_set*));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003840 if (!typeSet) return NO_MEMORY;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003841 grp->bags->set(t, typeSet);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003842 }
3843
3844 // Mark that we are currently working on this one.
3845 typeSet[e] = (bag_set*)0xFFFFFFFF;
3846
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003847 TABLE_NOISY(ALOGI("Building bag: %p\n", (void*)resID));
3848
3849 // Now collect all bag attributes
3850 Entry entry;
3851 status_t err = getEntry(grp, t, e, &mParams, &entry);
3852 if (err != NO_ERROR) {
3853 return err;
3854 }
3855
3856 const uint16_t entrySize = dtohs(entry.entry->size);
3857 const uint32_t parent = entrySize >= sizeof(ResTable_map_entry)
3858 ? dtohl(((const ResTable_map_entry*)entry.entry)->parent.ident) : 0;
3859 const uint32_t count = entrySize >= sizeof(ResTable_map_entry)
3860 ? dtohl(((const ResTable_map_entry*)entry.entry)->count) : 0;
3861
3862 size_t N = count;
3863
3864 TABLE_NOISY(ALOGI("Found map: size=%p parent=%p count=%d\n",
3865 entrySize, parent, count));
3866
3867 // If this map inherits from another, we need to start
3868 // with its parent's values. Otherwise start out empty.
3869 TABLE_NOISY(printf("Creating new bag, entrySize=0x%08x, parent=0x%08x\n",
3870 entrySize, parent));
3871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003872 // This is what we are building.
3873 bag_set* set = NULL;
3874
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003875 if (parent) {
3876 uint32_t resolvedParent = parent;
Mark Salyzyn00adb862014-03-19 11:00:06 -07003877
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003878 // Bags encode a parent reference without using the standard
3879 // Res_value structure. That means we must always try to
3880 // resolve a parent reference in case it is actually a
3881 // TYPE_DYNAMIC_REFERENCE.
3882 status_t err = grp->dynamicRefTable.lookupResourceId(&resolvedParent);
3883 if (err != NO_ERROR) {
3884 ALOGE("Failed resolving bag parent id 0x%08x", parent);
3885 return UNKNOWN_ERROR;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01003886 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003887
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003888 const bag_entry* parentBag;
3889 uint32_t parentTypeSpecFlags = 0;
3890 const ssize_t NP = getBagLocked(resolvedParent, &parentBag, &parentTypeSpecFlags);
3891 const size_t NT = ((NP >= 0) ? NP : 0) + N;
3892 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*NT);
3893 if (set == NULL) {
3894 return NO_MEMORY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003895 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003896 if (NP > 0) {
3897 memcpy(set+1, parentBag, NP*sizeof(bag_entry));
3898 set->numAttrs = NP;
3899 TABLE_NOISY(ALOGI("Initialized new bag with %d inherited attributes.\n", NP));
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01003900 } else {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003901 TABLE_NOISY(ALOGI("Initialized new bag with no inherited attributes.\n"));
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01003902 set->numAttrs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003904 set->availAttrs = NT;
3905 set->typeSpecFlags = parentTypeSpecFlags;
3906 } else {
3907 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*N);
3908 if (set == NULL) {
3909 return NO_MEMORY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003910 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003911 set->numAttrs = 0;
3912 set->availAttrs = N;
3913 set->typeSpecFlags = 0;
3914 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07003915
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003916 set->typeSpecFlags |= entry.specFlags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003917
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003918 // Now merge in the new attributes...
3919 size_t curOff = (reinterpret_cast<uintptr_t>(entry.entry) - reinterpret_cast<uintptr_t>(entry.type))
3920 + dtohs(entry.entry->size);
3921 const ResTable_map* map;
3922 bag_entry* entries = (bag_entry*)(set+1);
3923 size_t curEntry = 0;
3924 uint32_t pos = 0;
3925 TABLE_NOISY(ALOGI("Starting with set %p, entries=%p, avail=%d\n",
3926 set, entries, set->availAttrs));
3927 while (pos < count) {
3928 TABLE_NOISY(printf("Now at %p\n", (void*)curOff));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003929
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003930 if (curOff > (dtohl(entry.type->header.size)-sizeof(ResTable_map))) {
3931 ALOGW("ResTable_map at %d is beyond type chunk data %d",
3932 (int)curOff, dtohl(entry.type->header.size));
3933 return BAD_TYPE;
3934 }
3935 map = (const ResTable_map*)(((const uint8_t*)entry.type) + curOff);
3936 N++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003937
Adam Lesinskiccf25c7b2014-08-08 15:32:40 -07003938 uint32_t newName = htodl(map->name.ident);
3939 if (!Res_INTERNALID(newName)) {
3940 // Attributes don't have a resource id as the name. They specify
3941 // other data, which would be wrong to change via a lookup.
3942 if (grp->dynamicRefTable.lookupResourceId(&newName) != NO_ERROR) {
3943 ALOGE("Failed resolving ResTable_map name at %d with ident 0x%08x",
3944 (int) curOff, (int) newName);
3945 return UNKNOWN_ERROR;
3946 }
3947 }
3948
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003949 bool isInside;
3950 uint32_t oldName = 0;
3951 while ((isInside=(curEntry < set->numAttrs))
3952 && (oldName=entries[curEntry].map.name.ident) < newName) {
3953 TABLE_NOISY(printf("#%d: Keeping existing attribute: 0x%08x\n",
3954 curEntry, entries[curEntry].map.name.ident));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003955 curEntry++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003956 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003957
3958 if ((!isInside) || oldName != newName) {
3959 // This is a new attribute... figure out what to do with it.
3960 if (set->numAttrs >= set->availAttrs) {
3961 // Need to alloc more memory...
3962 const size_t newAvail = set->availAttrs+N;
3963 set = (bag_set*)realloc(set,
3964 sizeof(bag_set)
3965 + sizeof(bag_entry)*newAvail);
3966 if (set == NULL) {
3967 return NO_MEMORY;
3968 }
3969 set->availAttrs = newAvail;
3970 entries = (bag_entry*)(set+1);
3971 TABLE_NOISY(printf("Reallocated set %p, entries=%p, avail=%d\n",
3972 set, entries, set->availAttrs));
3973 }
3974 if (isInside) {
3975 // Going in the middle, need to make space.
3976 memmove(entries+curEntry+1, entries+curEntry,
3977 sizeof(bag_entry)*(set->numAttrs-curEntry));
3978 set->numAttrs++;
3979 }
3980 TABLE_NOISY(printf("#%d: Inserting new attribute: 0x%08x\n",
3981 curEntry, newName));
3982 } else {
3983 TABLE_NOISY(printf("#%d: Replacing existing attribute: 0x%08x\n",
3984 curEntry, oldName));
3985 }
3986
3987 bag_entry* cur = entries+curEntry;
3988
3989 cur->stringBlock = entry.package->header->index;
3990 cur->map.name.ident = newName;
3991 cur->map.value.copyFrom_dtoh(map->value);
3992 status_t err = grp->dynamicRefTable.lookupResourceValue(&cur->map.value);
3993 if (err != NO_ERROR) {
3994 ALOGE("Reference item(0x%08x) in bag could not be resolved.", cur->map.value.data);
3995 return UNKNOWN_ERROR;
3996 }
3997
3998 TABLE_NOISY(printf("Setting entry #%d %p: block=%d, name=0x%08x, type=%d, data=0x%08x\n",
3999 curEntry, cur, cur->stringBlock, cur->map.name.ident,
4000 cur->map.value.dataType, cur->map.value.data));
4001
4002 // On to the next!
4003 curEntry++;
4004 pos++;
4005 const size_t size = dtohs(map->value.size);
4006 curOff += size + sizeof(*map)-sizeof(map->value);
4007 };
4008
4009 if (curEntry > set->numAttrs) {
4010 set->numAttrs = curEntry;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 }
4012
4013 // And this is it...
4014 typeSet[e] = set;
4015 if (set) {
4016 if (outTypeSpecFlags != NULL) {
4017 *outTypeSpecFlags = set->typeSpecFlags;
4018 }
4019 *outBag = (bag_entry*)(set+1);
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08004020 TABLE_NOISY(ALOGI("Returning %d attrs\n", set->numAttrs));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004021 return set->numAttrs;
4022 }
4023 return BAD_INDEX;
4024}
4025
4026void ResTable::setParameters(const ResTable_config* params)
4027{
4028 mLock.lock();
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08004029 TABLE_GETENTRY(ALOGI("Setting parameters: %s\n", params->toString().string()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004030 mParams = *params;
4031 for (size_t i=0; i<mPackageGroups.size(); i++) {
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08004032 TABLE_NOISY(ALOGI("CLEARING BAGS FOR GROUP %d!", i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004033 mPackageGroups[i]->clearBagCache();
4034 }
4035 mLock.unlock();
4036}
4037
4038void ResTable::getParameters(ResTable_config* params) const
4039{
4040 mLock.lock();
4041 *params = mParams;
4042 mLock.unlock();
4043}
4044
4045struct id_name_map {
4046 uint32_t id;
4047 size_t len;
4048 char16_t name[6];
4049};
4050
4051const static id_name_map ID_NAMES[] = {
4052 { ResTable_map::ATTR_TYPE, 5, { '^', 't', 'y', 'p', 'e' } },
4053 { ResTable_map::ATTR_L10N, 5, { '^', 'l', '1', '0', 'n' } },
4054 { ResTable_map::ATTR_MIN, 4, { '^', 'm', 'i', 'n' } },
4055 { ResTable_map::ATTR_MAX, 4, { '^', 'm', 'a', 'x' } },
4056 { ResTable_map::ATTR_OTHER, 6, { '^', 'o', 't', 'h', 'e', 'r' } },
4057 { ResTable_map::ATTR_ZERO, 5, { '^', 'z', 'e', 'r', 'o' } },
4058 { ResTable_map::ATTR_ONE, 4, { '^', 'o', 'n', 'e' } },
4059 { ResTable_map::ATTR_TWO, 4, { '^', 't', 'w', 'o' } },
4060 { ResTable_map::ATTR_FEW, 4, { '^', 'f', 'e', 'w' } },
4061 { ResTable_map::ATTR_MANY, 5, { '^', 'm', 'a', 'n', 'y' } },
4062};
4063
4064uint32_t ResTable::identifierForName(const char16_t* name, size_t nameLen,
4065 const char16_t* type, size_t typeLen,
4066 const char16_t* package,
4067 size_t packageLen,
4068 uint32_t* outTypeSpecFlags) const
4069{
4070 TABLE_SUPER_NOISY(printf("Identifier for name: error=%d\n", mError));
4071
4072 // Check for internal resource identifier as the very first thing, so
4073 // that we will always find them even when there are no resources.
4074 if (name[0] == '^') {
4075 const int N = (sizeof(ID_NAMES)/sizeof(ID_NAMES[0]));
4076 size_t len;
4077 for (int i=0; i<N; i++) {
4078 const id_name_map* m = ID_NAMES + i;
4079 len = m->len;
4080 if (len != nameLen) {
4081 continue;
4082 }
4083 for (size_t j=1; j<len; j++) {
4084 if (m->name[j] != name[j]) {
4085 goto nope;
4086 }
4087 }
Dianne Hackborn426431a2011-06-09 11:29:08 -07004088 if (outTypeSpecFlags) {
4089 *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC;
4090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004091 return m->id;
4092nope:
4093 ;
4094 }
4095 if (nameLen > 7) {
4096 if (name[1] == 'i' && name[2] == 'n'
4097 && name[3] == 'd' && name[4] == 'e' && name[5] == 'x'
4098 && name[6] == '_') {
4099 int index = atoi(String8(name + 7, nameLen - 7).string());
4100 if (Res_CHECKID(index)) {
Steve Block8564c8d2012-01-05 23:22:43 +00004101 ALOGW("Array resource index: %d is too large.",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004102 index);
4103 return 0;
4104 }
Dianne Hackborn426431a2011-06-09 11:29:08 -07004105 if (outTypeSpecFlags) {
4106 *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC;
4107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004108 return Res_MAKEARRAY(index);
4109 }
4110 }
4111 return 0;
4112 }
4113
4114 if (mError != NO_ERROR) {
4115 return 0;
4116 }
4117
Dianne Hackborn426431a2011-06-09 11:29:08 -07004118 bool fakePublic = false;
4119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004120 // Figure out the package and type we are looking in...
4121
4122 const char16_t* packageEnd = NULL;
4123 const char16_t* typeEnd = NULL;
4124 const char16_t* const nameEnd = name+nameLen;
4125 const char16_t* p = name;
4126 while (p < nameEnd) {
4127 if (*p == ':') packageEnd = p;
4128 else if (*p == '/') typeEnd = p;
4129 p++;
4130 }
Dianne Hackborn426431a2011-06-09 11:29:08 -07004131 if (*name == '@') {
4132 name++;
4133 if (*name == '*') {
4134 fakePublic = true;
4135 name++;
4136 }
4137 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004138 if (name >= nameEnd) {
4139 return 0;
4140 }
4141
4142 if (packageEnd) {
4143 package = name;
4144 packageLen = packageEnd-name;
4145 name = packageEnd+1;
4146 } else if (!package) {
4147 return 0;
4148 }
4149
4150 if (typeEnd) {
4151 type = name;
4152 typeLen = typeEnd-name;
4153 name = typeEnd+1;
4154 } else if (!type) {
4155 return 0;
4156 }
4157
4158 if (name >= nameEnd) {
4159 return 0;
4160 }
4161 nameLen = nameEnd-name;
4162
4163 TABLE_NOISY(printf("Looking for identifier: type=%s, name=%s, package=%s\n",
4164 String8(type, typeLen).string(),
4165 String8(name, nameLen).string(),
4166 String8(package, packageLen).string()));
4167
4168 const size_t NG = mPackageGroups.size();
4169 for (size_t ig=0; ig<NG; ig++) {
4170 const PackageGroup* group = mPackageGroups[ig];
4171
4172 if (strzcmp16(package, packageLen,
4173 group->name.string(), group->name.size())) {
4174 TABLE_NOISY(printf("Skipping package group: %s\n", String8(group->name).string()));
4175 continue;
4176 }
4177
Adam Lesinskie60a87f2014-10-09 11:08:04 -07004178 const size_t packageCount = group->packages.size();
4179 for (size_t pi = 0; pi < packageCount; pi++) {
4180 ssize_t ti = group->packages[pi]->typeStrings.indexOfString(type, typeLen);
4181 if (ti < 0) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004182 continue;
4183 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004184
Adam Lesinskie60a87f2014-10-09 11:08:04 -07004185 ti += group->packages[pi]->typeIdOffset;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004186
Adam Lesinskie60a87f2014-10-09 11:08:04 -07004187 const TypeList& typeList = group->types[ti];
4188 if (typeList.isEmpty()) {
4189 TABLE_NOISY(printf("Expected type structure not found in package %s for index %d\n",
4190 String8(group->name).string(), ti));
4191 continue;
4192 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004193
Adam Lesinskie60a87f2014-10-09 11:08:04 -07004194 const size_t typeCount = typeList.size();
4195 for (size_t i = 0; i < typeCount; i++) {
4196 const Type* t = typeList[i];
4197 const ssize_t ei = t->package->keyStrings.indexOfString(name, nameLen);
4198 if (ei < 0) {
4199 continue;
4200 }
4201
4202 const size_t configCount = t->configs.size();
4203 for (size_t j = 0; j < configCount; j++) {
4204 const TypeVariant tv(t->configs[j]);
4205 for (TypeVariant::iterator iter = tv.beginEntries();
4206 iter != tv.endEntries();
4207 iter++) {
4208 const ResTable_entry* entry = *iter;
4209 if (entry == NULL) {
4210 continue;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004211 }
Adam Lesinskie60a87f2014-10-09 11:08:04 -07004212
4213 if (dtohl(entry->key.index) == (size_t) ei) {
4214 uint32_t resId = Res_MAKEID(group->id - 1, ti, iter.index());
4215 if (outTypeSpecFlags) {
4216 Entry result;
4217 if (getEntry(group, ti, iter.index(), NULL, &result) != NO_ERROR) {
4218 ALOGW("Failed to find spec flags for %s:%s/%s (0x%08x)",
4219 String8(group->name).string(),
4220 String8(String16(type, typeLen)).string(),
4221 String8(String16(name, nameLen)).string(),
4222 resId);
4223 return 0;
4224 }
4225 *outTypeSpecFlags = result.specFlags;
4226
4227 if (fakePublic) {
4228 *outTypeSpecFlags |= ResTable_typeSpec::SPEC_PUBLIC;
4229 }
4230 }
4231 return resId;
4232 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004234 }
4235 }
4236 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004237 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004238 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004239 return 0;
4240}
4241
Adam Lesinski4bf58102014-11-03 11:21:19 -08004242bool ResTable::expandResourceRef(const char16_t* refStr, size_t refLen,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004243 String16* outPackage,
4244 String16* outType,
4245 String16* outName,
4246 const String16* defType,
4247 const String16* defPackage,
Dianne Hackborn426431a2011-06-09 11:29:08 -07004248 const char** outErrorMsg,
4249 bool* outPublicOnly)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004250{
4251 const char16_t* packageEnd = NULL;
4252 const char16_t* typeEnd = NULL;
4253 const char16_t* p = refStr;
4254 const char16_t* const end = p + refLen;
4255 while (p < end) {
4256 if (*p == ':') packageEnd = p;
4257 else if (*p == '/') {
4258 typeEnd = p;
4259 break;
4260 }
4261 p++;
4262 }
4263 p = refStr;
4264 if (*p == '@') p++;
4265
Dianne Hackborn426431a2011-06-09 11:29:08 -07004266 if (outPublicOnly != NULL) {
4267 *outPublicOnly = true;
4268 }
4269 if (*p == '*') {
4270 p++;
4271 if (outPublicOnly != NULL) {
4272 *outPublicOnly = false;
4273 }
4274 }
4275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004276 if (packageEnd) {
4277 *outPackage = String16(p, packageEnd-p);
4278 p = packageEnd+1;
4279 } else {
4280 if (!defPackage) {
4281 if (outErrorMsg) {
4282 *outErrorMsg = "No resource package specified";
4283 }
4284 return false;
4285 }
4286 *outPackage = *defPackage;
4287 }
4288 if (typeEnd) {
4289 *outType = String16(p, typeEnd-p);
4290 p = typeEnd+1;
4291 } else {
4292 if (!defType) {
4293 if (outErrorMsg) {
4294 *outErrorMsg = "No resource type specified";
4295 }
4296 return false;
4297 }
4298 *outType = *defType;
4299 }
4300 *outName = String16(p, end-p);
Konstantin Lopyrevddcafcb2010-06-04 14:36:49 -07004301 if(**outPackage == 0) {
4302 if(outErrorMsg) {
4303 *outErrorMsg = "Resource package cannot be an empty string";
4304 }
4305 return false;
4306 }
4307 if(**outType == 0) {
4308 if(outErrorMsg) {
4309 *outErrorMsg = "Resource type cannot be an empty string";
4310 }
4311 return false;
4312 }
4313 if(**outName == 0) {
4314 if(outErrorMsg) {
4315 *outErrorMsg = "Resource id cannot be an empty string";
4316 }
4317 return false;
4318 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004319 return true;
4320}
4321
4322static uint32_t get_hex(char c, bool* outError)
4323{
4324 if (c >= '0' && c <= '9') {
4325 return c - '0';
4326 } else if (c >= 'a' && c <= 'f') {
4327 return c - 'a' + 0xa;
4328 } else if (c >= 'A' && c <= 'F') {
4329 return c - 'A' + 0xa;
4330 }
4331 *outError = true;
4332 return 0;
4333}
4334
4335struct unit_entry
4336{
4337 const char* name;
4338 size_t len;
4339 uint8_t type;
4340 uint32_t unit;
4341 float scale;
4342};
4343
4344static const unit_entry unitNames[] = {
4345 { "px", strlen("px"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PX, 1.0f },
4346 { "dip", strlen("dip"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
4347 { "dp", strlen("dp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
4348 { "sp", strlen("sp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_SP, 1.0f },
4349 { "pt", strlen("pt"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PT, 1.0f },
4350 { "in", strlen("in"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_IN, 1.0f },
4351 { "mm", strlen("mm"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_MM, 1.0f },
4352 { "%", strlen("%"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION, 1.0f/100 },
4353 { "%p", strlen("%p"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION_PARENT, 1.0f/100 },
4354 { NULL, 0, 0, 0, 0 }
4355};
4356
4357static bool parse_unit(const char* str, Res_value* outValue,
4358 float* outScale, const char** outEnd)
4359{
4360 const char* end = str;
4361 while (*end != 0 && !isspace((unsigned char)*end)) {
4362 end++;
4363 }
4364 const size_t len = end-str;
4365
4366 const char* realEnd = end;
4367 while (*realEnd != 0 && isspace((unsigned char)*realEnd)) {
4368 realEnd++;
4369 }
4370 if (*realEnd != 0) {
4371 return false;
4372 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07004373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004374 const unit_entry* cur = unitNames;
4375 while (cur->name) {
4376 if (len == cur->len && strncmp(cur->name, str, len) == 0) {
4377 outValue->dataType = cur->type;
4378 outValue->data = cur->unit << Res_value::COMPLEX_UNIT_SHIFT;
4379 *outScale = cur->scale;
4380 *outEnd = end;
4381 //printf("Found unit %s for %s\n", cur->name, str);
4382 return true;
4383 }
4384 cur++;
4385 }
4386
4387 return false;
4388}
4389
4390
4391bool ResTable::stringToInt(const char16_t* s, size_t len, Res_value* outValue)
4392{
4393 while (len > 0 && isspace16(*s)) {
4394 s++;
4395 len--;
4396 }
4397
4398 if (len <= 0) {
4399 return false;
4400 }
4401
4402 size_t i = 0;
4403 int32_t val = 0;
4404 bool neg = false;
4405
4406 if (*s == '-') {
4407 neg = true;
4408 i++;
4409 }
4410
4411 if (s[i] < '0' || s[i] > '9') {
4412 return false;
4413 }
4414
4415 // Decimal or hex?
4416 if (s[i] == '0' && s[i+1] == 'x') {
4417 if (outValue)
4418 outValue->dataType = outValue->TYPE_INT_HEX;
4419 i += 2;
4420 bool error = false;
4421 while (i < len && !error) {
4422 val = (val*16) + get_hex(s[i], &error);
4423 i++;
4424 }
4425 if (error) {
4426 return false;
4427 }
4428 } else {
4429 if (outValue)
4430 outValue->dataType = outValue->TYPE_INT_DEC;
4431 while (i < len) {
4432 if (s[i] < '0' || s[i] > '9') {
4433 return false;
4434 }
4435 val = (val*10) + s[i]-'0';
4436 i++;
4437 }
4438 }
4439
4440 if (neg) val = -val;
4441
4442 while (i < len && isspace16(s[i])) {
4443 i++;
4444 }
4445
4446 if (i == len) {
4447 if (outValue)
4448 outValue->data = val;
4449 return true;
4450 }
4451
4452 return false;
4453}
4454
4455bool ResTable::stringToFloat(const char16_t* s, size_t len, Res_value* outValue)
4456{
4457 while (len > 0 && isspace16(*s)) {
4458 s++;
4459 len--;
4460 }
4461
4462 if (len <= 0) {
4463 return false;
4464 }
4465
4466 char buf[128];
4467 int i=0;
4468 while (len > 0 && *s != 0 && i < 126) {
4469 if (*s > 255) {
4470 return false;
4471 }
4472 buf[i++] = *s++;
4473 len--;
4474 }
4475
4476 if (len > 0) {
4477 return false;
4478 }
4479 if (buf[0] < '0' && buf[0] > '9' && buf[0] != '.') {
4480 return false;
4481 }
4482
4483 buf[i] = 0;
4484 const char* end;
4485 float f = strtof(buf, (char**)&end);
4486
4487 if (*end != 0 && !isspace((unsigned char)*end)) {
4488 // Might be a unit...
4489 float scale;
4490 if (parse_unit(end, outValue, &scale, &end)) {
4491 f *= scale;
4492 const bool neg = f < 0;
4493 if (neg) f = -f;
4494 uint64_t bits = (uint64_t)(f*(1<<23)+.5f);
4495 uint32_t radix;
4496 uint32_t shift;
4497 if ((bits&0x7fffff) == 0) {
4498 // Always use 23p0 if there is no fraction, just to make
4499 // things easier to read.
4500 radix = Res_value::COMPLEX_RADIX_23p0;
4501 shift = 23;
4502 } else if ((bits&0xffffffffff800000LL) == 0) {
4503 // Magnitude is zero -- can fit in 0 bits of precision.
4504 radix = Res_value::COMPLEX_RADIX_0p23;
4505 shift = 0;
4506 } else if ((bits&0xffffffff80000000LL) == 0) {
4507 // Magnitude can fit in 8 bits of precision.
4508 radix = Res_value::COMPLEX_RADIX_8p15;
4509 shift = 8;
4510 } else if ((bits&0xffffff8000000000LL) == 0) {
4511 // Magnitude can fit in 16 bits of precision.
4512 radix = Res_value::COMPLEX_RADIX_16p7;
4513 shift = 16;
4514 } else {
4515 // Magnitude needs entire range, so no fractional part.
4516 radix = Res_value::COMPLEX_RADIX_23p0;
4517 shift = 23;
4518 }
4519 int32_t mantissa = (int32_t)(
4520 (bits>>shift) & Res_value::COMPLEX_MANTISSA_MASK);
4521 if (neg) {
4522 mantissa = (-mantissa) & Res_value::COMPLEX_MANTISSA_MASK;
4523 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07004524 outValue->data |=
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004525 (radix<<Res_value::COMPLEX_RADIX_SHIFT)
4526 | (mantissa<<Res_value::COMPLEX_MANTISSA_SHIFT);
4527 //printf("Input value: %f 0x%016Lx, mult: %f, radix: %d, shift: %d, final: 0x%08x\n",
4528 // f * (neg ? -1 : 1), bits, f*(1<<23),
4529 // radix, shift, outValue->data);
4530 return true;
4531 }
4532 return false;
4533 }
4534
4535 while (*end != 0 && isspace((unsigned char)*end)) {
4536 end++;
4537 }
4538
4539 if (*end == 0) {
4540 if (outValue) {
4541 outValue->dataType = outValue->TYPE_FLOAT;
4542 *(float*)(&outValue->data) = f;
4543 return true;
4544 }
4545 }
4546
4547 return false;
4548}
4549
4550bool ResTable::stringToValue(Res_value* outValue, String16* outString,
4551 const char16_t* s, size_t len,
4552 bool preserveSpaces, bool coerceType,
4553 uint32_t attrID,
4554 const String16* defType,
4555 const String16* defPackage,
4556 Accessor* accessor,
4557 void* accessorCookie,
4558 uint32_t attrType,
4559 bool enforcePrivate) const
4560{
4561 bool localizationSetting = accessor != NULL && accessor->getLocalizationSetting();
4562 const char* errorMsg = NULL;
4563
4564 outValue->size = sizeof(Res_value);
4565 outValue->res0 = 0;
4566
4567 // First strip leading/trailing whitespace. Do this before handling
4568 // escapes, so they can be used to force whitespace into the string.
4569 if (!preserveSpaces) {
4570 while (len > 0 && isspace16(*s)) {
4571 s++;
4572 len--;
4573 }
4574 while (len > 0 && isspace16(s[len-1])) {
4575 len--;
4576 }
4577 // If the string ends with '\', then we keep the space after it.
4578 if (len > 0 && s[len-1] == '\\' && s[len] != 0) {
4579 len++;
4580 }
4581 }
4582
4583 //printf("Value for: %s\n", String8(s, len).string());
4584
4585 uint32_t l10nReq = ResTable_map::L10N_NOT_REQUIRED;
4586 uint32_t attrMin = 0x80000000, attrMax = 0x7fffffff;
4587 bool fromAccessor = false;
4588 if (attrID != 0 && !Res_INTERNALID(attrID)) {
4589 const ssize_t p = getResourcePackageIndex(attrID);
4590 const bag_entry* bag;
4591 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
4592 //printf("For attr 0x%08x got bag of %d\n", attrID, cnt);
4593 if (cnt >= 0) {
4594 while (cnt > 0) {
4595 //printf("Entry 0x%08x = 0x%08x\n", bag->map.name.ident, bag->map.value.data);
4596 switch (bag->map.name.ident) {
4597 case ResTable_map::ATTR_TYPE:
4598 attrType = bag->map.value.data;
4599 break;
4600 case ResTable_map::ATTR_MIN:
4601 attrMin = bag->map.value.data;
4602 break;
4603 case ResTable_map::ATTR_MAX:
4604 attrMax = bag->map.value.data;
4605 break;
4606 case ResTable_map::ATTR_L10N:
4607 l10nReq = bag->map.value.data;
4608 break;
4609 }
4610 bag++;
4611 cnt--;
4612 }
4613 unlockBag(bag);
4614 } else if (accessor && accessor->getAttributeType(attrID, &attrType)) {
4615 fromAccessor = true;
4616 if (attrType == ResTable_map::TYPE_ENUM
4617 || attrType == ResTable_map::TYPE_FLAGS
4618 || attrType == ResTable_map::TYPE_INTEGER) {
4619 accessor->getAttributeMin(attrID, &attrMin);
4620 accessor->getAttributeMax(attrID, &attrMax);
4621 }
4622 if (localizationSetting) {
4623 l10nReq = accessor->getAttributeL10N(attrID);
4624 }
4625 }
4626 }
4627
4628 const bool canStringCoerce =
4629 coerceType && (attrType&ResTable_map::TYPE_STRING) != 0;
4630
4631 if (*s == '@') {
4632 outValue->dataType = outValue->TYPE_REFERENCE;
4633
4634 // Note: we don't check attrType here because the reference can
4635 // be to any other type; we just need to count on the client making
4636 // sure the referenced type is correct.
Mark Salyzyn00adb862014-03-19 11:00:06 -07004637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004638 //printf("Looking up ref: %s\n", String8(s, len).string());
4639
4640 // It's a reference!
4641 if (len == 5 && s[1]=='n' && s[2]=='u' && s[3]=='l' && s[4]=='l') {
4642 outValue->data = 0;
4643 return true;
4644 } else {
4645 bool createIfNotFound = false;
4646 const char16_t* resourceRefName;
4647 int resourceNameLen;
4648 if (len > 2 && s[1] == '+') {
4649 createIfNotFound = true;
4650 resourceRefName = s + 2;
4651 resourceNameLen = len - 2;
4652 } else if (len > 2 && s[1] == '*') {
4653 enforcePrivate = false;
4654 resourceRefName = s + 2;
4655 resourceNameLen = len - 2;
4656 } else {
4657 createIfNotFound = false;
4658 resourceRefName = s + 1;
4659 resourceNameLen = len - 1;
4660 }
4661 String16 package, type, name;
4662 if (!expandResourceRef(resourceRefName,resourceNameLen, &package, &type, &name,
4663 defType, defPackage, &errorMsg)) {
4664 if (accessor != NULL) {
4665 accessor->reportError(accessorCookie, errorMsg);
4666 }
4667 return false;
4668 }
4669
4670 uint32_t specFlags = 0;
4671 uint32_t rid = identifierForName(name.string(), name.size(), type.string(),
4672 type.size(), package.string(), package.size(), &specFlags);
4673 if (rid != 0) {
4674 if (enforcePrivate) {
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004675 if (accessor == NULL || accessor->getAssetsPackage() != package) {
4676 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
4677 if (accessor != NULL) {
4678 accessor->reportError(accessorCookie, "Resource is not public.");
4679 }
4680 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004682 }
4683 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08004684
4685 if (accessor) {
4686 rid = Res_MAKEID(
4687 accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
4688 Res_GETTYPE(rid), Res_GETENTRY(rid));
4689 TABLE_NOISY(printf("Incl %s:%s/%s: 0x%08x\n",
4690 String8(package).string(), String8(type).string(),
4691 String8(name).string(), rid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004692 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08004693
4694 uint32_t packageId = Res_GETPACKAGE(rid) + 1;
4695 if (packageId != APP_PACKAGE_ID && packageId != SYS_PACKAGE_ID) {
4696 outValue->dataType = Res_value::TYPE_DYNAMIC_REFERENCE;
4697 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004698 outValue->data = rid;
4699 return true;
4700 }
4701
4702 if (accessor) {
4703 uint32_t rid = accessor->getCustomResourceWithCreation(package, type, name,
4704 createIfNotFound);
4705 if (rid != 0) {
4706 TABLE_NOISY(printf("Pckg %s:%s/%s: 0x%08x\n",
4707 String8(package).string(), String8(type).string(),
4708 String8(name).string(), rid));
Adam Lesinskide898ff2014-01-29 18:20:45 -08004709 uint32_t packageId = Res_GETPACKAGE(rid) + 1;
4710 if (packageId == 0x00) {
4711 outValue->data = rid;
4712 outValue->dataType = Res_value::TYPE_DYNAMIC_REFERENCE;
4713 return true;
4714 } else if (packageId == APP_PACKAGE_ID || packageId == SYS_PACKAGE_ID) {
4715 // We accept packageId's generated as 0x01 in order to support
4716 // building the android system resources
4717 outValue->data = rid;
4718 return true;
4719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004720 }
4721 }
4722 }
4723
4724 if (accessor != NULL) {
4725 accessor->reportError(accessorCookie, "No resource found that matches the given name");
4726 }
4727 return false;
4728 }
4729
4730 // if we got to here, and localization is required and it's not a reference,
4731 // complain and bail.
4732 if (l10nReq == ResTable_map::L10N_SUGGESTED) {
4733 if (localizationSetting) {
4734 if (accessor != NULL) {
4735 accessor->reportError(accessorCookie, "This attribute must be localized.");
4736 }
4737 }
4738 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07004739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004740 if (*s == '#') {
4741 // It's a color! Convert to an integer of the form 0xaarrggbb.
4742 uint32_t color = 0;
4743 bool error = false;
4744 if (len == 4) {
4745 outValue->dataType = outValue->TYPE_INT_COLOR_RGB4;
4746 color |= 0xFF000000;
4747 color |= get_hex(s[1], &error) << 20;
4748 color |= get_hex(s[1], &error) << 16;
4749 color |= get_hex(s[2], &error) << 12;
4750 color |= get_hex(s[2], &error) << 8;
4751 color |= get_hex(s[3], &error) << 4;
4752 color |= get_hex(s[3], &error);
4753 } else if (len == 5) {
4754 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB4;
4755 color |= get_hex(s[1], &error) << 28;
4756 color |= get_hex(s[1], &error) << 24;
4757 color |= get_hex(s[2], &error) << 20;
4758 color |= get_hex(s[2], &error) << 16;
4759 color |= get_hex(s[3], &error) << 12;
4760 color |= get_hex(s[3], &error) << 8;
4761 color |= get_hex(s[4], &error) << 4;
4762 color |= get_hex(s[4], &error);
4763 } else if (len == 7) {
4764 outValue->dataType = outValue->TYPE_INT_COLOR_RGB8;
4765 color |= 0xFF000000;
4766 color |= get_hex(s[1], &error) << 20;
4767 color |= get_hex(s[2], &error) << 16;
4768 color |= get_hex(s[3], &error) << 12;
4769 color |= get_hex(s[4], &error) << 8;
4770 color |= get_hex(s[5], &error) << 4;
4771 color |= get_hex(s[6], &error);
4772 } else if (len == 9) {
4773 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB8;
4774 color |= get_hex(s[1], &error) << 28;
4775 color |= get_hex(s[2], &error) << 24;
4776 color |= get_hex(s[3], &error) << 20;
4777 color |= get_hex(s[4], &error) << 16;
4778 color |= get_hex(s[5], &error) << 12;
4779 color |= get_hex(s[6], &error) << 8;
4780 color |= get_hex(s[7], &error) << 4;
4781 color |= get_hex(s[8], &error);
4782 } else {
4783 error = true;
4784 }
4785 if (!error) {
4786 if ((attrType&ResTable_map::TYPE_COLOR) == 0) {
4787 if (!canStringCoerce) {
4788 if (accessor != NULL) {
4789 accessor->reportError(accessorCookie,
4790 "Color types not allowed");
4791 }
4792 return false;
4793 }
4794 } else {
4795 outValue->data = color;
4796 //printf("Color input=%s, output=0x%x\n", String8(s, len).string(), color);
4797 return true;
4798 }
4799 } else {
4800 if ((attrType&ResTable_map::TYPE_COLOR) != 0) {
4801 if (accessor != NULL) {
4802 accessor->reportError(accessorCookie, "Color value not valid --"
4803 " must be #rgb, #argb, #rrggbb, or #aarrggbb");
4804 }
4805 #if 0
4806 fprintf(stderr, "%s: Color ID %s value %s is not valid\n",
4807 "Resource File", //(const char*)in->getPrintableSource(),
4808 String8(*curTag).string(),
4809 String8(s, len).string());
4810 #endif
4811 return false;
4812 }
4813 }
4814 }
4815
4816 if (*s == '?') {
4817 outValue->dataType = outValue->TYPE_ATTRIBUTE;
4818
4819 // Note: we don't check attrType here because the reference can
4820 // be to any other type; we just need to count on the client making
4821 // sure the referenced type is correct.
4822
4823 //printf("Looking up attr: %s\n", String8(s, len).string());
4824
4825 static const String16 attr16("attr");
4826 String16 package, type, name;
4827 if (!expandResourceRef(s+1, len-1, &package, &type, &name,
4828 &attr16, defPackage, &errorMsg)) {
4829 if (accessor != NULL) {
4830 accessor->reportError(accessorCookie, errorMsg);
4831 }
4832 return false;
4833 }
4834
4835 //printf("Pkg: %s, Type: %s, Name: %s\n",
4836 // String8(package).string(), String8(type).string(),
4837 // String8(name).string());
4838 uint32_t specFlags = 0;
Mark Salyzyn00adb862014-03-19 11:00:06 -07004839 uint32_t rid =
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004840 identifierForName(name.string(), name.size(),
4841 type.string(), type.size(),
4842 package.string(), package.size(), &specFlags);
4843 if (rid != 0) {
4844 if (enforcePrivate) {
4845 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
4846 if (accessor != NULL) {
4847 accessor->reportError(accessorCookie, "Attribute is not public.");
4848 }
4849 return false;
4850 }
4851 }
4852 if (!accessor) {
4853 outValue->data = rid;
4854 return true;
4855 }
4856 rid = Res_MAKEID(
4857 accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
4858 Res_GETTYPE(rid), Res_GETENTRY(rid));
4859 //printf("Incl %s:%s/%s: 0x%08x\n",
4860 // String8(package).string(), String8(type).string(),
4861 // String8(name).string(), rid);
4862 outValue->data = rid;
4863 return true;
4864 }
4865
4866 if (accessor) {
4867 uint32_t rid = accessor->getCustomResource(package, type, name);
4868 if (rid != 0) {
4869 //printf("Mine %s:%s/%s: 0x%08x\n",
4870 // String8(package).string(), String8(type).string(),
4871 // String8(name).string(), rid);
4872 outValue->data = rid;
4873 return true;
4874 }
4875 }
4876
4877 if (accessor != NULL) {
4878 accessor->reportError(accessorCookie, "No resource found that matches the given name");
4879 }
4880 return false;
4881 }
4882
4883 if (stringToInt(s, len, outValue)) {
4884 if ((attrType&ResTable_map::TYPE_INTEGER) == 0) {
4885 // If this type does not allow integers, but does allow floats,
4886 // fall through on this error case because the float type should
4887 // be able to accept any integer value.
4888 if (!canStringCoerce && (attrType&ResTable_map::TYPE_FLOAT) == 0) {
4889 if (accessor != NULL) {
4890 accessor->reportError(accessorCookie, "Integer types not allowed");
4891 }
4892 return false;
4893 }
4894 } else {
4895 if (((int32_t)outValue->data) < ((int32_t)attrMin)
4896 || ((int32_t)outValue->data) > ((int32_t)attrMax)) {
4897 if (accessor != NULL) {
4898 accessor->reportError(accessorCookie, "Integer value out of range");
4899 }
4900 return false;
4901 }
4902 return true;
4903 }
4904 }
4905
4906 if (stringToFloat(s, len, outValue)) {
4907 if (outValue->dataType == Res_value::TYPE_DIMENSION) {
4908 if ((attrType&ResTable_map::TYPE_DIMENSION) != 0) {
4909 return true;
4910 }
4911 if (!canStringCoerce) {
4912 if (accessor != NULL) {
4913 accessor->reportError(accessorCookie, "Dimension types not allowed");
4914 }
4915 return false;
4916 }
4917 } else if (outValue->dataType == Res_value::TYPE_FRACTION) {
4918 if ((attrType&ResTable_map::TYPE_FRACTION) != 0) {
4919 return true;
4920 }
4921 if (!canStringCoerce) {
4922 if (accessor != NULL) {
4923 accessor->reportError(accessorCookie, "Fraction types not allowed");
4924 }
4925 return false;
4926 }
4927 } else if ((attrType&ResTable_map::TYPE_FLOAT) == 0) {
4928 if (!canStringCoerce) {
4929 if (accessor != NULL) {
4930 accessor->reportError(accessorCookie, "Float types not allowed");
4931 }
4932 return false;
4933 }
4934 } else {
4935 return true;
4936 }
4937 }
4938
4939 if (len == 4) {
4940 if ((s[0] == 't' || s[0] == 'T') &&
4941 (s[1] == 'r' || s[1] == 'R') &&
4942 (s[2] == 'u' || s[2] == 'U') &&
4943 (s[3] == 'e' || s[3] == 'E')) {
4944 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
4945 if (!canStringCoerce) {
4946 if (accessor != NULL) {
4947 accessor->reportError(accessorCookie, "Boolean types not allowed");
4948 }
4949 return false;
4950 }
4951 } else {
4952 outValue->dataType = outValue->TYPE_INT_BOOLEAN;
4953 outValue->data = (uint32_t)-1;
4954 return true;
4955 }
4956 }
4957 }
4958
4959 if (len == 5) {
4960 if ((s[0] == 'f' || s[0] == 'F') &&
4961 (s[1] == 'a' || s[1] == 'A') &&
4962 (s[2] == 'l' || s[2] == 'L') &&
4963 (s[3] == 's' || s[3] == 'S') &&
4964 (s[4] == 'e' || s[4] == 'E')) {
4965 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
4966 if (!canStringCoerce) {
4967 if (accessor != NULL) {
4968 accessor->reportError(accessorCookie, "Boolean types not allowed");
4969 }
4970 return false;
4971 }
4972 } else {
4973 outValue->dataType = outValue->TYPE_INT_BOOLEAN;
4974 outValue->data = 0;
4975 return true;
4976 }
4977 }
4978 }
4979
4980 if ((attrType&ResTable_map::TYPE_ENUM) != 0) {
4981 const ssize_t p = getResourcePackageIndex(attrID);
4982 const bag_entry* bag;
4983 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
4984 //printf("Got %d for enum\n", cnt);
4985 if (cnt >= 0) {
4986 resource_name rname;
4987 while (cnt > 0) {
4988 if (!Res_INTERNALID(bag->map.name.ident)) {
4989 //printf("Trying attr #%08x\n", bag->map.name.ident);
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07004990 if (getResourceName(bag->map.name.ident, false, &rname)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004991 #if 0
4992 printf("Matching %s against %s (0x%08x)\n",
4993 String8(s, len).string(),
4994 String8(rname.name, rname.nameLen).string(),
4995 bag->map.name.ident);
4996 #endif
4997 if (strzcmp16(s, len, rname.name, rname.nameLen) == 0) {
4998 outValue->dataType = bag->map.value.dataType;
4999 outValue->data = bag->map.value.data;
5000 unlockBag(bag);
5001 return true;
5002 }
5003 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005004
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005005 }
5006 bag++;
5007 cnt--;
5008 }
5009 unlockBag(bag);
5010 }
5011
5012 if (fromAccessor) {
5013 if (accessor->getAttributeEnum(attrID, s, len, outValue)) {
5014 return true;
5015 }
5016 }
5017 }
5018
5019 if ((attrType&ResTable_map::TYPE_FLAGS) != 0) {
5020 const ssize_t p = getResourcePackageIndex(attrID);
5021 const bag_entry* bag;
5022 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
5023 //printf("Got %d for flags\n", cnt);
5024 if (cnt >= 0) {
5025 bool failed = false;
5026 resource_name rname;
5027 outValue->dataType = Res_value::TYPE_INT_HEX;
5028 outValue->data = 0;
5029 const char16_t* end = s + len;
5030 const char16_t* pos = s;
5031 while (pos < end && !failed) {
5032 const char16_t* start = pos;
The Android Open Source Project4df24232009-03-05 14:34:35 -08005033 pos++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005034 while (pos < end && *pos != '|') {
5035 pos++;
5036 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08005037 //printf("Looking for: %s\n", String8(start, pos-start).string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005038 const bag_entry* bagi = bag;
The Android Open Source Project4df24232009-03-05 14:34:35 -08005039 ssize_t i;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005040 for (i=0; i<cnt; i++, bagi++) {
5041 if (!Res_INTERNALID(bagi->map.name.ident)) {
5042 //printf("Trying attr #%08x\n", bagi->map.name.ident);
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07005043 if (getResourceName(bagi->map.name.ident, false, &rname)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005044 #if 0
5045 printf("Matching %s against %s (0x%08x)\n",
5046 String8(start,pos-start).string(),
5047 String8(rname.name, rname.nameLen).string(),
5048 bagi->map.name.ident);
5049 #endif
5050 if (strzcmp16(start, pos-start, rname.name, rname.nameLen) == 0) {
5051 outValue->data |= bagi->map.value.data;
5052 break;
5053 }
5054 }
5055 }
5056 }
5057 if (i >= cnt) {
5058 // Didn't find this flag identifier.
5059 failed = true;
5060 }
5061 if (pos < end) {
5062 pos++;
5063 }
5064 }
5065 unlockBag(bag);
5066 if (!failed) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08005067 //printf("Final flag value: 0x%lx\n", outValue->data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005068 return true;
5069 }
5070 }
5071
5072
5073 if (fromAccessor) {
5074 if (accessor->getAttributeFlags(attrID, s, len, outValue)) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08005075 //printf("Final flag value: 0x%lx\n", outValue->data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005076 return true;
5077 }
5078 }
5079 }
5080
5081 if ((attrType&ResTable_map::TYPE_STRING) == 0) {
5082 if (accessor != NULL) {
5083 accessor->reportError(accessorCookie, "String types not allowed");
5084 }
5085 return false;
5086 }
5087
5088 // Generic string handling...
5089 outValue->dataType = outValue->TYPE_STRING;
5090 if (outString) {
5091 bool failed = collectString(outString, s, len, preserveSpaces, &errorMsg);
5092 if (accessor != NULL) {
5093 accessor->reportError(accessorCookie, errorMsg);
5094 }
5095 return failed;
5096 }
5097
5098 return true;
5099}
5100
5101bool ResTable::collectString(String16* outString,
5102 const char16_t* s, size_t len,
5103 bool preserveSpaces,
5104 const char** outErrorMsg,
5105 bool append)
5106{
5107 String16 tmp;
5108
5109 char quoted = 0;
5110 const char16_t* p = s;
5111 while (p < (s+len)) {
5112 while (p < (s+len)) {
5113 const char16_t c = *p;
5114 if (c == '\\') {
5115 break;
5116 }
5117 if (!preserveSpaces) {
5118 if (quoted == 0 && isspace16(c)
5119 && (c != ' ' || isspace16(*(p+1)))) {
5120 break;
5121 }
5122 if (c == '"' && (quoted == 0 || quoted == '"')) {
5123 break;
5124 }
5125 if (c == '\'' && (quoted == 0 || quoted == '\'')) {
Eric Fischerc87d2522009-09-01 15:20:30 -07005126 /*
5127 * In practice, when people write ' instead of \'
5128 * in a string, they are doing it by accident
5129 * instead of really meaning to use ' as a quoting
5130 * character. Warn them so they don't lose it.
5131 */
5132 if (outErrorMsg) {
5133 *outErrorMsg = "Apostrophe not preceded by \\";
5134 }
5135 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005136 }
5137 }
5138 p++;
5139 }
5140 if (p < (s+len)) {
5141 if (p > s) {
5142 tmp.append(String16(s, p-s));
5143 }
5144 if (!preserveSpaces && (*p == '"' || *p == '\'')) {
5145 if (quoted == 0) {
5146 quoted = *p;
5147 } else {
5148 quoted = 0;
5149 }
5150 p++;
5151 } else if (!preserveSpaces && isspace16(*p)) {
5152 // Space outside of a quote -- consume all spaces and
5153 // leave a single plain space char.
5154 tmp.append(String16(" "));
5155 p++;
5156 while (p < (s+len) && isspace16(*p)) {
5157 p++;
5158 }
5159 } else if (*p == '\\') {
5160 p++;
5161 if (p < (s+len)) {
5162 switch (*p) {
5163 case 't':
5164 tmp.append(String16("\t"));
5165 break;
5166 case 'n':
5167 tmp.append(String16("\n"));
5168 break;
5169 case '#':
5170 tmp.append(String16("#"));
5171 break;
5172 case '@':
5173 tmp.append(String16("@"));
5174 break;
5175 case '?':
5176 tmp.append(String16("?"));
5177 break;
5178 case '"':
5179 tmp.append(String16("\""));
5180 break;
5181 case '\'':
5182 tmp.append(String16("'"));
5183 break;
5184 case '\\':
5185 tmp.append(String16("\\"));
5186 break;
5187 case 'u':
5188 {
5189 char16_t chr = 0;
5190 int i = 0;
5191 while (i < 4 && p[1] != 0) {
5192 p++;
5193 i++;
5194 int c;
5195 if (*p >= '0' && *p <= '9') {
5196 c = *p - '0';
5197 } else if (*p >= 'a' && *p <= 'f') {
5198 c = *p - 'a' + 10;
5199 } else if (*p >= 'A' && *p <= 'F') {
5200 c = *p - 'A' + 10;
5201 } else {
5202 if (outErrorMsg) {
5203 *outErrorMsg = "Bad character in \\u unicode escape sequence";
5204 }
5205 return false;
5206 }
5207 chr = (chr<<4) | c;
5208 }
5209 tmp.append(String16(&chr, 1));
5210 } break;
5211 default:
5212 // ignore unknown escape chars.
5213 break;
5214 }
5215 p++;
5216 }
5217 }
5218 len -= (p-s);
5219 s = p;
5220 }
5221 }
5222
5223 if (tmp.size() != 0) {
5224 if (len > 0) {
5225 tmp.append(String16(s, len));
5226 }
5227 if (append) {
5228 outString->append(tmp);
5229 } else {
5230 outString->setTo(tmp);
5231 }
5232 } else {
5233 if (append) {
5234 outString->append(String16(s, len));
5235 } else {
5236 outString->setTo(s, len);
5237 }
5238 }
5239
5240 return true;
5241}
5242
5243size_t ResTable::getBasePackageCount() const
5244{
5245 if (mError != NO_ERROR) {
5246 return 0;
5247 }
5248 return mPackageGroups.size();
5249}
5250
Adam Lesinskide898ff2014-01-29 18:20:45 -08005251const String16 ResTable::getBasePackageName(size_t idx) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005252{
5253 if (mError != NO_ERROR) {
Adam Lesinskide898ff2014-01-29 18:20:45 -08005254 return String16();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005255 }
5256 LOG_FATAL_IF(idx >= mPackageGroups.size(),
5257 "Requested package index %d past package count %d",
5258 (int)idx, (int)mPackageGroups.size());
Adam Lesinskide898ff2014-01-29 18:20:45 -08005259 return mPackageGroups[idx]->name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005260}
5261
5262uint32_t ResTable::getBasePackageId(size_t idx) const
5263{
5264 if (mError != NO_ERROR) {
5265 return 0;
5266 }
5267 LOG_FATAL_IF(idx >= mPackageGroups.size(),
5268 "Requested package index %d past package count %d",
5269 (int)idx, (int)mPackageGroups.size());
5270 return mPackageGroups[idx]->id;
5271}
5272
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005273uint32_t ResTable::getLastTypeIdForPackage(size_t idx) const
5274{
5275 if (mError != NO_ERROR) {
5276 return 0;
5277 }
5278 LOG_FATAL_IF(idx >= mPackageGroups.size(),
5279 "Requested package index %d past package count %d",
5280 (int)idx, (int)mPackageGroups.size());
5281 const PackageGroup* const group = mPackageGroups[idx];
5282 return group->largestTypeId;
5283}
5284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005285size_t ResTable::getTableCount() const
5286{
5287 return mHeaders.size();
5288}
5289
5290const ResStringPool* ResTable::getTableStringBlock(size_t index) const
5291{
5292 return &mHeaders[index]->values;
5293}
5294
Narayan Kamath7c4887f2014-01-27 17:32:37 +00005295int32_t ResTable::getTableCookie(size_t index) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005296{
5297 return mHeaders[index]->cookie;
5298}
5299
Adam Lesinskide898ff2014-01-29 18:20:45 -08005300const DynamicRefTable* ResTable::getDynamicRefTableForCookie(int32_t cookie) const
5301{
5302 const size_t N = mPackageGroups.size();
5303 for (size_t i = 0; i < N; i++) {
5304 const PackageGroup* pg = mPackageGroups[i];
5305 size_t M = pg->packages.size();
5306 for (size_t j = 0; j < M; j++) {
5307 if (pg->packages[j]->header->cookie == cookie) {
5308 return &pg->dynamicRefTable;
5309 }
5310 }
5311 }
5312 return NULL;
5313}
5314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005315void ResTable::getConfigurations(Vector<ResTable_config>* configs) const
5316{
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005317 const size_t packageCount = mPackageGroups.size();
5318 for (size_t i = 0; i < packageCount; i++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005319 const PackageGroup* packageGroup = mPackageGroups[i];
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005320 const size_t typeCount = packageGroup->types.size();
5321 for (size_t j = 0; j < typeCount; j++) {
5322 const TypeList& typeList = packageGroup->types[j];
5323 const size_t numTypes = typeList.size();
5324 for (size_t k = 0; k < numTypes; k++) {
5325 const Type* type = typeList[k];
5326 const size_t numConfigs = type->configs.size();
5327 for (size_t m = 0; m < numConfigs; m++) {
5328 const ResTable_type* config = type->configs[m];
Narayan Kamath788fa412014-01-21 15:32:36 +00005329 ResTable_config cfg;
5330 memset(&cfg, 0, sizeof(ResTable_config));
5331 cfg.copyFromDtoH(config->config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005332 // only insert unique
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005333 const size_t N = configs->size();
5334 size_t n;
5335 for (n = 0; n < N; n++) {
5336 if (0 == (*configs)[n].compare(cfg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005337 break;
5338 }
5339 }
5340 // if we didn't find it
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005341 if (n == N) {
Narayan Kamath788fa412014-01-21 15:32:36 +00005342 configs->add(cfg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005343 }
5344 }
5345 }
5346 }
5347 }
5348}
5349
5350void ResTable::getLocales(Vector<String8>* locales) const
5351{
5352 Vector<ResTable_config> configs;
Steve Block71f2cf12011-10-20 11:56:00 +01005353 ALOGV("calling getConfigurations");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005354 getConfigurations(&configs);
Steve Block71f2cf12011-10-20 11:56:00 +01005355 ALOGV("called getConfigurations size=%d", (int)configs.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005356 const size_t I = configs.size();
Narayan Kamath48620f12014-01-20 13:57:11 +00005357
5358 char locale[RESTABLE_MAX_LOCALE_LEN];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005359 for (size_t i=0; i<I; i++) {
Narayan Kamath788fa412014-01-21 15:32:36 +00005360 configs[i].getBcp47Locale(locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005361 const size_t J = locales->size();
5362 size_t j;
5363 for (j=0; j<J; j++) {
5364 if (0 == strcmp(locale, (*locales)[j].string())) {
5365 break;
5366 }
5367 }
5368 if (j == J) {
5369 locales->add(String8(locale));
5370 }
5371 }
5372}
5373
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005374StringPoolRef::StringPoolRef(const ResStringPool* pool, uint32_t index)
5375 : mPool(pool), mIndex(index) {}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005376
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005377StringPoolRef::StringPoolRef()
5378 : mPool(NULL), mIndex(0) {}
5379
5380const char* StringPoolRef::string8(size_t* outLen) const {
5381 if (mPool != NULL) {
5382 return mPool->string8At(mIndex, outLen);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005383 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005384 if (outLen != NULL) {
5385 *outLen = 0;
5386 }
5387 return NULL;
5388}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005389
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005390const char16_t* StringPoolRef::string16(size_t* outLen) const {
5391 if (mPool != NULL) {
5392 return mPool->stringAt(mIndex, outLen);
5393 }
5394 if (outLen != NULL) {
5395 *outLen = 0;
5396 }
5397 return NULL;
5398}
5399
Adam Lesinski82a2dd82014-09-17 18:34:15 -07005400bool ResTable::getResourceFlags(uint32_t resID, uint32_t* outFlags) const {
5401 if (mError != NO_ERROR) {
5402 return false;
5403 }
5404
5405 const ssize_t p = getResourcePackageIndex(resID);
5406 const int t = Res_GETTYPE(resID);
5407 const int e = Res_GETENTRY(resID);
5408
5409 if (p < 0) {
5410 if (Res_GETPACKAGE(resID)+1 == 0) {
5411 ALOGW("No package identifier when getting flags for resource number 0x%08x", resID);
5412 } else {
5413 ALOGW("No known package when getting flags for resource number 0x%08x", resID);
5414 }
5415 return false;
5416 }
5417 if (t < 0) {
5418 ALOGW("No type identifier when getting flags for resource number 0x%08x", resID);
5419 return false;
5420 }
5421
5422 const PackageGroup* const grp = mPackageGroups[p];
5423 if (grp == NULL) {
5424 ALOGW("Bad identifier when getting flags for resource number 0x%08x", resID);
5425 return false;
5426 }
5427
5428 Entry entry;
5429 status_t err = getEntry(grp, t, e, NULL, &entry);
5430 if (err != NO_ERROR) {
5431 return false;
5432 }
5433
5434 *outFlags = entry.specFlags;
5435 return true;
5436}
5437
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005438status_t ResTable::getEntry(
5439 const PackageGroup* packageGroup, int typeIndex, int entryIndex,
5440 const ResTable_config* config,
5441 Entry* outEntry) const
5442{
5443 const TypeList& typeList = packageGroup->types[typeIndex];
5444 if (typeList.isEmpty()) {
5445 ALOGV("Skipping entry type index 0x%02x because type is NULL!\n", typeIndex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005446 return BAD_TYPE;
5447 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005448
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005449 const ResTable_type* bestType = NULL;
5450 uint32_t bestOffset = ResTable_type::NO_ENTRY;
5451 const Package* bestPackage = NULL;
5452 uint32_t specFlags = 0;
5453 uint8_t actualTypeIndex = typeIndex;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005454 ResTable_config bestConfig;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005455 memset(&bestConfig, 0, sizeof(bestConfig));
Mark Salyzyn00adb862014-03-19 11:00:06 -07005456
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005457 // Iterate over the Types of each package.
5458 const size_t typeCount = typeList.size();
5459 for (size_t i = 0; i < typeCount; i++) {
5460 const Type* const typeSpec = typeList[i];
Mark Salyzyn00adb862014-03-19 11:00:06 -07005461
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005462 int realEntryIndex = entryIndex;
5463 int realTypeIndex = typeIndex;
5464 bool currentTypeIsOverlay = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005465
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005466 // Runtime overlay packages provide a mapping of app resource
5467 // ID to package resource ID.
5468 if (typeSpec->idmapEntries.hasEntries()) {
5469 uint16_t overlayEntryIndex;
5470 if (typeSpec->idmapEntries.lookup(entryIndex, &overlayEntryIndex) != NO_ERROR) {
5471 // No such mapping exists
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005472 continue;
5473 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005474 realEntryIndex = overlayEntryIndex;
5475 realTypeIndex = typeSpec->idmapEntries.overlayTypeId() - 1;
5476 currentTypeIsOverlay = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005477 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005478
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005479 if (static_cast<size_t>(realEntryIndex) >= typeSpec->entryCount) {
5480 ALOGW("For resource 0x%08x, entry index(%d) is beyond type entryCount(%d)",
5481 Res_MAKEID(packageGroup->id - 1, typeIndex, entryIndex),
5482 entryIndex, static_cast<int>(typeSpec->entryCount));
5483 // We should normally abort here, but some legacy apps declare
5484 // resources in the 'android' package (old bug in AAPT).
5485 continue;
5486 }
5487
5488 // Aggregate all the flags for each package that defines this entry.
5489 if (typeSpec->typeSpecFlags != NULL) {
5490 specFlags |= dtohl(typeSpec->typeSpecFlags[realEntryIndex]);
5491 } else {
5492 specFlags = -1;
5493 }
5494
5495 const size_t numConfigs = typeSpec->configs.size();
5496 for (size_t c = 0; c < numConfigs; c++) {
5497 const ResTable_type* const thisType = typeSpec->configs[c];
5498 if (thisType == NULL) {
5499 continue;
5500 }
5501
5502 ResTable_config thisConfig;
5503 thisConfig.copyFromDtoH(thisType->config);
5504
5505 // Check to make sure this one is valid for the current parameters.
5506 if (config != NULL && !thisConfig.match(*config)) {
5507 continue;
5508 }
5509
5510 // Check if there is the desired entry in this type.
5511 const uint8_t* const end = reinterpret_cast<const uint8_t*>(thisType)
5512 + dtohl(thisType->header.size);
5513 const uint32_t* const eindex = reinterpret_cast<const uint32_t*>(
5514 reinterpret_cast<const uint8_t*>(thisType) + dtohs(thisType->header.headerSize));
5515
5516 uint32_t thisOffset = dtohl(eindex[realEntryIndex]);
5517 if (thisOffset == ResTable_type::NO_ENTRY) {
5518 // There is no entry for this index and configuration.
5519 continue;
5520 }
5521
5522 if (bestType != NULL) {
5523 // Check if this one is less specific than the last found. If so,
5524 // we will skip it. We check starting with things we most care
5525 // about to those we least care about.
5526 if (!thisConfig.isBetterThan(bestConfig, config)) {
5527 if (!currentTypeIsOverlay || thisConfig.compare(bestConfig) != 0) {
5528 continue;
5529 }
5530 }
5531 }
5532
5533 bestType = thisType;
5534 bestOffset = thisOffset;
5535 bestConfig = thisConfig;
5536 bestPackage = typeSpec->package;
5537 actualTypeIndex = realTypeIndex;
5538
5539 // If no config was specified, any type will do, so skip
5540 if (config == NULL) {
5541 break;
5542 }
5543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005544 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005545
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005546 if (bestType == NULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005547 return BAD_INDEX;
5548 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005549
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005550 bestOffset += dtohl(bestType->entriesStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005551
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005552 if (bestOffset > (dtohl(bestType->header.size)-sizeof(ResTable_entry))) {
Steve Block8564c8d2012-01-05 23:22:43 +00005553 ALOGW("ResTable_entry at 0x%x is beyond type chunk data 0x%x",
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005554 bestOffset, dtohl(bestType->header.size));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005555 return BAD_TYPE;
5556 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005557 if ((bestOffset & 0x3) != 0) {
5558 ALOGW("ResTable_entry at 0x%x is not on an integer boundary", bestOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005559 return BAD_TYPE;
5560 }
5561
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005562 const ResTable_entry* const entry = reinterpret_cast<const ResTable_entry*>(
5563 reinterpret_cast<const uint8_t*>(bestType) + bestOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005564 if (dtohs(entry->size) < sizeof(*entry)) {
Steve Block8564c8d2012-01-05 23:22:43 +00005565 ALOGW("ResTable_entry size 0x%x is too small", dtohs(entry->size));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005566 return BAD_TYPE;
5567 }
5568
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005569 if (outEntry != NULL) {
5570 outEntry->entry = entry;
5571 outEntry->config = bestConfig;
5572 outEntry->type = bestType;
5573 outEntry->specFlags = specFlags;
5574 outEntry->package = bestPackage;
5575 outEntry->typeStr = StringPoolRef(&bestPackage->typeStrings, actualTypeIndex - bestPackage->typeIdOffset);
5576 outEntry->keyStr = StringPoolRef(&bestPackage->keyStrings, dtohl(entry->key.index));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005577 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005578 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005579}
5580
5581status_t ResTable::parsePackage(const ResTable_package* const pkg,
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005582 const Header* const header)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005583{
5584 const uint8_t* base = (const uint8_t*)pkg;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005585 status_t err = validate_chunk(&pkg->header, sizeof(*pkg) - sizeof(pkg->typeIdOffset),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005586 header->dataEnd, "ResTable_package");
5587 if (err != NO_ERROR) {
5588 return (mError=err);
5589 }
5590
Patrik Bannura443dd932014-02-12 13:38:54 +01005591 const uint32_t pkgSize = dtohl(pkg->header.size);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005592
5593 if (dtohl(pkg->typeStrings) >= pkgSize) {
Patrik Bannura443dd932014-02-12 13:38:54 +01005594 ALOGW("ResTable_package type strings at 0x%x are past chunk size 0x%x.",
5595 dtohl(pkg->typeStrings), pkgSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005596 return (mError=BAD_TYPE);
5597 }
5598 if ((dtohl(pkg->typeStrings)&0x3) != 0) {
Patrik Bannura443dd932014-02-12 13:38:54 +01005599 ALOGW("ResTable_package type strings at 0x%x is not on an integer boundary.",
5600 dtohl(pkg->typeStrings));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005601 return (mError=BAD_TYPE);
5602 }
5603 if (dtohl(pkg->keyStrings) >= pkgSize) {
Patrik Bannura443dd932014-02-12 13:38:54 +01005604 ALOGW("ResTable_package key strings at 0x%x are past chunk size 0x%x.",
5605 dtohl(pkg->keyStrings), pkgSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005606 return (mError=BAD_TYPE);
5607 }
5608 if ((dtohl(pkg->keyStrings)&0x3) != 0) {
Patrik Bannura443dd932014-02-12 13:38:54 +01005609 ALOGW("ResTable_package key strings at 0x%x is not on an integer boundary.",
5610 dtohl(pkg->keyStrings));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005611 return (mError=BAD_TYPE);
5612 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005613
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005614 uint32_t id = dtohl(pkg->id);
5615 KeyedVector<uint8_t, IdmapEntries> idmapEntries;
Mark Salyzyn00adb862014-03-19 11:00:06 -07005616
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005617 if (header->resourceIDMap != NULL) {
5618 uint8_t targetPackageId = 0;
5619 status_t err = parseIdmap(header->resourceIDMap, header->resourceIDMapSize, &targetPackageId, &idmapEntries);
5620 if (err != NO_ERROR) {
5621 ALOGW("Overlay is broken");
5622 return (mError=err);
5623 }
5624 id = targetPackageId;
5625 }
5626
5627 if (id >= 256) {
5628 LOG_ALWAYS_FATAL("Package id out of range");
5629 return NO_ERROR;
5630 } else if (id == 0) {
5631 // This is a library so assign an ID
5632 id = mNextPackageId++;
5633 }
5634
5635 PackageGroup* group = NULL;
5636 Package* package = new Package(this, header, pkg);
5637 if (package == NULL) {
5638 return (mError=NO_MEMORY);
5639 }
5640
5641 err = package->typeStrings.setTo(base+dtohl(pkg->typeStrings),
5642 header->dataEnd-(base+dtohl(pkg->typeStrings)));
5643 if (err != NO_ERROR) {
5644 delete group;
5645 delete package;
5646 return (mError=err);
5647 }
5648
5649 err = package->keyStrings.setTo(base+dtohl(pkg->keyStrings),
5650 header->dataEnd-(base+dtohl(pkg->keyStrings)));
5651 if (err != NO_ERROR) {
5652 delete group;
5653 delete package;
5654 return (mError=err);
5655 }
5656
5657 size_t idx = mPackageMap[id];
5658 if (idx == 0) {
5659 idx = mPackageGroups.size() + 1;
5660
Adam Lesinski4bf58102014-11-03 11:21:19 -08005661 char16_t tmpName[sizeof(pkg->name)/sizeof(pkg->name[0])];
5662 strcpy16_dtoh(tmpName, pkg->name, sizeof(pkg->name)/sizeof(pkg->name[0]));
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005663 group = new PackageGroup(this, String16(tmpName), id);
5664 if (group == NULL) {
5665 delete package;
Dianne Hackborn78c40512009-07-06 11:07:40 -07005666 return (mError=NO_MEMORY);
5667 }
Adam Lesinskifab50872014-04-16 14:40:42 -07005668
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005669 err = mPackageGroups.add(group);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005670 if (err < NO_ERROR) {
5671 return (mError=err);
5672 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005673
5674 mPackageMap[id] = static_cast<uint8_t>(idx);
5675
5676 // Find all packages that reference this package
5677 size_t N = mPackageGroups.size();
5678 for (size_t i = 0; i < N; i++) {
5679 mPackageGroups[i]->dynamicRefTable.addMapping(
5680 group->name, static_cast<uint8_t>(group->id));
5681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005682 } else {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005683 group = mPackageGroups.itemAt(idx - 1);
5684 if (group == NULL) {
5685 return (mError=UNKNOWN_ERROR);
5686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005687 }
5688
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005689 err = group->packages.add(package);
5690 if (err < NO_ERROR) {
5691 return (mError=err);
5692 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005694 // Iterate through all chunks.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005695 const ResChunk_header* chunk =
5696 (const ResChunk_header*)(((const uint8_t*)pkg)
5697 + dtohs(pkg->header.headerSize));
5698 const uint8_t* endPos = ((const uint8_t*)pkg) + dtohs(pkg->header.size);
5699 while (((const uint8_t*)chunk) <= (endPos-sizeof(ResChunk_header)) &&
5700 ((const uint8_t*)chunk) <= (endPos-dtohl(chunk->size))) {
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08005701 TABLE_NOISY(ALOGV("PackageChunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005702 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
5703 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header))));
5704 const size_t csize = dtohl(chunk->size);
5705 const uint16_t ctype = dtohs(chunk->type);
5706 if (ctype == RES_TABLE_TYPE_SPEC_TYPE) {
5707 const ResTable_typeSpec* typeSpec = (const ResTable_typeSpec*)(chunk);
5708 err = validate_chunk(&typeSpec->header, sizeof(*typeSpec),
5709 endPos, "ResTable_typeSpec");
5710 if (err != NO_ERROR) {
5711 return (mError=err);
5712 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005714 const size_t typeSpecSize = dtohl(typeSpec->header.size);
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005715 const size_t newEntryCount = dtohl(typeSpec->entryCount);
Mark Salyzyn00adb862014-03-19 11:00:06 -07005716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005717 LOAD_TABLE_NOISY(printf("TypeSpec off %p: type=0x%x, headerSize=0x%x, size=%p\n",
5718 (void*)(base-(const uint8_t*)chunk),
5719 dtohs(typeSpec->header.type),
5720 dtohs(typeSpec->header.headerSize),
Adam Lesinskide898ff2014-01-29 18:20:45 -08005721 (void*)typeSpecSize));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005722 // look for block overrun or int overflow when multiplying by 4
5723 if ((dtohl(typeSpec->entryCount) > (INT32_MAX/sizeof(uint32_t))
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005724 || dtohs(typeSpec->header.headerSize)+(sizeof(uint32_t)*newEntryCount)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005725 > typeSpecSize)) {
Steve Block8564c8d2012-01-05 23:22:43 +00005726 ALOGW("ResTable_typeSpec entry index to %p extends beyond chunk end %p.",
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005727 (void*)(dtohs(typeSpec->header.headerSize) + (sizeof(uint32_t)*newEntryCount)),
5728 (void*)typeSpecSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005729 return (mError=BAD_TYPE);
5730 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005732 if (typeSpec->id == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005733 ALOGW("ResTable_type has an id of 0.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005734 return (mError=BAD_TYPE);
5735 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005736
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005737 if (newEntryCount > 0) {
5738 uint8_t typeIndex = typeSpec->id - 1;
5739 ssize_t idmapIndex = idmapEntries.indexOfKey(typeSpec->id);
5740 if (idmapIndex >= 0) {
5741 typeIndex = idmapEntries[idmapIndex].targetTypeId() - 1;
5742 }
5743
5744 TypeList& typeList = group->types.editItemAt(typeIndex);
5745 if (!typeList.isEmpty()) {
5746 const Type* existingType = typeList[0];
5747 if (existingType->entryCount != newEntryCount && idmapIndex < 0) {
5748 ALOGW("ResTable_typeSpec entry count inconsistent: given %d, previously %d",
5749 (int) newEntryCount, (int) existingType->entryCount);
5750 // We should normally abort here, but some legacy apps declare
5751 // resources in the 'android' package (old bug in AAPT).
5752 }
5753 }
5754
5755 Type* t = new Type(header, package, newEntryCount);
5756 t->typeSpec = typeSpec;
5757 t->typeSpecFlags = (const uint32_t*)(
5758 ((const uint8_t*)typeSpec) + dtohs(typeSpec->header.headerSize));
5759 if (idmapIndex >= 0) {
5760 t->idmapEntries = idmapEntries[idmapIndex];
5761 }
5762 typeList.add(t);
5763 group->largestTypeId = max(group->largestTypeId, typeSpec->id);
5764 } else {
5765 ALOGV("Skipping empty ResTable_typeSpec for type %d", typeSpec->id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005766 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005768 } else if (ctype == RES_TABLE_TYPE_TYPE) {
5769 const ResTable_type* type = (const ResTable_type*)(chunk);
5770 err = validate_chunk(&type->header, sizeof(*type)-sizeof(ResTable_config)+4,
5771 endPos, "ResTable_type");
5772 if (err != NO_ERROR) {
5773 return (mError=err);
5774 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005775
Patrik Bannura443dd932014-02-12 13:38:54 +01005776 const uint32_t typeSize = dtohl(type->header.size);
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005777 const size_t newEntryCount = dtohl(type->entryCount);
Mark Salyzyn00adb862014-03-19 11:00:06 -07005778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005779 LOAD_TABLE_NOISY(printf("Type off %p: type=0x%x, headerSize=0x%x, size=%p\n",
5780 (void*)(base-(const uint8_t*)chunk),
5781 dtohs(type->header.type),
5782 dtohs(type->header.headerSize),
5783 (void*)typeSize));
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005784 if (dtohs(type->header.headerSize)+(sizeof(uint32_t)*newEntryCount)
5785 > typeSize) {
Patrik Bannura443dd932014-02-12 13:38:54 +01005786 ALOGW("ResTable_type entry index to %p extends beyond chunk end 0x%x.",
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005787 (void*)(dtohs(type->header.headerSize) + (sizeof(uint32_t)*newEntryCount)),
5788 typeSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005789 return (mError=BAD_TYPE);
5790 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005791
5792 if (newEntryCount != 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005793 && dtohl(type->entriesStart) > (typeSize-sizeof(ResTable_entry))) {
Patrik Bannura443dd932014-02-12 13:38:54 +01005794 ALOGW("ResTable_type entriesStart at 0x%x extends beyond chunk end 0x%x.",
5795 dtohl(type->entriesStart), typeSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005796 return (mError=BAD_TYPE);
5797 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005799 if (type->id == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005800 ALOGW("ResTable_type has an id of 0.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005801 return (mError=BAD_TYPE);
5802 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005803
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005804 if (newEntryCount > 0) {
5805 uint8_t typeIndex = type->id - 1;
5806 ssize_t idmapIndex = idmapEntries.indexOfKey(type->id);
5807 if (idmapIndex >= 0) {
5808 typeIndex = idmapEntries[idmapIndex].targetTypeId() - 1;
5809 }
5810
5811 TypeList& typeList = group->types.editItemAt(typeIndex);
5812 if (typeList.isEmpty()) {
5813 ALOGE("No TypeSpec for type %d", type->id);
5814 return (mError=BAD_TYPE);
5815 }
5816
5817 Type* t = typeList.editItemAt(typeList.size() - 1);
5818 if (newEntryCount != t->entryCount) {
5819 ALOGE("ResTable_type entry count inconsistent: given %d, previously %d",
5820 (int)newEntryCount, (int)t->entryCount);
5821 return (mError=BAD_TYPE);
5822 }
5823
5824 if (t->package != package) {
5825 ALOGE("No TypeSpec for type %d", type->id);
5826 return (mError=BAD_TYPE);
5827 }
5828
5829 t->configs.add(type);
5830
5831 TABLE_GETENTRY(
5832 ResTable_config thisConfig;
5833 thisConfig.copyFromDtoH(type->config);
5834 ALOGI("Adding config to type %d: %s\n",
5835 type->id, thisConfig.toString().string()));
5836 } else {
5837 ALOGV("Skipping empty ResTable_type for type %d", type->id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005838 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005839
Adam Lesinskide898ff2014-01-29 18:20:45 -08005840 } else if (ctype == RES_TABLE_LIBRARY_TYPE) {
5841 if (group->dynamicRefTable.entries().size() == 0) {
5842 status_t err = group->dynamicRefTable.load((const ResTable_lib_header*) chunk);
5843 if (err != NO_ERROR) {
5844 return (mError=err);
5845 }
5846
5847 // Fill in the reference table with the entries we already know about.
5848 size_t N = mPackageGroups.size();
5849 for (size_t i = 0; i < N; i++) {
5850 group->dynamicRefTable.addMapping(mPackageGroups[i]->name, mPackageGroups[i]->id);
5851 }
5852 } else {
5853 ALOGW("Found multiple library tables, ignoring...");
5854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005855 } else {
5856 status_t err = validate_chunk(chunk, sizeof(ResChunk_header),
5857 endPos, "ResTable_package:unknown");
5858 if (err != NO_ERROR) {
5859 return (mError=err);
5860 }
5861 }
5862 chunk = (const ResChunk_header*)
5863 (((const uint8_t*)chunk) + csize);
5864 }
5865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005866 return NO_ERROR;
5867}
5868
Adam Lesinskide898ff2014-01-29 18:20:45 -08005869DynamicRefTable::DynamicRefTable(uint8_t packageId)
5870 : mAssignedPackageId(packageId)
5871{
5872 memset(mLookupTable, 0, sizeof(mLookupTable));
5873
5874 // Reserved package ids
5875 mLookupTable[APP_PACKAGE_ID] = APP_PACKAGE_ID;
5876 mLookupTable[SYS_PACKAGE_ID] = SYS_PACKAGE_ID;
5877}
5878
5879status_t DynamicRefTable::load(const ResTable_lib_header* const header)
5880{
5881 const uint32_t entryCount = dtohl(header->count);
5882 const uint32_t sizeOfEntries = sizeof(ResTable_lib_entry) * entryCount;
5883 const uint32_t expectedSize = dtohl(header->header.size) - dtohl(header->header.headerSize);
5884 if (sizeOfEntries > expectedSize) {
5885 ALOGE("ResTable_lib_header size %u is too small to fit %u entries (x %u).",
5886 expectedSize, entryCount, (uint32_t)sizeof(ResTable_lib_entry));
5887 return UNKNOWN_ERROR;
5888 }
5889
5890 const ResTable_lib_entry* entry = (const ResTable_lib_entry*)(((uint8_t*) header) +
5891 dtohl(header->header.headerSize));
5892 for (uint32_t entryIndex = 0; entryIndex < entryCount; entryIndex++) {
5893 uint32_t packageId = dtohl(entry->packageId);
5894 char16_t tmpName[sizeof(entry->packageName) / sizeof(char16_t)];
5895 strcpy16_dtoh(tmpName, entry->packageName, sizeof(entry->packageName) / sizeof(char16_t));
5896 LIB_NOISY(ALOGV("Found lib entry %s with id %d\n", String8(tmpName).string(),
5897 dtohl(entry->packageId)));
5898 if (packageId >= 256) {
5899 ALOGE("Bad package id 0x%08x", packageId);
5900 return UNKNOWN_ERROR;
5901 }
5902 mEntries.replaceValueFor(String16(tmpName), (uint8_t) packageId);
5903 entry = entry + 1;
5904 }
5905 return NO_ERROR;
5906}
5907
Adam Lesinski6022deb2014-08-20 14:59:19 -07005908status_t DynamicRefTable::addMappings(const DynamicRefTable& other) {
5909 if (mAssignedPackageId != other.mAssignedPackageId) {
5910 return UNKNOWN_ERROR;
5911 }
5912
5913 const size_t entryCount = other.mEntries.size();
5914 for (size_t i = 0; i < entryCount; i++) {
5915 ssize_t index = mEntries.indexOfKey(other.mEntries.keyAt(i));
5916 if (index < 0) {
5917 mEntries.add(other.mEntries.keyAt(i), other.mEntries[i]);
5918 } else {
5919 if (other.mEntries[i] != mEntries[index]) {
5920 return UNKNOWN_ERROR;
5921 }
5922 }
5923 }
5924
5925 // Merge the lookup table. No entry can conflict
5926 // (value of 0 means not set).
5927 for (size_t i = 0; i < 256; i++) {
5928 if (mLookupTable[i] != other.mLookupTable[i]) {
5929 if (mLookupTable[i] == 0) {
5930 mLookupTable[i] = other.mLookupTable[i];
5931 } else if (other.mLookupTable[i] != 0) {
5932 return UNKNOWN_ERROR;
5933 }
5934 }
5935 }
5936 return NO_ERROR;
5937}
5938
Adam Lesinskide898ff2014-01-29 18:20:45 -08005939status_t DynamicRefTable::addMapping(const String16& packageName, uint8_t packageId)
5940{
5941 ssize_t index = mEntries.indexOfKey(packageName);
5942 if (index < 0) {
5943 return UNKNOWN_ERROR;
5944 }
5945 mLookupTable[mEntries.valueAt(index)] = packageId;
5946 return NO_ERROR;
5947}
5948
5949status_t DynamicRefTable::lookupResourceId(uint32_t* resId) const {
5950 uint32_t res = *resId;
5951 size_t packageId = Res_GETPACKAGE(res) + 1;
5952
5953 if (packageId == APP_PACKAGE_ID) {
5954 // No lookup needs to be done, app package IDs are absolute.
5955 return NO_ERROR;
5956 }
5957
5958 if (packageId == 0) {
5959 // The package ID is 0x00. That means that a shared library is accessing
5960 // its own local resource, so we fix up the resource with the calling
5961 // package ID.
5962 *resId |= ((uint32_t) mAssignedPackageId) << 24;
5963 return NO_ERROR;
5964 }
5965
5966 // Do a proper lookup.
5967 uint8_t translatedId = mLookupTable[packageId];
5968 if (translatedId == 0) {
Adam Lesinskiccf25c7b2014-08-08 15:32:40 -07005969 ALOGE("DynamicRefTable(0x%02x): No mapping for build-time package ID 0x%02x.",
Adam Lesinskide898ff2014-01-29 18:20:45 -08005970 (uint8_t)mAssignedPackageId, (uint8_t)packageId);
5971 for (size_t i = 0; i < 256; i++) {
5972 if (mLookupTable[i] != 0) {
Adam Lesinskiccf25c7b2014-08-08 15:32:40 -07005973 ALOGE("e[0x%02x] -> 0x%02x", (uint8_t)i, mLookupTable[i]);
Adam Lesinskide898ff2014-01-29 18:20:45 -08005974 }
5975 }
5976 return UNKNOWN_ERROR;
5977 }
5978
5979 *resId = (res & 0x00ffffff) | (((uint32_t) translatedId) << 24);
5980 return NO_ERROR;
5981}
5982
5983status_t DynamicRefTable::lookupResourceValue(Res_value* value) const {
5984 if (value->dataType != Res_value::TYPE_DYNAMIC_REFERENCE) {
5985 return NO_ERROR;
5986 }
5987
5988 status_t err = lookupResourceId(&value->data);
5989 if (err != NO_ERROR) {
5990 return err;
5991 }
5992
5993 value->dataType = Res_value::TYPE_REFERENCE;
5994 return NO_ERROR;
5995}
5996
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005997struct IdmapTypeMap {
5998 ssize_t overlayTypeId;
5999 size_t entryOffset;
6000 Vector<uint32_t> entryMap;
6001};
6002
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006003status_t ResTable::createIdmap(const ResTable& overlay,
6004 uint32_t targetCrc, uint32_t overlayCrc,
6005 const char* targetPath, const char* overlayPath,
6006 void** outData, size_t* outSize) const
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006007{
6008 // see README for details on the format of map
6009 if (mPackageGroups.size() == 0) {
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006010 ALOGW("idmap: target package has no package groups, cannot create idmap\n");
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006011 return UNKNOWN_ERROR;
6012 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006013
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006014 if (mPackageGroups[0]->packages.size() == 0) {
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006015 ALOGW("idmap: target package has no packages in its first package group, "
6016 "cannot create idmap\n");
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006017 return UNKNOWN_ERROR;
6018 }
6019
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006020 KeyedVector<uint8_t, IdmapTypeMap> map;
6021
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006022 // overlaid packages are assumed to contain only one package group
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006023 const PackageGroup* pg = mPackageGroups[0];
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006024
6025 // starting size is header
6026 *outSize = ResTable::IDMAP_HEADER_SIZE_BYTES;
6027
6028 // target package id and number of types in map
6029 *outSize += 2 * sizeof(uint16_t);
6030
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006031 // overlay packages are assumed to contain only one package group
Adam Lesinski4bf58102014-11-03 11:21:19 -08006032 const ResTable_package* overlayPackageStruct = overlay.mPackageGroups[0]->packages[0]->package;
6033 char16_t tmpName[sizeof(overlayPackageStruct->name)/sizeof(overlayPackageStruct->name[0])];
6034 strcpy16_dtoh(tmpName, overlayPackageStruct->name, sizeof(overlayPackageStruct->name)/sizeof(overlayPackageStruct->name[0]));
6035 const String16 overlayPackage(tmpName);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006036
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006037 for (size_t typeIndex = 0; typeIndex < pg->types.size(); ++typeIndex) {
6038 const TypeList& typeList = pg->types[typeIndex];
6039 if (typeList.isEmpty()) {
6040 continue;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006041 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006042
6043 const Type* typeConfigs = typeList[0];
6044
6045 IdmapTypeMap typeMap;
6046 typeMap.overlayTypeId = -1;
6047 typeMap.entryOffset = 0;
6048
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006049 for (size_t entryIndex = 0; entryIndex < typeConfigs->entryCount; ++entryIndex) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006050 uint32_t resID = Res_MAKEID(pg->id - 1, typeIndex, entryIndex);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006051 resource_name resName;
MÃ¥rten Kongstad65a05fd2014-01-31 14:01:52 +01006052 if (!this->getResourceName(resID, false, &resName)) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006053 if (typeMap.entryMap.isEmpty()) {
6054 typeMap.entryOffset++;
6055 }
MÃ¥rten Kongstadfcaba142011-05-19 16:02:35 +02006056 continue;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006057 }
6058
6059 const String16 overlayType(resName.type, resName.typeLen);
6060 const String16 overlayName(resName.name, resName.nameLen);
6061 uint32_t overlayResID = overlay.identifierForName(overlayName.string(),
6062 overlayName.size(),
6063 overlayType.string(),
6064 overlayType.size(),
6065 overlayPackage.string(),
6066 overlayPackage.size());
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006067 if (overlayResID == 0) {
6068 if (typeMap.entryMap.isEmpty()) {
6069 typeMap.entryOffset++;
Jean-Baptiste Queru3e2d5912012-05-01 10:00:22 -07006070 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006071 continue;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006072 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006073
6074 if (typeMap.overlayTypeId == -1) {
6075 typeMap.overlayTypeId = Res_GETTYPE(overlayResID) + 1;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006076 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006077
6078 if (Res_GETTYPE(overlayResID) + 1 != static_cast<size_t>(typeMap.overlayTypeId)) {
6079 ALOGE("idmap: can't mix type ids in entry map. Resource 0x%08x maps to 0x%08x"
6080 " but entries should map to resources of type %02x",
6081 resID, overlayResID, typeMap.overlayTypeId);
6082 return BAD_TYPE;
6083 }
6084
6085 if (typeMap.entryOffset + typeMap.entryMap.size() < entryIndex) {
6086 // Resize to accomodate this entry and the 0's in between.
6087 if (typeMap.entryMap.resize((entryIndex - typeMap.entryOffset) + 1) < 0) {
6088 return NO_MEMORY;
6089 }
6090 typeMap.entryMap.editTop() = Res_GETENTRY(overlayResID);
6091 } else {
6092 typeMap.entryMap.add(Res_GETENTRY(overlayResID));
6093 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006094 }
6095
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006096 if (!typeMap.entryMap.isEmpty()) {
6097 if (map.add(static_cast<uint8_t>(typeIndex), typeMap) < 0) {
6098 return NO_MEMORY;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006099 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006100 *outSize += (4 * sizeof(uint16_t)) + (typeMap.entryMap.size() * sizeof(uint32_t));
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006101 }
6102 }
6103
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006104 if (map.isEmpty()) {
6105 ALOGW("idmap: no resources in overlay package present in base package");
6106 return UNKNOWN_ERROR;
6107 }
6108
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006109 if ((*outData = malloc(*outSize)) == NULL) {
6110 return NO_MEMORY;
6111 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006112
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006113 uint32_t* data = (uint32_t*)*outData;
6114 *data++ = htodl(IDMAP_MAGIC);
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006115 *data++ = htodl(IDMAP_CURRENT_VERSION);
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006116 *data++ = htodl(targetCrc);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006117 *data++ = htodl(overlayCrc);
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006118 const char* paths[] = { targetPath, overlayPath };
6119 for (int j = 0; j < 2; ++j) {
6120 char* p = (char*)data;
6121 const char* path = paths[j];
6122 const size_t I = strlen(path);
6123 if (I > 255) {
6124 ALOGV("path exceeds expected 255 characters: %s\n", path);
6125 return UNKNOWN_ERROR;
6126 }
6127 for (size_t i = 0; i < 256; ++i) {
6128 *p++ = i < I ? path[i] : '\0';
6129 }
6130 data += 256 / sizeof(uint32_t);
6131 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006132 const size_t mapSize = map.size();
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006133 uint16_t* typeData = reinterpret_cast<uint16_t*>(data);
6134 *typeData++ = htods(pg->id);
6135 *typeData++ = htods(mapSize);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006136 for (size_t i = 0; i < mapSize; ++i) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006137 uint8_t targetTypeId = map.keyAt(i);
6138 const IdmapTypeMap& typeMap = map[i];
6139 *typeData++ = htods(targetTypeId + 1);
6140 *typeData++ = htods(typeMap.overlayTypeId);
6141 *typeData++ = htods(typeMap.entryMap.size());
6142 *typeData++ = htods(typeMap.entryOffset);
6143
6144 const size_t entryCount = typeMap.entryMap.size();
6145 uint32_t* entries = reinterpret_cast<uint32_t*>(typeData);
6146 for (size_t j = 0; j < entryCount; j++) {
6147 entries[j] = htodl(typeMap.entryMap[j]);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006148 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006149 typeData += entryCount * 2;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006150 }
6151
6152 return NO_ERROR;
6153}
6154
6155bool ResTable::getIdmapInfo(const void* idmap, size_t sizeBytes,
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006156 uint32_t* pVersion,
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006157 uint32_t* pTargetCrc, uint32_t* pOverlayCrc,
6158 String8* pTargetPath, String8* pOverlayPath)
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006159{
6160 const uint32_t* map = (const uint32_t*)idmap;
6161 if (!assertIdmapHeader(map, sizeBytes)) {
6162 return false;
6163 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006164 if (pVersion) {
6165 *pVersion = dtohl(map[1]);
6166 }
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006167 if (pTargetCrc) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006168 *pTargetCrc = dtohl(map[2]);
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006169 }
6170 if (pOverlayCrc) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006171 *pOverlayCrc = dtohl(map[3]);
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006172 }
6173 if (pTargetPath) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006174 pTargetPath->setTo(reinterpret_cast<const char*>(map + 4));
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006175 }
6176 if (pOverlayPath) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006177 pOverlayPath->setTo(reinterpret_cast<const char*>(map + 4 + 256 / sizeof(uint32_t)));
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006178 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006179 return true;
6180}
6181
6182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006183#define CHAR16_TO_CSTR(c16, len) (String8(String16(c16,len)).string())
6184
6185#define CHAR16_ARRAY_EQ(constant, var, len) \
6186 ((len == (sizeof(constant)/sizeof(constant[0]))) && (0 == memcmp((var), (constant), (len))))
6187
Jeff Brown9d3b1a42013-07-01 19:07:15 -07006188static void print_complex(uint32_t complex, bool isFraction)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006189{
Dianne Hackborne17086b2009-06-19 15:13:28 -07006190 const float MANTISSA_MULT =
6191 1.0f / (1<<Res_value::COMPLEX_MANTISSA_SHIFT);
6192 const float RADIX_MULTS[] = {
6193 1.0f*MANTISSA_MULT, 1.0f/(1<<7)*MANTISSA_MULT,
6194 1.0f/(1<<15)*MANTISSA_MULT, 1.0f/(1<<23)*MANTISSA_MULT
6195 };
6196
6197 float value = (complex&(Res_value::COMPLEX_MANTISSA_MASK
6198 <<Res_value::COMPLEX_MANTISSA_SHIFT))
6199 * RADIX_MULTS[(complex>>Res_value::COMPLEX_RADIX_SHIFT)
6200 & Res_value::COMPLEX_RADIX_MASK];
6201 printf("%f", value);
Mark Salyzyn00adb862014-03-19 11:00:06 -07006202
Dianne Hackbornde7faf62009-06-30 13:27:30 -07006203 if (!isFraction) {
Dianne Hackborne17086b2009-06-19 15:13:28 -07006204 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
6205 case Res_value::COMPLEX_UNIT_PX: printf("px"); break;
6206 case Res_value::COMPLEX_UNIT_DIP: printf("dp"); break;
6207 case Res_value::COMPLEX_UNIT_SP: printf("sp"); break;
6208 case Res_value::COMPLEX_UNIT_PT: printf("pt"); break;
6209 case Res_value::COMPLEX_UNIT_IN: printf("in"); break;
6210 case Res_value::COMPLEX_UNIT_MM: printf("mm"); break;
6211 default: printf(" (unknown unit)"); break;
6212 }
6213 } else {
6214 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
6215 case Res_value::COMPLEX_UNIT_FRACTION: printf("%%"); break;
6216 case Res_value::COMPLEX_UNIT_FRACTION_PARENT: printf("%%p"); break;
6217 default: printf(" (unknown unit)"); break;
6218 }
6219 }
6220}
6221
Shachar Shemesh9872bf42010-12-20 17:38:33 +02006222// Normalize a string for output
6223String8 ResTable::normalizeForOutput( const char *input )
6224{
6225 String8 ret;
6226 char buff[2];
6227 buff[1] = '\0';
6228
6229 while (*input != '\0') {
6230 switch (*input) {
6231 // All interesting characters are in the ASCII zone, so we are making our own lives
6232 // easier by scanning the string one byte at a time.
6233 case '\\':
6234 ret += "\\\\";
6235 break;
6236 case '\n':
6237 ret += "\\n";
6238 break;
6239 case '"':
6240 ret += "\\\"";
6241 break;
6242 default:
6243 buff[0] = *input;
6244 ret += buff;
6245 break;
6246 }
6247
6248 input++;
6249 }
6250
6251 return ret;
6252}
6253
Dianne Hackbornde7faf62009-06-30 13:27:30 -07006254void ResTable::print_value(const Package* pkg, const Res_value& value) const
6255{
6256 if (value.dataType == Res_value::TYPE_NULL) {
6257 printf("(null)\n");
6258 } else if (value.dataType == Res_value::TYPE_REFERENCE) {
6259 printf("(reference) 0x%08x\n", value.data);
Adam Lesinskide898ff2014-01-29 18:20:45 -08006260 } else if (value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE) {
6261 printf("(dynamic reference) 0x%08x\n", value.data);
Dianne Hackbornde7faf62009-06-30 13:27:30 -07006262 } else if (value.dataType == Res_value::TYPE_ATTRIBUTE) {
6263 printf("(attribute) 0x%08x\n", value.data);
6264 } else if (value.dataType == Res_value::TYPE_STRING) {
6265 size_t len;
Kenny Root780d2a12010-02-22 22:36:26 -08006266 const char* str8 = pkg->header->values.string8At(
Dianne Hackbornde7faf62009-06-30 13:27:30 -07006267 value.data, &len);
Kenny Root780d2a12010-02-22 22:36:26 -08006268 if (str8 != NULL) {
Shachar Shemesh9872bf42010-12-20 17:38:33 +02006269 printf("(string8) \"%s\"\n", normalizeForOutput(str8).string());
Dianne Hackbornde7faf62009-06-30 13:27:30 -07006270 } else {
Kenny Root780d2a12010-02-22 22:36:26 -08006271 const char16_t* str16 = pkg->header->values.stringAt(
6272 value.data, &len);
6273 if (str16 != NULL) {
6274 printf("(string16) \"%s\"\n",
Shachar Shemesh9872bf42010-12-20 17:38:33 +02006275 normalizeForOutput(String8(str16, len).string()).string());
Kenny Root780d2a12010-02-22 22:36:26 -08006276 } else {
6277 printf("(string) null\n");
6278 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006279 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07006280 } else if (value.dataType == Res_value::TYPE_FLOAT) {
6281 printf("(float) %g\n", *(const float*)&value.data);
6282 } else if (value.dataType == Res_value::TYPE_DIMENSION) {
6283 printf("(dimension) ");
6284 print_complex(value.data, false);
6285 printf("\n");
6286 } else if (value.dataType == Res_value::TYPE_FRACTION) {
6287 printf("(fraction) ");
6288 print_complex(value.data, true);
6289 printf("\n");
6290 } else if (value.dataType >= Res_value::TYPE_FIRST_COLOR_INT
6291 || value.dataType <= Res_value::TYPE_LAST_COLOR_INT) {
6292 printf("(color) #%08x\n", value.data);
6293 } else if (value.dataType == Res_value::TYPE_INT_BOOLEAN) {
6294 printf("(boolean) %s\n", value.data ? "true" : "false");
6295 } else if (value.dataType >= Res_value::TYPE_FIRST_INT
6296 || value.dataType <= Res_value::TYPE_LAST_INT) {
6297 printf("(int) 0x%08x or %d\n", value.data, value.data);
6298 } else {
6299 printf("(unknown type) t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)\n",
6300 (int)value.dataType, (int)value.data,
6301 (int)value.size, (int)value.res0);
6302 }
6303}
6304
Dianne Hackborne17086b2009-06-19 15:13:28 -07006305void ResTable::print(bool inclValues) const
6306{
6307 if (mError != 0) {
6308 printf("mError=0x%x (%s)\n", mError, strerror(mError));
6309 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006310 size_t pgCount = mPackageGroups.size();
6311 printf("Package Groups (%d)\n", (int)pgCount);
6312 for (size_t pgIndex=0; pgIndex<pgCount; pgIndex++) {
6313 const PackageGroup* pg = mPackageGroups[pgIndex];
Adam Lesinski6022deb2014-08-20 14:59:19 -07006314 printf("Package Group %d id=0x%02x packageCount=%d name=%s\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006315 (int)pgIndex, pg->id, (int)pg->packages.size(),
6316 String8(pg->name).string());
Mark Salyzyn00adb862014-03-19 11:00:06 -07006317
Adam Lesinski6022deb2014-08-20 14:59:19 -07006318 const KeyedVector<String16, uint8_t>& refEntries = pg->dynamicRefTable.entries();
6319 const size_t refEntryCount = refEntries.size();
6320 if (refEntryCount > 0) {
6321 printf(" DynamicRefTable entryCount=%d:\n", (int) refEntryCount);
6322 for (size_t refIndex = 0; refIndex < refEntryCount; refIndex++) {
6323 printf(" 0x%02x -> %s\n",
6324 refEntries.valueAt(refIndex),
6325 String8(refEntries.keyAt(refIndex)).string());
6326 }
6327 printf("\n");
6328 }
6329
6330 int packageId = pg->id;
Adam Lesinski18560882014-08-15 17:18:21 +00006331 size_t pkgCount = pg->packages.size();
6332 for (size_t pkgIndex=0; pkgIndex<pkgCount; pkgIndex++) {
6333 const Package* pkg = pg->packages[pkgIndex];
Adam Lesinski6022deb2014-08-20 14:59:19 -07006334 // Use a package's real ID, since the ID may have been assigned
6335 // if this package is a shared library.
6336 packageId = pkg->package->id;
Adam Lesinski4bf58102014-11-03 11:21:19 -08006337 char16_t tmpName[sizeof(pkg->package->name)/sizeof(pkg->package->name[0])];
6338 strcpy16_dtoh(tmpName, pkg->package->name, sizeof(pkg->package->name)/sizeof(pkg->package->name[0]));
Adam Lesinski6022deb2014-08-20 14:59:19 -07006339 printf(" Package %d id=0x%02x name=%s\n", (int)pkgIndex,
Adam Lesinski4bf58102014-11-03 11:21:19 -08006340 pkg->package->id, String8(tmpName).string());
Adam Lesinski18560882014-08-15 17:18:21 +00006341 }
6342
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006343 for (size_t typeIndex=0; typeIndex < pg->types.size(); typeIndex++) {
6344 const TypeList& typeList = pg->types[typeIndex];
6345 if (typeList.isEmpty()) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006346 continue;
6347 }
6348 const Type* typeConfigs = typeList[0];
6349 const size_t NTC = typeConfigs->configs.size();
6350 printf(" type %d configCount=%d entryCount=%d\n",
6351 (int)typeIndex, (int)NTC, (int)typeConfigs->entryCount);
6352 if (typeConfigs->typeSpecFlags != NULL) {
6353 for (size_t entryIndex=0; entryIndex<typeConfigs->entryCount; entryIndex++) {
Adam Lesinski6022deb2014-08-20 14:59:19 -07006354 uint32_t resID = (0xff000000 & ((packageId)<<24))
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006355 | (0x00ff0000 & ((typeIndex+1)<<16))
6356 | (0x0000ffff & (entryIndex));
6357 // Since we are creating resID without actually
6358 // iterating over them, we have no idea which is a
6359 // dynamic reference. We must check.
Adam Lesinski6022deb2014-08-20 14:59:19 -07006360 if (packageId == 0) {
6361 pg->dynamicRefTable.lookupResourceId(&resID);
6362 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006363
6364 resource_name resName;
6365 if (this->getResourceName(resID, true, &resName)) {
6366 String8 type8;
6367 String8 name8;
6368 if (resName.type8 != NULL) {
6369 type8 = String8(resName.type8, resName.typeLen);
6370 } else {
6371 type8 = String8(resName.type, resName.typeLen);
6372 }
6373 if (resName.name8 != NULL) {
6374 name8 = String8(resName.name8, resName.nameLen);
6375 } else {
6376 name8 = String8(resName.name, resName.nameLen);
6377 }
6378 printf(" spec resource 0x%08x %s:%s/%s: flags=0x%08x\n",
6379 resID,
6380 CHAR16_TO_CSTR(resName.package, resName.packageLen),
6381 type8.string(), name8.string(),
6382 dtohl(typeConfigs->typeSpecFlags[entryIndex]));
6383 } else {
6384 printf(" INVALID TYPE CONFIG FOR RESOURCE 0x%08x\n", resID);
6385 }
6386 }
6387 }
6388 for (size_t configIndex=0; configIndex<NTC; configIndex++) {
6389 const ResTable_type* type = typeConfigs->configs[configIndex];
6390 if ((((uint64_t)type)&0x3) != 0) {
6391 printf(" NON-INTEGER ResTable_type ADDRESS: %p\n", type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006392 continue;
6393 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006394 String8 configStr = type->config.toString();
6395 printf(" config %s:\n", configStr.size() > 0
6396 ? configStr.string() : "(default)");
6397 size_t entryCount = dtohl(type->entryCount);
6398 uint32_t entriesStart = dtohl(type->entriesStart);
6399 if ((entriesStart&0x3) != 0) {
6400 printf(" NON-INTEGER ResTable_type entriesStart OFFSET: 0x%x\n", entriesStart);
6401 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006402 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006403 uint32_t typeSize = dtohl(type->header.size);
6404 if ((typeSize&0x3) != 0) {
6405 printf(" NON-INTEGER ResTable_type header.size: 0x%x\n", typeSize);
6406 continue;
6407 }
6408 for (size_t entryIndex=0; entryIndex<entryCount; entryIndex++) {
6409
6410 const uint8_t* const end = ((const uint8_t*)type)
6411 + dtohl(type->header.size);
6412 const uint32_t* const eindex = (const uint32_t*)
6413 (((const uint8_t*)type) + dtohs(type->header.headerSize));
6414
6415 uint32_t thisOffset = dtohl(eindex[entryIndex]);
6416 if (thisOffset == ResTable_type::NO_ENTRY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006417 continue;
6418 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006419
Adam Lesinski6022deb2014-08-20 14:59:19 -07006420 uint32_t resID = (0xff000000 & ((packageId)<<24))
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006421 | (0x00ff0000 & ((typeIndex+1)<<16))
6422 | (0x0000ffff & (entryIndex));
Adam Lesinski6022deb2014-08-20 14:59:19 -07006423 if (packageId == 0) {
6424 pg->dynamicRefTable.lookupResourceId(&resID);
6425 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006426 resource_name resName;
6427 if (this->getResourceName(resID, true, &resName)) {
6428 String8 type8;
6429 String8 name8;
6430 if (resName.type8 != NULL) {
6431 type8 = String8(resName.type8, resName.typeLen);
Kenny Root33791952010-06-08 10:16:48 -07006432 } else {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006433 type8 = String8(resName.type, resName.typeLen);
Kenny Root33791952010-06-08 10:16:48 -07006434 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006435 if (resName.name8 != NULL) {
6436 name8 = String8(resName.name8, resName.nameLen);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006437 } else {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006438 name8 = String8(resName.name, resName.nameLen);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006439 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006440 printf(" resource 0x%08x %s:%s/%s: ", resID,
6441 CHAR16_TO_CSTR(resName.package, resName.packageLen),
6442 type8.string(), name8.string());
6443 } else {
6444 printf(" INVALID RESOURCE 0x%08x: ", resID);
6445 }
6446 if ((thisOffset&0x3) != 0) {
6447 printf("NON-INTEGER OFFSET: 0x%x\n", thisOffset);
6448 continue;
6449 }
6450 if ((thisOffset+sizeof(ResTable_entry)) > typeSize) {
6451 printf("OFFSET OUT OF BOUNDS: 0x%x+0x%x (size is 0x%x)\n",
6452 entriesStart, thisOffset, typeSize);
6453 continue;
6454 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006455
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006456 const ResTable_entry* ent = (const ResTable_entry*)
6457 (((const uint8_t*)type) + entriesStart + thisOffset);
6458 if (((entriesStart + thisOffset)&0x3) != 0) {
6459 printf("NON-INTEGER ResTable_entry OFFSET: 0x%x\n",
6460 (entriesStart + thisOffset));
6461 continue;
6462 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006463
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006464 uintptr_t esize = dtohs(ent->size);
6465 if ((esize&0x3) != 0) {
6466 printf("NON-INTEGER ResTable_entry SIZE: %p\n", (void *)esize);
6467 continue;
6468 }
6469 if ((thisOffset+esize) > typeSize) {
6470 printf("ResTable_entry OUT OF BOUNDS: 0x%x+0x%x+%p (size is 0x%x)\n",
6471 entriesStart, thisOffset, (void *)esize, typeSize);
6472 continue;
6473 }
6474
6475 const Res_value* valuePtr = NULL;
6476 const ResTable_map_entry* bagPtr = NULL;
6477 Res_value value;
6478 if ((dtohs(ent->flags)&ResTable_entry::FLAG_COMPLEX) != 0) {
6479 printf("<bag>");
6480 bagPtr = (const ResTable_map_entry*)ent;
6481 } else {
6482 valuePtr = (const Res_value*)
6483 (((const uint8_t*)ent) + esize);
6484 value.copyFrom_dtoh(*valuePtr);
6485 printf("t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)",
6486 (int)value.dataType, (int)value.data,
6487 (int)value.size, (int)value.res0);
6488 }
6489
6490 if ((dtohs(ent->flags)&ResTable_entry::FLAG_PUBLIC) != 0) {
6491 printf(" (PUBLIC)");
6492 }
6493 printf("\n");
6494
6495 if (inclValues) {
6496 if (valuePtr != NULL) {
6497 printf(" ");
6498 print_value(typeConfigs->package, value);
6499 } else if (bagPtr != NULL) {
6500 const int N = dtohl(bagPtr->count);
6501 const uint8_t* baseMapPtr = (const uint8_t*)ent;
6502 size_t mapOffset = esize;
6503 const ResTable_map* mapPtr = (ResTable_map*)(baseMapPtr+mapOffset);
6504 const uint32_t parent = dtohl(bagPtr->parent.ident);
6505 uint32_t resolvedParent = parent;
Adam Lesinski6022deb2014-08-20 14:59:19 -07006506 if (Res_GETPACKAGE(resolvedParent) + 1 == 0) {
6507 status_t err = pg->dynamicRefTable.lookupResourceId(&resolvedParent);
6508 if (err != NO_ERROR) {
6509 resolvedParent = 0;
6510 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006511 }
6512 printf(" Parent=0x%08x(Resolved=0x%08x), Count=%d\n",
6513 parent, resolvedParent, N);
6514 for (int i=0; i<N && mapOffset < (typeSize-sizeof(ResTable_map)); i++) {
6515 printf(" #%i (Key=0x%08x): ",
6516 i, dtohl(mapPtr->name.ident));
6517 value.copyFrom_dtoh(mapPtr->value);
6518 print_value(typeConfigs->package, value);
6519 const size_t size = dtohs(mapPtr->value.size);
6520 mapOffset += size + sizeof(*mapPtr)-sizeof(mapPtr->value);
6521 mapPtr = (ResTable_map*)(baseMapPtr+mapOffset);
Dianne Hackborne17086b2009-06-19 15:13:28 -07006522 }
6523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006524 }
6525 }
6526 }
6527 }
6528 }
6529}
6530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006531} // namespace android