blob: 3277c36c8a3327e025d2ebfd101b8ce3774ab4e7 [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,
Roozbeh Pournader4de45962016-02-11 17:58:24 -08002239 language, requested->localeScript, requested->country);
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08002240 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
Roozbeh Pournader4de45962016-02-11 17:58:24 -08002529 // either of the desired locale or the provided locale. But if we could determine
2530 // the scripts, they should be the same for the locales to match.
2531 bool countriesMustMatch = false;
2532 char computed_script[4];
2533 const char* script;
2534 if (settings.localeScript[0] == '\0') { // could not determine the request's script
2535 countriesMustMatch = true;
2536 } else {
2537 if (localeScript[0] == '\0') { // script was not provided, so we try to compute it
2538 localeDataComputeScript(computed_script, language, country);
2539 if (computed_script[0] == '\0') { // we could not compute the script
2540 countriesMustMatch = true;
2541 } else {
2542 script = computed_script;
2543 }
2544 } else { // script was provided, so just use it
2545 script = localeScript;
2546 }
2547 }
2548
2549 if (countriesMustMatch) {
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08002550 if (country[0] != '\0'
2551 && (country[0] != settings.country[0]
2552 || country[1] != settings.country[1])) {
2553 return false;
2554 }
2555 } else {
Roozbeh Pournader4de45962016-02-11 17:58:24 -08002556 if (memcmp(script, settings.localeScript, sizeof(settings.localeScript)) != 0) {
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08002557 return false;
2558 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002559 }
2560 }
Narayan Kamath48620f12014-01-20 13:57:11 +00002561
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002562 if (screenConfig != 0) {
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07002563 const int layoutDir = screenLayout&MASK_LAYOUTDIR;
2564 const int setLayoutDir = settings.screenLayout&MASK_LAYOUTDIR;
2565 if (layoutDir != 0 && layoutDir != setLayoutDir) {
2566 return false;
2567 }
2568
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002569 const int screenSize = screenLayout&MASK_SCREENSIZE;
2570 const int setScreenSize = settings.screenLayout&MASK_SCREENSIZE;
2571 // Any screen sizes for larger screens than the setting do not
2572 // match.
2573 if (screenSize != 0 && screenSize > setScreenSize) {
2574 return false;
2575 }
2576
2577 const int screenLong = screenLayout&MASK_SCREENLONG;
2578 const int setScreenLong = settings.screenLayout&MASK_SCREENLONG;
2579 if (screenLong != 0 && screenLong != setScreenLong) {
2580 return false;
2581 }
2582
2583 const int uiModeType = uiMode&MASK_UI_MODE_TYPE;
2584 const int setUiModeType = settings.uiMode&MASK_UI_MODE_TYPE;
2585 if (uiModeType != 0 && uiModeType != setUiModeType) {
2586 return false;
2587 }
2588
2589 const int uiModeNight = uiMode&MASK_UI_MODE_NIGHT;
2590 const int setUiModeNight = settings.uiMode&MASK_UI_MODE_NIGHT;
2591 if (uiModeNight != 0 && uiModeNight != setUiModeNight) {
2592 return false;
2593 }
2594
2595 if (smallestScreenWidthDp != 0
2596 && smallestScreenWidthDp > settings.smallestScreenWidthDp) {
2597 return false;
2598 }
2599 }
Adam Lesinski2738c962015-05-14 14:25:36 -07002600
2601 if (screenConfig2 != 0) {
2602 const int screenRound = screenLayout2 & MASK_SCREENROUND;
2603 const int setScreenRound = settings.screenLayout2 & MASK_SCREENROUND;
2604 if (screenRound != 0 && screenRound != setScreenRound) {
2605 return false;
2606 }
2607 }
2608
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002609 if (screenSizeDp != 0) {
2610 if (screenWidthDp != 0 && screenWidthDp > settings.screenWidthDp) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07002611 if (kDebugTableSuperNoisy) {
2612 ALOGI("Filtering out width %d in requested %d", screenWidthDp,
2613 settings.screenWidthDp);
2614 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002615 return false;
2616 }
2617 if (screenHeightDp != 0 && screenHeightDp > settings.screenHeightDp) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07002618 if (kDebugTableSuperNoisy) {
2619 ALOGI("Filtering out height %d in requested %d", screenHeightDp,
2620 settings.screenHeightDp);
2621 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002622 return false;
2623 }
2624 }
2625 if (screenType != 0) {
2626 if (orientation != 0 && orientation != settings.orientation) {
2627 return false;
2628 }
2629 // density always matches - we can scale it. See isBetterThan
2630 if (touchscreen != 0 && touchscreen != settings.touchscreen) {
2631 return false;
2632 }
2633 }
2634 if (input != 0) {
2635 const int keysHidden = inputFlags&MASK_KEYSHIDDEN;
2636 const int setKeysHidden = settings.inputFlags&MASK_KEYSHIDDEN;
2637 if (keysHidden != 0 && keysHidden != setKeysHidden) {
2638 // For compatibility, we count a request for KEYSHIDDEN_NO as also
2639 // matching the more recent KEYSHIDDEN_SOFT. Basically
2640 // KEYSHIDDEN_NO means there is some kind of keyboard available.
Andreas Gampe2204f0b2014-10-21 23:04:54 -07002641 if (kDebugTableSuperNoisy) {
2642 ALOGI("Matching keysHidden: have=%d, config=%d\n", keysHidden, setKeysHidden);
2643 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002644 if (keysHidden != KEYSHIDDEN_NO || setKeysHidden != KEYSHIDDEN_SOFT) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07002645 if (kDebugTableSuperNoisy) {
2646 ALOGI("No match!");
2647 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002648 return false;
2649 }
2650 }
2651 const int navHidden = inputFlags&MASK_NAVHIDDEN;
2652 const int setNavHidden = settings.inputFlags&MASK_NAVHIDDEN;
2653 if (navHidden != 0 && navHidden != setNavHidden) {
2654 return false;
2655 }
2656 if (keyboard != 0 && keyboard != settings.keyboard) {
2657 return false;
2658 }
2659 if (navigation != 0 && navigation != settings.navigation) {
2660 return false;
2661 }
2662 }
2663 if (screenSize != 0) {
2664 if (screenWidth != 0 && screenWidth > settings.screenWidth) {
2665 return false;
2666 }
2667 if (screenHeight != 0 && screenHeight > settings.screenHeight) {
2668 return false;
2669 }
2670 }
2671 if (version != 0) {
2672 if (sdkVersion != 0 && sdkVersion > settings.sdkVersion) {
2673 return false;
2674 }
2675 if (minorVersion != 0 && minorVersion != settings.minorVersion) {
2676 return false;
2677 }
2678 }
2679 return true;
2680}
2681
Adam Lesinski8a9355a2015-03-10 16:55:43 -07002682void ResTable_config::appendDirLocale(String8& out) const {
2683 if (!language[0]) {
2684 return;
2685 }
2686
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08002687 if (!localeScriptWasProvided && !localeVariant[0]) {
Adam Lesinski8a9355a2015-03-10 16:55:43 -07002688 // Legacy format.
2689 if (out.size() > 0) {
2690 out.append("-");
2691 }
2692
2693 char buf[4];
2694 size_t len = unpackLanguage(buf);
2695 out.append(buf, len);
2696
2697 if (country[0]) {
2698 out.append("-r");
2699 len = unpackRegion(buf);
2700 out.append(buf, len);
2701 }
2702 return;
2703 }
2704
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08002705 // We are writing the modified BCP 47 tag.
Adam Lesinski8a9355a2015-03-10 16:55:43 -07002706 // It starts with 'b+' and uses '+' as a separator.
2707
2708 if (out.size() > 0) {
2709 out.append("-");
2710 }
2711 out.append("b+");
2712
2713 char buf[4];
2714 size_t len = unpackLanguage(buf);
2715 out.append(buf, len);
2716
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08002717 if (localeScriptWasProvided) {
Adam Lesinski8a9355a2015-03-10 16:55:43 -07002718 out.append("+");
2719 out.append(localeScript, sizeof(localeScript));
2720 }
2721
2722 if (country[0]) {
2723 out.append("+");
2724 len = unpackRegion(buf);
2725 out.append(buf, len);
2726 }
2727
2728 if (localeVariant[0]) {
2729 out.append("+");
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08002730 out.append(localeVariant, strnlen(localeVariant, sizeof(localeVariant)));
Adam Lesinski8a9355a2015-03-10 16:55:43 -07002731 }
2732}
2733
Narayan Kamath788fa412014-01-21 15:32:36 +00002734void ResTable_config::getBcp47Locale(char str[RESTABLE_MAX_LOCALE_LEN]) const {
Narayan Kamath48620f12014-01-20 13:57:11 +00002735 memset(str, 0, RESTABLE_MAX_LOCALE_LEN);
2736
2737 // This represents the "any" locale value, which has traditionally been
2738 // represented by the empty string.
2739 if (!language[0] && !country[0]) {
2740 return;
2741 }
2742
2743 size_t charsWritten = 0;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002744 if (language[0]) {
Narayan Kamath788fa412014-01-21 15:32:36 +00002745 charsWritten += unpackLanguage(str);
Narayan Kamath48620f12014-01-20 13:57:11 +00002746 }
2747
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08002748 if (localeScriptWasProvided) {
Narayan Kamath48620f12014-01-20 13:57:11 +00002749 if (charsWritten) {
Narayan Kamath788fa412014-01-21 15:32:36 +00002750 str[charsWritten++] = '-';
Narayan Kamath48620f12014-01-20 13:57:11 +00002751 }
2752 memcpy(str + charsWritten, localeScript, sizeof(localeScript));
Narayan Kamath788fa412014-01-21 15:32:36 +00002753 charsWritten += sizeof(localeScript);
2754 }
2755
2756 if (country[0]) {
2757 if (charsWritten) {
2758 str[charsWritten++] = '-';
2759 }
2760 charsWritten += unpackRegion(str + charsWritten);
Narayan Kamath48620f12014-01-20 13:57:11 +00002761 }
2762
2763 if (localeVariant[0]) {
2764 if (charsWritten) {
Narayan Kamath788fa412014-01-21 15:32:36 +00002765 str[charsWritten++] = '-';
Narayan Kamath48620f12014-01-20 13:57:11 +00002766 }
2767 memcpy(str + charsWritten, localeVariant, sizeof(localeVariant));
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002768 }
2769}
2770
Narayan Kamath788fa412014-01-21 15:32:36 +00002771/* static */ inline bool assignLocaleComponent(ResTable_config* config,
2772 const char* start, size_t size) {
2773
2774 switch (size) {
2775 case 0:
2776 return false;
2777 case 2:
2778 case 3:
2779 config->language[0] ? config->packRegion(start) : config->packLanguage(start);
2780 break;
2781 case 4:
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08002782 if ('0' <= start[0] && start[0] <= '9') {
2783 // this is a variant, so fall through
2784 } else {
2785 config->localeScript[0] = toupper(start[0]);
2786 for (size_t i = 1; i < 4; ++i) {
2787 config->localeScript[i] = tolower(start[i]);
2788 }
2789 config->localeScriptWasProvided = true;
2790 break;
Narayan Kamath788fa412014-01-21 15:32:36 +00002791 }
Narayan Kamath788fa412014-01-21 15:32:36 +00002792 case 5:
2793 case 6:
2794 case 7:
2795 case 8:
2796 for (size_t i = 0; i < size; ++i) {
2797 config->localeVariant[i] = tolower(start[i]);
2798 }
2799 break;
2800 default:
2801 return false;
2802 }
2803
2804 return true;
2805}
2806
2807void ResTable_config::setBcp47Locale(const char* in) {
2808 locale = 0;
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08002809 localeScriptWasProvided = false;
Narayan Kamath788fa412014-01-21 15:32:36 +00002810 memset(localeScript, 0, sizeof(localeScript));
2811 memset(localeVariant, 0, sizeof(localeVariant));
2812
2813 const char* separator = in;
2814 const char* start = in;
2815 while ((separator = strchr(start, '-')) != NULL) {
2816 const size_t size = separator - start;
2817 if (!assignLocaleComponent(this, start, size)) {
2818 fprintf(stderr, "Invalid BCP-47 locale string: %s", in);
2819 }
2820
2821 start = (separator + 1);
2822 }
2823
2824 const size_t size = in + strlen(in) - start;
2825 assignLocaleComponent(this, start, size);
Roozbeh Pournaderb927c552016-01-15 11:23:42 -08002826 if (localeScript[0] == '\0') {
2827 computeScript();
2828 };
Narayan Kamath788fa412014-01-21 15:32:36 +00002829}
2830
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002831String8 ResTable_config::toString() const {
2832 String8 res;
2833
2834 if (mcc != 0) {
2835 if (res.size() > 0) res.append("-");
Adam Lesinskifab50872014-04-16 14:40:42 -07002836 res.appendFormat("mcc%d", dtohs(mcc));
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002837 }
2838 if (mnc != 0) {
2839 if (res.size() > 0) res.append("-");
Adam Lesinskifab50872014-04-16 14:40:42 -07002840 res.appendFormat("mnc%d", dtohs(mnc));
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002841 }
Adam Lesinskifab50872014-04-16 14:40:42 -07002842
Adam Lesinski8a9355a2015-03-10 16:55:43 -07002843 appendDirLocale(res);
Narayan Kamath48620f12014-01-20 13:57:11 +00002844
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07002845 if ((screenLayout&MASK_LAYOUTDIR) != 0) {
2846 if (res.size() > 0) res.append("-");
2847 switch (screenLayout&ResTable_config::MASK_LAYOUTDIR) {
2848 case ResTable_config::LAYOUTDIR_LTR:
Fabrice Di Meglio8a802db2012-09-05 13:12:02 -07002849 res.append("ldltr");
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07002850 break;
2851 case ResTable_config::LAYOUTDIR_RTL:
Fabrice Di Meglio8a802db2012-09-05 13:12:02 -07002852 res.append("ldrtl");
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07002853 break;
2854 default:
2855 res.appendFormat("layoutDir=%d",
2856 dtohs(screenLayout&ResTable_config::MASK_LAYOUTDIR));
2857 break;
2858 }
2859 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002860 if (smallestScreenWidthDp != 0) {
2861 if (res.size() > 0) res.append("-");
2862 res.appendFormat("sw%ddp", dtohs(smallestScreenWidthDp));
2863 }
2864 if (screenWidthDp != 0) {
2865 if (res.size() > 0) res.append("-");
2866 res.appendFormat("w%ddp", dtohs(screenWidthDp));
2867 }
2868 if (screenHeightDp != 0) {
2869 if (res.size() > 0) res.append("-");
2870 res.appendFormat("h%ddp", dtohs(screenHeightDp));
2871 }
2872 if ((screenLayout&MASK_SCREENSIZE) != SCREENSIZE_ANY) {
2873 if (res.size() > 0) res.append("-");
2874 switch (screenLayout&ResTable_config::MASK_SCREENSIZE) {
2875 case ResTable_config::SCREENSIZE_SMALL:
2876 res.append("small");
2877 break;
2878 case ResTable_config::SCREENSIZE_NORMAL:
2879 res.append("normal");
2880 break;
2881 case ResTable_config::SCREENSIZE_LARGE:
2882 res.append("large");
2883 break;
2884 case ResTable_config::SCREENSIZE_XLARGE:
2885 res.append("xlarge");
2886 break;
2887 default:
2888 res.appendFormat("screenLayoutSize=%d",
2889 dtohs(screenLayout&ResTable_config::MASK_SCREENSIZE));
2890 break;
2891 }
2892 }
2893 if ((screenLayout&MASK_SCREENLONG) != 0) {
2894 if (res.size() > 0) res.append("-");
2895 switch (screenLayout&ResTable_config::MASK_SCREENLONG) {
2896 case ResTable_config::SCREENLONG_NO:
2897 res.append("notlong");
2898 break;
2899 case ResTable_config::SCREENLONG_YES:
2900 res.append("long");
2901 break;
2902 default:
2903 res.appendFormat("screenLayoutLong=%d",
2904 dtohs(screenLayout&ResTable_config::MASK_SCREENLONG));
2905 break;
2906 }
2907 }
Adam Lesinski2738c962015-05-14 14:25:36 -07002908 if ((screenLayout2&MASK_SCREENROUND) != 0) {
2909 if (res.size() > 0) res.append("-");
2910 switch (screenLayout2&MASK_SCREENROUND) {
2911 case SCREENROUND_NO:
2912 res.append("notround");
2913 break;
2914 case SCREENROUND_YES:
2915 res.append("round");
2916 break;
2917 default:
2918 res.appendFormat("screenRound=%d", dtohs(screenLayout2&MASK_SCREENROUND));
2919 break;
2920 }
2921 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002922 if (orientation != ORIENTATION_ANY) {
2923 if (res.size() > 0) res.append("-");
2924 switch (orientation) {
2925 case ResTable_config::ORIENTATION_PORT:
2926 res.append("port");
2927 break;
2928 case ResTable_config::ORIENTATION_LAND:
2929 res.append("land");
2930 break;
2931 case ResTable_config::ORIENTATION_SQUARE:
2932 res.append("square");
2933 break;
2934 default:
2935 res.appendFormat("orientation=%d", dtohs(orientation));
2936 break;
2937 }
2938 }
2939 if ((uiMode&MASK_UI_MODE_TYPE) != UI_MODE_TYPE_ANY) {
2940 if (res.size() > 0) res.append("-");
2941 switch (uiMode&ResTable_config::MASK_UI_MODE_TYPE) {
2942 case ResTable_config::UI_MODE_TYPE_DESK:
2943 res.append("desk");
2944 break;
2945 case ResTable_config::UI_MODE_TYPE_CAR:
2946 res.append("car");
2947 break;
2948 case ResTable_config::UI_MODE_TYPE_TELEVISION:
2949 res.append("television");
2950 break;
2951 case ResTable_config::UI_MODE_TYPE_APPLIANCE:
2952 res.append("appliance");
2953 break;
John Spurlock6c191292014-04-03 16:37:27 -04002954 case ResTable_config::UI_MODE_TYPE_WATCH:
2955 res.append("watch");
2956 break;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002957 default:
2958 res.appendFormat("uiModeType=%d",
2959 dtohs(screenLayout&ResTable_config::MASK_UI_MODE_TYPE));
2960 break;
2961 }
2962 }
2963 if ((uiMode&MASK_UI_MODE_NIGHT) != 0) {
2964 if (res.size() > 0) res.append("-");
2965 switch (uiMode&ResTable_config::MASK_UI_MODE_NIGHT) {
2966 case ResTable_config::UI_MODE_NIGHT_NO:
2967 res.append("notnight");
2968 break;
2969 case ResTable_config::UI_MODE_NIGHT_YES:
2970 res.append("night");
2971 break;
2972 default:
2973 res.appendFormat("uiModeNight=%d",
2974 dtohs(uiMode&MASK_UI_MODE_NIGHT));
2975 break;
2976 }
2977 }
2978 if (density != DENSITY_DEFAULT) {
2979 if (res.size() > 0) res.append("-");
2980 switch (density) {
2981 case ResTable_config::DENSITY_LOW:
2982 res.append("ldpi");
2983 break;
2984 case ResTable_config::DENSITY_MEDIUM:
2985 res.append("mdpi");
2986 break;
2987 case ResTable_config::DENSITY_TV:
2988 res.append("tvdpi");
2989 break;
2990 case ResTable_config::DENSITY_HIGH:
2991 res.append("hdpi");
2992 break;
2993 case ResTable_config::DENSITY_XHIGH:
2994 res.append("xhdpi");
2995 break;
2996 case ResTable_config::DENSITY_XXHIGH:
2997 res.append("xxhdpi");
2998 break;
Adam Lesinski8d5667d2014-08-13 21:02:57 -07002999 case ResTable_config::DENSITY_XXXHIGH:
3000 res.append("xxxhdpi");
3001 break;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08003002 case ResTable_config::DENSITY_NONE:
3003 res.append("nodpi");
3004 break;
Adam Lesinski31245b42014-08-22 19:10:56 -07003005 case ResTable_config::DENSITY_ANY:
3006 res.append("anydpi");
3007 break;
Dianne Hackborn6c997a92012-01-31 11:27:43 -08003008 default:
Dianne Hackborn5c6dfeb2012-03-09 13:17:17 -08003009 res.appendFormat("%ddpi", dtohs(density));
Dianne Hackborn6c997a92012-01-31 11:27:43 -08003010 break;
3011 }
3012 }
3013 if (touchscreen != TOUCHSCREEN_ANY) {
3014 if (res.size() > 0) res.append("-");
3015 switch (touchscreen) {
3016 case ResTable_config::TOUCHSCREEN_NOTOUCH:
3017 res.append("notouch");
3018 break;
3019 case ResTable_config::TOUCHSCREEN_FINGER:
3020 res.append("finger");
3021 break;
3022 case ResTable_config::TOUCHSCREEN_STYLUS:
3023 res.append("stylus");
3024 break;
3025 default:
3026 res.appendFormat("touchscreen=%d", dtohs(touchscreen));
3027 break;
3028 }
3029 }
Adam Lesinskifab50872014-04-16 14:40:42 -07003030 if ((inputFlags&MASK_KEYSHIDDEN) != 0) {
3031 if (res.size() > 0) res.append("-");
3032 switch (inputFlags&MASK_KEYSHIDDEN) {
3033 case ResTable_config::KEYSHIDDEN_NO:
3034 res.append("keysexposed");
3035 break;
3036 case ResTable_config::KEYSHIDDEN_YES:
3037 res.append("keyshidden");
3038 break;
3039 case ResTable_config::KEYSHIDDEN_SOFT:
3040 res.append("keyssoft");
3041 break;
3042 }
3043 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08003044 if (keyboard != KEYBOARD_ANY) {
3045 if (res.size() > 0) res.append("-");
3046 switch (keyboard) {
3047 case ResTable_config::KEYBOARD_NOKEYS:
3048 res.append("nokeys");
3049 break;
3050 case ResTable_config::KEYBOARD_QWERTY:
3051 res.append("qwerty");
3052 break;
3053 case ResTable_config::KEYBOARD_12KEY:
3054 res.append("12key");
3055 break;
3056 default:
3057 res.appendFormat("keyboard=%d", dtohs(keyboard));
3058 break;
3059 }
3060 }
Adam Lesinskifab50872014-04-16 14:40:42 -07003061 if ((inputFlags&MASK_NAVHIDDEN) != 0) {
Dianne Hackborn6c997a92012-01-31 11:27:43 -08003062 if (res.size() > 0) res.append("-");
Adam Lesinskifab50872014-04-16 14:40:42 -07003063 switch (inputFlags&MASK_NAVHIDDEN) {
3064 case ResTable_config::NAVHIDDEN_NO:
3065 res.append("navexposed");
Dianne Hackborn6c997a92012-01-31 11:27:43 -08003066 break;
Adam Lesinskifab50872014-04-16 14:40:42 -07003067 case ResTable_config::NAVHIDDEN_YES:
3068 res.append("navhidden");
Dianne Hackborn6c997a92012-01-31 11:27:43 -08003069 break;
Adam Lesinskifab50872014-04-16 14:40:42 -07003070 default:
3071 res.appendFormat("inputFlagsNavHidden=%d",
3072 dtohs(inputFlags&MASK_NAVHIDDEN));
Dianne Hackborn6c997a92012-01-31 11:27:43 -08003073 break;
3074 }
3075 }
3076 if (navigation != NAVIGATION_ANY) {
3077 if (res.size() > 0) res.append("-");
3078 switch (navigation) {
3079 case ResTable_config::NAVIGATION_NONAV:
3080 res.append("nonav");
3081 break;
3082 case ResTable_config::NAVIGATION_DPAD:
3083 res.append("dpad");
3084 break;
3085 case ResTable_config::NAVIGATION_TRACKBALL:
3086 res.append("trackball");
3087 break;
3088 case ResTable_config::NAVIGATION_WHEEL:
3089 res.append("wheel");
3090 break;
3091 default:
3092 res.appendFormat("navigation=%d", dtohs(navigation));
3093 break;
3094 }
3095 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08003096 if (screenSize != 0) {
3097 if (res.size() > 0) res.append("-");
3098 res.appendFormat("%dx%d", dtohs(screenWidth), dtohs(screenHeight));
3099 }
3100 if (version != 0) {
3101 if (res.size() > 0) res.append("-");
3102 res.appendFormat("v%d", dtohs(sdkVersion));
3103 if (minorVersion != 0) {
3104 res.appendFormat(".%d", dtohs(minorVersion));
3105 }
3106 }
3107
3108 return res;
3109}
3110
3111// --------------------------------------------------------------------
3112// --------------------------------------------------------------------
3113// --------------------------------------------------------------------
3114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003115struct ResTable::Header
3116{
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01003117 Header(ResTable* _owner) : owner(_owner), ownedData(NULL), header(NULL),
3118 resourceIDMap(NULL), resourceIDMapSize(0) { }
3119
3120 ~Header()
3121 {
3122 free(resourceIDMap);
3123 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003124
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003125 const ResTable* const owner;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003126 void* ownedData;
3127 const ResTable_header* header;
3128 size_t size;
3129 const uint8_t* dataEnd;
3130 size_t index;
Narayan Kamath7c4887f2014-01-27 17:32:37 +00003131 int32_t cookie;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003132
3133 ResStringPool values;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01003134 uint32_t* resourceIDMap;
3135 size_t resourceIDMapSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136};
3137
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003138struct ResTable::Entry {
3139 ResTable_config config;
3140 const ResTable_entry* entry;
3141 const ResTable_type* type;
3142 uint32_t specFlags;
3143 const Package* package;
3144
3145 StringPoolRef typeStr;
3146 StringPoolRef keyStr;
3147};
3148
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003149struct ResTable::Type
3150{
3151 Type(const Header* _header, const Package* _package, size_t count)
3152 : header(_header), package(_package), entryCount(count),
3153 typeSpec(NULL), typeSpecFlags(NULL) { }
3154 const Header* const header;
3155 const Package* const package;
3156 const size_t entryCount;
3157 const ResTable_typeSpec* typeSpec;
3158 const uint32_t* typeSpecFlags;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003159 IdmapEntries idmapEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003160 Vector<const ResTable_type*> configs;
3161};
3162
3163struct ResTable::Package
3164{
Dianne Hackborn78c40512009-07-06 11:07:40 -07003165 Package(ResTable* _owner, const Header* _header, const ResTable_package* _package)
Adam Lesinski18560882014-08-15 17:18:21 +00003166 : owner(_owner), header(_header), package(_package), typeIdOffset(0) {
3167 if (dtohs(package->header.headerSize) == sizeof(package)) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003168 // The package structure is the same size as the definition.
3169 // This means it contains the typeIdOffset field.
Adam Lesinski18560882014-08-15 17:18:21 +00003170 typeIdOffset = package->typeIdOffset;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003171 }
3172 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07003173
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003174 const ResTable* const owner;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003175 const Header* const header;
Adam Lesinski18560882014-08-15 17:18:21 +00003176 const ResTable_package* const package;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003177
Dianne Hackborn78c40512009-07-06 11:07:40 -07003178 ResStringPool typeStrings;
3179 ResStringPool keyStrings;
Mark Salyzyn00adb862014-03-19 11:00:06 -07003180
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003181 size_t typeIdOffset;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003182};
3183
3184// A group of objects describing a particular resource package.
3185// The first in 'package' is always the root object (from the resource
3186// table that defined the package); the ones after are skins on top of it.
3187struct ResTable::PackageGroup
3188{
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08003189 PackageGroup(
3190 ResTable* _owner, const String16& _name, uint32_t _id,
3191 bool appAsLib, bool _isSystemAsset)
Adam Lesinskide898ff2014-01-29 18:20:45 -08003192 : owner(_owner)
3193 , name(_name)
3194 , id(_id)
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003195 , largestTypeId(0)
Adam Lesinskide898ff2014-01-29 18:20:45 -08003196 , bags(NULL)
Tao Baia6d7e3f2015-09-01 18:49:54 -07003197 , dynamicRefTable(static_cast<uint8_t>(_id), appAsLib)
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08003198 , isSystemAsset(_isSystemAsset)
Adam Lesinskide898ff2014-01-29 18:20:45 -08003199 { }
3200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003201 ~PackageGroup() {
3202 clearBagCache();
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003203 const size_t numTypes = types.size();
3204 for (size_t i = 0; i < numTypes; i++) {
3205 const TypeList& typeList = types[i];
3206 const size_t numInnerTypes = typeList.size();
3207 for (size_t j = 0; j < numInnerTypes; j++) {
3208 if (typeList[j]->package->owner == owner) {
3209 delete typeList[j];
3210 }
3211 }
3212 }
3213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003214 const size_t N = packages.size();
3215 for (size_t i=0; i<N; i++) {
Dianne Hackborn78c40512009-07-06 11:07:40 -07003216 Package* pkg = packages[i];
3217 if (pkg->owner == owner) {
3218 delete pkg;
3219 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 }
3221 }
3222
3223 void clearBagCache() {
3224 if (bags) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003225 if (kDebugTableNoisy) {
3226 printf("bags=%p\n", bags);
3227 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003228 for (size_t i = 0; i < bags->size(); i++) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003229 if (kDebugTableNoisy) {
3230 printf("type=%zu\n", i);
3231 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003232 const TypeList& typeList = types[i];
Adam Lesinski7f668d02014-08-28 18:32:32 -07003233 if (!typeList.isEmpty()) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003234 bag_set** typeBags = bags->get(i);
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003235 if (kDebugTableNoisy) {
3236 printf("typeBags=%p\n", typeBags);
3237 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003238 if (typeBags) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003239 const size_t N = typeList[0]->entryCount;
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003240 if (kDebugTableNoisy) {
3241 printf("type->entryCount=%zu\n", N);
3242 }
3243 for (size_t j = 0; j < N; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003244 if (typeBags[j] && typeBags[j] != (bag_set*)0xFFFFFFFF)
3245 free(typeBags[j]);
3246 }
3247 free(typeBags);
3248 }
3249 }
3250 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003251 delete bags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003252 bags = NULL;
3253 }
3254 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07003255
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003256 ssize_t findType16(const char16_t* type, size_t len) const {
3257 const size_t N = packages.size();
3258 for (size_t i = 0; i < N; i++) {
3259 ssize_t index = packages[i]->typeStrings.indexOfString(type, len);
3260 if (index >= 0) {
3261 return index + packages[i]->typeIdOffset;
3262 }
3263 }
3264 return -1;
3265 }
3266
3267 const ResTable* const owner;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003268 String16 const name;
3269 uint32_t const id;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003270
3271 // This is mainly used to keep track of the loaded packages
3272 // and to clean them up properly. Accessing resources happens from
3273 // the 'types' array.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003274 Vector<Package*> packages;
Mark Salyzyn00adb862014-03-19 11:00:06 -07003275
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003276 ByteBucketArray<TypeList> types;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003277
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003278 uint8_t largestTypeId;
Mark Salyzyn00adb862014-03-19 11:00:06 -07003279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003280 // Computed attribute bags, first indexed by the type and second
3281 // by the entry in that type.
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003282 ByteBucketArray<bag_set**>* bags;
Adam Lesinskide898ff2014-01-29 18:20:45 -08003283
3284 // The table mapping dynamic references to resolved references for
3285 // this package group.
3286 // TODO: We may be able to support dynamic references in overlays
3287 // by having these tables in a per-package scope rather than
3288 // per-package-group.
3289 DynamicRefTable dynamicRefTable;
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08003290
3291 // If the package group comes from a system asset. Used in
3292 // determining non-system locales.
3293 const bool isSystemAsset;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003294};
3295
3296struct ResTable::bag_set
3297{
3298 size_t numAttrs; // number in array
3299 size_t availAttrs; // total space in array
3300 uint32_t typeSpecFlags;
3301 // Followed by 'numAttr' bag_entry structures.
3302};
3303
3304ResTable::Theme::Theme(const ResTable& table)
3305 : mTable(table)
Alan Viverettec1d52792015-05-05 09:49:03 -07003306 , mTypeSpecFlags(0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307{
3308 memset(mPackages, 0, sizeof(mPackages));
3309}
3310
3311ResTable::Theme::~Theme()
3312{
3313 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3314 package_info* pi = mPackages[i];
3315 if (pi != NULL) {
3316 free_package(pi);
3317 }
3318 }
3319}
3320
3321void ResTable::Theme::free_package(package_info* pi)
3322{
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003323 for (size_t j = 0; j <= Res_MAXTYPE; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003324 theme_entry* te = pi->types[j].entries;
3325 if (te != NULL) {
3326 free(te);
3327 }
3328 }
3329 free(pi);
3330}
3331
3332ResTable::Theme::package_info* ResTable::Theme::copy_package(package_info* pi)
3333{
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003334 package_info* newpi = (package_info*)malloc(sizeof(package_info));
3335 for (size_t j = 0; j <= Res_MAXTYPE; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003336 size_t cnt = pi->types[j].numEntries;
3337 newpi->types[j].numEntries = cnt;
3338 theme_entry* te = pi->types[j].entries;
Vishwath Mohan6a2c23d2015-03-09 18:55:11 -07003339 size_t cnt_max = SIZE_MAX / sizeof(theme_entry);
3340 if (te != NULL && (cnt < 0xFFFFFFFF-1) && (cnt < cnt_max)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003341 theme_entry* newte = (theme_entry*)malloc(cnt*sizeof(theme_entry));
3342 newpi->types[j].entries = newte;
3343 memcpy(newte, te, cnt*sizeof(theme_entry));
3344 } else {
3345 newpi->types[j].entries = NULL;
3346 }
3347 }
3348 return newpi;
3349}
3350
3351status_t ResTable::Theme::applyStyle(uint32_t resID, bool force)
3352{
3353 const bag_entry* bag;
3354 uint32_t bagTypeSpecFlags = 0;
3355 mTable.lock();
3356 const ssize_t N = mTable.getBagLocked(resID, &bag, &bagTypeSpecFlags);
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003357 if (kDebugTableNoisy) {
3358 ALOGV("Applying style 0x%08x to theme %p, count=%zu", resID, this, N);
3359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003360 if (N < 0) {
3361 mTable.unlock();
3362 return N;
3363 }
3364
Alan Viverettec1d52792015-05-05 09:49:03 -07003365 mTypeSpecFlags |= bagTypeSpecFlags;
3366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003367 uint32_t curPackage = 0xffffffff;
3368 ssize_t curPackageIndex = 0;
3369 package_info* curPI = NULL;
3370 uint32_t curType = 0xffffffff;
3371 size_t numEntries = 0;
3372 theme_entry* curEntries = NULL;
3373
3374 const bag_entry* end = bag + N;
3375 while (bag < end) {
3376 const uint32_t attrRes = bag->map.name.ident;
3377 const uint32_t p = Res_GETPACKAGE(attrRes);
3378 const uint32_t t = Res_GETTYPE(attrRes);
3379 const uint32_t e = Res_GETENTRY(attrRes);
3380
3381 if (curPackage != p) {
3382 const ssize_t pidx = mTable.getResourcePackageIndex(attrRes);
3383 if (pidx < 0) {
Steve Block3762c312012-01-06 19:20:56 +00003384 ALOGE("Style contains key with bad package: 0x%08x\n", attrRes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003385 bag++;
3386 continue;
3387 }
3388 curPackage = p;
3389 curPackageIndex = pidx;
3390 curPI = mPackages[pidx];
3391 if (curPI == NULL) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003392 curPI = (package_info*)malloc(sizeof(package_info));
3393 memset(curPI, 0, sizeof(*curPI));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003394 mPackages[pidx] = curPI;
3395 }
3396 curType = 0xffffffff;
3397 }
3398 if (curType != t) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003399 if (t > Res_MAXTYPE) {
Steve Block3762c312012-01-06 19:20:56 +00003400 ALOGE("Style contains key with bad type: 0x%08x\n", attrRes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003401 bag++;
3402 continue;
3403 }
3404 curType = t;
3405 curEntries = curPI->types[t].entries;
3406 if (curEntries == NULL) {
3407 PackageGroup* const grp = mTable.mPackageGroups[curPackageIndex];
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003408 const TypeList& typeList = grp->types[t];
Vishwath Mohan6a2c23d2015-03-09 18:55:11 -07003409 size_t cnt = typeList.isEmpty() ? 0 : typeList[0]->entryCount;
3410 size_t cnt_max = SIZE_MAX / sizeof(theme_entry);
3411 size_t buff_size = (cnt < cnt_max && cnt < 0xFFFFFFFF-1) ?
3412 cnt*sizeof(theme_entry) : 0;
3413 curEntries = (theme_entry*)malloc(buff_size);
3414 memset(curEntries, Res_value::TYPE_NULL, buff_size);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003415 curPI->types[t].numEntries = cnt;
3416 curPI->types[t].entries = curEntries;
3417 }
3418 numEntries = curPI->types[t].numEntries;
3419 }
3420 if (e >= numEntries) {
Steve Block3762c312012-01-06 19:20:56 +00003421 ALOGE("Style contains key with bad entry: 0x%08x\n", attrRes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003422 bag++;
3423 continue;
3424 }
3425 theme_entry* curEntry = curEntries + e;
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003426 if (kDebugTableNoisy) {
3427 ALOGV("Attr 0x%08x: type=0x%x, data=0x%08x; curType=0x%x",
3428 attrRes, bag->map.value.dataType, bag->map.value.data,
3429 curEntry->value.dataType);
3430 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003431 if (force || curEntry->value.dataType == Res_value::TYPE_NULL) {
3432 curEntry->stringBlock = bag->stringBlock;
3433 curEntry->typeSpecFlags |= bagTypeSpecFlags;
3434 curEntry->value = bag->map.value;
3435 }
3436
3437 bag++;
3438 }
3439
3440 mTable.unlock();
3441
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003442 if (kDebugTableTheme) {
3443 ALOGI("Applying style 0x%08x (force=%d) theme %p...\n", resID, force, this);
3444 dumpToLog();
3445 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07003446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003447 return NO_ERROR;
3448}
3449
3450status_t ResTable::Theme::setTo(const Theme& other)
3451{
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003452 if (kDebugTableTheme) {
3453 ALOGI("Setting theme %p from theme %p...\n", this, &other);
3454 dumpToLog();
3455 other.dumpToLog();
3456 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07003457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003458 if (&mTable == &other.mTable) {
3459 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3460 if (mPackages[i] != NULL) {
3461 free_package(mPackages[i]);
3462 }
3463 if (other.mPackages[i] != NULL) {
3464 mPackages[i] = copy_package(other.mPackages[i]);
3465 } else {
3466 mPackages[i] = NULL;
3467 }
3468 }
3469 } else {
3470 // @todo: need to really implement this, not just copy
3471 // the system package (which is still wrong because it isn't
3472 // fixing up resource references).
3473 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3474 if (mPackages[i] != NULL) {
3475 free_package(mPackages[i]);
3476 }
3477 if (i == 0 && other.mPackages[i] != NULL) {
3478 mPackages[i] = copy_package(other.mPackages[i]);
3479 } else {
3480 mPackages[i] = NULL;
3481 }
3482 }
3483 }
3484
Alan Viverettec1d52792015-05-05 09:49:03 -07003485 mTypeSpecFlags = other.mTypeSpecFlags;
3486
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003487 if (kDebugTableTheme) {
3488 ALOGI("Final theme:");
3489 dumpToLog();
3490 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07003491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003492 return NO_ERROR;
3493}
3494
Alan Viverettee54d2452015-05-06 10:41:43 -07003495status_t ResTable::Theme::clear()
3496{
3497 if (kDebugTableTheme) {
3498 ALOGI("Clearing theme %p...\n", this);
3499 dumpToLog();
3500 }
3501
3502 for (size_t i = 0; i < Res_MAXPACKAGE; i++) {
3503 if (mPackages[i] != NULL) {
3504 free_package(mPackages[i]);
3505 mPackages[i] = NULL;
3506 }
3507 }
3508
3509 mTypeSpecFlags = 0;
3510
3511 if (kDebugTableTheme) {
3512 ALOGI("Final theme:");
3513 dumpToLog();
3514 }
3515
3516 return NO_ERROR;
3517}
3518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003519ssize_t ResTable::Theme::getAttribute(uint32_t resID, Res_value* outValue,
3520 uint32_t* outTypeSpecFlags) const
3521{
3522 int cnt = 20;
3523
3524 if (outTypeSpecFlags != NULL) *outTypeSpecFlags = 0;
Mark Salyzyn00adb862014-03-19 11:00:06 -07003525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003526 do {
3527 const ssize_t p = mTable.getResourcePackageIndex(resID);
3528 const uint32_t t = Res_GETTYPE(resID);
3529 const uint32_t e = Res_GETENTRY(resID);
3530
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003531 if (kDebugTableTheme) {
3532 ALOGI("Looking up attr 0x%08x in theme %p", resID, this);
3533 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003534
3535 if (p >= 0) {
3536 const package_info* const pi = mPackages[p];
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003537 if (kDebugTableTheme) {
3538 ALOGI("Found package: %p", pi);
3539 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003540 if (pi != NULL) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003541 if (kDebugTableTheme) {
3542 ALOGI("Desired type index is %zd in avail %zu", t, Res_MAXTYPE + 1);
3543 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003544 if (t <= Res_MAXTYPE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003545 const type_info& ti = pi->types[t];
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003546 if (kDebugTableTheme) {
3547 ALOGI("Desired entry index is %u in avail %zu", e, ti.numEntries);
3548 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003549 if (e < ti.numEntries) {
3550 const theme_entry& te = ti.entries[e];
Dianne Hackbornb8d81672009-11-20 14:26:42 -08003551 if (outTypeSpecFlags != NULL) {
3552 *outTypeSpecFlags |= te.typeSpecFlags;
3553 }
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003554 if (kDebugTableTheme) {
3555 ALOGI("Theme value: type=0x%x, data=0x%08x",
3556 te.value.dataType, te.value.data);
3557 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003558 const uint8_t type = te.value.dataType;
3559 if (type == Res_value::TYPE_ATTRIBUTE) {
3560 if (cnt > 0) {
3561 cnt--;
3562 resID = te.value.data;
3563 continue;
3564 }
Steve Block8564c8d2012-01-05 23:22:43 +00003565 ALOGW("Too many attribute references, stopped at: 0x%08x\n", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003566 return BAD_INDEX;
3567 } else if (type != Res_value::TYPE_NULL) {
3568 *outValue = te.value;
3569 return te.stringBlock;
3570 }
3571 return BAD_INDEX;
3572 }
3573 }
3574 }
3575 }
3576 break;
3577
3578 } while (true);
3579
3580 return BAD_INDEX;
3581}
3582
3583ssize_t ResTable::Theme::resolveAttributeReference(Res_value* inOutValue,
3584 ssize_t blockIndex, uint32_t* outLastRef,
Dianne Hackborn0d221012009-07-29 15:41:19 -07003585 uint32_t* inoutTypeSpecFlags, ResTable_config* inoutConfig) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003586{
3587 //printf("Resolving type=0x%x\n", inOutValue->dataType);
3588 if (inOutValue->dataType == Res_value::TYPE_ATTRIBUTE) {
3589 uint32_t newTypeSpecFlags;
3590 blockIndex = getAttribute(inOutValue->data, inOutValue, &newTypeSpecFlags);
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003591 if (kDebugTableTheme) {
3592 ALOGI("Resolving attr reference: blockIndex=%d, type=0x%x, data=0x%x\n",
3593 (int)blockIndex, (int)inOutValue->dataType, inOutValue->data);
3594 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003595 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newTypeSpecFlags;
3596 //printf("Retrieved attribute new type=0x%x\n", inOutValue->dataType);
3597 if (blockIndex < 0) {
3598 return blockIndex;
3599 }
3600 }
Dianne Hackborn0d221012009-07-29 15:41:19 -07003601 return mTable.resolveReference(inOutValue, blockIndex, outLastRef,
3602 inoutTypeSpecFlags, inoutConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003603}
3604
Alan Viverettec1d52792015-05-05 09:49:03 -07003605uint32_t ResTable::Theme::getChangingConfigurations() const
3606{
3607 return mTypeSpecFlags;
3608}
3609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003610void ResTable::Theme::dumpToLog() const
3611{
Steve Block6215d3f2012-01-04 20:05:49 +00003612 ALOGI("Theme %p:\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003613 for (size_t i=0; i<Res_MAXPACKAGE; i++) {
3614 package_info* pi = mPackages[i];
3615 if (pi == NULL) continue;
Mark Salyzyn00adb862014-03-19 11:00:06 -07003616
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003617 ALOGI(" Package #0x%02x:\n", (int)(i + 1));
3618 for (size_t j = 0; j <= Res_MAXTYPE; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003619 type_info& ti = pi->types[j];
3620 if (ti.numEntries == 0) continue;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003621 ALOGI(" Type #0x%02x:\n", (int)(j + 1));
3622 for (size_t k = 0; k < ti.numEntries; k++) {
3623 const theme_entry& te = ti.entries[k];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003624 if (te.value.dataType == Res_value::TYPE_NULL) continue;
Steve Block6215d3f2012-01-04 20:05:49 +00003625 ALOGI(" 0x%08x: t=0x%x, d=0x%08x (block=%d)\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003626 (int)Res_MAKEID(i, j, k),
3627 te.value.dataType, (int)te.value.data, (int)te.stringBlock);
3628 }
3629 }
3630 }
3631}
3632
3633ResTable::ResTable()
Adam Lesinskide898ff2014-01-29 18:20:45 -08003634 : mError(NO_INIT), mNextPackageId(2)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635{
3636 memset(&mParams, 0, sizeof(mParams));
3637 memset(mPackageMap, 0, sizeof(mPackageMap));
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003638 if (kDebugTableSuperNoisy) {
3639 ALOGI("Creating ResTable %p\n", this);
3640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003641}
3642
Narayan Kamath7c4887f2014-01-27 17:32:37 +00003643ResTable::ResTable(const void* data, size_t size, const int32_t cookie, bool copyData)
Adam Lesinskide898ff2014-01-29 18:20:45 -08003644 : mError(NO_INIT), mNextPackageId(2)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003645{
3646 memset(&mParams, 0, sizeof(mParams));
3647 memset(mPackageMap, 0, sizeof(mPackageMap));
Tao Baia6d7e3f2015-09-01 18:49:54 -07003648 addInternal(data, size, NULL, 0, false, cookie, copyData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003649 LOG_FATAL_IF(mError != NO_ERROR, "Error parsing resource table");
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003650 if (kDebugTableSuperNoisy) {
3651 ALOGI("Creating ResTable %p\n", this);
3652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003653}
3654
3655ResTable::~ResTable()
3656{
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003657 if (kDebugTableSuperNoisy) {
3658 ALOGI("Destroying ResTable in %p\n", this);
3659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003660 uninit();
3661}
3662
3663inline ssize_t ResTable::getResourcePackageIndex(uint32_t resID) const
3664{
3665 return ((ssize_t)mPackageMap[Res_GETPACKAGE(resID)+1])-1;
3666}
3667
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003668status_t ResTable::add(const void* data, size_t size, const int32_t cookie, bool copyData) {
Tao Baia6d7e3f2015-09-01 18:49:54 -07003669 return addInternal(data, size, NULL, 0, false, cookie, copyData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003670}
3671
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003672status_t ResTable::add(const void* data, size_t size, const void* idmapData, size_t idmapDataSize,
Tao Baia6d7e3f2015-09-01 18:49:54 -07003673 const int32_t cookie, bool copyData, bool appAsLib) {
3674 return addInternal(data, size, idmapData, idmapDataSize, appAsLib, cookie, copyData);
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003675}
3676
3677status_t ResTable::add(Asset* asset, const int32_t cookie, bool copyData) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003678 const void* data = asset->getBuffer(true);
3679 if (data == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00003680 ALOGW("Unable to get buffer of resource asset file");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003681 return UNKNOWN_ERROR;
3682 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003683
Tao Baia6d7e3f2015-09-01 18:49:54 -07003684 return addInternal(data, static_cast<size_t>(asset->getLength()), NULL, false, 0, cookie,
3685 copyData);
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003686}
3687
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08003688status_t ResTable::add(
3689 Asset* asset, Asset* idmapAsset, const int32_t cookie, bool copyData,
3690 bool appAsLib, bool isSystemAsset) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003691 const void* data = asset->getBuffer(true);
3692 if (data == NULL) {
3693 ALOGW("Unable to get buffer of resource asset file");
3694 return UNKNOWN_ERROR;
3695 }
3696
3697 size_t idmapSize = 0;
3698 const void* idmapData = NULL;
3699 if (idmapAsset != NULL) {
3700 idmapData = idmapAsset->getBuffer(true);
3701 if (idmapData == NULL) {
3702 ALOGW("Unable to get buffer of idmap asset file");
3703 return UNKNOWN_ERROR;
3704 }
3705 idmapSize = static_cast<size_t>(idmapAsset->getLength());
3706 }
3707
3708 return addInternal(data, static_cast<size_t>(asset->getLength()),
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08003709 idmapData, idmapSize, appAsLib, cookie, copyData, isSystemAsset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003710}
3711
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08003712status_t ResTable::add(ResTable* src, bool isSystemAsset)
Dianne Hackborn78c40512009-07-06 11:07:40 -07003713{
3714 mError = src->mError;
Mark Salyzyn00adb862014-03-19 11:00:06 -07003715
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08003716 for (size_t i=0; i < src->mHeaders.size(); i++) {
Dianne Hackborn78c40512009-07-06 11:07:40 -07003717 mHeaders.add(src->mHeaders[i]);
3718 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07003719
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08003720 for (size_t i=0; i < src->mPackageGroups.size(); i++) {
Dianne Hackborn78c40512009-07-06 11:07:40 -07003721 PackageGroup* srcPg = src->mPackageGroups[i];
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08003722 PackageGroup* pg = new PackageGroup(this, srcPg->name, srcPg->id,
3723 false /* appAsLib */, isSystemAsset || srcPg->isSystemAsset);
Dianne Hackborn78c40512009-07-06 11:07:40 -07003724 for (size_t j=0; j<srcPg->packages.size(); j++) {
3725 pg->packages.add(srcPg->packages[j]);
3726 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003727
3728 for (size_t j = 0; j < srcPg->types.size(); j++) {
3729 if (srcPg->types[j].isEmpty()) {
3730 continue;
3731 }
3732
3733 TypeList& typeList = pg->types.editItemAt(j);
3734 typeList.appendVector(srcPg->types[j]);
3735 }
Adam Lesinski6022deb2014-08-20 14:59:19 -07003736 pg->dynamicRefTable.addMappings(srcPg->dynamicRefTable);
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003737 pg->largestTypeId = max(pg->largestTypeId, srcPg->largestTypeId);
Dianne Hackborn78c40512009-07-06 11:07:40 -07003738 mPackageGroups.add(pg);
3739 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07003740
Dianne Hackborn78c40512009-07-06 11:07:40 -07003741 memcpy(mPackageMap, src->mPackageMap, sizeof(mPackageMap));
Mark Salyzyn00adb862014-03-19 11:00:06 -07003742
Dianne Hackborn78c40512009-07-06 11:07:40 -07003743 return mError;
3744}
3745
Adam Lesinskide898ff2014-01-29 18:20:45 -08003746status_t ResTable::addEmpty(const int32_t cookie) {
3747 Header* header = new Header(this);
3748 header->index = mHeaders.size();
3749 header->cookie = cookie;
3750 header->values.setToEmpty();
3751 header->ownedData = calloc(1, sizeof(ResTable_header));
3752
3753 ResTable_header* resHeader = (ResTable_header*) header->ownedData;
3754 resHeader->header.type = RES_TABLE_TYPE;
3755 resHeader->header.headerSize = sizeof(ResTable_header);
3756 resHeader->header.size = sizeof(ResTable_header);
3757
3758 header->header = (const ResTable_header*) resHeader;
3759 mHeaders.add(header);
Adam Lesinski961dda72014-06-09 17:10:29 -07003760 return (mError=NO_ERROR);
Adam Lesinskide898ff2014-01-29 18:20:45 -08003761}
3762
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003763status_t ResTable::addInternal(const void* data, size_t dataSize, const void* idmapData, size_t idmapDataSize,
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08003764 bool appAsLib, const int32_t cookie, bool copyData, bool isSystemAsset)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003765{
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003766 if (!data) {
3767 return NO_ERROR;
3768 }
3769
Adam Lesinskif28d5052014-07-25 15:25:04 -07003770 if (dataSize < sizeof(ResTable_header)) {
3771 ALOGE("Invalid data. Size(%d) is smaller than a ResTable_header(%d).",
3772 (int) dataSize, (int) sizeof(ResTable_header));
3773 return UNKNOWN_ERROR;
3774 }
3775
Dianne Hackborn78c40512009-07-06 11:07:40 -07003776 Header* header = new Header(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003777 header->index = mHeaders.size();
3778 header->cookie = cookie;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003779 if (idmapData != NULL) {
3780 header->resourceIDMap = (uint32_t*) malloc(idmapDataSize);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01003781 if (header->resourceIDMap == NULL) {
3782 delete header;
3783 return (mError = NO_MEMORY);
3784 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003785 memcpy(header->resourceIDMap, idmapData, idmapDataSize);
3786 header->resourceIDMapSize = idmapDataSize;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01003787 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003788 mHeaders.add(header);
3789
3790 const bool notDeviceEndian = htods(0xf0) != 0xf0;
3791
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003792 if (kDebugLoadTableNoisy) {
3793 ALOGV("Adding resources to ResTable: data=%p, size=%zu, cookie=%d, copy=%d "
3794 "idmap=%p\n", data, dataSize, cookie, copyData, idmapData);
3795 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07003796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003797 if (copyData || notDeviceEndian) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003798 header->ownedData = malloc(dataSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003799 if (header->ownedData == NULL) {
3800 return (mError=NO_MEMORY);
3801 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003802 memcpy(header->ownedData, data, dataSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003803 data = header->ownedData;
3804 }
3805
3806 header->header = (const ResTable_header*)data;
3807 header->size = dtohl(header->header->header.size);
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003808 if (kDebugLoadTableSuperNoisy) {
3809 ALOGI("Got size %zu, again size 0x%x, raw size 0x%x\n", header->size,
3810 dtohl(header->header->header.size), header->header->header.size);
3811 }
3812 if (kDebugLoadTableNoisy) {
3813 ALOGV("Loading ResTable @%p:\n", header->header);
3814 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003815 if (dtohs(header->header->header.headerSize) > header->size
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003816 || header->size > dataSize) {
Steve Block8564c8d2012-01-05 23:22:43 +00003817 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 -08003818 (int)dtohs(header->header->header.headerSize),
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003819 (int)header->size, (int)dataSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003820 return (mError=BAD_TYPE);
3821 }
3822 if (((dtohs(header->header->header.headerSize)|header->size)&0x3) != 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003823 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 -08003824 (int)dtohs(header->header->header.headerSize),
3825 (int)header->size);
3826 return (mError=BAD_TYPE);
3827 }
3828 header->dataEnd = ((const uint8_t*)header->header) + header->size;
3829
3830 // Iterate through all chunks.
3831 size_t curPackage = 0;
3832
3833 const ResChunk_header* chunk =
3834 (const ResChunk_header*)(((const uint8_t*)header->header)
3835 + dtohs(header->header->header.headerSize));
3836 while (((const uint8_t*)chunk) <= (header->dataEnd-sizeof(ResChunk_header)) &&
3837 ((const uint8_t*)chunk) <= (header->dataEnd-dtohl(chunk->size))) {
3838 status_t err = validate_chunk(chunk, sizeof(ResChunk_header), header->dataEnd, "ResTable");
3839 if (err != NO_ERROR) {
3840 return (mError=err);
3841 }
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003842 if (kDebugTableNoisy) {
3843 ALOGV("Chunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n",
3844 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
3845 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)));
3846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003847 const size_t csize = dtohl(chunk->size);
3848 const uint16_t ctype = dtohs(chunk->type);
3849 if (ctype == RES_STRING_POOL_TYPE) {
3850 if (header->values.getError() != NO_ERROR) {
3851 // Only use the first string chunk; ignore any others that
3852 // may appear.
3853 status_t err = header->values.setTo(chunk, csize);
3854 if (err != NO_ERROR) {
3855 return (mError=err);
3856 }
3857 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003858 ALOGW("Multiple string chunks found in resource table.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859 }
3860 } else if (ctype == RES_TABLE_PACKAGE_TYPE) {
3861 if (curPackage >= dtohl(header->header->packageCount)) {
Steve Block8564c8d2012-01-05 23:22:43 +00003862 ALOGW("More package chunks were found than the %d declared in the header.",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003863 dtohl(header->header->packageCount));
3864 return (mError=BAD_TYPE);
3865 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003866
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08003867 if (parsePackage(
3868 (ResTable_package*)chunk, header, appAsLib, isSystemAsset) != NO_ERROR) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003869 return mError;
3870 }
3871 curPackage++;
3872 } else {
Patrik Bannura443dd932014-02-12 13:38:54 +01003873 ALOGW("Unknown chunk type 0x%x in table at %p.\n",
3874 ctype,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003875 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)));
3876 }
3877 chunk = (const ResChunk_header*)
3878 (((const uint8_t*)chunk) + csize);
3879 }
3880
3881 if (curPackage < dtohl(header->header->packageCount)) {
Steve Block8564c8d2012-01-05 23:22:43 +00003882 ALOGW("Fewer package chunks (%d) were found than the %d declared in the header.",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003883 (int)curPackage, dtohl(header->header->packageCount));
3884 return (mError=BAD_TYPE);
3885 }
3886 mError = header->values.getError();
3887 if (mError != NO_ERROR) {
Steve Block8564c8d2012-01-05 23:22:43 +00003888 ALOGW("No string values found in resource table!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003889 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01003890
Andreas Gampe2204f0b2014-10-21 23:04:54 -07003891 if (kDebugTableNoisy) {
3892 ALOGV("Returning from add with mError=%d\n", mError);
3893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003894 return mError;
3895}
3896
3897status_t ResTable::getError() const
3898{
3899 return mError;
3900}
3901
3902void ResTable::uninit()
3903{
3904 mError = NO_INIT;
3905 size_t N = mPackageGroups.size();
3906 for (size_t i=0; i<N; i++) {
3907 PackageGroup* g = mPackageGroups[i];
3908 delete g;
3909 }
3910 N = mHeaders.size();
3911 for (size_t i=0; i<N; i++) {
3912 Header* header = mHeaders[i];
Dianne Hackborn78c40512009-07-06 11:07:40 -07003913 if (header->owner == this) {
3914 if (header->ownedData) {
3915 free(header->ownedData);
3916 }
3917 delete header;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003918 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003919 }
3920
3921 mPackageGroups.clear();
3922 mHeaders.clear();
3923}
3924
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07003925bool ResTable::getResourceName(uint32_t resID, bool allowUtf8, resource_name* outName) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003926{
3927 if (mError != NO_ERROR) {
3928 return false;
3929 }
3930
3931 const ssize_t p = getResourcePackageIndex(resID);
3932 const int t = Res_GETTYPE(resID);
3933 const int e = Res_GETENTRY(resID);
3934
3935 if (p < 0) {
Dianne Hackborn6cca1592009-09-20 12:40:03 -07003936 if (Res_GETPACKAGE(resID)+1 == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003937 ALOGW("No package identifier when getting name for resource number 0x%08x", resID);
Dianne Hackborn6cca1592009-09-20 12:40:03 -07003938 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003939 ALOGW("No known package when getting name for resource number 0x%08x", resID);
Dianne Hackborn6cca1592009-09-20 12:40:03 -07003940 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003941 return false;
3942 }
3943 if (t < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003944 ALOGW("No type identifier when getting name for resource number 0x%08x", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003945 return false;
3946 }
3947
3948 const PackageGroup* const grp = mPackageGroups[p];
3949 if (grp == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00003950 ALOGW("Bad identifier when getting name for resource number 0x%08x", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003951 return false;
3952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003953
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003954 Entry entry;
3955 status_t err = getEntry(grp, t, e, NULL, &entry);
3956 if (err != NO_ERROR) {
3957 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003958 }
3959
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003960 outName->package = grp->name.string();
3961 outName->packageLen = grp->name.size();
3962 if (allowUtf8) {
3963 outName->type8 = entry.typeStr.string8(&outName->typeLen);
3964 outName->name8 = entry.keyStr.string8(&outName->nameLen);
3965 } else {
3966 outName->type8 = NULL;
3967 outName->name8 = NULL;
3968 }
3969 if (outName->type8 == NULL) {
3970 outName->type = entry.typeStr.string16(&outName->typeLen);
3971 // If we have a bad index for some reason, we should abort.
3972 if (outName->type == NULL) {
3973 return false;
3974 }
3975 }
3976 if (outName->name8 == NULL) {
3977 outName->name = entry.keyStr.string16(&outName->nameLen);
3978 // If we have a bad index for some reason, we should abort.
3979 if (outName->name == NULL) {
3980 return false;
3981 }
3982 }
3983
3984 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003985}
3986
Kenny Root55fc8502010-10-28 14:47:01 -07003987ssize_t ResTable::getResource(uint32_t resID, Res_value* outValue, bool mayBeBag, uint16_t density,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003988 uint32_t* outSpecFlags, ResTable_config* outConfig) const
3989{
3990 if (mError != NO_ERROR) {
3991 return mError;
3992 }
3993
3994 const ssize_t p = getResourcePackageIndex(resID);
3995 const int t = Res_GETTYPE(resID);
3996 const int e = Res_GETENTRY(resID);
3997
3998 if (p < 0) {
Dianne Hackborn6cca1592009-09-20 12:40:03 -07003999 if (Res_GETPACKAGE(resID)+1 == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00004000 ALOGW("No package identifier when getting value for resource number 0x%08x", resID);
Dianne Hackborn6cca1592009-09-20 12:40:03 -07004001 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00004002 ALOGW("No known package when getting value for resource number 0x%08x", resID);
Dianne Hackborn6cca1592009-09-20 12:40:03 -07004003 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004004 return BAD_INDEX;
4005 }
4006 if (t < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00004007 ALOGW("No type identifier when getting value for resource number 0x%08x", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004008 return BAD_INDEX;
4009 }
4010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 const PackageGroup* const grp = mPackageGroups[p];
4012 if (grp == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00004013 ALOGW("Bad identifier when getting value for resource number 0x%08x", resID);
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08004014 return BAD_INDEX;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004015 }
Kenny Root55fc8502010-10-28 14:47:01 -07004016
4017 // Allow overriding density
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004018 ResTable_config desiredConfig = mParams;
Kenny Root55fc8502010-10-28 14:47:01 -07004019 if (density > 0) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004020 desiredConfig.density = density;
Kenny Root55fc8502010-10-28 14:47:01 -07004021 }
4022
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004023 Entry entry;
4024 status_t err = getEntry(grp, t, e, &desiredConfig, &entry);
4025 if (err != NO_ERROR) {
Adam Lesinskide7de472014-11-03 12:03:08 -08004026 // Only log the failure when we're not running on the host as
4027 // part of a tool. The caller will do its own logging.
4028#ifndef STATIC_ANDROIDFW_FOR_TOOLS
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004029 ALOGW("Failure getting entry for 0x%08x (t=%d e=%d) (error %d)\n",
4030 resID, t, e, err);
Adam Lesinskide7de472014-11-03 12:03:08 -08004031#endif
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004032 return err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004033 }
4034
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004035 if ((dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) != 0) {
4036 if (!mayBeBag) {
4037 ALOGW("Requesting resource 0x%08x failed because it is complex\n", resID);
Adam Lesinskide898ff2014-01-29 18:20:45 -08004038 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004039 return BAD_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004040 }
4041
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004042 const Res_value* value = reinterpret_cast<const Res_value*>(
4043 reinterpret_cast<const uint8_t*>(entry.entry) + entry.entry->size);
4044
4045 outValue->size = dtohs(value->size);
4046 outValue->res0 = value->res0;
4047 outValue->dataType = value->dataType;
4048 outValue->data = dtohl(value->data);
4049
4050 // The reference may be pointing to a resource in a shared library. These
4051 // references have build-time generated package IDs. These ids may not match
4052 // the actual package IDs of the corresponding packages in this ResTable.
4053 // We need to fix the package ID based on a mapping.
4054 if (grp->dynamicRefTable.lookupResourceValue(outValue) != NO_ERROR) {
4055 ALOGW("Failed to resolve referenced package: 0x%08x", outValue->data);
4056 return BAD_VALUE;
Kenny Root55fc8502010-10-28 14:47:01 -07004057 }
4058
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004059 if (kDebugTableNoisy) {
4060 size_t len;
4061 printf("Found value: pkg=%zu, type=%d, str=%s, int=%d\n",
4062 entry.package->header->index,
4063 outValue->dataType,
4064 outValue->dataType == Res_value::TYPE_STRING ?
4065 String8(entry.package->header->values.stringAt(outValue->data, &len)).string() :
4066 "",
4067 outValue->data);
4068 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004069
4070 if (outSpecFlags != NULL) {
4071 *outSpecFlags = entry.specFlags;
4072 }
4073
4074 if (outConfig != NULL) {
4075 *outConfig = entry.config;
4076 }
4077
4078 return entry.package->header->index;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004079}
4080
4081ssize_t ResTable::resolveReference(Res_value* value, ssize_t blockIndex,
Dianne Hackborn0d221012009-07-29 15:41:19 -07004082 uint32_t* outLastRef, uint32_t* inoutTypeSpecFlags,
4083 ResTable_config* outConfig) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004084{
4085 int count=0;
Adam Lesinskide898ff2014-01-29 18:20:45 -08004086 while (blockIndex >= 0 && value->dataType == Res_value::TYPE_REFERENCE
4087 && value->data != 0 && count < 20) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004088 if (outLastRef) *outLastRef = value->data;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004089 uint32_t newFlags = 0;
Kenny Root55fc8502010-10-28 14:47:01 -07004090 const ssize_t newIndex = getResource(value->data, value, true, 0, &newFlags,
Dianne Hackborn0d221012009-07-29 15:41:19 -07004091 outConfig);
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08004092 if (newIndex == BAD_INDEX) {
4093 return BAD_INDEX;
4094 }
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004095 if (kDebugTableTheme) {
4096 ALOGI("Resolving reference 0x%x: newIndex=%d, type=0x%x, data=0x%x\n",
4097 value->data, (int)newIndex, (int)value->dataType, value->data);
4098 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004099 //printf("Getting reference 0x%08x: newIndex=%d\n", value->data, newIndex);
4100 if (inoutTypeSpecFlags != NULL) *inoutTypeSpecFlags |= newFlags;
4101 if (newIndex < 0) {
4102 // This can fail if the resource being referenced is a style...
4103 // in this case, just return the reference, and expect the
4104 // caller to deal with.
4105 return blockIndex;
4106 }
4107 blockIndex = newIndex;
4108 count++;
4109 }
4110 return blockIndex;
4111}
4112
4113const char16_t* ResTable::valueToString(
4114 const Res_value* value, size_t stringBlock,
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07004115 char16_t /*tmpBuffer*/ [TMP_BUFFER_SIZE], size_t* outLen) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004116{
4117 if (!value) {
4118 return NULL;
4119 }
4120 if (value->dataType == value->TYPE_STRING) {
4121 return getTableStringBlock(stringBlock)->stringAt(value->data, outLen);
4122 }
4123 // XXX do int to string conversions.
4124 return NULL;
4125}
4126
4127ssize_t ResTable::lockBag(uint32_t resID, const bag_entry** outBag) const
4128{
4129 mLock.lock();
4130 ssize_t err = getBagLocked(resID, outBag);
4131 if (err < NO_ERROR) {
4132 //printf("*** get failed! unlocking\n");
4133 mLock.unlock();
4134 }
4135 return err;
4136}
4137
Mark Salyzyn00adb862014-03-19 11:00:06 -07004138void ResTable::unlockBag(const bag_entry* /*bag*/) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004139{
4140 //printf("<<< unlockBag %p\n", this);
4141 mLock.unlock();
4142}
4143
4144void ResTable::lock() const
4145{
4146 mLock.lock();
4147}
4148
4149void ResTable::unlock() const
4150{
4151 mLock.unlock();
4152}
4153
4154ssize_t ResTable::getBagLocked(uint32_t resID, const bag_entry** outBag,
4155 uint32_t* outTypeSpecFlags) const
4156{
4157 if (mError != NO_ERROR) {
4158 return mError;
4159 }
4160
4161 const ssize_t p = getResourcePackageIndex(resID);
4162 const int t = Res_GETTYPE(resID);
4163 const int e = Res_GETENTRY(resID);
4164
4165 if (p < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00004166 ALOGW("Invalid package identifier when getting bag for resource number 0x%08x", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004167 return BAD_INDEX;
4168 }
4169 if (t < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00004170 ALOGW("No type identifier when getting bag for resource number 0x%08x", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004171 return BAD_INDEX;
4172 }
4173
4174 //printf("Get bag: id=0x%08x, p=%d, t=%d\n", resID, p, t);
4175 PackageGroup* const grp = mPackageGroups[p];
4176 if (grp == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00004177 ALOGW("Bad identifier when getting bag for resource number 0x%08x", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004178 return BAD_INDEX;
4179 }
4180
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004181 const TypeList& typeConfigs = grp->types[t];
4182 if (typeConfigs.isEmpty()) {
4183 ALOGW("Type identifier 0x%x does not exist.", t+1);
4184 return BAD_INDEX;
4185 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004186
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004187 const size_t NENTRY = typeConfigs[0]->entryCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004188 if (e >= (int)NENTRY) {
Steve Block8564c8d2012-01-05 23:22:43 +00004189 ALOGW("Entry identifier 0x%x is larger than entry count 0x%x",
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004190 e, (int)typeConfigs[0]->entryCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004191 return BAD_INDEX;
4192 }
4193
4194 // First see if we've already computed this bag...
4195 if (grp->bags) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004196 bag_set** typeSet = grp->bags->get(t);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004197 if (typeSet) {
4198 bag_set* set = typeSet[e];
4199 if (set) {
4200 if (set != (bag_set*)0xFFFFFFFF) {
4201 if (outTypeSpecFlags != NULL) {
4202 *outTypeSpecFlags = set->typeSpecFlags;
4203 }
4204 *outBag = (bag_entry*)(set+1);
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004205 if (kDebugTableSuperNoisy) {
4206 ALOGI("Found existing bag for: 0x%x\n", resID);
4207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004208 return set->numAttrs;
4209 }
Steve Block8564c8d2012-01-05 23:22:43 +00004210 ALOGW("Attempt to retrieve bag 0x%08x which is invalid or in a cycle.",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004211 resID);
4212 return BAD_INDEX;
4213 }
4214 }
4215 }
4216
4217 // Bag not found, we need to compute it!
4218 if (!grp->bags) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004219 grp->bags = new ByteBucketArray<bag_set**>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004220 if (!grp->bags) return NO_MEMORY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004221 }
4222
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004223 bag_set** typeSet = grp->bags->get(t);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004224 if (!typeSet) {
Iliyan Malchev7e1d3952012-02-17 12:15:58 -08004225 typeSet = (bag_set**)calloc(NENTRY, sizeof(bag_set*));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004226 if (!typeSet) return NO_MEMORY;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004227 grp->bags->set(t, typeSet);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004228 }
4229
4230 // Mark that we are currently working on this one.
4231 typeSet[e] = (bag_set*)0xFFFFFFFF;
4232
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004233 if (kDebugTableNoisy) {
4234 ALOGI("Building bag: %x\n", resID);
4235 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004236
4237 // Now collect all bag attributes
4238 Entry entry;
4239 status_t err = getEntry(grp, t, e, &mParams, &entry);
4240 if (err != NO_ERROR) {
4241 return err;
4242 }
4243
4244 const uint16_t entrySize = dtohs(entry.entry->size);
4245 const uint32_t parent = entrySize >= sizeof(ResTable_map_entry)
4246 ? dtohl(((const ResTable_map_entry*)entry.entry)->parent.ident) : 0;
4247 const uint32_t count = entrySize >= sizeof(ResTable_map_entry)
4248 ? dtohl(((const ResTable_map_entry*)entry.entry)->count) : 0;
4249
4250 size_t N = count;
4251
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004252 if (kDebugTableNoisy) {
4253 ALOGI("Found map: size=%x parent=%x count=%d\n", entrySize, parent, count);
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004254
4255 // If this map inherits from another, we need to start
4256 // with its parent's values. Otherwise start out empty.
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004257 ALOGI("Creating new bag, entrySize=0x%08x, parent=0x%08x\n", entrySize, parent);
4258 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004260 // This is what we are building.
4261 bag_set* set = NULL;
4262
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004263 if (parent) {
4264 uint32_t resolvedParent = parent;
Mark Salyzyn00adb862014-03-19 11:00:06 -07004265
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004266 // Bags encode a parent reference without using the standard
4267 // Res_value structure. That means we must always try to
4268 // resolve a parent reference in case it is actually a
4269 // TYPE_DYNAMIC_REFERENCE.
4270 status_t err = grp->dynamicRefTable.lookupResourceId(&resolvedParent);
4271 if (err != NO_ERROR) {
4272 ALOGE("Failed resolving bag parent id 0x%08x", parent);
4273 return UNKNOWN_ERROR;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01004274 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004275
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004276 const bag_entry* parentBag;
4277 uint32_t parentTypeSpecFlags = 0;
4278 const ssize_t NP = getBagLocked(resolvedParent, &parentBag, &parentTypeSpecFlags);
4279 const size_t NT = ((NP >= 0) ? NP : 0) + N;
4280 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*NT);
4281 if (set == NULL) {
4282 return NO_MEMORY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004283 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004284 if (NP > 0) {
4285 memcpy(set+1, parentBag, NP*sizeof(bag_entry));
4286 set->numAttrs = NP;
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004287 if (kDebugTableNoisy) {
4288 ALOGI("Initialized new bag with %zd inherited attributes.\n", NP);
4289 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01004290 } else {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004291 if (kDebugTableNoisy) {
4292 ALOGI("Initialized new bag with no inherited attributes.\n");
4293 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01004294 set->numAttrs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004295 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004296 set->availAttrs = NT;
4297 set->typeSpecFlags = parentTypeSpecFlags;
4298 } else {
4299 set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*N);
4300 if (set == NULL) {
4301 return NO_MEMORY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004302 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004303 set->numAttrs = 0;
4304 set->availAttrs = N;
4305 set->typeSpecFlags = 0;
4306 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07004307
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004308 set->typeSpecFlags |= entry.specFlags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004309
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004310 // Now merge in the new attributes...
4311 size_t curOff = (reinterpret_cast<uintptr_t>(entry.entry) - reinterpret_cast<uintptr_t>(entry.type))
4312 + dtohs(entry.entry->size);
4313 const ResTable_map* map;
4314 bag_entry* entries = (bag_entry*)(set+1);
4315 size_t curEntry = 0;
4316 uint32_t pos = 0;
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004317 if (kDebugTableNoisy) {
4318 ALOGI("Starting with set %p, entries=%p, avail=%zu\n", set, entries, set->availAttrs);
4319 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004320 while (pos < count) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004321 if (kDebugTableNoisy) {
4322 ALOGI("Now at %p\n", (void*)curOff);
4323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004324
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004325 if (curOff > (dtohl(entry.type->header.size)-sizeof(ResTable_map))) {
4326 ALOGW("ResTable_map at %d is beyond type chunk data %d",
4327 (int)curOff, dtohl(entry.type->header.size));
4328 return BAD_TYPE;
4329 }
4330 map = (const ResTable_map*)(((const uint8_t*)entry.type) + curOff);
4331 N++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004332
Adam Lesinskiccf25c7b2014-08-08 15:32:40 -07004333 uint32_t newName = htodl(map->name.ident);
4334 if (!Res_INTERNALID(newName)) {
4335 // Attributes don't have a resource id as the name. They specify
4336 // other data, which would be wrong to change via a lookup.
4337 if (grp->dynamicRefTable.lookupResourceId(&newName) != NO_ERROR) {
4338 ALOGE("Failed resolving ResTable_map name at %d with ident 0x%08x",
4339 (int) curOff, (int) newName);
4340 return UNKNOWN_ERROR;
4341 }
4342 }
4343
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004344 bool isInside;
4345 uint32_t oldName = 0;
4346 while ((isInside=(curEntry < set->numAttrs))
4347 && (oldName=entries[curEntry].map.name.ident) < newName) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004348 if (kDebugTableNoisy) {
4349 ALOGI("#%zu: Keeping existing attribute: 0x%08x\n",
4350 curEntry, entries[curEntry].map.name.ident);
4351 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004352 curEntry++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004353 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004354
4355 if ((!isInside) || oldName != newName) {
4356 // This is a new attribute... figure out what to do with it.
4357 if (set->numAttrs >= set->availAttrs) {
4358 // Need to alloc more memory...
4359 const size_t newAvail = set->availAttrs+N;
4360 set = (bag_set*)realloc(set,
4361 sizeof(bag_set)
4362 + sizeof(bag_entry)*newAvail);
4363 if (set == NULL) {
4364 return NO_MEMORY;
4365 }
4366 set->availAttrs = newAvail;
4367 entries = (bag_entry*)(set+1);
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004368 if (kDebugTableNoisy) {
4369 ALOGI("Reallocated set %p, entries=%p, avail=%zu\n",
4370 set, entries, set->availAttrs);
4371 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004372 }
4373 if (isInside) {
4374 // Going in the middle, need to make space.
4375 memmove(entries+curEntry+1, entries+curEntry,
4376 sizeof(bag_entry)*(set->numAttrs-curEntry));
4377 set->numAttrs++;
4378 }
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004379 if (kDebugTableNoisy) {
4380 ALOGI("#%zu: Inserting new attribute: 0x%08x\n", curEntry, newName);
4381 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004382 } else {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004383 if (kDebugTableNoisy) {
4384 ALOGI("#%zu: Replacing existing attribute: 0x%08x\n", curEntry, oldName);
4385 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004386 }
4387
4388 bag_entry* cur = entries+curEntry;
4389
4390 cur->stringBlock = entry.package->header->index;
4391 cur->map.name.ident = newName;
4392 cur->map.value.copyFrom_dtoh(map->value);
4393 status_t err = grp->dynamicRefTable.lookupResourceValue(&cur->map.value);
4394 if (err != NO_ERROR) {
4395 ALOGE("Reference item(0x%08x) in bag could not be resolved.", cur->map.value.data);
4396 return UNKNOWN_ERROR;
4397 }
4398
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004399 if (kDebugTableNoisy) {
4400 ALOGI("Setting entry #%zu %p: block=%zd, name=0x%08d, type=%d, data=0x%08x\n",
4401 curEntry, cur, cur->stringBlock, cur->map.name.ident,
4402 cur->map.value.dataType, cur->map.value.data);
4403 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004404
4405 // On to the next!
4406 curEntry++;
4407 pos++;
4408 const size_t size = dtohs(map->value.size);
4409 curOff += size + sizeof(*map)-sizeof(map->value);
4410 };
4411
4412 if (curEntry > set->numAttrs) {
4413 set->numAttrs = curEntry;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004414 }
4415
4416 // And this is it...
4417 typeSet[e] = set;
4418 if (set) {
4419 if (outTypeSpecFlags != NULL) {
4420 *outTypeSpecFlags = set->typeSpecFlags;
4421 }
4422 *outBag = (bag_entry*)(set+1);
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004423 if (kDebugTableNoisy) {
4424 ALOGI("Returning %zu attrs\n", set->numAttrs);
4425 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004426 return set->numAttrs;
4427 }
4428 return BAD_INDEX;
4429}
4430
4431void ResTable::setParameters(const ResTable_config* params)
4432{
Adam Lesinskifa7d78a2016-03-07 19:39:56 +00004433 mLock.lock();
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004434 if (kDebugTableGetEntry) {
4435 ALOGI("Setting parameters: %s\n", params->toString().string());
4436 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004437 mParams = *params;
Adam Lesinskifa7d78a2016-03-07 19:39:56 +00004438 for (size_t i=0; i<mPackageGroups.size(); i++) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004439 if (kDebugTableNoisy) {
Adam Lesinskifa7d78a2016-03-07 19:39:56 +00004440 ALOGI("CLEARING BAGS FOR GROUP %zu!", i);
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004441 }
Adam Lesinskifa7d78a2016-03-07 19:39:56 +00004442 mPackageGroups[i]->clearBagCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004443 }
Adam Lesinskifa7d78a2016-03-07 19:39:56 +00004444 mLock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004445}
4446
4447void ResTable::getParameters(ResTable_config* params) const
4448{
4449 mLock.lock();
4450 *params = mParams;
4451 mLock.unlock();
4452}
4453
4454struct id_name_map {
4455 uint32_t id;
4456 size_t len;
4457 char16_t name[6];
4458};
4459
4460const static id_name_map ID_NAMES[] = {
4461 { ResTable_map::ATTR_TYPE, 5, { '^', 't', 'y', 'p', 'e' } },
4462 { ResTable_map::ATTR_L10N, 5, { '^', 'l', '1', '0', 'n' } },
4463 { ResTable_map::ATTR_MIN, 4, { '^', 'm', 'i', 'n' } },
4464 { ResTable_map::ATTR_MAX, 4, { '^', 'm', 'a', 'x' } },
4465 { ResTable_map::ATTR_OTHER, 6, { '^', 'o', 't', 'h', 'e', 'r' } },
4466 { ResTable_map::ATTR_ZERO, 5, { '^', 'z', 'e', 'r', 'o' } },
4467 { ResTable_map::ATTR_ONE, 4, { '^', 'o', 'n', 'e' } },
4468 { ResTable_map::ATTR_TWO, 4, { '^', 't', 'w', 'o' } },
4469 { ResTable_map::ATTR_FEW, 4, { '^', 'f', 'e', 'w' } },
4470 { ResTable_map::ATTR_MANY, 5, { '^', 'm', 'a', 'n', 'y' } },
4471};
4472
4473uint32_t ResTable::identifierForName(const char16_t* name, size_t nameLen,
4474 const char16_t* type, size_t typeLen,
4475 const char16_t* package,
4476 size_t packageLen,
4477 uint32_t* outTypeSpecFlags) const
4478{
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004479 if (kDebugTableSuperNoisy) {
4480 printf("Identifier for name: error=%d\n", mError);
4481 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004482
4483 // Check for internal resource identifier as the very first thing, so
4484 // that we will always find them even when there are no resources.
4485 if (name[0] == '^') {
4486 const int N = (sizeof(ID_NAMES)/sizeof(ID_NAMES[0]));
4487 size_t len;
4488 for (int i=0; i<N; i++) {
4489 const id_name_map* m = ID_NAMES + i;
4490 len = m->len;
4491 if (len != nameLen) {
4492 continue;
4493 }
4494 for (size_t j=1; j<len; j++) {
4495 if (m->name[j] != name[j]) {
4496 goto nope;
4497 }
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 m->id;
4503nope:
4504 ;
4505 }
4506 if (nameLen > 7) {
4507 if (name[1] == 'i' && name[2] == 'n'
4508 && name[3] == 'd' && name[4] == 'e' && name[5] == 'x'
4509 && name[6] == '_') {
4510 int index = atoi(String8(name + 7, nameLen - 7).string());
4511 if (Res_CHECKID(index)) {
Steve Block8564c8d2012-01-05 23:22:43 +00004512 ALOGW("Array resource index: %d is too large.",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004513 index);
4514 return 0;
4515 }
Dianne Hackborn426431a2011-06-09 11:29:08 -07004516 if (outTypeSpecFlags) {
4517 *outTypeSpecFlags = ResTable_typeSpec::SPEC_PUBLIC;
4518 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004519 return Res_MAKEARRAY(index);
4520 }
4521 }
4522 return 0;
4523 }
4524
4525 if (mError != NO_ERROR) {
4526 return 0;
4527 }
4528
Dianne Hackborn426431a2011-06-09 11:29:08 -07004529 bool fakePublic = false;
4530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004531 // Figure out the package and type we are looking in...
4532
4533 const char16_t* packageEnd = NULL;
4534 const char16_t* typeEnd = NULL;
4535 const char16_t* const nameEnd = name+nameLen;
4536 const char16_t* p = name;
4537 while (p < nameEnd) {
4538 if (*p == ':') packageEnd = p;
4539 else if (*p == '/') typeEnd = p;
4540 p++;
4541 }
Dianne Hackborn426431a2011-06-09 11:29:08 -07004542 if (*name == '@') {
4543 name++;
4544 if (*name == '*') {
4545 fakePublic = true;
4546 name++;
4547 }
4548 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004549 if (name >= nameEnd) {
4550 return 0;
4551 }
4552
4553 if (packageEnd) {
4554 package = name;
4555 packageLen = packageEnd-name;
4556 name = packageEnd+1;
4557 } else if (!package) {
4558 return 0;
4559 }
4560
4561 if (typeEnd) {
4562 type = name;
4563 typeLen = typeEnd-name;
4564 name = typeEnd+1;
4565 } else if (!type) {
4566 return 0;
4567 }
4568
4569 if (name >= nameEnd) {
4570 return 0;
4571 }
4572 nameLen = nameEnd-name;
4573
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004574 if (kDebugTableNoisy) {
4575 printf("Looking for identifier: type=%s, name=%s, package=%s\n",
4576 String8(type, typeLen).string(),
4577 String8(name, nameLen).string(),
4578 String8(package, packageLen).string());
4579 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004580
Adam Lesinski9b624c12014-11-19 17:49:26 -08004581 const String16 attr("attr");
4582 const String16 attrPrivate("^attr-private");
4583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004584 const size_t NG = mPackageGroups.size();
4585 for (size_t ig=0; ig<NG; ig++) {
4586 const PackageGroup* group = mPackageGroups[ig];
4587
4588 if (strzcmp16(package, packageLen,
4589 group->name.string(), group->name.size())) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07004590 if (kDebugTableNoisy) {
4591 printf("Skipping package group: %s\n", String8(group->name).string());
4592 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004593 continue;
4594 }
4595
Adam Lesinskie60a87f2014-10-09 11:08:04 -07004596 const size_t packageCount = group->packages.size();
4597 for (size_t pi = 0; pi < packageCount; pi++) {
Adam Lesinski9b624c12014-11-19 17:49:26 -08004598 const char16_t* targetType = type;
4599 size_t targetTypeLen = typeLen;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004600
Adam Lesinski9b624c12014-11-19 17:49:26 -08004601 do {
4602 ssize_t ti = group->packages[pi]->typeStrings.indexOfString(
4603 targetType, targetTypeLen);
4604 if (ti < 0) {
Adam Lesinskie60a87f2014-10-09 11:08:04 -07004605 continue;
4606 }
4607
Adam Lesinski9b624c12014-11-19 17:49:26 -08004608 ti += group->packages[pi]->typeIdOffset;
Adam Lesinskie60a87f2014-10-09 11:08:04 -07004609
Adam Lesinski9b624c12014-11-19 17:49:26 -08004610 const uint32_t identifier = findEntry(group, ti, name, nameLen,
4611 outTypeSpecFlags);
4612 if (identifier != 0) {
4613 if (fakePublic && outTypeSpecFlags) {
4614 *outTypeSpecFlags |= ResTable_typeSpec::SPEC_PUBLIC;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07004615 }
Adam Lesinski9b624c12014-11-19 17:49:26 -08004616 return identifier;
4617 }
4618 } while (strzcmp16(attr.string(), attr.size(), targetType, targetTypeLen) == 0
4619 && (targetType = attrPrivate.string())
4620 && (targetTypeLen = attrPrivate.size())
4621 );
4622 }
4623 break;
4624 }
4625 return 0;
4626}
4627
4628uint32_t ResTable::findEntry(const PackageGroup* group, ssize_t typeIndex, const char16_t* name,
4629 size_t nameLen, uint32_t* outTypeSpecFlags) const {
4630 const TypeList& typeList = group->types[typeIndex];
4631 const size_t typeCount = typeList.size();
4632 for (size_t i = 0; i < typeCount; i++) {
4633 const Type* t = typeList[i];
4634 const ssize_t ei = t->package->keyStrings.indexOfString(name, nameLen);
4635 if (ei < 0) {
4636 continue;
4637 }
4638
4639 const size_t configCount = t->configs.size();
4640 for (size_t j = 0; j < configCount; j++) {
4641 const TypeVariant tv(t->configs[j]);
4642 for (TypeVariant::iterator iter = tv.beginEntries();
4643 iter != tv.endEntries();
4644 iter++) {
4645 const ResTable_entry* entry = *iter;
4646 if (entry == NULL) {
4647 continue;
4648 }
4649
4650 if (dtohl(entry->key.index) == (size_t) ei) {
4651 uint32_t resId = Res_MAKEID(group->id - 1, typeIndex, iter.index());
4652 if (outTypeSpecFlags) {
4653 Entry result;
4654 if (getEntry(group, typeIndex, iter.index(), NULL, &result) != NO_ERROR) {
4655 ALOGW("Failed to find spec flags for 0x%08x", resId);
4656 return 0;
4657 }
4658 *outTypeSpecFlags = result.specFlags;
4659 }
4660 return resId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004661 }
4662 }
4663 }
4664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004665 return 0;
4666}
4667
Dan Albertf348c152014-09-08 18:28:00 -07004668bool ResTable::expandResourceRef(const char16_t* refStr, size_t refLen,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004669 String16* outPackage,
4670 String16* outType,
4671 String16* outName,
4672 const String16* defType,
4673 const String16* defPackage,
Dianne Hackborn426431a2011-06-09 11:29:08 -07004674 const char** outErrorMsg,
4675 bool* outPublicOnly)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004676{
4677 const char16_t* packageEnd = NULL;
4678 const char16_t* typeEnd = NULL;
4679 const char16_t* p = refStr;
4680 const char16_t* const end = p + refLen;
4681 while (p < end) {
4682 if (*p == ':') packageEnd = p;
4683 else if (*p == '/') {
4684 typeEnd = p;
4685 break;
4686 }
4687 p++;
4688 }
4689 p = refStr;
4690 if (*p == '@') p++;
4691
Dianne Hackborn426431a2011-06-09 11:29:08 -07004692 if (outPublicOnly != NULL) {
4693 *outPublicOnly = true;
4694 }
4695 if (*p == '*') {
4696 p++;
4697 if (outPublicOnly != NULL) {
4698 *outPublicOnly = false;
4699 }
4700 }
4701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004702 if (packageEnd) {
4703 *outPackage = String16(p, packageEnd-p);
4704 p = packageEnd+1;
4705 } else {
4706 if (!defPackage) {
4707 if (outErrorMsg) {
4708 *outErrorMsg = "No resource package specified";
4709 }
4710 return false;
4711 }
4712 *outPackage = *defPackage;
4713 }
4714 if (typeEnd) {
4715 *outType = String16(p, typeEnd-p);
4716 p = typeEnd+1;
4717 } else {
4718 if (!defType) {
4719 if (outErrorMsg) {
4720 *outErrorMsg = "No resource type specified";
4721 }
4722 return false;
4723 }
4724 *outType = *defType;
4725 }
4726 *outName = String16(p, end-p);
Konstantin Lopyrevddcafcb2010-06-04 14:36:49 -07004727 if(**outPackage == 0) {
4728 if(outErrorMsg) {
4729 *outErrorMsg = "Resource package cannot be an empty string";
4730 }
4731 return false;
4732 }
4733 if(**outType == 0) {
4734 if(outErrorMsg) {
4735 *outErrorMsg = "Resource type cannot be an empty string";
4736 }
4737 return false;
4738 }
4739 if(**outName == 0) {
4740 if(outErrorMsg) {
4741 *outErrorMsg = "Resource id cannot be an empty string";
4742 }
4743 return false;
4744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004745 return true;
4746}
4747
4748static uint32_t get_hex(char c, bool* outError)
4749{
4750 if (c >= '0' && c <= '9') {
4751 return c - '0';
4752 } else if (c >= 'a' && c <= 'f') {
4753 return c - 'a' + 0xa;
4754 } else if (c >= 'A' && c <= 'F') {
4755 return c - 'A' + 0xa;
4756 }
4757 *outError = true;
4758 return 0;
4759}
4760
4761struct unit_entry
4762{
4763 const char* name;
4764 size_t len;
4765 uint8_t type;
4766 uint32_t unit;
4767 float scale;
4768};
4769
4770static const unit_entry unitNames[] = {
4771 { "px", strlen("px"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PX, 1.0f },
4772 { "dip", strlen("dip"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
4773 { "dp", strlen("dp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_DIP, 1.0f },
4774 { "sp", strlen("sp"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_SP, 1.0f },
4775 { "pt", strlen("pt"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_PT, 1.0f },
4776 { "in", strlen("in"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_IN, 1.0f },
4777 { "mm", strlen("mm"), Res_value::TYPE_DIMENSION, Res_value::COMPLEX_UNIT_MM, 1.0f },
4778 { "%", strlen("%"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION, 1.0f/100 },
4779 { "%p", strlen("%p"), Res_value::TYPE_FRACTION, Res_value::COMPLEX_UNIT_FRACTION_PARENT, 1.0f/100 },
4780 { NULL, 0, 0, 0, 0 }
4781};
4782
4783static bool parse_unit(const char* str, Res_value* outValue,
4784 float* outScale, const char** outEnd)
4785{
4786 const char* end = str;
4787 while (*end != 0 && !isspace((unsigned char)*end)) {
4788 end++;
4789 }
4790 const size_t len = end-str;
4791
4792 const char* realEnd = end;
4793 while (*realEnd != 0 && isspace((unsigned char)*realEnd)) {
4794 realEnd++;
4795 }
4796 if (*realEnd != 0) {
4797 return false;
4798 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07004799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004800 const unit_entry* cur = unitNames;
4801 while (cur->name) {
4802 if (len == cur->len && strncmp(cur->name, str, len) == 0) {
4803 outValue->dataType = cur->type;
4804 outValue->data = cur->unit << Res_value::COMPLEX_UNIT_SHIFT;
4805 *outScale = cur->scale;
4806 *outEnd = end;
4807 //printf("Found unit %s for %s\n", cur->name, str);
4808 return true;
4809 }
4810 cur++;
4811 }
4812
4813 return false;
4814}
4815
Dan Albert1b4f3162015-04-07 18:43:15 -07004816bool U16StringToInt(const char16_t* s, size_t len, Res_value* outValue)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004817{
4818 while (len > 0 && isspace16(*s)) {
4819 s++;
4820 len--;
4821 }
4822
4823 if (len <= 0) {
4824 return false;
4825 }
4826
4827 size_t i = 0;
Dan Albert1b4f3162015-04-07 18:43:15 -07004828 int64_t val = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004829 bool neg = false;
4830
4831 if (*s == '-') {
4832 neg = true;
4833 i++;
4834 }
4835
4836 if (s[i] < '0' || s[i] > '9') {
4837 return false;
4838 }
4839
Dan Albert1b4f3162015-04-07 18:43:15 -07004840 static_assert(std::is_same<uint32_t, Res_value::data_type>::value,
4841 "Res_value::data_type has changed. The range checks in this "
4842 "function are no longer correct.");
4843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004844 // Decimal or hex?
Dan Albert1b4f3162015-04-07 18:43:15 -07004845 bool isHex;
4846 if (len > 1 && s[i] == '0' && s[i+1] == 'x') {
4847 isHex = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004848 i += 2;
Dan Albert1b4f3162015-04-07 18:43:15 -07004849
4850 if (neg) {
4851 return false;
4852 }
4853
4854 if (i == len) {
4855 // Just u"0x"
4856 return false;
4857 }
4858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004859 bool error = false;
4860 while (i < len && !error) {
4861 val = (val*16) + get_hex(s[i], &error);
4862 i++;
Dan Albert1b4f3162015-04-07 18:43:15 -07004863
4864 if (val > std::numeric_limits<uint32_t>::max()) {
4865 return false;
4866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004867 }
4868 if (error) {
4869 return false;
4870 }
4871 } else {
Dan Albert1b4f3162015-04-07 18:43:15 -07004872 isHex = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004873 while (i < len) {
4874 if (s[i] < '0' || s[i] > '9') {
4875 return false;
4876 }
4877 val = (val*10) + s[i]-'0';
4878 i++;
Dan Albert1b4f3162015-04-07 18:43:15 -07004879
4880 if ((neg && -val < std::numeric_limits<int32_t>::min()) ||
4881 (!neg && val > std::numeric_limits<int32_t>::max())) {
4882 return false;
4883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004884 }
4885 }
4886
4887 if (neg) val = -val;
4888
4889 while (i < len && isspace16(s[i])) {
4890 i++;
4891 }
4892
Dan Albert1b4f3162015-04-07 18:43:15 -07004893 if (i != len) {
4894 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004895 }
4896
Dan Albert1b4f3162015-04-07 18:43:15 -07004897 if (outValue) {
4898 outValue->dataType =
4899 isHex ? outValue->TYPE_INT_HEX : outValue->TYPE_INT_DEC;
4900 outValue->data = static_cast<Res_value::data_type>(val);
4901 }
4902 return true;
4903}
4904
4905bool ResTable::stringToInt(const char16_t* s, size_t len, Res_value* outValue)
4906{
4907 return U16StringToInt(s, len, outValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004908}
4909
4910bool ResTable::stringToFloat(const char16_t* s, size_t len, Res_value* outValue)
4911{
4912 while (len > 0 && isspace16(*s)) {
4913 s++;
4914 len--;
4915 }
4916
4917 if (len <= 0) {
4918 return false;
4919 }
4920
4921 char buf[128];
4922 int i=0;
4923 while (len > 0 && *s != 0 && i < 126) {
4924 if (*s > 255) {
4925 return false;
4926 }
4927 buf[i++] = *s++;
4928 len--;
4929 }
4930
4931 if (len > 0) {
4932 return false;
4933 }
Torne (Richard Coles)46a807f2014-08-27 12:36:44 +01004934 if ((buf[0] < '0' || buf[0] > '9') && buf[0] != '.' && buf[0] != '-' && buf[0] != '+') {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004935 return false;
4936 }
4937
4938 buf[i] = 0;
4939 const char* end;
4940 float f = strtof(buf, (char**)&end);
4941
4942 if (*end != 0 && !isspace((unsigned char)*end)) {
4943 // Might be a unit...
4944 float scale;
4945 if (parse_unit(end, outValue, &scale, &end)) {
4946 f *= scale;
4947 const bool neg = f < 0;
4948 if (neg) f = -f;
4949 uint64_t bits = (uint64_t)(f*(1<<23)+.5f);
4950 uint32_t radix;
4951 uint32_t shift;
4952 if ((bits&0x7fffff) == 0) {
4953 // Always use 23p0 if there is no fraction, just to make
4954 // things easier to read.
4955 radix = Res_value::COMPLEX_RADIX_23p0;
4956 shift = 23;
4957 } else if ((bits&0xffffffffff800000LL) == 0) {
4958 // Magnitude is zero -- can fit in 0 bits of precision.
4959 radix = Res_value::COMPLEX_RADIX_0p23;
4960 shift = 0;
4961 } else if ((bits&0xffffffff80000000LL) == 0) {
4962 // Magnitude can fit in 8 bits of precision.
4963 radix = Res_value::COMPLEX_RADIX_8p15;
4964 shift = 8;
4965 } else if ((bits&0xffffff8000000000LL) == 0) {
4966 // Magnitude can fit in 16 bits of precision.
4967 radix = Res_value::COMPLEX_RADIX_16p7;
4968 shift = 16;
4969 } else {
4970 // Magnitude needs entire range, so no fractional part.
4971 radix = Res_value::COMPLEX_RADIX_23p0;
4972 shift = 23;
4973 }
4974 int32_t mantissa = (int32_t)(
4975 (bits>>shift) & Res_value::COMPLEX_MANTISSA_MASK);
4976 if (neg) {
4977 mantissa = (-mantissa) & Res_value::COMPLEX_MANTISSA_MASK;
4978 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07004979 outValue->data |=
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004980 (radix<<Res_value::COMPLEX_RADIX_SHIFT)
4981 | (mantissa<<Res_value::COMPLEX_MANTISSA_SHIFT);
4982 //printf("Input value: %f 0x%016Lx, mult: %f, radix: %d, shift: %d, final: 0x%08x\n",
4983 // f * (neg ? -1 : 1), bits, f*(1<<23),
4984 // radix, shift, outValue->data);
4985 return true;
4986 }
4987 return false;
4988 }
4989
4990 while (*end != 0 && isspace((unsigned char)*end)) {
4991 end++;
4992 }
4993
4994 if (*end == 0) {
4995 if (outValue) {
4996 outValue->dataType = outValue->TYPE_FLOAT;
4997 *(float*)(&outValue->data) = f;
4998 return true;
4999 }
5000 }
5001
5002 return false;
5003}
5004
5005bool ResTable::stringToValue(Res_value* outValue, String16* outString,
5006 const char16_t* s, size_t len,
5007 bool preserveSpaces, bool coerceType,
5008 uint32_t attrID,
5009 const String16* defType,
5010 const String16* defPackage,
5011 Accessor* accessor,
5012 void* accessorCookie,
5013 uint32_t attrType,
5014 bool enforcePrivate) const
5015{
5016 bool localizationSetting = accessor != NULL && accessor->getLocalizationSetting();
5017 const char* errorMsg = NULL;
5018
5019 outValue->size = sizeof(Res_value);
5020 outValue->res0 = 0;
5021
5022 // First strip leading/trailing whitespace. Do this before handling
5023 // escapes, so they can be used to force whitespace into the string.
5024 if (!preserveSpaces) {
5025 while (len > 0 && isspace16(*s)) {
5026 s++;
5027 len--;
5028 }
5029 while (len > 0 && isspace16(s[len-1])) {
5030 len--;
5031 }
5032 // If the string ends with '\', then we keep the space after it.
5033 if (len > 0 && s[len-1] == '\\' && s[len] != 0) {
5034 len++;
5035 }
5036 }
5037
5038 //printf("Value for: %s\n", String8(s, len).string());
5039
5040 uint32_t l10nReq = ResTable_map::L10N_NOT_REQUIRED;
5041 uint32_t attrMin = 0x80000000, attrMax = 0x7fffffff;
5042 bool fromAccessor = false;
5043 if (attrID != 0 && !Res_INTERNALID(attrID)) {
5044 const ssize_t p = getResourcePackageIndex(attrID);
5045 const bag_entry* bag;
5046 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
5047 //printf("For attr 0x%08x got bag of %d\n", attrID, cnt);
5048 if (cnt >= 0) {
5049 while (cnt > 0) {
5050 //printf("Entry 0x%08x = 0x%08x\n", bag->map.name.ident, bag->map.value.data);
5051 switch (bag->map.name.ident) {
5052 case ResTable_map::ATTR_TYPE:
5053 attrType = bag->map.value.data;
5054 break;
5055 case ResTable_map::ATTR_MIN:
5056 attrMin = bag->map.value.data;
5057 break;
5058 case ResTable_map::ATTR_MAX:
5059 attrMax = bag->map.value.data;
5060 break;
5061 case ResTable_map::ATTR_L10N:
5062 l10nReq = bag->map.value.data;
5063 break;
5064 }
5065 bag++;
5066 cnt--;
5067 }
5068 unlockBag(bag);
5069 } else if (accessor && accessor->getAttributeType(attrID, &attrType)) {
5070 fromAccessor = true;
5071 if (attrType == ResTable_map::TYPE_ENUM
5072 || attrType == ResTable_map::TYPE_FLAGS
5073 || attrType == ResTable_map::TYPE_INTEGER) {
5074 accessor->getAttributeMin(attrID, &attrMin);
5075 accessor->getAttributeMax(attrID, &attrMax);
5076 }
5077 if (localizationSetting) {
5078 l10nReq = accessor->getAttributeL10N(attrID);
5079 }
5080 }
5081 }
5082
5083 const bool canStringCoerce =
5084 coerceType && (attrType&ResTable_map::TYPE_STRING) != 0;
5085
5086 if (*s == '@') {
5087 outValue->dataType = outValue->TYPE_REFERENCE;
5088
5089 // Note: we don't check attrType here because the reference can
5090 // be to any other type; we just need to count on the client making
5091 // sure the referenced type is correct.
Mark Salyzyn00adb862014-03-19 11:00:06 -07005092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005093 //printf("Looking up ref: %s\n", String8(s, len).string());
5094
5095 // It's a reference!
5096 if (len == 5 && s[1]=='n' && s[2]=='u' && s[3]=='l' && s[4]=='l') {
Alan Viverettef2969402014-10-29 17:09:36 -07005097 // Special case @null as undefined. This will be converted by
5098 // AssetManager to TYPE_NULL with data DATA_NULL_UNDEFINED.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005099 outValue->data = 0;
5100 return true;
Alan Viverettef2969402014-10-29 17:09:36 -07005101 } else if (len == 6 && s[1]=='e' && s[2]=='m' && s[3]=='p' && s[4]=='t' && s[5]=='y') {
5102 // Special case @empty as explicitly defined empty value.
5103 outValue->dataType = Res_value::TYPE_NULL;
5104 outValue->data = Res_value::DATA_NULL_EMPTY;
5105 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005106 } else {
5107 bool createIfNotFound = false;
5108 const char16_t* resourceRefName;
5109 int resourceNameLen;
5110 if (len > 2 && s[1] == '+') {
5111 createIfNotFound = true;
5112 resourceRefName = s + 2;
5113 resourceNameLen = len - 2;
5114 } else if (len > 2 && s[1] == '*') {
5115 enforcePrivate = false;
5116 resourceRefName = s + 2;
5117 resourceNameLen = len - 2;
5118 } else {
5119 createIfNotFound = false;
5120 resourceRefName = s + 1;
5121 resourceNameLen = len - 1;
5122 }
5123 String16 package, type, name;
5124 if (!expandResourceRef(resourceRefName,resourceNameLen, &package, &type, &name,
5125 defType, defPackage, &errorMsg)) {
5126 if (accessor != NULL) {
5127 accessor->reportError(accessorCookie, errorMsg);
5128 }
5129 return false;
5130 }
5131
5132 uint32_t specFlags = 0;
5133 uint32_t rid = identifierForName(name.string(), name.size(), type.string(),
5134 type.size(), package.string(), package.size(), &specFlags);
5135 if (rid != 0) {
5136 if (enforcePrivate) {
Adam Lesinski833f3cc2014-06-18 15:06:01 -07005137 if (accessor == NULL || accessor->getAssetsPackage() != package) {
5138 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
5139 if (accessor != NULL) {
5140 accessor->reportError(accessorCookie, "Resource is not public.");
5141 }
5142 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005143 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005144 }
5145 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08005146
5147 if (accessor) {
5148 rid = Res_MAKEID(
5149 accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
5150 Res_GETTYPE(rid), Res_GETENTRY(rid));
Andreas Gampe2204f0b2014-10-21 23:04:54 -07005151 if (kDebugTableNoisy) {
5152 ALOGI("Incl %s:%s/%s: 0x%08x\n",
5153 String8(package).string(), String8(type).string(),
5154 String8(name).string(), rid);
5155 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005156 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08005157
5158 uint32_t packageId = Res_GETPACKAGE(rid) + 1;
5159 if (packageId != APP_PACKAGE_ID && packageId != SYS_PACKAGE_ID) {
5160 outValue->dataType = Res_value::TYPE_DYNAMIC_REFERENCE;
5161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005162 outValue->data = rid;
5163 return true;
5164 }
5165
5166 if (accessor) {
5167 uint32_t rid = accessor->getCustomResourceWithCreation(package, type, name,
5168 createIfNotFound);
5169 if (rid != 0) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07005170 if (kDebugTableNoisy) {
5171 ALOGI("Pckg %s:%s/%s: 0x%08x\n",
5172 String8(package).string(), String8(type).string(),
5173 String8(name).string(), rid);
5174 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08005175 uint32_t packageId = Res_GETPACKAGE(rid) + 1;
5176 if (packageId == 0x00) {
5177 outValue->data = rid;
5178 outValue->dataType = Res_value::TYPE_DYNAMIC_REFERENCE;
5179 return true;
5180 } else if (packageId == APP_PACKAGE_ID || packageId == SYS_PACKAGE_ID) {
5181 // We accept packageId's generated as 0x01 in order to support
5182 // building the android system resources
5183 outValue->data = rid;
5184 return true;
5185 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005186 }
5187 }
5188 }
5189
5190 if (accessor != NULL) {
5191 accessor->reportError(accessorCookie, "No resource found that matches the given name");
5192 }
5193 return false;
5194 }
5195
5196 // if we got to here, and localization is required and it's not a reference,
5197 // complain and bail.
5198 if (l10nReq == ResTable_map::L10N_SUGGESTED) {
5199 if (localizationSetting) {
5200 if (accessor != NULL) {
5201 accessor->reportError(accessorCookie, "This attribute must be localized.");
5202 }
5203 }
5204 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005206 if (*s == '#') {
5207 // It's a color! Convert to an integer of the form 0xaarrggbb.
5208 uint32_t color = 0;
5209 bool error = false;
5210 if (len == 4) {
5211 outValue->dataType = outValue->TYPE_INT_COLOR_RGB4;
5212 color |= 0xFF000000;
5213 color |= get_hex(s[1], &error) << 20;
5214 color |= get_hex(s[1], &error) << 16;
5215 color |= get_hex(s[2], &error) << 12;
5216 color |= get_hex(s[2], &error) << 8;
5217 color |= get_hex(s[3], &error) << 4;
5218 color |= get_hex(s[3], &error);
5219 } else if (len == 5) {
5220 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB4;
5221 color |= get_hex(s[1], &error) << 28;
5222 color |= get_hex(s[1], &error) << 24;
5223 color |= get_hex(s[2], &error) << 20;
5224 color |= get_hex(s[2], &error) << 16;
5225 color |= get_hex(s[3], &error) << 12;
5226 color |= get_hex(s[3], &error) << 8;
5227 color |= get_hex(s[4], &error) << 4;
5228 color |= get_hex(s[4], &error);
5229 } else if (len == 7) {
5230 outValue->dataType = outValue->TYPE_INT_COLOR_RGB8;
5231 color |= 0xFF000000;
5232 color |= get_hex(s[1], &error) << 20;
5233 color |= get_hex(s[2], &error) << 16;
5234 color |= get_hex(s[3], &error) << 12;
5235 color |= get_hex(s[4], &error) << 8;
5236 color |= get_hex(s[5], &error) << 4;
5237 color |= get_hex(s[6], &error);
5238 } else if (len == 9) {
5239 outValue->dataType = outValue->TYPE_INT_COLOR_ARGB8;
5240 color |= get_hex(s[1], &error) << 28;
5241 color |= get_hex(s[2], &error) << 24;
5242 color |= get_hex(s[3], &error) << 20;
5243 color |= get_hex(s[4], &error) << 16;
5244 color |= get_hex(s[5], &error) << 12;
5245 color |= get_hex(s[6], &error) << 8;
5246 color |= get_hex(s[7], &error) << 4;
5247 color |= get_hex(s[8], &error);
5248 } else {
5249 error = true;
5250 }
5251 if (!error) {
5252 if ((attrType&ResTable_map::TYPE_COLOR) == 0) {
5253 if (!canStringCoerce) {
5254 if (accessor != NULL) {
5255 accessor->reportError(accessorCookie,
5256 "Color types not allowed");
5257 }
5258 return false;
5259 }
5260 } else {
5261 outValue->data = color;
5262 //printf("Color input=%s, output=0x%x\n", String8(s, len).string(), color);
5263 return true;
5264 }
5265 } else {
5266 if ((attrType&ResTable_map::TYPE_COLOR) != 0) {
5267 if (accessor != NULL) {
5268 accessor->reportError(accessorCookie, "Color value not valid --"
5269 " must be #rgb, #argb, #rrggbb, or #aarrggbb");
5270 }
5271 #if 0
5272 fprintf(stderr, "%s: Color ID %s value %s is not valid\n",
5273 "Resource File", //(const char*)in->getPrintableSource(),
5274 String8(*curTag).string(),
5275 String8(s, len).string());
5276 #endif
5277 return false;
5278 }
5279 }
5280 }
5281
5282 if (*s == '?') {
5283 outValue->dataType = outValue->TYPE_ATTRIBUTE;
5284
5285 // Note: we don't check attrType here because the reference can
5286 // be to any other type; we just need to count on the client making
5287 // sure the referenced type is correct.
5288
5289 //printf("Looking up attr: %s\n", String8(s, len).string());
5290
5291 static const String16 attr16("attr");
5292 String16 package, type, name;
5293 if (!expandResourceRef(s+1, len-1, &package, &type, &name,
5294 &attr16, defPackage, &errorMsg)) {
5295 if (accessor != NULL) {
5296 accessor->reportError(accessorCookie, errorMsg);
5297 }
5298 return false;
5299 }
5300
5301 //printf("Pkg: %s, Type: %s, Name: %s\n",
5302 // String8(package).string(), String8(type).string(),
5303 // String8(name).string());
5304 uint32_t specFlags = 0;
Mark Salyzyn00adb862014-03-19 11:00:06 -07005305 uint32_t rid =
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005306 identifierForName(name.string(), name.size(),
5307 type.string(), type.size(),
5308 package.string(), package.size(), &specFlags);
5309 if (rid != 0) {
5310 if (enforcePrivate) {
5311 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
5312 if (accessor != NULL) {
5313 accessor->reportError(accessorCookie, "Attribute is not public.");
5314 }
5315 return false;
5316 }
5317 }
5318 if (!accessor) {
5319 outValue->data = rid;
5320 return true;
5321 }
5322 rid = Res_MAKEID(
5323 accessor->getRemappedPackage(Res_GETPACKAGE(rid)),
5324 Res_GETTYPE(rid), Res_GETENTRY(rid));
5325 //printf("Incl %s:%s/%s: 0x%08x\n",
5326 // String8(package).string(), String8(type).string(),
5327 // String8(name).string(), rid);
5328 outValue->data = rid;
5329 return true;
5330 }
5331
5332 if (accessor) {
5333 uint32_t rid = accessor->getCustomResource(package, type, name);
5334 if (rid != 0) {
5335 //printf("Mine %s:%s/%s: 0x%08x\n",
5336 // String8(package).string(), String8(type).string(),
5337 // String8(name).string(), rid);
5338 outValue->data = rid;
5339 return true;
5340 }
5341 }
5342
5343 if (accessor != NULL) {
5344 accessor->reportError(accessorCookie, "No resource found that matches the given name");
5345 }
5346 return false;
5347 }
5348
5349 if (stringToInt(s, len, outValue)) {
5350 if ((attrType&ResTable_map::TYPE_INTEGER) == 0) {
5351 // If this type does not allow integers, but does allow floats,
5352 // fall through on this error case because the float type should
5353 // be able to accept any integer value.
5354 if (!canStringCoerce && (attrType&ResTable_map::TYPE_FLOAT) == 0) {
5355 if (accessor != NULL) {
5356 accessor->reportError(accessorCookie, "Integer types not allowed");
5357 }
5358 return false;
5359 }
5360 } else {
5361 if (((int32_t)outValue->data) < ((int32_t)attrMin)
5362 || ((int32_t)outValue->data) > ((int32_t)attrMax)) {
5363 if (accessor != NULL) {
5364 accessor->reportError(accessorCookie, "Integer value out of range");
5365 }
5366 return false;
5367 }
5368 return true;
5369 }
5370 }
5371
5372 if (stringToFloat(s, len, outValue)) {
5373 if (outValue->dataType == Res_value::TYPE_DIMENSION) {
5374 if ((attrType&ResTable_map::TYPE_DIMENSION) != 0) {
5375 return true;
5376 }
5377 if (!canStringCoerce) {
5378 if (accessor != NULL) {
5379 accessor->reportError(accessorCookie, "Dimension types not allowed");
5380 }
5381 return false;
5382 }
5383 } else if (outValue->dataType == Res_value::TYPE_FRACTION) {
5384 if ((attrType&ResTable_map::TYPE_FRACTION) != 0) {
5385 return true;
5386 }
5387 if (!canStringCoerce) {
5388 if (accessor != NULL) {
5389 accessor->reportError(accessorCookie, "Fraction types not allowed");
5390 }
5391 return false;
5392 }
5393 } else if ((attrType&ResTable_map::TYPE_FLOAT) == 0) {
5394 if (!canStringCoerce) {
5395 if (accessor != NULL) {
5396 accessor->reportError(accessorCookie, "Float types not allowed");
5397 }
5398 return false;
5399 }
5400 } else {
5401 return true;
5402 }
5403 }
5404
5405 if (len == 4) {
5406 if ((s[0] == 't' || s[0] == 'T') &&
5407 (s[1] == 'r' || s[1] == 'R') &&
5408 (s[2] == 'u' || s[2] == 'U') &&
5409 (s[3] == 'e' || s[3] == 'E')) {
5410 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
5411 if (!canStringCoerce) {
5412 if (accessor != NULL) {
5413 accessor->reportError(accessorCookie, "Boolean types not allowed");
5414 }
5415 return false;
5416 }
5417 } else {
5418 outValue->dataType = outValue->TYPE_INT_BOOLEAN;
5419 outValue->data = (uint32_t)-1;
5420 return true;
5421 }
5422 }
5423 }
5424
5425 if (len == 5) {
5426 if ((s[0] == 'f' || s[0] == 'F') &&
5427 (s[1] == 'a' || s[1] == 'A') &&
5428 (s[2] == 'l' || s[2] == 'L') &&
5429 (s[3] == 's' || s[3] == 'S') &&
5430 (s[4] == 'e' || s[4] == 'E')) {
5431 if ((attrType&ResTable_map::TYPE_BOOLEAN) == 0) {
5432 if (!canStringCoerce) {
5433 if (accessor != NULL) {
5434 accessor->reportError(accessorCookie, "Boolean types not allowed");
5435 }
5436 return false;
5437 }
5438 } else {
5439 outValue->dataType = outValue->TYPE_INT_BOOLEAN;
5440 outValue->data = 0;
5441 return true;
5442 }
5443 }
5444 }
5445
5446 if ((attrType&ResTable_map::TYPE_ENUM) != 0) {
5447 const ssize_t p = getResourcePackageIndex(attrID);
5448 const bag_entry* bag;
5449 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
5450 //printf("Got %d for enum\n", cnt);
5451 if (cnt >= 0) {
5452 resource_name rname;
5453 while (cnt > 0) {
5454 if (!Res_INTERNALID(bag->map.name.ident)) {
5455 //printf("Trying attr #%08x\n", bag->map.name.ident);
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07005456 if (getResourceName(bag->map.name.ident, false, &rname)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005457 #if 0
5458 printf("Matching %s against %s (0x%08x)\n",
5459 String8(s, len).string(),
5460 String8(rname.name, rname.nameLen).string(),
5461 bag->map.name.ident);
5462 #endif
5463 if (strzcmp16(s, len, rname.name, rname.nameLen) == 0) {
5464 outValue->dataType = bag->map.value.dataType;
5465 outValue->data = bag->map.value.data;
5466 unlockBag(bag);
5467 return true;
5468 }
5469 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005470
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005471 }
5472 bag++;
5473 cnt--;
5474 }
5475 unlockBag(bag);
5476 }
5477
5478 if (fromAccessor) {
5479 if (accessor->getAttributeEnum(attrID, s, len, outValue)) {
5480 return true;
5481 }
5482 }
5483 }
5484
5485 if ((attrType&ResTable_map::TYPE_FLAGS) != 0) {
5486 const ssize_t p = getResourcePackageIndex(attrID);
5487 const bag_entry* bag;
5488 ssize_t cnt = p >= 0 ? lockBag(attrID, &bag) : -1;
5489 //printf("Got %d for flags\n", cnt);
5490 if (cnt >= 0) {
5491 bool failed = false;
5492 resource_name rname;
5493 outValue->dataType = Res_value::TYPE_INT_HEX;
5494 outValue->data = 0;
5495 const char16_t* end = s + len;
5496 const char16_t* pos = s;
5497 while (pos < end && !failed) {
5498 const char16_t* start = pos;
The Android Open Source Project4df24232009-03-05 14:34:35 -08005499 pos++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005500 while (pos < end && *pos != '|') {
5501 pos++;
5502 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08005503 //printf("Looking for: %s\n", String8(start, pos-start).string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005504 const bag_entry* bagi = bag;
The Android Open Source Project4df24232009-03-05 14:34:35 -08005505 ssize_t i;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005506 for (i=0; i<cnt; i++, bagi++) {
5507 if (!Res_INTERNALID(bagi->map.name.ident)) {
5508 //printf("Trying attr #%08x\n", bagi->map.name.ident);
Dianne Hackbornd45c68d2013-07-31 12:14:24 -07005509 if (getResourceName(bagi->map.name.ident, false, &rname)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005510 #if 0
5511 printf("Matching %s against %s (0x%08x)\n",
5512 String8(start,pos-start).string(),
5513 String8(rname.name, rname.nameLen).string(),
5514 bagi->map.name.ident);
5515 #endif
5516 if (strzcmp16(start, pos-start, rname.name, rname.nameLen) == 0) {
5517 outValue->data |= bagi->map.value.data;
5518 break;
5519 }
5520 }
5521 }
5522 }
5523 if (i >= cnt) {
5524 // Didn't find this flag identifier.
5525 failed = true;
5526 }
5527 if (pos < end) {
5528 pos++;
5529 }
5530 }
5531 unlockBag(bag);
5532 if (!failed) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08005533 //printf("Final flag value: 0x%lx\n", outValue->data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005534 return true;
5535 }
5536 }
5537
5538
5539 if (fromAccessor) {
5540 if (accessor->getAttributeFlags(attrID, s, len, outValue)) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08005541 //printf("Final flag value: 0x%lx\n", outValue->data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005542 return true;
5543 }
5544 }
5545 }
5546
5547 if ((attrType&ResTable_map::TYPE_STRING) == 0) {
5548 if (accessor != NULL) {
5549 accessor->reportError(accessorCookie, "String types not allowed");
5550 }
5551 return false;
5552 }
5553
5554 // Generic string handling...
5555 outValue->dataType = outValue->TYPE_STRING;
5556 if (outString) {
5557 bool failed = collectString(outString, s, len, preserveSpaces, &errorMsg);
5558 if (accessor != NULL) {
5559 accessor->reportError(accessorCookie, errorMsg);
5560 }
5561 return failed;
5562 }
5563
5564 return true;
5565}
5566
5567bool ResTable::collectString(String16* outString,
5568 const char16_t* s, size_t len,
5569 bool preserveSpaces,
5570 const char** outErrorMsg,
5571 bool append)
5572{
5573 String16 tmp;
5574
5575 char quoted = 0;
5576 const char16_t* p = s;
5577 while (p < (s+len)) {
5578 while (p < (s+len)) {
5579 const char16_t c = *p;
5580 if (c == '\\') {
5581 break;
5582 }
5583 if (!preserveSpaces) {
5584 if (quoted == 0 && isspace16(c)
5585 && (c != ' ' || isspace16(*(p+1)))) {
5586 break;
5587 }
5588 if (c == '"' && (quoted == 0 || quoted == '"')) {
5589 break;
5590 }
5591 if (c == '\'' && (quoted == 0 || quoted == '\'')) {
Eric Fischerc87d2522009-09-01 15:20:30 -07005592 /*
5593 * In practice, when people write ' instead of \'
5594 * in a string, they are doing it by accident
5595 * instead of really meaning to use ' as a quoting
5596 * character. Warn them so they don't lose it.
5597 */
5598 if (outErrorMsg) {
5599 *outErrorMsg = "Apostrophe not preceded by \\";
5600 }
5601 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005602 }
5603 }
5604 p++;
5605 }
5606 if (p < (s+len)) {
5607 if (p > s) {
5608 tmp.append(String16(s, p-s));
5609 }
5610 if (!preserveSpaces && (*p == '"' || *p == '\'')) {
5611 if (quoted == 0) {
5612 quoted = *p;
5613 } else {
5614 quoted = 0;
5615 }
5616 p++;
5617 } else if (!preserveSpaces && isspace16(*p)) {
5618 // Space outside of a quote -- consume all spaces and
5619 // leave a single plain space char.
5620 tmp.append(String16(" "));
5621 p++;
5622 while (p < (s+len) && isspace16(*p)) {
5623 p++;
5624 }
5625 } else if (*p == '\\') {
5626 p++;
5627 if (p < (s+len)) {
5628 switch (*p) {
5629 case 't':
5630 tmp.append(String16("\t"));
5631 break;
5632 case 'n':
5633 tmp.append(String16("\n"));
5634 break;
5635 case '#':
5636 tmp.append(String16("#"));
5637 break;
5638 case '@':
5639 tmp.append(String16("@"));
5640 break;
5641 case '?':
5642 tmp.append(String16("?"));
5643 break;
5644 case '"':
5645 tmp.append(String16("\""));
5646 break;
5647 case '\'':
5648 tmp.append(String16("'"));
5649 break;
5650 case '\\':
5651 tmp.append(String16("\\"));
5652 break;
5653 case 'u':
5654 {
5655 char16_t chr = 0;
5656 int i = 0;
5657 while (i < 4 && p[1] != 0) {
5658 p++;
5659 i++;
5660 int c;
5661 if (*p >= '0' && *p <= '9') {
5662 c = *p - '0';
5663 } else if (*p >= 'a' && *p <= 'f') {
5664 c = *p - 'a' + 10;
5665 } else if (*p >= 'A' && *p <= 'F') {
5666 c = *p - 'A' + 10;
5667 } else {
5668 if (outErrorMsg) {
5669 *outErrorMsg = "Bad character in \\u unicode escape sequence";
5670 }
5671 return false;
5672 }
5673 chr = (chr<<4) | c;
5674 }
5675 tmp.append(String16(&chr, 1));
5676 } break;
5677 default:
5678 // ignore unknown escape chars.
5679 break;
5680 }
5681 p++;
5682 }
5683 }
5684 len -= (p-s);
5685 s = p;
5686 }
5687 }
5688
5689 if (tmp.size() != 0) {
5690 if (len > 0) {
5691 tmp.append(String16(s, len));
5692 }
5693 if (append) {
5694 outString->append(tmp);
5695 } else {
5696 outString->setTo(tmp);
5697 }
5698 } else {
5699 if (append) {
5700 outString->append(String16(s, len));
5701 } else {
5702 outString->setTo(s, len);
5703 }
5704 }
5705
5706 return true;
5707}
5708
5709size_t ResTable::getBasePackageCount() const
5710{
5711 if (mError != NO_ERROR) {
5712 return 0;
5713 }
5714 return mPackageGroups.size();
5715}
5716
Adam Lesinskide898ff2014-01-29 18:20:45 -08005717const String16 ResTable::getBasePackageName(size_t idx) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005718{
5719 if (mError != NO_ERROR) {
Adam Lesinskide898ff2014-01-29 18:20:45 -08005720 return String16();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005721 }
5722 LOG_FATAL_IF(idx >= mPackageGroups.size(),
5723 "Requested package index %d past package count %d",
5724 (int)idx, (int)mPackageGroups.size());
Adam Lesinskide898ff2014-01-29 18:20:45 -08005725 return mPackageGroups[idx]->name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005726}
5727
5728uint32_t ResTable::getBasePackageId(size_t idx) const
5729{
5730 if (mError != NO_ERROR) {
5731 return 0;
5732 }
5733 LOG_FATAL_IF(idx >= mPackageGroups.size(),
5734 "Requested package index %d past package count %d",
5735 (int)idx, (int)mPackageGroups.size());
5736 return mPackageGroups[idx]->id;
5737}
5738
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005739uint32_t ResTable::getLastTypeIdForPackage(size_t idx) const
5740{
5741 if (mError != NO_ERROR) {
5742 return 0;
5743 }
5744 LOG_FATAL_IF(idx >= mPackageGroups.size(),
5745 "Requested package index %d past package count %d",
5746 (int)idx, (int)mPackageGroups.size());
5747 const PackageGroup* const group = mPackageGroups[idx];
5748 return group->largestTypeId;
5749}
5750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005751size_t ResTable::getTableCount() const
5752{
5753 return mHeaders.size();
5754}
5755
5756const ResStringPool* ResTable::getTableStringBlock(size_t index) const
5757{
5758 return &mHeaders[index]->values;
5759}
5760
Narayan Kamath7c4887f2014-01-27 17:32:37 +00005761int32_t ResTable::getTableCookie(size_t index) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005762{
5763 return mHeaders[index]->cookie;
5764}
5765
Adam Lesinskide898ff2014-01-29 18:20:45 -08005766const DynamicRefTable* ResTable::getDynamicRefTableForCookie(int32_t cookie) const
5767{
5768 const size_t N = mPackageGroups.size();
5769 for (size_t i = 0; i < N; i++) {
5770 const PackageGroup* pg = mPackageGroups[i];
5771 size_t M = pg->packages.size();
5772 for (size_t j = 0; j < M; j++) {
5773 if (pg->packages[j]->header->cookie == cookie) {
5774 return &pg->dynamicRefTable;
5775 }
5776 }
5777 }
5778 return NULL;
5779}
5780
Filip Gruszczynski23493322015-07-29 17:02:59 -07005781void ResTable::getConfigurations(Vector<ResTable_config>* configs, bool ignoreMipmap,
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08005782 bool ignoreAndroidPackage, bool includeSystemConfigs) const {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005783 const size_t packageCount = mPackageGroups.size();
Filip Gruszczynski23493322015-07-29 17:02:59 -07005784 String16 android("android");
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005785 for (size_t i = 0; i < packageCount; i++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005786 const PackageGroup* packageGroup = mPackageGroups[i];
Filip Gruszczynski23493322015-07-29 17:02:59 -07005787 if (ignoreAndroidPackage && android == packageGroup->name) {
5788 continue;
5789 }
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08005790 if (!includeSystemConfigs && packageGroup->isSystemAsset) {
5791 continue;
5792 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005793 const size_t typeCount = packageGroup->types.size();
5794 for (size_t j = 0; j < typeCount; j++) {
5795 const TypeList& typeList = packageGroup->types[j];
5796 const size_t numTypes = typeList.size();
5797 for (size_t k = 0; k < numTypes; k++) {
5798 const Type* type = typeList[k];
Adam Lesinski42eea272015-01-15 17:01:39 -08005799 const ResStringPool& typeStrings = type->package->typeStrings;
5800 if (ignoreMipmap && typeStrings.string8ObjectAt(
5801 type->typeSpec->id - 1) == "mipmap") {
5802 continue;
5803 }
5804
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005805 const size_t numConfigs = type->configs.size();
5806 for (size_t m = 0; m < numConfigs; m++) {
5807 const ResTable_type* config = type->configs[m];
Narayan Kamath788fa412014-01-21 15:32:36 +00005808 ResTable_config cfg;
5809 memset(&cfg, 0, sizeof(ResTable_config));
5810 cfg.copyFromDtoH(config->config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005811 // only insert unique
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005812 const size_t N = configs->size();
5813 size_t n;
5814 for (n = 0; n < N; n++) {
5815 if (0 == (*configs)[n].compare(cfg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005816 break;
5817 }
5818 }
5819 // if we didn't find it
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005820 if (n == N) {
Narayan Kamath788fa412014-01-21 15:32:36 +00005821 configs->add(cfg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005822 }
5823 }
5824 }
5825 }
5826 }
5827}
5828
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08005829void ResTable::getLocales(Vector<String8>* locales, bool includeSystemLocales) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005830{
5831 Vector<ResTable_config> configs;
Steve Block71f2cf12011-10-20 11:56:00 +01005832 ALOGV("calling getConfigurations");
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08005833 getConfigurations(&configs,
5834 false /* ignoreMipmap */,
5835 false /* ignoreAndroidPackage */,
5836 includeSystemLocales /* includeSystemConfigs */);
Steve Block71f2cf12011-10-20 11:56:00 +01005837 ALOGV("called getConfigurations size=%d", (int)configs.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005838 const size_t I = configs.size();
Narayan Kamath48620f12014-01-20 13:57:11 +00005839
5840 char locale[RESTABLE_MAX_LOCALE_LEN];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005841 for (size_t i=0; i<I; i++) {
Narayan Kamath788fa412014-01-21 15:32:36 +00005842 configs[i].getBcp47Locale(locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005843 const size_t J = locales->size();
5844 size_t j;
5845 for (j=0; j<J; j++) {
5846 if (0 == strcmp(locale, (*locales)[j].string())) {
5847 break;
5848 }
5849 }
5850 if (j == J) {
5851 locales->add(String8(locale));
5852 }
5853 }
5854}
5855
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005856StringPoolRef::StringPoolRef(const ResStringPool* pool, uint32_t index)
5857 : mPool(pool), mIndex(index) {}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005858
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005859StringPoolRef::StringPoolRef()
5860 : mPool(NULL), mIndex(0) {}
5861
5862const char* StringPoolRef::string8(size_t* outLen) const {
5863 if (mPool != NULL) {
5864 return mPool->string8At(mIndex, outLen);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005865 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005866 if (outLen != NULL) {
5867 *outLen = 0;
5868 }
5869 return NULL;
5870}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005871
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005872const char16_t* StringPoolRef::string16(size_t* outLen) const {
5873 if (mPool != NULL) {
5874 return mPool->stringAt(mIndex, outLen);
5875 }
5876 if (outLen != NULL) {
5877 *outLen = 0;
5878 }
5879 return NULL;
5880}
5881
Adam Lesinski82a2dd82014-09-17 18:34:15 -07005882bool ResTable::getResourceFlags(uint32_t resID, uint32_t* outFlags) const {
5883 if (mError != NO_ERROR) {
5884 return false;
5885 }
5886
5887 const ssize_t p = getResourcePackageIndex(resID);
5888 const int t = Res_GETTYPE(resID);
5889 const int e = Res_GETENTRY(resID);
5890
5891 if (p < 0) {
5892 if (Res_GETPACKAGE(resID)+1 == 0) {
5893 ALOGW("No package identifier when getting flags for resource number 0x%08x", resID);
5894 } else {
5895 ALOGW("No known package when getting flags for resource number 0x%08x", resID);
5896 }
5897 return false;
5898 }
5899 if (t < 0) {
5900 ALOGW("No type identifier when getting flags for resource number 0x%08x", resID);
5901 return false;
5902 }
5903
5904 const PackageGroup* const grp = mPackageGroups[p];
5905 if (grp == NULL) {
5906 ALOGW("Bad identifier when getting flags for resource number 0x%08x", resID);
5907 return false;
5908 }
5909
5910 Entry entry;
5911 status_t err = getEntry(grp, t, e, NULL, &entry);
5912 if (err != NO_ERROR) {
5913 return false;
5914 }
5915
5916 *outFlags = entry.specFlags;
5917 return true;
5918}
5919
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005920status_t ResTable::getEntry(
5921 const PackageGroup* packageGroup, int typeIndex, int entryIndex,
5922 const ResTable_config* config,
5923 Entry* outEntry) const
5924{
5925 const TypeList& typeList = packageGroup->types[typeIndex];
5926 if (typeList.isEmpty()) {
5927 ALOGV("Skipping entry type index 0x%02x because type is NULL!\n", typeIndex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005928 return BAD_TYPE;
5929 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005930
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005931 const ResTable_type* bestType = NULL;
5932 uint32_t bestOffset = ResTable_type::NO_ENTRY;
5933 const Package* bestPackage = NULL;
5934 uint32_t specFlags = 0;
5935 uint8_t actualTypeIndex = typeIndex;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005936 ResTable_config bestConfig;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005937 memset(&bestConfig, 0, sizeof(bestConfig));
Mark Salyzyn00adb862014-03-19 11:00:06 -07005938
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005939 // Iterate over the Types of each package.
5940 const size_t typeCount = typeList.size();
5941 for (size_t i = 0; i < typeCount; i++) {
5942 const Type* const typeSpec = typeList[i];
Mark Salyzyn00adb862014-03-19 11:00:06 -07005943
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005944 int realEntryIndex = entryIndex;
5945 int realTypeIndex = typeIndex;
5946 bool currentTypeIsOverlay = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005947
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005948 // Runtime overlay packages provide a mapping of app resource
5949 // ID to package resource ID.
5950 if (typeSpec->idmapEntries.hasEntries()) {
5951 uint16_t overlayEntryIndex;
5952 if (typeSpec->idmapEntries.lookup(entryIndex, &overlayEntryIndex) != NO_ERROR) {
5953 // No such mapping exists
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005954 continue;
5955 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005956 realEntryIndex = overlayEntryIndex;
5957 realTypeIndex = typeSpec->idmapEntries.overlayTypeId() - 1;
5958 currentTypeIsOverlay = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005959 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07005960
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005961 if (static_cast<size_t>(realEntryIndex) >= typeSpec->entryCount) {
5962 ALOGW("For resource 0x%08x, entry index(%d) is beyond type entryCount(%d)",
5963 Res_MAKEID(packageGroup->id - 1, typeIndex, entryIndex),
5964 entryIndex, static_cast<int>(typeSpec->entryCount));
5965 // We should normally abort here, but some legacy apps declare
5966 // resources in the 'android' package (old bug in AAPT).
5967 continue;
5968 }
5969
5970 // Aggregate all the flags for each package that defines this entry.
5971 if (typeSpec->typeSpecFlags != NULL) {
5972 specFlags |= dtohl(typeSpec->typeSpecFlags[realEntryIndex]);
5973 } else {
5974 specFlags = -1;
5975 }
5976
Adam Lesinskifa7d78a2016-03-07 19:39:56 +00005977 const size_t numConfigs = typeSpec->configs.size();
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005978 for (size_t c = 0; c < numConfigs; c++) {
Adam Lesinskifa7d78a2016-03-07 19:39:56 +00005979 const ResTable_type* const thisType = typeSpec->configs[c];
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005980 if (thisType == NULL) {
5981 continue;
5982 }
5983
5984 ResTable_config thisConfig;
5985 thisConfig.copyFromDtoH(thisType->config);
5986
5987 // Check to make sure this one is valid for the current parameters.
5988 if (config != NULL && !thisConfig.match(*config)) {
5989 continue;
5990 }
5991
5992 // Check if there is the desired entry in this type.
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07005993 const uint32_t* const eindex = reinterpret_cast<const uint32_t*>(
5994 reinterpret_cast<const uint8_t*>(thisType) + dtohs(thisType->header.headerSize));
5995
5996 uint32_t thisOffset = dtohl(eindex[realEntryIndex]);
5997 if (thisOffset == ResTable_type::NO_ENTRY) {
5998 // There is no entry for this index and configuration.
5999 continue;
6000 }
6001
6002 if (bestType != NULL) {
6003 // Check if this one is less specific than the last found. If so,
6004 // we will skip it. We check starting with things we most care
6005 // about to those we least care about.
6006 if (!thisConfig.isBetterThan(bestConfig, config)) {
6007 if (!currentTypeIsOverlay || thisConfig.compare(bestConfig) != 0) {
6008 continue;
6009 }
6010 }
6011 }
6012
6013 bestType = thisType;
6014 bestOffset = thisOffset;
6015 bestConfig = thisConfig;
6016 bestPackage = typeSpec->package;
6017 actualTypeIndex = realTypeIndex;
6018
6019 // If no config was specified, any type will do, so skip
6020 if (config == NULL) {
6021 break;
6022 }
6023 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006024 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006025
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006026 if (bestType == NULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006027 return BAD_INDEX;
6028 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006029
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006030 bestOffset += dtohl(bestType->entriesStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006031
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006032 if (bestOffset > (dtohl(bestType->header.size)-sizeof(ResTable_entry))) {
Steve Block8564c8d2012-01-05 23:22:43 +00006033 ALOGW("ResTable_entry at 0x%x is beyond type chunk data 0x%x",
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006034 bestOffset, dtohl(bestType->header.size));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006035 return BAD_TYPE;
6036 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006037 if ((bestOffset & 0x3) != 0) {
6038 ALOGW("ResTable_entry at 0x%x is not on an integer boundary", bestOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006039 return BAD_TYPE;
6040 }
6041
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006042 const ResTable_entry* const entry = reinterpret_cast<const ResTable_entry*>(
6043 reinterpret_cast<const uint8_t*>(bestType) + bestOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006044 if (dtohs(entry->size) < sizeof(*entry)) {
Steve Block8564c8d2012-01-05 23:22:43 +00006045 ALOGW("ResTable_entry size 0x%x is too small", dtohs(entry->size));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006046 return BAD_TYPE;
6047 }
6048
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006049 if (outEntry != NULL) {
6050 outEntry->entry = entry;
6051 outEntry->config = bestConfig;
6052 outEntry->type = bestType;
6053 outEntry->specFlags = specFlags;
6054 outEntry->package = bestPackage;
6055 outEntry->typeStr = StringPoolRef(&bestPackage->typeStrings, actualTypeIndex - bestPackage->typeIdOffset);
6056 outEntry->keyStr = StringPoolRef(&bestPackage->keyStrings, dtohl(entry->key.index));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006057 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006058 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006059}
6060
6061status_t ResTable::parsePackage(const ResTable_package* const pkg,
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08006062 const Header* const header, bool appAsLib, bool isSystemAsset)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006063{
6064 const uint8_t* base = (const uint8_t*)pkg;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006065 status_t err = validate_chunk(&pkg->header, sizeof(*pkg) - sizeof(pkg->typeIdOffset),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006066 header->dataEnd, "ResTable_package");
6067 if (err != NO_ERROR) {
6068 return (mError=err);
6069 }
6070
Patrik Bannura443dd932014-02-12 13:38:54 +01006071 const uint32_t pkgSize = dtohl(pkg->header.size);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006072
6073 if (dtohl(pkg->typeStrings) >= pkgSize) {
Patrik Bannura443dd932014-02-12 13:38:54 +01006074 ALOGW("ResTable_package type strings at 0x%x are past chunk size 0x%x.",
6075 dtohl(pkg->typeStrings), pkgSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006076 return (mError=BAD_TYPE);
6077 }
6078 if ((dtohl(pkg->typeStrings)&0x3) != 0) {
Patrik Bannura443dd932014-02-12 13:38:54 +01006079 ALOGW("ResTable_package type strings at 0x%x is not on an integer boundary.",
6080 dtohl(pkg->typeStrings));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006081 return (mError=BAD_TYPE);
6082 }
6083 if (dtohl(pkg->keyStrings) >= pkgSize) {
Patrik Bannura443dd932014-02-12 13:38:54 +01006084 ALOGW("ResTable_package key strings at 0x%x are past chunk size 0x%x.",
6085 dtohl(pkg->keyStrings), pkgSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006086 return (mError=BAD_TYPE);
6087 }
6088 if ((dtohl(pkg->keyStrings)&0x3) != 0) {
Patrik Bannura443dd932014-02-12 13:38:54 +01006089 ALOGW("ResTable_package key strings at 0x%x is not on an integer boundary.",
6090 dtohl(pkg->keyStrings));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006091 return (mError=BAD_TYPE);
6092 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006093
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006094 uint32_t id = dtohl(pkg->id);
6095 KeyedVector<uint8_t, IdmapEntries> idmapEntries;
Mark Salyzyn00adb862014-03-19 11:00:06 -07006096
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006097 if (header->resourceIDMap != NULL) {
6098 uint8_t targetPackageId = 0;
6099 status_t err = parseIdmap(header->resourceIDMap, header->resourceIDMapSize, &targetPackageId, &idmapEntries);
6100 if (err != NO_ERROR) {
6101 ALOGW("Overlay is broken");
6102 return (mError=err);
6103 }
6104 id = targetPackageId;
6105 }
6106
6107 if (id >= 256) {
6108 LOG_ALWAYS_FATAL("Package id out of range");
6109 return NO_ERROR;
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08006110 } else if (id == 0 || appAsLib || isSystemAsset) {
6111 // This is a library or a system asset, so assign an ID
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006112 id = mNextPackageId++;
6113 }
6114
6115 PackageGroup* group = NULL;
6116 Package* package = new Package(this, header, pkg);
6117 if (package == NULL) {
6118 return (mError=NO_MEMORY);
6119 }
6120
6121 err = package->typeStrings.setTo(base+dtohl(pkg->typeStrings),
6122 header->dataEnd-(base+dtohl(pkg->typeStrings)));
6123 if (err != NO_ERROR) {
6124 delete group;
6125 delete package;
6126 return (mError=err);
6127 }
6128
6129 err = package->keyStrings.setTo(base+dtohl(pkg->keyStrings),
6130 header->dataEnd-(base+dtohl(pkg->keyStrings)));
6131 if (err != NO_ERROR) {
6132 delete group;
6133 delete package;
6134 return (mError=err);
6135 }
6136
6137 size_t idx = mPackageMap[id];
6138 if (idx == 0) {
6139 idx = mPackageGroups.size() + 1;
6140
Adam Lesinski4bf58102014-11-03 11:21:19 -08006141 char16_t tmpName[sizeof(pkg->name)/sizeof(pkg->name[0])];
6142 strcpy16_dtoh(tmpName, pkg->name, sizeof(pkg->name)/sizeof(pkg->name[0]));
Roozbeh Pournader1c686f22015-12-18 14:22:14 -08006143 group = new PackageGroup(this, String16(tmpName), id, appAsLib, isSystemAsset);
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006144 if (group == NULL) {
6145 delete package;
Dianne Hackborn78c40512009-07-06 11:07:40 -07006146 return (mError=NO_MEMORY);
6147 }
Adam Lesinskifab50872014-04-16 14:40:42 -07006148
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006149 err = mPackageGroups.add(group);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006150 if (err < NO_ERROR) {
6151 return (mError=err);
6152 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006153
6154 mPackageMap[id] = static_cast<uint8_t>(idx);
6155
6156 // Find all packages that reference this package
6157 size_t N = mPackageGroups.size();
6158 for (size_t i = 0; i < N; i++) {
6159 mPackageGroups[i]->dynamicRefTable.addMapping(
6160 group->name, static_cast<uint8_t>(group->id));
6161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006162 } else {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006163 group = mPackageGroups.itemAt(idx - 1);
6164 if (group == NULL) {
6165 return (mError=UNKNOWN_ERROR);
6166 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006167 }
6168
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006169 err = group->packages.add(package);
6170 if (err < NO_ERROR) {
6171 return (mError=err);
6172 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006174 // Iterate through all chunks.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006175 const ResChunk_header* chunk =
6176 (const ResChunk_header*)(((const uint8_t*)pkg)
6177 + dtohs(pkg->header.headerSize));
6178 const uint8_t* endPos = ((const uint8_t*)pkg) + dtohs(pkg->header.size);
6179 while (((const uint8_t*)chunk) <= (endPos-sizeof(ResChunk_header)) &&
6180 ((const uint8_t*)chunk) <= (endPos-dtohl(chunk->size))) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -07006181 if (kDebugTableNoisy) {
6182 ALOGV("PackageChunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%p\n",
6183 dtohs(chunk->type), dtohs(chunk->headerSize), dtohl(chunk->size),
6184 (void*)(((const uint8_t*)chunk) - ((const uint8_t*)header->header)));
6185 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006186 const size_t csize = dtohl(chunk->size);
6187 const uint16_t ctype = dtohs(chunk->type);
6188 if (ctype == RES_TABLE_TYPE_SPEC_TYPE) {
6189 const ResTable_typeSpec* typeSpec = (const ResTable_typeSpec*)(chunk);
6190 err = validate_chunk(&typeSpec->header, sizeof(*typeSpec),
6191 endPos, "ResTable_typeSpec");
6192 if (err != NO_ERROR) {
6193 return (mError=err);
6194 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006196 const size_t typeSpecSize = dtohl(typeSpec->header.size);
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006197 const size_t newEntryCount = dtohl(typeSpec->entryCount);
Mark Salyzyn00adb862014-03-19 11:00:06 -07006198
Andreas Gampe2204f0b2014-10-21 23:04:54 -07006199 if (kDebugLoadTableNoisy) {
6200 ALOGI("TypeSpec off %p: type=0x%x, headerSize=0x%x, size=%p\n",
6201 (void*)(base-(const uint8_t*)chunk),
6202 dtohs(typeSpec->header.type),
6203 dtohs(typeSpec->header.headerSize),
6204 (void*)typeSpecSize);
6205 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006206 // look for block overrun or int overflow when multiplying by 4
6207 if ((dtohl(typeSpec->entryCount) > (INT32_MAX/sizeof(uint32_t))
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006208 || dtohs(typeSpec->header.headerSize)+(sizeof(uint32_t)*newEntryCount)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006209 > typeSpecSize)) {
Steve Block8564c8d2012-01-05 23:22:43 +00006210 ALOGW("ResTable_typeSpec entry index to %p extends beyond chunk end %p.",
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006211 (void*)(dtohs(typeSpec->header.headerSize) + (sizeof(uint32_t)*newEntryCount)),
6212 (void*)typeSpecSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006213 return (mError=BAD_TYPE);
6214 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006216 if (typeSpec->id == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00006217 ALOGW("ResTable_type has an id of 0.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006218 return (mError=BAD_TYPE);
6219 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006220
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006221 if (newEntryCount > 0) {
6222 uint8_t typeIndex = typeSpec->id - 1;
6223 ssize_t idmapIndex = idmapEntries.indexOfKey(typeSpec->id);
6224 if (idmapIndex >= 0) {
6225 typeIndex = idmapEntries[idmapIndex].targetTypeId() - 1;
6226 }
6227
6228 TypeList& typeList = group->types.editItemAt(typeIndex);
6229 if (!typeList.isEmpty()) {
6230 const Type* existingType = typeList[0];
6231 if (existingType->entryCount != newEntryCount && idmapIndex < 0) {
6232 ALOGW("ResTable_typeSpec entry count inconsistent: given %d, previously %d",
6233 (int) newEntryCount, (int) existingType->entryCount);
6234 // We should normally abort here, but some legacy apps declare
6235 // resources in the 'android' package (old bug in AAPT).
6236 }
6237 }
6238
6239 Type* t = new Type(header, package, newEntryCount);
6240 t->typeSpec = typeSpec;
6241 t->typeSpecFlags = (const uint32_t*)(
6242 ((const uint8_t*)typeSpec) + dtohs(typeSpec->header.headerSize));
6243 if (idmapIndex >= 0) {
6244 t->idmapEntries = idmapEntries[idmapIndex];
6245 }
6246 typeList.add(t);
6247 group->largestTypeId = max(group->largestTypeId, typeSpec->id);
6248 } else {
6249 ALOGV("Skipping empty ResTable_typeSpec for type %d", typeSpec->id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006250 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006252 } else if (ctype == RES_TABLE_TYPE_TYPE) {
6253 const ResTable_type* type = (const ResTable_type*)(chunk);
6254 err = validate_chunk(&type->header, sizeof(*type)-sizeof(ResTable_config)+4,
6255 endPos, "ResTable_type");
6256 if (err != NO_ERROR) {
6257 return (mError=err);
6258 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006259
Patrik Bannura443dd932014-02-12 13:38:54 +01006260 const uint32_t typeSize = dtohl(type->header.size);
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006261 const size_t newEntryCount = dtohl(type->entryCount);
Mark Salyzyn00adb862014-03-19 11:00:06 -07006262
Andreas Gampe2204f0b2014-10-21 23:04:54 -07006263 if (kDebugLoadTableNoisy) {
6264 printf("Type off %p: type=0x%x, headerSize=0x%x, size=%u\n",
6265 (void*)(base-(const uint8_t*)chunk),
6266 dtohs(type->header.type),
6267 dtohs(type->header.headerSize),
6268 typeSize);
6269 }
6270 if (dtohs(type->header.headerSize)+(sizeof(uint32_t)*newEntryCount) > typeSize) {
Patrik Bannura443dd932014-02-12 13:38:54 +01006271 ALOGW("ResTable_type entry index to %p extends beyond chunk end 0x%x.",
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006272 (void*)(dtohs(type->header.headerSize) + (sizeof(uint32_t)*newEntryCount)),
6273 typeSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006274 return (mError=BAD_TYPE);
6275 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006276
6277 if (newEntryCount != 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006278 && dtohl(type->entriesStart) > (typeSize-sizeof(ResTable_entry))) {
Patrik Bannura443dd932014-02-12 13:38:54 +01006279 ALOGW("ResTable_type entriesStart at 0x%x extends beyond chunk end 0x%x.",
6280 dtohl(type->entriesStart), typeSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006281 return (mError=BAD_TYPE);
6282 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006284 if (type->id == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00006285 ALOGW("ResTable_type has an id of 0.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006286 return (mError=BAD_TYPE);
6287 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006288
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006289 if (newEntryCount > 0) {
6290 uint8_t typeIndex = type->id - 1;
6291 ssize_t idmapIndex = idmapEntries.indexOfKey(type->id);
6292 if (idmapIndex >= 0) {
6293 typeIndex = idmapEntries[idmapIndex].targetTypeId() - 1;
6294 }
6295
6296 TypeList& typeList = group->types.editItemAt(typeIndex);
6297 if (typeList.isEmpty()) {
6298 ALOGE("No TypeSpec for type %d", type->id);
6299 return (mError=BAD_TYPE);
6300 }
6301
6302 Type* t = typeList.editItemAt(typeList.size() - 1);
6303 if (newEntryCount != t->entryCount) {
6304 ALOGE("ResTable_type entry count inconsistent: given %d, previously %d",
6305 (int)newEntryCount, (int)t->entryCount);
6306 return (mError=BAD_TYPE);
6307 }
6308
6309 if (t->package != package) {
6310 ALOGE("No TypeSpec for type %d", type->id);
6311 return (mError=BAD_TYPE);
6312 }
6313
6314 t->configs.add(type);
6315
Andreas Gampe2204f0b2014-10-21 23:04:54 -07006316 if (kDebugTableGetEntry) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006317 ResTable_config thisConfig;
6318 thisConfig.copyFromDtoH(type->config);
Andreas Gampe2204f0b2014-10-21 23:04:54 -07006319 ALOGI("Adding config to type %d: %s\n", type->id,
6320 thisConfig.toString().string());
6321 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006322 } else {
6323 ALOGV("Skipping empty ResTable_type for type %d", type->id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006324 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006325
Adam Lesinskide898ff2014-01-29 18:20:45 -08006326 } else if (ctype == RES_TABLE_LIBRARY_TYPE) {
6327 if (group->dynamicRefTable.entries().size() == 0) {
6328 status_t err = group->dynamicRefTable.load((const ResTable_lib_header*) chunk);
6329 if (err != NO_ERROR) {
6330 return (mError=err);
6331 }
6332
6333 // Fill in the reference table with the entries we already know about.
6334 size_t N = mPackageGroups.size();
6335 for (size_t i = 0; i < N; i++) {
6336 group->dynamicRefTable.addMapping(mPackageGroups[i]->name, mPackageGroups[i]->id);
6337 }
6338 } else {
6339 ALOGW("Found multiple library tables, ignoring...");
6340 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006341 } else {
6342 status_t err = validate_chunk(chunk, sizeof(ResChunk_header),
6343 endPos, "ResTable_package:unknown");
6344 if (err != NO_ERROR) {
6345 return (mError=err);
6346 }
6347 }
6348 chunk = (const ResChunk_header*)
6349 (((const uint8_t*)chunk) + csize);
6350 }
6351
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006352 return NO_ERROR;
6353}
6354
Tao Baia6d7e3f2015-09-01 18:49:54 -07006355DynamicRefTable::DynamicRefTable(uint8_t packageId, bool appAsLib)
Adam Lesinskide898ff2014-01-29 18:20:45 -08006356 : mAssignedPackageId(packageId)
Tao Baia6d7e3f2015-09-01 18:49:54 -07006357 , mAppAsLib(appAsLib)
Adam Lesinskide898ff2014-01-29 18:20:45 -08006358{
6359 memset(mLookupTable, 0, sizeof(mLookupTable));
6360
6361 // Reserved package ids
6362 mLookupTable[APP_PACKAGE_ID] = APP_PACKAGE_ID;
6363 mLookupTable[SYS_PACKAGE_ID] = SYS_PACKAGE_ID;
6364}
6365
6366status_t DynamicRefTable::load(const ResTable_lib_header* const header)
6367{
6368 const uint32_t entryCount = dtohl(header->count);
6369 const uint32_t sizeOfEntries = sizeof(ResTable_lib_entry) * entryCount;
6370 const uint32_t expectedSize = dtohl(header->header.size) - dtohl(header->header.headerSize);
6371 if (sizeOfEntries > expectedSize) {
6372 ALOGE("ResTable_lib_header size %u is too small to fit %u entries (x %u).",
6373 expectedSize, entryCount, (uint32_t)sizeof(ResTable_lib_entry));
6374 return UNKNOWN_ERROR;
6375 }
6376
6377 const ResTable_lib_entry* entry = (const ResTable_lib_entry*)(((uint8_t*) header) +
6378 dtohl(header->header.headerSize));
6379 for (uint32_t entryIndex = 0; entryIndex < entryCount; entryIndex++) {
6380 uint32_t packageId = dtohl(entry->packageId);
6381 char16_t tmpName[sizeof(entry->packageName) / sizeof(char16_t)];
6382 strcpy16_dtoh(tmpName, entry->packageName, sizeof(entry->packageName) / sizeof(char16_t));
Andreas Gampe2204f0b2014-10-21 23:04:54 -07006383 if (kDebugLibNoisy) {
6384 ALOGV("Found lib entry %s with id %d\n", String8(tmpName).string(),
6385 dtohl(entry->packageId));
6386 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08006387 if (packageId >= 256) {
6388 ALOGE("Bad package id 0x%08x", packageId);
6389 return UNKNOWN_ERROR;
6390 }
6391 mEntries.replaceValueFor(String16(tmpName), (uint8_t) packageId);
6392 entry = entry + 1;
6393 }
6394 return NO_ERROR;
6395}
6396
Adam Lesinski6022deb2014-08-20 14:59:19 -07006397status_t DynamicRefTable::addMappings(const DynamicRefTable& other) {
6398 if (mAssignedPackageId != other.mAssignedPackageId) {
6399 return UNKNOWN_ERROR;
6400 }
6401
6402 const size_t entryCount = other.mEntries.size();
6403 for (size_t i = 0; i < entryCount; i++) {
6404 ssize_t index = mEntries.indexOfKey(other.mEntries.keyAt(i));
6405 if (index < 0) {
6406 mEntries.add(other.mEntries.keyAt(i), other.mEntries[i]);
6407 } else {
6408 if (other.mEntries[i] != mEntries[index]) {
6409 return UNKNOWN_ERROR;
6410 }
6411 }
6412 }
6413
6414 // Merge the lookup table. No entry can conflict
6415 // (value of 0 means not set).
6416 for (size_t i = 0; i < 256; i++) {
6417 if (mLookupTable[i] != other.mLookupTable[i]) {
6418 if (mLookupTable[i] == 0) {
6419 mLookupTable[i] = other.mLookupTable[i];
6420 } else if (other.mLookupTable[i] != 0) {
6421 return UNKNOWN_ERROR;
6422 }
6423 }
6424 }
6425 return NO_ERROR;
6426}
6427
Adam Lesinskide898ff2014-01-29 18:20:45 -08006428status_t DynamicRefTable::addMapping(const String16& packageName, uint8_t packageId)
6429{
6430 ssize_t index = mEntries.indexOfKey(packageName);
6431 if (index < 0) {
6432 return UNKNOWN_ERROR;
6433 }
6434 mLookupTable[mEntries.valueAt(index)] = packageId;
6435 return NO_ERROR;
6436}
6437
6438status_t DynamicRefTable::lookupResourceId(uint32_t* resId) const {
6439 uint32_t res = *resId;
6440 size_t packageId = Res_GETPACKAGE(res) + 1;
6441
Tao Baia6d7e3f2015-09-01 18:49:54 -07006442 if (packageId == APP_PACKAGE_ID && !mAppAsLib) {
Adam Lesinskide898ff2014-01-29 18:20:45 -08006443 // No lookup needs to be done, app package IDs are absolute.
6444 return NO_ERROR;
6445 }
6446
Tao Baia6d7e3f2015-09-01 18:49:54 -07006447 if (packageId == 0 || (packageId == APP_PACKAGE_ID && mAppAsLib)) {
Adam Lesinskide898ff2014-01-29 18:20:45 -08006448 // The package ID is 0x00. That means that a shared library is accessing
Tao Baia6d7e3f2015-09-01 18:49:54 -07006449 // its own local resource.
6450 // Or if app resource is loaded as shared library, the resource which has
6451 // app package Id is local resources.
6452 // so we fix up those resources with the calling package ID.
6453 *resId = (0xFFFFFF & (*resId)) | (((uint32_t) mAssignedPackageId) << 24);
Adam Lesinskide898ff2014-01-29 18:20:45 -08006454 return NO_ERROR;
6455 }
6456
6457 // Do a proper lookup.
6458 uint8_t translatedId = mLookupTable[packageId];
6459 if (translatedId == 0) {
Adam Lesinskia7d1d732014-10-01 18:24:54 -07006460 ALOGV("DynamicRefTable(0x%02x): No mapping for build-time package ID 0x%02x.",
Adam Lesinskide898ff2014-01-29 18:20:45 -08006461 (uint8_t)mAssignedPackageId, (uint8_t)packageId);
6462 for (size_t i = 0; i < 256; i++) {
6463 if (mLookupTable[i] != 0) {
Adam Lesinskia7d1d732014-10-01 18:24:54 -07006464 ALOGV("e[0x%02x] -> 0x%02x", (uint8_t)i, mLookupTable[i]);
Adam Lesinskide898ff2014-01-29 18:20:45 -08006465 }
6466 }
6467 return UNKNOWN_ERROR;
6468 }
6469
6470 *resId = (res & 0x00ffffff) | (((uint32_t) translatedId) << 24);
6471 return NO_ERROR;
6472}
6473
6474status_t DynamicRefTable::lookupResourceValue(Res_value* value) const {
Tao Baia6d7e3f2015-09-01 18:49:54 -07006475 if (value->dataType != Res_value::TYPE_DYNAMIC_REFERENCE &&
6476 (value->dataType != Res_value::TYPE_REFERENCE || !mAppAsLib)) {
6477 // If the package is loaded as shared library, the resource reference
6478 // also need to be fixed.
Adam Lesinskide898ff2014-01-29 18:20:45 -08006479 return NO_ERROR;
6480 }
6481
6482 status_t err = lookupResourceId(&value->data);
6483 if (err != NO_ERROR) {
6484 return err;
6485 }
6486
6487 value->dataType = Res_value::TYPE_REFERENCE;
6488 return NO_ERROR;
6489}
6490
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006491struct IdmapTypeMap {
6492 ssize_t overlayTypeId;
6493 size_t entryOffset;
6494 Vector<uint32_t> entryMap;
6495};
6496
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006497status_t ResTable::createIdmap(const ResTable& overlay,
6498 uint32_t targetCrc, uint32_t overlayCrc,
6499 const char* targetPath, const char* overlayPath,
6500 void** outData, size_t* outSize) const
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006501{
6502 // see README for details on the format of map
6503 if (mPackageGroups.size() == 0) {
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006504 ALOGW("idmap: target package has no package groups, cannot create idmap\n");
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006505 return UNKNOWN_ERROR;
6506 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006507
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006508 if (mPackageGroups[0]->packages.size() == 0) {
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006509 ALOGW("idmap: target package has no packages in its first package group, "
6510 "cannot create idmap\n");
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006511 return UNKNOWN_ERROR;
6512 }
6513
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006514 KeyedVector<uint8_t, IdmapTypeMap> map;
6515
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006516 // overlaid packages are assumed to contain only one package group
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006517 const PackageGroup* pg = mPackageGroups[0];
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006518
6519 // starting size is header
6520 *outSize = ResTable::IDMAP_HEADER_SIZE_BYTES;
6521
6522 // target package id and number of types in map
6523 *outSize += 2 * sizeof(uint16_t);
6524
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006525 // overlay packages are assumed to contain only one package group
Adam Lesinski4bf58102014-11-03 11:21:19 -08006526 const ResTable_package* overlayPackageStruct = overlay.mPackageGroups[0]->packages[0]->package;
6527 char16_t tmpName[sizeof(overlayPackageStruct->name)/sizeof(overlayPackageStruct->name[0])];
6528 strcpy16_dtoh(tmpName, overlayPackageStruct->name, sizeof(overlayPackageStruct->name)/sizeof(overlayPackageStruct->name[0]));
6529 const String16 overlayPackage(tmpName);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006530
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006531 for (size_t typeIndex = 0; typeIndex < pg->types.size(); ++typeIndex) {
6532 const TypeList& typeList = pg->types[typeIndex];
6533 if (typeList.isEmpty()) {
6534 continue;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006535 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006536
6537 const Type* typeConfigs = typeList[0];
6538
6539 IdmapTypeMap typeMap;
6540 typeMap.overlayTypeId = -1;
6541 typeMap.entryOffset = 0;
6542
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006543 for (size_t entryIndex = 0; entryIndex < typeConfigs->entryCount; ++entryIndex) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006544 uint32_t resID = Res_MAKEID(pg->id - 1, typeIndex, entryIndex);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006545 resource_name resName;
MÃ¥rten Kongstad65a05fd2014-01-31 14:01:52 +01006546 if (!this->getResourceName(resID, false, &resName)) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006547 if (typeMap.entryMap.isEmpty()) {
6548 typeMap.entryOffset++;
6549 }
MÃ¥rten Kongstadfcaba142011-05-19 16:02:35 +02006550 continue;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006551 }
6552
6553 const String16 overlayType(resName.type, resName.typeLen);
6554 const String16 overlayName(resName.name, resName.nameLen);
6555 uint32_t overlayResID = overlay.identifierForName(overlayName.string(),
6556 overlayName.size(),
6557 overlayType.string(),
6558 overlayType.size(),
6559 overlayPackage.string(),
6560 overlayPackage.size());
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006561 if (overlayResID == 0) {
6562 if (typeMap.entryMap.isEmpty()) {
6563 typeMap.entryOffset++;
Jean-Baptiste Queru3e2d5912012-05-01 10:00:22 -07006564 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006565 continue;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006566 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006567
6568 if (typeMap.overlayTypeId == -1) {
6569 typeMap.overlayTypeId = Res_GETTYPE(overlayResID) + 1;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006570 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006571
6572 if (Res_GETTYPE(overlayResID) + 1 != static_cast<size_t>(typeMap.overlayTypeId)) {
6573 ALOGE("idmap: can't mix type ids in entry map. Resource 0x%08x maps to 0x%08x"
Andreas Gampe2204f0b2014-10-21 23:04:54 -07006574 " but entries should map to resources of type %02zx",
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006575 resID, overlayResID, typeMap.overlayTypeId);
6576 return BAD_TYPE;
6577 }
6578
6579 if (typeMap.entryOffset + typeMap.entryMap.size() < entryIndex) {
MÃ¥rten Kongstad96198eb2014-11-07 10:56:12 +01006580 // pad with 0xffffffff's (indicating non-existing entries) before adding this entry
6581 size_t index = typeMap.entryMap.size();
6582 size_t numItems = entryIndex - (typeMap.entryOffset + index);
6583 if (typeMap.entryMap.insertAt(0xffffffff, index, numItems) < 0) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006584 return NO_MEMORY;
6585 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006586 }
MÃ¥rten Kongstad96198eb2014-11-07 10:56:12 +01006587 typeMap.entryMap.add(Res_GETENTRY(overlayResID));
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006588 }
6589
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006590 if (!typeMap.entryMap.isEmpty()) {
6591 if (map.add(static_cast<uint8_t>(typeIndex), typeMap) < 0) {
6592 return NO_MEMORY;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006593 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006594 *outSize += (4 * sizeof(uint16_t)) + (typeMap.entryMap.size() * sizeof(uint32_t));
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006595 }
6596 }
6597
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006598 if (map.isEmpty()) {
6599 ALOGW("idmap: no resources in overlay package present in base package");
6600 return UNKNOWN_ERROR;
6601 }
6602
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006603 if ((*outData = malloc(*outSize)) == NULL) {
6604 return NO_MEMORY;
6605 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006606
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006607 uint32_t* data = (uint32_t*)*outData;
6608 *data++ = htodl(IDMAP_MAGIC);
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006609 *data++ = htodl(IDMAP_CURRENT_VERSION);
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006610 *data++ = htodl(targetCrc);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006611 *data++ = htodl(overlayCrc);
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006612 const char* paths[] = { targetPath, overlayPath };
6613 for (int j = 0; j < 2; ++j) {
6614 char* p = (char*)data;
6615 const char* path = paths[j];
6616 const size_t I = strlen(path);
6617 if (I > 255) {
6618 ALOGV("path exceeds expected 255 characters: %s\n", path);
6619 return UNKNOWN_ERROR;
6620 }
6621 for (size_t i = 0; i < 256; ++i) {
6622 *p++ = i < I ? path[i] : '\0';
6623 }
6624 data += 256 / sizeof(uint32_t);
6625 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006626 const size_t mapSize = map.size();
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006627 uint16_t* typeData = reinterpret_cast<uint16_t*>(data);
6628 *typeData++ = htods(pg->id);
6629 *typeData++ = htods(mapSize);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006630 for (size_t i = 0; i < mapSize; ++i) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006631 uint8_t targetTypeId = map.keyAt(i);
6632 const IdmapTypeMap& typeMap = map[i];
6633 *typeData++ = htods(targetTypeId + 1);
6634 *typeData++ = htods(typeMap.overlayTypeId);
6635 *typeData++ = htods(typeMap.entryMap.size());
6636 *typeData++ = htods(typeMap.entryOffset);
6637
6638 const size_t entryCount = typeMap.entryMap.size();
6639 uint32_t* entries = reinterpret_cast<uint32_t*>(typeData);
6640 for (size_t j = 0; j < entryCount; j++) {
6641 entries[j] = htodl(typeMap.entryMap[j]);
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006642 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006643 typeData += entryCount * 2;
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006644 }
6645
6646 return NO_ERROR;
6647}
6648
6649bool ResTable::getIdmapInfo(const void* idmap, size_t sizeBytes,
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006650 uint32_t* pVersion,
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006651 uint32_t* pTargetCrc, uint32_t* pOverlayCrc,
6652 String8* pTargetPath, String8* pOverlayPath)
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006653{
6654 const uint32_t* map = (const uint32_t*)idmap;
6655 if (!assertIdmapHeader(map, sizeBytes)) {
6656 return false;
6657 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006658 if (pVersion) {
6659 *pVersion = dtohl(map[1]);
6660 }
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006661 if (pTargetCrc) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006662 *pTargetCrc = dtohl(map[2]);
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006663 }
6664 if (pOverlayCrc) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006665 *pOverlayCrc = dtohl(map[3]);
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006666 }
6667 if (pTargetPath) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006668 pTargetPath->setTo(reinterpret_cast<const char*>(map + 4));
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006669 }
6670 if (pOverlayPath) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006671 pOverlayPath->setTo(reinterpret_cast<const char*>(map + 4 + 256 / sizeof(uint32_t)));
MÃ¥rten Kongstad48d22322014-01-31 14:43:27 +01006672 }
MÃ¥rten Kongstad57f4b772011-03-17 14:13:41 +01006673 return true;
6674}
6675
6676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006677#define CHAR16_TO_CSTR(c16, len) (String8(String16(c16,len)).string())
6678
6679#define CHAR16_ARRAY_EQ(constant, var, len) \
6680 ((len == (sizeof(constant)/sizeof(constant[0]))) && (0 == memcmp((var), (constant), (len))))
6681
Jeff Brown9d3b1a42013-07-01 19:07:15 -07006682static void print_complex(uint32_t complex, bool isFraction)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006683{
Dianne Hackborne17086b2009-06-19 15:13:28 -07006684 const float MANTISSA_MULT =
6685 1.0f / (1<<Res_value::COMPLEX_MANTISSA_SHIFT);
6686 const float RADIX_MULTS[] = {
6687 1.0f*MANTISSA_MULT, 1.0f/(1<<7)*MANTISSA_MULT,
6688 1.0f/(1<<15)*MANTISSA_MULT, 1.0f/(1<<23)*MANTISSA_MULT
6689 };
6690
6691 float value = (complex&(Res_value::COMPLEX_MANTISSA_MASK
6692 <<Res_value::COMPLEX_MANTISSA_SHIFT))
6693 * RADIX_MULTS[(complex>>Res_value::COMPLEX_RADIX_SHIFT)
6694 & Res_value::COMPLEX_RADIX_MASK];
6695 printf("%f", value);
Mark Salyzyn00adb862014-03-19 11:00:06 -07006696
Dianne Hackbornde7faf62009-06-30 13:27:30 -07006697 if (!isFraction) {
Dianne Hackborne17086b2009-06-19 15:13:28 -07006698 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
6699 case Res_value::COMPLEX_UNIT_PX: printf("px"); break;
6700 case Res_value::COMPLEX_UNIT_DIP: printf("dp"); break;
6701 case Res_value::COMPLEX_UNIT_SP: printf("sp"); break;
6702 case Res_value::COMPLEX_UNIT_PT: printf("pt"); break;
6703 case Res_value::COMPLEX_UNIT_IN: printf("in"); break;
6704 case Res_value::COMPLEX_UNIT_MM: printf("mm"); break;
6705 default: printf(" (unknown unit)"); break;
6706 }
6707 } else {
6708 switch ((complex>>Res_value::COMPLEX_UNIT_SHIFT)&Res_value::COMPLEX_UNIT_MASK) {
6709 case Res_value::COMPLEX_UNIT_FRACTION: printf("%%"); break;
6710 case Res_value::COMPLEX_UNIT_FRACTION_PARENT: printf("%%p"); break;
6711 default: printf(" (unknown unit)"); break;
6712 }
6713 }
6714}
6715
Shachar Shemesh9872bf42010-12-20 17:38:33 +02006716// Normalize a string for output
6717String8 ResTable::normalizeForOutput( const char *input )
6718{
6719 String8 ret;
6720 char buff[2];
6721 buff[1] = '\0';
6722
6723 while (*input != '\0') {
6724 switch (*input) {
6725 // All interesting characters are in the ASCII zone, so we are making our own lives
6726 // easier by scanning the string one byte at a time.
6727 case '\\':
6728 ret += "\\\\";
6729 break;
6730 case '\n':
6731 ret += "\\n";
6732 break;
6733 case '"':
6734 ret += "\\\"";
6735 break;
6736 default:
6737 buff[0] = *input;
6738 ret += buff;
6739 break;
6740 }
6741
6742 input++;
6743 }
6744
6745 return ret;
6746}
6747
Dianne Hackbornde7faf62009-06-30 13:27:30 -07006748void ResTable::print_value(const Package* pkg, const Res_value& value) const
6749{
6750 if (value.dataType == Res_value::TYPE_NULL) {
Alan Viverettef2969402014-10-29 17:09:36 -07006751 if (value.data == Res_value::DATA_NULL_UNDEFINED) {
6752 printf("(null)\n");
6753 } else if (value.data == Res_value::DATA_NULL_EMPTY) {
6754 printf("(null empty)\n");
6755 } else {
6756 // This should never happen.
6757 printf("(null) 0x%08x\n", value.data);
6758 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07006759 } else if (value.dataType == Res_value::TYPE_REFERENCE) {
6760 printf("(reference) 0x%08x\n", value.data);
Adam Lesinskide898ff2014-01-29 18:20:45 -08006761 } else if (value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE) {
6762 printf("(dynamic reference) 0x%08x\n", value.data);
Dianne Hackbornde7faf62009-06-30 13:27:30 -07006763 } else if (value.dataType == Res_value::TYPE_ATTRIBUTE) {
6764 printf("(attribute) 0x%08x\n", value.data);
6765 } else if (value.dataType == Res_value::TYPE_STRING) {
6766 size_t len;
Kenny Root780d2a12010-02-22 22:36:26 -08006767 const char* str8 = pkg->header->values.string8At(
Dianne Hackbornde7faf62009-06-30 13:27:30 -07006768 value.data, &len);
Kenny Root780d2a12010-02-22 22:36:26 -08006769 if (str8 != NULL) {
Shachar Shemesh9872bf42010-12-20 17:38:33 +02006770 printf("(string8) \"%s\"\n", normalizeForOutput(str8).string());
Dianne Hackbornde7faf62009-06-30 13:27:30 -07006771 } else {
Kenny Root780d2a12010-02-22 22:36:26 -08006772 const char16_t* str16 = pkg->header->values.stringAt(
6773 value.data, &len);
6774 if (str16 != NULL) {
6775 printf("(string16) \"%s\"\n",
Shachar Shemesh9872bf42010-12-20 17:38:33 +02006776 normalizeForOutput(String8(str16, len).string()).string());
Kenny Root780d2a12010-02-22 22:36:26 -08006777 } else {
6778 printf("(string) null\n");
6779 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006780 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07006781 } else if (value.dataType == Res_value::TYPE_FLOAT) {
6782 printf("(float) %g\n", *(const float*)&value.data);
6783 } else if (value.dataType == Res_value::TYPE_DIMENSION) {
6784 printf("(dimension) ");
6785 print_complex(value.data, false);
6786 printf("\n");
6787 } else if (value.dataType == Res_value::TYPE_FRACTION) {
6788 printf("(fraction) ");
6789 print_complex(value.data, true);
6790 printf("\n");
6791 } else if (value.dataType >= Res_value::TYPE_FIRST_COLOR_INT
6792 || value.dataType <= Res_value::TYPE_LAST_COLOR_INT) {
6793 printf("(color) #%08x\n", value.data);
6794 } else if (value.dataType == Res_value::TYPE_INT_BOOLEAN) {
6795 printf("(boolean) %s\n", value.data ? "true" : "false");
6796 } else if (value.dataType >= Res_value::TYPE_FIRST_INT
6797 || value.dataType <= Res_value::TYPE_LAST_INT) {
6798 printf("(int) 0x%08x or %d\n", value.data, value.data);
6799 } else {
6800 printf("(unknown type) t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)\n",
6801 (int)value.dataType, (int)value.data,
6802 (int)value.size, (int)value.res0);
6803 }
6804}
6805
Dianne Hackborne17086b2009-06-19 15:13:28 -07006806void ResTable::print(bool inclValues) const
6807{
6808 if (mError != 0) {
6809 printf("mError=0x%x (%s)\n", mError, strerror(mError));
6810 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006811 size_t pgCount = mPackageGroups.size();
6812 printf("Package Groups (%d)\n", (int)pgCount);
6813 for (size_t pgIndex=0; pgIndex<pgCount; pgIndex++) {
6814 const PackageGroup* pg = mPackageGroups[pgIndex];
Adam Lesinski6022deb2014-08-20 14:59:19 -07006815 printf("Package Group %d id=0x%02x packageCount=%d name=%s\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006816 (int)pgIndex, pg->id, (int)pg->packages.size(),
6817 String8(pg->name).string());
Mark Salyzyn00adb862014-03-19 11:00:06 -07006818
Adam Lesinski6022deb2014-08-20 14:59:19 -07006819 const KeyedVector<String16, uint8_t>& refEntries = pg->dynamicRefTable.entries();
6820 const size_t refEntryCount = refEntries.size();
6821 if (refEntryCount > 0) {
6822 printf(" DynamicRefTable entryCount=%d:\n", (int) refEntryCount);
6823 for (size_t refIndex = 0; refIndex < refEntryCount; refIndex++) {
6824 printf(" 0x%02x -> %s\n",
6825 refEntries.valueAt(refIndex),
6826 String8(refEntries.keyAt(refIndex)).string());
6827 }
6828 printf("\n");
6829 }
6830
6831 int packageId = pg->id;
Adam Lesinski18560882014-08-15 17:18:21 +00006832 size_t pkgCount = pg->packages.size();
6833 for (size_t pkgIndex=0; pkgIndex<pkgCount; pkgIndex++) {
6834 const Package* pkg = pg->packages[pkgIndex];
Adam Lesinski6022deb2014-08-20 14:59:19 -07006835 // Use a package's real ID, since the ID may have been assigned
6836 // if this package is a shared library.
6837 packageId = pkg->package->id;
Adam Lesinski4bf58102014-11-03 11:21:19 -08006838 char16_t tmpName[sizeof(pkg->package->name)/sizeof(pkg->package->name[0])];
6839 strcpy16_dtoh(tmpName, pkg->package->name, sizeof(pkg->package->name)/sizeof(pkg->package->name[0]));
Adam Lesinski6022deb2014-08-20 14:59:19 -07006840 printf(" Package %d id=0x%02x name=%s\n", (int)pkgIndex,
Adam Lesinski4bf58102014-11-03 11:21:19 -08006841 pkg->package->id, String8(tmpName).string());
Adam Lesinski18560882014-08-15 17:18:21 +00006842 }
6843
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006844 for (size_t typeIndex=0; typeIndex < pg->types.size(); typeIndex++) {
6845 const TypeList& typeList = pg->types[typeIndex];
6846 if (typeList.isEmpty()) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006847 continue;
6848 }
6849 const Type* typeConfigs = typeList[0];
6850 const size_t NTC = typeConfigs->configs.size();
6851 printf(" type %d configCount=%d entryCount=%d\n",
6852 (int)typeIndex, (int)NTC, (int)typeConfigs->entryCount);
6853 if (typeConfigs->typeSpecFlags != NULL) {
6854 for (size_t entryIndex=0; entryIndex<typeConfigs->entryCount; entryIndex++) {
Adam Lesinski6022deb2014-08-20 14:59:19 -07006855 uint32_t resID = (0xff000000 & ((packageId)<<24))
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006856 | (0x00ff0000 & ((typeIndex+1)<<16))
6857 | (0x0000ffff & (entryIndex));
6858 // Since we are creating resID without actually
6859 // iterating over them, we have no idea which is a
6860 // dynamic reference. We must check.
Adam Lesinski6022deb2014-08-20 14:59:19 -07006861 if (packageId == 0) {
6862 pg->dynamicRefTable.lookupResourceId(&resID);
6863 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006864
6865 resource_name resName;
6866 if (this->getResourceName(resID, true, &resName)) {
6867 String8 type8;
6868 String8 name8;
6869 if (resName.type8 != NULL) {
6870 type8 = String8(resName.type8, resName.typeLen);
6871 } else {
6872 type8 = String8(resName.type, resName.typeLen);
6873 }
6874 if (resName.name8 != NULL) {
6875 name8 = String8(resName.name8, resName.nameLen);
6876 } else {
6877 name8 = String8(resName.name, resName.nameLen);
6878 }
6879 printf(" spec resource 0x%08x %s:%s/%s: flags=0x%08x\n",
6880 resID,
6881 CHAR16_TO_CSTR(resName.package, resName.packageLen),
6882 type8.string(), name8.string(),
6883 dtohl(typeConfigs->typeSpecFlags[entryIndex]));
6884 } else {
6885 printf(" INVALID TYPE CONFIG FOR RESOURCE 0x%08x\n", resID);
6886 }
6887 }
6888 }
6889 for (size_t configIndex=0; configIndex<NTC; configIndex++) {
6890 const ResTable_type* type = typeConfigs->configs[configIndex];
6891 if ((((uint64_t)type)&0x3) != 0) {
6892 printf(" NON-INTEGER ResTable_type ADDRESS: %p\n", type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006893 continue;
6894 }
Adam Lesinski5b0f1be2015-07-27 16:53:14 -07006895
6896 // Always copy the config, as fields get added and we need to
6897 // set the defaults.
6898 ResTable_config thisConfig;
6899 thisConfig.copyFromDtoH(type->config);
6900
6901 String8 configStr = thisConfig.toString();
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006902 printf(" config %s:\n", configStr.size() > 0
6903 ? configStr.string() : "(default)");
6904 size_t entryCount = dtohl(type->entryCount);
6905 uint32_t entriesStart = dtohl(type->entriesStart);
6906 if ((entriesStart&0x3) != 0) {
6907 printf(" NON-INTEGER ResTable_type entriesStart OFFSET: 0x%x\n", entriesStart);
6908 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006909 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006910 uint32_t typeSize = dtohl(type->header.size);
6911 if ((typeSize&0x3) != 0) {
6912 printf(" NON-INTEGER ResTable_type header.size: 0x%x\n", typeSize);
6913 continue;
6914 }
6915 for (size_t entryIndex=0; entryIndex<entryCount; entryIndex++) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006916 const uint32_t* const eindex = (const uint32_t*)
6917 (((const uint8_t*)type) + dtohs(type->header.headerSize));
6918
6919 uint32_t thisOffset = dtohl(eindex[entryIndex]);
6920 if (thisOffset == ResTable_type::NO_ENTRY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006921 continue;
6922 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006923
Adam Lesinski6022deb2014-08-20 14:59:19 -07006924 uint32_t resID = (0xff000000 & ((packageId)<<24))
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006925 | (0x00ff0000 & ((typeIndex+1)<<16))
6926 | (0x0000ffff & (entryIndex));
Adam Lesinski6022deb2014-08-20 14:59:19 -07006927 if (packageId == 0) {
6928 pg->dynamicRefTable.lookupResourceId(&resID);
6929 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006930 resource_name resName;
6931 if (this->getResourceName(resID, true, &resName)) {
6932 String8 type8;
6933 String8 name8;
6934 if (resName.type8 != NULL) {
6935 type8 = String8(resName.type8, resName.typeLen);
Kenny Root33791952010-06-08 10:16:48 -07006936 } else {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006937 type8 = String8(resName.type, resName.typeLen);
Kenny Root33791952010-06-08 10:16:48 -07006938 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006939 if (resName.name8 != NULL) {
6940 name8 = String8(resName.name8, resName.nameLen);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006941 } else {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006942 name8 = String8(resName.name, resName.nameLen);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006943 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006944 printf(" resource 0x%08x %s:%s/%s: ", resID,
6945 CHAR16_TO_CSTR(resName.package, resName.packageLen),
6946 type8.string(), name8.string());
6947 } else {
6948 printf(" INVALID RESOURCE 0x%08x: ", resID);
6949 }
6950 if ((thisOffset&0x3) != 0) {
6951 printf("NON-INTEGER OFFSET: 0x%x\n", thisOffset);
6952 continue;
6953 }
6954 if ((thisOffset+sizeof(ResTable_entry)) > typeSize) {
6955 printf("OFFSET OUT OF BOUNDS: 0x%x+0x%x (size is 0x%x)\n",
6956 entriesStart, thisOffset, typeSize);
6957 continue;
6958 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006959
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006960 const ResTable_entry* ent = (const ResTable_entry*)
6961 (((const uint8_t*)type) + entriesStart + thisOffset);
6962 if (((entriesStart + thisOffset)&0x3) != 0) {
6963 printf("NON-INTEGER ResTable_entry OFFSET: 0x%x\n",
6964 (entriesStart + thisOffset));
6965 continue;
6966 }
Mark Salyzyn00adb862014-03-19 11:00:06 -07006967
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07006968 uintptr_t esize = dtohs(ent->size);
6969 if ((esize&0x3) != 0) {
6970 printf("NON-INTEGER ResTable_entry SIZE: %p\n", (void *)esize);
6971 continue;
6972 }
6973 if ((thisOffset+esize) > typeSize) {
6974 printf("ResTable_entry OUT OF BOUNDS: 0x%x+0x%x+%p (size is 0x%x)\n",
6975 entriesStart, thisOffset, (void *)esize, typeSize);
6976 continue;
6977 }
6978
6979 const Res_value* valuePtr = NULL;
6980 const ResTable_map_entry* bagPtr = NULL;
6981 Res_value value;
6982 if ((dtohs(ent->flags)&ResTable_entry::FLAG_COMPLEX) != 0) {
6983 printf("<bag>");
6984 bagPtr = (const ResTable_map_entry*)ent;
6985 } else {
6986 valuePtr = (const Res_value*)
6987 (((const uint8_t*)ent) + esize);
6988 value.copyFrom_dtoh(*valuePtr);
6989 printf("t=0x%02x d=0x%08x (s=0x%04x r=0x%02x)",
6990 (int)value.dataType, (int)value.data,
6991 (int)value.size, (int)value.res0);
6992 }
6993
6994 if ((dtohs(ent->flags)&ResTable_entry::FLAG_PUBLIC) != 0) {
6995 printf(" (PUBLIC)");
6996 }
6997 printf("\n");
6998
6999 if (inclValues) {
7000 if (valuePtr != NULL) {
7001 printf(" ");
7002 print_value(typeConfigs->package, value);
7003 } else if (bagPtr != NULL) {
7004 const int N = dtohl(bagPtr->count);
7005 const uint8_t* baseMapPtr = (const uint8_t*)ent;
7006 size_t mapOffset = esize;
7007 const ResTable_map* mapPtr = (ResTable_map*)(baseMapPtr+mapOffset);
7008 const uint32_t parent = dtohl(bagPtr->parent.ident);
7009 uint32_t resolvedParent = parent;
Adam Lesinski6022deb2014-08-20 14:59:19 -07007010 if (Res_GETPACKAGE(resolvedParent) + 1 == 0) {
7011 status_t err = pg->dynamicRefTable.lookupResourceId(&resolvedParent);
7012 if (err != NO_ERROR) {
7013 resolvedParent = 0;
7014 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07007015 }
7016 printf(" Parent=0x%08x(Resolved=0x%08x), Count=%d\n",
7017 parent, resolvedParent, N);
7018 for (int i=0; i<N && mapOffset < (typeSize-sizeof(ResTable_map)); i++) {
7019 printf(" #%i (Key=0x%08x): ",
7020 i, dtohl(mapPtr->name.ident));
7021 value.copyFrom_dtoh(mapPtr->value);
7022 print_value(typeConfigs->package, value);
7023 const size_t size = dtohs(mapPtr->value.size);
7024 mapOffset += size + sizeof(*mapPtr)-sizeof(mapPtr->value);
7025 mapPtr = (ResTable_map*)(baseMapPtr+mapOffset);
Dianne Hackborne17086b2009-06-19 15:13:28 -07007026 }
7027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007028 }
7029 }
7030 }
7031 }
7032 }
7033}
7034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007035} // namespace android