blob: d7b976553e93204b56af6c36894e45e2c09010e5 [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 Lesinskia7d1d732014-10-01 18:24:54 -07001188 uint32_t resId = dtohl(mTree.mResIds[id]);
1189 if (mTree.mDynamicRefTable != NULL) {
1190 mTree.mDynamicRefTable->lookupResourceId(&resId);
1191 }
1192 return resId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 }
1194 return 0;
1195}
1196
Mathias Agopian5f910972009-06-22 02:35:32 -07001197int32_t ResXMLParser::getAttributeValueStringID(size_t idx) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198{
1199 if (mEventCode == START_TAG) {
1200 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1201 if (idx < dtohs(tag->attributeCount)) {
1202 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1203 (((const uint8_t*)tag)
1204 + dtohs(tag->attributeStart)
1205 + (dtohs(tag->attributeSize)*idx));
1206 return dtohl(attr->rawValue.index);
1207 }
1208 }
1209 return -1;
1210}
1211
Adam Lesinski4bf58102014-11-03 11:21:19 -08001212const char16_t* ResXMLParser::getAttributeStringValue(size_t idx, size_t* outLen) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213{
1214 int32_t id = getAttributeValueStringID(idx);
1215 //XML_NOISY(printf("getAttributeValue 0x%x=0x%x\n", idx, id));
1216 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1217}
1218
1219int32_t ResXMLParser::getAttributeDataType(size_t idx) const
1220{
1221 if (mEventCode == START_TAG) {
1222 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1223 if (idx < dtohs(tag->attributeCount)) {
1224 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1225 (((const uint8_t*)tag)
1226 + dtohs(tag->attributeStart)
1227 + (dtohs(tag->attributeSize)*idx));
Adam Lesinskide898ff2014-01-29 18:20:45 -08001228 uint8_t type = attr->typedValue.dataType;
1229 if (type != Res_value::TYPE_DYNAMIC_REFERENCE) {
1230 return type;
1231 }
1232
1233 // This is a dynamic reference. We adjust those references
1234 // to regular references at this level, so lie to the caller.
1235 return Res_value::TYPE_REFERENCE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001236 }
1237 }
1238 return Res_value::TYPE_NULL;
1239}
1240
1241int32_t ResXMLParser::getAttributeData(size_t idx) const
1242{
1243 if (mEventCode == START_TAG) {
1244 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1245 if (idx < dtohs(tag->attributeCount)) {
1246 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1247 (((const uint8_t*)tag)
1248 + dtohs(tag->attributeStart)
1249 + (dtohs(tag->attributeSize)*idx));
Adam Lesinskide898ff2014-01-29 18:20:45 -08001250 if (attr->typedValue.dataType != Res_value::TYPE_DYNAMIC_REFERENCE ||
1251 mTree.mDynamicRefTable == NULL) {
1252 return dtohl(attr->typedValue.data);
1253 }
1254
1255 uint32_t data = dtohl(attr->typedValue.data);
1256 if (mTree.mDynamicRefTable->lookupResourceId(&data) == NO_ERROR) {
1257 return data;
1258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259 }
1260 }
1261 return 0;
1262}
1263
1264ssize_t ResXMLParser::getAttributeValue(size_t idx, Res_value* outValue) const
1265{
1266 if (mEventCode == START_TAG) {
1267 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1268 if (idx < dtohs(tag->attributeCount)) {
1269 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1270 (((const uint8_t*)tag)
1271 + dtohs(tag->attributeStart)
1272 + (dtohs(tag->attributeSize)*idx));
1273 outValue->copyFrom_dtoh(attr->typedValue);
Adam Lesinskide898ff2014-01-29 18:20:45 -08001274 if (mTree.mDynamicRefTable != NULL &&
1275 mTree.mDynamicRefTable->lookupResourceValue(outValue) != NO_ERROR) {
1276 return BAD_TYPE;
1277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 return sizeof(Res_value);
1279 }
1280 }
1281 return BAD_TYPE;
1282}
1283
1284ssize_t ResXMLParser::indexOfAttribute(const char* ns, const char* attr) const
1285{
1286 String16 nsStr(ns != NULL ? ns : "");
1287 String16 attrStr(attr);
1288 return indexOfAttribute(ns ? nsStr.string() : NULL, ns ? nsStr.size() : 0,
1289 attrStr.string(), attrStr.size());
1290}
1291
1292ssize_t ResXMLParser::indexOfAttribute(const char16_t* ns, size_t nsLen,
1293 const char16_t* attr, size_t attrLen) const
1294{
1295 if (mEventCode == START_TAG) {
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07001296 if (attr == NULL) {
1297 return NAME_NOT_FOUND;
1298 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 const size_t N = getAttributeCount();
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07001300 if (mTree.mStrings.isUTF8()) {
1301 String8 ns8, attr8;
1302 if (ns != NULL) {
1303 ns8 = String8(ns, nsLen);
1304 }
1305 attr8 = String8(attr, attrLen);
1306 STRING_POOL_NOISY(ALOGI("indexOfAttribute UTF8 %s (%d) / %s (%d)", ns8.string(), nsLen,
1307 attr8.string(), attrLen));
1308 for (size_t i=0; i<N; i++) {
1309 size_t curNsLen = 0, curAttrLen = 0;
1310 const char* curNs = getAttributeNamespace8(i, &curNsLen);
1311 const char* curAttr = getAttributeName8(i, &curAttrLen);
1312 STRING_POOL_NOISY(ALOGI(" curNs=%s (%d), curAttr=%s (%d)", curNs, curNsLen,
1313 curAttr, curAttrLen));
1314 if (curAttr != NULL && curNsLen == nsLen && curAttrLen == attrLen
1315 && memcmp(attr8.string(), curAttr, attrLen) == 0) {
1316 if (ns == NULL) {
1317 if (curNs == NULL) {
1318 STRING_POOL_NOISY(ALOGI(" FOUND!"));
1319 return i;
1320 }
1321 } else if (curNs != NULL) {
1322 //printf(" --> ns=%s, curNs=%s\n",
1323 // String8(ns).string(), String8(curNs).string());
1324 if (memcmp(ns8.string(), curNs, nsLen) == 0) {
1325 STRING_POOL_NOISY(ALOGI(" FOUND!"));
1326 return i;
1327 }
1328 }
1329 }
1330 }
1331 } else {
1332 STRING_POOL_NOISY(ALOGI("indexOfAttribute UTF16 %s (%d) / %s (%d)",
1333 String8(ns, nsLen).string(), nsLen,
1334 String8(attr, attrLen).string(), attrLen));
1335 for (size_t i=0; i<N; i++) {
1336 size_t curNsLen = 0, curAttrLen = 0;
1337 const char16_t* curNs = getAttributeNamespace(i, &curNsLen);
1338 const char16_t* curAttr = getAttributeName(i, &curAttrLen);
1339 STRING_POOL_NOISY(ALOGI(" curNs=%s (%d), curAttr=%s (%d)",
1340 String8(curNs, curNsLen).string(), curNsLen,
1341 String8(curAttr, curAttrLen).string(), curAttrLen));
1342 if (curAttr != NULL && curNsLen == nsLen && curAttrLen == attrLen
1343 && (memcmp(attr, curAttr, attrLen*sizeof(char16_t)) == 0)) {
1344 if (ns == NULL) {
1345 if (curNs == NULL) {
1346 STRING_POOL_NOISY(ALOGI(" FOUND!"));
1347 return i;
1348 }
1349 } else if (curNs != NULL) {
1350 //printf(" --> ns=%s, curNs=%s\n",
1351 // String8(ns).string(), String8(curNs).string());
1352 if (memcmp(ns, curNs, nsLen*sizeof(char16_t)) == 0) {
1353 STRING_POOL_NOISY(ALOGI(" FOUND!"));
1354 return i;
1355 }
1356 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 }
1358 }
1359 }
1360 }
1361
1362 return NAME_NOT_FOUND;
1363}
1364
1365ssize_t ResXMLParser::indexOfID() const
1366{
1367 if (mEventCode == START_TAG) {
1368 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->idIndex);
1369 if (idx > 0) return (idx-1);
1370 }
1371 return NAME_NOT_FOUND;
1372}
1373
1374ssize_t ResXMLParser::indexOfClass() const
1375{
1376 if (mEventCode == START_TAG) {
1377 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->classIndex);
1378 if (idx > 0) return (idx-1);
1379 }
1380 return NAME_NOT_FOUND;
1381}
1382
1383ssize_t ResXMLParser::indexOfStyle() const
1384{
1385 if (mEventCode == START_TAG) {
1386 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->styleIndex);
1387 if (idx > 0) return (idx-1);
1388 }
1389 return NAME_NOT_FOUND;
1390}
1391
1392ResXMLParser::event_code_t ResXMLParser::nextNode()
1393{
1394 if (mEventCode < 0) {
1395 return mEventCode;
1396 }
1397
1398 do {
1399 const ResXMLTree_node* next = (const ResXMLTree_node*)
1400 (((const uint8_t*)mCurNode) + dtohl(mCurNode->header.size));
Steve Block8564c8d2012-01-05 23:22:43 +00001401 //ALOGW("Next node: prev=%p, next=%p\n", mCurNode, next);
Mark Salyzyn00adb862014-03-19 11:00:06 -07001402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 if (((const uint8_t*)next) >= mTree.mDataEnd) {
1404 mCurNode = NULL;
1405 return (mEventCode=END_DOCUMENT);
1406 }
1407
1408 if (mTree.validateNode(next) != NO_ERROR) {
1409 mCurNode = NULL;
1410 return (mEventCode=BAD_DOCUMENT);
1411 }
1412
1413 mCurNode = next;
1414 const uint16_t headerSize = dtohs(next->header.headerSize);
1415 const uint32_t totalSize = dtohl(next->header.size);
1416 mCurExt = ((const uint8_t*)next) + headerSize;
1417 size_t minExtSize = 0;
1418 event_code_t eventCode = (event_code_t)dtohs(next->header.type);
1419 switch ((mEventCode=eventCode)) {
1420 case RES_XML_START_NAMESPACE_TYPE:
1421 case RES_XML_END_NAMESPACE_TYPE:
1422 minExtSize = sizeof(ResXMLTree_namespaceExt);
1423 break;
1424 case RES_XML_START_ELEMENT_TYPE:
1425 minExtSize = sizeof(ResXMLTree_attrExt);
1426 break;
1427 case RES_XML_END_ELEMENT_TYPE:
1428 minExtSize = sizeof(ResXMLTree_endElementExt);
1429 break;
1430 case RES_XML_CDATA_TYPE:
1431 minExtSize = sizeof(ResXMLTree_cdataExt);
1432 break;
1433 default:
Steve Block8564c8d2012-01-05 23:22:43 +00001434 ALOGW("Unknown XML block: header type %d in node at %d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 (int)dtohs(next->header.type),
1436 (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)));
1437 continue;
1438 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07001439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 if ((totalSize-headerSize) < minExtSize) {
Steve Block8564c8d2012-01-05 23:22:43 +00001441 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 -08001442 (int)dtohs(next->header.type),
1443 (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)),
1444 (int)(totalSize-headerSize), (int)minExtSize);
1445 return (mEventCode=BAD_DOCUMENT);
1446 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07001447
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 //printf("CurNode=%p, CurExt=%p, headerSize=%d, minExtSize=%d\n",
1449 // mCurNode, mCurExt, headerSize, minExtSize);
Mark Salyzyn00adb862014-03-19 11:00:06 -07001450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 return eventCode;
1452 } while (true);
1453}
1454
1455void ResXMLParser::getPosition(ResXMLParser::ResXMLPosition* pos) const
1456{
1457 pos->eventCode = mEventCode;
1458 pos->curNode = mCurNode;
1459 pos->curExt = mCurExt;
1460}
1461
1462void ResXMLParser::setPosition(const ResXMLParser::ResXMLPosition& pos)
1463{
1464 mEventCode = pos.eventCode;
1465 mCurNode = pos.curNode;
1466 mCurExt = pos.curExt;
1467}
1468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469// --------------------------------------------------------------------
1470
1471static volatile int32_t gCount = 0;
1472
Adam Lesinskide898ff2014-01-29 18:20:45 -08001473ResXMLTree::ResXMLTree(const DynamicRefTable* dynamicRefTable)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 : ResXMLParser(*this)
Adam Lesinskide898ff2014-01-29 18:20:45 -08001475 , mDynamicRefTable(dynamicRefTable)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 , mError(NO_INIT), mOwnedData(NULL)
1477{
Steve Block6215d3f2012-01-04 20:05:49 +00001478 //ALOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 restart();
1480}
1481
Adam Lesinskide898ff2014-01-29 18:20:45 -08001482ResXMLTree::ResXMLTree()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 : ResXMLParser(*this)
Adam Lesinskide898ff2014-01-29 18:20:45 -08001484 , mDynamicRefTable(NULL)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 , mError(NO_INIT), mOwnedData(NULL)
1486{
Steve Block6215d3f2012-01-04 20:05:49 +00001487 //ALOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1);
Adam Lesinskide898ff2014-01-29 18:20:45 -08001488 restart();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489}
1490
1491ResXMLTree::~ResXMLTree()
1492{
Steve Block6215d3f2012-01-04 20:05:49 +00001493 //ALOGI("Destroying ResXMLTree in %p #%d\n", this, android_atomic_dec(&gCount)-1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 uninit();
1495}
1496
1497status_t ResXMLTree::setTo(const void* data, size_t size, bool copyData)
1498{
1499 uninit();
1500 mEventCode = START_DOCUMENT;
1501
Kenny Root32d6aef2012-10-10 10:23:47 -07001502 if (!data || !size) {
1503 return (mError=BAD_TYPE);
1504 }
1505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 if (copyData) {
1507 mOwnedData = malloc(size);
1508 if (mOwnedData == NULL) {
1509 return (mError=NO_MEMORY);
1510 }
1511 memcpy(mOwnedData, data, size);
1512 data = mOwnedData;
1513 }
1514
1515 mHeader = (const ResXMLTree_header*)data;
1516 mSize = dtohl(mHeader->header.size);
1517 if (dtohs(mHeader->header.headerSize) > mSize || mSize > size) {
Steve Block8564c8d2012-01-05 23:22:43 +00001518 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 -08001519 (int)dtohs(mHeader->header.headerSize),
1520 (int)dtohl(mHeader->header.size), (int)size);
1521 mError = BAD_TYPE;
1522 restart();
1523 return mError;
1524 }
1525 mDataEnd = ((const uint8_t*)mHeader) + mSize;
1526
1527 mStrings.uninit();
1528 mRootNode = NULL;
1529 mResIds = NULL;
1530 mNumResIds = 0;
1531
1532 // First look for a couple interesting chunks: the string block
1533 // and first XML node.
1534 const ResChunk_header* chunk =
1535 (const ResChunk_header*)(((const uint8_t*)mHeader) + dtohs(mHeader->header.headerSize));
1536 const ResChunk_header* lastChunk = chunk;
1537 while (((const uint8_t*)chunk) < (mDataEnd-sizeof(ResChunk_header)) &&
1538 ((const uint8_t*)chunk) < (mDataEnd-dtohl(chunk->size))) {
1539 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), mDataEnd, "XML");
1540 if (err != NO_ERROR) {
1541 mError = err;
1542 goto done;
1543 }
1544 const uint16_t type = dtohs(chunk->type);
1545 const size_t size = dtohl(chunk->size);
1546 XML_NOISY(printf("Scanning @ %p: type=0x%x, size=0x%x\n",
1547 (void*)(((uint32_t)chunk)-((uint32_t)mHeader)), type, size));
1548 if (type == RES_STRING_POOL_TYPE) {
1549 mStrings.setTo(chunk, size);
1550 } else if (type == RES_XML_RESOURCE_MAP_TYPE) {
1551 mResIds = (const uint32_t*)
1552 (((const uint8_t*)chunk)+dtohs(chunk->headerSize));
1553 mNumResIds = (dtohl(chunk->size)-dtohs(chunk->headerSize))/sizeof(uint32_t);
1554 } else if (type >= RES_XML_FIRST_CHUNK_TYPE
1555 && type <= RES_XML_LAST_CHUNK_TYPE) {
1556 if (validateNode((const ResXMLTree_node*)chunk) != NO_ERROR) {
1557 mError = BAD_TYPE;
1558 goto done;
1559 }
1560 mCurNode = (const ResXMLTree_node*)lastChunk;
1561 if (nextNode() == BAD_DOCUMENT) {
1562 mError = BAD_TYPE;
1563 goto done;
1564 }
1565 mRootNode = mCurNode;
1566 mRootExt = mCurExt;
1567 mRootCode = mEventCode;
1568 break;
1569 } else {
1570 XML_NOISY(printf("Skipping unknown chunk!\n"));
1571 }
1572 lastChunk = chunk;
1573 chunk = (const ResChunk_header*)
1574 (((const uint8_t*)chunk) + size);
1575 }
1576
1577 if (mRootNode == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001578 ALOGW("Bad XML block: no root element node found\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 mError = BAD_TYPE;
1580 goto done;
1581 }
1582
1583 mError = mStrings.getError();
1584
1585done:
1586 restart();
1587 return mError;
1588}
1589
1590status_t ResXMLTree::getError() const
1591{
1592 return mError;
1593}
1594
1595void ResXMLTree::uninit()
1596{
1597 mError = NO_INIT;
Kenny Root19138462009-12-04 09:38:48 -08001598 mStrings.uninit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 if (mOwnedData) {
1600 free(mOwnedData);
1601 mOwnedData = NULL;
1602 }
1603 restart();
1604}
1605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606status_t ResXMLTree::validateNode(const ResXMLTree_node* node) const
1607{
1608 const uint16_t eventCode = dtohs(node->header.type);
1609
1610 status_t err = validate_chunk(
1611 &node->header, sizeof(ResXMLTree_node),
1612 mDataEnd, "ResXMLTree_node");
1613
1614 if (err >= NO_ERROR) {
1615 // Only perform additional validation on START nodes
1616 if (eventCode != RES_XML_START_ELEMENT_TYPE) {
1617 return NO_ERROR;
1618 }
1619
1620 const uint16_t headerSize = dtohs(node->header.headerSize);
1621 const uint32_t size = dtohl(node->header.size);
1622 const ResXMLTree_attrExt* attrExt = (const ResXMLTree_attrExt*)
1623 (((const uint8_t*)node) + headerSize);
1624 // check for sensical values pulled out of the stream so far...
1625 if ((size >= headerSize + sizeof(ResXMLTree_attrExt))
1626 && ((void*)attrExt > (void*)node)) {
1627 const size_t attrSize = ((size_t)dtohs(attrExt->attributeSize))
1628 * dtohs(attrExt->attributeCount);
1629 if ((dtohs(attrExt->attributeStart)+attrSize) <= (size-headerSize)) {
1630 return NO_ERROR;
1631 }
Steve Block8564c8d2012-01-05 23:22:43 +00001632 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 -08001633 (unsigned int)(dtohs(attrExt->attributeStart)+attrSize),
1634 (unsigned int)(size-headerSize));
1635 }
1636 else {
Steve Block8564c8d2012-01-05 23:22:43 +00001637 ALOGW("Bad XML start block: node header size 0x%x, size 0x%x\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 (unsigned int)headerSize, (unsigned int)size);
1639 }
1640 return BAD_TYPE;
1641 }
1642
1643 return err;
1644
1645#if 0
1646 const bool isStart = dtohs(node->header.type) == RES_XML_START_ELEMENT_TYPE;
1647
1648 const uint16_t headerSize = dtohs(node->header.headerSize);
1649 const uint32_t size = dtohl(node->header.size);
1650
1651 if (headerSize >= (isStart ? sizeof(ResXMLTree_attrNode) : sizeof(ResXMLTree_node))) {
1652 if (size >= headerSize) {
1653 if (((const uint8_t*)node) <= (mDataEnd-size)) {
1654 if (!isStart) {
1655 return NO_ERROR;
1656 }
1657 if ((((size_t)dtohs(node->attributeSize))*dtohs(node->attributeCount))
1658 <= (size-headerSize)) {
1659 return NO_ERROR;
1660 }
Steve Block8564c8d2012-01-05 23:22:43 +00001661 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 -08001662 ((int)dtohs(node->attributeSize))*dtohs(node->attributeCount),
1663 (int)(size-headerSize));
1664 return BAD_TYPE;
1665 }
Steve Block8564c8d2012-01-05 23:22:43 +00001666 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 -08001667 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)), (int)mSize);
1668 return BAD_TYPE;
1669 }
Steve Block8564c8d2012-01-05 23:22:43 +00001670 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 -08001671 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)),
1672 (int)headerSize, (int)size);
1673 return BAD_TYPE;
1674 }
Steve Block8564c8d2012-01-05 23:22:43 +00001675 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 -08001676 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)),
1677 (int)headerSize);
1678 return BAD_TYPE;
1679#endif
1680}
1681
1682// --------------------------------------------------------------------
1683// --------------------------------------------------------------------
1684// --------------------------------------------------------------------
1685
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001686void ResTable_config::copyFromDeviceNoSwap(const ResTable_config& o) {
1687 const size_t size = dtohl(o.size);
1688 if (size >= sizeof(ResTable_config)) {
1689 *this = o;
1690 } else {
1691 memcpy(this, &o, size);
1692 memset(((uint8_t*)this)+size, 0, sizeof(ResTable_config)-size);
1693 }
1694}
1695
Narayan Kamath48620f12014-01-20 13:57:11 +00001696/* static */ size_t unpackLanguageOrRegion(const char in[2], const char base,
1697 char out[4]) {
1698 if (in[0] & 0x80) {
1699 // The high bit is "1", which means this is a packed three letter
1700 // language code.
1701
1702 // The smallest 5 bits of the second char are the first alphabet.
1703 const uint8_t first = in[1] & 0x1f;
1704 // The last three bits of the second char and the first two bits
1705 // of the first char are the second alphabet.
1706 const uint8_t second = ((in[1] & 0xe0) >> 5) + ((in[0] & 0x03) << 3);
1707 // Bits 3 to 7 (inclusive) of the first char are the third alphabet.
1708 const uint8_t third = (in[0] & 0x7c) >> 2;
1709
1710 out[0] = first + base;
1711 out[1] = second + base;
1712 out[2] = third + base;
1713 out[3] = 0;
1714
1715 return 3;
1716 }
1717
1718 if (in[0]) {
1719 memcpy(out, in, 2);
1720 memset(out + 2, 0, 2);
1721 return 2;
1722 }
1723
1724 memset(out, 0, 4);
1725 return 0;
1726}
1727
Narayan Kamath788fa412014-01-21 15:32:36 +00001728/* static */ void packLanguageOrRegion(const char* in, const char base,
Narayan Kamath48620f12014-01-20 13:57:11 +00001729 char out[2]) {
Narayan Kamath788fa412014-01-21 15:32:36 +00001730 if (in[2] == 0 || in[2] == '-') {
Narayan Kamath48620f12014-01-20 13:57:11 +00001731 out[0] = in[0];
1732 out[1] = in[1];
1733 } else {
Narayan Kamathb2975912014-06-30 15:59:39 +01001734 uint8_t first = (in[0] - base) & 0x007f;
1735 uint8_t second = (in[1] - base) & 0x007f;
1736 uint8_t third = (in[2] - base) & 0x007f;
Narayan Kamath48620f12014-01-20 13:57:11 +00001737
1738 out[0] = (0x80 | (third << 2) | (second >> 3));
1739 out[1] = ((second << 5) | first);
1740 }
1741}
1742
1743
Narayan Kamath788fa412014-01-21 15:32:36 +00001744void ResTable_config::packLanguage(const char* language) {
Narayan Kamath48620f12014-01-20 13:57:11 +00001745 packLanguageOrRegion(language, 'a', this->language);
1746}
1747
Narayan Kamath788fa412014-01-21 15:32:36 +00001748void ResTable_config::packRegion(const char* region) {
Narayan Kamath48620f12014-01-20 13:57:11 +00001749 packLanguageOrRegion(region, '0', this->country);
1750}
1751
1752size_t ResTable_config::unpackLanguage(char language[4]) const {
1753 return unpackLanguageOrRegion(this->language, 'a', language);
1754}
1755
1756size_t ResTable_config::unpackRegion(char region[4]) const {
1757 return unpackLanguageOrRegion(this->country, '0', region);
1758}
1759
1760
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001761void ResTable_config::copyFromDtoH(const ResTable_config& o) {
1762 copyFromDeviceNoSwap(o);
1763 size = sizeof(ResTable_config);
1764 mcc = dtohs(mcc);
1765 mnc = dtohs(mnc);
1766 density = dtohs(density);
1767 screenWidth = dtohs(screenWidth);
1768 screenHeight = dtohs(screenHeight);
1769 sdkVersion = dtohs(sdkVersion);
1770 minorVersion = dtohs(minorVersion);
1771 smallestScreenWidthDp = dtohs(smallestScreenWidthDp);
1772 screenWidthDp = dtohs(screenWidthDp);
1773 screenHeightDp = dtohs(screenHeightDp);
1774}
1775
1776void ResTable_config::swapHtoD() {
1777 size = htodl(size);
1778 mcc = htods(mcc);
1779 mnc = htods(mnc);
1780 density = htods(density);
1781 screenWidth = htods(screenWidth);
1782 screenHeight = htods(screenHeight);
1783 sdkVersion = htods(sdkVersion);
1784 minorVersion = htods(minorVersion);
1785 smallestScreenWidthDp = htods(smallestScreenWidthDp);
1786 screenWidthDp = htods(screenWidthDp);
1787 screenHeightDp = htods(screenHeightDp);
1788}
1789
Narayan Kamath48620f12014-01-20 13:57:11 +00001790/* static */ inline int compareLocales(const ResTable_config &l, const ResTable_config &r) {
1791 if (l.locale != r.locale) {
1792 // NOTE: This is the old behaviour with respect to comparison orders.
1793 // The diff value here doesn't make much sense (given our bit packing scheme)
1794 // but it's stable, and that's all we need.
1795 return l.locale - r.locale;
1796 }
1797
1798 // The language & region are equal, so compare the scripts and variants.
1799 int script = memcmp(l.localeScript, r.localeScript, sizeof(l.localeScript));
1800 if (script) {
1801 return script;
1802 }
1803
1804 // The language, region and script are equal, so compare variants.
1805 //
1806 // This should happen very infrequently (if at all.)
1807 return memcmp(l.localeVariant, r.localeVariant, sizeof(l.localeVariant));
1808}
1809
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001810int ResTable_config::compare(const ResTable_config& o) const {
1811 int32_t diff = (int32_t)(imsi - o.imsi);
1812 if (diff != 0) return diff;
Narayan Kamath48620f12014-01-20 13:57:11 +00001813 diff = compareLocales(*this, o);
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001814 if (diff != 0) return diff;
1815 diff = (int32_t)(screenType - o.screenType);
1816 if (diff != 0) return diff;
1817 diff = (int32_t)(input - o.input);
1818 if (diff != 0) return diff;
1819 diff = (int32_t)(screenSize - o.screenSize);
1820 if (diff != 0) return diff;
1821 diff = (int32_t)(version - o.version);
1822 if (diff != 0) return diff;
1823 diff = (int32_t)(screenLayout - o.screenLayout);
1824 if (diff != 0) return diff;
1825 diff = (int32_t)(uiMode - o.uiMode);
1826 if (diff != 0) return diff;
1827 diff = (int32_t)(smallestScreenWidthDp - o.smallestScreenWidthDp);
1828 if (diff != 0) return diff;
1829 diff = (int32_t)(screenSizeDp - o.screenSizeDp);
1830 return (int)diff;
1831}
1832
1833int ResTable_config::compareLogical(const ResTable_config& o) const {
1834 if (mcc != o.mcc) {
1835 return mcc < o.mcc ? -1 : 1;
1836 }
1837 if (mnc != o.mnc) {
1838 return mnc < o.mnc ? -1 : 1;
1839 }
Narayan Kamath48620f12014-01-20 13:57:11 +00001840
1841 int diff = compareLocales(*this, o);
1842 if (diff < 0) {
1843 return -1;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001844 }
Narayan Kamath48620f12014-01-20 13:57:11 +00001845 if (diff > 0) {
1846 return 1;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001847 }
Narayan Kamath48620f12014-01-20 13:57:11 +00001848
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07001849 if ((screenLayout & MASK_LAYOUTDIR) != (o.screenLayout & MASK_LAYOUTDIR)) {
1850 return (screenLayout & MASK_LAYOUTDIR) < (o.screenLayout & MASK_LAYOUTDIR) ? -1 : 1;
1851 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001852 if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
1853 return smallestScreenWidthDp < o.smallestScreenWidthDp ? -1 : 1;
1854 }
1855 if (screenWidthDp != o.screenWidthDp) {
1856 return screenWidthDp < o.screenWidthDp ? -1 : 1;
1857 }
1858 if (screenHeightDp != o.screenHeightDp) {
1859 return screenHeightDp < o.screenHeightDp ? -1 : 1;
1860 }
1861 if (screenWidth != o.screenWidth) {
1862 return screenWidth < o.screenWidth ? -1 : 1;
1863 }
1864 if (screenHeight != o.screenHeight) {
1865 return screenHeight < o.screenHeight ? -1 : 1;
1866 }
1867 if (density != o.density) {
1868 return density < o.density ? -1 : 1;
1869 }
1870 if (orientation != o.orientation) {
1871 return orientation < o.orientation ? -1 : 1;
1872 }
1873 if (touchscreen != o.touchscreen) {
1874 return touchscreen < o.touchscreen ? -1 : 1;
1875 }
1876 if (input != o.input) {
1877 return input < o.input ? -1 : 1;
1878 }
1879 if (screenLayout != o.screenLayout) {
1880 return screenLayout < o.screenLayout ? -1 : 1;
1881 }
1882 if (uiMode != o.uiMode) {
1883 return uiMode < o.uiMode ? -1 : 1;
1884 }
1885 if (version != o.version) {
1886 return version < o.version ? -1 : 1;
1887 }
1888 return 0;
1889}
1890
1891int ResTable_config::diff(const ResTable_config& o) const {
1892 int diffs = 0;
1893 if (mcc != o.mcc) diffs |= CONFIG_MCC;
1894 if (mnc != o.mnc) diffs |= CONFIG_MNC;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001895 if (orientation != o.orientation) diffs |= CONFIG_ORIENTATION;
1896 if (density != o.density) diffs |= CONFIG_DENSITY;
1897 if (touchscreen != o.touchscreen) diffs |= CONFIG_TOUCHSCREEN;
1898 if (((inputFlags^o.inputFlags)&(MASK_KEYSHIDDEN|MASK_NAVHIDDEN)) != 0)
1899 diffs |= CONFIG_KEYBOARD_HIDDEN;
1900 if (keyboard != o.keyboard) diffs |= CONFIG_KEYBOARD;
1901 if (navigation != o.navigation) diffs |= CONFIG_NAVIGATION;
1902 if (screenSize != o.screenSize) diffs |= CONFIG_SCREEN_SIZE;
1903 if (version != o.version) diffs |= CONFIG_VERSION;
Fabrice Di Meglio35099352012-12-12 11:52:03 -08001904 if ((screenLayout & MASK_LAYOUTDIR) != (o.screenLayout & MASK_LAYOUTDIR)) diffs |= CONFIG_LAYOUTDIR;
1905 if ((screenLayout & ~MASK_LAYOUTDIR) != (o.screenLayout & ~MASK_LAYOUTDIR)) diffs |= CONFIG_SCREEN_LAYOUT;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001906 if (uiMode != o.uiMode) diffs |= CONFIG_UI_MODE;
1907 if (smallestScreenWidthDp != o.smallestScreenWidthDp) diffs |= CONFIG_SMALLEST_SCREEN_SIZE;
1908 if (screenSizeDp != o.screenSizeDp) diffs |= CONFIG_SCREEN_SIZE;
Narayan Kamath48620f12014-01-20 13:57:11 +00001909
1910 const int diff = compareLocales(*this, o);
1911 if (diff) diffs |= CONFIG_LOCALE;
1912
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001913 return diffs;
1914}
1915
Narayan Kamath48620f12014-01-20 13:57:11 +00001916int ResTable_config::isLocaleMoreSpecificThan(const ResTable_config& o) const {
1917 if (locale || o.locale) {
1918 if (language[0] != o.language[0]) {
1919 if (!language[0]) return -1;
1920 if (!o.language[0]) return 1;
1921 }
1922
1923 if (country[0] != o.country[0]) {
1924 if (!country[0]) return -1;
1925 if (!o.country[0]) return 1;
1926 }
1927 }
1928
1929 // There isn't a well specified "importance" order between variants and
1930 // scripts. We can't easily tell whether, say "en-Latn-US" is more or less
1931 // specific than "en-US-POSIX".
1932 //
1933 // We therefore arbitrarily decide to give priority to variants over
1934 // scripts since it seems more useful to do so. We will consider
1935 // "en-US-POSIX" to be more specific than "en-Latn-US".
1936
1937 const int score = ((localeScript[0] != 0) ? 1 : 0) +
1938 ((localeVariant[0] != 0) ? 2 : 0);
1939
1940 const int oScore = ((o.localeScript[0] != 0) ? 1 : 0) +
1941 ((o.localeVariant[0] != 0) ? 2 : 0);
1942
1943 return score - oScore;
1944
1945}
1946
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001947bool ResTable_config::isMoreSpecificThan(const ResTable_config& o) const {
1948 // The order of the following tests defines the importance of one
1949 // configuration parameter over another. Those tests first are more
1950 // important, trumping any values in those following them.
1951 if (imsi || o.imsi) {
1952 if (mcc != o.mcc) {
1953 if (!mcc) return false;
1954 if (!o.mcc) return true;
1955 }
1956
1957 if (mnc != o.mnc) {
1958 if (!mnc) return false;
1959 if (!o.mnc) return true;
1960 }
1961 }
1962
1963 if (locale || o.locale) {
Narayan Kamath48620f12014-01-20 13:57:11 +00001964 const int diff = isLocaleMoreSpecificThan(o);
1965 if (diff < 0) {
1966 return false;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001967 }
1968
Narayan Kamath48620f12014-01-20 13:57:11 +00001969 if (diff > 0) {
1970 return true;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001971 }
1972 }
1973
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07001974 if (screenLayout || o.screenLayout) {
1975 if (((screenLayout^o.screenLayout) & MASK_LAYOUTDIR) != 0) {
1976 if (!(screenLayout & MASK_LAYOUTDIR)) return false;
1977 if (!(o.screenLayout & MASK_LAYOUTDIR)) return true;
1978 }
1979 }
1980
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001981 if (smallestScreenWidthDp || o.smallestScreenWidthDp) {
1982 if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
1983 if (!smallestScreenWidthDp) return false;
1984 if (!o.smallestScreenWidthDp) return true;
1985 }
1986 }
1987
1988 if (screenSizeDp || o.screenSizeDp) {
1989 if (screenWidthDp != o.screenWidthDp) {
1990 if (!screenWidthDp) return false;
1991 if (!o.screenWidthDp) return true;
1992 }
1993
1994 if (screenHeightDp != o.screenHeightDp) {
1995 if (!screenHeightDp) return false;
1996 if (!o.screenHeightDp) return true;
1997 }
1998 }
1999
2000 if (screenLayout || o.screenLayout) {
2001 if (((screenLayout^o.screenLayout) & MASK_SCREENSIZE) != 0) {
2002 if (!(screenLayout & MASK_SCREENSIZE)) return false;
2003 if (!(o.screenLayout & MASK_SCREENSIZE)) return true;
2004 }
2005 if (((screenLayout^o.screenLayout) & MASK_SCREENLONG) != 0) {
2006 if (!(screenLayout & MASK_SCREENLONG)) return false;
2007 if (!(o.screenLayout & MASK_SCREENLONG)) return true;
2008 }
2009 }
2010
2011 if (orientation != o.orientation) {
2012 if (!orientation) return false;
2013 if (!o.orientation) return true;
2014 }
2015
2016 if (uiMode || o.uiMode) {
2017 if (((uiMode^o.uiMode) & MASK_UI_MODE_TYPE) != 0) {
2018 if (!(uiMode & MASK_UI_MODE_TYPE)) return false;
2019 if (!(o.uiMode & MASK_UI_MODE_TYPE)) return true;
2020 }
2021 if (((uiMode^o.uiMode) & MASK_UI_MODE_NIGHT) != 0) {
2022 if (!(uiMode & MASK_UI_MODE_NIGHT)) return false;
2023 if (!(o.uiMode & MASK_UI_MODE_NIGHT)) return true;
2024 }
2025 }
2026
2027 // density is never 'more specific'
2028 // as the default just equals 160
2029
2030 if (touchscreen != o.touchscreen) {
2031 if (!touchscreen) return false;
2032 if (!o.touchscreen) return true;
2033 }
2034
2035 if (input || o.input) {
2036 if (((inputFlags^o.inputFlags) & MASK_KEYSHIDDEN) != 0) {
2037 if (!(inputFlags & MASK_KEYSHIDDEN)) return false;
2038 if (!(o.inputFlags & MASK_KEYSHIDDEN)) return true;
2039 }
2040
2041 if (((inputFlags^o.inputFlags) & MASK_NAVHIDDEN) != 0) {
2042 if (!(inputFlags & MASK_NAVHIDDEN)) return false;
2043 if (!(o.inputFlags & MASK_NAVHIDDEN)) return true;
2044 }
2045
2046 if (keyboard != o.keyboard) {
2047 if (!keyboard) return false;
2048 if (!o.keyboard) return true;
2049 }
2050
2051 if (navigation != o.navigation) {
2052 if (!navigation) return false;
2053 if (!o.navigation) return true;
2054 }
2055 }
2056
2057 if (screenSize || o.screenSize) {
2058 if (screenWidth != o.screenWidth) {
2059 if (!screenWidth) return false;
2060 if (!o.screenWidth) return true;
2061 }
2062
2063 if (screenHeight != o.screenHeight) {
2064 if (!screenHeight) return false;
2065 if (!o.screenHeight) return true;
2066 }
2067 }
2068
2069 if (version || o.version) {
2070 if (sdkVersion != o.sdkVersion) {
2071 if (!sdkVersion) return false;
2072 if (!o.sdkVersion) return true;
2073 }
2074
2075 if (minorVersion != o.minorVersion) {
2076 if (!minorVersion) return false;
2077 if (!o.minorVersion) return true;
2078 }
2079 }
2080 return false;
2081}
2082
2083bool ResTable_config::isBetterThan(const ResTable_config& o,
2084 const ResTable_config* requested) const {
2085 if (requested) {
2086 if (imsi || o.imsi) {
2087 if ((mcc != o.mcc) && requested->mcc) {
2088 return (mcc);
2089 }
2090
2091 if ((mnc != o.mnc) && requested->mnc) {
2092 return (mnc);
2093 }
2094 }
2095
2096 if (locale || o.locale) {
2097 if ((language[0] != o.language[0]) && requested->language[0]) {
2098 return (language[0]);
2099 }
2100
2101 if ((country[0] != o.country[0]) && requested->country[0]) {
2102 return (country[0]);
2103 }
2104 }
2105
Narayan Kamath48620f12014-01-20 13:57:11 +00002106 if (localeScript[0] || o.localeScript[0]) {
2107 if (localeScript[0] != o.localeScript[0] && requested->localeScript[0]) {
2108 return localeScript[0];
2109 }
2110 }
2111
2112 if (localeVariant[0] || o.localeVariant[0]) {
2113 if (localeVariant[0] != o.localeVariant[0] && requested->localeVariant[0]) {
2114 return localeVariant[0];
2115 }
2116 }
2117
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07002118 if (screenLayout || o.screenLayout) {
2119 if (((screenLayout^o.screenLayout) & MASK_LAYOUTDIR) != 0
2120 && (requested->screenLayout & MASK_LAYOUTDIR)) {
2121 int myLayoutDir = screenLayout & MASK_LAYOUTDIR;
2122 int oLayoutDir = o.screenLayout & MASK_LAYOUTDIR;
2123 return (myLayoutDir > oLayoutDir);
2124 }
2125 }
2126
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002127 if (smallestScreenWidthDp || o.smallestScreenWidthDp) {
2128 // The configuration closest to the actual size is best.
2129 // We assume that larger configs have already been filtered
2130 // out at this point. That means we just want the largest one.
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08002131 if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
2132 return smallestScreenWidthDp > o.smallestScreenWidthDp;
2133 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002134 }
2135
2136 if (screenSizeDp || o.screenSizeDp) {
2137 // "Better" is based on the sum of the difference between both
2138 // width and height from the requested dimensions. We are
2139 // assuming the invalid configs (with smaller dimens) have
2140 // already been filtered. Note that if a particular dimension
2141 // is unspecified, we will end up with a large value (the
2142 // difference between 0 and the requested dimension), which is
2143 // good since we will prefer a config that has specified a
2144 // dimension value.
2145 int myDelta = 0, otherDelta = 0;
2146 if (requested->screenWidthDp) {
2147 myDelta += requested->screenWidthDp - screenWidthDp;
2148 otherDelta += requested->screenWidthDp - o.screenWidthDp;
2149 }
2150 if (requested->screenHeightDp) {
2151 myDelta += requested->screenHeightDp - screenHeightDp;
2152 otherDelta += requested->screenHeightDp - o.screenHeightDp;
2153 }
2154 //ALOGI("Comparing this %dx%d to other %dx%d in %dx%d: myDelta=%d otherDelta=%d",
2155 // screenWidthDp, screenHeightDp, o.screenWidthDp, o.screenHeightDp,
2156 // requested->screenWidthDp, requested->screenHeightDp, myDelta, otherDelta);
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08002157 if (myDelta != otherDelta) {
2158 return myDelta < otherDelta;
2159 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002160 }
2161
2162 if (screenLayout || o.screenLayout) {
2163 if (((screenLayout^o.screenLayout) & MASK_SCREENSIZE) != 0
2164 && (requested->screenLayout & MASK_SCREENSIZE)) {
2165 // A little backwards compatibility here: undefined is
2166 // considered equivalent to normal. But only if the
2167 // requested size is at least normal; otherwise, small
2168 // is better than the default.
2169 int mySL = (screenLayout & MASK_SCREENSIZE);
2170 int oSL = (o.screenLayout & MASK_SCREENSIZE);
2171 int fixedMySL = mySL;
2172 int fixedOSL = oSL;
2173 if ((requested->screenLayout & MASK_SCREENSIZE) >= SCREENSIZE_NORMAL) {
2174 if (fixedMySL == 0) fixedMySL = SCREENSIZE_NORMAL;
2175 if (fixedOSL == 0) fixedOSL = SCREENSIZE_NORMAL;
2176 }
2177 // For screen size, the best match is the one that is
2178 // closest to the requested screen size, but not over
2179 // (the not over part is dealt with in match() below).
2180 if (fixedMySL == fixedOSL) {
2181 // If the two are the same, but 'this' is actually
2182 // undefined, then the other is really a better match.
2183 if (mySL == 0) return false;
2184 return true;
2185 }
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08002186 if (fixedMySL != fixedOSL) {
2187 return fixedMySL > fixedOSL;
2188 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002189 }
2190 if (((screenLayout^o.screenLayout) & MASK_SCREENLONG) != 0
2191 && (requested->screenLayout & MASK_SCREENLONG)) {
2192 return (screenLayout & MASK_SCREENLONG);
2193 }
2194 }
2195
2196 if ((orientation != o.orientation) && requested->orientation) {
2197 return (orientation);
2198 }
2199
2200 if (uiMode || o.uiMode) {
2201 if (((uiMode^o.uiMode) & MASK_UI_MODE_TYPE) != 0
2202 && (requested->uiMode & MASK_UI_MODE_TYPE)) {
2203 return (uiMode & MASK_UI_MODE_TYPE);
2204 }
2205 if (((uiMode^o.uiMode) & MASK_UI_MODE_NIGHT) != 0
2206 && (requested->uiMode & MASK_UI_MODE_NIGHT)) {
2207 return (uiMode & MASK_UI_MODE_NIGHT);
2208 }
2209 }
2210
2211 if (screenType || o.screenType) {
2212 if (density != o.density) {
Adam Lesinski31245b42014-08-22 19:10:56 -07002213 // Use the system default density (DENSITY_MEDIUM, 160dpi) if none specified.
2214 const int thisDensity = density ? density : int(ResTable_config::DENSITY_MEDIUM);
2215 const int otherDensity = o.density ? o.density : int(ResTable_config::DENSITY_MEDIUM);
2216
2217 // We always prefer DENSITY_ANY over scaling a density bucket.
2218 if (thisDensity == ResTable_config::DENSITY_ANY) {
2219 return true;
2220 } else if (otherDensity == ResTable_config::DENSITY_ANY) {
2221 return false;
2222 }
2223
2224 int requestedDensity = requested->density;
2225 if (requested->density == 0 ||
2226 requested->density == ResTable_config::DENSITY_ANY) {
2227 requestedDensity = ResTable_config::DENSITY_MEDIUM;
2228 }
2229
2230 // DENSITY_ANY is now dealt with. We should look to
2231 // pick a density bucket and potentially scale it.
2232 // Any density is potentially useful
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002233 // because the system will scale it. Scaling down
2234 // is generally better than scaling up.
Adam Lesinski31245b42014-08-22 19:10:56 -07002235 int h = thisDensity;
2236 int l = otherDensity;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002237 bool bImBigger = true;
2238 if (l > h) {
2239 int t = h;
2240 h = l;
2241 l = t;
2242 bImBigger = false;
2243 }
2244
Adam Lesinski31245b42014-08-22 19:10:56 -07002245 if (requestedDensity >= h) {
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002246 // requested value higher than both l and h, give h
2247 return bImBigger;
2248 }
Adam Lesinski31245b42014-08-22 19:10:56 -07002249 if (l >= requestedDensity) {
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002250 // requested value lower than both l and h, give l
2251 return !bImBigger;
2252 }
2253 // saying that scaling down is 2x better than up
Adam Lesinski31245b42014-08-22 19:10:56 -07002254 if (((2 * l) - requestedDensity) * h > requestedDensity * requestedDensity) {
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002255 return !bImBigger;
2256 } else {
2257 return bImBigger;
2258 }
2259 }
2260
2261 if ((touchscreen != o.touchscreen) && requested->touchscreen) {
2262 return (touchscreen);
2263 }
2264 }
2265
2266 if (input || o.input) {
2267 const int keysHidden = inputFlags & MASK_KEYSHIDDEN;
2268 const int oKeysHidden = o.inputFlags & MASK_KEYSHIDDEN;
2269 if (keysHidden != oKeysHidden) {
2270 const int reqKeysHidden =
2271 requested->inputFlags & MASK_KEYSHIDDEN;
2272 if (reqKeysHidden) {
2273
2274 if (!keysHidden) return false;
2275 if (!oKeysHidden) return true;
2276 // For compatibility, we count KEYSHIDDEN_NO as being
2277 // the same as KEYSHIDDEN_SOFT. Here we disambiguate
2278 // these by making an exact match more specific.
2279 if (reqKeysHidden == keysHidden) return true;
2280 if (reqKeysHidden == oKeysHidden) return false;
2281 }
2282 }
2283
2284 const int navHidden = inputFlags & MASK_NAVHIDDEN;
2285 const int oNavHidden = o.inputFlags & MASK_NAVHIDDEN;
2286 if (navHidden != oNavHidden) {
2287 const int reqNavHidden =
2288 requested->inputFlags & MASK_NAVHIDDEN;
2289 if (reqNavHidden) {
2290
2291 if (!navHidden) return false;
2292 if (!oNavHidden) return true;
2293 }
2294 }
2295
2296 if ((keyboard != o.keyboard) && requested->keyboard) {
2297 return (keyboard);
2298 }
2299
2300 if ((navigation != o.navigation) && requested->navigation) {
2301 return (navigation);
2302 }
2303 }
2304
2305 if (screenSize || o.screenSize) {
2306 // "Better" is based on the sum of the difference between both
2307 // width and height from the requested dimensions. We are
2308 // assuming the invalid configs (with smaller sizes) have
2309 // already been filtered. Note that if a particular dimension
2310 // is unspecified, we will end up with a large value (the
2311 // difference between 0 and the requested dimension), which is
2312 // good since we will prefer a config that has specified a
2313 // size value.
2314 int myDelta = 0, otherDelta = 0;
2315 if (requested->screenWidth) {
2316 myDelta += requested->screenWidth - screenWidth;
2317 otherDelta += requested->screenWidth - o.screenWidth;
2318 }
2319 if (requested->screenHeight) {
2320 myDelta += requested->screenHeight - screenHeight;
2321 otherDelta += requested->screenHeight - o.screenHeight;
2322 }
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08002323 if (myDelta != otherDelta) {
2324 return myDelta < otherDelta;
2325 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002326 }
2327
2328 if (version || o.version) {
2329 if ((sdkVersion != o.sdkVersion) && requested->sdkVersion) {
2330 return (sdkVersion > o.sdkVersion);
2331 }
2332
2333 if ((minorVersion != o.minorVersion) &&
2334 requested->minorVersion) {
2335 return (minorVersion);
2336 }
2337 }
2338
2339 return false;
2340 }
2341 return isMoreSpecificThan(o);
2342}
2343
2344bool ResTable_config::match(const ResTable_config& settings) const {
2345 if (imsi != 0) {
2346 if (mcc != 0 && mcc != settings.mcc) {
2347 return false;
2348 }
2349 if (mnc != 0 && mnc != settings.mnc) {
2350 return false;
2351 }
2352 }
2353 if (locale != 0) {
Narayan Kamath48620f12014-01-20 13:57:11 +00002354 // Don't consider the script & variants when deciding matches.
2355 //
2356 // If we two configs differ only in their script or language, they
2357 // can be weeded out in the isMoreSpecificThan test.
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002358 if (language[0] != 0
2359 && (language[0] != settings.language[0]
2360 || language[1] != settings.language[1])) {
2361 return false;
2362 }
Narayan Kamath48620f12014-01-20 13:57:11 +00002363
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002364 if (country[0] != 0
2365 && (country[0] != settings.country[0]
2366 || country[1] != settings.country[1])) {
2367 return false;
2368 }
2369 }
Narayan Kamath48620f12014-01-20 13:57:11 +00002370
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002371 if (screenConfig != 0) {
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07002372 const int layoutDir = screenLayout&MASK_LAYOUTDIR;
2373 const int setLayoutDir = settings.screenLayout&MASK_LAYOUTDIR;
2374 if (layoutDir != 0 && layoutDir != setLayoutDir) {
2375 return false;
2376 }
2377
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002378 const int screenSize = screenLayout&MASK_SCREENSIZE;
2379 const int setScreenSize = settings.screenLayout&MASK_SCREENSIZE;
2380 // Any screen sizes for larger screens than the setting do not
2381 // match.
2382 if (screenSize != 0 && screenSize > setScreenSize) {
2383 return false;
2384 }
2385
2386 const int screenLong = screenLayout&MASK_SCREENLONG;
2387 const int setScreenLong = settings.screenLayout&MASK_SCREENLONG;
2388 if (screenLong != 0 && screenLong != setScreenLong) {
2389 return false;
2390 }
2391
2392 const int uiModeType = uiMode&MASK_UI_MODE_TYPE;
2393 const int setUiModeType = settings.uiMode&MASK_UI_MODE_TYPE;
2394 if (uiModeType != 0 && uiModeType != setUiModeType) {
2395 return false;
2396 }
2397
2398 const int uiModeNight = uiMode&MASK_UI_MODE_NIGHT;
2399 const int setUiModeNight = settings.uiMode&MASK_UI_MODE_NIGHT;
2400 if (uiModeNight != 0 && uiModeNight != setUiModeNight) {
2401 return false;
2402 }
2403
2404 if (smallestScreenWidthDp != 0
2405 && smallestScreenWidthDp > settings.smallestScreenWidthDp) {
2406 return false;
2407 }
2408 }
2409 if (screenSizeDp != 0) {
2410 if (screenWidthDp != 0 && screenWidthDp > settings.screenWidthDp) {
2411 //ALOGI("Filtering out width %d in requested %d", screenWidthDp, settings.screenWidthDp);
2412 return false;
2413 }
2414 if (screenHeightDp != 0 && screenHeightDp > settings.screenHeightDp) {
2415 //ALOGI("Filtering out height %d in requested %d", screenHeightDp, settings.screenHeightDp);
2416 return false;
2417 }
2418 }
2419 if (screenType != 0) {
2420 if (orientation != 0 && orientation != settings.orientation) {
2421 return false;
2422 }
2423 // density always matches - we can scale it. See isBetterThan
2424 if (touchscreen != 0 && touchscreen != settings.touchscreen) {
2425 return false;
2426 }
2427 }
2428 if (input != 0) {
2429 const int keysHidden = inputFlags&MASK_KEYSHIDDEN;
2430 const int setKeysHidden = settings.inputFlags&MASK_KEYSHIDDEN;
2431 if (keysHidden != 0 && keysHidden != setKeysHidden) {
2432 // For compatibility, we count a request for KEYSHIDDEN_NO as also
2433 // matching the more recent KEYSHIDDEN_SOFT. Basically
2434 // KEYSHIDDEN_NO means there is some kind of keyboard available.
2435 //ALOGI("Matching keysHidden: have=%d, config=%d\n", keysHidden, setKeysHidden);
2436 if (keysHidden != KEYSHIDDEN_NO || setKeysHidden != KEYSHIDDEN_SOFT) {
2437 //ALOGI("No match!");
2438 return false;
2439 }
2440 }
2441 const int navHidden = inputFlags&MASK_NAVHIDDEN;
2442 const int setNavHidden = settings.inputFlags&MASK_NAVHIDDEN;
2443 if (navHidden != 0 && navHidden != setNavHidden) {
2444 return false;
2445 }
2446 if (keyboard != 0 && keyboard != settings.keyboard) {
2447 return false;
2448 }
2449 if (navigation != 0 && navigation != settings.navigation) {
2450 return false;
2451 }
2452 }
2453 if (screenSize != 0) {
2454 if (screenWidth != 0 && screenWidth > settings.screenWidth) {
2455 return false;
2456 }
2457 if (screenHeight != 0 && screenHeight > settings.screenHeight) {
2458 return false;
2459 }
2460 }
2461 if (version != 0) {
2462 if (sdkVersion != 0 && sdkVersion > settings.sdkVersion) {
2463 return false;
2464 }
2465 if (minorVersion != 0 && minorVersion != settings.minorVersion) {
2466 return false;
2467 }
2468 }
2469 return true;
2470}
2471
Narayan Kamath788fa412014-01-21 15:32:36 +00002472void ResTable_config::getBcp47Locale(char str[RESTABLE_MAX_LOCALE_LEN]) const {
Narayan Kamath48620f12014-01-20 13:57:11 +00002473 memset(str, 0, RESTABLE_MAX_LOCALE_LEN);
2474
2475 // This represents the "any" locale value, which has traditionally been
2476 // represented by the empty string.
2477 if (!language[0] && !country[0]) {
2478 return;
2479 }
2480
2481 size_t charsWritten = 0;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002482 if (language[0]) {
Narayan Kamath788fa412014-01-21 15:32:36 +00002483 charsWritten += unpackLanguage(str);
Narayan Kamath48620f12014-01-20 13:57:11 +00002484 }
2485
2486 if (localeScript[0]) {
2487 if (charsWritten) {
Narayan Kamath788fa412014-01-21 15:32:36 +00002488 str[charsWritten++] = '-';
Narayan Kamath48620f12014-01-20 13:57:11 +00002489 }
2490 memcpy(str + charsWritten, localeScript, sizeof(localeScript));
Narayan Kamath788fa412014-01-21 15:32:36 +00002491 charsWritten += sizeof(localeScript);
2492 }
2493
2494 if (country[0]) {
2495 if (charsWritten) {
2496 str[charsWritten++] = '-';
2497 }
2498 charsWritten += unpackRegion(str + charsWritten);
Narayan Kamath48620f12014-01-20 13:57:11 +00002499 }
2500
2501 if (localeVariant[0]) {
2502 if (charsWritten) {
Narayan Kamath788fa412014-01-21 15:32:36 +00002503 str[charsWritten++] = '-';
Narayan Kamath48620f12014-01-20 13:57:11 +00002504 }
2505 memcpy(str + charsWritten, localeVariant, sizeof(localeVariant));
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002506 }
2507}
2508
Narayan Kamath788fa412014-01-21 15:32:36 +00002509/* static */ inline bool assignLocaleComponent(ResTable_config* config,
2510 const char* start, size_t size) {
2511
2512 switch (size) {
2513 case 0:
2514 return false;
2515 case 2:
2516 case 3:
2517 config->language[0] ? config->packRegion(start) : config->packLanguage(start);
2518 break;
2519 case 4:
2520 config->localeScript[0] = toupper(start[0]);
2521 for (size_t i = 1; i < 4; ++i) {
2522 config->localeScript[i] = tolower(start[i]);
2523 }
2524 break;
2525 case 5:
2526 case 6:
2527 case 7:
2528 case 8:
2529 for (size_t i = 0; i < size; ++i) {
2530 config->localeVariant[i] = tolower(start[i]);
2531 }
2532 break;
2533 default:
2534 return false;
2535 }
2536
2537 return true;
2538}
2539
2540void ResTable_config::setBcp47Locale(const char* in) {
2541 locale = 0;
2542 memset(localeScript, 0, sizeof(localeScript));
2543 memset(localeVariant, 0, sizeof(localeVariant));
2544
2545 const char* separator = in;
2546 const char* start = in;
2547 while ((separator = strchr(start, '-')) != NULL) {
2548 const size_t size = separator - start;
2549 if (!assignLocaleComponent(this, start, size)) {
2550 fprintf(stderr, "Invalid BCP-47 locale string: %s", in);
2551 }
2552
2553 start = (separator + 1);
2554 }
2555
2556 const size_t size = in + strlen(in) - start;
2557 assignLocaleComponent(this, start, size);
2558}
2559
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002560String8 ResTable_config::toString() const {
2561 String8 res;
2562
2563 if (mcc != 0) {
2564 if (res.size() > 0) res.append("-");
Adam Lesinskifab50872014-04-16 14:40:42 -07002565 res.appendFormat("mcc%d", dtohs(mcc));
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002566 }
2567 if (mnc != 0) {
2568 if (res.size() > 0) res.append("-");
Adam Lesinskifab50872014-04-16 14:40:42 -07002569 res.appendFormat("mnc%d", dtohs(mnc));
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002570 }
Adam Lesinskifab50872014-04-16 14:40:42 -07002571
Narayan Kamath48620f12014-01-20 13:57:11 +00002572 char localeStr[RESTABLE_MAX_LOCALE_LEN];
Narayan Kamath788fa412014-01-21 15:32:36 +00002573 getBcp47Locale(localeStr);
Adam Lesinskifab50872014-04-16 14:40:42 -07002574 if (strlen(localeStr) > 0) {
2575 if (res.size() > 0) res.append("-");
2576 res.append(localeStr);
2577 }
Narayan Kamath48620f12014-01-20 13:57:11 +00002578
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07002579 if ((screenLayout&MASK_LAYOUTDIR) != 0) {
2580 if (res.size() > 0) res.append("-");
2581 switch (screenLayout&ResTable_config::MASK_LAYOUTDIR) {
2582 case ResTable_config::LAYOUTDIR_LTR:
Fabrice Di Meglio8a802db2012-09-05 13:12:02 -07002583 res.append("ldltr");
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07002584 break;
2585 case ResTable_config::LAYOUTDIR_RTL:
Fabrice Di Meglio8a802db2012-09-05 13:12:02 -07002586 res.append("ldrtl");
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07002587 break;
2588 default:
2589 res.appendFormat("layoutDir=%d",
2590 dtohs(screenLayout&ResTable_config::MASK_LAYOUTDIR));
2591 break;
2592 }
2593 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002594 if (smallestScreenWidthDp != 0) {
2595 if (res.size() > 0) res.append("-");
2596 res.appendFormat("sw%ddp", dtohs(smallestScreenWidthDp));
2597 }
2598 if (screenWidthDp != 0) {
2599 if (res.size() > 0) res.append("-");
2600 res.appendFormat("w%ddp", dtohs(screenWidthDp));
2601 }
2602 if (screenHeightDp != 0) {
2603 if (res.size() > 0) res.append("-");
2604 res.appendFormat("h%ddp", dtohs(screenHeightDp));
2605 }
2606 if ((screenLayout&MASK_SCREENSIZE) != SCREENSIZE_ANY) {
2607 if (res.size() > 0) res.append("-");
2608 switch (screenLayout&ResTable_config::MASK_SCREENSIZE) {
2609 case ResTable_config::SCREENSIZE_SMALL:
2610 res.append("small");
2611 break;
2612 case ResTable_config::SCREENSIZE_NORMAL:
2613 res.append("normal");
2614 break;
2615 case ResTable_config::SCREENSIZE_LARGE:
2616 res.append("large");
2617 break;
2618 case ResTable_config::SCREENSIZE_XLARGE:
2619 res.append("xlarge");
2620 break;
2621 default:
2622 res.appendFormat("screenLayoutSize=%d",
2623 dtohs(screenLayout&ResTable_config::MASK_SCREENSIZE));
2624 break;
2625 }
2626 }
2627 if ((screenLayout&MASK_SCREENLONG) != 0) {
2628 if (res.size() > 0) res.append("-");
2629 switch (screenLayout&ResTable_config::MASK_SCREENLONG) {
2630 case ResTable_config::SCREENLONG_NO:
2631 res.append("notlong");
2632 break;
2633 case ResTable_config::SCREENLONG_YES:
2634 res.append("long");
2635 break;
2636 default:
2637 res.appendFormat("screenLayoutLong=%d",
2638 dtohs(screenLayout&ResTable_config::MASK_SCREENLONG));
2639 break;
2640 }
2641 }
2642 if (orientation != ORIENTATION_ANY) {
2643 if (res.size() > 0) res.append("-");
2644 switch (orientation) {
2645 case ResTable_config::ORIENTATION_PORT:
2646 res.append("port");
2647 break;
2648 case ResTable_config::ORIENTATION_LAND:
2649 res.append("land");
2650 break;
2651 case ResTable_config::ORIENTATION_SQUARE:
2652 res.append("square");
2653 break;
2654 default:
2655 res.appendFormat("orientation=%d", dtohs(orientation));
2656 break;
2657 }
2658 }
2659 if ((uiMode&MASK_UI_MODE_TYPE) != UI_MODE_TYPE_ANY) {
2660 if (res.size() > 0) res.append("-");
2661 switch (uiMode&ResTable_config::MASK_UI_MODE_TYPE) {
2662 case ResTable_config::UI_MODE_TYPE_DESK:
2663 res.append("desk");
2664 break;
2665 case ResTable_config::UI_MODE_TYPE_CAR:
2666 res.append("car");
2667 break;
2668 case ResTable_config::UI_MODE_TYPE_TELEVISION:
2669 res.append("television");
2670 break;
2671 case ResTable_config::UI_MODE_TYPE_APPLIANCE:
2672 res.append("appliance");
2673 break;
John Spurlock6c191292014-04-03 16:37:27 -04002674 case ResTable_config::UI_MODE_TYPE_WATCH:
2675 res.append("watch");
2676 break;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002677 default:
2678 res.appendFormat("uiModeType=%d",
2679 dtohs(screenLayout&ResTable_config::MASK_UI_MODE_TYPE));
2680 break;
2681 }
2682 }
2683 if ((uiMode&MASK_UI_MODE_NIGHT) != 0) {
2684 if (res.size() > 0) res.append("-");
2685 switch (uiMode&ResTable_config::MASK_UI_MODE_NIGHT) {
2686 case ResTable_config::UI_MODE_NIGHT_NO:
2687 res.append("notnight");
2688 break;
2689 case ResTable_config::UI_MODE_NIGHT_YES:
2690 res.append("night");
2691 break;
2692 default:
2693 res.appendFormat("uiModeNight=%d",
2694 dtohs(uiMode&MASK_UI_MODE_NIGHT));
2695 break;
2696 }
2697 }
2698 if (density != DENSITY_DEFAULT) {
2699 if (res.size() > 0) res.append("-");
2700 switch (density) {
2701 case ResTable_config::DENSITY_LOW:
2702 res.append("ldpi");
2703 break;
2704 case ResTable_config::DENSITY_MEDIUM:
2705 res.append("mdpi");
2706 break;
2707 case ResTable_config::DENSITY_TV:
2708 res.append("tvdpi");
2709 break;
2710 case ResTable_config::DENSITY_HIGH:
2711 res.append("hdpi");
2712 break;
2713 case ResTable_config::DENSITY_XHIGH:
2714 res.append("xhdpi");
2715 break;
2716 case ResTable_config::DENSITY_XXHIGH:
2717 res.append("xxhdpi");
2718 break;
Adam Lesinski8d5667d2014-08-13 21:02:57 -07002719 case ResTable_config::DENSITY_XXXHIGH:
2720 res.append("xxxhdpi");
2721 break;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002722 case ResTable_config::DENSITY_NONE:
2723 res.append("nodpi");
2724 break;
Adam Lesinski31245b42014-08-22 19:10:56 -07002725 case ResTable_config::DENSITY_ANY:
2726 res.append("anydpi");
2727 break;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002728 default:
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08002729 res.appendFormat("%ddpi", dtohs(density));
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002730 break;
2731 }
2732 }
2733 if (touchscreen != TOUCHSCREEN_ANY) {
2734 if (res.size() > 0) res.append("-");
2735 switch (touchscreen) {
2736 case ResTable_config::TOUCHSCREEN_NOTOUCH:
2737 res.append("notouch");
2738 break;
2739 case ResTable_config::TOUCHSCREEN_FINGER:
2740 res.append("finger");
2741 break;
2742 case ResTable_config::TOUCHSCREEN_STYLUS:
2743 res.append("stylus");
2744 break;
2745 default:
2746 res.appendFormat("touchscreen=%d", dtohs(touchscreen));
2747 break;
2748 }
2749 }
Adam Lesinskifab50872014-04-16 14:40:42 -07002750 if ((inputFlags&MASK_KEYSHIDDEN) != 0) {
2751 if (res.size() > 0) res.append("-");
2752 switch (inputFlags&MASK_KEYSHIDDEN) {
2753 case ResTable_config::KEYSHIDDEN_NO:
2754 res.append("keysexposed");
2755 break;
2756 case ResTable_config::KEYSHIDDEN_YES:
2757 res.append("keyshidden");
2758 break;
2759 case ResTable_config::KEYSHIDDEN_SOFT:
2760 res.append("keyssoft");
2761 break;
2762 }
2763 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002764 if (keyboard != KEYBOARD_ANY) {
2765 if (res.size() > 0) res.append("-");
2766 switch (keyboard) {
2767 case ResTable_config::KEYBOARD_NOKEYS:
2768 res.append("nokeys");
2769 break;
2770 case ResTable_config::KEYBOARD_QWERTY:
2771 res.append("qwerty");
2772 break;
2773 case ResTable_config::KEYBOARD_12KEY:
2774 res.append("12key");
2775 break;
2776 default:
2777 res.appendFormat("keyboard=%d", dtohs(keyboard));
2778 break;
2779 }
2780 }
Adam Lesinskifab50872014-04-16 14:40:42 -07002781 if ((inputFlags&MASK_NAVHIDDEN) != 0) {
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002782 if (res.size() > 0) res.append("-");
Adam Lesinskifab50872014-04-16 14:40:42 -07002783 switch (inputFlags&MASK_NAVHIDDEN) {
2784 case ResTable_config::NAVHIDDEN_NO:
2785 res.append("navexposed");
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002786 break;
Adam Lesinskifab50872014-04-16 14:40:42 -07002787 case ResTable_config::NAVHIDDEN_YES:
2788 res.append("navhidden");
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002789 break;
Adam Lesinskifab50872014-04-16 14:40:42 -07002790 default:
2791 res.appendFormat("inputFlagsNavHidden=%d",
2792 dtohs(inputFlags&MASK_NAVHIDDEN));
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002793 break;
2794 }
2795 }
2796 if (navigation != NAVIGATION_ANY) {
2797 if (res.size() > 0) res.append("-");
2798 switch (navigation) {
2799 case ResTable_config::NAVIGATION_NONAV:
2800 res.append("nonav");
2801 break;
2802 case ResTable_config::NAVIGATION_DPAD:
2803 res.append("dpad");
2804 break;
2805 case ResTable_config::NAVIGATION_TRACKBALL:
2806 res.append("trackball");
2807 break;
2808 case ResTable_config::NAVIGATION_WHEEL:
2809 res.append("wheel");
2810 break;
2811 default:
2812 res.appendFormat("navigation=%d", dtohs(navigation));
2813 break;
2814 }
2815 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002816 if (screenSize != 0) {
2817 if (res.size() > 0) res.append("-");
2818 res.appendFormat("%dx%d", dtohs(screenWidth), dtohs(screenHeight));
2819 }
2820 if (version != 0) {
2821 if (res.size() > 0) res.append("-");
2822 res.appendFormat("v%d", dtohs(sdkVersion));
2823 if (minorVersion != 0) {
2824 res.appendFormat(".%d", dtohs(minorVersion));
2825 }
2826 }
2827
2828 return res;
2829}
2830
2831// --------------------------------------------------------------------
2832// --------------------------------------------------------------------
2833// --------------------------------------------------------------------
2834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835struct ResTable::Header
2836{
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01002837 Header(ResTable* _owner) : owner(_owner), ownedData(NULL), header(NULL),
2838 resourceIDMap(NULL), resourceIDMapSize(0) { }
2839
2840 ~Header()
2841 {
2842 free(resourceIDMap);
2843 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002844
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002845 const ResTable* const owner;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002846 void* ownedData;
2847 const ResTable_header* header;
2848 size_t size;
2849 const uint8_t* dataEnd;
2850 size_t index;
Narayan Kamath7c4887f2014-01-27 17:32:37 +00002851 int32_t cookie;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002852
2853 ResStringPool values;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01002854 uint32_t* resourceIDMap;
2855 size_t resourceIDMapSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002856};
2857
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002858struct ResTable::Entry {
2859 ResTable_config config;
2860 const ResTable_entry* entry;
2861 const ResTable_type* type;
2862 uint32_t specFlags;
2863 const Package* package;
2864
2865 StringPoolRef typeStr;
2866 StringPoolRef keyStr;
2867};
2868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002869struct ResTable::Type
2870{
2871 Type(const Header* _header, const Package* _package, size_t count)
2872 : header(_header), package(_package), entryCount(count),
2873 typeSpec(NULL), typeSpecFlags(NULL) { }
2874 const Header* const header;
2875 const Package* const package;
2876 const size_t entryCount;
2877 const ResTable_typeSpec* typeSpec;
2878 const uint32_t* typeSpecFlags;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002879 IdmapEntries idmapEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002880 Vector<const ResTable_type*> configs;
2881};
2882
2883struct ResTable::Package
2884{
Dianne Hackborn78c40512009-07-06 11:07:40 -07002885 Package(ResTable* _owner, const Header* _header, const ResTable_package* _package)
Adam Lesinski18560882014-08-15 17:18:21 +00002886 : owner(_owner), header(_header), package(_package), typeIdOffset(0) {
2887 if (dtohs(package->header.headerSize) == sizeof(package)) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002888 // The package structure is the same size as the definition.
2889 // This means it contains the typeIdOffset field.
Adam Lesinski18560882014-08-15 17:18:21 +00002890 typeIdOffset = package->typeIdOffset;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002891 }
2892 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07002893
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002894 const ResTable* const owner;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895 const Header* const header;
Adam Lesinski18560882014-08-15 17:18:21 +00002896 const ResTable_package* const package;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897
Dianne Hackborn78c40512009-07-06 11:07:40 -07002898 ResStringPool typeStrings;
2899 ResStringPool keyStrings;
Mark Salyzyn00adb862014-03-19 11:00:06 -07002900
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002901 size_t typeIdOffset;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002902};
2903
2904// A group of objects describing a particular resource package.
2905// The first in 'package' is always the root object (from the resource
2906// table that defined the package); the ones after are skins on top of it.
2907struct ResTable::PackageGroup
2908{
Dianne Hackborn78c40512009-07-06 11:07:40 -07002909 PackageGroup(ResTable* _owner, const String16& _name, uint32_t _id)
Adam Lesinskide898ff2014-01-29 18:20:45 -08002910 : owner(_owner)
2911 , name(_name)
2912 , id(_id)
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002913 , largestTypeId(0)
Adam Lesinskide898ff2014-01-29 18:20:45 -08002914 , bags(NULL)
2915 , dynamicRefTable(static_cast<uint8_t>(_id))
2916 { }
2917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002918 ~PackageGroup() {
2919 clearBagCache();
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002920 const size_t numTypes = types.size();
2921 for (size_t i = 0; i < numTypes; i++) {
2922 const TypeList& typeList = types[i];
2923 const size_t numInnerTypes = typeList.size();
2924 for (size_t j = 0; j < numInnerTypes; j++) {
2925 if (typeList[j]->package->owner == owner) {
2926 delete typeList[j];
2927 }
2928 }
2929 }
2930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 const size_t N = packages.size();
2932 for (size_t i=0; i<N; i++) {
Dianne Hackborn78c40512009-07-06 11:07:40 -07002933 Package* pkg = packages[i];
2934 if (pkg->owner == owner) {
2935 delete pkg;
2936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937 }
2938 }
2939
2940 void clearBagCache() {
2941 if (bags) {
2942 TABLE_NOISY(printf("bags=%p\n", bags));
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002943 for (size_t i = 0; i < bags->size(); i++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002944 TABLE_NOISY(printf("type=%d\n", i));
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002945 const TypeList& typeList = types[i];
Adam Lesinski7f668d02014-08-28 18:32:32 -07002946 if (!typeList.isEmpty()) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002947 bag_set** typeBags = bags->get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002948 TABLE_NOISY(printf("typeBags=%p\n", typeBags));
2949 if (typeBags) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002950 const size_t N = typeList[0]->entryCount;
2951 TABLE_NOISY(printf("type->entryCount=%x\n", N));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952 for (size_t j=0; j<N; j++) {
2953 if (typeBags[j] && typeBags[j] != (bag_set*)0xFFFFFFFF)
2954 free(typeBags[j]);
2955 }
2956 free(typeBags);
2957 }
2958 }
2959 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002960 delete bags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002961 bags = NULL;
2962 }
2963 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07002964
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002965 ssize_t findType16(const char16_t* type, size_t len) const {
2966 const size_t N = packages.size();
2967 for (size_t i = 0; i < N; i++) {
2968 ssize_t index = packages[i]->typeStrings.indexOfString(type, len);
2969 if (index >= 0) {
2970 return index + packages[i]->typeIdOffset;
2971 }
2972 }
2973 return -1;
2974 }
2975
2976 const ResTable* const owner;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002977 String16 const name;
2978 uint32_t const id;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002979
2980 // This is mainly used to keep track of the loaded packages
2981 // and to clean them up properly. Accessing resources happens from
2982 // the 'types' array.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002983 Vector<Package*> packages;
Mark Salyzyn00adb862014-03-19 11:00:06 -07002984
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002985 ByteBucketArray<TypeList> types;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002986
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002987 uint8_t largestTypeId;
Mark Salyzyn00adb862014-03-19 11:00:06 -07002988
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002989 // Computed attribute bags, first indexed by the type and second
2990 // by the entry in that type.
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002991 ByteBucketArray<bag_set**>* bags;
Adam Lesinskide898ff2014-01-29 18:20:45 -08002992
2993 // The table mapping dynamic references to resolved references for
2994 // this package group.
2995 // TODO: We may be able to support dynamic references in overlays
2996 // by having these tables in a per-package scope rather than
2997 // per-package-group.
2998 DynamicRefTable dynamicRefTable;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002999};
3000
3001struct ResTable::bag_set
3002{
3003 size_t numAttrs; // number in array
3004 size_t availAttrs; // total space in array
3005 uint32_t typeSpecFlags;
3006 // Followed by 'numAttr' bag_entry structures.
3007};
3008
3009ResTable::Theme::Theme(const ResTable& table)
3010 : mTable(table)
3011{
3012 memset(mPackages, 0, sizeof(mPackages));
3013}
3014
3015ResTable::Theme::~Theme()
3016{
3017 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3018 package_info* pi = mPackages[i];
3019 if (pi != NULL) {
3020 free_package(pi);
3021 }
3022 }
3023}
3024
3025void ResTable::Theme::free_package(package_info* pi)
3026{
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003027 for (size_t j = 0; j <= Res_MAXTYPE; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003028 theme_entry* te = pi->types[j].entries;
3029 if (te != NULL) {
3030 free(te);
3031 }
3032 }
3033 free(pi);
3034}
3035
3036ResTable::Theme::package_info* ResTable::Theme::copy_package(package_info* pi)
3037{
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003038 package_info* newpi = (package_info*)malloc(sizeof(package_info));
3039 for (size_t j = 0; j <= Res_MAXTYPE; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003040 size_t cnt = pi->types[j].numEntries;
3041 newpi->types[j].numEntries = cnt;
3042 theme_entry* te = pi->types[j].entries;
3043 if (te != NULL) {
3044 theme_entry* newte = (theme_entry*)malloc(cnt*sizeof(theme_entry));
3045 newpi->types[j].entries = newte;
3046 memcpy(newte, te, cnt*sizeof(theme_entry));
3047 } else {
3048 newpi->types[j].entries = NULL;
3049 }
3050 }
3051 return newpi;
3052}
3053
3054status_t ResTable::Theme::applyStyle(uint32_t resID, bool force)
3055{
3056 const bag_entry* bag;
3057 uint32_t bagTypeSpecFlags = 0;
3058 mTable.lock();
3059 const ssize_t N = mTable.getBagLocked(resID, &bag, &bagTypeSpecFlags);
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08003060 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 -08003061 if (N < 0) {
3062 mTable.unlock();
3063 return N;
3064 }
3065
3066 uint32_t curPackage = 0xffffffff;
3067 ssize_t curPackageIndex = 0;
3068 package_info* curPI = NULL;
3069 uint32_t curType = 0xffffffff;
3070 size_t numEntries = 0;
3071 theme_entry* curEntries = NULL;
3072
3073 const bag_entry* end = bag + N;
3074 while (bag < end) {
3075 const uint32_t attrRes = bag->map.name.ident;
3076 const uint32_t p = Res_GETPACKAGE(attrRes);
3077 const uint32_t t = Res_GETTYPE(attrRes);
3078 const uint32_t e = Res_GETENTRY(attrRes);
3079
3080 if (curPackage != p) {
3081 const ssize_t pidx = mTable.getResourcePackageIndex(attrRes);
3082 if (pidx < 0) {
Steve Block3762c312012-01-06 19:20:56 +00003083 ALOGE("Style contains key with bad package: 0x%08x\n", attrRes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003084 bag++;
3085 continue;
3086 }
3087 curPackage = p;
3088 curPackageIndex = pidx;
3089 curPI = mPackages[pidx];
3090 if (curPI == NULL) {
3091 PackageGroup* const grp = mTable.mPackageGroups[pidx];
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003092 curPI = (package_info*)malloc(sizeof(package_info));
3093 memset(curPI, 0, sizeof(*curPI));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003094 mPackages[pidx] = curPI;
3095 }
3096 curType = 0xffffffff;
3097 }
3098 if (curType != t) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003099 if (t > Res_MAXTYPE) {
Steve Block3762c312012-01-06 19:20:56 +00003100 ALOGE("Style contains key with bad type: 0x%08x\n", attrRes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003101 bag++;
3102 continue;
3103 }
3104 curType = t;
3105 curEntries = curPI->types[t].entries;
3106 if (curEntries == NULL) {
3107 PackageGroup* const grp = mTable.mPackageGroups[curPackageIndex];
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003108 const TypeList& typeList = grp->types[t];
3109 int cnt = typeList.isEmpty() ? 0 : typeList[0]->entryCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003110 curEntries = (theme_entry*)malloc(cnt*sizeof(theme_entry));
3111 memset(curEntries, Res_value::TYPE_NULL, cnt*sizeof(theme_entry));
3112 curPI->types[t].numEntries = cnt;
3113 curPI->types[t].entries = curEntries;
3114 }
3115 numEntries = curPI->types[t].numEntries;
3116 }
3117 if (e >= numEntries) {
Steve Block3762c312012-01-06 19:20:56 +00003118 ALOGE("Style contains key with bad entry: 0x%08x\n", attrRes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003119 bag++;
3120 continue;
3121 }
3122 theme_entry* curEntry = curEntries + e;
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08003123 TABLE_NOISY(ALOGV("Attr 0x%08x: type=0x%x, data=0x%08x; curType=0x%x",
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003124 attrRes, bag->map.value.dataType, bag->map.value.data,
3125 curEntry->value.dataType));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003126 if (force || curEntry->value.dataType == Res_value::TYPE_NULL) {
3127 curEntry->stringBlock = bag->stringBlock;
3128 curEntry->typeSpecFlags |= bagTypeSpecFlags;
3129 curEntry->value = bag->map.value;
3130 }
3131
3132 bag++;
3133 }
3134
3135 mTable.unlock();
3136
Steve Block6215d3f2012-01-04 20:05:49 +00003137 //ALOGI("Applying style 0x%08x (force=%d) theme %p...\n", resID, force, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003138 //dumpToLog();
Mark Salyzyn00adb862014-03-19 11:00:06 -07003139
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003140 return NO_ERROR;
3141}
3142
3143status_t ResTable::Theme::setTo(const Theme& other)
3144{
Steve Block6215d3f2012-01-04 20:05:49 +00003145 //ALOGI("Setting theme %p from theme %p...\n", this, &other);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003146 //dumpToLog();
3147 //other.dumpToLog();
Mark Salyzyn00adb862014-03-19 11:00:06 -07003148
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003149 if (&mTable == &other.mTable) {
3150 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3151 if (mPackages[i] != NULL) {
3152 free_package(mPackages[i]);
3153 }
3154 if (other.mPackages[i] != NULL) {
3155 mPackages[i] = copy_package(other.mPackages[i]);
3156 } else {
3157 mPackages[i] = NULL;
3158 }
3159 }
3160 } else {
3161 // @todo: need to really implement this, not just copy
3162 // the system package (which is still wrong because it isn't
3163 // fixing up resource references).
3164 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3165 if (mPackages[i] != NULL) {
3166 free_package(mPackages[i]);
3167 }
3168 if (i == 0 && other.mPackages[i] != NULL) {
3169 mPackages[i] = copy_package(other.mPackages[i]);
3170 } else {
3171 mPackages[i] = NULL;
3172 }
3173 }
3174 }
3175
Steve Block6215d3f2012-01-04 20:05:49 +00003176 //ALOGI("Final theme:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003177 //dumpToLog();
Mark Salyzyn00adb862014-03-19 11:00:06 -07003178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003179 return NO_ERROR;
3180}
3181
3182ssize_t ResTable::Theme::getAttribute(uint32_t resID, Res_value* outValue,
3183 uint32_t* outTypeSpecFlags) const
3184{
3185 int cnt = 20;
3186
3187 if (outTypeSpecFlags != NULL) *outTypeSpecFlags = 0;
Mark Salyzyn00adb862014-03-19 11:00:06 -07003188
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003189 do {
3190 const ssize_t p = mTable.getResourcePackageIndex(resID);
3191 const uint32_t t = Res_GETTYPE(resID);
3192 const uint32_t e = Res_GETENTRY(resID);
3193
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08003194 TABLE_THEME(ALOGI("Looking up attr 0x%08x in theme %p", resID, this));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003195
3196 if (p >= 0) {
3197 const package_info* const pi = mPackages[p];
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08003198 TABLE_THEME(ALOGI("Found package: %p", pi));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 if (pi != NULL) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003200 TABLE_THEME(ALOGI("Desired type index is %ld in avail %d", t, Res_MAXTYPE + 1));
3201 if (t <= Res_MAXTYPE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003202 const type_info& ti = pi->types[t];
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08003203 TABLE_THEME(ALOGI("Desired entry index is %ld in avail %d", e, ti.numEntries));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003204 if (e < ti.numEntries) {
3205 const theme_entry& te = ti.entries[e];
Dianne Hackbornb8d81672009-11-20 14:26:42 -08003206 if (outTypeSpecFlags != NULL) {
3207 *outTypeSpecFlags |= te.typeSpecFlags;
3208 }
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08003209 TABLE_THEME(ALOGI("Theme value: type=0x%x, data=0x%08x",
Dianne Hackbornb8d81672009-11-20 14:26:42 -08003210 te.value.dataType, te.value.data));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003211 const uint8_t type = te.value.dataType;
3212 if (type == Res_value::TYPE_ATTRIBUTE) {
3213 if (cnt > 0) {
3214 cnt--;
3215 resID = te.value.data;
3216 continue;
3217 }
Steve Block8564c8d2012-01-05 23:22:43 +00003218 ALOGW("Too many attribute references, stopped at: 0x%08x\n", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003219 return BAD_INDEX;
3220 } else if (type != Res_value::TYPE_NULL) {
3221 *outValue = te.value;
3222 return te.stringBlock;
3223 }
3224 return BAD_INDEX;
3225 }
3226 }
3227 }
3228 }
3229 break;
3230
3231 } while (true);
3232
3233 return BAD_INDEX;
3234}
3235
3236ssize_t ResTable::Theme::resolveAttributeReference(Res_value* inOutValue,
3237 ssize_t blockIndex, uint32_t* outLastRef,
Dianne Hackborn0d221012009-07-29 15:41:19 -07003238 uint32_t* inoutTypeSpecFlags, ResTable_config* inoutConfig) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003239{
3240 //printf("Resolving type=0x%x\n", inOutValue->dataType);
3241 if (inOutValue->dataType == Res_value::TYPE_ATTRIBUTE) {
3242 uint32_t newTypeSpecFlags;
3243 blockIndex = getAttribute(inOutValue->data, inOutValue, &newTypeSpecFlags);
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08003244 TABLE_THEME(ALOGI("Resolving attr reference: blockIndex=%d, type=0x%x, data=%p\n",
Dianne Hackbornb8d81672009-11-20 14:26:42 -08003245 (int)blockIndex, (int)inOutValue->dataType, (void*)inOutValue->data));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003246 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newTypeSpecFlags;
3247 //printf("Retrieved attribute new type=0x%x\n", inOutValue->dataType);
3248 if (blockIndex < 0) {
3249 return blockIndex;
3250 }
3251 }
Dianne Hackborn0d221012009-07-29 15:41:19 -07003252 return mTable.resolveReference(inOutValue, blockIndex, outLastRef,
3253 inoutTypeSpecFlags, inoutConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003254}
3255
3256void ResTable::Theme::dumpToLog() const
3257{
Steve Block6215d3f2012-01-04 20:05:49 +00003258 ALOGI("Theme %p:\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003259 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3260 package_info* pi = mPackages[i];
3261 if (pi == NULL) continue;
Mark Salyzyn00adb862014-03-19 11:00:06 -07003262
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003263 ALOGI(" Package #0x%02x:\n", (int)(i + 1));
3264 for (size_t j = 0; j <= Res_MAXTYPE; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003265 type_info& ti = pi->types[j];
3266 if (ti.numEntries == 0) continue;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003267 ALOGI(" Type #0x%02x:\n", (int)(j + 1));
3268 for (size_t k = 0; k < ti.numEntries; k++) {
3269 const theme_entry& te = ti.entries[k];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003270 if (te.value.dataType == Res_value::TYPE_NULL) continue;
Steve Block6215d3f2012-01-04 20:05:49 +00003271 ALOGI(" 0x%08x: t=0x%x, d=0x%08x (block=%d)\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003272 (int)Res_MAKEID(i, j, k),
3273 te.value.dataType, (int)te.value.data, (int)te.stringBlock);
3274 }
3275 }
3276 }
3277}
3278
3279ResTable::ResTable()
Adam Lesinskide898ff2014-01-29 18:20:45 -08003280 : mError(NO_INIT), mNextPackageId(2)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003281{
3282 memset(&mParams, 0, sizeof(mParams));
3283 memset(mPackageMap, 0, sizeof(mPackageMap));
Steve Block6215d3f2012-01-04 20:05:49 +00003284 //ALOGI("Creating ResTable %p\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285}
3286
Narayan Kamath7c4887f2014-01-27 17:32:37 +00003287ResTable::ResTable(const void* data, size_t size, const int32_t cookie, bool copyData)
Adam Lesinskide898ff2014-01-29 18:20:45 -08003288 : mError(NO_INIT), mNextPackageId(2)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289{
3290 memset(&mParams, 0, sizeof(mParams));
3291 memset(mPackageMap, 0, sizeof(mPackageMap));
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003292 addInternal(data, size, NULL, 0, cookie, copyData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003293 LOG_FATAL_IF(mError != NO_ERROR, "Error parsing resource table");
Steve Block6215d3f2012-01-04 20:05:49 +00003294 //ALOGI("Creating ResTable %p\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003295}
3296
3297ResTable::~ResTable()
3298{
Steve Block6215d3f2012-01-04 20:05:49 +00003299 //ALOGI("Destroying ResTable in %p\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300 uninit();
3301}
3302
3303inline ssize_t ResTable::getResourcePackageIndex(uint32_t resID) const
3304{
3305 return ((ssize_t)mPackageMap[Res_GETPACKAGE(resID)+1])-1;
3306}
3307
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003308status_t ResTable::add(const void* data, size_t size, const int32_t cookie, bool copyData) {
3309 return addInternal(data, size, NULL, 0, cookie, copyData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003310}
3311
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003312status_t ResTable::add(const void* data, size_t size, const void* idmapData, size_t idmapDataSize,
3313 const int32_t cookie, bool copyData) {
3314 return addInternal(data, size, idmapData, idmapDataSize, cookie, copyData);
3315}
3316
3317status_t ResTable::add(Asset* asset, const int32_t cookie, bool copyData) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003318 const void* data = asset->getBuffer(true);
3319 if (data == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00003320 ALOGW("Unable to get buffer of resource asset file");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 return UNKNOWN_ERROR;
3322 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003323
3324 return addInternal(data, static_cast<size_t>(asset->getLength()), NULL, 0, cookie, copyData);
3325}
3326
3327status_t ResTable::add(Asset* asset, Asset* idmapAsset, const int32_t cookie, bool copyData) {
3328 const void* data = asset->getBuffer(true);
3329 if (data == NULL) {
3330 ALOGW("Unable to get buffer of resource asset file");
3331 return UNKNOWN_ERROR;
3332 }
3333
3334 size_t idmapSize = 0;
3335 const void* idmapData = NULL;
3336 if (idmapAsset != NULL) {
3337 idmapData = idmapAsset->getBuffer(true);
3338 if (idmapData == NULL) {
3339 ALOGW("Unable to get buffer of idmap asset file");
3340 return UNKNOWN_ERROR;
3341 }
3342 idmapSize = static_cast<size_t>(idmapAsset->getLength());
3343 }
3344
3345 return addInternal(data, static_cast<size_t>(asset->getLength()),
3346 idmapData, idmapSize, cookie, copyData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003347}
3348
Dianne Hackborn78c40512009-07-06 11:07:40 -07003349status_t ResTable::add(ResTable* src)
3350{
3351 mError = src->mError;
Mark Salyzyn00adb862014-03-19 11:00:06 -07003352
Dianne Hackborn78c40512009-07-06 11:07:40 -07003353 for (size_t i=0; i<src->mHeaders.size(); i++) {
3354 mHeaders.add(src->mHeaders[i]);
3355 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07003356
Dianne Hackborn78c40512009-07-06 11:07:40 -07003357 for (size_t i=0; i<src->mPackageGroups.size(); i++) {
3358 PackageGroup* srcPg = src->mPackageGroups[i];
3359 PackageGroup* pg = new PackageGroup(this, srcPg->name, srcPg->id);
3360 for (size_t j=0; j<srcPg->packages.size(); j++) {
3361 pg->packages.add(srcPg->packages[j]);
3362 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003363
3364 for (size_t j = 0; j < srcPg->types.size(); j++) {
3365 if (srcPg->types[j].isEmpty()) {
3366 continue;
3367 }
3368
3369 TypeList& typeList = pg->types.editItemAt(j);
3370 typeList.appendVector(srcPg->types[j]);
3371 }
Adam Lesinski6022deb2014-08-20 14:59:19 -07003372 pg->dynamicRefTable.addMappings(srcPg->dynamicRefTable);
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003373 pg->largestTypeId = max(pg->largestTypeId, srcPg->largestTypeId);
Dianne Hackborn78c40512009-07-06 11:07:40 -07003374 mPackageGroups.add(pg);
3375 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07003376
Dianne Hackborn78c40512009-07-06 11:07:40 -07003377 memcpy(mPackageMap, src->mPackageMap, sizeof(mPackageMap));
Mark Salyzyn00adb862014-03-19 11:00:06 -07003378
Dianne Hackborn78c40512009-07-06 11:07:40 -07003379 return mError;
3380}
3381
Adam Lesinskide898ff2014-01-29 18:20:45 -08003382status_t ResTable::addEmpty(const int32_t cookie) {
3383 Header* header = new Header(this);
3384 header->index = mHeaders.size();
3385 header->cookie = cookie;
3386 header->values.setToEmpty();
3387 header->ownedData = calloc(1, sizeof(ResTable_header));
3388
3389 ResTable_header* resHeader = (ResTable_header*) header->ownedData;
3390 resHeader->header.type = RES_TABLE_TYPE;
3391 resHeader->header.headerSize = sizeof(ResTable_header);
3392 resHeader->header.size = sizeof(ResTable_header);
3393
3394 header->header = (const ResTable_header*) resHeader;
3395 mHeaders.add(header);
Adam Lesinski961dda72014-06-09 17:10:29 -07003396 return (mError=NO_ERROR);
Adam Lesinskide898ff2014-01-29 18:20:45 -08003397}
3398
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003399status_t ResTable::addInternal(const void* data, size_t dataSize, const void* idmapData, size_t idmapDataSize,
3400 const int32_t cookie, bool copyData)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003401{
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003402 if (!data) {
3403 return NO_ERROR;
3404 }
3405
Adam Lesinskif28d5052014-07-25 15:25:04 -07003406 if (dataSize < sizeof(ResTable_header)) {
3407 ALOGE("Invalid data. Size(%d) is smaller than a ResTable_header(%d).",
3408 (int) dataSize, (int) sizeof(ResTable_header));
3409 return UNKNOWN_ERROR;
3410 }
3411
Dianne Hackborn78c40512009-07-06 11:07:40 -07003412 Header* header = new Header(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003413 header->index = mHeaders.size();
3414 header->cookie = cookie;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003415 if (idmapData != NULL) {
3416 header->resourceIDMap = (uint32_t*) malloc(idmapDataSize);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01003417 if (header->resourceIDMap == NULL) {
3418 delete header;
3419 return (mError = NO_MEMORY);
3420 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003421 memcpy(header->resourceIDMap, idmapData, idmapDataSize);
3422 header->resourceIDMapSize = idmapDataSize;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01003423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003424 mHeaders.add(header);
3425
3426 const bool notDeviceEndian = htods(0xf0) != 0xf0;
3427
3428 LOAD_TABLE_NOISY(
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003429 ALOGV("Adding resources to ResTable: data=%p, size=0x%x, cookie=%d, copy=%d "
3430 "idmap=%p\n", data, dataSize, cookie, copyData, idmap));
Mark Salyzyn00adb862014-03-19 11:00:06 -07003431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003432 if (copyData || notDeviceEndian) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003433 header->ownedData = malloc(dataSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003434 if (header->ownedData == NULL) {
3435 return (mError=NO_MEMORY);
3436 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003437 memcpy(header->ownedData, data, dataSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003438 data = header->ownedData;
3439 }
3440
3441 header->header = (const ResTable_header*)data;
3442 header->size = dtohl(header->header->header.size);
Steve Block6215d3f2012-01-04 20:05:49 +00003443 //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 -08003444 // dtohl(header->header->header.size), header->header->header.size);
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08003445 LOAD_TABLE_NOISY(ALOGV("Loading ResTable @%p:\n", header->header));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003446 if (dtohs(header->header->header.headerSize) > header->size
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003447 || header->size > dataSize) {
Steve Block8564c8d2012-01-05 23:22:43 +00003448 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 -08003449 (int)dtohs(header->header->header.headerSize),
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003450 (int)header->size, (int)dataSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003451 return (mError=BAD_TYPE);
3452 }
3453 if (((dtohs(header->header->header.headerSize)|header->size)&0x3) != 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003454 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 -08003455 (int)dtohs(header->header->header.headerSize),
3456 (int)header->size);
3457 return (mError=BAD_TYPE);
3458 }
3459 header->dataEnd = ((const uint8_t*)header->header) + header->size;
3460
3461 // Iterate through all chunks.
3462 size_t curPackage = 0;
3463
3464 const ResChunk_header* chunk =
3465 (const ResChunk_header*)(((const uint8_t*)header->header)
3466 + dtohs(header->header->header.headerSize));
3467 while (((const uint8_t*)chunk) <= (header->dataEnd-sizeof(ResChunk_header)) &&
3468 ((const uint8_t*)chunk) <= (header->dataEnd-dtohl(chunk->size))) {
3469 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), header->dataEnd, "ResTable");
3470 if (err != NO_ERROR) {
3471 return (mError=err);
3472 }
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08003473 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 -08003474 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
3475 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header))));
3476 const size_t csize = dtohl(chunk->size);
3477 const uint16_t ctype = dtohs(chunk->type);
3478 if (ctype == RES_STRING_POOL_TYPE) {
3479 if (header->values.getError() != NO_ERROR) {
3480 // Only use the first string chunk; ignore any others that
3481 // may appear.
3482 status_t err = header->values.setTo(chunk, csize);
3483 if (err != NO_ERROR) {
3484 return (mError=err);
3485 }
3486 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003487 ALOGW("Multiple string chunks found in resource table.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003488 }
3489 } else if (ctype == RES_TABLE_PACKAGE_TYPE) {
3490 if (curPackage >= dtohl(header->header->packageCount)) {
Steve Block8564c8d2012-01-05 23:22:43 +00003491 ALOGW("More package chunks were found than the %d declared in the header.",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003492 dtohl(header->header->packageCount));
3493 return (mError=BAD_TYPE);
3494 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003495
3496 if (parsePackage((ResTable_package*)chunk, header) != NO_ERROR) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003497 return mError;
3498 }
3499 curPackage++;
3500 } else {
Patrik Bannura443dd932014-02-12 13:38:54 +01003501 ALOGW("Unknown chunk type 0x%x in table at %p.\n",
3502 ctype,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003503 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)));
3504 }
3505 chunk = (const ResChunk_header*)
3506 (((const uint8_t*)chunk) + csize);
3507 }
3508
3509 if (curPackage < dtohl(header->header->packageCount)) {
Steve Block8564c8d2012-01-05 23:22:43 +00003510 ALOGW("Fewer package chunks (%d) were found than the %d declared in the header.",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003511 (int)curPackage, dtohl(header->header->packageCount));
3512 return (mError=BAD_TYPE);
3513 }
3514 mError = header->values.getError();
3515 if (mError != NO_ERROR) {
Steve Block8564c8d2012-01-05 23:22:43 +00003516 ALOGW("No string values found in resource table!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003517 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01003518
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08003519 TABLE_NOISY(ALOGV("Returning from add with mError=%d\n", mError));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003520 return mError;
3521}
3522
3523status_t ResTable::getError() const
3524{
3525 return mError;
3526}
3527
3528void ResTable::uninit()
3529{
3530 mError = NO_INIT;
3531 size_t N = mPackageGroups.size();
3532 for (size_t i=0; i<N; i++) {
3533 PackageGroup* g = mPackageGroups[i];
3534 delete g;
3535 }
3536 N = mHeaders.size();
3537 for (size_t i=0; i<N; i++) {
3538 Header* header = mHeaders[i];
Dianne Hackborn78c40512009-07-06 11:07:40 -07003539 if (header->owner == this) {
3540 if (header->ownedData) {
3541 free(header->ownedData);
3542 }
3543 delete header;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003545 }
3546
3547 mPackageGroups.clear();
3548 mHeaders.clear();
3549}
3550
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07003551bool ResTable::getResourceName(uint32_t resID, bool allowUtf8, resource_name* outName) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003552{
3553 if (mError != NO_ERROR) {
3554 return false;
3555 }
3556
3557 const ssize_t p = getResourcePackageIndex(resID);
3558 const int t = Res_GETTYPE(resID);
3559 const int e = Res_GETENTRY(resID);
3560
3561 if (p < 0) {
Dianne Hackborn6cca1592009-09-20 12:40:03 -07003562 if (Res_GETPACKAGE(resID)+1 == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003563 ALOGW("No package identifier when getting name for resource number 0x%08x", resID);
Dianne Hackborn6cca1592009-09-20 12:40:03 -07003564 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003565 ALOGW("No known package when getting name for resource number 0x%08x", resID);
Dianne Hackborn6cca1592009-09-20 12:40:03 -07003566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003567 return false;
3568 }
3569 if (t < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003570 ALOGW("No type identifier when getting name for resource number 0x%08x", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003571 return false;
3572 }
3573
3574 const PackageGroup* const grp = mPackageGroups[p];
3575 if (grp == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00003576 ALOGW("Bad identifier when getting name for resource number 0x%08x", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003577 return false;
3578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003579
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003580 Entry entry;
3581 status_t err = getEntry(grp, t, e, NULL, &entry);
3582 if (err != NO_ERROR) {
3583 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003584 }
3585
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003586 outName->package = grp->name.string();
3587 outName->packageLen = grp->name.size();
3588 if (allowUtf8) {
3589 outName->type8 = entry.typeStr.string8(&outName->typeLen);
3590 outName->name8 = entry.keyStr.string8(&outName->nameLen);
3591 } else {
3592 outName->type8 = NULL;
3593 outName->name8 = NULL;
3594 }
3595 if (outName->type8 == NULL) {
3596 outName->type = entry.typeStr.string16(&outName->typeLen);
3597 // If we have a bad index for some reason, we should abort.
3598 if (outName->type == NULL) {
3599 return false;
3600 }
3601 }
3602 if (outName->name8 == NULL) {
3603 outName->name = entry.keyStr.string16(&outName->nameLen);
3604 // If we have a bad index for some reason, we should abort.
3605 if (outName->name == NULL) {
3606 return false;
3607 }
3608 }
3609
3610 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003611}
3612
Kenny Root55fc8502010-10-28 14:47:01 -07003613ssize_t ResTable::getResource(uint32_t resID, Res_value* outValue, bool mayBeBag, uint16_t density,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003614 uint32_t* outSpecFlags, ResTable_config* outConfig) const
3615{
3616 if (mError != NO_ERROR) {
3617 return mError;
3618 }
3619
3620 const ssize_t p = getResourcePackageIndex(resID);
3621 const int t = Res_GETTYPE(resID);
3622 const int e = Res_GETENTRY(resID);
3623
3624 if (p < 0) {
Dianne Hackborn6cca1592009-09-20 12:40:03 -07003625 if (Res_GETPACKAGE(resID)+1 == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003626 ALOGW("No package identifier when getting value for resource number 0x%08x", resID);
Dianne Hackborn6cca1592009-09-20 12:40:03 -07003627 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003628 ALOGW("No known package when getting value for resource number 0x%08x", resID);
Dianne Hackborn6cca1592009-09-20 12:40:03 -07003629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003630 return BAD_INDEX;
3631 }
3632 if (t < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003633 ALOGW("No type identifier when getting value for resource number 0x%08x", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003634 return BAD_INDEX;
3635 }
3636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003637 const PackageGroup* const grp = mPackageGroups[p];
3638 if (grp == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00003639 ALOGW("Bad identifier when getting value for resource number 0x%08x", resID);
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08003640 return BAD_INDEX;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003641 }
Kenny Root55fc8502010-10-28 14:47:01 -07003642
3643 // Allow overriding density
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003644 ResTable_config desiredConfig = mParams;
Kenny Root55fc8502010-10-28 14:47:01 -07003645 if (density > 0) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003646 desiredConfig.density = density;
Kenny Root55fc8502010-10-28 14:47:01 -07003647 }
3648
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003649 Entry entry;
3650 status_t err = getEntry(grp, t, e, &desiredConfig, &entry);
3651 if (err != NO_ERROR) {
Adam Lesinskide7de472014-11-03 12:03:08 -08003652 // Only log the failure when we're not running on the host as
3653 // part of a tool. The caller will do its own logging.
3654#ifndef STATIC_ANDROIDFW_FOR_TOOLS
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003655 ALOGW("Failure getting entry for 0x%08x (t=%d e=%d) (error %d)\n",
3656 resID, t, e, err);
Adam Lesinskide7de472014-11-03 12:03:08 -08003657#endif
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003658 return err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003659 }
3660
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003661 if ((dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) != 0) {
3662 if (!mayBeBag) {
3663 ALOGW("Requesting resource 0x%08x failed because it is complex\n", resID);
Adam Lesinskide898ff2014-01-29 18:20:45 -08003664 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003665 return BAD_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003666 }
3667
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003668 const Res_value* value = reinterpret_cast<const Res_value*>(
3669 reinterpret_cast<const uint8_t*>(entry.entry) + entry.entry->size);
3670
3671 outValue->size = dtohs(value->size);
3672 outValue->res0 = value->res0;
3673 outValue->dataType = value->dataType;
3674 outValue->data = dtohl(value->data);
3675
3676 // The reference may be pointing to a resource in a shared library. These
3677 // references have build-time generated package IDs. These ids may not match
3678 // the actual package IDs of the corresponding packages in this ResTable.
3679 // We need to fix the package ID based on a mapping.
3680 if (grp->dynamicRefTable.lookupResourceValue(outValue) != NO_ERROR) {
3681 ALOGW("Failed to resolve referenced package: 0x%08x", outValue->data);
3682 return BAD_VALUE;
Kenny Root55fc8502010-10-28 14:47:01 -07003683 }
3684
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003685 TABLE_NOISY(size_t len;
3686 printf("Found value: pkg=%d, type=%d, str=%s, int=%d\n",
3687 entry.package->header->index,
3688 outValue->dataType,
3689 outValue->dataType == Res_value::TYPE_STRING
3690 ? String8(entry.package->header->values.stringAt(
3691 outValue->data, &len)).string()
3692 : "",
3693 outValue->data));
3694
3695 if (outSpecFlags != NULL) {
3696 *outSpecFlags = entry.specFlags;
3697 }
3698
3699 if (outConfig != NULL) {
3700 *outConfig = entry.config;
3701 }
3702
3703 return entry.package->header->index;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003704}
3705
3706ssize_t ResTable::resolveReference(Res_value* value, ssize_t blockIndex,
Dianne Hackborn0d221012009-07-29 15:41:19 -07003707 uint32_t* outLastRef, uint32_t* inoutTypeSpecFlags,
3708 ResTable_config* outConfig) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003709{
3710 int count=0;
Adam Lesinskide898ff2014-01-29 18:20:45 -08003711 while (blockIndex >= 0 && value->dataType == Res_value::TYPE_REFERENCE
3712 && value->data != 0 && count < 20) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003713 if (outLastRef) *outLastRef = value->data;
3714 uint32_t lastRef = value->data;
3715 uint32_t newFlags = 0;
Kenny Root55fc8502010-10-28 14:47:01 -07003716 const ssize_t newIndex = getResource(value->data, value, true, 0, &newFlags,
Dianne Hackborn0d221012009-07-29 15:41:19 -07003717 outConfig);
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08003718 if (newIndex == BAD_INDEX) {
3719 return BAD_INDEX;
3720 }
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08003721 TABLE_THEME(ALOGI("Resolving reference %p: newIndex=%d, type=0x%x, data=%p\n",
Dianne Hackbornb8d81672009-11-20 14:26:42 -08003722 (void*)lastRef, (int)newIndex, (int)value->dataType, (void*)value->data));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003723 //printf("Getting reference 0x%08x: newIndex=%d\n", value->data, newIndex);
3724 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newFlags;
3725 if (newIndex < 0) {
3726 // This can fail if the resource being referenced is a style...
3727 // in this case, just return the reference, and expect the
3728 // caller to deal with.
3729 return blockIndex;
3730 }
3731 blockIndex = newIndex;
3732 count++;
3733 }
3734 return blockIndex;
3735}
3736
3737const char16_t* ResTable::valueToString(
3738 const Res_value* value, size_t stringBlock,
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07003739 char16_t /*tmpBuffer*/ [TMP_BUFFER_SIZE], size_t* outLen) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003740{
3741 if (!value) {
3742 return NULL;
3743 }
3744 if (value->dataType == value->TYPE_STRING) {
3745 return getTableStringBlock(stringBlock)->stringAt(value->data, outLen);
3746 }
3747 // XXX do int to string conversions.
3748 return NULL;
3749}
3750
3751ssize_t ResTable::lockBag(uint32_t resID, const bag_entry** outBag) const
3752{
3753 mLock.lock();
3754 ssize_t err = getBagLocked(resID, outBag);
3755 if (err < NO_ERROR) {
3756 //printf("*** get failed! unlocking\n");
3757 mLock.unlock();
3758 }
3759 return err;
3760}
3761
Mark Salyzyn00adb862014-03-19 11:00:06 -07003762void ResTable::unlockBag(const bag_entry* /*bag*/) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003763{
3764 //printf("<<< unlockBag %p\n", this);
3765 mLock.unlock();
3766}
3767
3768void ResTable::lock() const
3769{
3770 mLock.lock();
3771}
3772
3773void ResTable::unlock() const
3774{
3775 mLock.unlock();
3776}
3777
3778ssize_t ResTable::getBagLocked(uint32_t resID, const bag_entry** outBag,
3779 uint32_t* outTypeSpecFlags) const
3780{
3781 if (mError != NO_ERROR) {
3782 return mError;
3783 }
3784
3785 const ssize_t p = getResourcePackageIndex(resID);
3786 const int t = Res_GETTYPE(resID);
3787 const int e = Res_GETENTRY(resID);
3788
3789 if (p < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003790 ALOGW("Invalid package identifier when getting bag for resource number 0x%08x", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003791 return BAD_INDEX;
3792 }
3793 if (t < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003794 ALOGW("No type identifier when getting bag for resource number 0x%08x", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003795 return BAD_INDEX;
3796 }
3797
3798 //printf("Get bag: id=0x%08x, p=%d, t=%d\n", resID, p, t);
3799 PackageGroup* const grp = mPackageGroups[p];
3800 if (grp == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00003801 ALOGW("Bad identifier when getting bag for resource number 0x%08x", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003802 return BAD_INDEX;
3803 }
3804
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003805 const TypeList& typeConfigs = grp->types[t];
3806 if (typeConfigs.isEmpty()) {
3807 ALOGW("Type identifier 0x%x does not exist.", t+1);
3808 return BAD_INDEX;
3809 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003810
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003811 const size_t NENTRY = typeConfigs[0]->entryCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003812 if (e >= (int)NENTRY) {
Steve Block8564c8d2012-01-05 23:22:43 +00003813 ALOGW("Entry identifier 0x%x is larger than entry count 0x%x",
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003814 e, (int)typeConfigs[0]->entryCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003815 return BAD_INDEX;
3816 }
3817
3818 // First see if we've already computed this bag...
3819 if (grp->bags) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003820 bag_set** typeSet = grp->bags->get(t);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003821 if (typeSet) {
3822 bag_set* set = typeSet[e];
3823 if (set) {
3824 if (set != (bag_set*)0xFFFFFFFF) {
3825 if (outTypeSpecFlags != NULL) {
3826 *outTypeSpecFlags = set->typeSpecFlags;
3827 }
3828 *outBag = (bag_entry*)(set+1);
Steve Block6215d3f2012-01-04 20:05:49 +00003829 //ALOGI("Found existing bag for: %p\n", (void*)resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003830 return set->numAttrs;
3831 }
Steve Block8564c8d2012-01-05 23:22:43 +00003832 ALOGW("Attempt to retrieve bag 0x%08x which is invalid or in a cycle.",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003833 resID);
3834 return BAD_INDEX;
3835 }
3836 }
3837 }
3838
3839 // Bag not found, we need to compute it!
3840 if (!grp->bags) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003841 grp->bags = new ByteBucketArray<bag_set**>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003842 if (!grp->bags) return NO_MEMORY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003843 }
3844
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003845 bag_set** typeSet = grp->bags->get(t);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003846 if (!typeSet) {
Iliyan Malchev7e1d3952012-02-17 12:15:58 -08003847 typeSet = (bag_set**)calloc(NENTRY, sizeof(bag_set*));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003848 if (!typeSet) return NO_MEMORY;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003849 grp->bags->set(t, typeSet);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003850 }
3851
3852 // Mark that we are currently working on this one.
3853 typeSet[e] = (bag_set*)0xFFFFFFFF;
3854
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003855 TABLE_NOISY(ALOGI("Building bag: %p\n", (void*)resID));
3856
3857 // Now collect all bag attributes
3858 Entry entry;
3859 status_t err = getEntry(grp, t, e, &mParams, &entry);
3860 if (err != NO_ERROR) {
3861 return err;
3862 }
3863
3864 const uint16_t entrySize = dtohs(entry.entry->size);
3865 const uint32_t parent = entrySize >= sizeof(ResTable_map_entry)
3866 ? dtohl(((const ResTable_map_entry*)entry.entry)->parent.ident) : 0;
3867 const uint32_t count = entrySize >= sizeof(ResTable_map_entry)
3868 ? dtohl(((const ResTable_map_entry*)entry.entry)->count) : 0;
3869
3870 size_t N = count;
3871
3872 TABLE_NOISY(ALOGI("Found map: size=%p parent=%p count=%d\n",
3873 entrySize, parent, count));
3874
3875 // If this map inherits from another, we need to start
3876 // with its parent's values. Otherwise start out empty.
3877 TABLE_NOISY(printf("Creating new bag, entrySize=0x%08x, parent=0x%08x\n",
3878 entrySize, parent));
3879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003880 // This is what we are building.
3881 bag_set* set = NULL;
3882
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003883 if (parent) {
3884 uint32_t resolvedParent = parent;
Mark Salyzyn00adb862014-03-19 11:00:06 -07003885
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003886 // Bags encode a parent reference without using the standard
3887 // Res_value structure. That means we must always try to
3888 // resolve a parent reference in case it is actually a
3889 // TYPE_DYNAMIC_REFERENCE.
3890 status_t err = grp->dynamicRefTable.lookupResourceId(&resolvedParent);
3891 if (err != NO_ERROR) {
3892 ALOGE("Failed resolving bag parent id 0x%08x", parent);
3893 return UNKNOWN_ERROR;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01003894 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003895
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003896 const bag_entry* parentBag;
3897 uint32_t parentTypeSpecFlags = 0;
3898 const ssize_t NP = getBagLocked(resolvedParent, &parentBag, &parentTypeSpecFlags);
3899 const size_t NT = ((NP >= 0) ? NP : 0) + N;
3900 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*NT);
3901 if (set == NULL) {
3902 return NO_MEMORY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003904 if (NP > 0) {
3905 memcpy(set+1, parentBag, NP*sizeof(bag_entry));
3906 set->numAttrs = NP;
3907 TABLE_NOISY(ALOGI("Initialized new bag with %d inherited attributes.\n", NP));
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01003908 } else {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003909 TABLE_NOISY(ALOGI("Initialized new bag with no inherited attributes.\n"));
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01003910 set->numAttrs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003911 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003912 set->availAttrs = NT;
3913 set->typeSpecFlags = parentTypeSpecFlags;
3914 } else {
3915 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*N);
3916 if (set == NULL) {
3917 return NO_MEMORY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003918 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003919 set->numAttrs = 0;
3920 set->availAttrs = N;
3921 set->typeSpecFlags = 0;
3922 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07003923
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003924 set->typeSpecFlags |= entry.specFlags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003925
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003926 // Now merge in the new attributes...
3927 size_t curOff = (reinterpret_cast<uintptr_t>(entry.entry) - reinterpret_cast<uintptr_t>(entry.type))
3928 + dtohs(entry.entry->size);
3929 const ResTable_map* map;
3930 bag_entry* entries = (bag_entry*)(set+1);
3931 size_t curEntry = 0;
3932 uint32_t pos = 0;
3933 TABLE_NOISY(ALOGI("Starting with set %p, entries=%p, avail=%d\n",
3934 set, entries, set->availAttrs));
3935 while (pos < count) {
3936 TABLE_NOISY(printf("Now at %p\n", (void*)curOff));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003937
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003938 if (curOff > (dtohl(entry.type->header.size)-sizeof(ResTable_map))) {
3939 ALOGW("ResTable_map at %d is beyond type chunk data %d",
3940 (int)curOff, dtohl(entry.type->header.size));
3941 return BAD_TYPE;
3942 }
3943 map = (const ResTable_map*)(((const uint8_t*)entry.type) + curOff);
3944 N++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003945
Adam Lesinskiccf25c7b2014-08-08 15:32:40 -07003946 uint32_t newName = htodl(map->name.ident);
3947 if (!Res_INTERNALID(newName)) {
3948 // Attributes don't have a resource id as the name. They specify
3949 // other data, which would be wrong to change via a lookup.
3950 if (grp->dynamicRefTable.lookupResourceId(&newName) != NO_ERROR) {
3951 ALOGE("Failed resolving ResTable_map name at %d with ident 0x%08x",
3952 (int) curOff, (int) newName);
3953 return UNKNOWN_ERROR;
3954 }
3955 }
3956
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003957 bool isInside;
3958 uint32_t oldName = 0;
3959 while ((isInside=(curEntry < set->numAttrs))
3960 && (oldName=entries[curEntry].map.name.ident) < newName) {
3961 TABLE_NOISY(printf("#%d: Keeping existing attribute: 0x%08x\n",
3962 curEntry, entries[curEntry].map.name.ident));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003963 curEntry++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003964 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003965
3966 if ((!isInside) || oldName != newName) {
3967 // This is a new attribute... figure out what to do with it.
3968 if (set->numAttrs >= set->availAttrs) {
3969 // Need to alloc more memory...
3970 const size_t newAvail = set->availAttrs+N;
3971 set = (bag_set*)realloc(set,
3972 sizeof(bag_set)
3973 + sizeof(bag_entry)*newAvail);
3974 if (set == NULL) {
3975 return NO_MEMORY;
3976 }
3977 set->availAttrs = newAvail;
3978 entries = (bag_entry*)(set+1);
3979 TABLE_NOISY(printf("Reallocated set %p, entries=%p, avail=%d\n",
3980 set, entries, set->availAttrs));
3981 }
3982 if (isInside) {
3983 // Going in the middle, need to make space.
3984 memmove(entries+curEntry+1, entries+curEntry,
3985 sizeof(bag_entry)*(set->numAttrs-curEntry));
3986 set->numAttrs++;
3987 }
3988 TABLE_NOISY(printf("#%d: Inserting new attribute: 0x%08x\n",
3989 curEntry, newName));
3990 } else {
3991 TABLE_NOISY(printf("#%d: Replacing existing attribute: 0x%08x\n",
3992 curEntry, oldName));
3993 }
3994
3995 bag_entry* cur = entries+curEntry;
3996
3997 cur->stringBlock = entry.package->header->index;
3998 cur->map.name.ident = newName;
3999 cur->map.value.copyFrom_dtoh(map->value);
4000 status_t err = grp->dynamicRefTable.lookupResourceValue(&cur->map.value);
4001 if (err != NO_ERROR) {
4002 ALOGE("Reference item(0x%08x) in bag could not be resolved.", cur->map.value.data);
4003 return UNKNOWN_ERROR;
4004 }
4005
4006 TABLE_NOISY(printf("Setting entry #%d %p: block=%d, name=0x%08x, type=%d, data=0x%08x\n",
4007 curEntry, cur, cur->stringBlock, cur->map.name.ident,
4008 cur->map.value.dataType, cur->map.value.data));
4009
4010 // On to the next!
4011 curEntry++;
4012 pos++;
4013 const size_t size = dtohs(map->value.size);
4014 curOff += size + sizeof(*map)-sizeof(map->value);
4015 };
4016
4017 if (curEntry > set->numAttrs) {
4018 set->numAttrs = curEntry;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004019 }
4020
4021 // And this is it...
4022 typeSet[e] = set;
4023 if (set) {
4024 if (outTypeSpecFlags != NULL) {
4025 *outTypeSpecFlags = set->typeSpecFlags;
4026 }
4027 *outBag = (bag_entry*)(set+1);
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08004028 TABLE_NOISY(ALOGI("Returning %d attrs\n", set->numAttrs));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004029 return set->numAttrs;
4030 }
4031 return BAD_INDEX;
4032}
4033
4034void ResTable::setParameters(const ResTable_config* params)
4035{
4036 mLock.lock();
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08004037 TABLE_GETENTRY(ALOGI("Setting parameters: %s\n", params->toString().string()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004038 mParams = *params;
4039 for (size_t i=0; i<mPackageGroups.size(); i++) {
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08004040 TABLE_NOISY(ALOGI("CLEARING BAGS FOR GROUP %d!", i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004041 mPackageGroups[i]->clearBagCache();
4042 }
4043 mLock.unlock();
4044}
4045
4046void ResTable::getParameters(ResTable_config* params) const
4047{
4048 mLock.lock();
4049 *params = mParams;
4050 mLock.unlock();
4051}
4052
4053struct id_name_map {
4054 uint32_t id;
4055 size_t len;
4056 char16_t name[6];
4057};
4058
4059const static id_name_map ID_NAMES[] = {
4060 { ResTable_map::ATTR_TYPE, 5, { '^', 't', 'y', 'p', 'e' } },
4061 { ResTable_map::ATTR_L10N, 5, { '^', 'l', '1', '0', 'n' } },
4062 { ResTable_map::ATTR_MIN, 4, { '^', 'm', 'i', 'n' } },
4063 { ResTable_map::ATTR_MAX, 4, { '^', 'm', 'a', 'x' } },
4064 { ResTable_map::ATTR_OTHER, 6, { '^', 'o', 't', 'h', 'e', 'r' } },
4065 { ResTable_map::ATTR_ZERO, 5, { '^', 'z', 'e', 'r', 'o' } },
4066 { ResTable_map::ATTR_ONE, 4, { '^', 'o', 'n', 'e' } },
4067 { ResTable_map::ATTR_TWO, 4, { '^', 't', 'w', 'o' } },
4068 { ResTable_map::ATTR_FEW, 4, { '^', 'f', 'e', 'w' } },
4069 { ResTable_map::ATTR_MANY, 5, { '^', 'm', 'a', 'n', 'y' } },
4070};
4071
4072uint32_t ResTable::identifierForName(const char16_t* name, size_t nameLen,
4073 const char16_t* type, size_t typeLen,
4074 const char16_t* package,
4075 size_t packageLen,
4076 uint32_t* outTypeSpecFlags) const
4077{
4078 TABLE_SUPER_NOISY(printf("Identifier for name: error=%d\n", mError));
4079
4080 // Check for internal resource identifier as the very first thing, so
4081 // that we will always find them even when there are no resources.
4082 if (name[0] == '^') {
4083 const int N = (sizeof(ID_NAMES)/sizeof(ID_NAMES[0]));
4084 size_t len;
4085 for (int i=0; i<N; i++) {
4086 const id_name_map* m = ID_NAMES + i;
4087 len = m->len;
4088 if (len != nameLen) {
4089 continue;
4090 }
4091 for (size_t j=1; j<len; j++) {
4092 if (m->name[j] != name[j]) {
4093 goto nope;
4094 }
4095 }
Dianne Hackborn426431a2011-06-09 11:29:08 -07004096 if (outTypeSpecFlags) {
4097 *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC;
4098 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004099 return m->id;
4100nope:
4101 ;
4102 }
4103 if (nameLen > 7) {
4104 if (name[1] == 'i' && name[2] == 'n'
4105 && name[3] == 'd' && name[4] == 'e' && name[5] == 'x'
4106 && name[6] == '_') {
4107 int index = atoi(String8(name + 7, nameLen - 7).string());
4108 if (Res_CHECKID(index)) {
Steve Block8564c8d2012-01-05 23:22:43 +00004109 ALOGW("Array resource index: %d is too large.",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004110 index);
4111 return 0;
4112 }
Dianne Hackborn426431a2011-06-09 11:29:08 -07004113 if (outTypeSpecFlags) {
4114 *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC;
4115 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004116 return Res_MAKEARRAY(index);
4117 }
4118 }
4119 return 0;
4120 }
4121
4122 if (mError != NO_ERROR) {
4123 return 0;
4124 }
4125
Dianne Hackborn426431a2011-06-09 11:29:08 -07004126 bool fakePublic = false;
4127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004128 // Figure out the package and type we are looking in...
4129
4130 const char16_t* packageEnd = NULL;
4131 const char16_t* typeEnd = NULL;
4132 const char16_t* const nameEnd = name+nameLen;
4133 const char16_t* p = name;
4134 while (p < nameEnd) {
4135 if (*p == ':') packageEnd = p;
4136 else if (*p == '/') typeEnd = p;
4137 p++;
4138 }
Dianne Hackborn426431a2011-06-09 11:29:08 -07004139 if (*name == '@') {
4140 name++;
4141 if (*name == '*') {
4142 fakePublic = true;
4143 name++;
4144 }
4145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004146 if (name >= nameEnd) {
4147 return 0;
4148 }
4149
4150 if (packageEnd) {
4151 package = name;
4152 packageLen = packageEnd-name;
4153 name = packageEnd+1;
4154 } else if (!package) {
4155 return 0;
4156 }
4157
4158 if (typeEnd) {
4159 type = name;
4160 typeLen = typeEnd-name;
4161 name = typeEnd+1;
4162 } else if (!type) {
4163 return 0;
4164 }
4165
4166 if (name >= nameEnd) {
4167 return 0;
4168 }
4169 nameLen = nameEnd-name;
4170
4171 TABLE_NOISY(printf("Looking for identifier: type=%s, name=%s, package=%s\n",
4172 String8(type, typeLen).string(),
4173 String8(name, nameLen).string(),
4174 String8(package, packageLen).string()));
4175
Adam Lesinski9b624c12014-11-19 17:49:26 -08004176 const String16 attr("attr");
4177 const String16 attrPrivate("^attr-private");
4178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004179 const size_t NG = mPackageGroups.size();
4180 for (size_t ig=0; ig<NG; ig++) {
4181 const PackageGroup* group = mPackageGroups[ig];
4182
4183 if (strzcmp16(package, packageLen,
4184 group->name.string(), group->name.size())) {
4185 TABLE_NOISY(printf("Skipping package group: %s\n", String8(group->name).string()));
4186 continue;
4187 }
4188
Adam Lesinskie60a87f2014-10-09 11:08:04 -07004189 const size_t packageCount = group->packages.size();
4190 for (size_t pi = 0; pi < packageCount; pi++) {
Adam Lesinski9b624c12014-11-19 17:49:26 -08004191 const char16_t* targetType = type;
4192 size_t targetTypeLen = typeLen;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004193
Adam Lesinski9b624c12014-11-19 17:49:26 -08004194 do {
4195 ssize_t ti = group->packages[pi]->typeStrings.indexOfString(
4196 targetType, targetTypeLen);
4197 if (ti < 0) {
Adam Lesinskie60a87f2014-10-09 11:08:04 -07004198 continue;
4199 }
4200
Adam Lesinski9b624c12014-11-19 17:49:26 -08004201 ti += group->packages[pi]->typeIdOffset;
Adam Lesinskie60a87f2014-10-09 11:08:04 -07004202
Adam Lesinski9b624c12014-11-19 17:49:26 -08004203 const uint32_t identifier = findEntry(group, ti, name, nameLen,
4204 outTypeSpecFlags);
4205 if (identifier != 0) {
4206 if (fakePublic && outTypeSpecFlags) {
4207 *outTypeSpecFlags |= ResTable_typeSpec::SPEC_PUBLIC;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004208 }
Adam Lesinski9b624c12014-11-19 17:49:26 -08004209 return identifier;
4210 }
4211 } while (strzcmp16(attr.string(), attr.size(), targetType, targetTypeLen) == 0
4212 && (targetType = attrPrivate.string())
4213 && (targetTypeLen = attrPrivate.size())
4214 );
4215 }
4216 break;
4217 }
4218 return 0;
4219}
4220
4221uint32_t ResTable::findEntry(const PackageGroup* group, ssize_t typeIndex, const char16_t* name,
4222 size_t nameLen, uint32_t* outTypeSpecFlags) const {
4223 const TypeList& typeList = group->types[typeIndex];
4224 const size_t typeCount = typeList.size();
4225 for (size_t i = 0; i < typeCount; i++) {
4226 const Type* t = typeList[i];
4227 const ssize_t ei = t->package->keyStrings.indexOfString(name, nameLen);
4228 if (ei < 0) {
4229 continue;
4230 }
4231
4232 const size_t configCount = t->configs.size();
4233 for (size_t j = 0; j < configCount; j++) {
4234 const TypeVariant tv(t->configs[j]);
4235 for (TypeVariant::iterator iter = tv.beginEntries();
4236 iter != tv.endEntries();
4237 iter++) {
4238 const ResTable_entry* entry = *iter;
4239 if (entry == NULL) {
4240 continue;
4241 }
4242
4243 if (dtohl(entry->key.index) == (size_t) ei) {
4244 uint32_t resId = Res_MAKEID(group->id - 1, typeIndex, iter.index());
4245 if (outTypeSpecFlags) {
4246 Entry result;
4247 if (getEntry(group, typeIndex, iter.index(), NULL, &result) != NO_ERROR) {
4248 ALOGW("Failed to find spec flags for 0x%08x", resId);
4249 return 0;
4250 }
4251 *outTypeSpecFlags = result.specFlags;
4252 }
4253 return resId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004254 }
4255 }
4256 }
4257 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004258 return 0;
4259}
4260
Adam Lesinski4bf58102014-11-03 11:21:19 -08004261bool ResTable::expandResourceRef(const char16_t* refStr, size_t refLen,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004262 String16* outPackage,
4263 String16* outType,
4264 String16* outName,
4265 const String16* defType,
4266 const String16* defPackage,
Dianne Hackborn426431a2011-06-09 11:29:08 -07004267 const char** outErrorMsg,
4268 bool* outPublicOnly)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004269{
4270 const char16_t* packageEnd = NULL;
4271 const char16_t* typeEnd = NULL;
4272 const char16_t* p = refStr;
4273 const char16_t* const end = p + refLen;
4274 while (p < end) {
4275 if (*p == ':') packageEnd = p;
4276 else if (*p == '/') {
4277 typeEnd = p;
4278 break;
4279 }
4280 p++;
4281 }
4282 p = refStr;
4283 if (*p == '@') p++;
4284
Dianne Hackborn426431a2011-06-09 11:29:08 -07004285 if (outPublicOnly != NULL) {
4286 *outPublicOnly = true;
4287 }
4288 if (*p == '*') {
4289 p++;
4290 if (outPublicOnly != NULL) {
4291 *outPublicOnly = false;
4292 }
4293 }
4294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004295 if (packageEnd) {
4296 *outPackage = String16(p, packageEnd-p);
4297 p = packageEnd+1;
4298 } else {
4299 if (!defPackage) {
4300 if (outErrorMsg) {
4301 *outErrorMsg = "No resource package specified";
4302 }
4303 return false;
4304 }
4305 *outPackage = *defPackage;
4306 }
4307 if (typeEnd) {
4308 *outType = String16(p, typeEnd-p);
4309 p = typeEnd+1;
4310 } else {
4311 if (!defType) {
4312 if (outErrorMsg) {
4313 *outErrorMsg = "No resource type specified";
4314 }
4315 return false;
4316 }
4317 *outType = *defType;
4318 }
4319 *outName = String16(p, end-p);
Konstantin Lopyrevddcafcb2010-06-04 14:36:49 -07004320 if(**outPackage == 0) {
4321 if(outErrorMsg) {
4322 *outErrorMsg = "Resource package cannot be an empty string";
4323 }
4324 return false;
4325 }
4326 if(**outType == 0) {
4327 if(outErrorMsg) {
4328 *outErrorMsg = "Resource type cannot be an empty string";
4329 }
4330 return false;
4331 }
4332 if(**outName == 0) {
4333 if(outErrorMsg) {
4334 *outErrorMsg = "Resource id cannot be an empty string";
4335 }
4336 return false;
4337 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004338 return true;
4339}
4340
4341static uint32_t get_hex(char c, bool* outError)
4342{
4343 if (c >= '0' && c <= '9') {
4344 return c - '0';
4345 } else if (c >= 'a' && c <= 'f') {
4346 return c - 'a' + 0xa;
4347 } else if (c >= 'A' && c <= 'F') {
4348 return c - 'A' + 0xa;
4349 }
4350 *outError = true;
4351 return 0;
4352}
4353
4354struct unit_entry
4355{
4356 const char* name;
4357 size_t len;
4358 uint8_t type;
4359 uint32_t unit;
4360 float scale;
4361};
4362
4363static const unit_entry unitNames[] = {
4364 { "px", strlen("px"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PX, 1.0f },
4365 { "dip", strlen("dip"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
4366 { "dp", strlen("dp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
4367 { "sp", strlen("sp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_SP, 1.0f },
4368 { "pt", strlen("pt"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PT, 1.0f },
4369 { "in", strlen("in"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_IN, 1.0f },
4370 { "mm", strlen("mm"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_MM, 1.0f },
4371 { "%", strlen("%"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION, 1.0f/100 },
4372 { "%p", strlen("%p"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION_PARENT, 1.0f/100 },
4373 { NULL, 0, 0, 0, 0 }
4374};
4375
4376static bool parse_unit(const char* str, Res_value* outValue,
4377 float* outScale, const char** outEnd)
4378{
4379 const char* end = str;
4380 while (*end != 0 && !isspace((unsigned char)*end)) {
4381 end++;
4382 }
4383 const size_t len = end-str;
4384
4385 const char* realEnd = end;
4386 while (*realEnd != 0 && isspace((unsigned char)*realEnd)) {
4387 realEnd++;
4388 }
4389 if (*realEnd != 0) {
4390 return false;
4391 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07004392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004393 const unit_entry* cur = unitNames;
4394 while (cur->name) {
4395 if (len == cur->len && strncmp(cur->name, str, len) == 0) {
4396 outValue->dataType = cur->type;
4397 outValue->data = cur->unit << Res_value::COMPLEX_UNIT_SHIFT;
4398 *outScale = cur->scale;
4399 *outEnd = end;
4400 //printf("Found unit %s for %s\n", cur->name, str);
4401 return true;
4402 }
4403 cur++;
4404 }
4405
4406 return false;
4407}
4408
4409
4410bool ResTable::stringToInt(const char16_t* s, size_t len, Res_value* outValue)
4411{
4412 while (len > 0 && isspace16(*s)) {
4413 s++;
4414 len--;
4415 }
4416
4417 if (len <= 0) {
4418 return false;
4419 }
4420
4421 size_t i = 0;
4422 int32_t val = 0;
4423 bool neg = false;
4424
4425 if (*s == '-') {
4426 neg = true;
4427 i++;
4428 }
4429
4430 if (s[i] < '0' || s[i] > '9') {
4431 return false;
4432 }
4433
4434 // Decimal or hex?
4435 if (s[i] == '0' && s[i+1] == 'x') {
4436 if (outValue)
4437 outValue->dataType = outValue->TYPE_INT_HEX;
4438 i += 2;
4439 bool error = false;
4440 while (i < len && !error) {
4441 val = (val*16) + get_hex(s[i], &error);
4442 i++;
4443 }
4444 if (error) {
4445 return false;
4446 }
4447 } else {
4448 if (outValue)
4449 outValue->dataType = outValue->TYPE_INT_DEC;
4450 while (i < len) {
4451 if (s[i] < '0' || s[i] > '9') {
4452 return false;
4453 }
4454 val = (val*10) + s[i]-'0';
4455 i++;
4456 }
4457 }
4458
4459 if (neg) val = -val;
4460
4461 while (i < len && isspace16(s[i])) {
4462 i++;
4463 }
4464
4465 if (i == len) {
4466 if (outValue)
4467 outValue->data = val;
4468 return true;
4469 }
4470
4471 return false;
4472}
4473
4474bool ResTable::stringToFloat(const char16_t* s, size_t len, Res_value* outValue)
4475{
4476 while (len > 0 && isspace16(*s)) {
4477 s++;
4478 len--;
4479 }
4480
4481 if (len <= 0) {
4482 return false;
4483 }
4484
4485 char buf[128];
4486 int i=0;
4487 while (len > 0 && *s != 0 && i < 126) {
4488 if (*s > 255) {
4489 return false;
4490 }
4491 buf[i++] = *s++;
4492 len--;
4493 }
4494
4495 if (len > 0) {
4496 return false;
4497 }
4498 if (buf[0] < '0' && buf[0] > '9' && buf[0] != '.') {
4499 return false;
4500 }
4501
4502 buf[i] = 0;
4503 const char* end;
4504 float f = strtof(buf, (char**)&end);
4505
4506 if (*end != 0 && !isspace((unsigned char)*end)) {
4507 // Might be a unit...
4508 float scale;
4509 if (parse_unit(end, outValue, &scale, &end)) {
4510 f *= scale;
4511 const bool neg = f < 0;
4512 if (neg) f = -f;
4513 uint64_t bits = (uint64_t)(f*(1<<23)+.5f);
4514 uint32_t radix;
4515 uint32_t shift;
4516 if ((bits&0x7fffff) == 0) {
4517 // Always use 23p0 if there is no fraction, just to make
4518 // things easier to read.
4519 radix = Res_value::COMPLEX_RADIX_23p0;
4520 shift = 23;
4521 } else if ((bits&0xffffffffff800000LL) == 0) {
4522 // Magnitude is zero -- can fit in 0 bits of precision.
4523 radix = Res_value::COMPLEX_RADIX_0p23;
4524 shift = 0;
4525 } else if ((bits&0xffffffff80000000LL) == 0) {
4526 // Magnitude can fit in 8 bits of precision.
4527 radix = Res_value::COMPLEX_RADIX_8p15;
4528 shift = 8;
4529 } else if ((bits&0xffffff8000000000LL) == 0) {
4530 // Magnitude can fit in 16 bits of precision.
4531 radix = Res_value::COMPLEX_RADIX_16p7;
4532 shift = 16;
4533 } else {
4534 // Magnitude needs entire range, so no fractional part.
4535 radix = Res_value::COMPLEX_RADIX_23p0;
4536 shift = 23;
4537 }
4538 int32_t mantissa = (int32_t)(
4539 (bits>>shift) & Res_value::COMPLEX_MANTISSA_MASK);
4540 if (neg) {
4541 mantissa = (-mantissa) & Res_value::COMPLEX_MANTISSA_MASK;
4542 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07004543 outValue->data |=
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004544 (radix<<Res_value::COMPLEX_RADIX_SHIFT)
4545 | (mantissa<<Res_value::COMPLEX_MANTISSA_SHIFT);
4546 //printf("Input value: %f 0x%016Lx, mult: %f, radix: %d, shift: %d, final: 0x%08x\n",
4547 // f * (neg ? -1 : 1), bits, f*(1<<23),
4548 // radix, shift, outValue->data);
4549 return true;
4550 }
4551 return false;
4552 }
4553
4554 while (*end != 0 && isspace((unsigned char)*end)) {
4555 end++;
4556 }
4557
4558 if (*end == 0) {
4559 if (outValue) {
4560 outValue->dataType = outValue->TYPE_FLOAT;
4561 *(float*)(&outValue->data) = f;
4562 return true;
4563 }
4564 }
4565
4566 return false;
4567}
4568
4569bool ResTable::stringToValue(Res_value* outValue, String16* outString,
4570 const char16_t* s, size_t len,
4571 bool preserveSpaces, bool coerceType,
4572 uint32_t attrID,
4573 const String16* defType,
4574 const String16* defPackage,
4575 Accessor* accessor,
4576 void* accessorCookie,
4577 uint32_t attrType,
4578 bool enforcePrivate) const
4579{
4580 bool localizationSetting = accessor != NULL && accessor->getLocalizationSetting();
4581 const char* errorMsg = NULL;
4582
4583 outValue->size = sizeof(Res_value);
4584 outValue->res0 = 0;
4585
4586 // First strip leading/trailing whitespace. Do this before handling
4587 // escapes, so they can be used to force whitespace into the string.
4588 if (!preserveSpaces) {
4589 while (len > 0 && isspace16(*s)) {
4590 s++;
4591 len--;
4592 }
4593 while (len > 0 && isspace16(s[len-1])) {
4594 len--;
4595 }
4596 // If the string ends with '\', then we keep the space after it.
4597 if (len > 0 && s[len-1] == '\\' && s[len] != 0) {
4598 len++;
4599 }
4600 }
4601
4602 //printf("Value for: %s\n", String8(s, len).string());
4603
4604 uint32_t l10nReq = ResTable_map::L10N_NOT_REQUIRED;
4605 uint32_t attrMin = 0x80000000, attrMax = 0x7fffffff;
4606 bool fromAccessor = false;
4607 if (attrID != 0 && !Res_INTERNALID(attrID)) {
4608 const ssize_t p = getResourcePackageIndex(attrID);
4609 const bag_entry* bag;
4610 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
4611 //printf("For attr 0x%08x got bag of %d\n", attrID, cnt);
4612 if (cnt >= 0) {
4613 while (cnt > 0) {
4614 //printf("Entry 0x%08x = 0x%08x\n", bag->map.name.ident, bag->map.value.data);
4615 switch (bag->map.name.ident) {
4616 case ResTable_map::ATTR_TYPE:
4617 attrType = bag->map.value.data;
4618 break;
4619 case ResTable_map::ATTR_MIN:
4620 attrMin = bag->map.value.data;
4621 break;
4622 case ResTable_map::ATTR_MAX:
4623 attrMax = bag->map.value.data;
4624 break;
4625 case ResTable_map::ATTR_L10N:
4626 l10nReq = bag->map.value.data;
4627 break;
4628 }
4629 bag++;
4630 cnt--;
4631 }
4632 unlockBag(bag);
4633 } else if (accessor && accessor->getAttributeType(attrID, &attrType)) {
4634 fromAccessor = true;
4635 if (attrType == ResTable_map::TYPE_ENUM
4636 || attrType == ResTable_map::TYPE_FLAGS
4637 || attrType == ResTable_map::TYPE_INTEGER) {
4638 accessor->getAttributeMin(attrID, &attrMin);
4639 accessor->getAttributeMax(attrID, &attrMax);
4640 }
4641 if (localizationSetting) {
4642 l10nReq = accessor->getAttributeL10N(attrID);
4643 }
4644 }
4645 }
4646
4647 const bool canStringCoerce =
4648 coerceType && (attrType&ResTable_map::TYPE_STRING) != 0;
4649
4650 if (*s == '@') {
4651 outValue->dataType = outValue->TYPE_REFERENCE;
4652
4653 // Note: we don't check attrType here because the reference can
4654 // be to any other type; we just need to count on the client making
4655 // sure the referenced type is correct.
Mark Salyzyn00adb862014-03-19 11:00:06 -07004656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004657 //printf("Looking up ref: %s\n", String8(s, len).string());
4658
4659 // It's a reference!
4660 if (len == 5 && s[1]=='n' && s[2]=='u' && s[3]=='l' && s[4]=='l') {
Alan Viverettef2969402014-10-29 17:09:36 -07004661 // Special case @null as undefined. This will be converted by
4662 // AssetManager to TYPE_NULL with data DATA_NULL_UNDEFINED.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004663 outValue->data = 0;
4664 return true;
Alan Viverettef2969402014-10-29 17:09:36 -07004665 } else if (len == 6 && s[1]=='e' && s[2]=='m' && s[3]=='p' && s[4]=='t' && s[5]=='y') {
4666 // Special case @empty as explicitly defined empty value.
4667 outValue->dataType = Res_value::TYPE_NULL;
4668 outValue->data = Res_value::DATA_NULL_EMPTY;
4669 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004670 } else {
4671 bool createIfNotFound = false;
4672 const char16_t* resourceRefName;
4673 int resourceNameLen;
4674 if (len > 2 && s[1] == '+') {
4675 createIfNotFound = true;
4676 resourceRefName = s + 2;
4677 resourceNameLen = len - 2;
4678 } else if (len > 2 && s[1] == '*') {
4679 enforcePrivate = false;
4680 resourceRefName = s + 2;
4681 resourceNameLen = len - 2;
4682 } else {
4683 createIfNotFound = false;
4684 resourceRefName = s + 1;
4685 resourceNameLen = len - 1;
4686 }
4687 String16 package, type, name;
4688 if (!expandResourceRef(resourceRefName,resourceNameLen, &package, &type, &name,
4689 defType, defPackage, &errorMsg)) {
4690 if (accessor != NULL) {
4691 accessor->reportError(accessorCookie, errorMsg);
4692 }
4693 return false;
4694 }
4695
4696 uint32_t specFlags = 0;
4697 uint32_t rid = identifierForName(name.string(), name.size(), type.string(),
4698 type.size(), package.string(), package.size(), &specFlags);
4699 if (rid != 0) {
4700 if (enforcePrivate) {
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004701 if (accessor == NULL || accessor->getAssetsPackage() != package) {
4702 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
4703 if (accessor != NULL) {
4704 accessor->reportError(accessorCookie, "Resource is not public.");
4705 }
4706 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004707 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004708 }
4709 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08004710
4711 if (accessor) {
4712 rid = Res_MAKEID(
4713 accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
4714 Res_GETTYPE(rid), Res_GETENTRY(rid));
4715 TABLE_NOISY(printf("Incl %s:%s/%s: 0x%08x\n",
4716 String8(package).string(), String8(type).string(),
4717 String8(name).string(), rid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004718 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08004719
4720 uint32_t packageId = Res_GETPACKAGE(rid) + 1;
4721 if (packageId != APP_PACKAGE_ID && packageId != SYS_PACKAGE_ID) {
4722 outValue->dataType = Res_value::TYPE_DYNAMIC_REFERENCE;
4723 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004724 outValue->data = rid;
4725 return true;
4726 }
4727
4728 if (accessor) {
4729 uint32_t rid = accessor->getCustomResourceWithCreation(package, type, name,
4730 createIfNotFound);
4731 if (rid != 0) {
4732 TABLE_NOISY(printf("Pckg %s:%s/%s: 0x%08x\n",
4733 String8(package).string(), String8(type).string(),
4734 String8(name).string(), rid));
Adam Lesinskide898ff2014-01-29 18:20:45 -08004735 uint32_t packageId = Res_GETPACKAGE(rid) + 1;
4736 if (packageId == 0x00) {
4737 outValue->data = rid;
4738 outValue->dataType = Res_value::TYPE_DYNAMIC_REFERENCE;
4739 return true;
4740 } else if (packageId == APP_PACKAGE_ID || packageId == SYS_PACKAGE_ID) {
4741 // We accept packageId's generated as 0x01 in order to support
4742 // building the android system resources
4743 outValue->data = rid;
4744 return true;
4745 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004746 }
4747 }
4748 }
4749
4750 if (accessor != NULL) {
4751 accessor->reportError(accessorCookie, "No resource found that matches the given name");
4752 }
4753 return false;
4754 }
4755
4756 // if we got to here, and localization is required and it's not a reference,
4757 // complain and bail.
4758 if (l10nReq == ResTable_map::L10N_SUGGESTED) {
4759 if (localizationSetting) {
4760 if (accessor != NULL) {
4761 accessor->reportError(accessorCookie, "This attribute must be localized.");
4762 }
4763 }
4764 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07004765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004766 if (*s == '#') {
4767 // It's a color! Convert to an integer of the form 0xaarrggbb.
4768 uint32_t color = 0;
4769 bool error = false;
4770 if (len == 4) {
4771 outValue->dataType = outValue->TYPE_INT_COLOR_RGB4;
4772 color |= 0xFF000000;
4773 color |= get_hex(s[1], &error) << 20;
4774 color |= get_hex(s[1], &error) << 16;
4775 color |= get_hex(s[2], &error) << 12;
4776 color |= get_hex(s[2], &error) << 8;
4777 color |= get_hex(s[3], &error) << 4;
4778 color |= get_hex(s[3], &error);
4779 } else if (len == 5) {
4780 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB4;
4781 color |= get_hex(s[1], &error) << 28;
4782 color |= get_hex(s[1], &error) << 24;
4783 color |= get_hex(s[2], &error) << 20;
4784 color |= get_hex(s[2], &error) << 16;
4785 color |= get_hex(s[3], &error) << 12;
4786 color |= get_hex(s[3], &error) << 8;
4787 color |= get_hex(s[4], &error) << 4;
4788 color |= get_hex(s[4], &error);
4789 } else if (len == 7) {
4790 outValue->dataType = outValue->TYPE_INT_COLOR_RGB8;
4791 color |= 0xFF000000;
4792 color |= get_hex(s[1], &error) << 20;
4793 color |= get_hex(s[2], &error) << 16;
4794 color |= get_hex(s[3], &error) << 12;
4795 color |= get_hex(s[4], &error) << 8;
4796 color |= get_hex(s[5], &error) << 4;
4797 color |= get_hex(s[6], &error);
4798 } else if (len == 9) {
4799 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB8;
4800 color |= get_hex(s[1], &error) << 28;
4801 color |= get_hex(s[2], &error) << 24;
4802 color |= get_hex(s[3], &error) << 20;
4803 color |= get_hex(s[4], &error) << 16;
4804 color |= get_hex(s[5], &error) << 12;
4805 color |= get_hex(s[6], &error) << 8;
4806 color |= get_hex(s[7], &error) << 4;
4807 color |= get_hex(s[8], &error);
4808 } else {
4809 error = true;
4810 }
4811 if (!error) {
4812 if ((attrType&ResTable_map::TYPE_COLOR) == 0) {
4813 if (!canStringCoerce) {
4814 if (accessor != NULL) {
4815 accessor->reportError(accessorCookie,
4816 "Color types not allowed");
4817 }
4818 return false;
4819 }
4820 } else {
4821 outValue->data = color;
4822 //printf("Color input=%s, output=0x%x\n", String8(s, len).string(), color);
4823 return true;
4824 }
4825 } else {
4826 if ((attrType&ResTable_map::TYPE_COLOR) != 0) {
4827 if (accessor != NULL) {
4828 accessor->reportError(accessorCookie, "Color value not valid --"
4829 " must be #rgb, #argb, #rrggbb, or #aarrggbb");
4830 }
4831 #if 0
4832 fprintf(stderr, "%s: Color ID %s value %s is not valid\n",
4833 "Resource File", //(const char*)in->getPrintableSource(),
4834 String8(*curTag).string(),
4835 String8(s, len).string());
4836 #endif
4837 return false;
4838 }
4839 }
4840 }
4841
4842 if (*s == '?') {
4843 outValue->dataType = outValue->TYPE_ATTRIBUTE;
4844
4845 // Note: we don't check attrType here because the reference can
4846 // be to any other type; we just need to count on the client making
4847 // sure the referenced type is correct.
4848
4849 //printf("Looking up attr: %s\n", String8(s, len).string());
4850
4851 static const String16 attr16("attr");
4852 String16 package, type, name;
4853 if (!expandResourceRef(s+1, len-1, &package, &type, &name,
4854 &attr16, defPackage, &errorMsg)) {
4855 if (accessor != NULL) {
4856 accessor->reportError(accessorCookie, errorMsg);
4857 }
4858 return false;
4859 }
4860
4861 //printf("Pkg: %s, Type: %s, Name: %s\n",
4862 // String8(package).string(), String8(type).string(),
4863 // String8(name).string());
4864 uint32_t specFlags = 0;
Mark Salyzyn00adb862014-03-19 11:00:06 -07004865 uint32_t rid =
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004866 identifierForName(name.string(), name.size(),
4867 type.string(), type.size(),
4868 package.string(), package.size(), &specFlags);
4869 if (rid != 0) {
4870 if (enforcePrivate) {
4871 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
4872 if (accessor != NULL) {
4873 accessor->reportError(accessorCookie, "Attribute is not public.");
4874 }
4875 return false;
4876 }
4877 }
4878 if (!accessor) {
4879 outValue->data = rid;
4880 return true;
4881 }
4882 rid = Res_MAKEID(
4883 accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
4884 Res_GETTYPE(rid), Res_GETENTRY(rid));
4885 //printf("Incl %s:%s/%s: 0x%08x\n",
4886 // String8(package).string(), String8(type).string(),
4887 // String8(name).string(), rid);
4888 outValue->data = rid;
4889 return true;
4890 }
4891
4892 if (accessor) {
4893 uint32_t rid = accessor->getCustomResource(package, type, name);
4894 if (rid != 0) {
4895 //printf("Mine %s:%s/%s: 0x%08x\n",
4896 // String8(package).string(), String8(type).string(),
4897 // String8(name).string(), rid);
4898 outValue->data = rid;
4899 return true;
4900 }
4901 }
4902
4903 if (accessor != NULL) {
4904 accessor->reportError(accessorCookie, "No resource found that matches the given name");
4905 }
4906 return false;
4907 }
4908
4909 if (stringToInt(s, len, outValue)) {
4910 if ((attrType&ResTable_map::TYPE_INTEGER) == 0) {
4911 // If this type does not allow integers, but does allow floats,
4912 // fall through on this error case because the float type should
4913 // be able to accept any integer value.
4914 if (!canStringCoerce && (attrType&ResTable_map::TYPE_FLOAT) == 0) {
4915 if (accessor != NULL) {
4916 accessor->reportError(accessorCookie, "Integer types not allowed");
4917 }
4918 return false;
4919 }
4920 } else {
4921 if (((int32_t)outValue->data) < ((int32_t)attrMin)
4922 || ((int32_t)outValue->data) > ((int32_t)attrMax)) {
4923 if (accessor != NULL) {
4924 accessor->reportError(accessorCookie, "Integer value out of range");
4925 }
4926 return false;
4927 }
4928 return true;
4929 }
4930 }
4931
4932 if (stringToFloat(s, len, outValue)) {
4933 if (outValue->dataType == Res_value::TYPE_DIMENSION) {
4934 if ((attrType&ResTable_map::TYPE_DIMENSION) != 0) {
4935 return true;
4936 }
4937 if (!canStringCoerce) {
4938 if (accessor != NULL) {
4939 accessor->reportError(accessorCookie, "Dimension types not allowed");
4940 }
4941 return false;
4942 }
4943 } else if (outValue->dataType == Res_value::TYPE_FRACTION) {
4944 if ((attrType&ResTable_map::TYPE_FRACTION) != 0) {
4945 return true;
4946 }
4947 if (!canStringCoerce) {
4948 if (accessor != NULL) {
4949 accessor->reportError(accessorCookie, "Fraction types not allowed");
4950 }
4951 return false;
4952 }
4953 } else if ((attrType&ResTable_map::TYPE_FLOAT) == 0) {
4954 if (!canStringCoerce) {
4955 if (accessor != NULL) {
4956 accessor->reportError(accessorCookie, "Float types not allowed");
4957 }
4958 return false;
4959 }
4960 } else {
4961 return true;
4962 }
4963 }
4964
4965 if (len == 4) {
4966 if ((s[0] == 't' || s[0] == 'T') &&
4967 (s[1] == 'r' || s[1] == 'R') &&
4968 (s[2] == 'u' || s[2] == 'U') &&
4969 (s[3] == 'e' || s[3] == 'E')) {
4970 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
4971 if (!canStringCoerce) {
4972 if (accessor != NULL) {
4973 accessor->reportError(accessorCookie, "Boolean types not allowed");
4974 }
4975 return false;
4976 }
4977 } else {
4978 outValue->dataType = outValue->TYPE_INT_BOOLEAN;
4979 outValue->data = (uint32_t)-1;
4980 return true;
4981 }
4982 }
4983 }
4984
4985 if (len == 5) {
4986 if ((s[0] == 'f' || s[0] == 'F') &&
4987 (s[1] == 'a' || s[1] == 'A') &&
4988 (s[2] == 'l' || s[2] == 'L') &&
4989 (s[3] == 's' || s[3] == 'S') &&
4990 (s[4] == 'e' || s[4] == 'E')) {
4991 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
4992 if (!canStringCoerce) {
4993 if (accessor != NULL) {
4994 accessor->reportError(accessorCookie, "Boolean types not allowed");
4995 }
4996 return false;
4997 }
4998 } else {
4999 outValue->dataType = outValue->TYPE_INT_BOOLEAN;
5000 outValue->data = 0;
5001 return true;
5002 }
5003 }
5004 }
5005
5006 if ((attrType&ResTable_map::TYPE_ENUM) != 0) {
5007 const ssize_t p = getResourcePackageIndex(attrID);
5008 const bag_entry* bag;
5009 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
5010 //printf("Got %d for enum\n", cnt);
5011 if (cnt >= 0) {
5012 resource_name rname;
5013 while (cnt > 0) {
5014 if (!Res_INTERNALID(bag->map.name.ident)) {
5015 //printf("Trying attr #%08x\n", bag->map.name.ident);
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07005016 if (getResourceName(bag->map.name.ident, false, &rname)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005017 #if 0
5018 printf("Matching %s against %s (0x%08x)\n",
5019 String8(s, len).string(),
5020 String8(rname.name, rname.nameLen).string(),
5021 bag->map.name.ident);
5022 #endif
5023 if (strzcmp16(s, len, rname.name, rname.nameLen) == 0) {
5024 outValue->dataType = bag->map.value.dataType;
5025 outValue->data = bag->map.value.data;
5026 unlockBag(bag);
5027 return true;
5028 }
5029 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005030
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005031 }
5032 bag++;
5033 cnt--;
5034 }
5035 unlockBag(bag);
5036 }
5037
5038 if (fromAccessor) {
5039 if (accessor->getAttributeEnum(attrID, s, len, outValue)) {
5040 return true;
5041 }
5042 }
5043 }
5044
5045 if ((attrType&ResTable_map::TYPE_FLAGS) != 0) {
5046 const ssize_t p = getResourcePackageIndex(attrID);
5047 const bag_entry* bag;
5048 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
5049 //printf("Got %d for flags\n", cnt);
5050 if (cnt >= 0) {
5051 bool failed = false;
5052 resource_name rname;
5053 outValue->dataType = Res_value::TYPE_INT_HEX;
5054 outValue->data = 0;
5055 const char16_t* end = s + len;
5056 const char16_t* pos = s;
5057 while (pos < end && !failed) {
5058 const char16_t* start = pos;
The Android Open Source Project4df24232009-03-05 14:34:35 -08005059 pos++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005060 while (pos < end && *pos != '|') {
5061 pos++;
5062 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08005063 //printf("Looking for: %s\n", String8(start, pos-start).string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005064 const bag_entry* bagi = bag;
The Android Open Source Project4df24232009-03-05 14:34:35 -08005065 ssize_t i;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005066 for (i=0; i<cnt; i++, bagi++) {
5067 if (!Res_INTERNALID(bagi->map.name.ident)) {
5068 //printf("Trying attr #%08x\n", bagi->map.name.ident);
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07005069 if (getResourceName(bagi->map.name.ident, false, &rname)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005070 #if 0
5071 printf("Matching %s against %s (0x%08x)\n",
5072 String8(start,pos-start).string(),
5073 String8(rname.name, rname.nameLen).string(),
5074 bagi->map.name.ident);
5075 #endif
5076 if (strzcmp16(start, pos-start, rname.name, rname.nameLen) == 0) {
5077 outValue->data |= bagi->map.value.data;
5078 break;
5079 }
5080 }
5081 }
5082 }
5083 if (i >= cnt) {
5084 // Didn't find this flag identifier.
5085 failed = true;
5086 }
5087 if (pos < end) {
5088 pos++;
5089 }
5090 }
5091 unlockBag(bag);
5092 if (!failed) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08005093 //printf("Final flag value: 0x%lx\n", outValue->data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005094 return true;
5095 }
5096 }
5097
5098
5099 if (fromAccessor) {
5100 if (accessor->getAttributeFlags(attrID, s, len, outValue)) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08005101 //printf("Final flag value: 0x%lx\n", outValue->data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005102 return true;
5103 }
5104 }
5105 }
5106
5107 if ((attrType&ResTable_map::TYPE_STRING) == 0) {
5108 if (accessor != NULL) {
5109 accessor->reportError(accessorCookie, "String types not allowed");
5110 }
5111 return false;
5112 }
5113
5114 // Generic string handling...
5115 outValue->dataType = outValue->TYPE_STRING;
5116 if (outString) {
5117 bool failed = collectString(outString, s, len, preserveSpaces, &errorMsg);
5118 if (accessor != NULL) {
5119 accessor->reportError(accessorCookie, errorMsg);
5120 }
5121 return failed;
5122 }
5123
5124 return true;
5125}
5126
5127bool ResTable::collectString(String16* outString,
5128 const char16_t* s, size_t len,
5129 bool preserveSpaces,
5130 const char** outErrorMsg,
5131 bool append)
5132{
5133 String16 tmp;
5134
5135 char quoted = 0;
5136 const char16_t* p = s;
5137 while (p < (s+len)) {
5138 while (p < (s+len)) {
5139 const char16_t c = *p;
5140 if (c == '\\') {
5141 break;
5142 }
5143 if (!preserveSpaces) {
5144 if (quoted == 0 && isspace16(c)
5145 && (c != ' ' || isspace16(*(p+1)))) {
5146 break;
5147 }
5148 if (c == '"' && (quoted == 0 || quoted == '"')) {
5149 break;
5150 }
5151 if (c == '\'' && (quoted == 0 || quoted == '\'')) {
Eric Fischerc87d2522009-09-01 15:20:30 -07005152 /*
5153 * In practice, when people write ' instead of \'
5154 * in a string, they are doing it by accident
5155 * instead of really meaning to use ' as a quoting
5156 * character. Warn them so they don't lose it.
5157 */
5158 if (outErrorMsg) {
5159 *outErrorMsg = "Apostrophe not preceded by \\";
5160 }
5161 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005162 }
5163 }
5164 p++;
5165 }
5166 if (p < (s+len)) {
5167 if (p > s) {
5168 tmp.append(String16(s, p-s));
5169 }
5170 if (!preserveSpaces && (*p == '"' || *p == '\'')) {
5171 if (quoted == 0) {
5172 quoted = *p;
5173 } else {
5174 quoted = 0;
5175 }
5176 p++;
5177 } else if (!preserveSpaces && isspace16(*p)) {
5178 // Space outside of a quote -- consume all spaces and
5179 // leave a single plain space char.
5180 tmp.append(String16(" "));
5181 p++;
5182 while (p < (s+len) && isspace16(*p)) {
5183 p++;
5184 }
5185 } else if (*p == '\\') {
5186 p++;
5187 if (p < (s+len)) {
5188 switch (*p) {
5189 case 't':
5190 tmp.append(String16("\t"));
5191 break;
5192 case 'n':
5193 tmp.append(String16("\n"));
5194 break;
5195 case '#':
5196 tmp.append(String16("#"));
5197 break;
5198 case '@':
5199 tmp.append(String16("@"));
5200 break;
5201 case '?':
5202 tmp.append(String16("?"));
5203 break;
5204 case '"':
5205 tmp.append(String16("\""));
5206 break;
5207 case '\'':
5208 tmp.append(String16("'"));
5209 break;
5210 case '\\':
5211 tmp.append(String16("\\"));
5212 break;
5213 case 'u':
5214 {
5215 char16_t chr = 0;
5216 int i = 0;
5217 while (i < 4 && p[1] != 0) {
5218 p++;
5219 i++;
5220 int c;
5221 if (*p >= '0' && *p <= '9') {
5222 c = *p - '0';
5223 } else if (*p >= 'a' && *p <= 'f') {
5224 c = *p - 'a' + 10;
5225 } else if (*p >= 'A' && *p <= 'F') {
5226 c = *p - 'A' + 10;
5227 } else {
5228 if (outErrorMsg) {
5229 *outErrorMsg = "Bad character in \\u unicode escape sequence";
5230 }
5231 return false;
5232 }
5233 chr = (chr<<4) | c;
5234 }
5235 tmp.append(String16(&chr, 1));
5236 } break;
5237 default:
5238 // ignore unknown escape chars.
5239 break;
5240 }
5241 p++;
5242 }
5243 }
5244 len -= (p-s);
5245 s = p;
5246 }
5247 }
5248
5249 if (tmp.size() != 0) {
5250 if (len > 0) {
5251 tmp.append(String16(s, len));
5252 }
5253 if (append) {
5254 outString->append(tmp);
5255 } else {
5256 outString->setTo(tmp);
5257 }
5258 } else {
5259 if (append) {
5260 outString->append(String16(s, len));
5261 } else {
5262 outString->setTo(s, len);
5263 }
5264 }
5265
5266 return true;
5267}
5268
5269size_t ResTable::getBasePackageCount() const
5270{
5271 if (mError != NO_ERROR) {
5272 return 0;
5273 }
5274 return mPackageGroups.size();
5275}
5276
Adam Lesinskide898ff2014-01-29 18:20:45 -08005277const String16 ResTable::getBasePackageName(size_t idx) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005278{
5279 if (mError != NO_ERROR) {
Adam Lesinskide898ff2014-01-29 18:20:45 -08005280 return String16();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005281 }
5282 LOG_FATAL_IF(idx >= mPackageGroups.size(),
5283 "Requested package index %d past package count %d",
5284 (int)idx, (int)mPackageGroups.size());
Adam Lesinskide898ff2014-01-29 18:20:45 -08005285 return mPackageGroups[idx]->name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005286}
5287
5288uint32_t ResTable::getBasePackageId(size_t idx) const
5289{
5290 if (mError != NO_ERROR) {
5291 return 0;
5292 }
5293 LOG_FATAL_IF(idx >= mPackageGroups.size(),
5294 "Requested package index %d past package count %d",
5295 (int)idx, (int)mPackageGroups.size());
5296 return mPackageGroups[idx]->id;
5297}
5298
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005299uint32_t ResTable::getLastTypeIdForPackage(size_t idx) const
5300{
5301 if (mError != NO_ERROR) {
5302 return 0;
5303 }
5304 LOG_FATAL_IF(idx >= mPackageGroups.size(),
5305 "Requested package index %d past package count %d",
5306 (int)idx, (int)mPackageGroups.size());
5307 const PackageGroup* const group = mPackageGroups[idx];
5308 return group->largestTypeId;
5309}
5310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005311size_t ResTable::getTableCount() const
5312{
5313 return mHeaders.size();
5314}
5315
5316const ResStringPool* ResTable::getTableStringBlock(size_t index) const
5317{
5318 return &mHeaders[index]->values;
5319}
5320
Narayan Kamath7c4887f2014-01-27 17:32:37 +00005321int32_t ResTable::getTableCookie(size_t index) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005322{
5323 return mHeaders[index]->cookie;
5324}
5325
Adam Lesinskide898ff2014-01-29 18:20:45 -08005326const DynamicRefTable* ResTable::getDynamicRefTableForCookie(int32_t cookie) const
5327{
5328 const size_t N = mPackageGroups.size();
5329 for (size_t i = 0; i < N; i++) {
5330 const PackageGroup* pg = mPackageGroups[i];
5331 size_t M = pg->packages.size();
5332 for (size_t j = 0; j < M; j++) {
5333 if (pg->packages[j]->header->cookie == cookie) {
5334 return &pg->dynamicRefTable;
5335 }
5336 }
5337 }
5338 return NULL;
5339}
5340
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005341void ResTable::getConfigurations(Vector<ResTable_config>* configs) const
5342{
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005343 const size_t packageCount = mPackageGroups.size();
5344 for (size_t i = 0; i < packageCount; i++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005345 const PackageGroup* packageGroup = mPackageGroups[i];
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005346 const size_t typeCount = packageGroup->types.size();
5347 for (size_t j = 0; j < typeCount; j++) {
5348 const TypeList& typeList = packageGroup->types[j];
5349 const size_t numTypes = typeList.size();
5350 for (size_t k = 0; k < numTypes; k++) {
5351 const Type* type = typeList[k];
5352 const size_t numConfigs = type->configs.size();
5353 for (size_t m = 0; m < numConfigs; m++) {
5354 const ResTable_type* config = type->configs[m];
Narayan Kamath788fa412014-01-21 15:32:36 +00005355 ResTable_config cfg;
5356 memset(&cfg, 0, sizeof(ResTable_config));
5357 cfg.copyFromDtoH(config->config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005358 // only insert unique
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005359 const size_t N = configs->size();
5360 size_t n;
5361 for (n = 0; n < N; n++) {
5362 if (0 == (*configs)[n].compare(cfg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005363 break;
5364 }
5365 }
5366 // if we didn't find it
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005367 if (n == N) {
Narayan Kamath788fa412014-01-21 15:32:36 +00005368 configs->add(cfg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005369 }
5370 }
5371 }
5372 }
5373 }
5374}
5375
5376void ResTable::getLocales(Vector<String8>* locales) const
5377{
5378 Vector<ResTable_config> configs;
Steve Block71f2cf12011-10-20 11:56:00 +01005379 ALOGV("calling getConfigurations");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005380 getConfigurations(&configs);
Steve Block71f2cf12011-10-20 11:56:00 +01005381 ALOGV("called getConfigurations size=%d", (int)configs.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005382 const size_t I = configs.size();
Narayan Kamath48620f12014-01-20 13:57:11 +00005383
5384 char locale[RESTABLE_MAX_LOCALE_LEN];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005385 for (size_t i=0; i<I; i++) {
Narayan Kamath788fa412014-01-21 15:32:36 +00005386 configs[i].getBcp47Locale(locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005387 const size_t J = locales->size();
5388 size_t j;
5389 for (j=0; j<J; j++) {
5390 if (0 == strcmp(locale, (*locales)[j].string())) {
5391 break;
5392 }
5393 }
5394 if (j == J) {
5395 locales->add(String8(locale));
5396 }
5397 }
5398}
5399
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005400StringPoolRef::StringPoolRef(const ResStringPool* pool, uint32_t index)
5401 : mPool(pool), mIndex(index) {}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005402
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005403StringPoolRef::StringPoolRef()
5404 : mPool(NULL), mIndex(0) {}
5405
5406const char* StringPoolRef::string8(size_t* outLen) const {
5407 if (mPool != NULL) {
5408 return mPool->string8At(mIndex, outLen);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005409 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005410 if (outLen != NULL) {
5411 *outLen = 0;
5412 }
5413 return NULL;
5414}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005415
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005416const char16_t* StringPoolRef::string16(size_t* outLen) const {
5417 if (mPool != NULL) {
5418 return mPool->stringAt(mIndex, outLen);
5419 }
5420 if (outLen != NULL) {
5421 *outLen = 0;
5422 }
5423 return NULL;
5424}
5425
Adam Lesinski82a2dd82014-09-17 18:34:15 -07005426bool ResTable::getResourceFlags(uint32_t resID, uint32_t* outFlags) const {
5427 if (mError != NO_ERROR) {
5428 return false;
5429 }
5430
5431 const ssize_t p = getResourcePackageIndex(resID);
5432 const int t = Res_GETTYPE(resID);
5433 const int e = Res_GETENTRY(resID);
5434
5435 if (p < 0) {
5436 if (Res_GETPACKAGE(resID)+1 == 0) {
5437 ALOGW("No package identifier when getting flags for resource number 0x%08x", resID);
5438 } else {
5439 ALOGW("No known package when getting flags for resource number 0x%08x", resID);
5440 }
5441 return false;
5442 }
5443 if (t < 0) {
5444 ALOGW("No type identifier when getting flags for resource number 0x%08x", resID);
5445 return false;
5446 }
5447
5448 const PackageGroup* const grp = mPackageGroups[p];
5449 if (grp == NULL) {
5450 ALOGW("Bad identifier when getting flags for resource number 0x%08x", resID);
5451 return false;
5452 }
5453
5454 Entry entry;
5455 status_t err = getEntry(grp, t, e, NULL, &entry);
5456 if (err != NO_ERROR) {
5457 return false;
5458 }
5459
5460 *outFlags = entry.specFlags;
5461 return true;
5462}
5463
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005464status_t ResTable::getEntry(
5465 const PackageGroup* packageGroup, int typeIndex, int entryIndex,
5466 const ResTable_config* config,
5467 Entry* outEntry) const
5468{
5469 const TypeList& typeList = packageGroup->types[typeIndex];
5470 if (typeList.isEmpty()) {
5471 ALOGV("Skipping entry type index 0x%02x because type is NULL!\n", typeIndex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005472 return BAD_TYPE;
5473 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005474
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005475 const ResTable_type* bestType = NULL;
5476 uint32_t bestOffset = ResTable_type::NO_ENTRY;
5477 const Package* bestPackage = NULL;
5478 uint32_t specFlags = 0;
5479 uint8_t actualTypeIndex = typeIndex;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005480 ResTable_config bestConfig;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005481 memset(&bestConfig, 0, sizeof(bestConfig));
Mark Salyzyn00adb862014-03-19 11:00:06 -07005482
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005483 // Iterate over the Types of each package.
5484 const size_t typeCount = typeList.size();
5485 for (size_t i = 0; i < typeCount; i++) {
5486 const Type* const typeSpec = typeList[i];
Mark Salyzyn00adb862014-03-19 11:00:06 -07005487
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005488 int realEntryIndex = entryIndex;
5489 int realTypeIndex = typeIndex;
5490 bool currentTypeIsOverlay = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005491
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005492 // Runtime overlay packages provide a mapping of app resource
5493 // ID to package resource ID.
5494 if (typeSpec->idmapEntries.hasEntries()) {
5495 uint16_t overlayEntryIndex;
5496 if (typeSpec->idmapEntries.lookup(entryIndex, &overlayEntryIndex) != NO_ERROR) {
5497 // No such mapping exists
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005498 continue;
5499 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005500 realEntryIndex = overlayEntryIndex;
5501 realTypeIndex = typeSpec->idmapEntries.overlayTypeId() - 1;
5502 currentTypeIsOverlay = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005503 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005504
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005505 if (static_cast<size_t>(realEntryIndex) >= typeSpec->entryCount) {
5506 ALOGW("For resource 0x%08x, entry index(%d) is beyond type entryCount(%d)",
5507 Res_MAKEID(packageGroup->id - 1, typeIndex, entryIndex),
5508 entryIndex, static_cast<int>(typeSpec->entryCount));
5509 // We should normally abort here, but some legacy apps declare
5510 // resources in the 'android' package (old bug in AAPT).
5511 continue;
5512 }
5513
5514 // Aggregate all the flags for each package that defines this entry.
5515 if (typeSpec->typeSpecFlags != NULL) {
5516 specFlags |= dtohl(typeSpec->typeSpecFlags[realEntryIndex]);
5517 } else {
5518 specFlags = -1;
5519 }
5520
5521 const size_t numConfigs = typeSpec->configs.size();
5522 for (size_t c = 0; c < numConfigs; c++) {
5523 const ResTable_type* const thisType = typeSpec->configs[c];
5524 if (thisType == NULL) {
5525 continue;
5526 }
5527
5528 ResTable_config thisConfig;
5529 thisConfig.copyFromDtoH(thisType->config);
5530
5531 // Check to make sure this one is valid for the current parameters.
5532 if (config != NULL && !thisConfig.match(*config)) {
5533 continue;
5534 }
5535
5536 // Check if there is the desired entry in this type.
5537 const uint8_t* const end = reinterpret_cast<const uint8_t*>(thisType)
5538 + dtohl(thisType->header.size);
5539 const uint32_t* const eindex = reinterpret_cast<const uint32_t*>(
5540 reinterpret_cast<const uint8_t*>(thisType) + dtohs(thisType->header.headerSize));
5541
5542 uint32_t thisOffset = dtohl(eindex[realEntryIndex]);
5543 if (thisOffset == ResTable_type::NO_ENTRY) {
5544 // There is no entry for this index and configuration.
5545 continue;
5546 }
5547
5548 if (bestType != NULL) {
5549 // Check if this one is less specific than the last found. If so,
5550 // we will skip it. We check starting with things we most care
5551 // about to those we least care about.
5552 if (!thisConfig.isBetterThan(bestConfig, config)) {
5553 if (!currentTypeIsOverlay || thisConfig.compare(bestConfig) != 0) {
5554 continue;
5555 }
5556 }
5557 }
5558
5559 bestType = thisType;
5560 bestOffset = thisOffset;
5561 bestConfig = thisConfig;
5562 bestPackage = typeSpec->package;
5563 actualTypeIndex = realTypeIndex;
5564
5565 // If no config was specified, any type will do, so skip
5566 if (config == NULL) {
5567 break;
5568 }
5569 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005570 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005571
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005572 if (bestType == NULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005573 return BAD_INDEX;
5574 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005575
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005576 bestOffset += dtohl(bestType->entriesStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005577
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005578 if (bestOffset > (dtohl(bestType->header.size)-sizeof(ResTable_entry))) {
Steve Block8564c8d2012-01-05 23:22:43 +00005579 ALOGW("ResTable_entry at 0x%x is beyond type chunk data 0x%x",
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005580 bestOffset, dtohl(bestType->header.size));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005581 return BAD_TYPE;
5582 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005583 if ((bestOffset & 0x3) != 0) {
5584 ALOGW("ResTable_entry at 0x%x is not on an integer boundary", bestOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005585 return BAD_TYPE;
5586 }
5587
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005588 const ResTable_entry* const entry = reinterpret_cast<const ResTable_entry*>(
5589 reinterpret_cast<const uint8_t*>(bestType) + bestOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005590 if (dtohs(entry->size) < sizeof(*entry)) {
Steve Block8564c8d2012-01-05 23:22:43 +00005591 ALOGW("ResTable_entry size 0x%x is too small", dtohs(entry->size));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005592 return BAD_TYPE;
5593 }
5594
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005595 if (outEntry != NULL) {
5596 outEntry->entry = entry;
5597 outEntry->config = bestConfig;
5598 outEntry->type = bestType;
5599 outEntry->specFlags = specFlags;
5600 outEntry->package = bestPackage;
5601 outEntry->typeStr = StringPoolRef(&bestPackage->typeStrings, actualTypeIndex - bestPackage->typeIdOffset);
5602 outEntry->keyStr = StringPoolRef(&bestPackage->keyStrings, dtohl(entry->key.index));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005603 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005604 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005605}
5606
5607status_t ResTable::parsePackage(const ResTable_package* const pkg,
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005608 const Header* const header)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005609{
5610 const uint8_t* base = (const uint8_t*)pkg;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005611 status_t err = validate_chunk(&pkg->header, sizeof(*pkg) - sizeof(pkg->typeIdOffset),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005612 header->dataEnd, "ResTable_package");
5613 if (err != NO_ERROR) {
5614 return (mError=err);
5615 }
5616
Patrik Bannura443dd932014-02-12 13:38:54 +01005617 const uint32_t pkgSize = dtohl(pkg->header.size);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005618
5619 if (dtohl(pkg->typeStrings) >= pkgSize) {
Patrik Bannura443dd932014-02-12 13:38:54 +01005620 ALOGW("ResTable_package type strings at 0x%x are past chunk size 0x%x.",
5621 dtohl(pkg->typeStrings), pkgSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005622 return (mError=BAD_TYPE);
5623 }
5624 if ((dtohl(pkg->typeStrings)&0x3) != 0) {
Patrik Bannura443dd932014-02-12 13:38:54 +01005625 ALOGW("ResTable_package type strings at 0x%x is not on an integer boundary.",
5626 dtohl(pkg->typeStrings));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005627 return (mError=BAD_TYPE);
5628 }
5629 if (dtohl(pkg->keyStrings) >= pkgSize) {
Patrik Bannura443dd932014-02-12 13:38:54 +01005630 ALOGW("ResTable_package key strings at 0x%x are past chunk size 0x%x.",
5631 dtohl(pkg->keyStrings), pkgSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005632 return (mError=BAD_TYPE);
5633 }
5634 if ((dtohl(pkg->keyStrings)&0x3) != 0) {
Patrik Bannura443dd932014-02-12 13:38:54 +01005635 ALOGW("ResTable_package key strings at 0x%x is not on an integer boundary.",
5636 dtohl(pkg->keyStrings));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005637 return (mError=BAD_TYPE);
5638 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005639
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005640 uint32_t id = dtohl(pkg->id);
5641 KeyedVector<uint8_t, IdmapEntries> idmapEntries;
Mark Salyzyn00adb862014-03-19 11:00:06 -07005642
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005643 if (header->resourceIDMap != NULL) {
5644 uint8_t targetPackageId = 0;
5645 status_t err = parseIdmap(header->resourceIDMap, header->resourceIDMapSize, &targetPackageId, &idmapEntries);
5646 if (err != NO_ERROR) {
5647 ALOGW("Overlay is broken");
5648 return (mError=err);
5649 }
5650 id = targetPackageId;
5651 }
5652
5653 if (id >= 256) {
5654 LOG_ALWAYS_FATAL("Package id out of range");
5655 return NO_ERROR;
5656 } else if (id == 0) {
5657 // This is a library so assign an ID
5658 id = mNextPackageId++;
5659 }
5660
5661 PackageGroup* group = NULL;
5662 Package* package = new Package(this, header, pkg);
5663 if (package == NULL) {
5664 return (mError=NO_MEMORY);
5665 }
5666
5667 err = package->typeStrings.setTo(base+dtohl(pkg->typeStrings),
5668 header->dataEnd-(base+dtohl(pkg->typeStrings)));
5669 if (err != NO_ERROR) {
5670 delete group;
5671 delete package;
5672 return (mError=err);
5673 }
5674
5675 err = package->keyStrings.setTo(base+dtohl(pkg->keyStrings),
5676 header->dataEnd-(base+dtohl(pkg->keyStrings)));
5677 if (err != NO_ERROR) {
5678 delete group;
5679 delete package;
5680 return (mError=err);
5681 }
5682
5683 size_t idx = mPackageMap[id];
5684 if (idx == 0) {
5685 idx = mPackageGroups.size() + 1;
5686
Adam Lesinski4bf58102014-11-03 11:21:19 -08005687 char16_t tmpName[sizeof(pkg->name)/sizeof(pkg->name[0])];
5688 strcpy16_dtoh(tmpName, pkg->name, sizeof(pkg->name)/sizeof(pkg->name[0]));
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005689 group = new PackageGroup(this, String16(tmpName), id);
5690 if (group == NULL) {
5691 delete package;
Dianne Hackborn78c40512009-07-06 11:07:40 -07005692 return (mError=NO_MEMORY);
5693 }
Adam Lesinskifab50872014-04-16 14:40:42 -07005694
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005695 err = mPackageGroups.add(group);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005696 if (err < NO_ERROR) {
5697 return (mError=err);
5698 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005699
5700 mPackageMap[id] = static_cast<uint8_t>(idx);
5701
5702 // Find all packages that reference this package
5703 size_t N = mPackageGroups.size();
5704 for (size_t i = 0; i < N; i++) {
5705 mPackageGroups[i]->dynamicRefTable.addMapping(
5706 group->name, static_cast<uint8_t>(group->id));
5707 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005708 } else {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005709 group = mPackageGroups.itemAt(idx - 1);
5710 if (group == NULL) {
5711 return (mError=UNKNOWN_ERROR);
5712 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005713 }
5714
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005715 err = group->packages.add(package);
5716 if (err < NO_ERROR) {
5717 return (mError=err);
5718 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005720 // Iterate through all chunks.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005721 const ResChunk_header* chunk =
5722 (const ResChunk_header*)(((const uint8_t*)pkg)
5723 + dtohs(pkg->header.headerSize));
5724 const uint8_t* endPos = ((const uint8_t*)pkg) + dtohs(pkg->header.size);
5725 while (((const uint8_t*)chunk) <= (endPos-sizeof(ResChunk_header)) &&
5726 ((const uint8_t*)chunk) <= (endPos-dtohl(chunk->size))) {
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08005727 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 -08005728 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
5729 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header))));
5730 const size_t csize = dtohl(chunk->size);
5731 const uint16_t ctype = dtohs(chunk->type);
5732 if (ctype == RES_TABLE_TYPE_SPEC_TYPE) {
5733 const ResTable_typeSpec* typeSpec = (const ResTable_typeSpec*)(chunk);
5734 err = validate_chunk(&typeSpec->header, sizeof(*typeSpec),
5735 endPos, "ResTable_typeSpec");
5736 if (err != NO_ERROR) {
5737 return (mError=err);
5738 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005740 const size_t typeSpecSize = dtohl(typeSpec->header.size);
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005741 const size_t newEntryCount = dtohl(typeSpec->entryCount);
Mark Salyzyn00adb862014-03-19 11:00:06 -07005742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005743 LOAD_TABLE_NOISY(printf("TypeSpec off %p: type=0x%x, headerSize=0x%x, size=%p\n",
5744 (void*)(base-(const uint8_t*)chunk),
5745 dtohs(typeSpec->header.type),
5746 dtohs(typeSpec->header.headerSize),
Adam Lesinskide898ff2014-01-29 18:20:45 -08005747 (void*)typeSpecSize));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005748 // look for block overrun or int overflow when multiplying by 4
5749 if ((dtohl(typeSpec->entryCount) > (INT32_MAX/sizeof(uint32_t))
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005750 || dtohs(typeSpec->header.headerSize)+(sizeof(uint32_t)*newEntryCount)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005751 > typeSpecSize)) {
Steve Block8564c8d2012-01-05 23:22:43 +00005752 ALOGW("ResTable_typeSpec entry index to %p extends beyond chunk end %p.",
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005753 (void*)(dtohs(typeSpec->header.headerSize) + (sizeof(uint32_t)*newEntryCount)),
5754 (void*)typeSpecSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005755 return (mError=BAD_TYPE);
5756 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005758 if (typeSpec->id == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005759 ALOGW("ResTable_type has an id of 0.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005760 return (mError=BAD_TYPE);
5761 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005762
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005763 if (newEntryCount > 0) {
5764 uint8_t typeIndex = typeSpec->id - 1;
5765 ssize_t idmapIndex = idmapEntries.indexOfKey(typeSpec->id);
5766 if (idmapIndex >= 0) {
5767 typeIndex = idmapEntries[idmapIndex].targetTypeId() - 1;
5768 }
5769
5770 TypeList& typeList = group->types.editItemAt(typeIndex);
5771 if (!typeList.isEmpty()) {
5772 const Type* existingType = typeList[0];
5773 if (existingType->entryCount != newEntryCount && idmapIndex < 0) {
5774 ALOGW("ResTable_typeSpec entry count inconsistent: given %d, previously %d",
5775 (int) newEntryCount, (int) existingType->entryCount);
5776 // We should normally abort here, but some legacy apps declare
5777 // resources in the 'android' package (old bug in AAPT).
5778 }
5779 }
5780
5781 Type* t = new Type(header, package, newEntryCount);
5782 t->typeSpec = typeSpec;
5783 t->typeSpecFlags = (const uint32_t*)(
5784 ((const uint8_t*)typeSpec) + dtohs(typeSpec->header.headerSize));
5785 if (idmapIndex >= 0) {
5786 t->idmapEntries = idmapEntries[idmapIndex];
5787 }
5788 typeList.add(t);
5789 group->largestTypeId = max(group->largestTypeId, typeSpec->id);
5790 } else {
5791 ALOGV("Skipping empty ResTable_typeSpec for type %d", typeSpec->id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005792 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005794 } else if (ctype == RES_TABLE_TYPE_TYPE) {
5795 const ResTable_type* type = (const ResTable_type*)(chunk);
5796 err = validate_chunk(&type->header, sizeof(*type)-sizeof(ResTable_config)+4,
5797 endPos, "ResTable_type");
5798 if (err != NO_ERROR) {
5799 return (mError=err);
5800 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005801
Patrik Bannura443dd932014-02-12 13:38:54 +01005802 const uint32_t typeSize = dtohl(type->header.size);
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005803 const size_t newEntryCount = dtohl(type->entryCount);
Mark Salyzyn00adb862014-03-19 11:00:06 -07005804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005805 LOAD_TABLE_NOISY(printf("Type off %p: type=0x%x, headerSize=0x%x, size=%p\n",
5806 (void*)(base-(const uint8_t*)chunk),
5807 dtohs(type->header.type),
5808 dtohs(type->header.headerSize),
5809 (void*)typeSize));
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005810 if (dtohs(type->header.headerSize)+(sizeof(uint32_t)*newEntryCount)
5811 > typeSize) {
Patrik Bannura443dd932014-02-12 13:38:54 +01005812 ALOGW("ResTable_type entry index to %p extends beyond chunk end 0x%x.",
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005813 (void*)(dtohs(type->header.headerSize) + (sizeof(uint32_t)*newEntryCount)),
5814 typeSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005815 return (mError=BAD_TYPE);
5816 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005817
5818 if (newEntryCount != 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005819 && dtohl(type->entriesStart) > (typeSize-sizeof(ResTable_entry))) {
Patrik Bannura443dd932014-02-12 13:38:54 +01005820 ALOGW("ResTable_type entriesStart at 0x%x extends beyond chunk end 0x%x.",
5821 dtohl(type->entriesStart), typeSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005822 return (mError=BAD_TYPE);
5823 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005825 if (type->id == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005826 ALOGW("ResTable_type has an id of 0.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005827 return (mError=BAD_TYPE);
5828 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005829
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005830 if (newEntryCount > 0) {
5831 uint8_t typeIndex = type->id - 1;
5832 ssize_t idmapIndex = idmapEntries.indexOfKey(type->id);
5833 if (idmapIndex >= 0) {
5834 typeIndex = idmapEntries[idmapIndex].targetTypeId() - 1;
5835 }
5836
5837 TypeList& typeList = group->types.editItemAt(typeIndex);
5838 if (typeList.isEmpty()) {
5839 ALOGE("No TypeSpec for type %d", type->id);
5840 return (mError=BAD_TYPE);
5841 }
5842
5843 Type* t = typeList.editItemAt(typeList.size() - 1);
5844 if (newEntryCount != t->entryCount) {
5845 ALOGE("ResTable_type entry count inconsistent: given %d, previously %d",
5846 (int)newEntryCount, (int)t->entryCount);
5847 return (mError=BAD_TYPE);
5848 }
5849
5850 if (t->package != package) {
5851 ALOGE("No TypeSpec for type %d", type->id);
5852 return (mError=BAD_TYPE);
5853 }
5854
5855 t->configs.add(type);
5856
5857 TABLE_GETENTRY(
5858 ResTable_config thisConfig;
5859 thisConfig.copyFromDtoH(type->config);
5860 ALOGI("Adding config to type %d: %s\n",
5861 type->id, thisConfig.toString().string()));
5862 } else {
5863 ALOGV("Skipping empty ResTable_type for type %d", type->id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005864 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005865
Adam Lesinskide898ff2014-01-29 18:20:45 -08005866 } else if (ctype == RES_TABLE_LIBRARY_TYPE) {
5867 if (group->dynamicRefTable.entries().size() == 0) {
5868 status_t err = group->dynamicRefTable.load((const ResTable_lib_header*) chunk);
5869 if (err != NO_ERROR) {
5870 return (mError=err);
5871 }
5872
5873 // Fill in the reference table with the entries we already know about.
5874 size_t N = mPackageGroups.size();
5875 for (size_t i = 0; i < N; i++) {
5876 group->dynamicRefTable.addMapping(mPackageGroups[i]->name, mPackageGroups[i]->id);
5877 }
5878 } else {
5879 ALOGW("Found multiple library tables, ignoring...");
5880 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005881 } else {
5882 status_t err = validate_chunk(chunk, sizeof(ResChunk_header),
5883 endPos, "ResTable_package:unknown");
5884 if (err != NO_ERROR) {
5885 return (mError=err);
5886 }
5887 }
5888 chunk = (const ResChunk_header*)
5889 (((const uint8_t*)chunk) + csize);
5890 }
5891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005892 return NO_ERROR;
5893}
5894
Adam Lesinskide898ff2014-01-29 18:20:45 -08005895DynamicRefTable::DynamicRefTable(uint8_t packageId)
5896 : mAssignedPackageId(packageId)
5897{
5898 memset(mLookupTable, 0, sizeof(mLookupTable));
5899
5900 // Reserved package ids
5901 mLookupTable[APP_PACKAGE_ID] = APP_PACKAGE_ID;
5902 mLookupTable[SYS_PACKAGE_ID] = SYS_PACKAGE_ID;
5903}
5904
5905status_t DynamicRefTable::load(const ResTable_lib_header* const header)
5906{
5907 const uint32_t entryCount = dtohl(header->count);
5908 const uint32_t sizeOfEntries = sizeof(ResTable_lib_entry) * entryCount;
5909 const uint32_t expectedSize = dtohl(header->header.size) - dtohl(header->header.headerSize);
5910 if (sizeOfEntries > expectedSize) {
5911 ALOGE("ResTable_lib_header size %u is too small to fit %u entries (x %u).",
5912 expectedSize, entryCount, (uint32_t)sizeof(ResTable_lib_entry));
5913 return UNKNOWN_ERROR;
5914 }
5915
5916 const ResTable_lib_entry* entry = (const ResTable_lib_entry*)(((uint8_t*) header) +
5917 dtohl(header->header.headerSize));
5918 for (uint32_t entryIndex = 0; entryIndex < entryCount; entryIndex++) {
5919 uint32_t packageId = dtohl(entry->packageId);
5920 char16_t tmpName[sizeof(entry->packageName) / sizeof(char16_t)];
5921 strcpy16_dtoh(tmpName, entry->packageName, sizeof(entry->packageName) / sizeof(char16_t));
5922 LIB_NOISY(ALOGV("Found lib entry %s with id %d\n", String8(tmpName).string(),
5923 dtohl(entry->packageId)));
5924 if (packageId >= 256) {
5925 ALOGE("Bad package id 0x%08x", packageId);
5926 return UNKNOWN_ERROR;
5927 }
5928 mEntries.replaceValueFor(String16(tmpName), (uint8_t) packageId);
5929 entry = entry + 1;
5930 }
5931 return NO_ERROR;
5932}
5933
Adam Lesinski6022deb2014-08-20 14:59:19 -07005934status_t DynamicRefTable::addMappings(const DynamicRefTable& other) {
5935 if (mAssignedPackageId != other.mAssignedPackageId) {
5936 return UNKNOWN_ERROR;
5937 }
5938
5939 const size_t entryCount = other.mEntries.size();
5940 for (size_t i = 0; i < entryCount; i++) {
5941 ssize_t index = mEntries.indexOfKey(other.mEntries.keyAt(i));
5942 if (index < 0) {
5943 mEntries.add(other.mEntries.keyAt(i), other.mEntries[i]);
5944 } else {
5945 if (other.mEntries[i] != mEntries[index]) {
5946 return UNKNOWN_ERROR;
5947 }
5948 }
5949 }
5950
5951 // Merge the lookup table. No entry can conflict
5952 // (value of 0 means not set).
5953 for (size_t i = 0; i < 256; i++) {
5954 if (mLookupTable[i] != other.mLookupTable[i]) {
5955 if (mLookupTable[i] == 0) {
5956 mLookupTable[i] = other.mLookupTable[i];
5957 } else if (other.mLookupTable[i] != 0) {
5958 return UNKNOWN_ERROR;
5959 }
5960 }
5961 }
5962 return NO_ERROR;
5963}
5964
Adam Lesinskide898ff2014-01-29 18:20:45 -08005965status_t DynamicRefTable::addMapping(const String16& packageName, uint8_t packageId)
5966{
5967 ssize_t index = mEntries.indexOfKey(packageName);
5968 if (index < 0) {
5969 return UNKNOWN_ERROR;
5970 }
5971 mLookupTable[mEntries.valueAt(index)] = packageId;
5972 return NO_ERROR;
5973}
5974
5975status_t DynamicRefTable::lookupResourceId(uint32_t* resId) const {
5976 uint32_t res = *resId;
5977 size_t packageId = Res_GETPACKAGE(res) + 1;
5978
5979 if (packageId == APP_PACKAGE_ID) {
5980 // No lookup needs to be done, app package IDs are absolute.
5981 return NO_ERROR;
5982 }
5983
5984 if (packageId == 0) {
5985 // The package ID is 0x00. That means that a shared library is accessing
5986 // its own local resource, so we fix up the resource with the calling
5987 // package ID.
5988 *resId |= ((uint32_t) mAssignedPackageId) << 24;
5989 return NO_ERROR;
5990 }
5991
5992 // Do a proper lookup.
5993 uint8_t translatedId = mLookupTable[packageId];
5994 if (translatedId == 0) {
Adam Lesinskia7d1d732014-10-01 18:24:54 -07005995 ALOGV("DynamicRefTable(0x%02x): No mapping for build-time package ID 0x%02x.",
Adam Lesinskide898ff2014-01-29 18:20:45 -08005996 (uint8_t)mAssignedPackageId, (uint8_t)packageId);
5997 for (size_t i = 0; i < 256; i++) {
5998 if (mLookupTable[i] != 0) {
Adam Lesinskia7d1d732014-10-01 18:24:54 -07005999 ALOGV("e[0x%02x] -> 0x%02x", (uint8_t)i, mLookupTable[i]);
Adam Lesinskide898ff2014-01-29 18:20:45 -08006000 }
6001 }
6002 return UNKNOWN_ERROR;
6003 }
6004
6005 *resId = (res & 0x00ffffff) | (((uint32_t) translatedId) << 24);
6006 return NO_ERROR;
6007}
6008
6009status_t DynamicRefTable::lookupResourceValue(Res_value* value) const {
6010 if (value->dataType != Res_value::TYPE_DYNAMIC_REFERENCE) {
6011 return NO_ERROR;
6012 }
6013
6014 status_t err = lookupResourceId(&value->data);
6015 if (err != NO_ERROR) {
6016 return err;
6017 }
6018
6019 value->dataType = Res_value::TYPE_REFERENCE;
6020 return NO_ERROR;
6021}
6022
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006023struct IdmapTypeMap {
6024 ssize_t overlayTypeId;
6025 size_t entryOffset;
6026 Vector<uint32_t> entryMap;
6027};
6028
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006029status_t ResTable::createIdmap(const ResTable& overlay,
6030 uint32_t targetCrc, uint32_t overlayCrc,
6031 const char* targetPath, const char* overlayPath,
6032 void** outData, size_t* outSize) const
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006033{
6034 // see README for details on the format of map
6035 if (mPackageGroups.size() == 0) {
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006036 ALOGW("idmap: target package has no package groups, cannot create idmap\n");
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006037 return UNKNOWN_ERROR;
6038 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006039
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006040 if (mPackageGroups[0]->packages.size() == 0) {
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006041 ALOGW("idmap: target package has no packages in its first package group, "
6042 "cannot create idmap\n");
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006043 return UNKNOWN_ERROR;
6044 }
6045
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006046 KeyedVector<uint8_t, IdmapTypeMap> map;
6047
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006048 // overlaid packages are assumed to contain only one package group
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006049 const PackageGroup* pg = mPackageGroups[0];
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006050
6051 // starting size is header
6052 *outSize = ResTable::IDMAP_HEADER_SIZE_BYTES;
6053
6054 // target package id and number of types in map
6055 *outSize += 2 * sizeof(uint16_t);
6056
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006057 // overlay packages are assumed to contain only one package group
Adam Lesinski4bf58102014-11-03 11:21:19 -08006058 const ResTable_package* overlayPackageStruct = overlay.mPackageGroups[0]->packages[0]->package;
6059 char16_t tmpName[sizeof(overlayPackageStruct->name)/sizeof(overlayPackageStruct->name[0])];
6060 strcpy16_dtoh(tmpName, overlayPackageStruct->name, sizeof(overlayPackageStruct->name)/sizeof(overlayPackageStruct->name[0]));
6061 const String16 overlayPackage(tmpName);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006062
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006063 for (size_t typeIndex = 0; typeIndex < pg->types.size(); ++typeIndex) {
6064 const TypeList& typeList = pg->types[typeIndex];
6065 if (typeList.isEmpty()) {
6066 continue;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006067 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006068
6069 const Type* typeConfigs = typeList[0];
6070
6071 IdmapTypeMap typeMap;
6072 typeMap.overlayTypeId = -1;
6073 typeMap.entryOffset = 0;
6074
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006075 for (size_t entryIndex = 0; entryIndex < typeConfigs->entryCount; ++entryIndex) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006076 uint32_t resID = Res_MAKEID(pg->id - 1, typeIndex, entryIndex);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006077 resource_name resName;
MÃ¥rten Kongstad65a05fd2014-01-31 14:01:52 +01006078 if (!this->getResourceName(resID, false, &resName)) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006079 if (typeMap.entryMap.isEmpty()) {
6080 typeMap.entryOffset++;
6081 }
MÃ¥rten Kongstadfcaba142011-05-19 16:02:35 +02006082 continue;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006083 }
6084
6085 const String16 overlayType(resName.type, resName.typeLen);
6086 const String16 overlayName(resName.name, resName.nameLen);
6087 uint32_t overlayResID = overlay.identifierForName(overlayName.string(),
6088 overlayName.size(),
6089 overlayType.string(),
6090 overlayType.size(),
6091 overlayPackage.string(),
6092 overlayPackage.size());
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006093 if (overlayResID == 0) {
6094 if (typeMap.entryMap.isEmpty()) {
6095 typeMap.entryOffset++;
Jean-Baptiste Queru3e2d5912012-05-01 10:00:22 -07006096 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006097 continue;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006098 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006099
6100 if (typeMap.overlayTypeId == -1) {
6101 typeMap.overlayTypeId = Res_GETTYPE(overlayResID) + 1;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006102 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006103
6104 if (Res_GETTYPE(overlayResID) + 1 != static_cast<size_t>(typeMap.overlayTypeId)) {
6105 ALOGE("idmap: can't mix type ids in entry map. Resource 0x%08x maps to 0x%08x"
6106 " but entries should map to resources of type %02x",
6107 resID, overlayResID, typeMap.overlayTypeId);
6108 return BAD_TYPE;
6109 }
6110
6111 if (typeMap.entryOffset + typeMap.entryMap.size() < entryIndex) {
6112 // Resize to accomodate this entry and the 0's in between.
6113 if (typeMap.entryMap.resize((entryIndex - typeMap.entryOffset) + 1) < 0) {
6114 return NO_MEMORY;
6115 }
6116 typeMap.entryMap.editTop() = Res_GETENTRY(overlayResID);
6117 } else {
6118 typeMap.entryMap.add(Res_GETENTRY(overlayResID));
6119 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006120 }
6121
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006122 if (!typeMap.entryMap.isEmpty()) {
6123 if (map.add(static_cast<uint8_t>(typeIndex), typeMap) < 0) {
6124 return NO_MEMORY;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006125 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006126 *outSize += (4 * sizeof(uint16_t)) + (typeMap.entryMap.size() * sizeof(uint32_t));
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006127 }
6128 }
6129
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006130 if (map.isEmpty()) {
6131 ALOGW("idmap: no resources in overlay package present in base package");
6132 return UNKNOWN_ERROR;
6133 }
6134
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006135 if ((*outData = malloc(*outSize)) == NULL) {
6136 return NO_MEMORY;
6137 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006138
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006139 uint32_t* data = (uint32_t*)*outData;
6140 *data++ = htodl(IDMAP_MAGIC);
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006141 *data++ = htodl(IDMAP_CURRENT_VERSION);
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006142 *data++ = htodl(targetCrc);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006143 *data++ = htodl(overlayCrc);
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006144 const char* paths[] = { targetPath, overlayPath };
6145 for (int j = 0; j < 2; ++j) {
6146 char* p = (char*)data;
6147 const char* path = paths[j];
6148 const size_t I = strlen(path);
6149 if (I > 255) {
6150 ALOGV("path exceeds expected 255 characters: %s\n", path);
6151 return UNKNOWN_ERROR;
6152 }
6153 for (size_t i = 0; i < 256; ++i) {
6154 *p++ = i < I ? path[i] : '\0';
6155 }
6156 data += 256 / sizeof(uint32_t);
6157 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006158 const size_t mapSize = map.size();
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006159 uint16_t* typeData = reinterpret_cast<uint16_t*>(data);
6160 *typeData++ = htods(pg->id);
6161 *typeData++ = htods(mapSize);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006162 for (size_t i = 0; i < mapSize; ++i) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006163 uint8_t targetTypeId = map.keyAt(i);
6164 const IdmapTypeMap& typeMap = map[i];
6165 *typeData++ = htods(targetTypeId + 1);
6166 *typeData++ = htods(typeMap.overlayTypeId);
6167 *typeData++ = htods(typeMap.entryMap.size());
6168 *typeData++ = htods(typeMap.entryOffset);
6169
6170 const size_t entryCount = typeMap.entryMap.size();
6171 uint32_t* entries = reinterpret_cast<uint32_t*>(typeData);
6172 for (size_t j = 0; j < entryCount; j++) {
6173 entries[j] = htodl(typeMap.entryMap[j]);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006174 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006175 typeData += entryCount * 2;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006176 }
6177
6178 return NO_ERROR;
6179}
6180
6181bool ResTable::getIdmapInfo(const void* idmap, size_t sizeBytes,
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006182 uint32_t* pVersion,
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006183 uint32_t* pTargetCrc, uint32_t* pOverlayCrc,
6184 String8* pTargetPath, String8* pOverlayPath)
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006185{
6186 const uint32_t* map = (const uint32_t*)idmap;
6187 if (!assertIdmapHeader(map, sizeBytes)) {
6188 return false;
6189 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006190 if (pVersion) {
6191 *pVersion = dtohl(map[1]);
6192 }
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006193 if (pTargetCrc) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006194 *pTargetCrc = dtohl(map[2]);
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006195 }
6196 if (pOverlayCrc) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006197 *pOverlayCrc = dtohl(map[3]);
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006198 }
6199 if (pTargetPath) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006200 pTargetPath->setTo(reinterpret_cast<const char*>(map + 4));
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006201 }
6202 if (pOverlayPath) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006203 pOverlayPath->setTo(reinterpret_cast<const char*>(map + 4 + 256 / sizeof(uint32_t)));
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006204 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006205 return true;
6206}
6207
6208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006209#define CHAR16_TO_CSTR(c16, len) (String8(String16(c16,len)).string())
6210
6211#define CHAR16_ARRAY_EQ(constant, var, len) \
6212 ((len == (sizeof(constant)/sizeof(constant[0]))) && (0 == memcmp((var), (constant), (len))))
6213
Jeff Brown9d3b1a42013-07-01 19:07:15 -07006214static void print_complex(uint32_t complex, bool isFraction)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006215{
Dianne Hackborne17086b2009-06-19 15:13:28 -07006216 const float MANTISSA_MULT =
6217 1.0f / (1<<Res_value::COMPLEX_MANTISSA_SHIFT);
6218 const float RADIX_MULTS[] = {
6219 1.0f*MANTISSA_MULT, 1.0f/(1<<7)*MANTISSA_MULT,
6220 1.0f/(1<<15)*MANTISSA_MULT, 1.0f/(1<<23)*MANTISSA_MULT
6221 };
6222
6223 float value = (complex&(Res_value::COMPLEX_MANTISSA_MASK
6224 <<Res_value::COMPLEX_MANTISSA_SHIFT))
6225 * RADIX_MULTS[(complex>>Res_value::COMPLEX_RADIX_SHIFT)
6226 & Res_value::COMPLEX_RADIX_MASK];
6227 printf("%f", value);
Mark Salyzyn00adb862014-03-19 11:00:06 -07006228
Dianne Hackbornde7faf62009-06-30 13:27:30 -07006229 if (!isFraction) {
Dianne Hackborne17086b2009-06-19 15:13:28 -07006230 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
6231 case Res_value::COMPLEX_UNIT_PX: printf("px"); break;
6232 case Res_value::COMPLEX_UNIT_DIP: printf("dp"); break;
6233 case Res_value::COMPLEX_UNIT_SP: printf("sp"); break;
6234 case Res_value::COMPLEX_UNIT_PT: printf("pt"); break;
6235 case Res_value::COMPLEX_UNIT_IN: printf("in"); break;
6236 case Res_value::COMPLEX_UNIT_MM: printf("mm"); break;
6237 default: printf(" (unknown unit)"); break;
6238 }
6239 } else {
6240 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
6241 case Res_value::COMPLEX_UNIT_FRACTION: printf("%%"); break;
6242 case Res_value::COMPLEX_UNIT_FRACTION_PARENT: printf("%%p"); break;
6243 default: printf(" (unknown unit)"); break;
6244 }
6245 }
6246}
6247
Shachar Shemesh9872bf42010-12-20 17:38:33 +02006248// Normalize a string for output
6249String8 ResTable::normalizeForOutput( const char *input )
6250{
6251 String8 ret;
6252 char buff[2];
6253 buff[1] = '\0';
6254
6255 while (*input != '\0') {
6256 switch (*input) {
6257 // All interesting characters are in the ASCII zone, so we are making our own lives
6258 // easier by scanning the string one byte at a time.
6259 case '\\':
6260 ret += "\\\\";
6261 break;
6262 case '\n':
6263 ret += "\\n";
6264 break;
6265 case '"':
6266 ret += "\\\"";
6267 break;
6268 default:
6269 buff[0] = *input;
6270 ret += buff;
6271 break;
6272 }
6273
6274 input++;
6275 }
6276
6277 return ret;
6278}
6279
Dianne Hackbornde7faf62009-06-30 13:27:30 -07006280void ResTable::print_value(const Package* pkg, const Res_value& value) const
6281{
6282 if (value.dataType == Res_value::TYPE_NULL) {
Alan Viverettef2969402014-10-29 17:09:36 -07006283 if (value.data == Res_value::DATA_NULL_UNDEFINED) {
6284 printf("(null)\n");
6285 } else if (value.data == Res_value::DATA_NULL_EMPTY) {
6286 printf("(null empty)\n");
6287 } else {
6288 // This should never happen.
6289 printf("(null) 0x%08x\n", value.data);
6290 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07006291 } else if (value.dataType == Res_value::TYPE_REFERENCE) {
6292 printf("(reference) 0x%08x\n", value.data);
Adam Lesinskide898ff2014-01-29 18:20:45 -08006293 } else if (value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE) {
6294 printf("(dynamic reference) 0x%08x\n", value.data);
Dianne Hackbornde7faf62009-06-30 13:27:30 -07006295 } else if (value.dataType == Res_value::TYPE_ATTRIBUTE) {
6296 printf("(attribute) 0x%08x\n", value.data);
6297 } else if (value.dataType == Res_value::TYPE_STRING) {
6298 size_t len;
Kenny Root780d2a12010-02-22 22:36:26 -08006299 const char* str8 = pkg->header->values.string8At(
Dianne Hackbornde7faf62009-06-30 13:27:30 -07006300 value.data, &len);
Kenny Root780d2a12010-02-22 22:36:26 -08006301 if (str8 != NULL) {
Shachar Shemesh9872bf42010-12-20 17:38:33 +02006302 printf("(string8) \"%s\"\n", normalizeForOutput(str8).string());
Dianne Hackbornde7faf62009-06-30 13:27:30 -07006303 } else {
Kenny Root780d2a12010-02-22 22:36:26 -08006304 const char16_t* str16 = pkg->header->values.stringAt(
6305 value.data, &len);
6306 if (str16 != NULL) {
6307 printf("(string16) \"%s\"\n",
Shachar Shemesh9872bf42010-12-20 17:38:33 +02006308 normalizeForOutput(String8(str16, len).string()).string());
Kenny Root780d2a12010-02-22 22:36:26 -08006309 } else {
6310 printf("(string) null\n");
6311 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006312 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07006313 } else if (value.dataType == Res_value::TYPE_FLOAT) {
6314 printf("(float) %g\n", *(const float*)&value.data);
6315 } else if (value.dataType == Res_value::TYPE_DIMENSION) {
6316 printf("(dimension) ");
6317 print_complex(value.data, false);
6318 printf("\n");
6319 } else if (value.dataType == Res_value::TYPE_FRACTION) {
6320 printf("(fraction) ");
6321 print_complex(value.data, true);
6322 printf("\n");
6323 } else if (value.dataType >= Res_value::TYPE_FIRST_COLOR_INT
6324 || value.dataType <= Res_value::TYPE_LAST_COLOR_INT) {
6325 printf("(color) #%08x\n", value.data);
6326 } else if (value.dataType == Res_value::TYPE_INT_BOOLEAN) {
6327 printf("(boolean) %s\n", value.data ? "true" : "false");
6328 } else if (value.dataType >= Res_value::TYPE_FIRST_INT
6329 || value.dataType <= Res_value::TYPE_LAST_INT) {
6330 printf("(int) 0x%08x or %d\n", value.data, value.data);
6331 } else {
6332 printf("(unknown type) t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)\n",
6333 (int)value.dataType, (int)value.data,
6334 (int)value.size, (int)value.res0);
6335 }
6336}
6337
Dianne Hackborne17086b2009-06-19 15:13:28 -07006338void ResTable::print(bool inclValues) const
6339{
6340 if (mError != 0) {
6341 printf("mError=0x%x (%s)\n", mError, strerror(mError));
6342 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006343 size_t pgCount = mPackageGroups.size();
6344 printf("Package Groups (%d)\n", (int)pgCount);
6345 for (size_t pgIndex=0; pgIndex<pgCount; pgIndex++) {
6346 const PackageGroup* pg = mPackageGroups[pgIndex];
Adam Lesinski6022deb2014-08-20 14:59:19 -07006347 printf("Package Group %d id=0x%02x packageCount=%d name=%s\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006348 (int)pgIndex, pg->id, (int)pg->packages.size(),
6349 String8(pg->name).string());
Mark Salyzyn00adb862014-03-19 11:00:06 -07006350
Adam Lesinski6022deb2014-08-20 14:59:19 -07006351 const KeyedVector<String16, uint8_t>& refEntries = pg->dynamicRefTable.entries();
6352 const size_t refEntryCount = refEntries.size();
6353 if (refEntryCount > 0) {
6354 printf(" DynamicRefTable entryCount=%d:\n", (int) refEntryCount);
6355 for (size_t refIndex = 0; refIndex < refEntryCount; refIndex++) {
6356 printf(" 0x%02x -> %s\n",
6357 refEntries.valueAt(refIndex),
6358 String8(refEntries.keyAt(refIndex)).string());
6359 }
6360 printf("\n");
6361 }
6362
6363 int packageId = pg->id;
Adam Lesinski18560882014-08-15 17:18:21 +00006364 size_t pkgCount = pg->packages.size();
6365 for (size_t pkgIndex=0; pkgIndex<pkgCount; pkgIndex++) {
6366 const Package* pkg = pg->packages[pkgIndex];
Adam Lesinski6022deb2014-08-20 14:59:19 -07006367 // Use a package's real ID, since the ID may have been assigned
6368 // if this package is a shared library.
6369 packageId = pkg->package->id;
Adam Lesinski4bf58102014-11-03 11:21:19 -08006370 char16_t tmpName[sizeof(pkg->package->name)/sizeof(pkg->package->name[0])];
6371 strcpy16_dtoh(tmpName, pkg->package->name, sizeof(pkg->package->name)/sizeof(pkg->package->name[0]));
Adam Lesinski6022deb2014-08-20 14:59:19 -07006372 printf(" Package %d id=0x%02x name=%s\n", (int)pkgIndex,
Adam Lesinski4bf58102014-11-03 11:21:19 -08006373 pkg->package->id, String8(tmpName).string());
Adam Lesinski18560882014-08-15 17:18:21 +00006374 }
6375
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006376 for (size_t typeIndex=0; typeIndex < pg->types.size(); typeIndex++) {
6377 const TypeList& typeList = pg->types[typeIndex];
6378 if (typeList.isEmpty()) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006379 continue;
6380 }
6381 const Type* typeConfigs = typeList[0];
6382 const size_t NTC = typeConfigs->configs.size();
6383 printf(" type %d configCount=%d entryCount=%d\n",
6384 (int)typeIndex, (int)NTC, (int)typeConfigs->entryCount);
6385 if (typeConfigs->typeSpecFlags != NULL) {
6386 for (size_t entryIndex=0; entryIndex<typeConfigs->entryCount; entryIndex++) {
Adam Lesinski6022deb2014-08-20 14:59:19 -07006387 uint32_t resID = (0xff000000 & ((packageId)<<24))
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006388 | (0x00ff0000 & ((typeIndex+1)<<16))
6389 | (0x0000ffff & (entryIndex));
6390 // Since we are creating resID without actually
6391 // iterating over them, we have no idea which is a
6392 // dynamic reference. We must check.
Adam Lesinski6022deb2014-08-20 14:59:19 -07006393 if (packageId == 0) {
6394 pg->dynamicRefTable.lookupResourceId(&resID);
6395 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006396
6397 resource_name resName;
6398 if (this->getResourceName(resID, true, &resName)) {
6399 String8 type8;
6400 String8 name8;
6401 if (resName.type8 != NULL) {
6402 type8 = String8(resName.type8, resName.typeLen);
6403 } else {
6404 type8 = String8(resName.type, resName.typeLen);
6405 }
6406 if (resName.name8 != NULL) {
6407 name8 = String8(resName.name8, resName.nameLen);
6408 } else {
6409 name8 = String8(resName.name, resName.nameLen);
6410 }
6411 printf(" spec resource 0x%08x %s:%s/%s: flags=0x%08x\n",
6412 resID,
6413 CHAR16_TO_CSTR(resName.package, resName.packageLen),
6414 type8.string(), name8.string(),
6415 dtohl(typeConfigs->typeSpecFlags[entryIndex]));
6416 } else {
6417 printf(" INVALID TYPE CONFIG FOR RESOURCE 0x%08x\n", resID);
6418 }
6419 }
6420 }
6421 for (size_t configIndex=0; configIndex<NTC; configIndex++) {
6422 const ResTable_type* type = typeConfigs->configs[configIndex];
6423 if ((((uint64_t)type)&0x3) != 0) {
6424 printf(" NON-INTEGER ResTable_type ADDRESS: %p\n", type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006425 continue;
6426 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006427 String8 configStr = type->config.toString();
6428 printf(" config %s:\n", configStr.size() > 0
6429 ? configStr.string() : "(default)");
6430 size_t entryCount = dtohl(type->entryCount);
6431 uint32_t entriesStart = dtohl(type->entriesStart);
6432 if ((entriesStart&0x3) != 0) {
6433 printf(" NON-INTEGER ResTable_type entriesStart OFFSET: 0x%x\n", entriesStart);
6434 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006435 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006436 uint32_t typeSize = dtohl(type->header.size);
6437 if ((typeSize&0x3) != 0) {
6438 printf(" NON-INTEGER ResTable_type header.size: 0x%x\n", typeSize);
6439 continue;
6440 }
6441 for (size_t entryIndex=0; entryIndex<entryCount; entryIndex++) {
6442
6443 const uint8_t* const end = ((const uint8_t*)type)
6444 + dtohl(type->header.size);
6445 const uint32_t* const eindex = (const uint32_t*)
6446 (((const uint8_t*)type) + dtohs(type->header.headerSize));
6447
6448 uint32_t thisOffset = dtohl(eindex[entryIndex]);
6449 if (thisOffset == ResTable_type::NO_ENTRY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006450 continue;
6451 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006452
Adam Lesinski6022deb2014-08-20 14:59:19 -07006453 uint32_t resID = (0xff000000 & ((packageId)<<24))
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006454 | (0x00ff0000 & ((typeIndex+1)<<16))
6455 | (0x0000ffff & (entryIndex));
Adam Lesinski6022deb2014-08-20 14:59:19 -07006456 if (packageId == 0) {
6457 pg->dynamicRefTable.lookupResourceId(&resID);
6458 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006459 resource_name resName;
6460 if (this->getResourceName(resID, true, &resName)) {
6461 String8 type8;
6462 String8 name8;
6463 if (resName.type8 != NULL) {
6464 type8 = String8(resName.type8, resName.typeLen);
Kenny Root33791952010-06-08 10:16:48 -07006465 } else {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006466 type8 = String8(resName.type, resName.typeLen);
Kenny Root33791952010-06-08 10:16:48 -07006467 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006468 if (resName.name8 != NULL) {
6469 name8 = String8(resName.name8, resName.nameLen);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006470 } else {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006471 name8 = String8(resName.name, resName.nameLen);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006472 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006473 printf(" resource 0x%08x %s:%s/%s: ", resID,
6474 CHAR16_TO_CSTR(resName.package, resName.packageLen),
6475 type8.string(), name8.string());
6476 } else {
6477 printf(" INVALID RESOURCE 0x%08x: ", resID);
6478 }
6479 if ((thisOffset&0x3) != 0) {
6480 printf("NON-INTEGER OFFSET: 0x%x\n", thisOffset);
6481 continue;
6482 }
6483 if ((thisOffset+sizeof(ResTable_entry)) > typeSize) {
6484 printf("OFFSET OUT OF BOUNDS: 0x%x+0x%x (size is 0x%x)\n",
6485 entriesStart, thisOffset, typeSize);
6486 continue;
6487 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006488
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006489 const ResTable_entry* ent = (const ResTable_entry*)
6490 (((const uint8_t*)type) + entriesStart + thisOffset);
6491 if (((entriesStart + thisOffset)&0x3) != 0) {
6492 printf("NON-INTEGER ResTable_entry OFFSET: 0x%x\n",
6493 (entriesStart + thisOffset));
6494 continue;
6495 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006496
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006497 uintptr_t esize = dtohs(ent->size);
6498 if ((esize&0x3) != 0) {
6499 printf("NON-INTEGER ResTable_entry SIZE: %p\n", (void *)esize);
6500 continue;
6501 }
6502 if ((thisOffset+esize) > typeSize) {
6503 printf("ResTable_entry OUT OF BOUNDS: 0x%x+0x%x+%p (size is 0x%x)\n",
6504 entriesStart, thisOffset, (void *)esize, typeSize);
6505 continue;
6506 }
6507
6508 const Res_value* valuePtr = NULL;
6509 const ResTable_map_entry* bagPtr = NULL;
6510 Res_value value;
6511 if ((dtohs(ent->flags)&ResTable_entry::FLAG_COMPLEX) != 0) {
6512 printf("<bag>");
6513 bagPtr = (const ResTable_map_entry*)ent;
6514 } else {
6515 valuePtr = (const Res_value*)
6516 (((const uint8_t*)ent) + esize);
6517 value.copyFrom_dtoh(*valuePtr);
6518 printf("t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)",
6519 (int)value.dataType, (int)value.data,
6520 (int)value.size, (int)value.res0);
6521 }
6522
6523 if ((dtohs(ent->flags)&ResTable_entry::FLAG_PUBLIC) != 0) {
6524 printf(" (PUBLIC)");
6525 }
6526 printf("\n");
6527
6528 if (inclValues) {
6529 if (valuePtr != NULL) {
6530 printf(" ");
6531 print_value(typeConfigs->package, value);
6532 } else if (bagPtr != NULL) {
6533 const int N = dtohl(bagPtr->count);
6534 const uint8_t* baseMapPtr = (const uint8_t*)ent;
6535 size_t mapOffset = esize;
6536 const ResTable_map* mapPtr = (ResTable_map*)(baseMapPtr+mapOffset);
6537 const uint32_t parent = dtohl(bagPtr->parent.ident);
6538 uint32_t resolvedParent = parent;
Adam Lesinski6022deb2014-08-20 14:59:19 -07006539 if (Res_GETPACKAGE(resolvedParent) + 1 == 0) {
6540 status_t err = pg->dynamicRefTable.lookupResourceId(&resolvedParent);
6541 if (err != NO_ERROR) {
6542 resolvedParent = 0;
6543 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006544 }
6545 printf(" Parent=0x%08x(Resolved=0x%08x), Count=%d\n",
6546 parent, resolvedParent, N);
6547 for (int i=0; i<N && mapOffset < (typeSize-sizeof(ResTable_map)); i++) {
6548 printf(" #%i (Key=0x%08x): ",
6549 i, dtohl(mapPtr->name.ident));
6550 value.copyFrom_dtoh(mapPtr->value);
6551 print_value(typeConfigs->package, value);
6552 const size_t size = dtohs(mapPtr->value.size);
6553 mapOffset += size + sizeof(*mapPtr)-sizeof(mapPtr->value);
6554 mapPtr = (ResTable_map*)(baseMapPtr+mapOffset);
Dianne Hackborne17086b2009-06-19 15:13:28 -07006555 }
6556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006557 }
6558 }
6559 }
6560 }
6561 }
6562}
6563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006564} // namespace android