blob: 1d9fe35bac35affd01bbd5c77654a4b31f9851dc [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
Dan Albert1b4f3162015-04-07 18:43:15 -070020#include <ctype.h>
21#include <memory.h>
22#include <stddef.h>
23#include <stdint.h>
24#include <stdlib.h>
25#include <string.h>
26
27#include <limits>
28#include <type_traits>
29
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -070030#include <androidfw/ByteBucketArray.h>
Mathias Agopianb13b9bd2012-02-17 18:27:36 -080031#include <androidfw/ResourceTypes.h>
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -070032#include <androidfw/TypeWrappers.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033#include <utils/Atomic.h>
34#include <utils/ByteOrder.h>
35#include <utils/Debug.h>
Mathias Agopianb13b9bd2012-02-17 18:27:36 -080036#include <utils/Log.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037#include <utils/String16.h>
38#include <utils/String8.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039
Dan Albert1b4f3162015-04-07 18:43:15 -070040#ifdef __ANDROID__
Andreas Gampe2204f0b2014-10-21 23:04:54 -070041#include <binder/TextOutput.h>
42#endif
43
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044#ifndef INT32_MAX
45#define INT32_MAX ((int32_t)(2147483647))
46#endif
47
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048namespace android {
49
Elliott Hughes59cbe8d2015-07-29 17:49:27 -070050#if defined(_WIN32)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051#undef nhtol
52#undef htonl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053#define ntohl(x) ( ((x) << 24) | (((x) >> 24) & 255) | (((x) << 8) & 0xff0000) | (((x) >> 8) & 0xff00) )
54#define htonl(x) ntohl(x)
55#define ntohs(x) ( (((x) << 8) & 0xff00) | (((x) >> 8) & 255) )
56#define htons(x) ntohs(x)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057#endif
58
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -070059#define IDMAP_MAGIC 0x504D4449
60#define IDMAP_CURRENT_VERSION 0x00000001
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +010061
Adam Lesinskide898ff2014-01-29 18:20:45 -080062#define APP_PACKAGE_ID 0x7f
63#define SYS_PACKAGE_ID 0x01
64
Andreas Gampe2204f0b2014-10-21 23:04:54 -070065static const bool kDebugStringPoolNoisy = false;
66static const bool kDebugXMLNoisy = false;
67static const bool kDebugTableNoisy = false;
68static const bool kDebugTableGetEntry = false;
69static const bool kDebugTableSuperNoisy = false;
70static const bool kDebugLoadTableNoisy = false;
71static const bool kDebugLoadTableSuperNoisy = false;
72static const bool kDebugTableTheme = false;
73static const bool kDebugResXMLTree = false;
74static const bool kDebugLibNoisy = false;
75
76// TODO: This code uses 0xFFFFFFFF converted to bag_set* as a sentinel value. This is bad practice.
77
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078// Standard C isspace() is only required to look at the low byte of its input, so
79// produces incorrect results for UTF-16 characters. For safety's sake, assume that
80// any high-byte UTF-16 code point is not whitespace.
81inline int isspace16(char16_t c) {
82 return (c < 0x0080 && isspace(c));
83}
84
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -070085template<typename T>
86inline static T max(T a, T b) {
87 return a > b ? a : b;
88}
89
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090// range checked; guaranteed to NUL-terminate within the stated number of available slots
91// NOTE: if this truncates the dst string due to running out of space, no attempt is
92// made to avoid splitting surrogate pairs.
Adam Lesinski4bf58102014-11-03 11:21:19 -080093static void strcpy16_dtoh(char16_t* dst, const uint16_t* src, size_t avail)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094{
Dan Albertf348c152014-09-08 18:28:00 -070095 char16_t* last = dst + avail - 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096 while (*src && (dst < last)) {
Adam Lesinski4bf58102014-11-03 11:21:19 -080097 char16_t s = dtohs(static_cast<char16_t>(*src));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098 *dst++ = s;
99 src++;
100 }
101 *dst = 0;
102}
103
104static status_t validate_chunk(const ResChunk_header* chunk,
105 size_t minSize,
106 const uint8_t* dataEnd,
107 const char* name)
108{
109 const uint16_t headerSize = dtohs(chunk->headerSize);
110 const uint32_t size = dtohl(chunk->size);
111
112 if (headerSize >= minSize) {
113 if (headerSize <= size) {
114 if (((headerSize|size)&0x3) == 0) {
Adam Lesinski7322ea72014-05-14 11:43:26 -0700115 if ((size_t)size <= (size_t)(dataEnd-((const uint8_t*)chunk))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 return NO_ERROR;
117 }
Patrik Bannura443dd932014-02-12 13:38:54 +0100118 ALOGW("%s data size 0x%x extends beyond resource end %p.",
119 name, size, (void*)(dataEnd-((const uint8_t*)chunk)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120 return BAD_TYPE;
121 }
Steve Block8564c8d2012-01-05 23:22:43 +0000122 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 -0800123 name, (int)size, (int)headerSize);
124 return BAD_TYPE;
125 }
Patrik Bannura443dd932014-02-12 13:38:54 +0100126 ALOGW("%s size 0x%x is smaller than header size 0x%x.",
127 name, size, headerSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 return BAD_TYPE;
129 }
Adam Lesinskide898ff2014-01-29 18:20:45 -0800130 ALOGW("%s header size 0x%04x is too small.",
Patrik Bannura443dd932014-02-12 13:38:54 +0100131 name, headerSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 return BAD_TYPE;
133}
134
Narayan Kamath6381dd42014-03-03 17:12:03 +0000135static void fill9patchOffsets(Res_png_9patch* patch) {
136 patch->xDivsOffset = sizeof(Res_png_9patch);
137 patch->yDivsOffset = patch->xDivsOffset + (patch->numXDivs * sizeof(int32_t));
138 patch->colorsOffset = patch->yDivsOffset + (patch->numYDivs * sizeof(int32_t));
139}
140
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141inline void Res_value::copyFrom_dtoh(const Res_value& src)
142{
143 size = dtohs(src.size);
144 res0 = src.res0;
145 dataType = src.dataType;
146 data = dtohl(src.data);
147}
148
149void Res_png_9patch::deviceToFile()
150{
Narayan Kamath6381dd42014-03-03 17:12:03 +0000151 int32_t* xDivs = getXDivs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152 for (int i = 0; i < numXDivs; i++) {
153 xDivs[i] = htonl(xDivs[i]);
154 }
Narayan Kamath6381dd42014-03-03 17:12:03 +0000155 int32_t* yDivs = getYDivs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156 for (int i = 0; i < numYDivs; i++) {
157 yDivs[i] = htonl(yDivs[i]);
158 }
159 paddingLeft = htonl(paddingLeft);
160 paddingRight = htonl(paddingRight);
161 paddingTop = htonl(paddingTop);
162 paddingBottom = htonl(paddingBottom);
Narayan Kamath6381dd42014-03-03 17:12:03 +0000163 uint32_t* colors = getColors();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 for (int i=0; i<numColors; i++) {
165 colors[i] = htonl(colors[i]);
166 }
167}
168
169void Res_png_9patch::fileToDevice()
170{
Narayan Kamath6381dd42014-03-03 17:12:03 +0000171 int32_t* xDivs = getXDivs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 for (int i = 0; i < numXDivs; i++) {
173 xDivs[i] = ntohl(xDivs[i]);
174 }
Narayan Kamath6381dd42014-03-03 17:12:03 +0000175 int32_t* yDivs = getYDivs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 for (int i = 0; i < numYDivs; i++) {
177 yDivs[i] = ntohl(yDivs[i]);
178 }
179 paddingLeft = ntohl(paddingLeft);
180 paddingRight = ntohl(paddingRight);
181 paddingTop = ntohl(paddingTop);
182 paddingBottom = ntohl(paddingBottom);
Narayan Kamath6381dd42014-03-03 17:12:03 +0000183 uint32_t* colors = getColors();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 for (int i=0; i<numColors; i++) {
185 colors[i] = ntohl(colors[i]);
186 }
187}
188
Narayan Kamath6381dd42014-03-03 17:12:03 +0000189size_t Res_png_9patch::serializedSize() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190{
191 // The size of this struct is 32 bytes on the 32-bit target system
192 // 4 * int8_t
193 // 4 * int32_t
Narayan Kamath6381dd42014-03-03 17:12:03 +0000194 // 3 * uint32_t
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 return 32
196 + numXDivs * sizeof(int32_t)
197 + numYDivs * sizeof(int32_t)
198 + numColors * sizeof(uint32_t);
199}
200
Narayan Kamath6381dd42014-03-03 17:12:03 +0000201void* Res_png_9patch::serialize(const Res_png_9patch& patch, const int32_t* xDivs,
202 const int32_t* yDivs, const uint32_t* colors)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203{
The Android Open Source Project4df24232009-03-05 14:34:35 -0800204 // Use calloc since we're going to leave a few holes in the data
205 // and want this to run cleanly under valgrind
Narayan Kamath6381dd42014-03-03 17:12:03 +0000206 void* newData = calloc(1, patch.serializedSize());
207 serialize(patch, xDivs, yDivs, colors, newData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 return newData;
209}
210
Narayan Kamath6381dd42014-03-03 17:12:03 +0000211void Res_png_9patch::serialize(const Res_png_9patch& patch, const int32_t* xDivs,
212 const int32_t* yDivs, const uint32_t* colors, void* outData)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213{
Narayan Kamath6381dd42014-03-03 17:12:03 +0000214 uint8_t* data = (uint8_t*) outData;
215 memcpy(data, &patch.wasDeserialized, 4); // copy wasDeserialized, numXDivs, numYDivs, numColors
216 memcpy(data + 12, &patch.paddingLeft, 16); // copy paddingXXXX
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 data += 32;
218
Narayan Kamath6381dd42014-03-03 17:12:03 +0000219 memcpy(data, xDivs, patch.numXDivs * sizeof(int32_t));
220 data += patch.numXDivs * sizeof(int32_t);
221 memcpy(data, yDivs, patch.numYDivs * sizeof(int32_t));
222 data += patch.numYDivs * sizeof(int32_t);
223 memcpy(data, colors, patch.numColors * sizeof(uint32_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224
Narayan Kamath6381dd42014-03-03 17:12:03 +0000225 fill9patchOffsets(reinterpret_cast<Res_png_9patch*>(outData));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226}
227
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700228static bool assertIdmapHeader(const void* idmap, size_t size) {
229 if (reinterpret_cast<uintptr_t>(idmap) & 0x03) {
230 ALOGE("idmap: header is not word aligned");
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +0100231 return false;
232 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700233
234 if (size < ResTable::IDMAP_HEADER_SIZE_BYTES) {
235 ALOGW("idmap: header too small (%d bytes)", (uint32_t) size);
236 return false;
237 }
238
239 const uint32_t magic = htodl(*reinterpret_cast<const uint32_t*>(idmap));
240 if (magic != IDMAP_MAGIC) {
241 ALOGW("idmap: no magic found in header (is 0x%08x, expected 0x%08x)",
242 magic, IDMAP_MAGIC);
243 return false;
244 }
245
246 const uint32_t version = htodl(*(reinterpret_cast<const uint32_t*>(idmap) + 1));
247 if (version != IDMAP_CURRENT_VERSION) {
248 // We are strict about versions because files with this format are
249 // auto-generated and don't need backwards compatibility.
250 ALOGW("idmap: version mismatch in header (is 0x%08x, expected 0x%08x)",
251 version, IDMAP_CURRENT_VERSION);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +0100252 return false;
253 }
254 return true;
255}
256
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700257class IdmapEntries {
258public:
259 IdmapEntries() : mData(NULL) {}
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +0100260
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700261 bool hasEntries() const {
262 if (mData == NULL) {
263 return false;
264 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +0100265
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700266 return (dtohs(*mData) > 0);
267 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +0100268
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700269 size_t byteSize() const {
270 if (mData == NULL) {
271 return 0;
272 }
273 uint16_t entryCount = dtohs(mData[2]);
274 return (sizeof(uint16_t) * 4) + (sizeof(uint32_t) * static_cast<size_t>(entryCount));
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +0100275 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700276
277 uint8_t targetTypeId() const {
278 if (mData == NULL) {
279 return 0;
280 }
281 return dtohs(mData[0]);
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +0100282 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700283
284 uint8_t overlayTypeId() const {
285 if (mData == NULL) {
286 return 0;
287 }
288 return dtohs(mData[1]);
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +0100289 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700290
291 status_t setTo(const void* entryHeader, size_t size) {
292 if (reinterpret_cast<uintptr_t>(entryHeader) & 0x03) {
293 ALOGE("idmap: entry header is not word aligned");
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +0100294 return UNKNOWN_ERROR;
295 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700296
297 if (size < sizeof(uint16_t) * 4) {
298 ALOGE("idmap: entry header is too small (%u bytes)", (uint32_t) size);
299 return UNKNOWN_ERROR;
300 }
301
302 const uint16_t* header = reinterpret_cast<const uint16_t*>(entryHeader);
303 const uint16_t targetTypeId = dtohs(header[0]);
304 const uint16_t overlayTypeId = dtohs(header[1]);
305 if (targetTypeId == 0 || overlayTypeId == 0 || targetTypeId > 255 || overlayTypeId > 255) {
306 ALOGE("idmap: invalid type map (%u -> %u)", targetTypeId, overlayTypeId);
307 return UNKNOWN_ERROR;
308 }
309
310 uint16_t entryCount = dtohs(header[2]);
311 if (size < sizeof(uint32_t) * (entryCount + 2)) {
312 ALOGE("idmap: too small (%u bytes) for the number of entries (%u)",
313 (uint32_t) size, (uint32_t) entryCount);
314 return UNKNOWN_ERROR;
315 }
316 mData = header;
317 return NO_ERROR;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +0100318 }
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +0100319
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700320 status_t lookup(uint16_t entryId, uint16_t* outEntryId) const {
321 uint16_t entryCount = dtohs(mData[2]);
322 uint16_t offset = dtohs(mData[3]);
323
324 if (entryId < offset) {
325 // The entry is not present in this idmap
326 return BAD_INDEX;
327 }
328
329 entryId -= offset;
330
331 if (entryId >= entryCount) {
332 // The entry is not present in this idmap
333 return BAD_INDEX;
334 }
335
336 // It is safe to access the type here without checking the size because
337 // we have checked this when it was first loaded.
338 const uint32_t* entries = reinterpret_cast<const uint32_t*>(mData) + 2;
339 uint32_t mappedEntry = dtohl(entries[entryId]);
340 if (mappedEntry == 0xffffffff) {
341 // This entry is not present in this idmap
342 return BAD_INDEX;
343 }
344 *outEntryId = static_cast<uint16_t>(mappedEntry);
345 return NO_ERROR;
346 }
347
348private:
349 const uint16_t* mData;
350};
351
352status_t parseIdmap(const void* idmap, size_t size, uint8_t* outPackageId, KeyedVector<uint8_t, IdmapEntries>* outMap) {
353 if (!assertIdmapHeader(idmap, size)) {
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +0100354 return UNKNOWN_ERROR;
355 }
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +0100356
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700357 size -= ResTable::IDMAP_HEADER_SIZE_BYTES;
358 if (size < sizeof(uint16_t) * 2) {
359 ALOGE("idmap: too small to contain any mapping");
360 return UNKNOWN_ERROR;
361 }
362
363 const uint16_t* data = reinterpret_cast<const uint16_t*>(
364 reinterpret_cast<const uint8_t*>(idmap) + ResTable::IDMAP_HEADER_SIZE_BYTES);
365
366 uint16_t targetPackageId = dtohs(*(data++));
367 if (targetPackageId == 0 || targetPackageId > 255) {
368 ALOGE("idmap: target package ID is invalid (%02x)", targetPackageId);
369 return UNKNOWN_ERROR;
370 }
371
372 uint16_t mapCount = dtohs(*(data++));
373 if (mapCount == 0) {
374 ALOGE("idmap: no mappings");
375 return UNKNOWN_ERROR;
376 }
377
378 if (mapCount > 255) {
379 ALOGW("idmap: too many mappings. Only 255 are possible but %u are present", (uint32_t) mapCount);
380 }
381
382 while (size > sizeof(uint16_t) * 4) {
383 IdmapEntries entries;
384 status_t err = entries.setTo(data, size);
385 if (err != NO_ERROR) {
386 return err;
387 }
388
389 ssize_t index = outMap->add(entries.overlayTypeId(), entries);
390 if (index < 0) {
391 return NO_MEMORY;
392 }
393
394 data += entries.byteSize() / sizeof(uint16_t);
395 size -= entries.byteSize();
396 }
397
398 if (outPackageId != NULL) {
399 *outPackageId = static_cast<uint8_t>(targetPackageId);
400 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +0100401 return NO_ERROR;
402}
403
Narayan Kamath6381dd42014-03-03 17:12:03 +0000404Res_png_9patch* Res_png_9patch::deserialize(void* inData)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405{
Narayan Kamath6381dd42014-03-03 17:12:03 +0000406
407 Res_png_9patch* patch = reinterpret_cast<Res_png_9patch*>(inData);
408 patch->wasDeserialized = true;
409 fill9patchOffsets(patch);
410
411 return patch;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412}
413
414// --------------------------------------------------------------------
415// --------------------------------------------------------------------
416// --------------------------------------------------------------------
417
418ResStringPool::ResStringPool()
Kenny Root19138462009-12-04 09:38:48 -0800419 : mError(NO_INIT), mOwnedData(NULL), mHeader(NULL), mCache(NULL)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800420{
421}
422
423ResStringPool::ResStringPool(const void* data, size_t size, bool copyData)
Kenny Root19138462009-12-04 09:38:48 -0800424 : mError(NO_INIT), mOwnedData(NULL), mHeader(NULL), mCache(NULL)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425{
426 setTo(data, size, copyData);
427}
428
429ResStringPool::~ResStringPool()
430{
431 uninit();
432}
433
Adam Lesinskide898ff2014-01-29 18:20:45 -0800434void ResStringPool::setToEmpty()
435{
436 uninit();
437
438 mOwnedData = calloc(1, sizeof(ResStringPool_header));
439 ResStringPool_header* header = (ResStringPool_header*) mOwnedData;
440 mSize = 0;
441 mEntries = NULL;
442 mStrings = NULL;
443 mStringPoolSize = 0;
444 mEntryStyles = NULL;
445 mStyles = NULL;
446 mStylePoolSize = 0;
447 mHeader = (const ResStringPool_header*) header;
448}
449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800450status_t ResStringPool::setTo(const void* data, size_t size, bool copyData)
451{
452 if (!data || !size) {
453 return (mError=BAD_TYPE);
454 }
455
456 uninit();
457
458 const bool notDeviceEndian = htods(0xf0) != 0xf0;
459
460 if (copyData || notDeviceEndian) {
461 mOwnedData = malloc(size);
462 if (mOwnedData == NULL) {
463 return (mError=NO_MEMORY);
464 }
465 memcpy(mOwnedData, data, size);
466 data = mOwnedData;
467 }
468
469 mHeader = (const ResStringPool_header*)data;
470
471 if (notDeviceEndian) {
472 ResStringPool_header* h = const_cast<ResStringPool_header*>(mHeader);
473 h->header.headerSize = dtohs(mHeader->header.headerSize);
474 h->header.type = dtohs(mHeader->header.type);
475 h->header.size = dtohl(mHeader->header.size);
476 h->stringCount = dtohl(mHeader->stringCount);
477 h->styleCount = dtohl(mHeader->styleCount);
478 h->flags = dtohl(mHeader->flags);
479 h->stringsStart = dtohl(mHeader->stringsStart);
480 h->stylesStart = dtohl(mHeader->stylesStart);
481 }
482
483 if (mHeader->header.headerSize > mHeader->header.size
484 || mHeader->header.size > size) {
Steve Block8564c8d2012-01-05 23:22:43 +0000485 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 -0800486 (int)mHeader->header.headerSize, (int)mHeader->header.size, (int)size);
487 return (mError=BAD_TYPE);
488 }
489 mSize = mHeader->header.size;
490 mEntries = (const uint32_t*)
491 (((const uint8_t*)data)+mHeader->header.headerSize);
492
493 if (mHeader->stringCount > 0) {
494 if ((mHeader->stringCount*sizeof(uint32_t) < mHeader->stringCount) // uint32 overflow?
495 || (mHeader->header.headerSize+(mHeader->stringCount*sizeof(uint32_t)))
496 > size) {
Steve Block8564c8d2012-01-05 23:22:43 +0000497 ALOGW("Bad string block: entry of %d items extends past data size %d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800498 (int)(mHeader->header.headerSize+(mHeader->stringCount*sizeof(uint32_t))),
499 (int)size);
500 return (mError=BAD_TYPE);
501 }
Kenny Root19138462009-12-04 09:38:48 -0800502
503 size_t charSize;
504 if (mHeader->flags&ResStringPool_header::UTF8_FLAG) {
505 charSize = sizeof(uint8_t);
Kenny Root19138462009-12-04 09:38:48 -0800506 } else {
Adam Lesinski4bf58102014-11-03 11:21:19 -0800507 charSize = sizeof(uint16_t);
Kenny Root19138462009-12-04 09:38:48 -0800508 }
509
Adam Lesinskif28d5052014-07-25 15:25:04 -0700510 // There should be at least space for the smallest string
511 // (2 bytes length, null terminator).
512 if (mHeader->stringsStart >= (mSize - sizeof(uint16_t))) {
Steve Block8564c8d2012-01-05 23:22:43 +0000513 ALOGW("Bad string block: string pool starts at %d, after total size %d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514 (int)mHeader->stringsStart, (int)mHeader->header.size);
515 return (mError=BAD_TYPE);
516 }
Adam Lesinskif28d5052014-07-25 15:25:04 -0700517
518 mStrings = (const void*)
519 (((const uint8_t*)data) + mHeader->stringsStart);
520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 if (mHeader->styleCount == 0) {
Adam Lesinskif28d5052014-07-25 15:25:04 -0700522 mStringPoolSize = (mSize - mHeader->stringsStart) / charSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523 } else {
Kenny Root5e4d9a02010-06-08 12:34:43 -0700524 // check invariant: styles starts before end of data
Adam Lesinskif28d5052014-07-25 15:25:04 -0700525 if (mHeader->stylesStart >= (mSize - sizeof(uint16_t))) {
Steve Block8564c8d2012-01-05 23:22:43 +0000526 ALOGW("Bad style block: style block starts at %d past data size of %d\n",
Kenny Root5e4d9a02010-06-08 12:34:43 -0700527 (int)mHeader->stylesStart, (int)mHeader->header.size);
528 return (mError=BAD_TYPE);
529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 // check invariant: styles follow the strings
531 if (mHeader->stylesStart <= mHeader->stringsStart) {
Steve Block8564c8d2012-01-05 23:22:43 +0000532 ALOGW("Bad style block: style block starts at %d, before strings at %d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 (int)mHeader->stylesStart, (int)mHeader->stringsStart);
534 return (mError=BAD_TYPE);
535 }
536 mStringPoolSize =
Kenny Root19138462009-12-04 09:38:48 -0800537 (mHeader->stylesStart-mHeader->stringsStart)/charSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538 }
539
540 // check invariant: stringCount > 0 requires a string pool to exist
541 if (mStringPoolSize == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +0000542 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 -0800543 return (mError=BAD_TYPE);
544 }
545
546 if (notDeviceEndian) {
547 size_t i;
548 uint32_t* e = const_cast<uint32_t*>(mEntries);
549 for (i=0; i<mHeader->stringCount; i++) {
550 e[i] = dtohl(mEntries[i]);
551 }
Kenny Root19138462009-12-04 09:38:48 -0800552 if (!(mHeader->flags&ResStringPool_header::UTF8_FLAG)) {
Adam Lesinski4bf58102014-11-03 11:21:19 -0800553 const uint16_t* strings = (const uint16_t*)mStrings;
554 uint16_t* s = const_cast<uint16_t*>(strings);
Kenny Root19138462009-12-04 09:38:48 -0800555 for (i=0; i<mStringPoolSize; i++) {
556 s[i] = dtohs(strings[i]);
557 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800558 }
559 }
560
Kenny Root19138462009-12-04 09:38:48 -0800561 if ((mHeader->flags&ResStringPool_header::UTF8_FLAG &&
562 ((uint8_t*)mStrings)[mStringPoolSize-1] != 0) ||
563 (!mHeader->flags&ResStringPool_header::UTF8_FLAG &&
Adam Lesinski4bf58102014-11-03 11:21:19 -0800564 ((uint16_t*)mStrings)[mStringPoolSize-1] != 0)) {
Steve Block8564c8d2012-01-05 23:22:43 +0000565 ALOGW("Bad string block: last string is not 0-terminated\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566 return (mError=BAD_TYPE);
567 }
568 } else {
569 mStrings = NULL;
570 mStringPoolSize = 0;
571 }
572
573 if (mHeader->styleCount > 0) {
574 mEntryStyles = mEntries + mHeader->stringCount;
575 // invariant: integer overflow in calculating mEntryStyles
576 if (mEntryStyles < mEntries) {
Steve Block8564c8d2012-01-05 23:22:43 +0000577 ALOGW("Bad string block: integer overflow finding styles\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578 return (mError=BAD_TYPE);
579 }
580
581 if (((const uint8_t*)mEntryStyles-(const uint8_t*)mHeader) > (int)size) {
Steve Block8564c8d2012-01-05 23:22:43 +0000582 ALOGW("Bad string block: entry of %d styles extends past data size %d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 (int)((const uint8_t*)mEntryStyles-(const uint8_t*)mHeader),
584 (int)size);
585 return (mError=BAD_TYPE);
586 }
587 mStyles = (const uint32_t*)
588 (((const uint8_t*)data)+mHeader->stylesStart);
589 if (mHeader->stylesStart >= mHeader->header.size) {
Steve Block8564c8d2012-01-05 23:22:43 +0000590 ALOGW("Bad string block: style pool starts %d, after total size %d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591 (int)mHeader->stylesStart, (int)mHeader->header.size);
592 return (mError=BAD_TYPE);
593 }
594 mStylePoolSize =
595 (mHeader->header.size-mHeader->stylesStart)/sizeof(uint32_t);
596
597 if (notDeviceEndian) {
598 size_t i;
599 uint32_t* e = const_cast<uint32_t*>(mEntryStyles);
600 for (i=0; i<mHeader->styleCount; i++) {
601 e[i] = dtohl(mEntryStyles[i]);
602 }
603 uint32_t* s = const_cast<uint32_t*>(mStyles);
604 for (i=0; i<mStylePoolSize; i++) {
605 s[i] = dtohl(mStyles[i]);
606 }
607 }
608
609 const ResStringPool_span endSpan = {
610 { htodl(ResStringPool_span::END) },
611 htodl(ResStringPool_span::END), htodl(ResStringPool_span::END)
612 };
613 if (memcmp(&mStyles[mStylePoolSize-(sizeof(endSpan)/sizeof(uint32_t))],
614 &endSpan, sizeof(endSpan)) != 0) {
Steve Block8564c8d2012-01-05 23:22:43 +0000615 ALOGW("Bad string block: last style is not 0xFFFFFFFF-terminated\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 return (mError=BAD_TYPE);
617 }
618 } else {
619 mEntryStyles = NULL;
620 mStyles = NULL;
621 mStylePoolSize = 0;
622 }
623
624 return (mError=NO_ERROR);
625}
626
627status_t ResStringPool::getError() const
628{
629 return mError;
630}
631
632void ResStringPool::uninit()
633{
634 mError = NO_INIT;
Kenny Root19138462009-12-04 09:38:48 -0800635 if (mHeader != NULL && mCache != NULL) {
636 for (size_t x = 0; x < mHeader->stringCount; x++) {
637 if (mCache[x] != NULL) {
638 free(mCache[x]);
639 mCache[x] = NULL;
640 }
641 }
642 free(mCache);
643 mCache = NULL;
644 }
Chris Dearmana1d82ff32012-10-08 12:22:02 -0700645 if (mOwnedData) {
646 free(mOwnedData);
647 mOwnedData = NULL;
648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649}
650
Kenny Root300ba682010-11-09 14:37:23 -0800651/**
652 * Strings in UTF-16 format have length indicated by a length encoded in the
653 * stored data. It is either 1 or 2 characters of length data. This allows a
654 * maximum length of 0x7FFFFFF (2147483647 bytes), but if you're storing that
655 * much data in a string, you're abusing them.
656 *
657 * If the high bit is set, then there are two characters or 4 bytes of length
658 * data encoded. In that case, drop the high bit of the first character and
659 * add it together with the next character.
660 */
661static inline size_t
Adam Lesinski4bf58102014-11-03 11:21:19 -0800662decodeLength(const uint16_t** str)
Kenny Root300ba682010-11-09 14:37:23 -0800663{
664 size_t len = **str;
665 if ((len & 0x8000) != 0) {
666 (*str)++;
667 len = ((len & 0x7FFF) << 16) | **str;
668 }
669 (*str)++;
670 return len;
671}
Kenny Root19138462009-12-04 09:38:48 -0800672
Kenny Root300ba682010-11-09 14:37:23 -0800673/**
674 * Strings in UTF-8 format have length indicated by a length encoded in the
675 * stored data. It is either 1 or 2 characters of length data. This allows a
676 * maximum length of 0x7FFF (32767 bytes), but you should consider storing
677 * text in another way if you're using that much data in a single string.
678 *
679 * If the high bit is set, then there are two characters or 2 bytes of length
680 * data encoded. In that case, drop the high bit of the first character and
681 * add it together with the next character.
682 */
683static inline size_t
684decodeLength(const uint8_t** str)
685{
686 size_t len = **str;
687 if ((len & 0x80) != 0) {
688 (*str)++;
689 len = ((len & 0x7F) << 8) | **str;
690 }
691 (*str)++;
692 return len;
693}
694
Dan Albertf348c152014-09-08 18:28:00 -0700695const char16_t* ResStringPool::stringAt(size_t idx, size_t* u16len) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696{
697 if (mError == NO_ERROR && idx < mHeader->stringCount) {
Kenny Root19138462009-12-04 09:38:48 -0800698 const bool isUTF8 = (mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0;
Adam Lesinski4bf58102014-11-03 11:21:19 -0800699 const uint32_t off = mEntries[idx]/(isUTF8?sizeof(uint8_t):sizeof(uint16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 if (off < (mStringPoolSize-1)) {
Kenny Root19138462009-12-04 09:38:48 -0800701 if (!isUTF8) {
Adam Lesinski4bf58102014-11-03 11:21:19 -0800702 const uint16_t* strings = (uint16_t*)mStrings;
703 const uint16_t* str = strings+off;
Kenny Root300ba682010-11-09 14:37:23 -0800704
705 *u16len = decodeLength(&str);
706 if ((uint32_t)(str+*u16len-strings) < mStringPoolSize) {
Vishwath Mohan6521a1b2015-03-11 16:08:37 -0700707 // Reject malformed (non null-terminated) strings
708 if (str[*u16len] != 0x0000) {
709 ALOGW("Bad string block: string #%d is not null-terminated",
710 (int)idx);
711 return NULL;
712 }
Adam Lesinski4bf58102014-11-03 11:21:19 -0800713 return reinterpret_cast<const char16_t*>(str);
Kenny Root19138462009-12-04 09:38:48 -0800714 } else {
Steve Block8564c8d2012-01-05 23:22:43 +0000715 ALOGW("Bad string block: string #%d extends to %d, past end at %d\n",
Kenny Root300ba682010-11-09 14:37:23 -0800716 (int)idx, (int)(str+*u16len-strings), (int)mStringPoolSize);
Kenny Root19138462009-12-04 09:38:48 -0800717 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 } else {
Kenny Root19138462009-12-04 09:38:48 -0800719 const uint8_t* strings = (uint8_t*)mStrings;
Kenny Root300ba682010-11-09 14:37:23 -0800720 const uint8_t* u8str = strings+off;
721
722 *u16len = decodeLength(&u8str);
723 size_t u8len = decodeLength(&u8str);
724
725 // encLen must be less than 0x7FFF due to encoding.
726 if ((uint32_t)(u8str+u8len-strings) < mStringPoolSize) {
Kenny Root19138462009-12-04 09:38:48 -0800727 AutoMutex lock(mDecodeLock);
Kenny Root300ba682010-11-09 14:37:23 -0800728
Dianne Hackbornd45c68d2013-07-31 12:14:24 -0700729 if (mCache == NULL) {
Elliott Hughesba3fe562015-08-12 14:49:53 -0700730#ifndef __ANDROID__
Andreas Gampe2204f0b2014-10-21 23:04:54 -0700731 if (kDebugStringPoolNoisy) {
732 ALOGI("CREATING STRING CACHE OF %zu bytes",
733 mHeader->stringCount*sizeof(char16_t**));
734 }
Dianne Hackbornd45c68d2013-07-31 12:14:24 -0700735#else
736 // We do not want to be in this case when actually running Android.
Andreas Gampe25df5fb2014-11-07 22:24:57 -0800737 ALOGW("CREATING STRING CACHE OF %zu bytes",
738 static_cast<size_t>(mHeader->stringCount*sizeof(char16_t**)));
Dianne Hackbornd45c68d2013-07-31 12:14:24 -0700739#endif
740 mCache = (char16_t**)calloc(mHeader->stringCount, sizeof(char16_t**));
741 if (mCache == NULL) {
742 ALOGW("No memory trying to allocate decode cache table of %d bytes\n",
743 (int)(mHeader->stringCount*sizeof(char16_t**)));
744 return NULL;
745 }
746 }
747
Kenny Root19138462009-12-04 09:38:48 -0800748 if (mCache[idx] != NULL) {
749 return mCache[idx];
750 }
Kenny Root300ba682010-11-09 14:37:23 -0800751
752 ssize_t actualLen = utf8_to_utf16_length(u8str, u8len);
753 if (actualLen < 0 || (size_t)actualLen != *u16len) {
Steve Block8564c8d2012-01-05 23:22:43 +0000754 ALOGW("Bad string block: string #%lld decoded length is not correct "
Kenny Root300ba682010-11-09 14:37:23 -0800755 "%lld vs %llu\n",
756 (long long)idx, (long long)actualLen, (long long)*u16len);
757 return NULL;
758 }
759
Vishwath Mohan6521a1b2015-03-11 16:08:37 -0700760 // Reject malformed (non null-terminated) strings
761 if (u8str[u8len] != 0x00) {
762 ALOGW("Bad string block: string #%d is not null-terminated",
763 (int)idx);
764 return NULL;
765 }
766
Kenny Root300ba682010-11-09 14:37:23 -0800767 char16_t *u16str = (char16_t *)calloc(*u16len+1, sizeof(char16_t));
Kenny Root19138462009-12-04 09:38:48 -0800768 if (!u16str) {
Steve Block8564c8d2012-01-05 23:22:43 +0000769 ALOGW("No memory when trying to allocate decode cache for string #%d\n",
Kenny Root19138462009-12-04 09:38:48 -0800770 (int)idx);
771 return NULL;
772 }
Kenny Root300ba682010-11-09 14:37:23 -0800773
Andreas Gampe2204f0b2014-10-21 23:04:54 -0700774 if (kDebugStringPoolNoisy) {
775 ALOGI("Caching UTF8 string: %s", u8str);
776 }
Kenny Root300ba682010-11-09 14:37:23 -0800777 utf8_to_utf16(u8str, u8len, u16str);
Kenny Root19138462009-12-04 09:38:48 -0800778 mCache[idx] = u16str;
779 return u16str;
780 } else {
Steve Block8564c8d2012-01-05 23:22:43 +0000781 ALOGW("Bad string block: string #%lld extends to %lld, past end at %lld\n",
Kenny Root300ba682010-11-09 14:37:23 -0800782 (long long)idx, (long long)(u8str+u8len-strings),
783 (long long)mStringPoolSize);
Kenny Root19138462009-12-04 09:38:48 -0800784 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 }
786 } else {
Steve Block8564c8d2012-01-05 23:22:43 +0000787 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 -0800788 (int)idx, (int)(off*sizeof(uint16_t)),
789 (int)(mStringPoolSize*sizeof(uint16_t)));
790 }
791 }
792 return NULL;
793}
794
Kenny Root780d2a12010-02-22 22:36:26 -0800795const char* ResStringPool::string8At(size_t idx, size_t* outLen) const
796{
797 if (mError == NO_ERROR && idx < mHeader->stringCount) {
Dianne Hackbornd45c68d2013-07-31 12:14:24 -0700798 if ((mHeader->flags&ResStringPool_header::UTF8_FLAG) == 0) {
799 return NULL;
800 }
801 const uint32_t off = mEntries[idx]/sizeof(char);
Kenny Root780d2a12010-02-22 22:36:26 -0800802 if (off < (mStringPoolSize-1)) {
Dianne Hackbornd45c68d2013-07-31 12:14:24 -0700803 const uint8_t* strings = (uint8_t*)mStrings;
804 const uint8_t* str = strings+off;
805 *outLen = decodeLength(&str);
806 size_t encLen = decodeLength(&str);
807 if ((uint32_t)(str+encLen-strings) < mStringPoolSize) {
808 return (const char*)str;
809 } else {
810 ALOGW("Bad string block: string #%d extends to %d, past end at %d\n",
811 (int)idx, (int)(str+encLen-strings), (int)mStringPoolSize);
Kenny Root780d2a12010-02-22 22:36:26 -0800812 }
813 } else {
Steve Block8564c8d2012-01-05 23:22:43 +0000814 ALOGW("Bad string block: string #%d entry is at %d, past end at %d\n",
Kenny Root780d2a12010-02-22 22:36:26 -0800815 (int)idx, (int)(off*sizeof(uint16_t)),
816 (int)(mStringPoolSize*sizeof(uint16_t)));
817 }
818 }
819 return NULL;
820}
821
Dianne Hackborn6c997a92012-01-31 11:27:43 -0800822const String8 ResStringPool::string8ObjectAt(size_t idx) const
823{
824 size_t len;
Adam Lesinski4b2d0f22014-08-14 17:58:37 -0700825 const char *str = string8At(idx, &len);
Dianne Hackborn6c997a92012-01-31 11:27:43 -0800826 if (str != NULL) {
Adam Lesinski4b2d0f22014-08-14 17:58:37 -0700827 return String8(str, len);
Dianne Hackborn6c997a92012-01-31 11:27:43 -0800828 }
Adam Lesinski4b2d0f22014-08-14 17:58:37 -0700829
830 const char16_t *str16 = stringAt(idx, &len);
831 if (str16 != NULL) {
832 return String8(str16, len);
833 }
834 return String8();
Dianne Hackborn6c997a92012-01-31 11:27:43 -0800835}
836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837const ResStringPool_span* ResStringPool::styleAt(const ResStringPool_ref& ref) const
838{
839 return styleAt(ref.index);
840}
841
842const ResStringPool_span* ResStringPool::styleAt(size_t idx) const
843{
844 if (mError == NO_ERROR && idx < mHeader->styleCount) {
845 const uint32_t off = (mEntryStyles[idx]/sizeof(uint32_t));
846 if (off < mStylePoolSize) {
847 return (const ResStringPool_span*)(mStyles+off);
848 } else {
Steve Block8564c8d2012-01-05 23:22:43 +0000849 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 -0800850 (int)idx, (int)(off*sizeof(uint32_t)),
851 (int)(mStylePoolSize*sizeof(uint32_t)));
852 }
853 }
854 return NULL;
855}
856
857ssize_t ResStringPool::indexOfString(const char16_t* str, size_t strLen) const
858{
859 if (mError != NO_ERROR) {
860 return mError;
861 }
862
863 size_t len;
864
Dianne Hackbornd45c68d2013-07-31 12:14:24 -0700865 if ((mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -0700866 if (kDebugStringPoolNoisy) {
867 ALOGI("indexOfString UTF-8: %s", String8(str, strLen).string());
868 }
Kenny Root19138462009-12-04 09:38:48 -0800869
Dianne Hackbornd45c68d2013-07-31 12:14:24 -0700870 // The string pool contains UTF 8 strings; we don't want to cause
871 // temporary UTF-16 strings to be created as we search.
872 if (mHeader->flags&ResStringPool_header::SORTED_FLAG) {
873 // Do a binary search for the string... this is a little tricky,
874 // because the strings are sorted with strzcmp16(). So to match
875 // the ordering, we need to convert strings in the pool to UTF-16.
876 // But we don't want to hit the cache, so instead we will have a
877 // local temporary allocation for the conversions.
878 char16_t* convBuffer = (char16_t*)malloc(strLen+4);
879 ssize_t l = 0;
880 ssize_t h = mHeader->stringCount-1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881
Dianne Hackbornd45c68d2013-07-31 12:14:24 -0700882 ssize_t mid;
883 while (l <= h) {
884 mid = l + (h - l)/2;
885 const uint8_t* s = (const uint8_t*)string8At(mid, &len);
886 int c;
887 if (s != NULL) {
888 char16_t* end = utf8_to_utf16_n(s, len, convBuffer, strLen+3);
889 *end = 0;
890 c = strzcmp16(convBuffer, end-convBuffer, str, strLen);
891 } else {
892 c = -1;
893 }
Andreas Gampe2204f0b2014-10-21 23:04:54 -0700894 if (kDebugStringPoolNoisy) {
895 ALOGI("Looking at %s, cmp=%d, l/mid/h=%d/%d/%d\n",
896 (const char*)s, c, (int)l, (int)mid, (int)h);
897 }
Dianne Hackbornd45c68d2013-07-31 12:14:24 -0700898 if (c == 0) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -0700899 if (kDebugStringPoolNoisy) {
900 ALOGI("MATCH!");
901 }
Dianne Hackbornd45c68d2013-07-31 12:14:24 -0700902 free(convBuffer);
903 return mid;
904 } else if (c < 0) {
905 l = mid + 1;
906 } else {
907 h = mid - 1;
908 }
909 }
910 free(convBuffer);
911 } else {
912 // It is unusual to get the ID from an unsorted string block...
913 // most often this happens because we want to get IDs for style
914 // span tags; since those always appear at the end of the string
915 // block, start searching at the back.
916 String8 str8(str, strLen);
917 const size_t str8Len = str8.size();
918 for (int i=mHeader->stringCount-1; i>=0; i--) {
919 const char* s = string8At(i, &len);
Andreas Gampe2204f0b2014-10-21 23:04:54 -0700920 if (kDebugStringPoolNoisy) {
921 ALOGI("Looking at %s, i=%d\n", String8(s).string(), i);
922 }
Dianne Hackbornd45c68d2013-07-31 12:14:24 -0700923 if (s && str8Len == len && memcmp(s, str8.string(), str8Len) == 0) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -0700924 if (kDebugStringPoolNoisy) {
925 ALOGI("MATCH!");
926 }
Dianne Hackbornd45c68d2013-07-31 12:14:24 -0700927 return i;
928 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 }
930 }
Dianne Hackbornd45c68d2013-07-31 12:14:24 -0700931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 } else {
Andreas Gampe2204f0b2014-10-21 23:04:54 -0700933 if (kDebugStringPoolNoisy) {
934 ALOGI("indexOfString UTF-16: %s", String8(str, strLen).string());
935 }
Dianne Hackbornd45c68d2013-07-31 12:14:24 -0700936
937 if (mHeader->flags&ResStringPool_header::SORTED_FLAG) {
938 // Do a binary search for the string...
939 ssize_t l = 0;
940 ssize_t h = mHeader->stringCount-1;
941
942 ssize_t mid;
943 while (l <= h) {
944 mid = l + (h - l)/2;
945 const char16_t* s = stringAt(mid, &len);
946 int c = s ? strzcmp16(s, len, str, strLen) : -1;
Andreas Gampe2204f0b2014-10-21 23:04:54 -0700947 if (kDebugStringPoolNoisy) {
948 ALOGI("Looking at %s, cmp=%d, l/mid/h=%d/%d/%d\n",
949 String8(s).string(), c, (int)l, (int)mid, (int)h);
950 }
Dianne Hackbornd45c68d2013-07-31 12:14:24 -0700951 if (c == 0) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -0700952 if (kDebugStringPoolNoisy) {
953 ALOGI("MATCH!");
954 }
Dianne Hackbornd45c68d2013-07-31 12:14:24 -0700955 return mid;
956 } else if (c < 0) {
957 l = mid + 1;
958 } else {
959 h = mid - 1;
960 }
961 }
962 } else {
963 // It is unusual to get the ID from an unsorted string block...
964 // most often this happens because we want to get IDs for style
965 // span tags; since those always appear at the end of the string
966 // block, start searching at the back.
967 for (int i=mHeader->stringCount-1; i>=0; i--) {
968 const char16_t* s = stringAt(i, &len);
Andreas Gampe2204f0b2014-10-21 23:04:54 -0700969 if (kDebugStringPoolNoisy) {
970 ALOGI("Looking at %s, i=%d\n", String8(s).string(), i);
971 }
Dianne Hackbornd45c68d2013-07-31 12:14:24 -0700972 if (s && strLen == len && strzcmp16(s, len, str, strLen) == 0) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -0700973 if (kDebugStringPoolNoisy) {
974 ALOGI("MATCH!");
975 }
Dianne Hackbornd45c68d2013-07-31 12:14:24 -0700976 return i;
977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 }
979 }
980 }
981
982 return NAME_NOT_FOUND;
983}
984
985size_t ResStringPool::size() const
986{
987 return (mError == NO_ERROR) ? mHeader->stringCount : 0;
988}
989
Dianne Hackborn6c997a92012-01-31 11:27:43 -0800990size_t ResStringPool::styleCount() const
991{
992 return (mError == NO_ERROR) ? mHeader->styleCount : 0;
993}
994
995size_t ResStringPool::bytes() const
996{
997 return (mError == NO_ERROR) ? mHeader->header.size : 0;
998}
999
1000bool ResStringPool::isSorted() const
1001{
1002 return (mHeader->flags&ResStringPool_header::SORTED_FLAG)!=0;
1003}
1004
Kenny Rootbb79f642009-12-10 14:20:15 -08001005bool ResStringPool::isUTF8() const
1006{
1007 return (mHeader->flags&ResStringPool_header::UTF8_FLAG)!=0;
1008}
Kenny Rootbb79f642009-12-10 14:20:15 -08001009
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010// --------------------------------------------------------------------
1011// --------------------------------------------------------------------
1012// --------------------------------------------------------------------
1013
1014ResXMLParser::ResXMLParser(const ResXMLTree& tree)
1015 : mTree(tree), mEventCode(BAD_DOCUMENT)
1016{
1017}
1018
1019void ResXMLParser::restart()
1020{
1021 mCurNode = NULL;
1022 mEventCode = mTree.mError == NO_ERROR ? START_DOCUMENT : BAD_DOCUMENT;
1023}
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001024const ResStringPool& ResXMLParser::getStrings() const
1025{
1026 return mTree.mStrings;
1027}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028
1029ResXMLParser::event_code_t ResXMLParser::getEventType() const
1030{
1031 return mEventCode;
1032}
1033
1034ResXMLParser::event_code_t ResXMLParser::next()
1035{
1036 if (mEventCode == START_DOCUMENT) {
1037 mCurNode = mTree.mRootNode;
1038 mCurExt = mTree.mRootExt;
1039 return (mEventCode=mTree.mRootCode);
1040 } else if (mEventCode >= FIRST_CHUNK_CODE) {
1041 return nextNode();
1042 }
1043 return mEventCode;
1044}
1045
Mathias Agopian5f910972009-06-22 02:35:32 -07001046int32_t ResXMLParser::getCommentID() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047{
1048 return mCurNode != NULL ? dtohl(mCurNode->comment.index) : -1;
1049}
1050
Dan Albertf348c152014-09-08 18:28:00 -07001051const char16_t* ResXMLParser::getComment(size_t* outLen) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052{
1053 int32_t id = getCommentID();
1054 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1055}
1056
Mathias Agopian5f910972009-06-22 02:35:32 -07001057uint32_t ResXMLParser::getLineNumber() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058{
1059 return mCurNode != NULL ? dtohl(mCurNode->lineNumber) : -1;
1060}
1061
Mathias Agopian5f910972009-06-22 02:35:32 -07001062int32_t ResXMLParser::getTextID() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063{
1064 if (mEventCode == TEXT) {
1065 return dtohl(((const ResXMLTree_cdataExt*)mCurExt)->data.index);
1066 }
1067 return -1;
1068}
1069
Dan Albertf348c152014-09-08 18:28:00 -07001070const char16_t* ResXMLParser::getText(size_t* outLen) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071{
1072 int32_t id = getTextID();
1073 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1074}
1075
1076ssize_t ResXMLParser::getTextValue(Res_value* outValue) const
1077{
1078 if (mEventCode == TEXT) {
1079 outValue->copyFrom_dtoh(((const ResXMLTree_cdataExt*)mCurExt)->typedData);
1080 return sizeof(Res_value);
1081 }
1082 return BAD_TYPE;
1083}
1084
Mathias Agopian5f910972009-06-22 02:35:32 -07001085int32_t ResXMLParser::getNamespacePrefixID() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086{
1087 if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) {
1088 return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->prefix.index);
1089 }
1090 return -1;
1091}
1092
Dan Albertf348c152014-09-08 18:28:00 -07001093const char16_t* ResXMLParser::getNamespacePrefix(size_t* outLen) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094{
1095 int32_t id = getNamespacePrefixID();
1096 //printf("prefix=%d event=%p\n", id, mEventCode);
1097 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1098}
1099
Mathias Agopian5f910972009-06-22 02:35:32 -07001100int32_t ResXMLParser::getNamespaceUriID() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001101{
1102 if (mEventCode == START_NAMESPACE || mEventCode == END_NAMESPACE) {
1103 return dtohl(((const ResXMLTree_namespaceExt*)mCurExt)->uri.index);
1104 }
1105 return -1;
1106}
1107
Dan Albertf348c152014-09-08 18:28:00 -07001108const char16_t* ResXMLParser::getNamespaceUri(size_t* outLen) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109{
1110 int32_t id = getNamespaceUriID();
1111 //printf("uri=%d event=%p\n", id, mEventCode);
1112 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1113}
1114
Mathias Agopian5f910972009-06-22 02:35:32 -07001115int32_t ResXMLParser::getElementNamespaceID() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116{
1117 if (mEventCode == START_TAG) {
1118 return dtohl(((const ResXMLTree_attrExt*)mCurExt)->ns.index);
1119 }
1120 if (mEventCode == END_TAG) {
1121 return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->ns.index);
1122 }
1123 return -1;
1124}
1125
Dan Albertf348c152014-09-08 18:28:00 -07001126const char16_t* ResXMLParser::getElementNamespace(size_t* outLen) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127{
1128 int32_t id = getElementNamespaceID();
1129 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1130}
1131
Mathias Agopian5f910972009-06-22 02:35:32 -07001132int32_t ResXMLParser::getElementNameID() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133{
1134 if (mEventCode == START_TAG) {
1135 return dtohl(((const ResXMLTree_attrExt*)mCurExt)->name.index);
1136 }
1137 if (mEventCode == END_TAG) {
1138 return dtohl(((const ResXMLTree_endElementExt*)mCurExt)->name.index);
1139 }
1140 return -1;
1141}
1142
Dan Albertf348c152014-09-08 18:28:00 -07001143const char16_t* ResXMLParser::getElementName(size_t* outLen) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144{
1145 int32_t id = getElementNameID();
1146 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1147}
1148
1149size_t ResXMLParser::getAttributeCount() const
1150{
1151 if (mEventCode == START_TAG) {
1152 return dtohs(((const ResXMLTree_attrExt*)mCurExt)->attributeCount);
1153 }
1154 return 0;
1155}
1156
Mathias Agopian5f910972009-06-22 02:35:32 -07001157int32_t ResXMLParser::getAttributeNamespaceID(size_t idx) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158{
1159 if (mEventCode == START_TAG) {
1160 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1161 if (idx < dtohs(tag->attributeCount)) {
1162 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1163 (((const uint8_t*)tag)
1164 + dtohs(tag->attributeStart)
1165 + (dtohs(tag->attributeSize)*idx));
1166 return dtohl(attr->ns.index);
1167 }
1168 }
1169 return -2;
1170}
1171
Dan Albertf348c152014-09-08 18:28:00 -07001172const char16_t* ResXMLParser::getAttributeNamespace(size_t idx, size_t* outLen) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173{
1174 int32_t id = getAttributeNamespaceID(idx);
1175 //printf("attribute namespace=%d idx=%d event=%p\n", id, idx, mEventCode);
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001176 if (kDebugXMLNoisy) {
1177 printf("getAttributeNamespace 0x%zx=0x%x\n", idx, id);
1178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1180}
1181
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07001182const char* ResXMLParser::getAttributeNamespace8(size_t idx, size_t* outLen) const
1183{
1184 int32_t id = getAttributeNamespaceID(idx);
1185 //printf("attribute namespace=%d idx=%d event=%p\n", id, idx, mEventCode);
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001186 if (kDebugXMLNoisy) {
1187 printf("getAttributeNamespace 0x%zx=0x%x\n", idx, id);
1188 }
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07001189 return id >= 0 ? mTree.mStrings.string8At(id, outLen) : NULL;
1190}
1191
Mathias Agopian5f910972009-06-22 02:35:32 -07001192int32_t ResXMLParser::getAttributeNameID(size_t idx) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193{
1194 if (mEventCode == START_TAG) {
1195 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1196 if (idx < dtohs(tag->attributeCount)) {
1197 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1198 (((const uint8_t*)tag)
1199 + dtohs(tag->attributeStart)
1200 + (dtohs(tag->attributeSize)*idx));
1201 return dtohl(attr->name.index);
1202 }
1203 }
1204 return -1;
1205}
1206
Dan Albertf348c152014-09-08 18:28:00 -07001207const char16_t* ResXMLParser::getAttributeName(size_t idx, size_t* outLen) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208{
1209 int32_t id = getAttributeNameID(idx);
1210 //printf("attribute name=%d idx=%d event=%p\n", id, idx, mEventCode);
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001211 if (kDebugXMLNoisy) {
1212 printf("getAttributeName 0x%zx=0x%x\n", idx, id);
1213 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1215}
1216
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07001217const char* ResXMLParser::getAttributeName8(size_t idx, size_t* outLen) const
1218{
1219 int32_t id = getAttributeNameID(idx);
1220 //printf("attribute name=%d idx=%d event=%p\n", id, idx, mEventCode);
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001221 if (kDebugXMLNoisy) {
1222 printf("getAttributeName 0x%zx=0x%x\n", idx, id);
1223 }
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07001224 return id >= 0 ? mTree.mStrings.string8At(id, outLen) : NULL;
1225}
1226
Mathias Agopian5f910972009-06-22 02:35:32 -07001227uint32_t ResXMLParser::getAttributeNameResID(size_t idx) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001228{
1229 int32_t id = getAttributeNameID(idx);
1230 if (id >= 0 && (size_t)id < mTree.mNumResIds) {
Adam Lesinskia7d1d732014-10-01 18:24:54 -07001231 uint32_t resId = dtohl(mTree.mResIds[id]);
1232 if (mTree.mDynamicRefTable != NULL) {
1233 mTree.mDynamicRefTable->lookupResourceId(&resId);
1234 }
1235 return resId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001236 }
1237 return 0;
1238}
1239
Mathias Agopian5f910972009-06-22 02:35:32 -07001240int32_t ResXMLParser::getAttributeValueStringID(size_t idx) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241{
1242 if (mEventCode == START_TAG) {
1243 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1244 if (idx < dtohs(tag->attributeCount)) {
1245 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1246 (((const uint8_t*)tag)
1247 + dtohs(tag->attributeStart)
1248 + (dtohs(tag->attributeSize)*idx));
1249 return dtohl(attr->rawValue.index);
1250 }
1251 }
1252 return -1;
1253}
1254
Dan Albertf348c152014-09-08 18:28:00 -07001255const char16_t* ResXMLParser::getAttributeStringValue(size_t idx, size_t* outLen) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256{
1257 int32_t id = getAttributeValueStringID(idx);
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001258 if (kDebugXMLNoisy) {
1259 printf("getAttributeValue 0x%zx=0x%x\n", idx, id);
1260 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 return id >= 0 ? mTree.mStrings.stringAt(id, outLen) : NULL;
1262}
1263
1264int32_t ResXMLParser::getAttributeDataType(size_t idx) 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));
Adam Lesinskide898ff2014-01-29 18:20:45 -08001273 uint8_t type = attr->typedValue.dataType;
1274 if (type != Res_value::TYPE_DYNAMIC_REFERENCE) {
1275 return type;
1276 }
1277
1278 // This is a dynamic reference. We adjust those references
1279 // to regular references at this level, so lie to the caller.
1280 return Res_value::TYPE_REFERENCE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 }
1282 }
1283 return Res_value::TYPE_NULL;
1284}
1285
1286int32_t ResXMLParser::getAttributeData(size_t idx) const
1287{
1288 if (mEventCode == START_TAG) {
1289 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1290 if (idx < dtohs(tag->attributeCount)) {
1291 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1292 (((const uint8_t*)tag)
1293 + dtohs(tag->attributeStart)
1294 + (dtohs(tag->attributeSize)*idx));
Adam Lesinskide898ff2014-01-29 18:20:45 -08001295 if (attr->typedValue.dataType != Res_value::TYPE_DYNAMIC_REFERENCE ||
1296 mTree.mDynamicRefTable == NULL) {
1297 return dtohl(attr->typedValue.data);
1298 }
1299
1300 uint32_t data = dtohl(attr->typedValue.data);
1301 if (mTree.mDynamicRefTable->lookupResourceId(&data) == NO_ERROR) {
1302 return data;
1303 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 }
1305 }
1306 return 0;
1307}
1308
1309ssize_t ResXMLParser::getAttributeValue(size_t idx, Res_value* outValue) const
1310{
1311 if (mEventCode == START_TAG) {
1312 const ResXMLTree_attrExt* tag = (const ResXMLTree_attrExt*)mCurExt;
1313 if (idx < dtohs(tag->attributeCount)) {
1314 const ResXMLTree_attribute* attr = (const ResXMLTree_attribute*)
1315 (((const uint8_t*)tag)
1316 + dtohs(tag->attributeStart)
1317 + (dtohs(tag->attributeSize)*idx));
1318 outValue->copyFrom_dtoh(attr->typedValue);
Adam Lesinskide898ff2014-01-29 18:20:45 -08001319 if (mTree.mDynamicRefTable != NULL &&
1320 mTree.mDynamicRefTable->lookupResourceValue(outValue) != NO_ERROR) {
1321 return BAD_TYPE;
1322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 return sizeof(Res_value);
1324 }
1325 }
1326 return BAD_TYPE;
1327}
1328
1329ssize_t ResXMLParser::indexOfAttribute(const char* ns, const char* attr) const
1330{
1331 String16 nsStr(ns != NULL ? ns : "");
1332 String16 attrStr(attr);
1333 return indexOfAttribute(ns ? nsStr.string() : NULL, ns ? nsStr.size() : 0,
1334 attrStr.string(), attrStr.size());
1335}
1336
1337ssize_t ResXMLParser::indexOfAttribute(const char16_t* ns, size_t nsLen,
1338 const char16_t* attr, size_t attrLen) const
1339{
1340 if (mEventCode == START_TAG) {
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07001341 if (attr == NULL) {
1342 return NAME_NOT_FOUND;
1343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 const size_t N = getAttributeCount();
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07001345 if (mTree.mStrings.isUTF8()) {
1346 String8 ns8, attr8;
1347 if (ns != NULL) {
1348 ns8 = String8(ns, nsLen);
1349 }
1350 attr8 = String8(attr, attrLen);
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001351 if (kDebugStringPoolNoisy) {
1352 ALOGI("indexOfAttribute UTF8 %s (%zu) / %s (%zu)", ns8.string(), nsLen,
1353 attr8.string(), attrLen);
1354 }
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07001355 for (size_t i=0; i<N; i++) {
1356 size_t curNsLen = 0, curAttrLen = 0;
1357 const char* curNs = getAttributeNamespace8(i, &curNsLen);
1358 const char* curAttr = getAttributeName8(i, &curAttrLen);
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001359 if (kDebugStringPoolNoisy) {
1360 ALOGI(" curNs=%s (%zu), curAttr=%s (%zu)", curNs, curNsLen, curAttr, curAttrLen);
1361 }
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07001362 if (curAttr != NULL && curNsLen == nsLen && curAttrLen == attrLen
1363 && memcmp(attr8.string(), curAttr, attrLen) == 0) {
1364 if (ns == NULL) {
1365 if (curNs == NULL) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001366 if (kDebugStringPoolNoisy) {
1367 ALOGI(" FOUND!");
1368 }
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07001369 return i;
1370 }
1371 } else if (curNs != NULL) {
1372 //printf(" --> ns=%s, curNs=%s\n",
1373 // String8(ns).string(), String8(curNs).string());
1374 if (memcmp(ns8.string(), curNs, nsLen) == 0) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001375 if (kDebugStringPoolNoisy) {
1376 ALOGI(" FOUND!");
1377 }
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07001378 return i;
1379 }
1380 }
1381 }
1382 }
1383 } else {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001384 if (kDebugStringPoolNoisy) {
1385 ALOGI("indexOfAttribute UTF16 %s (%zu) / %s (%zu)",
1386 String8(ns, nsLen).string(), nsLen,
1387 String8(attr, attrLen).string(), attrLen);
1388 }
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07001389 for (size_t i=0; i<N; i++) {
1390 size_t curNsLen = 0, curAttrLen = 0;
1391 const char16_t* curNs = getAttributeNamespace(i, &curNsLen);
1392 const char16_t* curAttr = getAttributeName(i, &curAttrLen);
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001393 if (kDebugStringPoolNoisy) {
1394 ALOGI(" curNs=%s (%zu), curAttr=%s (%zu)",
1395 String8(curNs, curNsLen).string(), curNsLen,
1396 String8(curAttr, curAttrLen).string(), curAttrLen);
1397 }
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07001398 if (curAttr != NULL && curNsLen == nsLen && curAttrLen == attrLen
1399 && (memcmp(attr, curAttr, attrLen*sizeof(char16_t)) == 0)) {
1400 if (ns == NULL) {
1401 if (curNs == NULL) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001402 if (kDebugStringPoolNoisy) {
1403 ALOGI(" FOUND!");
1404 }
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07001405 return i;
1406 }
1407 } else if (curNs != NULL) {
1408 //printf(" --> ns=%s, curNs=%s\n",
1409 // String8(ns).string(), String8(curNs).string());
1410 if (memcmp(ns, curNs, nsLen*sizeof(char16_t)) == 0) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001411 if (kDebugStringPoolNoisy) {
1412 ALOGI(" FOUND!");
1413 }
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07001414 return i;
1415 }
1416 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 }
1418 }
1419 }
1420 }
1421
1422 return NAME_NOT_FOUND;
1423}
1424
1425ssize_t ResXMLParser::indexOfID() const
1426{
1427 if (mEventCode == START_TAG) {
1428 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->idIndex);
1429 if (idx > 0) return (idx-1);
1430 }
1431 return NAME_NOT_FOUND;
1432}
1433
1434ssize_t ResXMLParser::indexOfClass() const
1435{
1436 if (mEventCode == START_TAG) {
1437 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->classIndex);
1438 if (idx > 0) return (idx-1);
1439 }
1440 return NAME_NOT_FOUND;
1441}
1442
1443ssize_t ResXMLParser::indexOfStyle() const
1444{
1445 if (mEventCode == START_TAG) {
1446 const ssize_t idx = dtohs(((const ResXMLTree_attrExt*)mCurExt)->styleIndex);
1447 if (idx > 0) return (idx-1);
1448 }
1449 return NAME_NOT_FOUND;
1450}
1451
1452ResXMLParser::event_code_t ResXMLParser::nextNode()
1453{
1454 if (mEventCode < 0) {
1455 return mEventCode;
1456 }
1457
1458 do {
1459 const ResXMLTree_node* next = (const ResXMLTree_node*)
1460 (((const uint8_t*)mCurNode) + dtohl(mCurNode->header.size));
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001461 if (kDebugXMLNoisy) {
1462 ALOGI("Next node: prev=%p, next=%p\n", mCurNode, next);
1463 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07001464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 if (((const uint8_t*)next) >= mTree.mDataEnd) {
1466 mCurNode = NULL;
1467 return (mEventCode=END_DOCUMENT);
1468 }
1469
1470 if (mTree.validateNode(next) != NO_ERROR) {
1471 mCurNode = NULL;
1472 return (mEventCode=BAD_DOCUMENT);
1473 }
1474
1475 mCurNode = next;
1476 const uint16_t headerSize = dtohs(next->header.headerSize);
1477 const uint32_t totalSize = dtohl(next->header.size);
1478 mCurExt = ((const uint8_t*)next) + headerSize;
1479 size_t minExtSize = 0;
1480 event_code_t eventCode = (event_code_t)dtohs(next->header.type);
1481 switch ((mEventCode=eventCode)) {
1482 case RES_XML_START_NAMESPACE_TYPE:
1483 case RES_XML_END_NAMESPACE_TYPE:
1484 minExtSize = sizeof(ResXMLTree_namespaceExt);
1485 break;
1486 case RES_XML_START_ELEMENT_TYPE:
1487 minExtSize = sizeof(ResXMLTree_attrExt);
1488 break;
1489 case RES_XML_END_ELEMENT_TYPE:
1490 minExtSize = sizeof(ResXMLTree_endElementExt);
1491 break;
1492 case RES_XML_CDATA_TYPE:
1493 minExtSize = sizeof(ResXMLTree_cdataExt);
1494 break;
1495 default:
Steve Block8564c8d2012-01-05 23:22:43 +00001496 ALOGW("Unknown XML block: header type %d in node at %d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 (int)dtohs(next->header.type),
1498 (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)));
1499 continue;
1500 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07001501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 if ((totalSize-headerSize) < minExtSize) {
Steve Block8564c8d2012-01-05 23:22:43 +00001503 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 -08001504 (int)dtohs(next->header.type),
1505 (int)(((const uint8_t*)next)-((const uint8_t*)mTree.mHeader)),
1506 (int)(totalSize-headerSize), (int)minExtSize);
1507 return (mEventCode=BAD_DOCUMENT);
1508 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07001509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 //printf("CurNode=%p, CurExt=%p, headerSize=%d, minExtSize=%d\n",
1511 // mCurNode, mCurExt, headerSize, minExtSize);
Mark Salyzyn00adb862014-03-19 11:00:06 -07001512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 return eventCode;
1514 } while (true);
1515}
1516
1517void ResXMLParser::getPosition(ResXMLParser::ResXMLPosition* pos) const
1518{
1519 pos->eventCode = mEventCode;
1520 pos->curNode = mCurNode;
1521 pos->curExt = mCurExt;
1522}
1523
1524void ResXMLParser::setPosition(const ResXMLParser::ResXMLPosition& pos)
1525{
1526 mEventCode = pos.eventCode;
1527 mCurNode = pos.curNode;
1528 mCurExt = pos.curExt;
1529}
1530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531// --------------------------------------------------------------------
1532
1533static volatile int32_t gCount = 0;
1534
Adam Lesinskide898ff2014-01-29 18:20:45 -08001535ResXMLTree::ResXMLTree(const DynamicRefTable* dynamicRefTable)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 : ResXMLParser(*this)
Adam Lesinskide898ff2014-01-29 18:20:45 -08001537 , mDynamicRefTable(dynamicRefTable)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 , mError(NO_INIT), mOwnedData(NULL)
1539{
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001540 if (kDebugResXMLTree) {
1541 ALOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1);
1542 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 restart();
1544}
1545
Adam Lesinskide898ff2014-01-29 18:20:45 -08001546ResXMLTree::ResXMLTree()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 : ResXMLParser(*this)
Adam Lesinskide898ff2014-01-29 18:20:45 -08001548 , mDynamicRefTable(NULL)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 , mError(NO_INIT), mOwnedData(NULL)
1550{
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001551 if (kDebugResXMLTree) {
1552 ALOGI("Creating ResXMLTree %p #%d\n", this, android_atomic_inc(&gCount)+1);
1553 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08001554 restart();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555}
1556
1557ResXMLTree::~ResXMLTree()
1558{
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001559 if (kDebugResXMLTree) {
1560 ALOGI("Destroying ResXMLTree in %p #%d\n", this, android_atomic_dec(&gCount)-1);
1561 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 uninit();
1563}
1564
1565status_t ResXMLTree::setTo(const void* data, size_t size, bool copyData)
1566{
1567 uninit();
1568 mEventCode = START_DOCUMENT;
1569
Kenny Root32d6aef2012-10-10 10:23:47 -07001570 if (!data || !size) {
1571 return (mError=BAD_TYPE);
1572 }
1573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 if (copyData) {
1575 mOwnedData = malloc(size);
1576 if (mOwnedData == NULL) {
1577 return (mError=NO_MEMORY);
1578 }
1579 memcpy(mOwnedData, data, size);
1580 data = mOwnedData;
1581 }
1582
1583 mHeader = (const ResXMLTree_header*)data;
1584 mSize = dtohl(mHeader->header.size);
1585 if (dtohs(mHeader->header.headerSize) > mSize || mSize > size) {
Steve Block8564c8d2012-01-05 23:22:43 +00001586 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 -08001587 (int)dtohs(mHeader->header.headerSize),
1588 (int)dtohl(mHeader->header.size), (int)size);
1589 mError = BAD_TYPE;
1590 restart();
1591 return mError;
1592 }
1593 mDataEnd = ((const uint8_t*)mHeader) + mSize;
1594
1595 mStrings.uninit();
1596 mRootNode = NULL;
1597 mResIds = NULL;
1598 mNumResIds = 0;
1599
1600 // First look for a couple interesting chunks: the string block
1601 // and first XML node.
1602 const ResChunk_header* chunk =
1603 (const ResChunk_header*)(((const uint8_t*)mHeader) + dtohs(mHeader->header.headerSize));
1604 const ResChunk_header* lastChunk = chunk;
1605 while (((const uint8_t*)chunk) < (mDataEnd-sizeof(ResChunk_header)) &&
1606 ((const uint8_t*)chunk) < (mDataEnd-dtohl(chunk->size))) {
1607 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), mDataEnd, "XML");
1608 if (err != NO_ERROR) {
1609 mError = err;
1610 goto done;
1611 }
1612 const uint16_t type = dtohs(chunk->type);
1613 const size_t size = dtohl(chunk->size);
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001614 if (kDebugXMLNoisy) {
1615 printf("Scanning @ %p: type=0x%x, size=0x%zx\n",
1616 (void*)(((uintptr_t)chunk)-((uintptr_t)mHeader)), type, size);
1617 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 if (type == RES_STRING_POOL_TYPE) {
1619 mStrings.setTo(chunk, size);
1620 } else if (type == RES_XML_RESOURCE_MAP_TYPE) {
1621 mResIds = (const uint32_t*)
1622 (((const uint8_t*)chunk)+dtohs(chunk->headerSize));
1623 mNumResIds = (dtohl(chunk->size)-dtohs(chunk->headerSize))/sizeof(uint32_t);
1624 } else if (type >= RES_XML_FIRST_CHUNK_TYPE
1625 && type <= RES_XML_LAST_CHUNK_TYPE) {
1626 if (validateNode((const ResXMLTree_node*)chunk) != NO_ERROR) {
1627 mError = BAD_TYPE;
1628 goto done;
1629 }
1630 mCurNode = (const ResXMLTree_node*)lastChunk;
1631 if (nextNode() == BAD_DOCUMENT) {
1632 mError = BAD_TYPE;
1633 goto done;
1634 }
1635 mRootNode = mCurNode;
1636 mRootExt = mCurExt;
1637 mRootCode = mEventCode;
1638 break;
1639 } else {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001640 if (kDebugXMLNoisy) {
1641 printf("Skipping unknown chunk!\n");
1642 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 }
1644 lastChunk = chunk;
1645 chunk = (const ResChunk_header*)
1646 (((const uint8_t*)chunk) + size);
1647 }
1648
1649 if (mRootNode == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001650 ALOGW("Bad XML block: no root element node found\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 mError = BAD_TYPE;
1652 goto done;
1653 }
1654
1655 mError = mStrings.getError();
1656
1657done:
1658 restart();
1659 return mError;
1660}
1661
1662status_t ResXMLTree::getError() const
1663{
1664 return mError;
1665}
1666
1667void ResXMLTree::uninit()
1668{
1669 mError = NO_INIT;
Kenny Root19138462009-12-04 09:38:48 -08001670 mStrings.uninit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 if (mOwnedData) {
1672 free(mOwnedData);
1673 mOwnedData = NULL;
1674 }
1675 restart();
1676}
1677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678status_t ResXMLTree::validateNode(const ResXMLTree_node* node) const
1679{
1680 const uint16_t eventCode = dtohs(node->header.type);
1681
1682 status_t err = validate_chunk(
1683 &node->header, sizeof(ResXMLTree_node),
1684 mDataEnd, "ResXMLTree_node");
1685
1686 if (err >= NO_ERROR) {
1687 // Only perform additional validation on START nodes
1688 if (eventCode != RES_XML_START_ELEMENT_TYPE) {
1689 return NO_ERROR;
1690 }
1691
1692 const uint16_t headerSize = dtohs(node->header.headerSize);
1693 const uint32_t size = dtohl(node->header.size);
1694 const ResXMLTree_attrExt* attrExt = (const ResXMLTree_attrExt*)
1695 (((const uint8_t*)node) + headerSize);
1696 // check for sensical values pulled out of the stream so far...
1697 if ((size >= headerSize + sizeof(ResXMLTree_attrExt))
1698 && ((void*)attrExt > (void*)node)) {
1699 const size_t attrSize = ((size_t)dtohs(attrExt->attributeSize))
1700 * dtohs(attrExt->attributeCount);
1701 if ((dtohs(attrExt->attributeStart)+attrSize) <= (size-headerSize)) {
1702 return NO_ERROR;
1703 }
Steve Block8564c8d2012-01-05 23:22:43 +00001704 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 -08001705 (unsigned int)(dtohs(attrExt->attributeStart)+attrSize),
1706 (unsigned int)(size-headerSize));
1707 }
1708 else {
Steve Block8564c8d2012-01-05 23:22:43 +00001709 ALOGW("Bad XML start block: node header size 0x%x, size 0x%x\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 (unsigned int)headerSize, (unsigned int)size);
1711 }
1712 return BAD_TYPE;
1713 }
1714
1715 return err;
1716
1717#if 0
1718 const bool isStart = dtohs(node->header.type) == RES_XML_START_ELEMENT_TYPE;
1719
1720 const uint16_t headerSize = dtohs(node->header.headerSize);
1721 const uint32_t size = dtohl(node->header.size);
1722
1723 if (headerSize >= (isStart ? sizeof(ResXMLTree_attrNode) : sizeof(ResXMLTree_node))) {
1724 if (size >= headerSize) {
1725 if (((const uint8_t*)node) <= (mDataEnd-size)) {
1726 if (!isStart) {
1727 return NO_ERROR;
1728 }
1729 if ((((size_t)dtohs(node->attributeSize))*dtohs(node->attributeCount))
1730 <= (size-headerSize)) {
1731 return NO_ERROR;
1732 }
Steve Block8564c8d2012-01-05 23:22:43 +00001733 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 -08001734 ((int)dtohs(node->attributeSize))*dtohs(node->attributeCount),
1735 (int)(size-headerSize));
1736 return BAD_TYPE;
1737 }
Steve Block8564c8d2012-01-05 23:22:43 +00001738 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 -08001739 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)), (int)mSize);
1740 return BAD_TYPE;
1741 }
Steve Block8564c8d2012-01-05 23:22:43 +00001742 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 -08001743 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)),
1744 (int)headerSize, (int)size);
1745 return BAD_TYPE;
1746 }
Steve Block8564c8d2012-01-05 23:22:43 +00001747 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 -08001748 (int)(((const uint8_t*)node)-((const uint8_t*)mHeader)),
1749 (int)headerSize);
1750 return BAD_TYPE;
1751#endif
1752}
1753
1754// --------------------------------------------------------------------
1755// --------------------------------------------------------------------
1756// --------------------------------------------------------------------
1757
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001758void ResTable_config::copyFromDeviceNoSwap(const ResTable_config& o) {
1759 const size_t size = dtohl(o.size);
1760 if (size >= sizeof(ResTable_config)) {
1761 *this = o;
1762 } else {
1763 memcpy(this, &o, size);
1764 memset(((uint8_t*)this)+size, 0, sizeof(ResTable_config)-size);
1765 }
1766}
1767
Narayan Kamath48620f12014-01-20 13:57:11 +00001768/* static */ size_t unpackLanguageOrRegion(const char in[2], const char base,
1769 char out[4]) {
1770 if (in[0] & 0x80) {
1771 // The high bit is "1", which means this is a packed three letter
1772 // language code.
1773
1774 // The smallest 5 bits of the second char are the first alphabet.
1775 const uint8_t first = in[1] & 0x1f;
1776 // The last three bits of the second char and the first two bits
1777 // of the first char are the second alphabet.
1778 const uint8_t second = ((in[1] & 0xe0) >> 5) + ((in[0] & 0x03) << 3);
1779 // Bits 3 to 7 (inclusive) of the first char are the third alphabet.
1780 const uint8_t third = (in[0] & 0x7c) >> 2;
1781
1782 out[0] = first + base;
1783 out[1] = second + base;
1784 out[2] = third + base;
1785 out[3] = 0;
1786
1787 return 3;
1788 }
1789
1790 if (in[0]) {
1791 memcpy(out, in, 2);
1792 memset(out + 2, 0, 2);
1793 return 2;
1794 }
1795
1796 memset(out, 0, 4);
1797 return 0;
1798}
1799
Narayan Kamath788fa412014-01-21 15:32:36 +00001800/* static */ void packLanguageOrRegion(const char* in, const char base,
Narayan Kamath48620f12014-01-20 13:57:11 +00001801 char out[2]) {
Narayan Kamath788fa412014-01-21 15:32:36 +00001802 if (in[2] == 0 || in[2] == '-') {
Narayan Kamath48620f12014-01-20 13:57:11 +00001803 out[0] = in[0];
1804 out[1] = in[1];
1805 } else {
Narayan Kamathb2975912014-06-30 15:59:39 +01001806 uint8_t first = (in[0] - base) & 0x007f;
1807 uint8_t second = (in[1] - base) & 0x007f;
1808 uint8_t third = (in[2] - base) & 0x007f;
Narayan Kamath48620f12014-01-20 13:57:11 +00001809
1810 out[0] = (0x80 | (third << 2) | (second >> 3));
1811 out[1] = ((second << 5) | first);
1812 }
1813}
1814
1815
Narayan Kamath788fa412014-01-21 15:32:36 +00001816void ResTable_config::packLanguage(const char* language) {
Narayan Kamath48620f12014-01-20 13:57:11 +00001817 packLanguageOrRegion(language, 'a', this->language);
1818}
1819
Narayan Kamath788fa412014-01-21 15:32:36 +00001820void ResTable_config::packRegion(const char* region) {
Narayan Kamath48620f12014-01-20 13:57:11 +00001821 packLanguageOrRegion(region, '0', this->country);
1822}
1823
1824size_t ResTable_config::unpackLanguage(char language[4]) const {
1825 return unpackLanguageOrRegion(this->language, 'a', language);
1826}
1827
1828size_t ResTable_config::unpackRegion(char region[4]) const {
1829 return unpackLanguageOrRegion(this->country, '0', region);
1830}
1831
1832
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001833void ResTable_config::copyFromDtoH(const ResTable_config& o) {
1834 copyFromDeviceNoSwap(o);
1835 size = sizeof(ResTable_config);
1836 mcc = dtohs(mcc);
1837 mnc = dtohs(mnc);
1838 density = dtohs(density);
1839 screenWidth = dtohs(screenWidth);
1840 screenHeight = dtohs(screenHeight);
1841 sdkVersion = dtohs(sdkVersion);
1842 minorVersion = dtohs(minorVersion);
1843 smallestScreenWidthDp = dtohs(smallestScreenWidthDp);
1844 screenWidthDp = dtohs(screenWidthDp);
1845 screenHeightDp = dtohs(screenHeightDp);
1846}
1847
1848void ResTable_config::swapHtoD() {
1849 size = htodl(size);
1850 mcc = htods(mcc);
1851 mnc = htods(mnc);
1852 density = htods(density);
1853 screenWidth = htods(screenWidth);
1854 screenHeight = htods(screenHeight);
1855 sdkVersion = htods(sdkVersion);
1856 minorVersion = htods(minorVersion);
1857 smallestScreenWidthDp = htods(smallestScreenWidthDp);
1858 screenWidthDp = htods(screenWidthDp);
1859 screenHeightDp = htods(screenHeightDp);
1860}
1861
Narayan Kamath48620f12014-01-20 13:57:11 +00001862/* static */ inline int compareLocales(const ResTable_config &l, const ResTable_config &r) {
1863 if (l.locale != r.locale) {
1864 // NOTE: This is the old behaviour with respect to comparison orders.
1865 // The diff value here doesn't make much sense (given our bit packing scheme)
1866 // but it's stable, and that's all we need.
1867 return l.locale - r.locale;
1868 }
1869
1870 // The language & region are equal, so compare the scripts and variants.
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08001871 const char emptyScript[sizeof(l.localeScript)] = {'\0', '\0', '\0', '\0'};
1872 const char *lScript = l.localeScriptWasProvided ? l.localeScript : emptyScript;
1873 const char *rScript = r.localeScriptWasProvided ? r.localeScript : emptyScript;
1874 int script = memcmp(lScript, rScript, sizeof(l.localeScript));
Narayan Kamath48620f12014-01-20 13:57:11 +00001875 if (script) {
1876 return script;
1877 }
1878
1879 // The language, region and script are equal, so compare variants.
1880 //
1881 // This should happen very infrequently (if at all.)
1882 return memcmp(l.localeVariant, r.localeVariant, sizeof(l.localeVariant));
1883}
1884
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001885int ResTable_config::compare(const ResTable_config& o) const {
1886 int32_t diff = (int32_t)(imsi - o.imsi);
1887 if (diff != 0) return diff;
Narayan Kamath48620f12014-01-20 13:57:11 +00001888 diff = compareLocales(*this, o);
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001889 if (diff != 0) return diff;
1890 diff = (int32_t)(screenType - o.screenType);
1891 if (diff != 0) return diff;
1892 diff = (int32_t)(input - o.input);
1893 if (diff != 0) return diff;
1894 diff = (int32_t)(screenSize - o.screenSize);
1895 if (diff != 0) return diff;
1896 diff = (int32_t)(version - o.version);
1897 if (diff != 0) return diff;
1898 diff = (int32_t)(screenLayout - o.screenLayout);
1899 if (diff != 0) return diff;
Adam Lesinski2738c962015-05-14 14:25:36 -07001900 diff = (int32_t)(screenLayout2 - o.screenLayout2);
1901 if (diff != 0) return diff;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001902 diff = (int32_t)(uiMode - o.uiMode);
1903 if (diff != 0) return diff;
1904 diff = (int32_t)(smallestScreenWidthDp - o.smallestScreenWidthDp);
1905 if (diff != 0) return diff;
1906 diff = (int32_t)(screenSizeDp - o.screenSizeDp);
1907 return (int)diff;
1908}
1909
1910int ResTable_config::compareLogical(const ResTable_config& o) const {
1911 if (mcc != o.mcc) {
1912 return mcc < o.mcc ? -1 : 1;
1913 }
1914 if (mnc != o.mnc) {
1915 return mnc < o.mnc ? -1 : 1;
1916 }
Narayan Kamath48620f12014-01-20 13:57:11 +00001917
1918 int diff = compareLocales(*this, o);
1919 if (diff < 0) {
1920 return -1;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001921 }
Narayan Kamath48620f12014-01-20 13:57:11 +00001922 if (diff > 0) {
1923 return 1;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001924 }
Narayan Kamath48620f12014-01-20 13:57:11 +00001925
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07001926 if ((screenLayout & MASK_LAYOUTDIR) != (o.screenLayout & MASK_LAYOUTDIR)) {
1927 return (screenLayout & MASK_LAYOUTDIR) < (o.screenLayout & MASK_LAYOUTDIR) ? -1 : 1;
1928 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001929 if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
1930 return smallestScreenWidthDp < o.smallestScreenWidthDp ? -1 : 1;
1931 }
1932 if (screenWidthDp != o.screenWidthDp) {
1933 return screenWidthDp < o.screenWidthDp ? -1 : 1;
1934 }
1935 if (screenHeightDp != o.screenHeightDp) {
1936 return screenHeightDp < o.screenHeightDp ? -1 : 1;
1937 }
1938 if (screenWidth != o.screenWidth) {
1939 return screenWidth < o.screenWidth ? -1 : 1;
1940 }
1941 if (screenHeight != o.screenHeight) {
1942 return screenHeight < o.screenHeight ? -1 : 1;
1943 }
1944 if (density != o.density) {
1945 return density < o.density ? -1 : 1;
1946 }
1947 if (orientation != o.orientation) {
1948 return orientation < o.orientation ? -1 : 1;
1949 }
1950 if (touchscreen != o.touchscreen) {
1951 return touchscreen < o.touchscreen ? -1 : 1;
1952 }
1953 if (input != o.input) {
1954 return input < o.input ? -1 : 1;
1955 }
1956 if (screenLayout != o.screenLayout) {
1957 return screenLayout < o.screenLayout ? -1 : 1;
1958 }
Adam Lesinski2738c962015-05-14 14:25:36 -07001959 if (screenLayout2 != o.screenLayout2) {
1960 return screenLayout2 < o.screenLayout2 ? -1 : 1;
1961 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001962 if (uiMode != o.uiMode) {
1963 return uiMode < o.uiMode ? -1 : 1;
1964 }
1965 if (version != o.version) {
1966 return version < o.version ? -1 : 1;
1967 }
1968 return 0;
1969}
1970
1971int ResTable_config::diff(const ResTable_config& o) const {
1972 int diffs = 0;
1973 if (mcc != o.mcc) diffs |= CONFIG_MCC;
1974 if (mnc != o.mnc) diffs |= CONFIG_MNC;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001975 if (orientation != o.orientation) diffs |= CONFIG_ORIENTATION;
1976 if (density != o.density) diffs |= CONFIG_DENSITY;
1977 if (touchscreen != o.touchscreen) diffs |= CONFIG_TOUCHSCREEN;
1978 if (((inputFlags^o.inputFlags)&(MASK_KEYSHIDDEN|MASK_NAVHIDDEN)) != 0)
1979 diffs |= CONFIG_KEYBOARD_HIDDEN;
1980 if (keyboard != o.keyboard) diffs |= CONFIG_KEYBOARD;
1981 if (navigation != o.navigation) diffs |= CONFIG_NAVIGATION;
1982 if (screenSize != o.screenSize) diffs |= CONFIG_SCREEN_SIZE;
1983 if (version != o.version) diffs |= CONFIG_VERSION;
Fabrice Di Meglio35099352012-12-12 11:52:03 -08001984 if ((screenLayout & MASK_LAYOUTDIR) != (o.screenLayout & MASK_LAYOUTDIR)) diffs |= CONFIG_LAYOUTDIR;
1985 if ((screenLayout & ~MASK_LAYOUTDIR) != (o.screenLayout & ~MASK_LAYOUTDIR)) diffs |= CONFIG_SCREEN_LAYOUT;
Adam Lesinski2738c962015-05-14 14:25:36 -07001986 if ((screenLayout2 & MASK_SCREENROUND) != (o.screenLayout2 & MASK_SCREENROUND)) diffs |= CONFIG_SCREEN_ROUND;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001987 if (uiMode != o.uiMode) diffs |= CONFIG_UI_MODE;
1988 if (smallestScreenWidthDp != o.smallestScreenWidthDp) diffs |= CONFIG_SMALLEST_SCREEN_SIZE;
1989 if (screenSizeDp != o.screenSizeDp) diffs |= CONFIG_SCREEN_SIZE;
Narayan Kamath48620f12014-01-20 13:57:11 +00001990
1991 const int diff = compareLocales(*this, o);
1992 if (diff) diffs |= CONFIG_LOCALE;
1993
Dianne Hackborn6c997a92012-01-31 11:27:43 -08001994 return diffs;
1995}
1996
Narayan Kamath48620f12014-01-20 13:57:11 +00001997int ResTable_config::isLocaleMoreSpecificThan(const ResTable_config& o) const {
1998 if (locale || o.locale) {
1999 if (language[0] != o.language[0]) {
2000 if (!language[0]) return -1;
2001 if (!o.language[0]) return 1;
2002 }
2003
2004 if (country[0] != o.country[0]) {
2005 if (!country[0]) return -1;
2006 if (!o.country[0]) return 1;
2007 }
2008 }
2009
2010 // There isn't a well specified "importance" order between variants and
2011 // scripts. We can't easily tell whether, say "en-Latn-US" is more or less
2012 // specific than "en-US-POSIX".
2013 //
2014 // We therefore arbitrarily decide to give priority to variants over
2015 // scripts since it seems more useful to do so. We will consider
2016 // "en-US-POSIX" to be more specific than "en-Latn-US".
2017
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08002018 const int score = (localeScriptWasProvided ? 1 : 0) +
Narayan Kamath48620f12014-01-20 13:57:11 +00002019 ((localeVariant[0] != 0) ? 2 : 0);
2020
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08002021 const int oScore = (o.localeScriptWasProvided ? 1 : 0) +
Narayan Kamath48620f12014-01-20 13:57:11 +00002022 ((o.localeVariant[0] != 0) ? 2 : 0);
2023
2024 return score - oScore;
2025
2026}
2027
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002028bool ResTable_config::isMoreSpecificThan(const ResTable_config& o) const {
2029 // The order of the following tests defines the importance of one
2030 // configuration parameter over another. Those tests first are more
2031 // important, trumping any values in those following them.
2032 if (imsi || o.imsi) {
2033 if (mcc != o.mcc) {
2034 if (!mcc) return false;
2035 if (!o.mcc) return true;
2036 }
2037
2038 if (mnc != o.mnc) {
2039 if (!mnc) return false;
2040 if (!o.mnc) return true;
2041 }
2042 }
2043
2044 if (locale || o.locale) {
Narayan Kamath48620f12014-01-20 13:57:11 +00002045 const int diff = isLocaleMoreSpecificThan(o);
2046 if (diff < 0) {
2047 return false;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002048 }
2049
Narayan Kamath48620f12014-01-20 13:57:11 +00002050 if (diff > 0) {
2051 return true;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002052 }
2053 }
2054
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07002055 if (screenLayout || o.screenLayout) {
2056 if (((screenLayout^o.screenLayout) & MASK_LAYOUTDIR) != 0) {
2057 if (!(screenLayout & MASK_LAYOUTDIR)) return false;
2058 if (!(o.screenLayout & MASK_LAYOUTDIR)) return true;
2059 }
2060 }
2061
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002062 if (smallestScreenWidthDp || o.smallestScreenWidthDp) {
2063 if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
2064 if (!smallestScreenWidthDp) return false;
2065 if (!o.smallestScreenWidthDp) return true;
2066 }
2067 }
2068
2069 if (screenSizeDp || o.screenSizeDp) {
2070 if (screenWidthDp != o.screenWidthDp) {
2071 if (!screenWidthDp) return false;
2072 if (!o.screenWidthDp) return true;
2073 }
2074
2075 if (screenHeightDp != o.screenHeightDp) {
2076 if (!screenHeightDp) return false;
2077 if (!o.screenHeightDp) return true;
2078 }
2079 }
2080
2081 if (screenLayout || o.screenLayout) {
2082 if (((screenLayout^o.screenLayout) & MASK_SCREENSIZE) != 0) {
2083 if (!(screenLayout & MASK_SCREENSIZE)) return false;
2084 if (!(o.screenLayout & MASK_SCREENSIZE)) return true;
2085 }
2086 if (((screenLayout^o.screenLayout) & MASK_SCREENLONG) != 0) {
2087 if (!(screenLayout & MASK_SCREENLONG)) return false;
2088 if (!(o.screenLayout & MASK_SCREENLONG)) return true;
2089 }
2090 }
2091
Adam Lesinski2738c962015-05-14 14:25:36 -07002092 if (screenLayout2 || o.screenLayout2) {
2093 if (((screenLayout2^o.screenLayout2) & MASK_SCREENROUND) != 0) {
2094 if (!(screenLayout2 & MASK_SCREENROUND)) return false;
2095 if (!(o.screenLayout2 & MASK_SCREENROUND)) return true;
2096 }
2097 }
2098
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002099 if (orientation != o.orientation) {
2100 if (!orientation) return false;
2101 if (!o.orientation) return true;
2102 }
2103
2104 if (uiMode || o.uiMode) {
2105 if (((uiMode^o.uiMode) & MASK_UI_MODE_TYPE) != 0) {
2106 if (!(uiMode & MASK_UI_MODE_TYPE)) return false;
2107 if (!(o.uiMode & MASK_UI_MODE_TYPE)) return true;
2108 }
2109 if (((uiMode^o.uiMode) & MASK_UI_MODE_NIGHT) != 0) {
2110 if (!(uiMode & MASK_UI_MODE_NIGHT)) return false;
2111 if (!(o.uiMode & MASK_UI_MODE_NIGHT)) return true;
2112 }
2113 }
2114
2115 // density is never 'more specific'
2116 // as the default just equals 160
2117
2118 if (touchscreen != o.touchscreen) {
2119 if (!touchscreen) return false;
2120 if (!o.touchscreen) return true;
2121 }
2122
2123 if (input || o.input) {
2124 if (((inputFlags^o.inputFlags) & MASK_KEYSHIDDEN) != 0) {
2125 if (!(inputFlags & MASK_KEYSHIDDEN)) return false;
2126 if (!(o.inputFlags & MASK_KEYSHIDDEN)) return true;
2127 }
2128
2129 if (((inputFlags^o.inputFlags) & MASK_NAVHIDDEN) != 0) {
2130 if (!(inputFlags & MASK_NAVHIDDEN)) return false;
2131 if (!(o.inputFlags & MASK_NAVHIDDEN)) return true;
2132 }
2133
2134 if (keyboard != o.keyboard) {
2135 if (!keyboard) return false;
2136 if (!o.keyboard) return true;
2137 }
2138
2139 if (navigation != o.navigation) {
2140 if (!navigation) return false;
2141 if (!o.navigation) return true;
2142 }
2143 }
2144
2145 if (screenSize || o.screenSize) {
2146 if (screenWidth != o.screenWidth) {
2147 if (!screenWidth) return false;
2148 if (!o.screenWidth) return true;
2149 }
2150
2151 if (screenHeight != o.screenHeight) {
2152 if (!screenHeight) return false;
2153 if (!o.screenHeight) return true;
2154 }
2155 }
2156
2157 if (version || o.version) {
2158 if (sdkVersion != o.sdkVersion) {
2159 if (!sdkVersion) return false;
2160 if (!o.sdkVersion) return true;
2161 }
2162
2163 if (minorVersion != o.minorVersion) {
2164 if (!minorVersion) return false;
2165 if (!o.minorVersion) return true;
2166 }
2167 }
2168 return false;
2169}
2170
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08002171bool ResTable_config::isLocaleBetterThan(const ResTable_config& o,
2172 const ResTable_config* requested) const {
2173 if (requested->locale == 0) {
2174 // The request doesn't have a locale, so no resource is better
2175 // than the other.
2176 return false;
2177 }
2178
2179 if (locale == 0 && o.locale == 0) {
2180 // The locales parts of both resources are empty, so no one is better
2181 // than the other.
2182 return false;
2183 }
2184
2185 // Non-matching locales have been filtered out, so both resources
2186 // match the requested locale.
2187 //
2188 // Because of the locale-related checks in match() and the checks, we know
2189 // that:
2190 // 1) The resource languages are either empty or match the request;
2191 // and
2192 // 2) If the request's script is known, the resource scripts are either
2193 // unknown or match the request.
2194
2195 if (language[0] != o.language[0]) {
2196 // The languages of the two resources are not the same. We can only
2197 // assume that one of the two resources matched the request because one
2198 // doesn't have a language and the other has a matching language.
Roozbeh Pournader27953c32016-02-01 13:49:52 -08002199 //
2200 // We consider the one that has the language specified a better match.
2201 //
2202 // The exception is that we consider no-language resources a better match
2203 // for US English and similar locales than locales that are a descendant
2204 // of Internatinal English (en-001), since no-language resources are
2205 // where the US English resource have traditionally lived for most apps.
2206 if (requested->language[0] == 'e' && requested->language[1] == 'n') {
2207 if (requested->country[0] == 'U' && requested->country[1] == 'S') {
2208 // For US English itself, we consider a no-locale resource a
2209 // better match if the other resource has a country other than
2210 // US specified.
2211 if (language[0] != '\0') {
2212 return country[0] == '\0' || (country[0] == 'U' && country[1] == 'S');
2213 } else {
2214 return !(o.country[0] == '\0' || (o.country[0] == 'U' && o.country[1] == 'S'));
2215 }
2216 } else if (localeDataIsCloseToUsEnglish(requested->country)) {
2217 if (language[0] != '\0') {
2218 return localeDataIsCloseToUsEnglish(country);
2219 } else {
2220 return !localeDataIsCloseToUsEnglish(o.country);
2221 }
2222 }
2223 }
2224 return (language[0] != '\0');
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08002225 }
2226
2227 // If we are here, both the resources have the same non-empty language as
2228 // the request.
2229 //
2230 // Because the languages are the same, computeScript() always
2231 // returns a non-empty script for languages it knows about, and we have passed
2232 // the script checks in match(), the scripts are either all unknown or are
2233 // all the same. So we can't gain anything by checking the scripts. We need
2234 // to check the region and variant.
2235
2236 // See if any of the regions is better than the other
2237 const int region_comparison = localeDataCompareRegions(
2238 country, o.country,
2239 language, localeScript, requested->country);
2240 if (region_comparison != 0) {
2241 return (region_comparison > 0);
2242 }
2243
2244 // The regions are the same. Try the variant.
2245 if (requested->localeVariant[0] != '\0'
2246 && strncmp(localeVariant, requested->localeVariant, sizeof(localeVariant)) == 0) {
2247 return (strncmp(o.localeVariant, requested->localeVariant, sizeof(localeVariant)) != 0);
2248 }
2249
2250 return false;
2251}
2252
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002253bool ResTable_config::isBetterThan(const ResTable_config& o,
2254 const ResTable_config* requested) const {
2255 if (requested) {
2256 if (imsi || o.imsi) {
2257 if ((mcc != o.mcc) && requested->mcc) {
2258 return (mcc);
2259 }
2260
2261 if ((mnc != o.mnc) && requested->mnc) {
2262 return (mnc);
2263 }
2264 }
2265
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08002266 if (isLocaleBetterThan(o, requested)) {
2267 return true;
Narayan Kamath48620f12014-01-20 13:57:11 +00002268 }
2269
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07002270 if (screenLayout || o.screenLayout) {
2271 if (((screenLayout^o.screenLayout) & MASK_LAYOUTDIR) != 0
2272 && (requested->screenLayout & MASK_LAYOUTDIR)) {
2273 int myLayoutDir = screenLayout & MASK_LAYOUTDIR;
2274 int oLayoutDir = o.screenLayout & MASK_LAYOUTDIR;
2275 return (myLayoutDir > oLayoutDir);
2276 }
2277 }
2278
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002279 if (smallestScreenWidthDp || o.smallestScreenWidthDp) {
2280 // The configuration closest to the actual size is best.
2281 // We assume that larger configs have already been filtered
2282 // out at this point. That means we just want the largest one.
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08002283 if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
2284 return smallestScreenWidthDp > o.smallestScreenWidthDp;
2285 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002286 }
2287
2288 if (screenSizeDp || o.screenSizeDp) {
2289 // "Better" is based on the sum of the difference between both
2290 // width and height from the requested dimensions. We are
2291 // assuming the invalid configs (with smaller dimens) have
2292 // already been filtered. Note that if a particular dimension
2293 // is unspecified, we will end up with a large value (the
2294 // difference between 0 and the requested dimension), which is
2295 // good since we will prefer a config that has specified a
2296 // dimension value.
2297 int myDelta = 0, otherDelta = 0;
2298 if (requested->screenWidthDp) {
2299 myDelta += requested->screenWidthDp - screenWidthDp;
2300 otherDelta += requested->screenWidthDp - o.screenWidthDp;
2301 }
2302 if (requested->screenHeightDp) {
2303 myDelta += requested->screenHeightDp - screenHeightDp;
2304 otherDelta += requested->screenHeightDp - o.screenHeightDp;
2305 }
Andreas Gampe2204f0b2014-10-21 23:04:54 -07002306 if (kDebugTableSuperNoisy) {
2307 ALOGI("Comparing this %dx%d to other %dx%d in %dx%d: myDelta=%d otherDelta=%d",
2308 screenWidthDp, screenHeightDp, o.screenWidthDp, o.screenHeightDp,
2309 requested->screenWidthDp, requested->screenHeightDp, myDelta, otherDelta);
2310 }
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08002311 if (myDelta != otherDelta) {
2312 return myDelta < otherDelta;
2313 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002314 }
2315
2316 if (screenLayout || o.screenLayout) {
2317 if (((screenLayout^o.screenLayout) & MASK_SCREENSIZE) != 0
2318 && (requested->screenLayout & MASK_SCREENSIZE)) {
2319 // A little backwards compatibility here: undefined is
2320 // considered equivalent to normal. But only if the
2321 // requested size is at least normal; otherwise, small
2322 // is better than the default.
2323 int mySL = (screenLayout & MASK_SCREENSIZE);
2324 int oSL = (o.screenLayout & MASK_SCREENSIZE);
2325 int fixedMySL = mySL;
2326 int fixedOSL = oSL;
2327 if ((requested->screenLayout & MASK_SCREENSIZE) >= SCREENSIZE_NORMAL) {
2328 if (fixedMySL == 0) fixedMySL = SCREENSIZE_NORMAL;
2329 if (fixedOSL == 0) fixedOSL = SCREENSIZE_NORMAL;
2330 }
2331 // For screen size, the best match is the one that is
2332 // closest to the requested screen size, but not over
2333 // (the not over part is dealt with in match() below).
2334 if (fixedMySL == fixedOSL) {
2335 // If the two are the same, but 'this' is actually
2336 // undefined, then the other is really a better match.
2337 if (mySL == 0) return false;
2338 return true;
2339 }
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08002340 if (fixedMySL != fixedOSL) {
2341 return fixedMySL > fixedOSL;
2342 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002343 }
2344 if (((screenLayout^o.screenLayout) & MASK_SCREENLONG) != 0
2345 && (requested->screenLayout & MASK_SCREENLONG)) {
2346 return (screenLayout & MASK_SCREENLONG);
2347 }
2348 }
2349
Adam Lesinski2738c962015-05-14 14:25:36 -07002350 if (screenLayout2 || o.screenLayout2) {
2351 if (((screenLayout2^o.screenLayout2) & MASK_SCREENROUND) != 0 &&
2352 (requested->screenLayout2 & MASK_SCREENROUND)) {
2353 return screenLayout2 & MASK_SCREENROUND;
2354 }
2355 }
2356
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002357 if ((orientation != o.orientation) && requested->orientation) {
2358 return (orientation);
2359 }
2360
2361 if (uiMode || o.uiMode) {
2362 if (((uiMode^o.uiMode) & MASK_UI_MODE_TYPE) != 0
2363 && (requested->uiMode & MASK_UI_MODE_TYPE)) {
2364 return (uiMode & MASK_UI_MODE_TYPE);
2365 }
2366 if (((uiMode^o.uiMode) & MASK_UI_MODE_NIGHT) != 0
2367 && (requested->uiMode & MASK_UI_MODE_NIGHT)) {
2368 return (uiMode & MASK_UI_MODE_NIGHT);
2369 }
2370 }
2371
2372 if (screenType || o.screenType) {
2373 if (density != o.density) {
Adam Lesinski31245b42014-08-22 19:10:56 -07002374 // Use the system default density (DENSITY_MEDIUM, 160dpi) if none specified.
2375 const int thisDensity = density ? density : int(ResTable_config::DENSITY_MEDIUM);
2376 const int otherDensity = o.density ? o.density : int(ResTable_config::DENSITY_MEDIUM);
2377
2378 // We always prefer DENSITY_ANY over scaling a density bucket.
2379 if (thisDensity == ResTable_config::DENSITY_ANY) {
2380 return true;
2381 } else if (otherDensity == ResTable_config::DENSITY_ANY) {
2382 return false;
2383 }
2384
2385 int requestedDensity = requested->density;
2386 if (requested->density == 0 ||
2387 requested->density == ResTable_config::DENSITY_ANY) {
2388 requestedDensity = ResTable_config::DENSITY_MEDIUM;
2389 }
2390
2391 // DENSITY_ANY is now dealt with. We should look to
2392 // pick a density bucket and potentially scale it.
2393 // Any density is potentially useful
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002394 // because the system will scale it. Scaling down
2395 // is generally better than scaling up.
Adam Lesinski31245b42014-08-22 19:10:56 -07002396 int h = thisDensity;
2397 int l = otherDensity;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002398 bool bImBigger = true;
2399 if (l > h) {
2400 int t = h;
2401 h = l;
2402 l = t;
2403 bImBigger = false;
2404 }
2405
Adam Lesinski31245b42014-08-22 19:10:56 -07002406 if (requestedDensity >= h) {
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002407 // requested value higher than both l and h, give h
2408 return bImBigger;
2409 }
Adam Lesinski31245b42014-08-22 19:10:56 -07002410 if (l >= requestedDensity) {
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002411 // requested value lower than both l and h, give l
2412 return !bImBigger;
2413 }
2414 // saying that scaling down is 2x better than up
Adam Lesinski31245b42014-08-22 19:10:56 -07002415 if (((2 * l) - requestedDensity) * h > requestedDensity * requestedDensity) {
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002416 return !bImBigger;
2417 } else {
2418 return bImBigger;
2419 }
2420 }
2421
2422 if ((touchscreen != o.touchscreen) && requested->touchscreen) {
2423 return (touchscreen);
2424 }
2425 }
2426
2427 if (input || o.input) {
2428 const int keysHidden = inputFlags & MASK_KEYSHIDDEN;
2429 const int oKeysHidden = o.inputFlags & MASK_KEYSHIDDEN;
2430 if (keysHidden != oKeysHidden) {
2431 const int reqKeysHidden =
2432 requested->inputFlags & MASK_KEYSHIDDEN;
2433 if (reqKeysHidden) {
2434
2435 if (!keysHidden) return false;
2436 if (!oKeysHidden) return true;
2437 // For compatibility, we count KEYSHIDDEN_NO as being
2438 // the same as KEYSHIDDEN_SOFT. Here we disambiguate
2439 // these by making an exact match more specific.
2440 if (reqKeysHidden == keysHidden) return true;
2441 if (reqKeysHidden == oKeysHidden) return false;
2442 }
2443 }
2444
2445 const int navHidden = inputFlags & MASK_NAVHIDDEN;
2446 const int oNavHidden = o.inputFlags & MASK_NAVHIDDEN;
2447 if (navHidden != oNavHidden) {
2448 const int reqNavHidden =
2449 requested->inputFlags & MASK_NAVHIDDEN;
2450 if (reqNavHidden) {
2451
2452 if (!navHidden) return false;
2453 if (!oNavHidden) return true;
2454 }
2455 }
2456
2457 if ((keyboard != o.keyboard) && requested->keyboard) {
2458 return (keyboard);
2459 }
2460
2461 if ((navigation != o.navigation) && requested->navigation) {
2462 return (navigation);
2463 }
2464 }
2465
2466 if (screenSize || o.screenSize) {
2467 // "Better" is based on the sum of the difference between both
2468 // width and height from the requested dimensions. We are
2469 // assuming the invalid configs (with smaller sizes) have
2470 // already been filtered. Note that if a particular dimension
2471 // is unspecified, we will end up with a large value (the
2472 // difference between 0 and the requested dimension), which is
2473 // good since we will prefer a config that has specified a
2474 // size value.
2475 int myDelta = 0, otherDelta = 0;
2476 if (requested->screenWidth) {
2477 myDelta += requested->screenWidth - screenWidth;
2478 otherDelta += requested->screenWidth - o.screenWidth;
2479 }
2480 if (requested->screenHeight) {
2481 myDelta += requested->screenHeight - screenHeight;
2482 otherDelta += requested->screenHeight - o.screenHeight;
2483 }
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08002484 if (myDelta != otherDelta) {
2485 return myDelta < otherDelta;
2486 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002487 }
2488
2489 if (version || o.version) {
2490 if ((sdkVersion != o.sdkVersion) && requested->sdkVersion) {
2491 return (sdkVersion > o.sdkVersion);
2492 }
2493
2494 if ((minorVersion != o.minorVersion) &&
2495 requested->minorVersion) {
2496 return (minorVersion);
2497 }
2498 }
2499
2500 return false;
2501 }
2502 return isMoreSpecificThan(o);
2503}
2504
2505bool ResTable_config::match(const ResTable_config& settings) const {
2506 if (imsi != 0) {
2507 if (mcc != 0 && mcc != settings.mcc) {
2508 return false;
2509 }
2510 if (mnc != 0 && mnc != settings.mnc) {
2511 return false;
2512 }
2513 }
2514 if (locale != 0) {
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08002515 // Don't consider country and variants when deciding matches.
2516 // (Theoretically, the variant can also affect the script. For
2517 // example, "ar-alalc97" probably implies the Latin script, but since
2518 // CLDR doesn't support getting likely scripts for that, we'll assume
2519 // the variant doesn't change the script.)
Narayan Kamath48620f12014-01-20 13:57:11 +00002520 //
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08002521 // If two configs differ only in their country and variant,
2522 // they can be weeded out in the isMoreSpecificThan test.
2523 if (language[0] != settings.language[0] || language[1] != settings.language[1]) {
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002524 return false;
2525 }
Narayan Kamath48620f12014-01-20 13:57:11 +00002526
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08002527 // For backward compatibility and supporting private-use locales, we
2528 // fall back to old behavior if we couldn't determine the script for
2529 // either of the desired locale or the provided locale.
2530 if (localeScript[0] == '\0' || localeScript[1] == '\0') {
2531 if (country[0] != '\0'
2532 && (country[0] != settings.country[0]
2533 || country[1] != settings.country[1])) {
2534 return false;
2535 }
2536 } else {
2537 // But if we could determine the scripts, they should be the same
2538 // for the locales to match.
2539 if (memcmp(localeScript, settings.localeScript, sizeof(localeScript)) != 0) {
2540 return false;
2541 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002542 }
2543 }
Narayan Kamath48620f12014-01-20 13:57:11 +00002544
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002545 if (screenConfig != 0) {
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07002546 const int layoutDir = screenLayout&MASK_LAYOUTDIR;
2547 const int setLayoutDir = settings.screenLayout&MASK_LAYOUTDIR;
2548 if (layoutDir != 0 && layoutDir != setLayoutDir) {
2549 return false;
2550 }
2551
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002552 const int screenSize = screenLayout&MASK_SCREENSIZE;
2553 const int setScreenSize = settings.screenLayout&MASK_SCREENSIZE;
2554 // Any screen sizes for larger screens than the setting do not
2555 // match.
2556 if (screenSize != 0 && screenSize > setScreenSize) {
2557 return false;
2558 }
2559
2560 const int screenLong = screenLayout&MASK_SCREENLONG;
2561 const int setScreenLong = settings.screenLayout&MASK_SCREENLONG;
2562 if (screenLong != 0 && screenLong != setScreenLong) {
2563 return false;
2564 }
2565
2566 const int uiModeType = uiMode&MASK_UI_MODE_TYPE;
2567 const int setUiModeType = settings.uiMode&MASK_UI_MODE_TYPE;
2568 if (uiModeType != 0 && uiModeType != setUiModeType) {
2569 return false;
2570 }
2571
2572 const int uiModeNight = uiMode&MASK_UI_MODE_NIGHT;
2573 const int setUiModeNight = settings.uiMode&MASK_UI_MODE_NIGHT;
2574 if (uiModeNight != 0 && uiModeNight != setUiModeNight) {
2575 return false;
2576 }
2577
2578 if (smallestScreenWidthDp != 0
2579 && smallestScreenWidthDp > settings.smallestScreenWidthDp) {
2580 return false;
2581 }
2582 }
Adam Lesinski2738c962015-05-14 14:25:36 -07002583
2584 if (screenConfig2 != 0) {
2585 const int screenRound = screenLayout2 & MASK_SCREENROUND;
2586 const int setScreenRound = settings.screenLayout2 & MASK_SCREENROUND;
2587 if (screenRound != 0 && screenRound != setScreenRound) {
2588 return false;
2589 }
2590 }
2591
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002592 if (screenSizeDp != 0) {
2593 if (screenWidthDp != 0 && screenWidthDp > settings.screenWidthDp) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07002594 if (kDebugTableSuperNoisy) {
2595 ALOGI("Filtering out width %d in requested %d", screenWidthDp,
2596 settings.screenWidthDp);
2597 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002598 return false;
2599 }
2600 if (screenHeightDp != 0 && screenHeightDp > settings.screenHeightDp) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07002601 if (kDebugTableSuperNoisy) {
2602 ALOGI("Filtering out height %d in requested %d", screenHeightDp,
2603 settings.screenHeightDp);
2604 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002605 return false;
2606 }
2607 }
2608 if (screenType != 0) {
2609 if (orientation != 0 && orientation != settings.orientation) {
2610 return false;
2611 }
2612 // density always matches - we can scale it. See isBetterThan
2613 if (touchscreen != 0 && touchscreen != settings.touchscreen) {
2614 return false;
2615 }
2616 }
2617 if (input != 0) {
2618 const int keysHidden = inputFlags&MASK_KEYSHIDDEN;
2619 const int setKeysHidden = settings.inputFlags&MASK_KEYSHIDDEN;
2620 if (keysHidden != 0 && keysHidden != setKeysHidden) {
2621 // For compatibility, we count a request for KEYSHIDDEN_NO as also
2622 // matching the more recent KEYSHIDDEN_SOFT. Basically
2623 // KEYSHIDDEN_NO means there is some kind of keyboard available.
Andreas Gampe2204f0b2014-10-21 23:04:54 -07002624 if (kDebugTableSuperNoisy) {
2625 ALOGI("Matching keysHidden: have=%d, config=%d\n", keysHidden, setKeysHidden);
2626 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002627 if (keysHidden != KEYSHIDDEN_NO || setKeysHidden != KEYSHIDDEN_SOFT) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07002628 if (kDebugTableSuperNoisy) {
2629 ALOGI("No match!");
2630 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002631 return false;
2632 }
2633 }
2634 const int navHidden = inputFlags&MASK_NAVHIDDEN;
2635 const int setNavHidden = settings.inputFlags&MASK_NAVHIDDEN;
2636 if (navHidden != 0 && navHidden != setNavHidden) {
2637 return false;
2638 }
2639 if (keyboard != 0 && keyboard != settings.keyboard) {
2640 return false;
2641 }
2642 if (navigation != 0 && navigation != settings.navigation) {
2643 return false;
2644 }
2645 }
2646 if (screenSize != 0) {
2647 if (screenWidth != 0 && screenWidth > settings.screenWidth) {
2648 return false;
2649 }
2650 if (screenHeight != 0 && screenHeight > settings.screenHeight) {
2651 return false;
2652 }
2653 }
2654 if (version != 0) {
2655 if (sdkVersion != 0 && sdkVersion > settings.sdkVersion) {
2656 return false;
2657 }
2658 if (minorVersion != 0 && minorVersion != settings.minorVersion) {
2659 return false;
2660 }
2661 }
2662 return true;
2663}
2664
Adam Lesinski8a9355a2015-03-10 16:55:43 -07002665void ResTable_config::appendDirLocale(String8& out) const {
2666 if (!language[0]) {
2667 return;
2668 }
2669
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08002670 if (!localeScriptWasProvided && !localeVariant[0]) {
Adam Lesinski8a9355a2015-03-10 16:55:43 -07002671 // Legacy format.
2672 if (out.size() > 0) {
2673 out.append("-");
2674 }
2675
2676 char buf[4];
2677 size_t len = unpackLanguage(buf);
2678 out.append(buf, len);
2679
2680 if (country[0]) {
2681 out.append("-r");
2682 len = unpackRegion(buf);
2683 out.append(buf, len);
2684 }
2685 return;
2686 }
2687
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08002688 // We are writing the modified BCP 47 tag.
Adam Lesinski8a9355a2015-03-10 16:55:43 -07002689 // It starts with 'b+' and uses '+' as a separator.
2690
2691 if (out.size() > 0) {
2692 out.append("-");
2693 }
2694 out.append("b+");
2695
2696 char buf[4];
2697 size_t len = unpackLanguage(buf);
2698 out.append(buf, len);
2699
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08002700 if (localeScriptWasProvided) {
Adam Lesinski8a9355a2015-03-10 16:55:43 -07002701 out.append("+");
2702 out.append(localeScript, sizeof(localeScript));
2703 }
2704
2705 if (country[0]) {
2706 out.append("+");
2707 len = unpackRegion(buf);
2708 out.append(buf, len);
2709 }
2710
2711 if (localeVariant[0]) {
2712 out.append("+");
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08002713 out.append(localeVariant, strnlen(localeVariant, sizeof(localeVariant)));
Adam Lesinski8a9355a2015-03-10 16:55:43 -07002714 }
2715}
2716
Narayan Kamath788fa412014-01-21 15:32:36 +00002717void ResTable_config::getBcp47Locale(char str[RESTABLE_MAX_LOCALE_LEN]) const {
Narayan Kamath48620f12014-01-20 13:57:11 +00002718 memset(str, 0, RESTABLE_MAX_LOCALE_LEN);
2719
2720 // This represents the "any" locale value, which has traditionally been
2721 // represented by the empty string.
2722 if (!language[0] && !country[0]) {
2723 return;
2724 }
2725
2726 size_t charsWritten = 0;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002727 if (language[0]) {
Narayan Kamath788fa412014-01-21 15:32:36 +00002728 charsWritten += unpackLanguage(str);
Narayan Kamath48620f12014-01-20 13:57:11 +00002729 }
2730
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08002731 if (localeScriptWasProvided) {
Narayan Kamath48620f12014-01-20 13:57:11 +00002732 if (charsWritten) {
Narayan Kamath788fa412014-01-21 15:32:36 +00002733 str[charsWritten++] = '-';
Narayan Kamath48620f12014-01-20 13:57:11 +00002734 }
2735 memcpy(str + charsWritten, localeScript, sizeof(localeScript));
Narayan Kamath788fa412014-01-21 15:32:36 +00002736 charsWritten += sizeof(localeScript);
2737 }
2738
2739 if (country[0]) {
2740 if (charsWritten) {
2741 str[charsWritten++] = '-';
2742 }
2743 charsWritten += unpackRegion(str + charsWritten);
Narayan Kamath48620f12014-01-20 13:57:11 +00002744 }
2745
2746 if (localeVariant[0]) {
2747 if (charsWritten) {
Narayan Kamath788fa412014-01-21 15:32:36 +00002748 str[charsWritten++] = '-';
Narayan Kamath48620f12014-01-20 13:57:11 +00002749 }
2750 memcpy(str + charsWritten, localeVariant, sizeof(localeVariant));
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002751 }
2752}
2753
Narayan Kamath788fa412014-01-21 15:32:36 +00002754/* static */ inline bool assignLocaleComponent(ResTable_config* config,
2755 const char* start, size_t size) {
2756
2757 switch (size) {
2758 case 0:
2759 return false;
2760 case 2:
2761 case 3:
2762 config->language[0] ? config->packRegion(start) : config->packLanguage(start);
2763 break;
2764 case 4:
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08002765 if ('0' <= start[0] && start[0] <= '9') {
2766 // this is a variant, so fall through
2767 } else {
2768 config->localeScript[0] = toupper(start[0]);
2769 for (size_t i = 1; i < 4; ++i) {
2770 config->localeScript[i] = tolower(start[i]);
2771 }
2772 config->localeScriptWasProvided = true;
2773 break;
Narayan Kamath788fa412014-01-21 15:32:36 +00002774 }
Narayan Kamath788fa412014-01-21 15:32:36 +00002775 case 5:
2776 case 6:
2777 case 7:
2778 case 8:
2779 for (size_t i = 0; i < size; ++i) {
2780 config->localeVariant[i] = tolower(start[i]);
2781 }
2782 break;
2783 default:
2784 return false;
2785 }
2786
2787 return true;
2788}
2789
2790void ResTable_config::setBcp47Locale(const char* in) {
2791 locale = 0;
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08002792 localeScriptWasProvided = false;
Narayan Kamath788fa412014-01-21 15:32:36 +00002793 memset(localeScript, 0, sizeof(localeScript));
2794 memset(localeVariant, 0, sizeof(localeVariant));
2795
2796 const char* separator = in;
2797 const char* start = in;
2798 while ((separator = strchr(start, '-')) != NULL) {
2799 const size_t size = separator - start;
2800 if (!assignLocaleComponent(this, start, size)) {
2801 fprintf(stderr, "Invalid BCP-47 locale string: %s", in);
2802 }
2803
2804 start = (separator + 1);
2805 }
2806
2807 const size_t size = in + strlen(in) - start;
2808 assignLocaleComponent(this, start, size);
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08002809 if (localeScript[0] == '\0') {
2810 computeScript();
2811 };
Narayan Kamath788fa412014-01-21 15:32:36 +00002812}
2813
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002814String8 ResTable_config::toString() const {
2815 String8 res;
2816
2817 if (mcc != 0) {
2818 if (res.size() > 0) res.append("-");
Adam Lesinskifab50872014-04-16 14:40:42 -07002819 res.appendFormat("mcc%d", dtohs(mcc));
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002820 }
2821 if (mnc != 0) {
2822 if (res.size() > 0) res.append("-");
Adam Lesinskifab50872014-04-16 14:40:42 -07002823 res.appendFormat("mnc%d", dtohs(mnc));
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002824 }
Adam Lesinskifab50872014-04-16 14:40:42 -07002825
Adam Lesinski8a9355a2015-03-10 16:55:43 -07002826 appendDirLocale(res);
Narayan Kamath48620f12014-01-20 13:57:11 +00002827
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07002828 if ((screenLayout&MASK_LAYOUTDIR) != 0) {
2829 if (res.size() > 0) res.append("-");
2830 switch (screenLayout&ResTable_config::MASK_LAYOUTDIR) {
2831 case ResTable_config::LAYOUTDIR_LTR:
Fabrice Di Meglio8a802db2012-09-05 13:12:02 -07002832 res.append("ldltr");
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07002833 break;
2834 case ResTable_config::LAYOUTDIR_RTL:
Fabrice Di Meglio8a802db2012-09-05 13:12:02 -07002835 res.append("ldrtl");
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07002836 break;
2837 default:
2838 res.appendFormat("layoutDir=%d",
2839 dtohs(screenLayout&ResTable_config::MASK_LAYOUTDIR));
2840 break;
2841 }
2842 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002843 if (smallestScreenWidthDp != 0) {
2844 if (res.size() > 0) res.append("-");
2845 res.appendFormat("sw%ddp", dtohs(smallestScreenWidthDp));
2846 }
2847 if (screenWidthDp != 0) {
2848 if (res.size() > 0) res.append("-");
2849 res.appendFormat("w%ddp", dtohs(screenWidthDp));
2850 }
2851 if (screenHeightDp != 0) {
2852 if (res.size() > 0) res.append("-");
2853 res.appendFormat("h%ddp", dtohs(screenHeightDp));
2854 }
2855 if ((screenLayout&MASK_SCREENSIZE) != SCREENSIZE_ANY) {
2856 if (res.size() > 0) res.append("-");
2857 switch (screenLayout&ResTable_config::MASK_SCREENSIZE) {
2858 case ResTable_config::SCREENSIZE_SMALL:
2859 res.append("small");
2860 break;
2861 case ResTable_config::SCREENSIZE_NORMAL:
2862 res.append("normal");
2863 break;
2864 case ResTable_config::SCREENSIZE_LARGE:
2865 res.append("large");
2866 break;
2867 case ResTable_config::SCREENSIZE_XLARGE:
2868 res.append("xlarge");
2869 break;
2870 default:
2871 res.appendFormat("screenLayoutSize=%d",
2872 dtohs(screenLayout&ResTable_config::MASK_SCREENSIZE));
2873 break;
2874 }
2875 }
2876 if ((screenLayout&MASK_SCREENLONG) != 0) {
2877 if (res.size() > 0) res.append("-");
2878 switch (screenLayout&ResTable_config::MASK_SCREENLONG) {
2879 case ResTable_config::SCREENLONG_NO:
2880 res.append("notlong");
2881 break;
2882 case ResTable_config::SCREENLONG_YES:
2883 res.append("long");
2884 break;
2885 default:
2886 res.appendFormat("screenLayoutLong=%d",
2887 dtohs(screenLayout&ResTable_config::MASK_SCREENLONG));
2888 break;
2889 }
2890 }
Adam Lesinski2738c962015-05-14 14:25:36 -07002891 if ((screenLayout2&MASK_SCREENROUND) != 0) {
2892 if (res.size() > 0) res.append("-");
2893 switch (screenLayout2&MASK_SCREENROUND) {
2894 case SCREENROUND_NO:
2895 res.append("notround");
2896 break;
2897 case SCREENROUND_YES:
2898 res.append("round");
2899 break;
2900 default:
2901 res.appendFormat("screenRound=%d", dtohs(screenLayout2&MASK_SCREENROUND));
2902 break;
2903 }
2904 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002905 if (orientation != ORIENTATION_ANY) {
2906 if (res.size() > 0) res.append("-");
2907 switch (orientation) {
2908 case ResTable_config::ORIENTATION_PORT:
2909 res.append("port");
2910 break;
2911 case ResTable_config::ORIENTATION_LAND:
2912 res.append("land");
2913 break;
2914 case ResTable_config::ORIENTATION_SQUARE:
2915 res.append("square");
2916 break;
2917 default:
2918 res.appendFormat("orientation=%d", dtohs(orientation));
2919 break;
2920 }
2921 }
2922 if ((uiMode&MASK_UI_MODE_TYPE) != UI_MODE_TYPE_ANY) {
2923 if (res.size() > 0) res.append("-");
2924 switch (uiMode&ResTable_config::MASK_UI_MODE_TYPE) {
2925 case ResTable_config::UI_MODE_TYPE_DESK:
2926 res.append("desk");
2927 break;
2928 case ResTable_config::UI_MODE_TYPE_CAR:
2929 res.append("car");
2930 break;
2931 case ResTable_config::UI_MODE_TYPE_TELEVISION:
2932 res.append("television");
2933 break;
2934 case ResTable_config::UI_MODE_TYPE_APPLIANCE:
2935 res.append("appliance");
2936 break;
John Spurlock6c191292014-04-03 16:37:27 -04002937 case ResTable_config::UI_MODE_TYPE_WATCH:
2938 res.append("watch");
2939 break;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002940 default:
2941 res.appendFormat("uiModeType=%d",
2942 dtohs(screenLayout&ResTable_config::MASK_UI_MODE_TYPE));
2943 break;
2944 }
2945 }
2946 if ((uiMode&MASK_UI_MODE_NIGHT) != 0) {
2947 if (res.size() > 0) res.append("-");
2948 switch (uiMode&ResTable_config::MASK_UI_MODE_NIGHT) {
2949 case ResTable_config::UI_MODE_NIGHT_NO:
2950 res.append("notnight");
2951 break;
2952 case ResTable_config::UI_MODE_NIGHT_YES:
2953 res.append("night");
2954 break;
2955 default:
2956 res.appendFormat("uiModeNight=%d",
2957 dtohs(uiMode&MASK_UI_MODE_NIGHT));
2958 break;
2959 }
2960 }
2961 if (density != DENSITY_DEFAULT) {
2962 if (res.size() > 0) res.append("-");
2963 switch (density) {
2964 case ResTable_config::DENSITY_LOW:
2965 res.append("ldpi");
2966 break;
2967 case ResTable_config::DENSITY_MEDIUM:
2968 res.append("mdpi");
2969 break;
2970 case ResTable_config::DENSITY_TV:
2971 res.append("tvdpi");
2972 break;
2973 case ResTable_config::DENSITY_HIGH:
2974 res.append("hdpi");
2975 break;
2976 case ResTable_config::DENSITY_XHIGH:
2977 res.append("xhdpi");
2978 break;
2979 case ResTable_config::DENSITY_XXHIGH:
2980 res.append("xxhdpi");
2981 break;
Adam Lesinski8d5667d2014-08-13 21:02:57 -07002982 case ResTable_config::DENSITY_XXXHIGH:
2983 res.append("xxxhdpi");
2984 break;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002985 case ResTable_config::DENSITY_NONE:
2986 res.append("nodpi");
2987 break;
Adam Lesinski31245b42014-08-22 19:10:56 -07002988 case ResTable_config::DENSITY_ANY:
2989 res.append("anydpi");
2990 break;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002991 default:
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08002992 res.appendFormat("%ddpi", dtohs(density));
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002993 break;
2994 }
2995 }
2996 if (touchscreen != TOUCHSCREEN_ANY) {
2997 if (res.size() > 0) res.append("-");
2998 switch (touchscreen) {
2999 case ResTable_config::TOUCHSCREEN_NOTOUCH:
3000 res.append("notouch");
3001 break;
3002 case ResTable_config::TOUCHSCREEN_FINGER:
3003 res.append("finger");
3004 break;
3005 case ResTable_config::TOUCHSCREEN_STYLUS:
3006 res.append("stylus");
3007 break;
3008 default:
3009 res.appendFormat("touchscreen=%d", dtohs(touchscreen));
3010 break;
3011 }
3012 }
Adam Lesinskifab50872014-04-16 14:40:42 -07003013 if ((inputFlags&MASK_KEYSHIDDEN) != 0) {
3014 if (res.size() > 0) res.append("-");
3015 switch (inputFlags&MASK_KEYSHIDDEN) {
3016 case ResTable_config::KEYSHIDDEN_NO:
3017 res.append("keysexposed");
3018 break;
3019 case ResTable_config::KEYSHIDDEN_YES:
3020 res.append("keyshidden");
3021 break;
3022 case ResTable_config::KEYSHIDDEN_SOFT:
3023 res.append("keyssoft");
3024 break;
3025 }
3026 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08003027 if (keyboard != KEYBOARD_ANY) {
3028 if (res.size() > 0) res.append("-");
3029 switch (keyboard) {
3030 case ResTable_config::KEYBOARD_NOKEYS:
3031 res.append("nokeys");
3032 break;
3033 case ResTable_config::KEYBOARD_QWERTY:
3034 res.append("qwerty");
3035 break;
3036 case ResTable_config::KEYBOARD_12KEY:
3037 res.append("12key");
3038 break;
3039 default:
3040 res.appendFormat("keyboard=%d", dtohs(keyboard));
3041 break;
3042 }
3043 }
Adam Lesinskifab50872014-04-16 14:40:42 -07003044 if ((inputFlags&MASK_NAVHIDDEN) != 0) {
Dianne Hackborn6c997a92012-01-31 11:27:43 -08003045 if (res.size() > 0) res.append("-");
Adam Lesinskifab50872014-04-16 14:40:42 -07003046 switch (inputFlags&MASK_NAVHIDDEN) {
3047 case ResTable_config::NAVHIDDEN_NO:
3048 res.append("navexposed");
Dianne Hackborn6c997a92012-01-31 11:27:43 -08003049 break;
Adam Lesinskifab50872014-04-16 14:40:42 -07003050 case ResTable_config::NAVHIDDEN_YES:
3051 res.append("navhidden");
Dianne Hackborn6c997a92012-01-31 11:27:43 -08003052 break;
Adam Lesinskifab50872014-04-16 14:40:42 -07003053 default:
3054 res.appendFormat("inputFlagsNavHidden=%d",
3055 dtohs(inputFlags&MASK_NAVHIDDEN));
Dianne Hackborn6c997a92012-01-31 11:27:43 -08003056 break;
3057 }
3058 }
3059 if (navigation != NAVIGATION_ANY) {
3060 if (res.size() > 0) res.append("-");
3061 switch (navigation) {
3062 case ResTable_config::NAVIGATION_NONAV:
3063 res.append("nonav");
3064 break;
3065 case ResTable_config::NAVIGATION_DPAD:
3066 res.append("dpad");
3067 break;
3068 case ResTable_config::NAVIGATION_TRACKBALL:
3069 res.append("trackball");
3070 break;
3071 case ResTable_config::NAVIGATION_WHEEL:
3072 res.append("wheel");
3073 break;
3074 default:
3075 res.appendFormat("navigation=%d", dtohs(navigation));
3076 break;
3077 }
3078 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08003079 if (screenSize != 0) {
3080 if (res.size() > 0) res.append("-");
3081 res.appendFormat("%dx%d", dtohs(screenWidth), dtohs(screenHeight));
3082 }
3083 if (version != 0) {
3084 if (res.size() > 0) res.append("-");
3085 res.appendFormat("v%d", dtohs(sdkVersion));
3086 if (minorVersion != 0) {
3087 res.appendFormat(".%d", dtohs(minorVersion));
3088 }
3089 }
3090
3091 return res;
3092}
3093
3094// --------------------------------------------------------------------
3095// --------------------------------------------------------------------
3096// --------------------------------------------------------------------
3097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003098struct ResTable::Header
3099{
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01003100 Header(ResTable* _owner) : owner(_owner), ownedData(NULL), header(NULL),
3101 resourceIDMap(NULL), resourceIDMapSize(0) { }
3102
3103 ~Header()
3104 {
3105 free(resourceIDMap);
3106 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003107
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003108 const ResTable* const owner;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003109 void* ownedData;
3110 const ResTable_header* header;
3111 size_t size;
3112 const uint8_t* dataEnd;
3113 size_t index;
Narayan Kamath7c4887f2014-01-27 17:32:37 +00003114 int32_t cookie;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003115
3116 ResStringPool values;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01003117 uint32_t* resourceIDMap;
3118 size_t resourceIDMapSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003119};
3120
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003121struct ResTable::Entry {
3122 ResTable_config config;
3123 const ResTable_entry* entry;
3124 const ResTable_type* type;
3125 uint32_t specFlags;
3126 const Package* package;
3127
3128 StringPoolRef typeStr;
3129 StringPoolRef keyStr;
3130};
3131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003132struct ResTable::Type
3133{
3134 Type(const Header* _header, const Package* _package, size_t count)
3135 : header(_header), package(_package), entryCount(count),
3136 typeSpec(NULL), typeSpecFlags(NULL) { }
3137 const Header* const header;
3138 const Package* const package;
3139 const size_t entryCount;
3140 const ResTable_typeSpec* typeSpec;
3141 const uint32_t* typeSpecFlags;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003142 IdmapEntries idmapEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003143 Vector<const ResTable_type*> configs;
3144};
3145
3146struct ResTable::Package
3147{
Dianne Hackborn78c40512009-07-06 11:07:40 -07003148 Package(ResTable* _owner, const Header* _header, const ResTable_package* _package)
Adam Lesinski18560882014-08-15 17:18:21 +00003149 : owner(_owner), header(_header), package(_package), typeIdOffset(0) {
3150 if (dtohs(package->header.headerSize) == sizeof(package)) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003151 // The package structure is the same size as the definition.
3152 // This means it contains the typeIdOffset field.
Adam Lesinski18560882014-08-15 17:18:21 +00003153 typeIdOffset = package->typeIdOffset;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003154 }
3155 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07003156
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003157 const ResTable* const owner;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003158 const Header* const header;
Adam Lesinski18560882014-08-15 17:18:21 +00003159 const ResTable_package* const package;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003160
Dianne Hackborn78c40512009-07-06 11:07:40 -07003161 ResStringPool typeStrings;
3162 ResStringPool keyStrings;
Mark Salyzyn00adb862014-03-19 11:00:06 -07003163
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003164 size_t typeIdOffset;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003165};
3166
3167// A group of objects describing a particular resource package.
3168// The first in 'package' is always the root object (from the resource
3169// table that defined the package); the ones after are skins on top of it.
3170struct ResTable::PackageGroup
3171{
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08003172 PackageGroup(
3173 ResTable* _owner, const String16& _name, uint32_t _id,
3174 bool appAsLib, bool _isSystemAsset)
Adam Lesinskide898ff2014-01-29 18:20:45 -08003175 : owner(_owner)
3176 , name(_name)
3177 , id(_id)
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003178 , largestTypeId(0)
Adam Lesinskide898ff2014-01-29 18:20:45 -08003179 , bags(NULL)
Tao Baia6d7e3f2015-09-01 18:49:54 -07003180 , dynamicRefTable(static_cast<uint8_t>(_id), appAsLib)
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08003181 , isSystemAsset(_isSystemAsset)
Adam Lesinskide898ff2014-01-29 18:20:45 -08003182 { }
3183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003184 ~PackageGroup() {
3185 clearBagCache();
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003186 const size_t numTypes = types.size();
3187 for (size_t i = 0; i < numTypes; i++) {
3188 const TypeList& typeList = types[i];
3189 const size_t numInnerTypes = typeList.size();
3190 for (size_t j = 0; j < numInnerTypes; j++) {
3191 if (typeList[j]->package->owner == owner) {
3192 delete typeList[j];
3193 }
3194 }
3195 }
3196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003197 const size_t N = packages.size();
3198 for (size_t i=0; i<N; i++) {
Dianne Hackborn78c40512009-07-06 11:07:40 -07003199 Package* pkg = packages[i];
3200 if (pkg->owner == owner) {
3201 delete pkg;
3202 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003203 }
3204 }
3205
3206 void clearBagCache() {
3207 if (bags) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003208 if (kDebugTableNoisy) {
3209 printf("bags=%p\n", bags);
3210 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003211 for (size_t i = 0; i < bags->size(); i++) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003212 if (kDebugTableNoisy) {
3213 printf("type=%zu\n", i);
3214 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003215 const TypeList& typeList = types[i];
Adam Lesinski7f668d02014-08-28 18:32:32 -07003216 if (!typeList.isEmpty()) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003217 bag_set** typeBags = bags->get(i);
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003218 if (kDebugTableNoisy) {
3219 printf("typeBags=%p\n", typeBags);
3220 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003221 if (typeBags) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003222 const size_t N = typeList[0]->entryCount;
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003223 if (kDebugTableNoisy) {
3224 printf("type->entryCount=%zu\n", N);
3225 }
3226 for (size_t j = 0; j < N; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003227 if (typeBags[j] && typeBags[j] != (bag_set*)0xFFFFFFFF)
3228 free(typeBags[j]);
3229 }
3230 free(typeBags);
3231 }
3232 }
3233 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003234 delete bags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003235 bags = NULL;
3236 }
3237 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07003238
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003239 ssize_t findType16(const char16_t* type, size_t len) const {
3240 const size_t N = packages.size();
3241 for (size_t i = 0; i < N; i++) {
3242 ssize_t index = packages[i]->typeStrings.indexOfString(type, len);
3243 if (index >= 0) {
3244 return index + packages[i]->typeIdOffset;
3245 }
3246 }
3247 return -1;
3248 }
3249
3250 const ResTable* const owner;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003251 String16 const name;
3252 uint32_t const id;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003253
3254 // This is mainly used to keep track of the loaded packages
3255 // and to clean them up properly. Accessing resources happens from
3256 // the 'types' array.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003257 Vector<Package*> packages;
Mark Salyzyn00adb862014-03-19 11:00:06 -07003258
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003259 ByteBucketArray<TypeList> types;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003260
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003261 uint8_t largestTypeId;
Mark Salyzyn00adb862014-03-19 11:00:06 -07003262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003263 // Computed attribute bags, first indexed by the type and second
3264 // by the entry in that type.
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003265 ByteBucketArray<bag_set**>* bags;
Adam Lesinskide898ff2014-01-29 18:20:45 -08003266
3267 // The table mapping dynamic references to resolved references for
3268 // this package group.
3269 // TODO: We may be able to support dynamic references in overlays
3270 // by having these tables in a per-package scope rather than
3271 // per-package-group.
3272 DynamicRefTable dynamicRefTable;
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08003273
3274 // If the package group comes from a system asset. Used in
3275 // determining non-system locales.
3276 const bool isSystemAsset;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003277};
3278
3279struct ResTable::bag_set
3280{
3281 size_t numAttrs; // number in array
3282 size_t availAttrs; // total space in array
3283 uint32_t typeSpecFlags;
3284 // Followed by 'numAttr' bag_entry structures.
3285};
3286
3287ResTable::Theme::Theme(const ResTable& table)
3288 : mTable(table)
Alan Viverettec1d52792015-05-05 09:49:03 -07003289 , mTypeSpecFlags(0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003290{
3291 memset(mPackages, 0, sizeof(mPackages));
3292}
3293
3294ResTable::Theme::~Theme()
3295{
3296 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3297 package_info* pi = mPackages[i];
3298 if (pi != NULL) {
3299 free_package(pi);
3300 }
3301 }
3302}
3303
3304void ResTable::Theme::free_package(package_info* pi)
3305{
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003306 for (size_t j = 0; j <= Res_MAXTYPE; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307 theme_entry* te = pi->types[j].entries;
3308 if (te != NULL) {
3309 free(te);
3310 }
3311 }
3312 free(pi);
3313}
3314
3315ResTable::Theme::package_info* ResTable::Theme::copy_package(package_info* pi)
3316{
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003317 package_info* newpi = (package_info*)malloc(sizeof(package_info));
3318 for (size_t j = 0; j <= Res_MAXTYPE; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 size_t cnt = pi->types[j].numEntries;
3320 newpi->types[j].numEntries = cnt;
3321 theme_entry* te = pi->types[j].entries;
Vishwath Mohan6a2c23d2015-03-09 18:55:11 -07003322 size_t cnt_max = SIZE_MAX / sizeof(theme_entry);
3323 if (te != NULL && (cnt < 0xFFFFFFFF-1) && (cnt < cnt_max)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003324 theme_entry* newte = (theme_entry*)malloc(cnt*sizeof(theme_entry));
3325 newpi->types[j].entries = newte;
3326 memcpy(newte, te, cnt*sizeof(theme_entry));
3327 } else {
3328 newpi->types[j].entries = NULL;
3329 }
3330 }
3331 return newpi;
3332}
3333
3334status_t ResTable::Theme::applyStyle(uint32_t resID, bool force)
3335{
3336 const bag_entry* bag;
3337 uint32_t bagTypeSpecFlags = 0;
3338 mTable.lock();
3339 const ssize_t N = mTable.getBagLocked(resID, &bag, &bagTypeSpecFlags);
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003340 if (kDebugTableNoisy) {
3341 ALOGV("Applying style 0x%08x to theme %p, count=%zu", resID, this, N);
3342 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003343 if (N < 0) {
3344 mTable.unlock();
3345 return N;
3346 }
3347
Alan Viverettec1d52792015-05-05 09:49:03 -07003348 mTypeSpecFlags |= bagTypeSpecFlags;
3349
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003350 uint32_t curPackage = 0xffffffff;
3351 ssize_t curPackageIndex = 0;
3352 package_info* curPI = NULL;
3353 uint32_t curType = 0xffffffff;
3354 size_t numEntries = 0;
3355 theme_entry* curEntries = NULL;
3356
3357 const bag_entry* end = bag + N;
3358 while (bag < end) {
3359 const uint32_t attrRes = bag->map.name.ident;
3360 const uint32_t p = Res_GETPACKAGE(attrRes);
3361 const uint32_t t = Res_GETTYPE(attrRes);
3362 const uint32_t e = Res_GETENTRY(attrRes);
3363
3364 if (curPackage != p) {
3365 const ssize_t pidx = mTable.getResourcePackageIndex(attrRes);
3366 if (pidx < 0) {
Steve Block3762c312012-01-06 19:20:56 +00003367 ALOGE("Style contains key with bad package: 0x%08x\n", attrRes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003368 bag++;
3369 continue;
3370 }
3371 curPackage = p;
3372 curPackageIndex = pidx;
3373 curPI = mPackages[pidx];
3374 if (curPI == NULL) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003375 curPI = (package_info*)malloc(sizeof(package_info));
3376 memset(curPI, 0, sizeof(*curPI));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003377 mPackages[pidx] = curPI;
3378 }
3379 curType = 0xffffffff;
3380 }
3381 if (curType != t) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003382 if (t > Res_MAXTYPE) {
Steve Block3762c312012-01-06 19:20:56 +00003383 ALOGE("Style contains key with bad type: 0x%08x\n", attrRes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003384 bag++;
3385 continue;
3386 }
3387 curType = t;
3388 curEntries = curPI->types[t].entries;
3389 if (curEntries == NULL) {
3390 PackageGroup* const grp = mTable.mPackageGroups[curPackageIndex];
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003391 const TypeList& typeList = grp->types[t];
Vishwath Mohan6a2c23d2015-03-09 18:55:11 -07003392 size_t cnt = typeList.isEmpty() ? 0 : typeList[0]->entryCount;
3393 size_t cnt_max = SIZE_MAX / sizeof(theme_entry);
3394 size_t buff_size = (cnt < cnt_max && cnt < 0xFFFFFFFF-1) ?
3395 cnt*sizeof(theme_entry) : 0;
3396 curEntries = (theme_entry*)malloc(buff_size);
3397 memset(curEntries, Res_value::TYPE_NULL, buff_size);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003398 curPI->types[t].numEntries = cnt;
3399 curPI->types[t].entries = curEntries;
3400 }
3401 numEntries = curPI->types[t].numEntries;
3402 }
3403 if (e >= numEntries) {
Steve Block3762c312012-01-06 19:20:56 +00003404 ALOGE("Style contains key with bad entry: 0x%08x\n", attrRes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003405 bag++;
3406 continue;
3407 }
3408 theme_entry* curEntry = curEntries + e;
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003409 if (kDebugTableNoisy) {
3410 ALOGV("Attr 0x%08x: type=0x%x, data=0x%08x; curType=0x%x",
3411 attrRes, bag->map.value.dataType, bag->map.value.data,
3412 curEntry->value.dataType);
3413 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003414 if (force || curEntry->value.dataType == Res_value::TYPE_NULL) {
3415 curEntry->stringBlock = bag->stringBlock;
3416 curEntry->typeSpecFlags |= bagTypeSpecFlags;
3417 curEntry->value = bag->map.value;
3418 }
3419
3420 bag++;
3421 }
3422
3423 mTable.unlock();
3424
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003425 if (kDebugTableTheme) {
3426 ALOGI("Applying style 0x%08x (force=%d) theme %p...\n", resID, force, this);
3427 dumpToLog();
3428 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07003429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003430 return NO_ERROR;
3431}
3432
3433status_t ResTable::Theme::setTo(const Theme& other)
3434{
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003435 if (kDebugTableTheme) {
3436 ALOGI("Setting theme %p from theme %p...\n", this, &other);
3437 dumpToLog();
3438 other.dumpToLog();
3439 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07003440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003441 if (&mTable == &other.mTable) {
3442 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3443 if (mPackages[i] != NULL) {
3444 free_package(mPackages[i]);
3445 }
3446 if (other.mPackages[i] != NULL) {
3447 mPackages[i] = copy_package(other.mPackages[i]);
3448 } else {
3449 mPackages[i] = NULL;
3450 }
3451 }
3452 } else {
3453 // @todo: need to really implement this, not just copy
3454 // the system package (which is still wrong because it isn't
3455 // fixing up resource references).
3456 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3457 if (mPackages[i] != NULL) {
3458 free_package(mPackages[i]);
3459 }
3460 if (i == 0 && other.mPackages[i] != NULL) {
3461 mPackages[i] = copy_package(other.mPackages[i]);
3462 } else {
3463 mPackages[i] = NULL;
3464 }
3465 }
3466 }
3467
Alan Viverettec1d52792015-05-05 09:49:03 -07003468 mTypeSpecFlags = other.mTypeSpecFlags;
3469
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003470 if (kDebugTableTheme) {
3471 ALOGI("Final theme:");
3472 dumpToLog();
3473 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07003474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003475 return NO_ERROR;
3476}
3477
Alan Viverettee54d2452015-05-06 10:41:43 -07003478status_t ResTable::Theme::clear()
3479{
3480 if (kDebugTableTheme) {
3481 ALOGI("Clearing theme %p...\n", this);
3482 dumpToLog();
3483 }
3484
3485 for (size_t i = 0; i < Res_MAXPACKAGE; i++) {
3486 if (mPackages[i] != NULL) {
3487 free_package(mPackages[i]);
3488 mPackages[i] = NULL;
3489 }
3490 }
3491
3492 mTypeSpecFlags = 0;
3493
3494 if (kDebugTableTheme) {
3495 ALOGI("Final theme:");
3496 dumpToLog();
3497 }
3498
3499 return NO_ERROR;
3500}
3501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003502ssize_t ResTable::Theme::getAttribute(uint32_t resID, Res_value* outValue,
3503 uint32_t* outTypeSpecFlags) const
3504{
3505 int cnt = 20;
3506
3507 if (outTypeSpecFlags != NULL) *outTypeSpecFlags = 0;
Mark Salyzyn00adb862014-03-19 11:00:06 -07003508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003509 do {
3510 const ssize_t p = mTable.getResourcePackageIndex(resID);
3511 const uint32_t t = Res_GETTYPE(resID);
3512 const uint32_t e = Res_GETENTRY(resID);
3513
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003514 if (kDebugTableTheme) {
3515 ALOGI("Looking up attr 0x%08x in theme %p", resID, this);
3516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003517
3518 if (p >= 0) {
3519 const package_info* const pi = mPackages[p];
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003520 if (kDebugTableTheme) {
3521 ALOGI("Found package: %p", pi);
3522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003523 if (pi != NULL) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003524 if (kDebugTableTheme) {
3525 ALOGI("Desired type index is %zd in avail %zu", t, Res_MAXTYPE + 1);
3526 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003527 if (t <= Res_MAXTYPE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003528 const type_info& ti = pi->types[t];
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003529 if (kDebugTableTheme) {
3530 ALOGI("Desired entry index is %u in avail %zu", e, ti.numEntries);
3531 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003532 if (e < ti.numEntries) {
3533 const theme_entry& te = ti.entries[e];
Dianne Hackbornb8d81672009-11-20 14:26:42 -08003534 if (outTypeSpecFlags != NULL) {
3535 *outTypeSpecFlags |= te.typeSpecFlags;
3536 }
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003537 if (kDebugTableTheme) {
3538 ALOGI("Theme value: type=0x%x, data=0x%08x",
3539 te.value.dataType, te.value.data);
3540 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003541 const uint8_t type = te.value.dataType;
3542 if (type == Res_value::TYPE_ATTRIBUTE) {
3543 if (cnt > 0) {
3544 cnt--;
3545 resID = te.value.data;
3546 continue;
3547 }
Steve Block8564c8d2012-01-05 23:22:43 +00003548 ALOGW("Too many attribute references, stopped at: 0x%08x\n", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003549 return BAD_INDEX;
3550 } else if (type != Res_value::TYPE_NULL) {
3551 *outValue = te.value;
3552 return te.stringBlock;
3553 }
3554 return BAD_INDEX;
3555 }
3556 }
3557 }
3558 }
3559 break;
3560
3561 } while (true);
3562
3563 return BAD_INDEX;
3564}
3565
3566ssize_t ResTable::Theme::resolveAttributeReference(Res_value* inOutValue,
3567 ssize_t blockIndex, uint32_t* outLastRef,
Dianne Hackborn0d221012009-07-29 15:41:19 -07003568 uint32_t* inoutTypeSpecFlags, ResTable_config* inoutConfig) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003569{
3570 //printf("Resolving type=0x%x\n", inOutValue->dataType);
3571 if (inOutValue->dataType == Res_value::TYPE_ATTRIBUTE) {
3572 uint32_t newTypeSpecFlags;
3573 blockIndex = getAttribute(inOutValue->data, inOutValue, &newTypeSpecFlags);
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003574 if (kDebugTableTheme) {
3575 ALOGI("Resolving attr reference: blockIndex=%d, type=0x%x, data=0x%x\n",
3576 (int)blockIndex, (int)inOutValue->dataType, inOutValue->data);
3577 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003578 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newTypeSpecFlags;
3579 //printf("Retrieved attribute new type=0x%x\n", inOutValue->dataType);
3580 if (blockIndex < 0) {
3581 return blockIndex;
3582 }
3583 }
Dianne Hackborn0d221012009-07-29 15:41:19 -07003584 return mTable.resolveReference(inOutValue, blockIndex, outLastRef,
3585 inoutTypeSpecFlags, inoutConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003586}
3587
Alan Viverettec1d52792015-05-05 09:49:03 -07003588uint32_t ResTable::Theme::getChangingConfigurations() const
3589{
3590 return mTypeSpecFlags;
3591}
3592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003593void ResTable::Theme::dumpToLog() const
3594{
Steve Block6215d3f2012-01-04 20:05:49 +00003595 ALOGI("Theme %p:\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003596 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3597 package_info* pi = mPackages[i];
3598 if (pi == NULL) continue;
Mark Salyzyn00adb862014-03-19 11:00:06 -07003599
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003600 ALOGI(" Package #0x%02x:\n", (int)(i + 1));
3601 for (size_t j = 0; j <= Res_MAXTYPE; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003602 type_info& ti = pi->types[j];
3603 if (ti.numEntries == 0) continue;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003604 ALOGI(" Type #0x%02x:\n", (int)(j + 1));
3605 for (size_t k = 0; k < ti.numEntries; k++) {
3606 const theme_entry& te = ti.entries[k];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003607 if (te.value.dataType == Res_value::TYPE_NULL) continue;
Steve Block6215d3f2012-01-04 20:05:49 +00003608 ALOGI(" 0x%08x: t=0x%x, d=0x%08x (block=%d)\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003609 (int)Res_MAKEID(i, j, k),
3610 te.value.dataType, (int)te.value.data, (int)te.stringBlock);
3611 }
3612 }
3613 }
3614}
3615
3616ResTable::ResTable()
Adam Lesinskide898ff2014-01-29 18:20:45 -08003617 : mError(NO_INIT), mNextPackageId(2)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003618{
3619 memset(&mParams, 0, sizeof(mParams));
3620 memset(mPackageMap, 0, sizeof(mPackageMap));
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003621 if (kDebugTableSuperNoisy) {
3622 ALOGI("Creating ResTable %p\n", this);
3623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003624}
3625
Narayan Kamath7c4887f2014-01-27 17:32:37 +00003626ResTable::ResTable(const void* data, size_t size, const int32_t cookie, bool copyData)
Adam Lesinskide898ff2014-01-29 18:20:45 -08003627 : mError(NO_INIT), mNextPackageId(2)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003628{
3629 memset(&mParams, 0, sizeof(mParams));
3630 memset(mPackageMap, 0, sizeof(mPackageMap));
Tao Baia6d7e3f2015-09-01 18:49:54 -07003631 addInternal(data, size, NULL, 0, false, cookie, copyData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003632 LOG_FATAL_IF(mError != NO_ERROR, "Error parsing resource table");
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003633 if (kDebugTableSuperNoisy) {
3634 ALOGI("Creating ResTable %p\n", this);
3635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003636}
3637
3638ResTable::~ResTable()
3639{
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003640 if (kDebugTableSuperNoisy) {
3641 ALOGI("Destroying ResTable in %p\n", this);
3642 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003643 uninit();
3644}
3645
3646inline ssize_t ResTable::getResourcePackageIndex(uint32_t resID) const
3647{
3648 return ((ssize_t)mPackageMap[Res_GETPACKAGE(resID)+1])-1;
3649}
3650
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003651status_t ResTable::add(const void* data, size_t size, const int32_t cookie, bool copyData) {
Tao Baia6d7e3f2015-09-01 18:49:54 -07003652 return addInternal(data, size, NULL, 0, false, cookie, copyData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003653}
3654
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003655status_t ResTable::add(const void* data, size_t size, const void* idmapData, size_t idmapDataSize,
Tao Baia6d7e3f2015-09-01 18:49:54 -07003656 const int32_t cookie, bool copyData, bool appAsLib) {
3657 return addInternal(data, size, idmapData, idmapDataSize, appAsLib, cookie, copyData);
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003658}
3659
3660status_t ResTable::add(Asset* asset, const int32_t cookie, bool copyData) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661 const void* data = asset->getBuffer(true);
3662 if (data == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00003663 ALOGW("Unable to get buffer of resource asset file");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003664 return UNKNOWN_ERROR;
3665 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003666
Tao Baia6d7e3f2015-09-01 18:49:54 -07003667 return addInternal(data, static_cast<size_t>(asset->getLength()), NULL, false, 0, cookie,
3668 copyData);
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003669}
3670
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08003671status_t ResTable::add(
3672 Asset* asset, Asset* idmapAsset, const int32_t cookie, bool copyData,
3673 bool appAsLib, bool isSystemAsset) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003674 const void* data = asset->getBuffer(true);
3675 if (data == NULL) {
3676 ALOGW("Unable to get buffer of resource asset file");
3677 return UNKNOWN_ERROR;
3678 }
3679
3680 size_t idmapSize = 0;
3681 const void* idmapData = NULL;
3682 if (idmapAsset != NULL) {
3683 idmapData = idmapAsset->getBuffer(true);
3684 if (idmapData == NULL) {
3685 ALOGW("Unable to get buffer of idmap asset file");
3686 return UNKNOWN_ERROR;
3687 }
3688 idmapSize = static_cast<size_t>(idmapAsset->getLength());
3689 }
3690
3691 return addInternal(data, static_cast<size_t>(asset->getLength()),
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08003692 idmapData, idmapSize, appAsLib, cookie, copyData, isSystemAsset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003693}
3694
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08003695status_t ResTable::add(ResTable* src, bool isSystemAsset)
Dianne Hackborn78c40512009-07-06 11:07:40 -07003696{
3697 mError = src->mError;
Mark Salyzyn00adb862014-03-19 11:00:06 -07003698
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08003699 for (size_t i=0; i < src->mHeaders.size(); i++) {
Dianne Hackborn78c40512009-07-06 11:07:40 -07003700 mHeaders.add(src->mHeaders[i]);
3701 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07003702
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08003703 for (size_t i=0; i < src->mPackageGroups.size(); i++) {
Dianne Hackborn78c40512009-07-06 11:07:40 -07003704 PackageGroup* srcPg = src->mPackageGroups[i];
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08003705 PackageGroup* pg = new PackageGroup(this, srcPg->name, srcPg->id,
3706 false /* appAsLib */, isSystemAsset || srcPg->isSystemAsset);
Dianne Hackborn78c40512009-07-06 11:07:40 -07003707 for (size_t j=0; j<srcPg->packages.size(); j++) {
3708 pg->packages.add(srcPg->packages[j]);
3709 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003710
3711 for (size_t j = 0; j < srcPg->types.size(); j++) {
3712 if (srcPg->types[j].isEmpty()) {
3713 continue;
3714 }
3715
3716 TypeList& typeList = pg->types.editItemAt(j);
3717 typeList.appendVector(srcPg->types[j]);
3718 }
Adam Lesinski6022deb2014-08-20 14:59:19 -07003719 pg->dynamicRefTable.addMappings(srcPg->dynamicRefTable);
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003720 pg->largestTypeId = max(pg->largestTypeId, srcPg->largestTypeId);
Dianne Hackborn78c40512009-07-06 11:07:40 -07003721 mPackageGroups.add(pg);
3722 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07003723
Dianne Hackborn78c40512009-07-06 11:07:40 -07003724 memcpy(mPackageMap, src->mPackageMap, sizeof(mPackageMap));
Mark Salyzyn00adb862014-03-19 11:00:06 -07003725
Dianne Hackborn78c40512009-07-06 11:07:40 -07003726 return mError;
3727}
3728
Adam Lesinskide898ff2014-01-29 18:20:45 -08003729status_t ResTable::addEmpty(const int32_t cookie) {
3730 Header* header = new Header(this);
3731 header->index = mHeaders.size();
3732 header->cookie = cookie;
3733 header->values.setToEmpty();
3734 header->ownedData = calloc(1, sizeof(ResTable_header));
3735
3736 ResTable_header* resHeader = (ResTable_header*) header->ownedData;
3737 resHeader->header.type = RES_TABLE_TYPE;
3738 resHeader->header.headerSize = sizeof(ResTable_header);
3739 resHeader->header.size = sizeof(ResTable_header);
3740
3741 header->header = (const ResTable_header*) resHeader;
3742 mHeaders.add(header);
Adam Lesinski961dda72014-06-09 17:10:29 -07003743 return (mError=NO_ERROR);
Adam Lesinskide898ff2014-01-29 18:20:45 -08003744}
3745
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003746status_t ResTable::addInternal(const void* data, size_t dataSize, const void* idmapData, size_t idmapDataSize,
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08003747 bool appAsLib, const int32_t cookie, bool copyData, bool isSystemAsset)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003748{
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003749 if (!data) {
3750 return NO_ERROR;
3751 }
3752
Adam Lesinskif28d5052014-07-25 15:25:04 -07003753 if (dataSize < sizeof(ResTable_header)) {
3754 ALOGE("Invalid data. Size(%d) is smaller than a ResTable_header(%d).",
3755 (int) dataSize, (int) sizeof(ResTable_header));
3756 return UNKNOWN_ERROR;
3757 }
3758
Dianne Hackborn78c40512009-07-06 11:07:40 -07003759 Header* header = new Header(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003760 header->index = mHeaders.size();
3761 header->cookie = cookie;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003762 if (idmapData != NULL) {
3763 header->resourceIDMap = (uint32_t*) malloc(idmapDataSize);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01003764 if (header->resourceIDMap == NULL) {
3765 delete header;
3766 return (mError = NO_MEMORY);
3767 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003768 memcpy(header->resourceIDMap, idmapData, idmapDataSize);
3769 header->resourceIDMapSize = idmapDataSize;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01003770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003771 mHeaders.add(header);
3772
3773 const bool notDeviceEndian = htods(0xf0) != 0xf0;
3774
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003775 if (kDebugLoadTableNoisy) {
3776 ALOGV("Adding resources to ResTable: data=%p, size=%zu, cookie=%d, copy=%d "
3777 "idmap=%p\n", data, dataSize, cookie, copyData, idmapData);
3778 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07003779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003780 if (copyData || notDeviceEndian) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003781 header->ownedData = malloc(dataSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003782 if (header->ownedData == NULL) {
3783 return (mError=NO_MEMORY);
3784 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003785 memcpy(header->ownedData, data, dataSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003786 data = header->ownedData;
3787 }
3788
3789 header->header = (const ResTable_header*)data;
3790 header->size = dtohl(header->header->header.size);
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003791 if (kDebugLoadTableSuperNoisy) {
3792 ALOGI("Got size %zu, again size 0x%x, raw size 0x%x\n", header->size,
3793 dtohl(header->header->header.size), header->header->header.size);
3794 }
3795 if (kDebugLoadTableNoisy) {
3796 ALOGV("Loading ResTable @%p:\n", header->header);
3797 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003798 if (dtohs(header->header->header.headerSize) > header->size
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003799 || header->size > dataSize) {
Steve Block8564c8d2012-01-05 23:22:43 +00003800 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 -08003801 (int)dtohs(header->header->header.headerSize),
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003802 (int)header->size, (int)dataSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003803 return (mError=BAD_TYPE);
3804 }
3805 if (((dtohs(header->header->header.headerSize)|header->size)&0x3) != 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003806 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 -08003807 (int)dtohs(header->header->header.headerSize),
3808 (int)header->size);
3809 return (mError=BAD_TYPE);
3810 }
3811 header->dataEnd = ((const uint8_t*)header->header) + header->size;
3812
3813 // Iterate through all chunks.
3814 size_t curPackage = 0;
3815
3816 const ResChunk_header* chunk =
3817 (const ResChunk_header*)(((const uint8_t*)header->header)
3818 + dtohs(header->header->header.headerSize));
3819 while (((const uint8_t*)chunk) <= (header->dataEnd-sizeof(ResChunk_header)) &&
3820 ((const uint8_t*)chunk) <= (header->dataEnd-dtohl(chunk->size))) {
3821 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), header->dataEnd, "ResTable");
3822 if (err != NO_ERROR) {
3823 return (mError=err);
3824 }
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003825 if (kDebugTableNoisy) {
3826 ALOGV("Chunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n",
3827 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
3828 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)));
3829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003830 const size_t csize = dtohl(chunk->size);
3831 const uint16_t ctype = dtohs(chunk->type);
3832 if (ctype == RES_STRING_POOL_TYPE) {
3833 if (header->values.getError() != NO_ERROR) {
3834 // Only use the first string chunk; ignore any others that
3835 // may appear.
3836 status_t err = header->values.setTo(chunk, csize);
3837 if (err != NO_ERROR) {
3838 return (mError=err);
3839 }
3840 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003841 ALOGW("Multiple string chunks found in resource table.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003842 }
3843 } else if (ctype == RES_TABLE_PACKAGE_TYPE) {
3844 if (curPackage >= dtohl(header->header->packageCount)) {
Steve Block8564c8d2012-01-05 23:22:43 +00003845 ALOGW("More package chunks were found than the %d declared in the header.",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003846 dtohl(header->header->packageCount));
3847 return (mError=BAD_TYPE);
3848 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003849
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08003850 if (parsePackage(
3851 (ResTable_package*)chunk, header, appAsLib, isSystemAsset) != NO_ERROR) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003852 return mError;
3853 }
3854 curPackage++;
3855 } else {
Patrik Bannura443dd932014-02-12 13:38:54 +01003856 ALOGW("Unknown chunk type 0x%x in table at %p.\n",
3857 ctype,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003858 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)));
3859 }
3860 chunk = (const ResChunk_header*)
3861 (((const uint8_t*)chunk) + csize);
3862 }
3863
3864 if (curPackage < dtohl(header->header->packageCount)) {
Steve Block8564c8d2012-01-05 23:22:43 +00003865 ALOGW("Fewer package chunks (%d) were found than the %d declared in the header.",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866 (int)curPackage, dtohl(header->header->packageCount));
3867 return (mError=BAD_TYPE);
3868 }
3869 mError = header->values.getError();
3870 if (mError != NO_ERROR) {
Steve Block8564c8d2012-01-05 23:22:43 +00003871 ALOGW("No string values found in resource table!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003872 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01003873
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003874 if (kDebugTableNoisy) {
3875 ALOGV("Returning from add with mError=%d\n", mError);
3876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003877 return mError;
3878}
3879
3880status_t ResTable::getError() const
3881{
3882 return mError;
3883}
3884
3885void ResTable::uninit()
3886{
3887 mError = NO_INIT;
3888 size_t N = mPackageGroups.size();
3889 for (size_t i=0; i<N; i++) {
3890 PackageGroup* g = mPackageGroups[i];
3891 delete g;
3892 }
3893 N = mHeaders.size();
3894 for (size_t i=0; i<N; i++) {
3895 Header* header = mHeaders[i];
Dianne Hackborn78c40512009-07-06 11:07:40 -07003896 if (header->owner == this) {
3897 if (header->ownedData) {
3898 free(header->ownedData);
3899 }
3900 delete header;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003902 }
3903
3904 mPackageGroups.clear();
3905 mHeaders.clear();
3906}
3907
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07003908bool ResTable::getResourceName(uint32_t resID, bool allowUtf8, resource_name* outName) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003909{
3910 if (mError != NO_ERROR) {
3911 return false;
3912 }
3913
3914 const ssize_t p = getResourcePackageIndex(resID);
3915 const int t = Res_GETTYPE(resID);
3916 const int e = Res_GETENTRY(resID);
3917
3918 if (p < 0) {
Dianne Hackborn6cca1592009-09-20 12:40:03 -07003919 if (Res_GETPACKAGE(resID)+1 == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003920 ALOGW("No package identifier when getting name for resource number 0x%08x", resID);
Dianne Hackborn6cca1592009-09-20 12:40:03 -07003921 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003922 ALOGW("No known package when getting name for resource number 0x%08x", resID);
Dianne Hackborn6cca1592009-09-20 12:40:03 -07003923 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 return false;
3925 }
3926 if (t < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003927 ALOGW("No type identifier when getting name for resource number 0x%08x", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003928 return false;
3929 }
3930
3931 const PackageGroup* const grp = mPackageGroups[p];
3932 if (grp == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00003933 ALOGW("Bad identifier when getting name for resource number 0x%08x", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003934 return false;
3935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003937 Entry entry;
3938 status_t err = getEntry(grp, t, e, NULL, &entry);
3939 if (err != NO_ERROR) {
3940 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003941 }
3942
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003943 outName->package = grp->name.string();
3944 outName->packageLen = grp->name.size();
3945 if (allowUtf8) {
3946 outName->type8 = entry.typeStr.string8(&outName->typeLen);
3947 outName->name8 = entry.keyStr.string8(&outName->nameLen);
3948 } else {
3949 outName->type8 = NULL;
3950 outName->name8 = NULL;
3951 }
3952 if (outName->type8 == NULL) {
3953 outName->type = entry.typeStr.string16(&outName->typeLen);
3954 // If we have a bad index for some reason, we should abort.
3955 if (outName->type == NULL) {
3956 return false;
3957 }
3958 }
3959 if (outName->name8 == NULL) {
3960 outName->name = entry.keyStr.string16(&outName->nameLen);
3961 // If we have a bad index for some reason, we should abort.
3962 if (outName->name == NULL) {
3963 return false;
3964 }
3965 }
3966
3967 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003968}
3969
Kenny Root55fc8502010-10-28 14:47:01 -07003970ssize_t ResTable::getResource(uint32_t resID, Res_value* outValue, bool mayBeBag, uint16_t density,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003971 uint32_t* outSpecFlags, ResTable_config* outConfig) const
3972{
3973 if (mError != NO_ERROR) {
3974 return mError;
3975 }
3976
3977 const ssize_t p = getResourcePackageIndex(resID);
3978 const int t = Res_GETTYPE(resID);
3979 const int e = Res_GETENTRY(resID);
3980
3981 if (p < 0) {
Dianne Hackborn6cca1592009-09-20 12:40:03 -07003982 if (Res_GETPACKAGE(resID)+1 == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003983 ALOGW("No package identifier when getting value for resource number 0x%08x", resID);
Dianne Hackborn6cca1592009-09-20 12:40:03 -07003984 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003985 ALOGW("No known package when getting value for resource number 0x%08x", resID);
Dianne Hackborn6cca1592009-09-20 12:40:03 -07003986 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003987 return BAD_INDEX;
3988 }
3989 if (t < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003990 ALOGW("No type identifier when getting value for resource number 0x%08x", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003991 return BAD_INDEX;
3992 }
3993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003994 const PackageGroup* const grp = mPackageGroups[p];
3995 if (grp == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00003996 ALOGW("Bad identifier when getting value for resource number 0x%08x", resID);
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08003997 return BAD_INDEX;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003998 }
Kenny Root55fc8502010-10-28 14:47:01 -07003999
4000 // Allow overriding density
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004001 ResTable_config desiredConfig = mParams;
Kenny Root55fc8502010-10-28 14:47:01 -07004002 if (density > 0) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004003 desiredConfig.density = density;
Kenny Root55fc8502010-10-28 14:47:01 -07004004 }
4005
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004006 Entry entry;
4007 status_t err = getEntry(grp, t, e, &desiredConfig, &entry);
4008 if (err != NO_ERROR) {
Adam Lesinskide7de472014-11-03 12:03:08 -08004009 // Only log the failure when we're not running on the host as
4010 // part of a tool. The caller will do its own logging.
4011#ifndef STATIC_ANDROIDFW_FOR_TOOLS
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004012 ALOGW("Failure getting entry for 0x%08x (t=%d e=%d) (error %d)\n",
4013 resID, t, e, err);
Adam Lesinskide7de472014-11-03 12:03:08 -08004014#endif
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004015 return err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004016 }
4017
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004018 if ((dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) != 0) {
4019 if (!mayBeBag) {
4020 ALOGW("Requesting resource 0x%08x failed because it is complex\n", resID);
Adam Lesinskide898ff2014-01-29 18:20:45 -08004021 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004022 return BAD_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004023 }
4024
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004025 const Res_value* value = reinterpret_cast<const Res_value*>(
4026 reinterpret_cast<const uint8_t*>(entry.entry) + entry.entry->size);
4027
4028 outValue->size = dtohs(value->size);
4029 outValue->res0 = value->res0;
4030 outValue->dataType = value->dataType;
4031 outValue->data = dtohl(value->data);
4032
4033 // The reference may be pointing to a resource in a shared library. These
4034 // references have build-time generated package IDs. These ids may not match
4035 // the actual package IDs of the corresponding packages in this ResTable.
4036 // We need to fix the package ID based on a mapping.
4037 if (grp->dynamicRefTable.lookupResourceValue(outValue) != NO_ERROR) {
4038 ALOGW("Failed to resolve referenced package: 0x%08x", outValue->data);
4039 return BAD_VALUE;
Kenny Root55fc8502010-10-28 14:47:01 -07004040 }
4041
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004042 if (kDebugTableNoisy) {
4043 size_t len;
4044 printf("Found value: pkg=%zu, type=%d, str=%s, int=%d\n",
4045 entry.package->header->index,
4046 outValue->dataType,
4047 outValue->dataType == Res_value::TYPE_STRING ?
4048 String8(entry.package->header->values.stringAt(outValue->data, &len)).string() :
4049 "",
4050 outValue->data);
4051 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004052
4053 if (outSpecFlags != NULL) {
4054 *outSpecFlags = entry.specFlags;
4055 }
4056
4057 if (outConfig != NULL) {
4058 *outConfig = entry.config;
4059 }
4060
4061 return entry.package->header->index;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004062}
4063
4064ssize_t ResTable::resolveReference(Res_value* value, ssize_t blockIndex,
Dianne Hackborn0d221012009-07-29 15:41:19 -07004065 uint32_t* outLastRef, uint32_t* inoutTypeSpecFlags,
4066 ResTable_config* outConfig) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004067{
4068 int count=0;
Adam Lesinskide898ff2014-01-29 18:20:45 -08004069 while (blockIndex >= 0 && value->dataType == Res_value::TYPE_REFERENCE
4070 && value->data != 0 && count < 20) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004071 if (outLastRef) *outLastRef = value->data;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004072 uint32_t newFlags = 0;
Kenny Root55fc8502010-10-28 14:47:01 -07004073 const ssize_t newIndex = getResource(value->data, value, true, 0, &newFlags,
Dianne Hackborn0d221012009-07-29 15:41:19 -07004074 outConfig);
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08004075 if (newIndex == BAD_INDEX) {
4076 return BAD_INDEX;
4077 }
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004078 if (kDebugTableTheme) {
4079 ALOGI("Resolving reference 0x%x: newIndex=%d, type=0x%x, data=0x%x\n",
4080 value->data, (int)newIndex, (int)value->dataType, value->data);
4081 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004082 //printf("Getting reference 0x%08x: newIndex=%d\n", value->data, newIndex);
4083 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newFlags;
4084 if (newIndex < 0) {
4085 // This can fail if the resource being referenced is a style...
4086 // in this case, just return the reference, and expect the
4087 // caller to deal with.
4088 return blockIndex;
4089 }
4090 blockIndex = newIndex;
4091 count++;
4092 }
4093 return blockIndex;
4094}
4095
4096const char16_t* ResTable::valueToString(
4097 const Res_value* value, size_t stringBlock,
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07004098 char16_t /*tmpBuffer*/ [TMP_BUFFER_SIZE], size_t* outLen) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004099{
4100 if (!value) {
4101 return NULL;
4102 }
4103 if (value->dataType == value->TYPE_STRING) {
4104 return getTableStringBlock(stringBlock)->stringAt(value->data, outLen);
4105 }
4106 // XXX do int to string conversions.
4107 return NULL;
4108}
4109
4110ssize_t ResTable::lockBag(uint32_t resID, const bag_entry** outBag) const
4111{
4112 mLock.lock();
4113 ssize_t err = getBagLocked(resID, outBag);
4114 if (err < NO_ERROR) {
4115 //printf("*** get failed! unlocking\n");
4116 mLock.unlock();
4117 }
4118 return err;
4119}
4120
Mark Salyzyn00adb862014-03-19 11:00:06 -07004121void ResTable::unlockBag(const bag_entry* /*bag*/) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004122{
4123 //printf("<<< unlockBag %p\n", this);
4124 mLock.unlock();
4125}
4126
4127void ResTable::lock() const
4128{
4129 mLock.lock();
4130}
4131
4132void ResTable::unlock() const
4133{
4134 mLock.unlock();
4135}
4136
4137ssize_t ResTable::getBagLocked(uint32_t resID, const bag_entry** outBag,
4138 uint32_t* outTypeSpecFlags) const
4139{
4140 if (mError != NO_ERROR) {
4141 return mError;
4142 }
4143
4144 const ssize_t p = getResourcePackageIndex(resID);
4145 const int t = Res_GETTYPE(resID);
4146 const int e = Res_GETENTRY(resID);
4147
4148 if (p < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00004149 ALOGW("Invalid package identifier when getting bag for resource number 0x%08x", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004150 return BAD_INDEX;
4151 }
4152 if (t < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00004153 ALOGW("No type identifier when getting bag for resource number 0x%08x", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004154 return BAD_INDEX;
4155 }
4156
4157 //printf("Get bag: id=0x%08x, p=%d, t=%d\n", resID, p, t);
4158 PackageGroup* const grp = mPackageGroups[p];
4159 if (grp == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00004160 ALOGW("Bad identifier when getting bag for resource number 0x%08x", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004161 return BAD_INDEX;
4162 }
4163
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004164 const TypeList& typeConfigs = grp->types[t];
4165 if (typeConfigs.isEmpty()) {
4166 ALOGW("Type identifier 0x%x does not exist.", t+1);
4167 return BAD_INDEX;
4168 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004169
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004170 const size_t NENTRY = typeConfigs[0]->entryCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004171 if (e >= (int)NENTRY) {
Steve Block8564c8d2012-01-05 23:22:43 +00004172 ALOGW("Entry identifier 0x%x is larger than entry count 0x%x",
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004173 e, (int)typeConfigs[0]->entryCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 return BAD_INDEX;
4175 }
4176
4177 // First see if we've already computed this bag...
4178 if (grp->bags) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004179 bag_set** typeSet = grp->bags->get(t);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004180 if (typeSet) {
4181 bag_set* set = typeSet[e];
4182 if (set) {
4183 if (set != (bag_set*)0xFFFFFFFF) {
4184 if (outTypeSpecFlags != NULL) {
4185 *outTypeSpecFlags = set->typeSpecFlags;
4186 }
4187 *outBag = (bag_entry*)(set+1);
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004188 if (kDebugTableSuperNoisy) {
4189 ALOGI("Found existing bag for: 0x%x\n", resID);
4190 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004191 return set->numAttrs;
4192 }
Steve Block8564c8d2012-01-05 23:22:43 +00004193 ALOGW("Attempt to retrieve bag 0x%08x which is invalid or in a cycle.",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004194 resID);
4195 return BAD_INDEX;
4196 }
4197 }
4198 }
4199
4200 // Bag not found, we need to compute it!
4201 if (!grp->bags) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004202 grp->bags = new ByteBucketArray<bag_set**>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004203 if (!grp->bags) return NO_MEMORY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004204 }
4205
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004206 bag_set** typeSet = grp->bags->get(t);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004207 if (!typeSet) {
Iliyan Malchev7e1d3952012-02-17 12:15:58 -08004208 typeSet = (bag_set**)calloc(NENTRY, sizeof(bag_set*));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004209 if (!typeSet) return NO_MEMORY;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004210 grp->bags->set(t, typeSet);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004211 }
4212
4213 // Mark that we are currently working on this one.
4214 typeSet[e] = (bag_set*)0xFFFFFFFF;
4215
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004216 if (kDebugTableNoisy) {
4217 ALOGI("Building bag: %x\n", resID);
4218 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004219
4220 // Now collect all bag attributes
4221 Entry entry;
4222 status_t err = getEntry(grp, t, e, &mParams, &entry);
4223 if (err != NO_ERROR) {
4224 return err;
4225 }
4226
4227 const uint16_t entrySize = dtohs(entry.entry->size);
4228 const uint32_t parent = entrySize >= sizeof(ResTable_map_entry)
4229 ? dtohl(((const ResTable_map_entry*)entry.entry)->parent.ident) : 0;
4230 const uint32_t count = entrySize >= sizeof(ResTable_map_entry)
4231 ? dtohl(((const ResTable_map_entry*)entry.entry)->count) : 0;
4232
4233 size_t N = count;
4234
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004235 if (kDebugTableNoisy) {
4236 ALOGI("Found map: size=%x parent=%x count=%d\n", entrySize, parent, count);
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004237
4238 // If this map inherits from another, we need to start
4239 // with its parent's values. Otherwise start out empty.
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004240 ALOGI("Creating new bag, entrySize=0x%08x, parent=0x%08x\n", entrySize, parent);
4241 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004243 // This is what we are building.
4244 bag_set* set = NULL;
4245
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004246 if (parent) {
4247 uint32_t resolvedParent = parent;
Mark Salyzyn00adb862014-03-19 11:00:06 -07004248
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004249 // Bags encode a parent reference without using the standard
4250 // Res_value structure. That means we must always try to
4251 // resolve a parent reference in case it is actually a
4252 // TYPE_DYNAMIC_REFERENCE.
4253 status_t err = grp->dynamicRefTable.lookupResourceId(&resolvedParent);
4254 if (err != NO_ERROR) {
4255 ALOGE("Failed resolving bag parent id 0x%08x", parent);
4256 return UNKNOWN_ERROR;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01004257 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004258
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004259 const bag_entry* parentBag;
4260 uint32_t parentTypeSpecFlags = 0;
4261 const ssize_t NP = getBagLocked(resolvedParent, &parentBag, &parentTypeSpecFlags);
4262 const size_t NT = ((NP >= 0) ? NP : 0) + N;
4263 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*NT);
4264 if (set == NULL) {
4265 return NO_MEMORY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004266 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004267 if (NP > 0) {
4268 memcpy(set+1, parentBag, NP*sizeof(bag_entry));
4269 set->numAttrs = NP;
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004270 if (kDebugTableNoisy) {
4271 ALOGI("Initialized new bag with %zd inherited attributes.\n", NP);
4272 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01004273 } else {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004274 if (kDebugTableNoisy) {
4275 ALOGI("Initialized new bag with no inherited attributes.\n");
4276 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01004277 set->numAttrs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004278 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004279 set->availAttrs = NT;
4280 set->typeSpecFlags = parentTypeSpecFlags;
4281 } else {
4282 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*N);
4283 if (set == NULL) {
4284 return NO_MEMORY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004285 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004286 set->numAttrs = 0;
4287 set->availAttrs = N;
4288 set->typeSpecFlags = 0;
4289 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07004290
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004291 set->typeSpecFlags |= entry.specFlags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004292
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004293 // Now merge in the new attributes...
4294 size_t curOff = (reinterpret_cast<uintptr_t>(entry.entry) - reinterpret_cast<uintptr_t>(entry.type))
4295 + dtohs(entry.entry->size);
4296 const ResTable_map* map;
4297 bag_entry* entries = (bag_entry*)(set+1);
4298 size_t curEntry = 0;
4299 uint32_t pos = 0;
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004300 if (kDebugTableNoisy) {
4301 ALOGI("Starting with set %p, entries=%p, avail=%zu\n", set, entries, set->availAttrs);
4302 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004303 while (pos < count) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004304 if (kDebugTableNoisy) {
4305 ALOGI("Now at %p\n", (void*)curOff);
4306 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004307
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004308 if (curOff > (dtohl(entry.type->header.size)-sizeof(ResTable_map))) {
4309 ALOGW("ResTable_map at %d is beyond type chunk data %d",
4310 (int)curOff, dtohl(entry.type->header.size));
4311 return BAD_TYPE;
4312 }
4313 map = (const ResTable_map*)(((const uint8_t*)entry.type) + curOff);
4314 N++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004315
Adam Lesinskiccf25c7b2014-08-08 15:32:40 -07004316 uint32_t newName = htodl(map->name.ident);
4317 if (!Res_INTERNALID(newName)) {
4318 // Attributes don't have a resource id as the name. They specify
4319 // other data, which would be wrong to change via a lookup.
4320 if (grp->dynamicRefTable.lookupResourceId(&newName) != NO_ERROR) {
4321 ALOGE("Failed resolving ResTable_map name at %d with ident 0x%08x",
4322 (int) curOff, (int) newName);
4323 return UNKNOWN_ERROR;
4324 }
4325 }
4326
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004327 bool isInside;
4328 uint32_t oldName = 0;
4329 while ((isInside=(curEntry < set->numAttrs))
4330 && (oldName=entries[curEntry].map.name.ident) < newName) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004331 if (kDebugTableNoisy) {
4332 ALOGI("#%zu: Keeping existing attribute: 0x%08x\n",
4333 curEntry, entries[curEntry].map.name.ident);
4334 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004335 curEntry++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004336 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004337
4338 if ((!isInside) || oldName != newName) {
4339 // This is a new attribute... figure out what to do with it.
4340 if (set->numAttrs >= set->availAttrs) {
4341 // Need to alloc more memory...
4342 const size_t newAvail = set->availAttrs+N;
4343 set = (bag_set*)realloc(set,
4344 sizeof(bag_set)
4345 + sizeof(bag_entry)*newAvail);
4346 if (set == NULL) {
4347 return NO_MEMORY;
4348 }
4349 set->availAttrs = newAvail;
4350 entries = (bag_entry*)(set+1);
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004351 if (kDebugTableNoisy) {
4352 ALOGI("Reallocated set %p, entries=%p, avail=%zu\n",
4353 set, entries, set->availAttrs);
4354 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004355 }
4356 if (isInside) {
4357 // Going in the middle, need to make space.
4358 memmove(entries+curEntry+1, entries+curEntry,
4359 sizeof(bag_entry)*(set->numAttrs-curEntry));
4360 set->numAttrs++;
4361 }
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004362 if (kDebugTableNoisy) {
4363 ALOGI("#%zu: Inserting new attribute: 0x%08x\n", curEntry, newName);
4364 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004365 } else {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004366 if (kDebugTableNoisy) {
4367 ALOGI("#%zu: Replacing existing attribute: 0x%08x\n", curEntry, oldName);
4368 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004369 }
4370
4371 bag_entry* cur = entries+curEntry;
4372
4373 cur->stringBlock = entry.package->header->index;
4374 cur->map.name.ident = newName;
4375 cur->map.value.copyFrom_dtoh(map->value);
4376 status_t err = grp->dynamicRefTable.lookupResourceValue(&cur->map.value);
4377 if (err != NO_ERROR) {
4378 ALOGE("Reference item(0x%08x) in bag could not be resolved.", cur->map.value.data);
4379 return UNKNOWN_ERROR;
4380 }
4381
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004382 if (kDebugTableNoisy) {
4383 ALOGI("Setting entry #%zu %p: block=%zd, name=0x%08d, type=%d, data=0x%08x\n",
4384 curEntry, cur, cur->stringBlock, cur->map.name.ident,
4385 cur->map.value.dataType, cur->map.value.data);
4386 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004387
4388 // On to the next!
4389 curEntry++;
4390 pos++;
4391 const size_t size = dtohs(map->value.size);
4392 curOff += size + sizeof(*map)-sizeof(map->value);
4393 };
4394
4395 if (curEntry > set->numAttrs) {
4396 set->numAttrs = curEntry;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004397 }
4398
4399 // And this is it...
4400 typeSet[e] = set;
4401 if (set) {
4402 if (outTypeSpecFlags != NULL) {
4403 *outTypeSpecFlags = set->typeSpecFlags;
4404 }
4405 *outBag = (bag_entry*)(set+1);
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004406 if (kDebugTableNoisy) {
4407 ALOGI("Returning %zu attrs\n", set->numAttrs);
4408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004409 return set->numAttrs;
4410 }
4411 return BAD_INDEX;
4412}
4413
4414void ResTable::setParameters(const ResTable_config* params)
4415{
4416 mLock.lock();
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004417 if (kDebugTableGetEntry) {
4418 ALOGI("Setting parameters: %s\n", params->toString().string());
4419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004420 mParams = *params;
4421 for (size_t i=0; i<mPackageGroups.size(); i++) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004422 if (kDebugTableNoisy) {
4423 ALOGI("CLEARING BAGS FOR GROUP %zu!", i);
4424 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004425 mPackageGroups[i]->clearBagCache();
4426 }
4427 mLock.unlock();
4428}
4429
4430void ResTable::getParameters(ResTable_config* params) const
4431{
4432 mLock.lock();
4433 *params = mParams;
4434 mLock.unlock();
4435}
4436
4437struct id_name_map {
4438 uint32_t id;
4439 size_t len;
4440 char16_t name[6];
4441};
4442
4443const static id_name_map ID_NAMES[] = {
4444 { ResTable_map::ATTR_TYPE, 5, { '^', 't', 'y', 'p', 'e' } },
4445 { ResTable_map::ATTR_L10N, 5, { '^', 'l', '1', '0', 'n' } },
4446 { ResTable_map::ATTR_MIN, 4, { '^', 'm', 'i', 'n' } },
4447 { ResTable_map::ATTR_MAX, 4, { '^', 'm', 'a', 'x' } },
4448 { ResTable_map::ATTR_OTHER, 6, { '^', 'o', 't', 'h', 'e', 'r' } },
4449 { ResTable_map::ATTR_ZERO, 5, { '^', 'z', 'e', 'r', 'o' } },
4450 { ResTable_map::ATTR_ONE, 4, { '^', 'o', 'n', 'e' } },
4451 { ResTable_map::ATTR_TWO, 4, { '^', 't', 'w', 'o' } },
4452 { ResTable_map::ATTR_FEW, 4, { '^', 'f', 'e', 'w' } },
4453 { ResTable_map::ATTR_MANY, 5, { '^', 'm', 'a', 'n', 'y' } },
4454};
4455
4456uint32_t ResTable::identifierForName(const char16_t* name, size_t nameLen,
4457 const char16_t* type, size_t typeLen,
4458 const char16_t* package,
4459 size_t packageLen,
4460 uint32_t* outTypeSpecFlags) const
4461{
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004462 if (kDebugTableSuperNoisy) {
4463 printf("Identifier for name: error=%d\n", mError);
4464 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004465
4466 // Check for internal resource identifier as the very first thing, so
4467 // that we will always find them even when there are no resources.
4468 if (name[0] == '^') {
4469 const int N = (sizeof(ID_NAMES)/sizeof(ID_NAMES[0]));
4470 size_t len;
4471 for (int i=0; i<N; i++) {
4472 const id_name_map* m = ID_NAMES + i;
4473 len = m->len;
4474 if (len != nameLen) {
4475 continue;
4476 }
4477 for (size_t j=1; j<len; j++) {
4478 if (m->name[j] != name[j]) {
4479 goto nope;
4480 }
4481 }
Dianne Hackborn426431a2011-06-09 11:29:08 -07004482 if (outTypeSpecFlags) {
4483 *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC;
4484 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004485 return m->id;
4486nope:
4487 ;
4488 }
4489 if (nameLen > 7) {
4490 if (name[1] == 'i' && name[2] == 'n'
4491 && name[3] == 'd' && name[4] == 'e' && name[5] == 'x'
4492 && name[6] == '_') {
4493 int index = atoi(String8(name + 7, nameLen - 7).string());
4494 if (Res_CHECKID(index)) {
Steve Block8564c8d2012-01-05 23:22:43 +00004495 ALOGW("Array resource index: %d is too large.",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004496 index);
4497 return 0;
4498 }
Dianne Hackborn426431a2011-06-09 11:29:08 -07004499 if (outTypeSpecFlags) {
4500 *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC;
4501 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004502 return Res_MAKEARRAY(index);
4503 }
4504 }
4505 return 0;
4506 }
4507
4508 if (mError != NO_ERROR) {
4509 return 0;
4510 }
4511
Dianne Hackborn426431a2011-06-09 11:29:08 -07004512 bool fakePublic = false;
4513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004514 // Figure out the package and type we are looking in...
4515
4516 const char16_t* packageEnd = NULL;
4517 const char16_t* typeEnd = NULL;
4518 const char16_t* const nameEnd = name+nameLen;
4519 const char16_t* p = name;
4520 while (p < nameEnd) {
4521 if (*p == ':') packageEnd = p;
4522 else if (*p == '/') typeEnd = p;
4523 p++;
4524 }
Dianne Hackborn426431a2011-06-09 11:29:08 -07004525 if (*name == '@') {
4526 name++;
4527 if (*name == '*') {
4528 fakePublic = true;
4529 name++;
4530 }
4531 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004532 if (name >= nameEnd) {
4533 return 0;
4534 }
4535
4536 if (packageEnd) {
4537 package = name;
4538 packageLen = packageEnd-name;
4539 name = packageEnd+1;
4540 } else if (!package) {
4541 return 0;
4542 }
4543
4544 if (typeEnd) {
4545 type = name;
4546 typeLen = typeEnd-name;
4547 name = typeEnd+1;
4548 } else if (!type) {
4549 return 0;
4550 }
4551
4552 if (name >= nameEnd) {
4553 return 0;
4554 }
4555 nameLen = nameEnd-name;
4556
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004557 if (kDebugTableNoisy) {
4558 printf("Looking for identifier: type=%s, name=%s, package=%s\n",
4559 String8(type, typeLen).string(),
4560 String8(name, nameLen).string(),
4561 String8(package, packageLen).string());
4562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004563
Adam Lesinski9b624c12014-11-19 17:49:26 -08004564 const String16 attr("attr");
4565 const String16 attrPrivate("^attr-private");
4566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004567 const size_t NG = mPackageGroups.size();
4568 for (size_t ig=0; ig<NG; ig++) {
4569 const PackageGroup* group = mPackageGroups[ig];
4570
4571 if (strzcmp16(package, packageLen,
4572 group->name.string(), group->name.size())) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004573 if (kDebugTableNoisy) {
4574 printf("Skipping package group: %s\n", String8(group->name).string());
4575 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004576 continue;
4577 }
4578
Adam Lesinskie60a87f2014-10-09 11:08:04 -07004579 const size_t packageCount = group->packages.size();
4580 for (size_t pi = 0; pi < packageCount; pi++) {
Adam Lesinski9b624c12014-11-19 17:49:26 -08004581 const char16_t* targetType = type;
4582 size_t targetTypeLen = typeLen;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004583
Adam Lesinski9b624c12014-11-19 17:49:26 -08004584 do {
4585 ssize_t ti = group->packages[pi]->typeStrings.indexOfString(
4586 targetType, targetTypeLen);
4587 if (ti < 0) {
Adam Lesinskie60a87f2014-10-09 11:08:04 -07004588 continue;
4589 }
4590
Adam Lesinski9b624c12014-11-19 17:49:26 -08004591 ti += group->packages[pi]->typeIdOffset;
Adam Lesinskie60a87f2014-10-09 11:08:04 -07004592
Adam Lesinski9b624c12014-11-19 17:49:26 -08004593 const uint32_t identifier = findEntry(group, ti, name, nameLen,
4594 outTypeSpecFlags);
4595 if (identifier != 0) {
4596 if (fakePublic && outTypeSpecFlags) {
4597 *outTypeSpecFlags |= ResTable_typeSpec::SPEC_PUBLIC;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004598 }
Adam Lesinski9b624c12014-11-19 17:49:26 -08004599 return identifier;
4600 }
4601 } while (strzcmp16(attr.string(), attr.size(), targetType, targetTypeLen) == 0
4602 && (targetType = attrPrivate.string())
4603 && (targetTypeLen = attrPrivate.size())
4604 );
4605 }
4606 break;
4607 }
4608 return 0;
4609}
4610
4611uint32_t ResTable::findEntry(const PackageGroup* group, ssize_t typeIndex, const char16_t* name,
4612 size_t nameLen, uint32_t* outTypeSpecFlags) const {
4613 const TypeList& typeList = group->types[typeIndex];
4614 const size_t typeCount = typeList.size();
4615 for (size_t i = 0; i < typeCount; i++) {
4616 const Type* t = typeList[i];
4617 const ssize_t ei = t->package->keyStrings.indexOfString(name, nameLen);
4618 if (ei < 0) {
4619 continue;
4620 }
4621
4622 const size_t configCount = t->configs.size();
4623 for (size_t j = 0; j < configCount; j++) {
4624 const TypeVariant tv(t->configs[j]);
4625 for (TypeVariant::iterator iter = tv.beginEntries();
4626 iter != tv.endEntries();
4627 iter++) {
4628 const ResTable_entry* entry = *iter;
4629 if (entry == NULL) {
4630 continue;
4631 }
4632
4633 if (dtohl(entry->key.index) == (size_t) ei) {
4634 uint32_t resId = Res_MAKEID(group->id - 1, typeIndex, iter.index());
4635 if (outTypeSpecFlags) {
4636 Entry result;
4637 if (getEntry(group, typeIndex, iter.index(), NULL, &result) != NO_ERROR) {
4638 ALOGW("Failed to find spec flags for 0x%08x", resId);
4639 return 0;
4640 }
4641 *outTypeSpecFlags = result.specFlags;
4642 }
4643 return resId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004644 }
4645 }
4646 }
4647 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004648 return 0;
4649}
4650
Dan Albertf348c152014-09-08 18:28:00 -07004651bool ResTable::expandResourceRef(const char16_t* refStr, size_t refLen,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004652 String16* outPackage,
4653 String16* outType,
4654 String16* outName,
4655 const String16* defType,
4656 const String16* defPackage,
Dianne Hackborn426431a2011-06-09 11:29:08 -07004657 const char** outErrorMsg,
4658 bool* outPublicOnly)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004659{
4660 const char16_t* packageEnd = NULL;
4661 const char16_t* typeEnd = NULL;
4662 const char16_t* p = refStr;
4663 const char16_t* const end = p + refLen;
4664 while (p < end) {
4665 if (*p == ':') packageEnd = p;
4666 else if (*p == '/') {
4667 typeEnd = p;
4668 break;
4669 }
4670 p++;
4671 }
4672 p = refStr;
4673 if (*p == '@') p++;
4674
Dianne Hackborn426431a2011-06-09 11:29:08 -07004675 if (outPublicOnly != NULL) {
4676 *outPublicOnly = true;
4677 }
4678 if (*p == '*') {
4679 p++;
4680 if (outPublicOnly != NULL) {
4681 *outPublicOnly = false;
4682 }
4683 }
4684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004685 if (packageEnd) {
4686 *outPackage = String16(p, packageEnd-p);
4687 p = packageEnd+1;
4688 } else {
4689 if (!defPackage) {
4690 if (outErrorMsg) {
4691 *outErrorMsg = "No resource package specified";
4692 }
4693 return false;
4694 }
4695 *outPackage = *defPackage;
4696 }
4697 if (typeEnd) {
4698 *outType = String16(p, typeEnd-p);
4699 p = typeEnd+1;
4700 } else {
4701 if (!defType) {
4702 if (outErrorMsg) {
4703 *outErrorMsg = "No resource type specified";
4704 }
4705 return false;
4706 }
4707 *outType = *defType;
4708 }
4709 *outName = String16(p, end-p);
Konstantin Lopyrevddcafcb2010-06-04 14:36:49 -07004710 if(**outPackage == 0) {
4711 if(outErrorMsg) {
4712 *outErrorMsg = "Resource package cannot be an empty string";
4713 }
4714 return false;
4715 }
4716 if(**outType == 0) {
4717 if(outErrorMsg) {
4718 *outErrorMsg = "Resource type cannot be an empty string";
4719 }
4720 return false;
4721 }
4722 if(**outName == 0) {
4723 if(outErrorMsg) {
4724 *outErrorMsg = "Resource id cannot be an empty string";
4725 }
4726 return false;
4727 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004728 return true;
4729}
4730
4731static uint32_t get_hex(char c, bool* outError)
4732{
4733 if (c >= '0' && c <= '9') {
4734 return c - '0';
4735 } else if (c >= 'a' && c <= 'f') {
4736 return c - 'a' + 0xa;
4737 } else if (c >= 'A' && c <= 'F') {
4738 return c - 'A' + 0xa;
4739 }
4740 *outError = true;
4741 return 0;
4742}
4743
4744struct unit_entry
4745{
4746 const char* name;
4747 size_t len;
4748 uint8_t type;
4749 uint32_t unit;
4750 float scale;
4751};
4752
4753static const unit_entry unitNames[] = {
4754 { "px", strlen("px"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PX, 1.0f },
4755 { "dip", strlen("dip"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
4756 { "dp", strlen("dp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
4757 { "sp", strlen("sp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_SP, 1.0f },
4758 { "pt", strlen("pt"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PT, 1.0f },
4759 { "in", strlen("in"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_IN, 1.0f },
4760 { "mm", strlen("mm"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_MM, 1.0f },
4761 { "%", strlen("%"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION, 1.0f/100 },
4762 { "%p", strlen("%p"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION_PARENT, 1.0f/100 },
4763 { NULL, 0, 0, 0, 0 }
4764};
4765
4766static bool parse_unit(const char* str, Res_value* outValue,
4767 float* outScale, const char** outEnd)
4768{
4769 const char* end = str;
4770 while (*end != 0 && !isspace((unsigned char)*end)) {
4771 end++;
4772 }
4773 const size_t len = end-str;
4774
4775 const char* realEnd = end;
4776 while (*realEnd != 0 && isspace((unsigned char)*realEnd)) {
4777 realEnd++;
4778 }
4779 if (*realEnd != 0) {
4780 return false;
4781 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07004782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004783 const unit_entry* cur = unitNames;
4784 while (cur->name) {
4785 if (len == cur->len && strncmp(cur->name, str, len) == 0) {
4786 outValue->dataType = cur->type;
4787 outValue->data = cur->unit << Res_value::COMPLEX_UNIT_SHIFT;
4788 *outScale = cur->scale;
4789 *outEnd = end;
4790 //printf("Found unit %s for %s\n", cur->name, str);
4791 return true;
4792 }
4793 cur++;
4794 }
4795
4796 return false;
4797}
4798
Dan Albert1b4f3162015-04-07 18:43:15 -07004799bool U16StringToInt(const char16_t* s, size_t len, Res_value* outValue)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004800{
4801 while (len > 0 && isspace16(*s)) {
4802 s++;
4803 len--;
4804 }
4805
4806 if (len <= 0) {
4807 return false;
4808 }
4809
4810 size_t i = 0;
Dan Albert1b4f3162015-04-07 18:43:15 -07004811 int64_t val = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004812 bool neg = false;
4813
4814 if (*s == '-') {
4815 neg = true;
4816 i++;
4817 }
4818
4819 if (s[i] < '0' || s[i] > '9') {
4820 return false;
4821 }
4822
Dan Albert1b4f3162015-04-07 18:43:15 -07004823 static_assert(std::is_same<uint32_t, Res_value::data_type>::value,
4824 "Res_value::data_type has changed. The range checks in this "
4825 "function are no longer correct.");
4826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004827 // Decimal or hex?
Dan Albert1b4f3162015-04-07 18:43:15 -07004828 bool isHex;
4829 if (len > 1 && s[i] == '0' && s[i+1] == 'x') {
4830 isHex = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004831 i += 2;
Dan Albert1b4f3162015-04-07 18:43:15 -07004832
4833 if (neg) {
4834 return false;
4835 }
4836
4837 if (i == len) {
4838 // Just u"0x"
4839 return false;
4840 }
4841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004842 bool error = false;
4843 while (i < len && !error) {
4844 val = (val*16) + get_hex(s[i], &error);
4845 i++;
Dan Albert1b4f3162015-04-07 18:43:15 -07004846
4847 if (val > std::numeric_limits<uint32_t>::max()) {
4848 return false;
4849 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004850 }
4851 if (error) {
4852 return false;
4853 }
4854 } else {
Dan Albert1b4f3162015-04-07 18:43:15 -07004855 isHex = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004856 while (i < len) {
4857 if (s[i] < '0' || s[i] > '9') {
4858 return false;
4859 }
4860 val = (val*10) + s[i]-'0';
4861 i++;
Dan Albert1b4f3162015-04-07 18:43:15 -07004862
4863 if ((neg && -val < std::numeric_limits<int32_t>::min()) ||
4864 (!neg && val > std::numeric_limits<int32_t>::max())) {
4865 return false;
4866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004867 }
4868 }
4869
4870 if (neg) val = -val;
4871
4872 while (i < len && isspace16(s[i])) {
4873 i++;
4874 }
4875
Dan Albert1b4f3162015-04-07 18:43:15 -07004876 if (i != len) {
4877 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004878 }
4879
Dan Albert1b4f3162015-04-07 18:43:15 -07004880 if (outValue) {
4881 outValue->dataType =
4882 isHex ? outValue->TYPE_INT_HEX : outValue->TYPE_INT_DEC;
4883 outValue->data = static_cast<Res_value::data_type>(val);
4884 }
4885 return true;
4886}
4887
4888bool ResTable::stringToInt(const char16_t* s, size_t len, Res_value* outValue)
4889{
4890 return U16StringToInt(s, len, outValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004891}
4892
4893bool ResTable::stringToFloat(const char16_t* s, size_t len, Res_value* outValue)
4894{
4895 while (len > 0 && isspace16(*s)) {
4896 s++;
4897 len--;
4898 }
4899
4900 if (len <= 0) {
4901 return false;
4902 }
4903
4904 char buf[128];
4905 int i=0;
4906 while (len > 0 && *s != 0 && i < 126) {
4907 if (*s > 255) {
4908 return false;
4909 }
4910 buf[i++] = *s++;
4911 len--;
4912 }
4913
4914 if (len > 0) {
4915 return false;
4916 }
Torne (Richard Coles)46a807f2014-08-27 12:36:44 +01004917 if ((buf[0] < '0' || buf[0] > '9') && buf[0] != '.' && buf[0] != '-' && buf[0] != '+') {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004918 return false;
4919 }
4920
4921 buf[i] = 0;
4922 const char* end;
4923 float f = strtof(buf, (char**)&end);
4924
4925 if (*end != 0 && !isspace((unsigned char)*end)) {
4926 // Might be a unit...
4927 float scale;
4928 if (parse_unit(end, outValue, &scale, &end)) {
4929 f *= scale;
4930 const bool neg = f < 0;
4931 if (neg) f = -f;
4932 uint64_t bits = (uint64_t)(f*(1<<23)+.5f);
4933 uint32_t radix;
4934 uint32_t shift;
4935 if ((bits&0x7fffff) == 0) {
4936 // Always use 23p0 if there is no fraction, just to make
4937 // things easier to read.
4938 radix = Res_value::COMPLEX_RADIX_23p0;
4939 shift = 23;
4940 } else if ((bits&0xffffffffff800000LL) == 0) {
4941 // Magnitude is zero -- can fit in 0 bits of precision.
4942 radix = Res_value::COMPLEX_RADIX_0p23;
4943 shift = 0;
4944 } else if ((bits&0xffffffff80000000LL) == 0) {
4945 // Magnitude can fit in 8 bits of precision.
4946 radix = Res_value::COMPLEX_RADIX_8p15;
4947 shift = 8;
4948 } else if ((bits&0xffffff8000000000LL) == 0) {
4949 // Magnitude can fit in 16 bits of precision.
4950 radix = Res_value::COMPLEX_RADIX_16p7;
4951 shift = 16;
4952 } else {
4953 // Magnitude needs entire range, so no fractional part.
4954 radix = Res_value::COMPLEX_RADIX_23p0;
4955 shift = 23;
4956 }
4957 int32_t mantissa = (int32_t)(
4958 (bits>>shift) & Res_value::COMPLEX_MANTISSA_MASK);
4959 if (neg) {
4960 mantissa = (-mantissa) & Res_value::COMPLEX_MANTISSA_MASK;
4961 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07004962 outValue->data |=
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004963 (radix<<Res_value::COMPLEX_RADIX_SHIFT)
4964 | (mantissa<<Res_value::COMPLEX_MANTISSA_SHIFT);
4965 //printf("Input value: %f 0x%016Lx, mult: %f, radix: %d, shift: %d, final: 0x%08x\n",
4966 // f * (neg ? -1 : 1), bits, f*(1<<23),
4967 // radix, shift, outValue->data);
4968 return true;
4969 }
4970 return false;
4971 }
4972
4973 while (*end != 0 && isspace((unsigned char)*end)) {
4974 end++;
4975 }
4976
4977 if (*end == 0) {
4978 if (outValue) {
4979 outValue->dataType = outValue->TYPE_FLOAT;
4980 *(float*)(&outValue->data) = f;
4981 return true;
4982 }
4983 }
4984
4985 return false;
4986}
4987
4988bool ResTable::stringToValue(Res_value* outValue, String16* outString,
4989 const char16_t* s, size_t len,
4990 bool preserveSpaces, bool coerceType,
4991 uint32_t attrID,
4992 const String16* defType,
4993 const String16* defPackage,
4994 Accessor* accessor,
4995 void* accessorCookie,
4996 uint32_t attrType,
4997 bool enforcePrivate) const
4998{
4999 bool localizationSetting = accessor != NULL && accessor->getLocalizationSetting();
5000 const char* errorMsg = NULL;
5001
5002 outValue->size = sizeof(Res_value);
5003 outValue->res0 = 0;
5004
5005 // First strip leading/trailing whitespace. Do this before handling
5006 // escapes, so they can be used to force whitespace into the string.
5007 if (!preserveSpaces) {
5008 while (len > 0 && isspace16(*s)) {
5009 s++;
5010 len--;
5011 }
5012 while (len > 0 && isspace16(s[len-1])) {
5013 len--;
5014 }
5015 // If the string ends with '\', then we keep the space after it.
5016 if (len > 0 && s[len-1] == '\\' && s[len] != 0) {
5017 len++;
5018 }
5019 }
5020
5021 //printf("Value for: %s\n", String8(s, len).string());
5022
5023 uint32_t l10nReq = ResTable_map::L10N_NOT_REQUIRED;
5024 uint32_t attrMin = 0x80000000, attrMax = 0x7fffffff;
5025 bool fromAccessor = false;
5026 if (attrID != 0 && !Res_INTERNALID(attrID)) {
5027 const ssize_t p = getResourcePackageIndex(attrID);
5028 const bag_entry* bag;
5029 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
5030 //printf("For attr 0x%08x got bag of %d\n", attrID, cnt);
5031 if (cnt >= 0) {
5032 while (cnt > 0) {
5033 //printf("Entry 0x%08x = 0x%08x\n", bag->map.name.ident, bag->map.value.data);
5034 switch (bag->map.name.ident) {
5035 case ResTable_map::ATTR_TYPE:
5036 attrType = bag->map.value.data;
5037 break;
5038 case ResTable_map::ATTR_MIN:
5039 attrMin = bag->map.value.data;
5040 break;
5041 case ResTable_map::ATTR_MAX:
5042 attrMax = bag->map.value.data;
5043 break;
5044 case ResTable_map::ATTR_L10N:
5045 l10nReq = bag->map.value.data;
5046 break;
5047 }
5048 bag++;
5049 cnt--;
5050 }
5051 unlockBag(bag);
5052 } else if (accessor && accessor->getAttributeType(attrID, &attrType)) {
5053 fromAccessor = true;
5054 if (attrType == ResTable_map::TYPE_ENUM
5055 || attrType == ResTable_map::TYPE_FLAGS
5056 || attrType == ResTable_map::TYPE_INTEGER) {
5057 accessor->getAttributeMin(attrID, &attrMin);
5058 accessor->getAttributeMax(attrID, &attrMax);
5059 }
5060 if (localizationSetting) {
5061 l10nReq = accessor->getAttributeL10N(attrID);
5062 }
5063 }
5064 }
5065
5066 const bool canStringCoerce =
5067 coerceType && (attrType&ResTable_map::TYPE_STRING) != 0;
5068
5069 if (*s == '@') {
5070 outValue->dataType = outValue->TYPE_REFERENCE;
5071
5072 // Note: we don't check attrType here because the reference can
5073 // be to any other type; we just need to count on the client making
5074 // sure the referenced type is correct.
Mark Salyzyn00adb862014-03-19 11:00:06 -07005075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005076 //printf("Looking up ref: %s\n", String8(s, len).string());
5077
5078 // It's a reference!
5079 if (len == 5 && s[1]=='n' && s[2]=='u' && s[3]=='l' && s[4]=='l') {
Alan Viverettef2969402014-10-29 17:09:36 -07005080 // Special case @null as undefined. This will be converted by
5081 // AssetManager to TYPE_NULL with data DATA_NULL_UNDEFINED.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005082 outValue->data = 0;
5083 return true;
Alan Viverettef2969402014-10-29 17:09:36 -07005084 } else if (len == 6 && s[1]=='e' && s[2]=='m' && s[3]=='p' && s[4]=='t' && s[5]=='y') {
5085 // Special case @empty as explicitly defined empty value.
5086 outValue->dataType = Res_value::TYPE_NULL;
5087 outValue->data = Res_value::DATA_NULL_EMPTY;
5088 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005089 } else {
5090 bool createIfNotFound = false;
5091 const char16_t* resourceRefName;
5092 int resourceNameLen;
5093 if (len > 2 && s[1] == '+') {
5094 createIfNotFound = true;
5095 resourceRefName = s + 2;
5096 resourceNameLen = len - 2;
5097 } else if (len > 2 && s[1] == '*') {
5098 enforcePrivate = false;
5099 resourceRefName = s + 2;
5100 resourceNameLen = len - 2;
5101 } else {
5102 createIfNotFound = false;
5103 resourceRefName = s + 1;
5104 resourceNameLen = len - 1;
5105 }
5106 String16 package, type, name;
5107 if (!expandResourceRef(resourceRefName,resourceNameLen, &package, &type, &name,
5108 defType, defPackage, &errorMsg)) {
5109 if (accessor != NULL) {
5110 accessor->reportError(accessorCookie, errorMsg);
5111 }
5112 return false;
5113 }
5114
5115 uint32_t specFlags = 0;
5116 uint32_t rid = identifierForName(name.string(), name.size(), type.string(),
5117 type.size(), package.string(), package.size(), &specFlags);
5118 if (rid != 0) {
5119 if (enforcePrivate) {
Adam Lesinski833f3cc2014-06-18 15:06:01 -07005120 if (accessor == NULL || accessor->getAssetsPackage() != package) {
5121 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
5122 if (accessor != NULL) {
5123 accessor->reportError(accessorCookie, "Resource is not public.");
5124 }
5125 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005127 }
5128 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08005129
5130 if (accessor) {
5131 rid = Res_MAKEID(
5132 accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
5133 Res_GETTYPE(rid), Res_GETENTRY(rid));
Andreas Gampe2204f0b2014-10-21 23:04:54 -07005134 if (kDebugTableNoisy) {
5135 ALOGI("Incl %s:%s/%s: 0x%08x\n",
5136 String8(package).string(), String8(type).string(),
5137 String8(name).string(), rid);
5138 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005139 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08005140
5141 uint32_t packageId = Res_GETPACKAGE(rid) + 1;
5142 if (packageId != APP_PACKAGE_ID && packageId != SYS_PACKAGE_ID) {
5143 outValue->dataType = Res_value::TYPE_DYNAMIC_REFERENCE;
5144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005145 outValue->data = rid;
5146 return true;
5147 }
5148
5149 if (accessor) {
5150 uint32_t rid = accessor->getCustomResourceWithCreation(package, type, name,
5151 createIfNotFound);
5152 if (rid != 0) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07005153 if (kDebugTableNoisy) {
5154 ALOGI("Pckg %s:%s/%s: 0x%08x\n",
5155 String8(package).string(), String8(type).string(),
5156 String8(name).string(), rid);
5157 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08005158 uint32_t packageId = Res_GETPACKAGE(rid) + 1;
5159 if (packageId == 0x00) {
5160 outValue->data = rid;
5161 outValue->dataType = Res_value::TYPE_DYNAMIC_REFERENCE;
5162 return true;
5163 } else if (packageId == APP_PACKAGE_ID || packageId == SYS_PACKAGE_ID) {
5164 // We accept packageId's generated as 0x01 in order to support
5165 // building the android system resources
5166 outValue->data = rid;
5167 return true;
5168 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005169 }
5170 }
5171 }
5172
5173 if (accessor != NULL) {
5174 accessor->reportError(accessorCookie, "No resource found that matches the given name");
5175 }
5176 return false;
5177 }
5178
5179 // if we got to here, and localization is required and it's not a reference,
5180 // complain and bail.
5181 if (l10nReq == ResTable_map::L10N_SUGGESTED) {
5182 if (localizationSetting) {
5183 if (accessor != NULL) {
5184 accessor->reportError(accessorCookie, "This attribute must be localized.");
5185 }
5186 }
5187 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005188
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005189 if (*s == '#') {
5190 // It's a color! Convert to an integer of the form 0xaarrggbb.
5191 uint32_t color = 0;
5192 bool error = false;
5193 if (len == 4) {
5194 outValue->dataType = outValue->TYPE_INT_COLOR_RGB4;
5195 color |= 0xFF000000;
5196 color |= get_hex(s[1], &error) << 20;
5197 color |= get_hex(s[1], &error) << 16;
5198 color |= get_hex(s[2], &error) << 12;
5199 color |= get_hex(s[2], &error) << 8;
5200 color |= get_hex(s[3], &error) << 4;
5201 color |= get_hex(s[3], &error);
5202 } else if (len == 5) {
5203 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB4;
5204 color |= get_hex(s[1], &error) << 28;
5205 color |= get_hex(s[1], &error) << 24;
5206 color |= get_hex(s[2], &error) << 20;
5207 color |= get_hex(s[2], &error) << 16;
5208 color |= get_hex(s[3], &error) << 12;
5209 color |= get_hex(s[3], &error) << 8;
5210 color |= get_hex(s[4], &error) << 4;
5211 color |= get_hex(s[4], &error);
5212 } else if (len == 7) {
5213 outValue->dataType = outValue->TYPE_INT_COLOR_RGB8;
5214 color |= 0xFF000000;
5215 color |= get_hex(s[1], &error) << 20;
5216 color |= get_hex(s[2], &error) << 16;
5217 color |= get_hex(s[3], &error) << 12;
5218 color |= get_hex(s[4], &error) << 8;
5219 color |= get_hex(s[5], &error) << 4;
5220 color |= get_hex(s[6], &error);
5221 } else if (len == 9) {
5222 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB8;
5223 color |= get_hex(s[1], &error) << 28;
5224 color |= get_hex(s[2], &error) << 24;
5225 color |= get_hex(s[3], &error) << 20;
5226 color |= get_hex(s[4], &error) << 16;
5227 color |= get_hex(s[5], &error) << 12;
5228 color |= get_hex(s[6], &error) << 8;
5229 color |= get_hex(s[7], &error) << 4;
5230 color |= get_hex(s[8], &error);
5231 } else {
5232 error = true;
5233 }
5234 if (!error) {
5235 if ((attrType&ResTable_map::TYPE_COLOR) == 0) {
5236 if (!canStringCoerce) {
5237 if (accessor != NULL) {
5238 accessor->reportError(accessorCookie,
5239 "Color types not allowed");
5240 }
5241 return false;
5242 }
5243 } else {
5244 outValue->data = color;
5245 //printf("Color input=%s, output=0x%x\n", String8(s, len).string(), color);
5246 return true;
5247 }
5248 } else {
5249 if ((attrType&ResTable_map::TYPE_COLOR) != 0) {
5250 if (accessor != NULL) {
5251 accessor->reportError(accessorCookie, "Color value not valid --"
5252 " must be #rgb, #argb, #rrggbb, or #aarrggbb");
5253 }
5254 #if 0
5255 fprintf(stderr, "%s: Color ID %s value %s is not valid\n",
5256 "Resource File", //(const char*)in->getPrintableSource(),
5257 String8(*curTag).string(),
5258 String8(s, len).string());
5259 #endif
5260 return false;
5261 }
5262 }
5263 }
5264
5265 if (*s == '?') {
5266 outValue->dataType = outValue->TYPE_ATTRIBUTE;
5267
5268 // Note: we don't check attrType here because the reference can
5269 // be to any other type; we just need to count on the client making
5270 // sure the referenced type is correct.
5271
5272 //printf("Looking up attr: %s\n", String8(s, len).string());
5273
5274 static const String16 attr16("attr");
5275 String16 package, type, name;
5276 if (!expandResourceRef(s+1, len-1, &package, &type, &name,
5277 &attr16, defPackage, &errorMsg)) {
5278 if (accessor != NULL) {
5279 accessor->reportError(accessorCookie, errorMsg);
5280 }
5281 return false;
5282 }
5283
5284 //printf("Pkg: %s, Type: %s, Name: %s\n",
5285 // String8(package).string(), String8(type).string(),
5286 // String8(name).string());
5287 uint32_t specFlags = 0;
Mark Salyzyn00adb862014-03-19 11:00:06 -07005288 uint32_t rid =
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005289 identifierForName(name.string(), name.size(),
5290 type.string(), type.size(),
5291 package.string(), package.size(), &specFlags);
5292 if (rid != 0) {
5293 if (enforcePrivate) {
5294 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
5295 if (accessor != NULL) {
5296 accessor->reportError(accessorCookie, "Attribute is not public.");
5297 }
5298 return false;
5299 }
5300 }
5301 if (!accessor) {
5302 outValue->data = rid;
5303 return true;
5304 }
5305 rid = Res_MAKEID(
5306 accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
5307 Res_GETTYPE(rid), Res_GETENTRY(rid));
5308 //printf("Incl %s:%s/%s: 0x%08x\n",
5309 // String8(package).string(), String8(type).string(),
5310 // String8(name).string(), rid);
5311 outValue->data = rid;
5312 return true;
5313 }
5314
5315 if (accessor) {
5316 uint32_t rid = accessor->getCustomResource(package, type, name);
5317 if (rid != 0) {
5318 //printf("Mine %s:%s/%s: 0x%08x\n",
5319 // String8(package).string(), String8(type).string(),
5320 // String8(name).string(), rid);
5321 outValue->data = rid;
5322 return true;
5323 }
5324 }
5325
5326 if (accessor != NULL) {
5327 accessor->reportError(accessorCookie, "No resource found that matches the given name");
5328 }
5329 return false;
5330 }
5331
5332 if (stringToInt(s, len, outValue)) {
5333 if ((attrType&ResTable_map::TYPE_INTEGER) == 0) {
5334 // If this type does not allow integers, but does allow floats,
5335 // fall through on this error case because the float type should
5336 // be able to accept any integer value.
5337 if (!canStringCoerce && (attrType&ResTable_map::TYPE_FLOAT) == 0) {
5338 if (accessor != NULL) {
5339 accessor->reportError(accessorCookie, "Integer types not allowed");
5340 }
5341 return false;
5342 }
5343 } else {
5344 if (((int32_t)outValue->data) < ((int32_t)attrMin)
5345 || ((int32_t)outValue->data) > ((int32_t)attrMax)) {
5346 if (accessor != NULL) {
5347 accessor->reportError(accessorCookie, "Integer value out of range");
5348 }
5349 return false;
5350 }
5351 return true;
5352 }
5353 }
5354
5355 if (stringToFloat(s, len, outValue)) {
5356 if (outValue->dataType == Res_value::TYPE_DIMENSION) {
5357 if ((attrType&ResTable_map::TYPE_DIMENSION) != 0) {
5358 return true;
5359 }
5360 if (!canStringCoerce) {
5361 if (accessor != NULL) {
5362 accessor->reportError(accessorCookie, "Dimension types not allowed");
5363 }
5364 return false;
5365 }
5366 } else if (outValue->dataType == Res_value::TYPE_FRACTION) {
5367 if ((attrType&ResTable_map::TYPE_FRACTION) != 0) {
5368 return true;
5369 }
5370 if (!canStringCoerce) {
5371 if (accessor != NULL) {
5372 accessor->reportError(accessorCookie, "Fraction types not allowed");
5373 }
5374 return false;
5375 }
5376 } else if ((attrType&ResTable_map::TYPE_FLOAT) == 0) {
5377 if (!canStringCoerce) {
5378 if (accessor != NULL) {
5379 accessor->reportError(accessorCookie, "Float types not allowed");
5380 }
5381 return false;
5382 }
5383 } else {
5384 return true;
5385 }
5386 }
5387
5388 if (len == 4) {
5389 if ((s[0] == 't' || s[0] == 'T') &&
5390 (s[1] == 'r' || s[1] == 'R') &&
5391 (s[2] == 'u' || s[2] == 'U') &&
5392 (s[3] == 'e' || s[3] == 'E')) {
5393 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
5394 if (!canStringCoerce) {
5395 if (accessor != NULL) {
5396 accessor->reportError(accessorCookie, "Boolean types not allowed");
5397 }
5398 return false;
5399 }
5400 } else {
5401 outValue->dataType = outValue->TYPE_INT_BOOLEAN;
5402 outValue->data = (uint32_t)-1;
5403 return true;
5404 }
5405 }
5406 }
5407
5408 if (len == 5) {
5409 if ((s[0] == 'f' || s[0] == 'F') &&
5410 (s[1] == 'a' || s[1] == 'A') &&
5411 (s[2] == 'l' || s[2] == 'L') &&
5412 (s[3] == 's' || s[3] == 'S') &&
5413 (s[4] == 'e' || s[4] == 'E')) {
5414 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
5415 if (!canStringCoerce) {
5416 if (accessor != NULL) {
5417 accessor->reportError(accessorCookie, "Boolean types not allowed");
5418 }
5419 return false;
5420 }
5421 } else {
5422 outValue->dataType = outValue->TYPE_INT_BOOLEAN;
5423 outValue->data = 0;
5424 return true;
5425 }
5426 }
5427 }
5428
5429 if ((attrType&ResTable_map::TYPE_ENUM) != 0) {
5430 const ssize_t p = getResourcePackageIndex(attrID);
5431 const bag_entry* bag;
5432 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
5433 //printf("Got %d for enum\n", cnt);
5434 if (cnt >= 0) {
5435 resource_name rname;
5436 while (cnt > 0) {
5437 if (!Res_INTERNALID(bag->map.name.ident)) {
5438 //printf("Trying attr #%08x\n", bag->map.name.ident);
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07005439 if (getResourceName(bag->map.name.ident, false, &rname)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005440 #if 0
5441 printf("Matching %s against %s (0x%08x)\n",
5442 String8(s, len).string(),
5443 String8(rname.name, rname.nameLen).string(),
5444 bag->map.name.ident);
5445 #endif
5446 if (strzcmp16(s, len, rname.name, rname.nameLen) == 0) {
5447 outValue->dataType = bag->map.value.dataType;
5448 outValue->data = bag->map.value.data;
5449 unlockBag(bag);
5450 return true;
5451 }
5452 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005454 }
5455 bag++;
5456 cnt--;
5457 }
5458 unlockBag(bag);
5459 }
5460
5461 if (fromAccessor) {
5462 if (accessor->getAttributeEnum(attrID, s, len, outValue)) {
5463 return true;
5464 }
5465 }
5466 }
5467
5468 if ((attrType&ResTable_map::TYPE_FLAGS) != 0) {
5469 const ssize_t p = getResourcePackageIndex(attrID);
5470 const bag_entry* bag;
5471 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
5472 //printf("Got %d for flags\n", cnt);
5473 if (cnt >= 0) {
5474 bool failed = false;
5475 resource_name rname;
5476 outValue->dataType = Res_value::TYPE_INT_HEX;
5477 outValue->data = 0;
5478 const char16_t* end = s + len;
5479 const char16_t* pos = s;
5480 while (pos < end && !failed) {
5481 const char16_t* start = pos;
The Android Open Source Project4df24232009-03-05 14:34:35 -08005482 pos++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005483 while (pos < end && *pos != '|') {
5484 pos++;
5485 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08005486 //printf("Looking for: %s\n", String8(start, pos-start).string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005487 const bag_entry* bagi = bag;
The Android Open Source Project4df24232009-03-05 14:34:35 -08005488 ssize_t i;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005489 for (i=0; i<cnt; i++, bagi++) {
5490 if (!Res_INTERNALID(bagi->map.name.ident)) {
5491 //printf("Trying attr #%08x\n", bagi->map.name.ident);
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07005492 if (getResourceName(bagi->map.name.ident, false, &rname)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005493 #if 0
5494 printf("Matching %s against %s (0x%08x)\n",
5495 String8(start,pos-start).string(),
5496 String8(rname.name, rname.nameLen).string(),
5497 bagi->map.name.ident);
5498 #endif
5499 if (strzcmp16(start, pos-start, rname.name, rname.nameLen) == 0) {
5500 outValue->data |= bagi->map.value.data;
5501 break;
5502 }
5503 }
5504 }
5505 }
5506 if (i >= cnt) {
5507 // Didn't find this flag identifier.
5508 failed = true;
5509 }
5510 if (pos < end) {
5511 pos++;
5512 }
5513 }
5514 unlockBag(bag);
5515 if (!failed) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08005516 //printf("Final flag value: 0x%lx\n", outValue->data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005517 return true;
5518 }
5519 }
5520
5521
5522 if (fromAccessor) {
5523 if (accessor->getAttributeFlags(attrID, s, len, outValue)) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08005524 //printf("Final flag value: 0x%lx\n", outValue->data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005525 return true;
5526 }
5527 }
5528 }
5529
5530 if ((attrType&ResTable_map::TYPE_STRING) == 0) {
5531 if (accessor != NULL) {
5532 accessor->reportError(accessorCookie, "String types not allowed");
5533 }
5534 return false;
5535 }
5536
5537 // Generic string handling...
5538 outValue->dataType = outValue->TYPE_STRING;
5539 if (outString) {
5540 bool failed = collectString(outString, s, len, preserveSpaces, &errorMsg);
5541 if (accessor != NULL) {
5542 accessor->reportError(accessorCookie, errorMsg);
5543 }
5544 return failed;
5545 }
5546
5547 return true;
5548}
5549
5550bool ResTable::collectString(String16* outString,
5551 const char16_t* s, size_t len,
5552 bool preserveSpaces,
5553 const char** outErrorMsg,
5554 bool append)
5555{
5556 String16 tmp;
5557
5558 char quoted = 0;
5559 const char16_t* p = s;
5560 while (p < (s+len)) {
5561 while (p < (s+len)) {
5562 const char16_t c = *p;
5563 if (c == '\\') {
5564 break;
5565 }
5566 if (!preserveSpaces) {
5567 if (quoted == 0 && isspace16(c)
5568 && (c != ' ' || isspace16(*(p+1)))) {
5569 break;
5570 }
5571 if (c == '"' && (quoted == 0 || quoted == '"')) {
5572 break;
5573 }
5574 if (c == '\'' && (quoted == 0 || quoted == '\'')) {
Eric Fischerc87d2522009-09-01 15:20:30 -07005575 /*
5576 * In practice, when people write ' instead of \'
5577 * in a string, they are doing it by accident
5578 * instead of really meaning to use ' as a quoting
5579 * character. Warn them so they don't lose it.
5580 */
5581 if (outErrorMsg) {
5582 *outErrorMsg = "Apostrophe not preceded by \\";
5583 }
5584 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005585 }
5586 }
5587 p++;
5588 }
5589 if (p < (s+len)) {
5590 if (p > s) {
5591 tmp.append(String16(s, p-s));
5592 }
5593 if (!preserveSpaces && (*p == '"' || *p == '\'')) {
5594 if (quoted == 0) {
5595 quoted = *p;
5596 } else {
5597 quoted = 0;
5598 }
5599 p++;
5600 } else if (!preserveSpaces && isspace16(*p)) {
5601 // Space outside of a quote -- consume all spaces and
5602 // leave a single plain space char.
5603 tmp.append(String16(" "));
5604 p++;
5605 while (p < (s+len) && isspace16(*p)) {
5606 p++;
5607 }
5608 } else if (*p == '\\') {
5609 p++;
5610 if (p < (s+len)) {
5611 switch (*p) {
5612 case 't':
5613 tmp.append(String16("\t"));
5614 break;
5615 case 'n':
5616 tmp.append(String16("\n"));
5617 break;
5618 case '#':
5619 tmp.append(String16("#"));
5620 break;
5621 case '@':
5622 tmp.append(String16("@"));
5623 break;
5624 case '?':
5625 tmp.append(String16("?"));
5626 break;
5627 case '"':
5628 tmp.append(String16("\""));
5629 break;
5630 case '\'':
5631 tmp.append(String16("'"));
5632 break;
5633 case '\\':
5634 tmp.append(String16("\\"));
5635 break;
5636 case 'u':
5637 {
5638 char16_t chr = 0;
5639 int i = 0;
5640 while (i < 4 && p[1] != 0) {
5641 p++;
5642 i++;
5643 int c;
5644 if (*p >= '0' && *p <= '9') {
5645 c = *p - '0';
5646 } else if (*p >= 'a' && *p <= 'f') {
5647 c = *p - 'a' + 10;
5648 } else if (*p >= 'A' && *p <= 'F') {
5649 c = *p - 'A' + 10;
5650 } else {
5651 if (outErrorMsg) {
5652 *outErrorMsg = "Bad character in \\u unicode escape sequence";
5653 }
5654 return false;
5655 }
5656 chr = (chr<<4) | c;
5657 }
5658 tmp.append(String16(&chr, 1));
5659 } break;
5660 default:
5661 // ignore unknown escape chars.
5662 break;
5663 }
5664 p++;
5665 }
5666 }
5667 len -= (p-s);
5668 s = p;
5669 }
5670 }
5671
5672 if (tmp.size() != 0) {
5673 if (len > 0) {
5674 tmp.append(String16(s, len));
5675 }
5676 if (append) {
5677 outString->append(tmp);
5678 } else {
5679 outString->setTo(tmp);
5680 }
5681 } else {
5682 if (append) {
5683 outString->append(String16(s, len));
5684 } else {
5685 outString->setTo(s, len);
5686 }
5687 }
5688
5689 return true;
5690}
5691
5692size_t ResTable::getBasePackageCount() const
5693{
5694 if (mError != NO_ERROR) {
5695 return 0;
5696 }
5697 return mPackageGroups.size();
5698}
5699
Adam Lesinskide898ff2014-01-29 18:20:45 -08005700const String16 ResTable::getBasePackageName(size_t idx) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005701{
5702 if (mError != NO_ERROR) {
Adam Lesinskide898ff2014-01-29 18:20:45 -08005703 return String16();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005704 }
5705 LOG_FATAL_IF(idx >= mPackageGroups.size(),
5706 "Requested package index %d past package count %d",
5707 (int)idx, (int)mPackageGroups.size());
Adam Lesinskide898ff2014-01-29 18:20:45 -08005708 return mPackageGroups[idx]->name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005709}
5710
5711uint32_t ResTable::getBasePackageId(size_t idx) const
5712{
5713 if (mError != NO_ERROR) {
5714 return 0;
5715 }
5716 LOG_FATAL_IF(idx >= mPackageGroups.size(),
5717 "Requested package index %d past package count %d",
5718 (int)idx, (int)mPackageGroups.size());
5719 return mPackageGroups[idx]->id;
5720}
5721
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005722uint32_t ResTable::getLastTypeIdForPackage(size_t idx) const
5723{
5724 if (mError != NO_ERROR) {
5725 return 0;
5726 }
5727 LOG_FATAL_IF(idx >= mPackageGroups.size(),
5728 "Requested package index %d past package count %d",
5729 (int)idx, (int)mPackageGroups.size());
5730 const PackageGroup* const group = mPackageGroups[idx];
5731 return group->largestTypeId;
5732}
5733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005734size_t ResTable::getTableCount() const
5735{
5736 return mHeaders.size();
5737}
5738
5739const ResStringPool* ResTable::getTableStringBlock(size_t index) const
5740{
5741 return &mHeaders[index]->values;
5742}
5743
Narayan Kamath7c4887f2014-01-27 17:32:37 +00005744int32_t ResTable::getTableCookie(size_t index) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005745{
5746 return mHeaders[index]->cookie;
5747}
5748
Adam Lesinskide898ff2014-01-29 18:20:45 -08005749const DynamicRefTable* ResTable::getDynamicRefTableForCookie(int32_t cookie) const
5750{
5751 const size_t N = mPackageGroups.size();
5752 for (size_t i = 0; i < N; i++) {
5753 const PackageGroup* pg = mPackageGroups[i];
5754 size_t M = pg->packages.size();
5755 for (size_t j = 0; j < M; j++) {
5756 if (pg->packages[j]->header->cookie == cookie) {
5757 return &pg->dynamicRefTable;
5758 }
5759 }
5760 }
5761 return NULL;
5762}
5763
Filip Gruszczynski23493322015-07-29 17:02:59 -07005764void ResTable::getConfigurations(Vector<ResTable_config>* configs, bool ignoreMipmap,
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08005765 bool ignoreAndroidPackage, bool includeSystemConfigs) const {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005766 const size_t packageCount = mPackageGroups.size();
Filip Gruszczynski23493322015-07-29 17:02:59 -07005767 String16 android("android");
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005768 for (size_t i = 0; i < packageCount; i++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005769 const PackageGroup* packageGroup = mPackageGroups[i];
Filip Gruszczynski23493322015-07-29 17:02:59 -07005770 if (ignoreAndroidPackage && android == packageGroup->name) {
5771 continue;
5772 }
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08005773 if (!includeSystemConfigs && packageGroup->isSystemAsset) {
5774 continue;
5775 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005776 const size_t typeCount = packageGroup->types.size();
5777 for (size_t j = 0; j < typeCount; j++) {
5778 const TypeList& typeList = packageGroup->types[j];
5779 const size_t numTypes = typeList.size();
5780 for (size_t k = 0; k < numTypes; k++) {
5781 const Type* type = typeList[k];
Adam Lesinski42eea272015-01-15 17:01:39 -08005782 const ResStringPool& typeStrings = type->package->typeStrings;
5783 if (ignoreMipmap && typeStrings.string8ObjectAt(
5784 type->typeSpec->id - 1) == "mipmap") {
5785 continue;
5786 }
5787
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005788 const size_t numConfigs = type->configs.size();
5789 for (size_t m = 0; m < numConfigs; m++) {
5790 const ResTable_type* config = type->configs[m];
Narayan Kamath788fa412014-01-21 15:32:36 +00005791 ResTable_config cfg;
5792 memset(&cfg, 0, sizeof(ResTable_config));
5793 cfg.copyFromDtoH(config->config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005794 // only insert unique
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005795 const size_t N = configs->size();
5796 size_t n;
5797 for (n = 0; n < N; n++) {
5798 if (0 == (*configs)[n].compare(cfg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005799 break;
5800 }
5801 }
5802 // if we didn't find it
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005803 if (n == N) {
Narayan Kamath788fa412014-01-21 15:32:36 +00005804 configs->add(cfg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005805 }
5806 }
5807 }
5808 }
5809 }
5810}
5811
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08005812void ResTable::getLocales(Vector<String8>* locales, bool includeSystemLocales) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005813{
5814 Vector<ResTable_config> configs;
Steve Block71f2cf12011-10-20 11:56:00 +01005815 ALOGV("calling getConfigurations");
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08005816 getConfigurations(&configs,
5817 false /* ignoreMipmap */,
5818 false /* ignoreAndroidPackage */,
5819 includeSystemLocales /* includeSystemConfigs */);
Steve Block71f2cf12011-10-20 11:56:00 +01005820 ALOGV("called getConfigurations size=%d", (int)configs.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005821 const size_t I = configs.size();
Narayan Kamath48620f12014-01-20 13:57:11 +00005822
5823 char locale[RESTABLE_MAX_LOCALE_LEN];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005824 for (size_t i=0; i<I; i++) {
Narayan Kamath788fa412014-01-21 15:32:36 +00005825 configs[i].getBcp47Locale(locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005826 const size_t J = locales->size();
5827 size_t j;
5828 for (j=0; j<J; j++) {
5829 if (0 == strcmp(locale, (*locales)[j].string())) {
5830 break;
5831 }
5832 }
5833 if (j == J) {
5834 locales->add(String8(locale));
5835 }
5836 }
5837}
5838
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005839StringPoolRef::StringPoolRef(const ResStringPool* pool, uint32_t index)
5840 : mPool(pool), mIndex(index) {}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005841
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005842StringPoolRef::StringPoolRef()
5843 : mPool(NULL), mIndex(0) {}
5844
5845const char* StringPoolRef::string8(size_t* outLen) const {
5846 if (mPool != NULL) {
5847 return mPool->string8At(mIndex, outLen);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005848 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005849 if (outLen != NULL) {
5850 *outLen = 0;
5851 }
5852 return NULL;
5853}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005854
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005855const char16_t* StringPoolRef::string16(size_t* outLen) const {
5856 if (mPool != NULL) {
5857 return mPool->stringAt(mIndex, outLen);
5858 }
5859 if (outLen != NULL) {
5860 *outLen = 0;
5861 }
5862 return NULL;
5863}
5864
Adam Lesinski82a2dd82014-09-17 18:34:15 -07005865bool ResTable::getResourceFlags(uint32_t resID, uint32_t* outFlags) const {
5866 if (mError != NO_ERROR) {
5867 return false;
5868 }
5869
5870 const ssize_t p = getResourcePackageIndex(resID);
5871 const int t = Res_GETTYPE(resID);
5872 const int e = Res_GETENTRY(resID);
5873
5874 if (p < 0) {
5875 if (Res_GETPACKAGE(resID)+1 == 0) {
5876 ALOGW("No package identifier when getting flags for resource number 0x%08x", resID);
5877 } else {
5878 ALOGW("No known package when getting flags for resource number 0x%08x", resID);
5879 }
5880 return false;
5881 }
5882 if (t < 0) {
5883 ALOGW("No type identifier when getting flags for resource number 0x%08x", resID);
5884 return false;
5885 }
5886
5887 const PackageGroup* const grp = mPackageGroups[p];
5888 if (grp == NULL) {
5889 ALOGW("Bad identifier when getting flags for resource number 0x%08x", resID);
5890 return false;
5891 }
5892
5893 Entry entry;
5894 status_t err = getEntry(grp, t, e, NULL, &entry);
5895 if (err != NO_ERROR) {
5896 return false;
5897 }
5898
5899 *outFlags = entry.specFlags;
5900 return true;
5901}
5902
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005903status_t ResTable::getEntry(
5904 const PackageGroup* packageGroup, int typeIndex, int entryIndex,
5905 const ResTable_config* config,
5906 Entry* outEntry) const
5907{
5908 const TypeList& typeList = packageGroup->types[typeIndex];
5909 if (typeList.isEmpty()) {
5910 ALOGV("Skipping entry type index 0x%02x because type is NULL!\n", typeIndex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005911 return BAD_TYPE;
5912 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005913
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005914 const ResTable_type* bestType = NULL;
5915 uint32_t bestOffset = ResTable_type::NO_ENTRY;
5916 const Package* bestPackage = NULL;
5917 uint32_t specFlags = 0;
5918 uint8_t actualTypeIndex = typeIndex;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005919 ResTable_config bestConfig;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005920 memset(&bestConfig, 0, sizeof(bestConfig));
Mark Salyzyn00adb862014-03-19 11:00:06 -07005921
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005922 // Iterate over the Types of each package.
5923 const size_t typeCount = typeList.size();
5924 for (size_t i = 0; i < typeCount; i++) {
5925 const Type* const typeSpec = typeList[i];
Mark Salyzyn00adb862014-03-19 11:00:06 -07005926
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005927 int realEntryIndex = entryIndex;
5928 int realTypeIndex = typeIndex;
5929 bool currentTypeIsOverlay = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005930
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005931 // Runtime overlay packages provide a mapping of app resource
5932 // ID to package resource ID.
5933 if (typeSpec->idmapEntries.hasEntries()) {
5934 uint16_t overlayEntryIndex;
5935 if (typeSpec->idmapEntries.lookup(entryIndex, &overlayEntryIndex) != NO_ERROR) {
5936 // No such mapping exists
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005937 continue;
5938 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005939 realEntryIndex = overlayEntryIndex;
5940 realTypeIndex = typeSpec->idmapEntries.overlayTypeId() - 1;
5941 currentTypeIsOverlay = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005942 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005943
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005944 if (static_cast<size_t>(realEntryIndex) >= typeSpec->entryCount) {
5945 ALOGW("For resource 0x%08x, entry index(%d) is beyond type entryCount(%d)",
5946 Res_MAKEID(packageGroup->id - 1, typeIndex, entryIndex),
5947 entryIndex, static_cast<int>(typeSpec->entryCount));
5948 // We should normally abort here, but some legacy apps declare
5949 // resources in the 'android' package (old bug in AAPT).
5950 continue;
5951 }
5952
5953 // Aggregate all the flags for each package that defines this entry.
5954 if (typeSpec->typeSpecFlags != NULL) {
5955 specFlags |= dtohl(typeSpec->typeSpecFlags[realEntryIndex]);
5956 } else {
5957 specFlags = -1;
5958 }
5959
5960 const size_t numConfigs = typeSpec->configs.size();
5961 for (size_t c = 0; c < numConfigs; c++) {
5962 const ResTable_type* const thisType = typeSpec->configs[c];
5963 if (thisType == NULL) {
5964 continue;
5965 }
5966
5967 ResTable_config thisConfig;
5968 thisConfig.copyFromDtoH(thisType->config);
5969
5970 // Check to make sure this one is valid for the current parameters.
5971 if (config != NULL && !thisConfig.match(*config)) {
5972 continue;
5973 }
5974
5975 // Check if there is the desired entry in this type.
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005976 const uint32_t* const eindex = reinterpret_cast<const uint32_t*>(
5977 reinterpret_cast<const uint8_t*>(thisType) + dtohs(thisType->header.headerSize));
5978
5979 uint32_t thisOffset = dtohl(eindex[realEntryIndex]);
5980 if (thisOffset == ResTable_type::NO_ENTRY) {
5981 // There is no entry for this index and configuration.
5982 continue;
5983 }
5984
5985 if (bestType != NULL) {
5986 // Check if this one is less specific than the last found. If so,
5987 // we will skip it. We check starting with things we most care
5988 // about to those we least care about.
5989 if (!thisConfig.isBetterThan(bestConfig, config)) {
5990 if (!currentTypeIsOverlay || thisConfig.compare(bestConfig) != 0) {
5991 continue;
5992 }
5993 }
5994 }
5995
5996 bestType = thisType;
5997 bestOffset = thisOffset;
5998 bestConfig = thisConfig;
5999 bestPackage = typeSpec->package;
6000 actualTypeIndex = realTypeIndex;
6001
6002 // If no config was specified, any type will do, so skip
6003 if (config == NULL) {
6004 break;
6005 }
6006 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006007 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006008
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006009 if (bestType == NULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006010 return BAD_INDEX;
6011 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006012
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006013 bestOffset += dtohl(bestType->entriesStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006014
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006015 if (bestOffset > (dtohl(bestType->header.size)-sizeof(ResTable_entry))) {
Steve Block8564c8d2012-01-05 23:22:43 +00006016 ALOGW("ResTable_entry at 0x%x is beyond type chunk data 0x%x",
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006017 bestOffset, dtohl(bestType->header.size));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006018 return BAD_TYPE;
6019 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006020 if ((bestOffset & 0x3) != 0) {
6021 ALOGW("ResTable_entry at 0x%x is not on an integer boundary", bestOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006022 return BAD_TYPE;
6023 }
6024
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006025 const ResTable_entry* const entry = reinterpret_cast<const ResTable_entry*>(
6026 reinterpret_cast<const uint8_t*>(bestType) + bestOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006027 if (dtohs(entry->size) < sizeof(*entry)) {
Steve Block8564c8d2012-01-05 23:22:43 +00006028 ALOGW("ResTable_entry size 0x%x is too small", dtohs(entry->size));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006029 return BAD_TYPE;
6030 }
6031
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006032 if (outEntry != NULL) {
6033 outEntry->entry = entry;
6034 outEntry->config = bestConfig;
6035 outEntry->type = bestType;
6036 outEntry->specFlags = specFlags;
6037 outEntry->package = bestPackage;
6038 outEntry->typeStr = StringPoolRef(&bestPackage->typeStrings, actualTypeIndex - bestPackage->typeIdOffset);
6039 outEntry->keyStr = StringPoolRef(&bestPackage->keyStrings, dtohl(entry->key.index));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006040 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006041 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006042}
6043
6044status_t ResTable::parsePackage(const ResTable_package* const pkg,
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08006045 const Header* const header, bool appAsLib, bool isSystemAsset)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006046{
6047 const uint8_t* base = (const uint8_t*)pkg;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006048 status_t err = validate_chunk(&pkg->header, sizeof(*pkg) - sizeof(pkg->typeIdOffset),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006049 header->dataEnd, "ResTable_package");
6050 if (err != NO_ERROR) {
6051 return (mError=err);
6052 }
6053
Patrik Bannura443dd932014-02-12 13:38:54 +01006054 const uint32_t pkgSize = dtohl(pkg->header.size);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006055
6056 if (dtohl(pkg->typeStrings) >= pkgSize) {
Patrik Bannura443dd932014-02-12 13:38:54 +01006057 ALOGW("ResTable_package type strings at 0x%x are past chunk size 0x%x.",
6058 dtohl(pkg->typeStrings), pkgSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006059 return (mError=BAD_TYPE);
6060 }
6061 if ((dtohl(pkg->typeStrings)&0x3) != 0) {
Patrik Bannura443dd932014-02-12 13:38:54 +01006062 ALOGW("ResTable_package type strings at 0x%x is not on an integer boundary.",
6063 dtohl(pkg->typeStrings));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006064 return (mError=BAD_TYPE);
6065 }
6066 if (dtohl(pkg->keyStrings) >= pkgSize) {
Patrik Bannura443dd932014-02-12 13:38:54 +01006067 ALOGW("ResTable_package key strings at 0x%x are past chunk size 0x%x.",
6068 dtohl(pkg->keyStrings), pkgSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006069 return (mError=BAD_TYPE);
6070 }
6071 if ((dtohl(pkg->keyStrings)&0x3) != 0) {
Patrik Bannura443dd932014-02-12 13:38:54 +01006072 ALOGW("ResTable_package key strings at 0x%x is not on an integer boundary.",
6073 dtohl(pkg->keyStrings));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006074 return (mError=BAD_TYPE);
6075 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006076
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006077 uint32_t id = dtohl(pkg->id);
6078 KeyedVector<uint8_t, IdmapEntries> idmapEntries;
Mark Salyzyn00adb862014-03-19 11:00:06 -07006079
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006080 if (header->resourceIDMap != NULL) {
6081 uint8_t targetPackageId = 0;
6082 status_t err = parseIdmap(header->resourceIDMap, header->resourceIDMapSize, &targetPackageId, &idmapEntries);
6083 if (err != NO_ERROR) {
6084 ALOGW("Overlay is broken");
6085 return (mError=err);
6086 }
6087 id = targetPackageId;
6088 }
6089
6090 if (id >= 256) {
6091 LOG_ALWAYS_FATAL("Package id out of range");
6092 return NO_ERROR;
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08006093 } else if (id == 0 || appAsLib || isSystemAsset) {
6094 // This is a library or a system asset, so assign an ID
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006095 id = mNextPackageId++;
6096 }
6097
6098 PackageGroup* group = NULL;
6099 Package* package = new Package(this, header, pkg);
6100 if (package == NULL) {
6101 return (mError=NO_MEMORY);
6102 }
6103
6104 err = package->typeStrings.setTo(base+dtohl(pkg->typeStrings),
6105 header->dataEnd-(base+dtohl(pkg->typeStrings)));
6106 if (err != NO_ERROR) {
6107 delete group;
6108 delete package;
6109 return (mError=err);
6110 }
6111
6112 err = package->keyStrings.setTo(base+dtohl(pkg->keyStrings),
6113 header->dataEnd-(base+dtohl(pkg->keyStrings)));
6114 if (err != NO_ERROR) {
6115 delete group;
6116 delete package;
6117 return (mError=err);
6118 }
6119
6120 size_t idx = mPackageMap[id];
6121 if (idx == 0) {
6122 idx = mPackageGroups.size() + 1;
6123
Adam Lesinski4bf58102014-11-03 11:21:19 -08006124 char16_t tmpName[sizeof(pkg->name)/sizeof(pkg->name[0])];
6125 strcpy16_dtoh(tmpName, pkg->name, sizeof(pkg->name)/sizeof(pkg->name[0]));
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08006126 group = new PackageGroup(this, String16(tmpName), id, appAsLib, isSystemAsset);
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006127 if (group == NULL) {
6128 delete package;
Dianne Hackborn78c40512009-07-06 11:07:40 -07006129 return (mError=NO_MEMORY);
6130 }
Adam Lesinskifab50872014-04-16 14:40:42 -07006131
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006132 err = mPackageGroups.add(group);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006133 if (err < NO_ERROR) {
6134 return (mError=err);
6135 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006136
6137 mPackageMap[id] = static_cast<uint8_t>(idx);
6138
6139 // Find all packages that reference this package
6140 size_t N = mPackageGroups.size();
6141 for (size_t i = 0; i < N; i++) {
6142 mPackageGroups[i]->dynamicRefTable.addMapping(
6143 group->name, static_cast<uint8_t>(group->id));
6144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006145 } else {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006146 group = mPackageGroups.itemAt(idx - 1);
6147 if (group == NULL) {
6148 return (mError=UNKNOWN_ERROR);
6149 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006150 }
6151
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006152 err = group->packages.add(package);
6153 if (err < NO_ERROR) {
6154 return (mError=err);
6155 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006157 // Iterate through all chunks.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006158 const ResChunk_header* chunk =
6159 (const ResChunk_header*)(((const uint8_t*)pkg)
6160 + dtohs(pkg->header.headerSize));
6161 const uint8_t* endPos = ((const uint8_t*)pkg) + dtohs(pkg->header.size);
6162 while (((const uint8_t*)chunk) <= (endPos-sizeof(ResChunk_header)) &&
6163 ((const uint8_t*)chunk) <= (endPos-dtohl(chunk->size))) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07006164 if (kDebugTableNoisy) {
6165 ALOGV("PackageChunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n",
6166 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
6167 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)));
6168 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006169 const size_t csize = dtohl(chunk->size);
6170 const uint16_t ctype = dtohs(chunk->type);
6171 if (ctype == RES_TABLE_TYPE_SPEC_TYPE) {
6172 const ResTable_typeSpec* typeSpec = (const ResTable_typeSpec*)(chunk);
6173 err = validate_chunk(&typeSpec->header, sizeof(*typeSpec),
6174 endPos, "ResTable_typeSpec");
6175 if (err != NO_ERROR) {
6176 return (mError=err);
6177 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006179 const size_t typeSpecSize = dtohl(typeSpec->header.size);
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006180 const size_t newEntryCount = dtohl(typeSpec->entryCount);
Mark Salyzyn00adb862014-03-19 11:00:06 -07006181
Andreas Gampe2204f0b2014-10-21 23:04:54 -07006182 if (kDebugLoadTableNoisy) {
6183 ALOGI("TypeSpec off %p: type=0x%x, headerSize=0x%x, size=%p\n",
6184 (void*)(base-(const uint8_t*)chunk),
6185 dtohs(typeSpec->header.type),
6186 dtohs(typeSpec->header.headerSize),
6187 (void*)typeSpecSize);
6188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006189 // look for block overrun or int overflow when multiplying by 4
6190 if ((dtohl(typeSpec->entryCount) > (INT32_MAX/sizeof(uint32_t))
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006191 || dtohs(typeSpec->header.headerSize)+(sizeof(uint32_t)*newEntryCount)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006192 > typeSpecSize)) {
Steve Block8564c8d2012-01-05 23:22:43 +00006193 ALOGW("ResTable_typeSpec entry index to %p extends beyond chunk end %p.",
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006194 (void*)(dtohs(typeSpec->header.headerSize) + (sizeof(uint32_t)*newEntryCount)),
6195 (void*)typeSpecSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006196 return (mError=BAD_TYPE);
6197 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006199 if (typeSpec->id == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00006200 ALOGW("ResTable_type has an id of 0.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006201 return (mError=BAD_TYPE);
6202 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006203
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006204 if (newEntryCount > 0) {
6205 uint8_t typeIndex = typeSpec->id - 1;
6206 ssize_t idmapIndex = idmapEntries.indexOfKey(typeSpec->id);
6207 if (idmapIndex >= 0) {
6208 typeIndex = idmapEntries[idmapIndex].targetTypeId() - 1;
6209 }
6210
6211 TypeList& typeList = group->types.editItemAt(typeIndex);
6212 if (!typeList.isEmpty()) {
6213 const Type* existingType = typeList[0];
6214 if (existingType->entryCount != newEntryCount && idmapIndex < 0) {
6215 ALOGW("ResTable_typeSpec entry count inconsistent: given %d, previously %d",
6216 (int) newEntryCount, (int) existingType->entryCount);
6217 // We should normally abort here, but some legacy apps declare
6218 // resources in the 'android' package (old bug in AAPT).
6219 }
6220 }
6221
6222 Type* t = new Type(header, package, newEntryCount);
6223 t->typeSpec = typeSpec;
6224 t->typeSpecFlags = (const uint32_t*)(
6225 ((const uint8_t*)typeSpec) + dtohs(typeSpec->header.headerSize));
6226 if (idmapIndex >= 0) {
6227 t->idmapEntries = idmapEntries[idmapIndex];
6228 }
6229 typeList.add(t);
6230 group->largestTypeId = max(group->largestTypeId, typeSpec->id);
6231 } else {
6232 ALOGV("Skipping empty ResTable_typeSpec for type %d", typeSpec->id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006233 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006235 } else if (ctype == RES_TABLE_TYPE_TYPE) {
6236 const ResTable_type* type = (const ResTable_type*)(chunk);
6237 err = validate_chunk(&type->header, sizeof(*type)-sizeof(ResTable_config)+4,
6238 endPos, "ResTable_type");
6239 if (err != NO_ERROR) {
6240 return (mError=err);
6241 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006242
Patrik Bannura443dd932014-02-12 13:38:54 +01006243 const uint32_t typeSize = dtohl(type->header.size);
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006244 const size_t newEntryCount = dtohl(type->entryCount);
Mark Salyzyn00adb862014-03-19 11:00:06 -07006245
Andreas Gampe2204f0b2014-10-21 23:04:54 -07006246 if (kDebugLoadTableNoisy) {
6247 printf("Type off %p: type=0x%x, headerSize=0x%x, size=%u\n",
6248 (void*)(base-(const uint8_t*)chunk),
6249 dtohs(type->header.type),
6250 dtohs(type->header.headerSize),
6251 typeSize);
6252 }
6253 if (dtohs(type->header.headerSize)+(sizeof(uint32_t)*newEntryCount) > typeSize) {
Patrik Bannura443dd932014-02-12 13:38:54 +01006254 ALOGW("ResTable_type entry index to %p extends beyond chunk end 0x%x.",
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006255 (void*)(dtohs(type->header.headerSize) + (sizeof(uint32_t)*newEntryCount)),
6256 typeSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006257 return (mError=BAD_TYPE);
6258 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006259
6260 if (newEntryCount != 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006261 && dtohl(type->entriesStart) > (typeSize-sizeof(ResTable_entry))) {
Patrik Bannura443dd932014-02-12 13:38:54 +01006262 ALOGW("ResTable_type entriesStart at 0x%x extends beyond chunk end 0x%x.",
6263 dtohl(type->entriesStart), typeSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006264 return (mError=BAD_TYPE);
6265 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006267 if (type->id == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00006268 ALOGW("ResTable_type has an id of 0.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006269 return (mError=BAD_TYPE);
6270 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006271
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006272 if (newEntryCount > 0) {
6273 uint8_t typeIndex = type->id - 1;
6274 ssize_t idmapIndex = idmapEntries.indexOfKey(type->id);
6275 if (idmapIndex >= 0) {
6276 typeIndex = idmapEntries[idmapIndex].targetTypeId() - 1;
6277 }
6278
6279 TypeList& typeList = group->types.editItemAt(typeIndex);
6280 if (typeList.isEmpty()) {
6281 ALOGE("No TypeSpec for type %d", type->id);
6282 return (mError=BAD_TYPE);
6283 }
6284
6285 Type* t = typeList.editItemAt(typeList.size() - 1);
6286 if (newEntryCount != t->entryCount) {
6287 ALOGE("ResTable_type entry count inconsistent: given %d, previously %d",
6288 (int)newEntryCount, (int)t->entryCount);
6289 return (mError=BAD_TYPE);
6290 }
6291
6292 if (t->package != package) {
6293 ALOGE("No TypeSpec for type %d", type->id);
6294 return (mError=BAD_TYPE);
6295 }
6296
6297 t->configs.add(type);
6298
Andreas Gampe2204f0b2014-10-21 23:04:54 -07006299 if (kDebugTableGetEntry) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006300 ResTable_config thisConfig;
6301 thisConfig.copyFromDtoH(type->config);
Andreas Gampe2204f0b2014-10-21 23:04:54 -07006302 ALOGI("Adding config to type %d: %s\n", type->id,
6303 thisConfig.toString().string());
6304 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006305 } else {
6306 ALOGV("Skipping empty ResTable_type for type %d", type->id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006307 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006308
Adam Lesinskide898ff2014-01-29 18:20:45 -08006309 } else if (ctype == RES_TABLE_LIBRARY_TYPE) {
6310 if (group->dynamicRefTable.entries().size() == 0) {
6311 status_t err = group->dynamicRefTable.load((const ResTable_lib_header*) chunk);
6312 if (err != NO_ERROR) {
6313 return (mError=err);
6314 }
6315
6316 // Fill in the reference table with the entries we already know about.
6317 size_t N = mPackageGroups.size();
6318 for (size_t i = 0; i < N; i++) {
6319 group->dynamicRefTable.addMapping(mPackageGroups[i]->name, mPackageGroups[i]->id);
6320 }
6321 } else {
6322 ALOGW("Found multiple library tables, ignoring...");
6323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006324 } else {
6325 status_t err = validate_chunk(chunk, sizeof(ResChunk_header),
6326 endPos, "ResTable_package:unknown");
6327 if (err != NO_ERROR) {
6328 return (mError=err);
6329 }
6330 }
6331 chunk = (const ResChunk_header*)
6332 (((const uint8_t*)chunk) + csize);
6333 }
6334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006335 return NO_ERROR;
6336}
6337
Tao Baia6d7e3f2015-09-01 18:49:54 -07006338DynamicRefTable::DynamicRefTable(uint8_t packageId, bool appAsLib)
Adam Lesinskide898ff2014-01-29 18:20:45 -08006339 : mAssignedPackageId(packageId)
Tao Baia6d7e3f2015-09-01 18:49:54 -07006340 , mAppAsLib(appAsLib)
Adam Lesinskide898ff2014-01-29 18:20:45 -08006341{
6342 memset(mLookupTable, 0, sizeof(mLookupTable));
6343
6344 // Reserved package ids
6345 mLookupTable[APP_PACKAGE_ID] = APP_PACKAGE_ID;
6346 mLookupTable[SYS_PACKAGE_ID] = SYS_PACKAGE_ID;
6347}
6348
6349status_t DynamicRefTable::load(const ResTable_lib_header* const header)
6350{
6351 const uint32_t entryCount = dtohl(header->count);
6352 const uint32_t sizeOfEntries = sizeof(ResTable_lib_entry) * entryCount;
6353 const uint32_t expectedSize = dtohl(header->header.size) - dtohl(header->header.headerSize);
6354 if (sizeOfEntries > expectedSize) {
6355 ALOGE("ResTable_lib_header size %u is too small to fit %u entries (x %u).",
6356 expectedSize, entryCount, (uint32_t)sizeof(ResTable_lib_entry));
6357 return UNKNOWN_ERROR;
6358 }
6359
6360 const ResTable_lib_entry* entry = (const ResTable_lib_entry*)(((uint8_t*) header) +
6361 dtohl(header->header.headerSize));
6362 for (uint32_t entryIndex = 0; entryIndex < entryCount; entryIndex++) {
6363 uint32_t packageId = dtohl(entry->packageId);
6364 char16_t tmpName[sizeof(entry->packageName) / sizeof(char16_t)];
6365 strcpy16_dtoh(tmpName, entry->packageName, sizeof(entry->packageName) / sizeof(char16_t));
Andreas Gampe2204f0b2014-10-21 23:04:54 -07006366 if (kDebugLibNoisy) {
6367 ALOGV("Found lib entry %s with id %d\n", String8(tmpName).string(),
6368 dtohl(entry->packageId));
6369 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08006370 if (packageId >= 256) {
6371 ALOGE("Bad package id 0x%08x", packageId);
6372 return UNKNOWN_ERROR;
6373 }
6374 mEntries.replaceValueFor(String16(tmpName), (uint8_t) packageId);
6375 entry = entry + 1;
6376 }
6377 return NO_ERROR;
6378}
6379
Adam Lesinski6022deb2014-08-20 14:59:19 -07006380status_t DynamicRefTable::addMappings(const DynamicRefTable& other) {
6381 if (mAssignedPackageId != other.mAssignedPackageId) {
6382 return UNKNOWN_ERROR;
6383 }
6384
6385 const size_t entryCount = other.mEntries.size();
6386 for (size_t i = 0; i < entryCount; i++) {
6387 ssize_t index = mEntries.indexOfKey(other.mEntries.keyAt(i));
6388 if (index < 0) {
6389 mEntries.add(other.mEntries.keyAt(i), other.mEntries[i]);
6390 } else {
6391 if (other.mEntries[i] != mEntries[index]) {
6392 return UNKNOWN_ERROR;
6393 }
6394 }
6395 }
6396
6397 // Merge the lookup table. No entry can conflict
6398 // (value of 0 means not set).
6399 for (size_t i = 0; i < 256; i++) {
6400 if (mLookupTable[i] != other.mLookupTable[i]) {
6401 if (mLookupTable[i] == 0) {
6402 mLookupTable[i] = other.mLookupTable[i];
6403 } else if (other.mLookupTable[i] != 0) {
6404 return UNKNOWN_ERROR;
6405 }
6406 }
6407 }
6408 return NO_ERROR;
6409}
6410
Adam Lesinskide898ff2014-01-29 18:20:45 -08006411status_t DynamicRefTable::addMapping(const String16& packageName, uint8_t packageId)
6412{
6413 ssize_t index = mEntries.indexOfKey(packageName);
6414 if (index < 0) {
6415 return UNKNOWN_ERROR;
6416 }
6417 mLookupTable[mEntries.valueAt(index)] = packageId;
6418 return NO_ERROR;
6419}
6420
6421status_t DynamicRefTable::lookupResourceId(uint32_t* resId) const {
6422 uint32_t res = *resId;
6423 size_t packageId = Res_GETPACKAGE(res) + 1;
6424
Tao Baia6d7e3f2015-09-01 18:49:54 -07006425 if (packageId == APP_PACKAGE_ID && !mAppAsLib) {
Adam Lesinskide898ff2014-01-29 18:20:45 -08006426 // No lookup needs to be done, app package IDs are absolute.
6427 return NO_ERROR;
6428 }
6429
Tao Baia6d7e3f2015-09-01 18:49:54 -07006430 if (packageId == 0 || (packageId == APP_PACKAGE_ID && mAppAsLib)) {
Adam Lesinskide898ff2014-01-29 18:20:45 -08006431 // The package ID is 0x00. That means that a shared library is accessing
Tao Baia6d7e3f2015-09-01 18:49:54 -07006432 // its own local resource.
6433 // Or if app resource is loaded as shared library, the resource which has
6434 // app package Id is local resources.
6435 // so we fix up those resources with the calling package ID.
6436 *resId = (0xFFFFFF & (*resId)) | (((uint32_t) mAssignedPackageId) << 24);
Adam Lesinskide898ff2014-01-29 18:20:45 -08006437 return NO_ERROR;
6438 }
6439
6440 // Do a proper lookup.
6441 uint8_t translatedId = mLookupTable[packageId];
6442 if (translatedId == 0) {
Adam Lesinskia7d1d732014-10-01 18:24:54 -07006443 ALOGV("DynamicRefTable(0x%02x): No mapping for build-time package ID 0x%02x.",
Adam Lesinskide898ff2014-01-29 18:20:45 -08006444 (uint8_t)mAssignedPackageId, (uint8_t)packageId);
6445 for (size_t i = 0; i < 256; i++) {
6446 if (mLookupTable[i] != 0) {
Adam Lesinskia7d1d732014-10-01 18:24:54 -07006447 ALOGV("e[0x%02x] -> 0x%02x", (uint8_t)i, mLookupTable[i]);
Adam Lesinskide898ff2014-01-29 18:20:45 -08006448 }
6449 }
6450 return UNKNOWN_ERROR;
6451 }
6452
6453 *resId = (res & 0x00ffffff) | (((uint32_t) translatedId) << 24);
6454 return NO_ERROR;
6455}
6456
6457status_t DynamicRefTable::lookupResourceValue(Res_value* value) const {
Tao Baia6d7e3f2015-09-01 18:49:54 -07006458 if (value->dataType != Res_value::TYPE_DYNAMIC_REFERENCE &&
6459 (value->dataType != Res_value::TYPE_REFERENCE || !mAppAsLib)) {
6460 // If the package is loaded as shared library, the resource reference
6461 // also need to be fixed.
Adam Lesinskide898ff2014-01-29 18:20:45 -08006462 return NO_ERROR;
6463 }
6464
6465 status_t err = lookupResourceId(&value->data);
6466 if (err != NO_ERROR) {
6467 return err;
6468 }
6469
6470 value->dataType = Res_value::TYPE_REFERENCE;
6471 return NO_ERROR;
6472}
6473
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006474struct IdmapTypeMap {
6475 ssize_t overlayTypeId;
6476 size_t entryOffset;
6477 Vector<uint32_t> entryMap;
6478};
6479
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006480status_t ResTable::createIdmap(const ResTable& overlay,
6481 uint32_t targetCrc, uint32_t overlayCrc,
6482 const char* targetPath, const char* overlayPath,
6483 void** outData, size_t* outSize) const
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006484{
6485 // see README for details on the format of map
6486 if (mPackageGroups.size() == 0) {
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006487 ALOGW("idmap: target package has no package groups, cannot create idmap\n");
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006488 return UNKNOWN_ERROR;
6489 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006490
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006491 if (mPackageGroups[0]->packages.size() == 0) {
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006492 ALOGW("idmap: target package has no packages in its first package group, "
6493 "cannot create idmap\n");
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006494 return UNKNOWN_ERROR;
6495 }
6496
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006497 KeyedVector<uint8_t, IdmapTypeMap> map;
6498
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006499 // overlaid packages are assumed to contain only one package group
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006500 const PackageGroup* pg = mPackageGroups[0];
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006501
6502 // starting size is header
6503 *outSize = ResTable::IDMAP_HEADER_SIZE_BYTES;
6504
6505 // target package id and number of types in map
6506 *outSize += 2 * sizeof(uint16_t);
6507
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006508 // overlay packages are assumed to contain only one package group
Adam Lesinski4bf58102014-11-03 11:21:19 -08006509 const ResTable_package* overlayPackageStruct = overlay.mPackageGroups[0]->packages[0]->package;
6510 char16_t tmpName[sizeof(overlayPackageStruct->name)/sizeof(overlayPackageStruct->name[0])];
6511 strcpy16_dtoh(tmpName, overlayPackageStruct->name, sizeof(overlayPackageStruct->name)/sizeof(overlayPackageStruct->name[0]));
6512 const String16 overlayPackage(tmpName);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006513
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006514 for (size_t typeIndex = 0; typeIndex < pg->types.size(); ++typeIndex) {
6515 const TypeList& typeList = pg->types[typeIndex];
6516 if (typeList.isEmpty()) {
6517 continue;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006518 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006519
6520 const Type* typeConfigs = typeList[0];
6521
6522 IdmapTypeMap typeMap;
6523 typeMap.overlayTypeId = -1;
6524 typeMap.entryOffset = 0;
6525
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006526 for (size_t entryIndex = 0; entryIndex < typeConfigs->entryCount; ++entryIndex) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006527 uint32_t resID = Res_MAKEID(pg->id - 1, typeIndex, entryIndex);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006528 resource_name resName;
MÃ¥rten Kongstad65a05fd2014-01-31 14:01:52 +01006529 if (!this->getResourceName(resID, false, &resName)) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006530 if (typeMap.entryMap.isEmpty()) {
6531 typeMap.entryOffset++;
6532 }
MÃ¥rten Kongstadfcaba142011-05-19 16:02:35 +02006533 continue;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006534 }
6535
6536 const String16 overlayType(resName.type, resName.typeLen);
6537 const String16 overlayName(resName.name, resName.nameLen);
6538 uint32_t overlayResID = overlay.identifierForName(overlayName.string(),
6539 overlayName.size(),
6540 overlayType.string(),
6541 overlayType.size(),
6542 overlayPackage.string(),
6543 overlayPackage.size());
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006544 if (overlayResID == 0) {
6545 if (typeMap.entryMap.isEmpty()) {
6546 typeMap.entryOffset++;
Jean-Baptiste Queru3e2d5912012-05-01 10:00:22 -07006547 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006548 continue;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006549 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006550
6551 if (typeMap.overlayTypeId == -1) {
6552 typeMap.overlayTypeId = Res_GETTYPE(overlayResID) + 1;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006553 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006554
6555 if (Res_GETTYPE(overlayResID) + 1 != static_cast<size_t>(typeMap.overlayTypeId)) {
6556 ALOGE("idmap: can't mix type ids in entry map. Resource 0x%08x maps to 0x%08x"
Andreas Gampe2204f0b2014-10-21 23:04:54 -07006557 " but entries should map to resources of type %02zx",
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006558 resID, overlayResID, typeMap.overlayTypeId);
6559 return BAD_TYPE;
6560 }
6561
6562 if (typeMap.entryOffset + typeMap.entryMap.size() < entryIndex) {
MÃ¥rten Kongstad96198eb2014-11-07 10:56:12 +01006563 // pad with 0xffffffff's (indicating non-existing entries) before adding this entry
6564 size_t index = typeMap.entryMap.size();
6565 size_t numItems = entryIndex - (typeMap.entryOffset + index);
6566 if (typeMap.entryMap.insertAt(0xffffffff, index, numItems) < 0) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006567 return NO_MEMORY;
6568 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006569 }
MÃ¥rten Kongstad96198eb2014-11-07 10:56:12 +01006570 typeMap.entryMap.add(Res_GETENTRY(overlayResID));
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006571 }
6572
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006573 if (!typeMap.entryMap.isEmpty()) {
6574 if (map.add(static_cast<uint8_t>(typeIndex), typeMap) < 0) {
6575 return NO_MEMORY;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006576 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006577 *outSize += (4 * sizeof(uint16_t)) + (typeMap.entryMap.size() * sizeof(uint32_t));
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006578 }
6579 }
6580
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006581 if (map.isEmpty()) {
6582 ALOGW("idmap: no resources in overlay package present in base package");
6583 return UNKNOWN_ERROR;
6584 }
6585
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006586 if ((*outData = malloc(*outSize)) == NULL) {
6587 return NO_MEMORY;
6588 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006589
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006590 uint32_t* data = (uint32_t*)*outData;
6591 *data++ = htodl(IDMAP_MAGIC);
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006592 *data++ = htodl(IDMAP_CURRENT_VERSION);
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006593 *data++ = htodl(targetCrc);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006594 *data++ = htodl(overlayCrc);
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006595 const char* paths[] = { targetPath, overlayPath };
6596 for (int j = 0; j < 2; ++j) {
6597 char* p = (char*)data;
6598 const char* path = paths[j];
6599 const size_t I = strlen(path);
6600 if (I > 255) {
6601 ALOGV("path exceeds expected 255 characters: %s\n", path);
6602 return UNKNOWN_ERROR;
6603 }
6604 for (size_t i = 0; i < 256; ++i) {
6605 *p++ = i < I ? path[i] : '\0';
6606 }
6607 data += 256 / sizeof(uint32_t);
6608 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006609 const size_t mapSize = map.size();
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006610 uint16_t* typeData = reinterpret_cast<uint16_t*>(data);
6611 *typeData++ = htods(pg->id);
6612 *typeData++ = htods(mapSize);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006613 for (size_t i = 0; i < mapSize; ++i) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006614 uint8_t targetTypeId = map.keyAt(i);
6615 const IdmapTypeMap& typeMap = map[i];
6616 *typeData++ = htods(targetTypeId + 1);
6617 *typeData++ = htods(typeMap.overlayTypeId);
6618 *typeData++ = htods(typeMap.entryMap.size());
6619 *typeData++ = htods(typeMap.entryOffset);
6620
6621 const size_t entryCount = typeMap.entryMap.size();
6622 uint32_t* entries = reinterpret_cast<uint32_t*>(typeData);
6623 for (size_t j = 0; j < entryCount; j++) {
6624 entries[j] = htodl(typeMap.entryMap[j]);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006625 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006626 typeData += entryCount * 2;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006627 }
6628
6629 return NO_ERROR;
6630}
6631
6632bool ResTable::getIdmapInfo(const void* idmap, size_t sizeBytes,
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006633 uint32_t* pVersion,
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006634 uint32_t* pTargetCrc, uint32_t* pOverlayCrc,
6635 String8* pTargetPath, String8* pOverlayPath)
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006636{
6637 const uint32_t* map = (const uint32_t*)idmap;
6638 if (!assertIdmapHeader(map, sizeBytes)) {
6639 return false;
6640 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006641 if (pVersion) {
6642 *pVersion = dtohl(map[1]);
6643 }
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006644 if (pTargetCrc) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006645 *pTargetCrc = dtohl(map[2]);
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006646 }
6647 if (pOverlayCrc) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006648 *pOverlayCrc = dtohl(map[3]);
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006649 }
6650 if (pTargetPath) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006651 pTargetPath->setTo(reinterpret_cast<const char*>(map + 4));
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006652 }
6653 if (pOverlayPath) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006654 pOverlayPath->setTo(reinterpret_cast<const char*>(map + 4 + 256 / sizeof(uint32_t)));
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006655 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006656 return true;
6657}
6658
6659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006660#define CHAR16_TO_CSTR(c16, len) (String8(String16(c16,len)).string())
6661
6662#define CHAR16_ARRAY_EQ(constant, var, len) \
6663 ((len == (sizeof(constant)/sizeof(constant[0]))) && (0 == memcmp((var), (constant), (len))))
6664
Jeff Brown9d3b1a42013-07-01 19:07:15 -07006665static void print_complex(uint32_t complex, bool isFraction)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006666{
Dianne Hackborne17086b2009-06-19 15:13:28 -07006667 const float MANTISSA_MULT =
6668 1.0f / (1<<Res_value::COMPLEX_MANTISSA_SHIFT);
6669 const float RADIX_MULTS[] = {
6670 1.0f*MANTISSA_MULT, 1.0f/(1<<7)*MANTISSA_MULT,
6671 1.0f/(1<<15)*MANTISSA_MULT, 1.0f/(1<<23)*MANTISSA_MULT
6672 };
6673
6674 float value = (complex&(Res_value::COMPLEX_MANTISSA_MASK
6675 <<Res_value::COMPLEX_MANTISSA_SHIFT))
6676 * RADIX_MULTS[(complex>>Res_value::COMPLEX_RADIX_SHIFT)
6677 & Res_value::COMPLEX_RADIX_MASK];
6678 printf("%f", value);
Mark Salyzyn00adb862014-03-19 11:00:06 -07006679
Dianne Hackbornde7faf62009-06-30 13:27:30 -07006680 if (!isFraction) {
Dianne Hackborne17086b2009-06-19 15:13:28 -07006681 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
6682 case Res_value::COMPLEX_UNIT_PX: printf("px"); break;
6683 case Res_value::COMPLEX_UNIT_DIP: printf("dp"); break;
6684 case Res_value::COMPLEX_UNIT_SP: printf("sp"); break;
6685 case Res_value::COMPLEX_UNIT_PT: printf("pt"); break;
6686 case Res_value::COMPLEX_UNIT_IN: printf("in"); break;
6687 case Res_value::COMPLEX_UNIT_MM: printf("mm"); break;
6688 default: printf(" (unknown unit)"); break;
6689 }
6690 } else {
6691 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
6692 case Res_value::COMPLEX_UNIT_FRACTION: printf("%%"); break;
6693 case Res_value::COMPLEX_UNIT_FRACTION_PARENT: printf("%%p"); break;
6694 default: printf(" (unknown unit)"); break;
6695 }
6696 }
6697}
6698
Shachar Shemesh9872bf42010-12-20 17:38:33 +02006699// Normalize a string for output
6700String8 ResTable::normalizeForOutput( const char *input )
6701{
6702 String8 ret;
6703 char buff[2];
6704 buff[1] = '\0';
6705
6706 while (*input != '\0') {
6707 switch (*input) {
6708 // All interesting characters are in the ASCII zone, so we are making our own lives
6709 // easier by scanning the string one byte at a time.
6710 case '\\':
6711 ret += "\\\\";
6712 break;
6713 case '\n':
6714 ret += "\\n";
6715 break;
6716 case '"':
6717 ret += "\\\"";
6718 break;
6719 default:
6720 buff[0] = *input;
6721 ret += buff;
6722 break;
6723 }
6724
6725 input++;
6726 }
6727
6728 return ret;
6729}
6730
Dianne Hackbornde7faf62009-06-30 13:27:30 -07006731void ResTable::print_value(const Package* pkg, const Res_value& value) const
6732{
6733 if (value.dataType == Res_value::TYPE_NULL) {
Alan Viverettef2969402014-10-29 17:09:36 -07006734 if (value.data == Res_value::DATA_NULL_UNDEFINED) {
6735 printf("(null)\n");
6736 } else if (value.data == Res_value::DATA_NULL_EMPTY) {
6737 printf("(null empty)\n");
6738 } else {
6739 // This should never happen.
6740 printf("(null) 0x%08x\n", value.data);
6741 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07006742 } else if (value.dataType == Res_value::TYPE_REFERENCE) {
6743 printf("(reference) 0x%08x\n", value.data);
Adam Lesinskide898ff2014-01-29 18:20:45 -08006744 } else if (value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE) {
6745 printf("(dynamic reference) 0x%08x\n", value.data);
Dianne Hackbornde7faf62009-06-30 13:27:30 -07006746 } else if (value.dataType == Res_value::TYPE_ATTRIBUTE) {
6747 printf("(attribute) 0x%08x\n", value.data);
6748 } else if (value.dataType == Res_value::TYPE_STRING) {
6749 size_t len;
Kenny Root780d2a12010-02-22 22:36:26 -08006750 const char* str8 = pkg->header->values.string8At(
Dianne Hackbornde7faf62009-06-30 13:27:30 -07006751 value.data, &len);
Kenny Root780d2a12010-02-22 22:36:26 -08006752 if (str8 != NULL) {
Shachar Shemesh9872bf42010-12-20 17:38:33 +02006753 printf("(string8) \"%s\"\n", normalizeForOutput(str8).string());
Dianne Hackbornde7faf62009-06-30 13:27:30 -07006754 } else {
Kenny Root780d2a12010-02-22 22:36:26 -08006755 const char16_t* str16 = pkg->header->values.stringAt(
6756 value.data, &len);
6757 if (str16 != NULL) {
6758 printf("(string16) \"%s\"\n",
Shachar Shemesh9872bf42010-12-20 17:38:33 +02006759 normalizeForOutput(String8(str16, len).string()).string());
Kenny Root780d2a12010-02-22 22:36:26 -08006760 } else {
6761 printf("(string) null\n");
6762 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006763 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07006764 } else if (value.dataType == Res_value::TYPE_FLOAT) {
6765 printf("(float) %g\n", *(const float*)&value.data);
6766 } else if (value.dataType == Res_value::TYPE_DIMENSION) {
6767 printf("(dimension) ");
6768 print_complex(value.data, false);
6769 printf("\n");
6770 } else if (value.dataType == Res_value::TYPE_FRACTION) {
6771 printf("(fraction) ");
6772 print_complex(value.data, true);
6773 printf("\n");
6774 } else if (value.dataType >= Res_value::TYPE_FIRST_COLOR_INT
6775 || value.dataType <= Res_value::TYPE_LAST_COLOR_INT) {
6776 printf("(color) #%08x\n", value.data);
6777 } else if (value.dataType == Res_value::TYPE_INT_BOOLEAN) {
6778 printf("(boolean) %s\n", value.data ? "true" : "false");
6779 } else if (value.dataType >= Res_value::TYPE_FIRST_INT
6780 || value.dataType <= Res_value::TYPE_LAST_INT) {
6781 printf("(int) 0x%08x or %d\n", value.data, value.data);
6782 } else {
6783 printf("(unknown type) t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)\n",
6784 (int)value.dataType, (int)value.data,
6785 (int)value.size, (int)value.res0);
6786 }
6787}
6788
Dianne Hackborne17086b2009-06-19 15:13:28 -07006789void ResTable::print(bool inclValues) const
6790{
6791 if (mError != 0) {
6792 printf("mError=0x%x (%s)\n", mError, strerror(mError));
6793 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006794 size_t pgCount = mPackageGroups.size();
6795 printf("Package Groups (%d)\n", (int)pgCount);
6796 for (size_t pgIndex=0; pgIndex<pgCount; pgIndex++) {
6797 const PackageGroup* pg = mPackageGroups[pgIndex];
Adam Lesinski6022deb2014-08-20 14:59:19 -07006798 printf("Package Group %d id=0x%02x packageCount=%d name=%s\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006799 (int)pgIndex, pg->id, (int)pg->packages.size(),
6800 String8(pg->name).string());
Mark Salyzyn00adb862014-03-19 11:00:06 -07006801
Adam Lesinski6022deb2014-08-20 14:59:19 -07006802 const KeyedVector<String16, uint8_t>& refEntries = pg->dynamicRefTable.entries();
6803 const size_t refEntryCount = refEntries.size();
6804 if (refEntryCount > 0) {
6805 printf(" DynamicRefTable entryCount=%d:\n", (int) refEntryCount);
6806 for (size_t refIndex = 0; refIndex < refEntryCount; refIndex++) {
6807 printf(" 0x%02x -> %s\n",
6808 refEntries.valueAt(refIndex),
6809 String8(refEntries.keyAt(refIndex)).string());
6810 }
6811 printf("\n");
6812 }
6813
6814 int packageId = pg->id;
Adam Lesinski18560882014-08-15 17:18:21 +00006815 size_t pkgCount = pg->packages.size();
6816 for (size_t pkgIndex=0; pkgIndex<pkgCount; pkgIndex++) {
6817 const Package* pkg = pg->packages[pkgIndex];
Adam Lesinski6022deb2014-08-20 14:59:19 -07006818 // Use a package's real ID, since the ID may have been assigned
6819 // if this package is a shared library.
6820 packageId = pkg->package->id;
Adam Lesinski4bf58102014-11-03 11:21:19 -08006821 char16_t tmpName[sizeof(pkg->package->name)/sizeof(pkg->package->name[0])];
6822 strcpy16_dtoh(tmpName, pkg->package->name, sizeof(pkg->package->name)/sizeof(pkg->package->name[0]));
Adam Lesinski6022deb2014-08-20 14:59:19 -07006823 printf(" Package %d id=0x%02x name=%s\n", (int)pkgIndex,
Adam Lesinski4bf58102014-11-03 11:21:19 -08006824 pkg->package->id, String8(tmpName).string());
Adam Lesinski18560882014-08-15 17:18:21 +00006825 }
6826
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006827 for (size_t typeIndex=0; typeIndex < pg->types.size(); typeIndex++) {
6828 const TypeList& typeList = pg->types[typeIndex];
6829 if (typeList.isEmpty()) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006830 continue;
6831 }
6832 const Type* typeConfigs = typeList[0];
6833 const size_t NTC = typeConfigs->configs.size();
6834 printf(" type %d configCount=%d entryCount=%d\n",
6835 (int)typeIndex, (int)NTC, (int)typeConfigs->entryCount);
6836 if (typeConfigs->typeSpecFlags != NULL) {
6837 for (size_t entryIndex=0; entryIndex<typeConfigs->entryCount; entryIndex++) {
Adam Lesinski6022deb2014-08-20 14:59:19 -07006838 uint32_t resID = (0xff000000 & ((packageId)<<24))
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006839 | (0x00ff0000 & ((typeIndex+1)<<16))
6840 | (0x0000ffff & (entryIndex));
6841 // Since we are creating resID without actually
6842 // iterating over them, we have no idea which is a
6843 // dynamic reference. We must check.
Adam Lesinski6022deb2014-08-20 14:59:19 -07006844 if (packageId == 0) {
6845 pg->dynamicRefTable.lookupResourceId(&resID);
6846 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006847
6848 resource_name resName;
6849 if (this->getResourceName(resID, true, &resName)) {
6850 String8 type8;
6851 String8 name8;
6852 if (resName.type8 != NULL) {
6853 type8 = String8(resName.type8, resName.typeLen);
6854 } else {
6855 type8 = String8(resName.type, resName.typeLen);
6856 }
6857 if (resName.name8 != NULL) {
6858 name8 = String8(resName.name8, resName.nameLen);
6859 } else {
6860 name8 = String8(resName.name, resName.nameLen);
6861 }
6862 printf(" spec resource 0x%08x %s:%s/%s: flags=0x%08x\n",
6863 resID,
6864 CHAR16_TO_CSTR(resName.package, resName.packageLen),
6865 type8.string(), name8.string(),
6866 dtohl(typeConfigs->typeSpecFlags[entryIndex]));
6867 } else {
6868 printf(" INVALID TYPE CONFIG FOR RESOURCE 0x%08x\n", resID);
6869 }
6870 }
6871 }
6872 for (size_t configIndex=0; configIndex<NTC; configIndex++) {
6873 const ResTable_type* type = typeConfigs->configs[configIndex];
6874 if ((((uint64_t)type)&0x3) != 0) {
6875 printf(" NON-INTEGER ResTable_type ADDRESS: %p\n", type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006876 continue;
6877 }
Adam Lesinski5b0f1be2015-07-27 16:53:14 -07006878
6879 // Always copy the config, as fields get added and we need to
6880 // set the defaults.
6881 ResTable_config thisConfig;
6882 thisConfig.copyFromDtoH(type->config);
6883
6884 String8 configStr = thisConfig.toString();
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006885 printf(" config %s:\n", configStr.size() > 0
6886 ? configStr.string() : "(default)");
6887 size_t entryCount = dtohl(type->entryCount);
6888 uint32_t entriesStart = dtohl(type->entriesStart);
6889 if ((entriesStart&0x3) != 0) {
6890 printf(" NON-INTEGER ResTable_type entriesStart OFFSET: 0x%x\n", entriesStart);
6891 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006892 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006893 uint32_t typeSize = dtohl(type->header.size);
6894 if ((typeSize&0x3) != 0) {
6895 printf(" NON-INTEGER ResTable_type header.size: 0x%x\n", typeSize);
6896 continue;
6897 }
6898 for (size_t entryIndex=0; entryIndex<entryCount; entryIndex++) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006899 const uint32_t* const eindex = (const uint32_t*)
6900 (((const uint8_t*)type) + dtohs(type->header.headerSize));
6901
6902 uint32_t thisOffset = dtohl(eindex[entryIndex]);
6903 if (thisOffset == ResTable_type::NO_ENTRY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006904 continue;
6905 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006906
Adam Lesinski6022deb2014-08-20 14:59:19 -07006907 uint32_t resID = (0xff000000 & ((packageId)<<24))
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006908 | (0x00ff0000 & ((typeIndex+1)<<16))
6909 | (0x0000ffff & (entryIndex));
Adam Lesinski6022deb2014-08-20 14:59:19 -07006910 if (packageId == 0) {
6911 pg->dynamicRefTable.lookupResourceId(&resID);
6912 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006913 resource_name resName;
6914 if (this->getResourceName(resID, true, &resName)) {
6915 String8 type8;
6916 String8 name8;
6917 if (resName.type8 != NULL) {
6918 type8 = String8(resName.type8, resName.typeLen);
Kenny Root33791952010-06-08 10:16:48 -07006919 } else {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006920 type8 = String8(resName.type, resName.typeLen);
Kenny Root33791952010-06-08 10:16:48 -07006921 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006922 if (resName.name8 != NULL) {
6923 name8 = String8(resName.name8, resName.nameLen);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006924 } else {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006925 name8 = String8(resName.name, resName.nameLen);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006926 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006927 printf(" resource 0x%08x %s:%s/%s: ", resID,
6928 CHAR16_TO_CSTR(resName.package, resName.packageLen),
6929 type8.string(), name8.string());
6930 } else {
6931 printf(" INVALID RESOURCE 0x%08x: ", resID);
6932 }
6933 if ((thisOffset&0x3) != 0) {
6934 printf("NON-INTEGER OFFSET: 0x%x\n", thisOffset);
6935 continue;
6936 }
6937 if ((thisOffset+sizeof(ResTable_entry)) > typeSize) {
6938 printf("OFFSET OUT OF BOUNDS: 0x%x+0x%x (size is 0x%x)\n",
6939 entriesStart, thisOffset, typeSize);
6940 continue;
6941 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006942
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006943 const ResTable_entry* ent = (const ResTable_entry*)
6944 (((const uint8_t*)type) + entriesStart + thisOffset);
6945 if (((entriesStart + thisOffset)&0x3) != 0) {
6946 printf("NON-INTEGER ResTable_entry OFFSET: 0x%x\n",
6947 (entriesStart + thisOffset));
6948 continue;
6949 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006950
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006951 uintptr_t esize = dtohs(ent->size);
6952 if ((esize&0x3) != 0) {
6953 printf("NON-INTEGER ResTable_entry SIZE: %p\n", (void *)esize);
6954 continue;
6955 }
6956 if ((thisOffset+esize) > typeSize) {
6957 printf("ResTable_entry OUT OF BOUNDS: 0x%x+0x%x+%p (size is 0x%x)\n",
6958 entriesStart, thisOffset, (void *)esize, typeSize);
6959 continue;
6960 }
6961
6962 const Res_value* valuePtr = NULL;
6963 const ResTable_map_entry* bagPtr = NULL;
6964 Res_value value;
6965 if ((dtohs(ent->flags)&ResTable_entry::FLAG_COMPLEX) != 0) {
6966 printf("<bag>");
6967 bagPtr = (const ResTable_map_entry*)ent;
6968 } else {
6969 valuePtr = (const Res_value*)
6970 (((const uint8_t*)ent) + esize);
6971 value.copyFrom_dtoh(*valuePtr);
6972 printf("t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)",
6973 (int)value.dataType, (int)value.data,
6974 (int)value.size, (int)value.res0);
6975 }
6976
6977 if ((dtohs(ent->flags)&ResTable_entry::FLAG_PUBLIC) != 0) {
6978 printf(" (PUBLIC)");
6979 }
6980 printf("\n");
6981
6982 if (inclValues) {
6983 if (valuePtr != NULL) {
6984 printf(" ");
6985 print_value(typeConfigs->package, value);
6986 } else if (bagPtr != NULL) {
6987 const int N = dtohl(bagPtr->count);
6988 const uint8_t* baseMapPtr = (const uint8_t*)ent;
6989 size_t mapOffset = esize;
6990 const ResTable_map* mapPtr = (ResTable_map*)(baseMapPtr+mapOffset);
6991 const uint32_t parent = dtohl(bagPtr->parent.ident);
6992 uint32_t resolvedParent = parent;
Adam Lesinski6022deb2014-08-20 14:59:19 -07006993 if (Res_GETPACKAGE(resolvedParent) + 1 == 0) {
6994 status_t err = pg->dynamicRefTable.lookupResourceId(&resolvedParent);
6995 if (err != NO_ERROR) {
6996 resolvedParent = 0;
6997 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006998 }
6999 printf(" Parent=0x%08x(Resolved=0x%08x), Count=%d\n",
7000 parent, resolvedParent, N);
7001 for (int i=0; i<N && mapOffset < (typeSize-sizeof(ResTable_map)); i++) {
7002 printf(" #%i (Key=0x%08x): ",
7003 i, dtohl(mapPtr->name.ident));
7004 value.copyFrom_dtoh(mapPtr->value);
7005 print_value(typeConfigs->package, value);
7006 const size_t size = dtohs(mapPtr->value.size);
7007 mapOffset += size + sizeof(*mapPtr)-sizeof(mapPtr->value);
7008 mapPtr = (ResTable_map*)(baseMapPtr+mapOffset);
Dianne Hackborne17086b2009-06-19 15:13:28 -07007009 }
7010 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007011 }
7012 }
7013 }
7014 }
7015 }
7016}
7017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007018} // namespace android