1 /*
2 * Copyright (C) 2005 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 //
18 // Definitions of resource data structures.
19 //
20 #ifndef _LIBS_UTILS_RESOURCE_TYPES_H
21 #define _LIBS_UTILS_RESOURCE_TYPES_H
22
23 #include <android-base/expected.h>
24 #include <android-base/unique_fd.h>
25
26 #include <androidfw/Asset.h>
27 #include <androidfw/Errors.h>
28 #include <androidfw/LocaleData.h>
29 #include <androidfw/StringPiece.h>
30 #include <utils/ByteOrder.h>
31 #include <utils/Errors.h>
32 #include <utils/String16.h>
33 #include <utils/Vector.h>
34 #include <utils/KeyedVector.h>
35
36 #include <utils/threads.h>
37
38 #include <stdint.h>
39 #include <sys/types.h>
40
41 #include <android/configuration.h>
42
43 #include <array>
44 #include <map>
45 #include <memory>
46
47 namespace android {
48
49 constexpr const uint32_t kIdmapMagic = 0x504D4449u;
50 constexpr const uint32_t kIdmapCurrentVersion = 0x00000009u;
51
52 // This must never change.
53 constexpr const uint32_t kFabricatedOverlayMagic = 0x4f525246; // FRRO (big endian)
54
55 // The version should only be changed when a backwards-incompatible change must be made to the
56 // fabricated overlay file format. Old fabricated overlays must be migrated to the new file format
57 // to prevent losing fabricated overlay data.
58 constexpr const uint32_t kFabricatedOverlayCurrentVersion = 3;
59
60 // Returns whether or not the path represents a fabricated overlay.
61 bool IsFabricatedOverlay(const std::string& path);
62 bool IsFabricatedOverlay(const char* path);
63 bool IsFabricatedOverlay(android::base::borrowed_fd fd);
64
65 /**
66 * In C++11, char16_t is defined as *at least* 16 bits. We do a lot of
67 * casting on raw data and expect char16_t to be exactly 16 bits.
68 */
69 #if __cplusplus >= 201103L
70 struct __assertChar16Size {
71 static_assert(sizeof(char16_t) == sizeof(uint16_t), "char16_t is not 16 bits");
72 static_assert(alignof(char16_t) == alignof(uint16_t), "char16_t is not 16-bit aligned");
73 };
74 #endif
75
76 /** ********************************************************************
77 * PNG Extensions
78 *
79 * New private chunks that may be placed in PNG images.
80 *
81 *********************************************************************** */
82
83 /**
84 * This chunk specifies how to split an image into segments for
85 * scaling.
86 *
87 * There are J horizontal and K vertical segments. These segments divide
88 * the image into J*K regions as follows (where J=4 and K=3):
89 *
90 * F0 S0 F1 S1
91 * +-----+----+------+-------+
92 * S2| 0 | 1 | 2 | 3 |
93 * +-----+----+------+-------+
94 * | | | | |
95 * | | | | |
96 * F2| 4 | 5 | 6 | 7 |
97 * | | | | |
98 * | | | | |
99 * +-----+----+------+-------+
100 * S3| 8 | 9 | 10 | 11 |
101 * +-----+----+------+-------+
102 *
103 * Each horizontal and vertical segment is considered to by either
104 * stretchable (marked by the Sx labels) or fixed (marked by the Fy
105 * labels), in the horizontal or vertical axis, respectively. In the
106 * above example, the first is horizontal segment (F0) is fixed, the
107 * next is stretchable and then they continue to alternate. Note that
108 * the segment list for each axis can begin or end with a stretchable
109 * or fixed segment.
110 *
111 * The relative sizes of the stretchy segments indicates the relative
112 * amount of stretchiness of the regions bordered by the segments. For
113 * example, regions 3, 7 and 11 above will take up more horizontal space
114 * than regions 1, 5 and 9 since the horizontal segment associated with
115 * the first set of regions is larger than the other set of regions. The
116 * ratios of the amount of horizontal (or vertical) space taken by any
117 * two stretchable slices is exactly the ratio of their corresponding
118 * segment lengths.
119 *
120 * xDivs and yDivs are arrays of horizontal and vertical pixel
121 * indices. The first pair of Divs (in either array) indicate the
122 * starting and ending points of the first stretchable segment in that
123 * axis. The next pair specifies the next stretchable segment, etc. So
124 * in the above example xDiv[0] and xDiv[1] specify the horizontal
125 * coordinates for the regions labeled 1, 5 and 9. xDiv[2] and
126 * xDiv[3] specify the coordinates for regions 3, 7 and 11. Note that
127 * the leftmost slices always start at x=0 and the rightmost slices
128 * always end at the end of the image. So, for example, the regions 0,
129 * 4 and 8 (which are fixed along the X axis) start at x value 0 and
130 * go to xDiv[0] and slices 2, 6 and 10 start at xDiv[1] and end at
131 * xDiv[2].
132 *
133 * The colors array contains hints for each of the regions. They are
134 * ordered according left-to-right and top-to-bottom as indicated above.
135 * For each segment that is a solid color the array entry will contain
136 * that color value; otherwise it will contain NO_COLOR. Segments that
137 * are completely transparent will always have the value TRANSPARENT_COLOR.
138 *
139 * The PNG chunk type is "npTc".
140 */
141 struct alignas(uintptr_t) Res_png_9patch
142 {
Res_png_9patchRes_png_9patch143 Res_png_9patch() : wasDeserialized(false), xDivsOffset(0),
144 yDivsOffset(0), colorsOffset(0) { }
145
146 int8_t wasDeserialized;
147 uint8_t numXDivs;
148 uint8_t numYDivs;
149 uint8_t numColors;
150
151 // The offset (from the start of this structure) to the xDivs & yDivs
152 // array for this 9patch. To get a pointer to this array, call
153 // getXDivs or getYDivs. Note that the serialized form for 9patches places
154 // the xDivs, yDivs and colors arrays immediately after the location
155 // of the Res_png_9patch struct.
156 uint32_t xDivsOffset;
157 uint32_t yDivsOffset;
158
159 int32_t paddingLeft, paddingRight;
160 int32_t paddingTop, paddingBottom;
161
162 enum {
163 // The 9 patch segment is not a solid color.
164 NO_COLOR = 0x00000001,
165
166 // The 9 patch segment is completely transparent.
167 TRANSPARENT_COLOR = 0x00000000
168 };
169
170 // The offset (from the start of this structure) to the colors array
171 // for this 9patch.
172 uint32_t colorsOffset;
173
174 // Convert data from device representation to PNG file representation.
175 void deviceToFile();
176 // Convert data from PNG file representation to device representation.
177 void fileToDevice();
178
179 // Serialize/Marshall the patch data into a newly malloc-ed block.
180 static void* serialize(const Res_png_9patch& patchHeader, const int32_t* xDivs,
181 const int32_t* yDivs, const uint32_t* colors);
182 // Serialize/Marshall the patch data into |outData|.
183 static void serialize(const Res_png_9patch& patchHeader, const int32_t* xDivs,
184 const int32_t* yDivs, const uint32_t* colors, void* outData);
185 // Deserialize/Unmarshall the patch data
186 static Res_png_9patch* deserialize(void* data);
187 // Compute the size of the serialized data structure
188 size_t serializedSize() const;
189
190 // These tell where the next section of a patch starts.
191 // For example, the first patch includes the pixels from
192 // 0 to xDivs[0]-1 and the second patch includes the pixels
193 // from xDivs[0] to xDivs[1]-1.
getXDivsRes_png_9patch194 inline int32_t* getXDivs() const {
195 return reinterpret_cast<int32_t*>(reinterpret_cast<uintptr_t>(this) + xDivsOffset);
196 }
getYDivsRes_png_9patch197 inline int32_t* getYDivs() const {
198 return reinterpret_cast<int32_t*>(reinterpret_cast<uintptr_t>(this) + yDivsOffset);
199 }
getColorsRes_png_9patch200 inline uint32_t* getColors() const {
201 return reinterpret_cast<uint32_t*>(reinterpret_cast<uintptr_t>(this) + colorsOffset);
202 }
203
204 } __attribute__((packed));
205
206 /** ********************************************************************
207 * Base Types
208 *
209 * These are standard types that are shared between multiple specific
210 * resource types.
211 *
212 *********************************************************************** */
213
214 /**
215 * Header that appears at the front of every data chunk in a resource.
216 */
217 struct ResChunk_header
218 {
219 // Type identifier for this chunk. The meaning of this value depends
220 // on the containing chunk.
221 uint16_t type;
222
223 // Size of the chunk header (in bytes). Adding this value to
224 // the address of the chunk allows you to find its associated data
225 // (if any).
226 uint16_t headerSize;
227
228 // Total size of this chunk (in bytes). This is the chunkSize plus
229 // the size of any data associated with the chunk. Adding this value
230 // to the chunk allows you to completely skip its contents (including
231 // any child chunks). If this value is the same as chunkSize, there is
232 // no data associated with the chunk.
233 uint32_t size;
234 };
235
236 enum {
237 RES_NULL_TYPE = 0x0000,
238 RES_STRING_POOL_TYPE = 0x0001,
239 RES_TABLE_TYPE = 0x0002,
240 RES_XML_TYPE = 0x0003,
241
242 // Chunk types in RES_XML_TYPE
243 RES_XML_FIRST_CHUNK_TYPE = 0x0100,
244 RES_XML_START_NAMESPACE_TYPE = 0x0100,
245 RES_XML_END_NAMESPACE_TYPE = 0x0101,
246 RES_XML_START_ELEMENT_TYPE = 0x0102,
247 RES_XML_END_ELEMENT_TYPE = 0x0103,
248 RES_XML_CDATA_TYPE = 0x0104,
249 RES_XML_LAST_CHUNK_TYPE = 0x017f,
250 // This contains a uint32_t array mapping strings in the string
251 // pool back to resource identifiers. It is optional.
252 RES_XML_RESOURCE_MAP_TYPE = 0x0180,
253
254 // Chunk types in RES_TABLE_TYPE
255 RES_TABLE_PACKAGE_TYPE = 0x0200,
256 RES_TABLE_TYPE_TYPE = 0x0201,
257 RES_TABLE_TYPE_SPEC_TYPE = 0x0202,
258 RES_TABLE_LIBRARY_TYPE = 0x0203,
259 RES_TABLE_OVERLAYABLE_TYPE = 0x0204,
260 RES_TABLE_OVERLAYABLE_POLICY_TYPE = 0x0205,
261 RES_TABLE_STAGED_ALIAS_TYPE = 0x0206,
262 };
263
264 /**
265 * Macros for building/splitting resource identifiers.
266 */
267 #define Res_VALIDID(resid) (resid != 0)
268 #define Res_CHECKID(resid) ((resid&0xFFFF0000) != 0)
269 #define Res_MAKEID(package, type, entry) \
270 (((package+1)<<24) | (((type+1)&0xFF)<<16) | (entry&0xFFFF))
271 #define Res_GETPACKAGE(id) ((id>>24)-1)
272 #define Res_GETTYPE(id) (((id>>16)&0xFF)-1)
273 #define Res_GETENTRY(id) (id&0xFFFF)
274
275 #define Res_INTERNALID(resid) ((resid&0xFFFF0000) != 0 && (resid&0xFF0000) == 0)
276 #define Res_MAKEINTERNAL(entry) (0x01000000 | (entry&0xFFFF))
277 #define Res_MAKEARRAY(entry) (0x02000000 | (entry&0xFFFF))
278
279 static const size_t Res_MAXPACKAGE = 255;
280 static const size_t Res_MAXTYPE = 255;
281
282 /**
283 * Representation of a value in a resource, supplying type
284 * information.
285 */
286 struct Res_value
287 {
288 // Number of bytes in this structure.
289 uint16_t size;
290
291 // Always set to 0.
292 uint8_t res0;
293
294 // Type of the data value.
295 enum : uint8_t {
296 // The 'data' is either 0 or 1, specifying this resource is either
297 // undefined or empty, respectively.
298 TYPE_NULL = 0x00,
299 // The 'data' holds a ResTable_ref, a reference to another resource
300 // table entry.
301 TYPE_REFERENCE = 0x01,
302 // The 'data' holds an attribute resource identifier.
303 TYPE_ATTRIBUTE = 0x02,
304 // The 'data' holds an index into the containing resource table's
305 // global value string pool.
306 TYPE_STRING = 0x03,
307 // The 'data' holds a single-precision floating point number.
308 TYPE_FLOAT = 0x04,
309 // The 'data' holds a complex number encoding a dimension value,
310 // such as "100in".
311 TYPE_DIMENSION = 0x05,
312 // The 'data' holds a complex number encoding a fraction of a
313 // container.
314 TYPE_FRACTION = 0x06,
315 // The 'data' holds a dynamic ResTable_ref, which needs to be
316 // resolved before it can be used like a TYPE_REFERENCE.
317 TYPE_DYNAMIC_REFERENCE = 0x07,
318 // The 'data' holds an attribute resource identifier, which needs to be resolved
319 // before it can be used like a TYPE_ATTRIBUTE.
320 TYPE_DYNAMIC_ATTRIBUTE = 0x08,
321
322 // Beginning of integer flavors...
323 TYPE_FIRST_INT = 0x10,
324
325 // The 'data' is a raw integer value of the form n..n.
326 TYPE_INT_DEC = 0x10,
327 // The 'data' is a raw integer value of the form 0xn..n.
328 TYPE_INT_HEX = 0x11,
329 // The 'data' is either 0 or 1, for input "false" or "true" respectively.
330 TYPE_INT_BOOLEAN = 0x12,
331
332 // Beginning of color integer flavors...
333 TYPE_FIRST_COLOR_INT = 0x1c,
334
335 // The 'data' is a raw integer value of the form #aarrggbb.
336 TYPE_INT_COLOR_ARGB8 = 0x1c,
337 // The 'data' is a raw integer value of the form #rrggbb.
338 TYPE_INT_COLOR_RGB8 = 0x1d,
339 // The 'data' is a raw integer value of the form #argb.
340 TYPE_INT_COLOR_ARGB4 = 0x1e,
341 // The 'data' is a raw integer value of the form #rgb.
342 TYPE_INT_COLOR_RGB4 = 0x1f,
343
344 // ...end of integer flavors.
345 TYPE_LAST_COLOR_INT = 0x1f,
346
347 // ...end of integer flavors.
348 TYPE_LAST_INT = 0x1f
349 };
350 uint8_t dataType;
351
352 // Structure of complex data values (TYPE_UNIT and TYPE_FRACTION)
353 enum {
354 // Where the unit type information is. This gives us 16 possible
355 // types, as defined below.
356 COMPLEX_UNIT_SHIFT = 0,
357 COMPLEX_UNIT_MASK = 0xf,
358
359 // TYPE_DIMENSION: Value is raw pixels.
360 COMPLEX_UNIT_PX = 0,
361 // TYPE_DIMENSION: Value is Device Independent Pixels.
362 COMPLEX_UNIT_DIP = 1,
363 // TYPE_DIMENSION: Value is a Scaled device independent Pixels.
364 COMPLEX_UNIT_SP = 2,
365 // TYPE_DIMENSION: Value is in points.
366 COMPLEX_UNIT_PT = 3,
367 // TYPE_DIMENSION: Value is in inches.
368 COMPLEX_UNIT_IN = 4,
369 // TYPE_DIMENSION: Value is in millimeters.
370 COMPLEX_UNIT_MM = 5,
371
372 // TYPE_FRACTION: A basic fraction of the overall size.
373 COMPLEX_UNIT_FRACTION = 0,
374 // TYPE_FRACTION: A fraction of the parent size.
375 COMPLEX_UNIT_FRACTION_PARENT = 1,
376
377 // Where the radix information is, telling where the decimal place
378 // appears in the mantissa. This give us 4 possible fixed point
379 // representations as defined below.
380 COMPLEX_RADIX_SHIFT = 4,
381 COMPLEX_RADIX_MASK = 0x3,
382
383 // The mantissa is an integral number -- i.e., 0xnnnnnn.0
384 COMPLEX_RADIX_23p0 = 0,
385 // The mantissa magnitude is 16 bits -- i.e, 0xnnnn.nn
386 COMPLEX_RADIX_16p7 = 1,
387 // The mantissa magnitude is 8 bits -- i.e, 0xnn.nnnn
388 COMPLEX_RADIX_8p15 = 2,
389 // The mantissa magnitude is 0 bits -- i.e, 0x0.nnnnnn
390 COMPLEX_RADIX_0p23 = 3,
391
392 // Where the actual value is. This gives us 23 bits of
393 // precision. The top bit is the sign.
394 COMPLEX_MANTISSA_SHIFT = 8,
395 COMPLEX_MANTISSA_MASK = 0xffffff
396 };
397
398 // Possible data values for TYPE_NULL.
399 enum {
400 // The value is not defined.
401 DATA_NULL_UNDEFINED = 0,
402 // The value is explicitly defined as empty.
403 DATA_NULL_EMPTY = 1
404 };
405
406 // The data for this item, as interpreted according to dataType.
407 typedef uint32_t data_type;
408 data_type data;
409
410 void copyFrom_dtoh(const Res_value& src);
411 };
412
413 /**
414 * This is a reference to a unique entry (a ResTable_entry structure)
415 * in a resource table. The value is structured as: 0xpptteeee,
416 * where pp is the package index, tt is the type index in that
417 * package, and eeee is the entry index in that type. The package
418 * and type values start at 1 for the first item, to help catch cases
419 * where they have not been supplied.
420 */
421 struct ResTable_ref
422 {
423 uint32_t ident;
424 };
425
426 /**
427 * Reference to a string in a string pool.
428 */
429 struct ResStringPool_ref
430 {
431 // Index into the string pool table (uint32_t-offset from the indices
432 // immediately after ResStringPool_header) at which to find the location
433 // of the string data in the pool.
434 uint32_t index;
435 };
436
437 /** ********************************************************************
438 * String Pool
439 *
440 * A set of strings that can be references by others through a
441 * ResStringPool_ref.
442 *
443 *********************************************************************** */
444
445 /**
446 * Definition for a pool of strings. The data of this chunk is an
447 * array of uint32_t providing indices into the pool, relative to
448 * stringsStart. At stringsStart are all of the UTF-16 strings
449 * concatenated together; each starts with a uint16_t of the string's
450 * length and each ends with a 0x0000 terminator. If a string is >
451 * 32767 characters, the high bit of the length is set meaning to take
452 * those 15 bits as a high word and it will be followed by another
453 * uint16_t containing the low word.
454 *
455 * If styleCount is not zero, then immediately following the array of
456 * uint32_t indices into the string table is another array of indices
457 * into a style table starting at stylesStart. Each entry in the
458 * style table is an array of ResStringPool_span structures.
459 */
460 struct ResStringPool_header
461 {
462 struct ResChunk_header header;
463
464 // Number of strings in this pool (number of uint32_t indices that follow
465 // in the data).
466 uint32_t stringCount;
467
468 // Number of style span arrays in the pool (number of uint32_t indices
469 // follow the string indices).
470 uint32_t styleCount;
471
472 // Flags.
473 enum {
474 // If set, the string index is sorted by the string values (based
475 // on strcmp16()).
476 SORTED_FLAG = 1<<0,
477
478 // String pool is encoded in UTF-8
479 UTF8_FLAG = 1<<8
480 };
481 uint32_t flags;
482
483 // Index from header of the string data.
484 uint32_t stringsStart;
485
486 // Index from header of the style data.
487 uint32_t stylesStart;
488 };
489
490 /**
491 * This structure defines a span of style information associated with
492 * a string in the pool.
493 */
494 struct ResStringPool_span
495 {
496 enum {
497 END = 0xFFFFFFFF
498 };
499
500 // This is the name of the span -- that is, the name of the XML
501 // tag that defined it. The special value END (0xFFFFFFFF) indicates
502 // the end of an array of spans.
503 ResStringPool_ref name;
504
505 // The range of characters in the string that this span applies to.
506 uint32_t firstChar, lastChar;
507 };
508
509 /**
510 * Convenience class for accessing data in a ResStringPool resource.
511 */
512 class ResStringPool
513 {
514 public:
515 ResStringPool();
516 ResStringPool(const void* data, size_t size, bool copyData=false);
517 virtual ~ResStringPool();
518
519 void setToEmpty();
520 status_t setTo(incfs::map_ptr<void> data, size_t size, bool copyData=false);
521
522 status_t getError() const;
523
524 void uninit();
525
526 // Return string entry as UTF16; if the pool is UTF8, the string will
527 // be converted before returning.
stringAt(const ResStringPool_ref & ref)528 inline base::expected<StringPiece16, NullOrIOError> stringAt(
529 const ResStringPool_ref& ref) const {
530 return stringAt(ref.index);
531 }
532 virtual base::expected<StringPiece16, NullOrIOError> stringAt(size_t idx) const;
533
534 // Note: returns null if the string pool is not UTF8.
535 virtual base::expected<StringPiece, NullOrIOError> string8At(size_t idx) const;
536
537 // Return string whether the pool is UTF8 or UTF16. Does not allow you
538 // to distinguish null.
539 base::expected<String8, IOError> string8ObjectAt(size_t idx) const;
540
541 base::expected<incfs::map_ptr<ResStringPool_span>, NullOrIOError> styleAt(
542 const ResStringPool_ref& ref) const;
543 base::expected<incfs::map_ptr<ResStringPool_span>, NullOrIOError> styleAt(size_t idx) const;
544
545 base::expected<size_t, NullOrIOError> indexOfString(const char16_t* str, size_t strLen) const;
546
547 virtual size_t size() const;
548 size_t styleCount() const;
549 size_t bytes() const;
550 incfs::map_ptr<void> data() const;
551
552 bool isSorted() const;
553 bool isUTF8() const;
554
555 private:
556 status_t mError;
557 void* mOwnedData;
558 incfs::verified_map_ptr<ResStringPool_header> mHeader;
559 size_t mSize;
560 mutable Mutex mDecodeLock;
561 incfs::map_ptr<uint32_t> mEntries;
562 incfs::map_ptr<uint32_t> mEntryStyles;
563 incfs::map_ptr<void> mStrings;
564 char16_t mutable** mCache;
565 uint32_t mStringPoolSize; // number of uint16_t
566 incfs::map_ptr<uint32_t> mStyles;
567 uint32_t mStylePoolSize; // number of uint32_t
568
569 base::expected<StringPiece, NullOrIOError> stringDecodeAt(
570 size_t idx, incfs::map_ptr<uint8_t> str, size_t encLen) const;
571 };
572
573 /**
574 * Wrapper class that allows the caller to retrieve a string from
575 * a string pool without knowing which string pool to look.
576 */
577 class StringPoolRef {
578 public:
579 StringPoolRef() = default;
580 StringPoolRef(const ResStringPool* pool, uint32_t index);
581
582 base::expected<StringPiece, NullOrIOError> string8() const;
583 base::expected<StringPiece16, NullOrIOError> string16() const;
584
585 private:
586 const ResStringPool* mPool = nullptr;
587 uint32_t mIndex = 0u;
588 };
589
590 /** ********************************************************************
591 * XML Tree
592 *
593 * Binary representation of an XML document. This is designed to
594 * express everything in an XML document, in a form that is much
595 * easier to parse on the device.
596 *
597 *********************************************************************** */
598
599 /**
600 * XML tree header. This appears at the front of an XML tree,
601 * describing its content. It is followed by a flat array of
602 * ResXMLTree_node structures; the hierarchy of the XML document
603 * is described by the occurrance of RES_XML_START_ELEMENT_TYPE
604 * and corresponding RES_XML_END_ELEMENT_TYPE nodes in the array.
605 */
606 struct ResXMLTree_header
607 {
608 struct ResChunk_header header;
609 };
610
611 /**
612 * Basic XML tree node. A single item in the XML document. Extended info
613 * about the node can be found after header.headerSize.
614 */
615 struct ResXMLTree_node
616 {
617 struct ResChunk_header header;
618
619 // Line number in original source file at which this element appeared.
620 uint32_t lineNumber;
621
622 // Optional XML comment that was associated with this element; -1 if none.
623 struct ResStringPool_ref comment;
624 };
625
626 /**
627 * Extended XML tree node for CDATA tags -- includes the CDATA string.
628 * Appears header.headerSize bytes after a ResXMLTree_node.
629 */
630 struct ResXMLTree_cdataExt
631 {
632 // The raw CDATA character data.
633 struct ResStringPool_ref data;
634
635 // The typed value of the character data if this is a CDATA node.
636 struct Res_value typedData;
637 };
638
639 /**
640 * Extended XML tree node for namespace start/end nodes.
641 * Appears header.headerSize bytes after a ResXMLTree_node.
642 */
643 struct ResXMLTree_namespaceExt
644 {
645 // The prefix of the namespace.
646 struct ResStringPool_ref prefix;
647
648 // The URI of the namespace.
649 struct ResStringPool_ref uri;
650 };
651
652 /**
653 * Extended XML tree node for element start/end nodes.
654 * Appears header.headerSize bytes after a ResXMLTree_node.
655 */
656 struct ResXMLTree_endElementExt
657 {
658 // String of the full namespace of this element.
659 struct ResStringPool_ref ns;
660
661 // String name of this node if it is an ELEMENT; the raw
662 // character data if this is a CDATA node.
663 struct ResStringPool_ref name;
664 };
665
666 /**
667 * Extended XML tree node for start tags -- includes attribute
668 * information.
669 * Appears header.headerSize bytes after a ResXMLTree_node.
670 */
671 struct ResXMLTree_attrExt
672 {
673 // String of the full namespace of this element.
674 struct ResStringPool_ref ns;
675
676 // String name of this node if it is an ELEMENT; the raw
677 // character data if this is a CDATA node.
678 struct ResStringPool_ref name;
679
680 // Byte offset from the start of this structure where the attributes start.
681 uint16_t attributeStart;
682
683 // Size of the ResXMLTree_attribute structures that follow.
684 uint16_t attributeSize;
685
686 // Number of attributes associated with an ELEMENT. These are
687 // available as an array of ResXMLTree_attribute structures
688 // immediately following this node.
689 uint16_t attributeCount;
690
691 // Index (1-based) of the "id" attribute. 0 if none.
692 uint16_t idIndex;
693
694 // Index (1-based) of the "class" attribute. 0 if none.
695 uint16_t classIndex;
696
697 // Index (1-based) of the "style" attribute. 0 if none.
698 uint16_t styleIndex;
699 };
700
701 struct ResXMLTree_attribute
702 {
703 // Namespace of this attribute.
704 struct ResStringPool_ref ns;
705
706 // Name of this attribute.
707 struct ResStringPool_ref name;
708
709 // The original raw string value of this attribute.
710 struct ResStringPool_ref rawValue;
711
712 // Processesd typed value of this attribute.
713 struct Res_value typedValue;
714 };
715
716 class ResXMLTree;
717
718 class ResXMLParser
719 {
720 public:
721 explicit ResXMLParser(const ResXMLTree& tree);
722
723 enum event_code_t {
724 BAD_DOCUMENT = -1,
725 START_DOCUMENT = 0,
726 END_DOCUMENT = 1,
727
728 FIRST_CHUNK_CODE = RES_XML_FIRST_CHUNK_TYPE,
729
730 START_NAMESPACE = RES_XML_START_NAMESPACE_TYPE,
731 END_NAMESPACE = RES_XML_END_NAMESPACE_TYPE,
732 START_TAG = RES_XML_START_ELEMENT_TYPE,
733 END_TAG = RES_XML_END_ELEMENT_TYPE,
734 TEXT = RES_XML_CDATA_TYPE
735 };
736
737 struct ResXMLPosition
738 {
739 event_code_t eventCode;
740 const ResXMLTree_node* curNode;
741 const void* curExt;
742 };
743
744 void restart();
745
746 const ResStringPool& getStrings() const;
747
748 event_code_t getEventType() const;
749 // Note, unlike XmlPullParser, the first call to next() will return
750 // START_TAG of the first element.
751 event_code_t next();
752
753 // These are available for all nodes:
754 int32_t getCommentID() const;
755 const char16_t* getComment(size_t* outLen) const;
756 uint32_t getLineNumber() const;
757
758 // This is available for TEXT:
759 int32_t getTextID() const;
760 const char16_t* getText(size_t* outLen) const;
761 ssize_t getTextValue(Res_value* outValue) const;
762
763 // These are available for START_NAMESPACE and END_NAMESPACE:
764 int32_t getNamespacePrefixID() const;
765 const char16_t* getNamespacePrefix(size_t* outLen) const;
766 int32_t getNamespaceUriID() const;
767 const char16_t* getNamespaceUri(size_t* outLen) const;
768
769 // These are available for START_TAG and END_TAG:
770 int32_t getElementNamespaceID() const;
771 const char16_t* getElementNamespace(size_t* outLen) const;
772 int32_t getElementNameID() const;
773 const char16_t* getElementName(size_t* outLen) const;
774
775 // Remaining methods are for retrieving information about attributes
776 // associated with a START_TAG:
777
778 size_t getAttributeCount() const;
779
780 // Returns -1 if no namespace, -2 if idx out of range.
781 int32_t getAttributeNamespaceID(size_t idx) const;
782 const char16_t* getAttributeNamespace(size_t idx, size_t* outLen) const;
783
784 int32_t getAttributeNameID(size_t idx) const;
785 const char16_t* getAttributeName(size_t idx, size_t* outLen) const;
786 uint32_t getAttributeNameResID(size_t idx) const;
787
788 // These will work only if the underlying string pool is UTF-8.
789 const char* getAttributeNamespace8(size_t idx, size_t* outLen) const;
790 const char* getAttributeName8(size_t idx, size_t* outLen) const;
791
792 int32_t getAttributeValueStringID(size_t idx) const;
793 const char16_t* getAttributeStringValue(size_t idx, size_t* outLen) const;
794
795 int32_t getAttributeDataType(size_t idx) const;
796 int32_t getAttributeData(size_t idx) const;
797 ssize_t getAttributeValue(size_t idx, Res_value* outValue) const;
798
799 ssize_t indexOfAttribute(const char* ns, const char* attr) const;
800 ssize_t indexOfAttribute(const char16_t* ns, size_t nsLen,
801 const char16_t* attr, size_t attrLen) const;
802
803 ssize_t indexOfID() const;
804 ssize_t indexOfClass() const;
805 ssize_t indexOfStyle() const;
806
807 void getPosition(ResXMLPosition* pos) const;
808 void setPosition(const ResXMLPosition& pos);
809
810 void setSourceResourceId(const uint32_t resId);
811 uint32_t getSourceResourceId() const;
812
813 private:
814 friend class ResXMLTree;
815
816 event_code_t nextNode();
817
818 const ResXMLTree& mTree;
819 event_code_t mEventCode;
820 const ResXMLTree_node* mCurNode;
821 const void* mCurExt;
822 uint32_t mSourceResourceId;
823 };
824
825 static inline bool operator==(const android::ResXMLParser::ResXMLPosition& lhs,
826 const android::ResXMLParser::ResXMLPosition& rhs) {
827 return lhs.curNode == rhs.curNode;
828 }
829
830 class DynamicRefTable;
831
832 /**
833 * Convenience class for accessing data in a ResXMLTree resource.
834 */
835 class ResXMLTree : public ResXMLParser
836 {
837 public:
838 /**
839 * Creates a ResXMLTree with the specified DynamicRefTable for run-time package id translation.
840 * The tree stores a clone of the specified DynamicRefTable, so any changes to the original
841 * DynamicRefTable will not affect this tree after instantiation.
842 **/
843 explicit ResXMLTree(std::shared_ptr<const DynamicRefTable> dynamicRefTable);
844 ResXMLTree();
845 ~ResXMLTree();
846
847 status_t setTo(const void* data, size_t size, bool copyData=false);
848
849 status_t getError() const;
850
851 void uninit();
852
853 private:
854 friend class ResXMLParser;
855
856 status_t validateNode(const ResXMLTree_node* node) const;
857
858 std::shared_ptr<const DynamicRefTable> mDynamicRefTable;
859
860 status_t mError;
861 void* mOwnedData;
862 const ResXMLTree_header* mHeader;
863 size_t mSize;
864 const uint8_t* mDataEnd;
865 ResStringPool mStrings;
866 const uint32_t* mResIds;
867 size_t mNumResIds;
868 const ResXMLTree_node* mRootNode;
869 const void* mRootExt;
870 event_code_t mRootCode;
871 };
872
873 /** ********************************************************************
874 * RESOURCE TABLE
875 *
876 *********************************************************************** */
877
878 /**
879 * Header for a resource table. Its data contains a series of
880 * additional chunks:
881 * * A ResStringPool_header containing all table values. This string pool
882 * contains all of the string values in the entire resource table (not
883 * the names of entries or type identifiers however).
884 * * One or more ResTable_package chunks.
885 *
886 * Specific entries within a resource table can be uniquely identified
887 * with a single integer as defined by the ResTable_ref structure.
888 */
889 struct ResTable_header
890 {
891 struct ResChunk_header header;
892
893 // The number of ResTable_package structures.
894 uint32_t packageCount;
895 };
896
897 /**
898 * A collection of resource data types within a package. Followed by
899 * one or more ResTable_type and ResTable_typeSpec structures containing the
900 * entry values for each resource type.
901 */
902 struct ResTable_package
903 {
904 struct ResChunk_header header;
905
906 // If this is a base package, its ID. Package IDs start
907 // at 1 (corresponding to the value of the package bits in a
908 // resource identifier). 0 means this is not a base package.
909 uint32_t id;
910
911 // Actual name of this package, \0-terminated.
912 uint16_t name[128];
913
914 // Offset to a ResStringPool_header defining the resource
915 // type symbol table. If zero, this package is inheriting from
916 // another base package (overriding specific values in it).
917 uint32_t typeStrings;
918
919 // Last index into typeStrings that is for public use by others.
920 uint32_t lastPublicType;
921
922 // Offset to a ResStringPool_header defining the resource
923 // key symbol table. If zero, this package is inheriting from
924 // another base package (overriding specific values in it).
925 uint32_t keyStrings;
926
927 // Last index into keyStrings that is for public use by others.
928 uint32_t lastPublicKey;
929
930 uint32_t typeIdOffset;
931 };
932
933 // The most specific locale can consist of:
934 //
935 // - a 3 char language code
936 // - a 3 char region code prefixed by a 'r'
937 // - a 4 char script code prefixed by a 's'
938 // - a 8 char variant code prefixed by a 'v'
939 //
940 // each separated by a single char separator, which sums up to a total of 24
941 // chars, (25 include the string terminator). Numbering system specificator,
942 // if present, can add up to 14 bytes (-u-nu-xxxxxxxx), giving 39 bytes,
943 // or 40 bytes to make it 4 bytes aligned.
944 #define RESTABLE_MAX_LOCALE_LEN 40
945
946
947 /**
948 * Describes a particular resource configuration.
949 */
950 struct ResTable_config
951 {
952 // Number of bytes in this structure.
953 uint32_t size;
954
955 union {
956 struct {
957 // Mobile country code (from SIM). 0 means "any".
958 uint16_t mcc;
959 // Mobile network code (from SIM). 0 means "any".
960 uint16_t mnc;
961 };
962 uint32_t imsi;
963 };
964
965 union {
966 struct {
967 // This field can take three different forms:
968 // - \0\0 means "any".
969 //
970 // - Two 7 bit ascii values interpreted as ISO-639-1 language
971 // codes ('fr', 'en' etc. etc.). The high bit for both bytes is
972 // zero.
973 //
974 // - A single 16 bit little endian packed value representing an
975 // ISO-639-2 3 letter language code. This will be of the form:
976 //
977 // {1, t, t, t, t, t, s, s, s, s, s, f, f, f, f, f}
978 //
979 // bit[0, 4] = first letter of the language code
980 // bit[5, 9] = second letter of the language code
981 // bit[10, 14] = third letter of the language code.
982 // bit[15] = 1 always
983 //
984 // For backwards compatibility, languages that have unambiguous
985 // two letter codes are represented in that format.
986 //
987 // The layout is always bigendian irrespective of the runtime
988 // architecture.
989 char language[2];
990
991 // This field can take three different forms:
992 // - \0\0 means "any".
993 //
994 // - Two 7 bit ascii values interpreted as 2 letter region
995 // codes ('US', 'GB' etc.). The high bit for both bytes is zero.
996 //
997 // - An UN M.49 3 digit region code. For simplicity, these are packed
998 // in the same manner as the language codes, though we should need
999 // only 10 bits to represent them, instead of the 15.
1000 //
1001 // The layout is always bigendian irrespective of the runtime
1002 // architecture.
1003 char country[2];
1004 };
1005 uint32_t locale;
1006 };
1007
1008 enum {
1009 ORIENTATION_ANY = ACONFIGURATION_ORIENTATION_ANY,
1010 ORIENTATION_PORT = ACONFIGURATION_ORIENTATION_PORT,
1011 ORIENTATION_LAND = ACONFIGURATION_ORIENTATION_LAND,
1012 ORIENTATION_SQUARE = ACONFIGURATION_ORIENTATION_SQUARE,
1013 };
1014
1015 enum {
1016 TOUCHSCREEN_ANY = ACONFIGURATION_TOUCHSCREEN_ANY,
1017 TOUCHSCREEN_NOTOUCH = ACONFIGURATION_TOUCHSCREEN_NOTOUCH,
1018 TOUCHSCREEN_STYLUS = ACONFIGURATION_TOUCHSCREEN_STYLUS,
1019 TOUCHSCREEN_FINGER = ACONFIGURATION_TOUCHSCREEN_FINGER,
1020 };
1021
1022 enum {
1023 DENSITY_DEFAULT = ACONFIGURATION_DENSITY_DEFAULT,
1024 DENSITY_LOW = ACONFIGURATION_DENSITY_LOW,
1025 DENSITY_MEDIUM = ACONFIGURATION_DENSITY_MEDIUM,
1026 DENSITY_TV = ACONFIGURATION_DENSITY_TV,
1027 DENSITY_HIGH = ACONFIGURATION_DENSITY_HIGH,
1028 DENSITY_XHIGH = ACONFIGURATION_DENSITY_XHIGH,
1029 DENSITY_XXHIGH = ACONFIGURATION_DENSITY_XXHIGH,
1030 DENSITY_XXXHIGH = ACONFIGURATION_DENSITY_XXXHIGH,
1031 DENSITY_ANY = ACONFIGURATION_DENSITY_ANY,
1032 DENSITY_NONE = ACONFIGURATION_DENSITY_NONE
1033 };
1034
1035 union {
1036 struct {
1037 uint8_t orientation;
1038 uint8_t touchscreen;
1039 uint16_t density;
1040 };
1041 uint32_t screenType;
1042 };
1043
1044 enum {
1045 KEYBOARD_ANY = ACONFIGURATION_KEYBOARD_ANY,
1046 KEYBOARD_NOKEYS = ACONFIGURATION_KEYBOARD_NOKEYS,
1047 KEYBOARD_QWERTY = ACONFIGURATION_KEYBOARD_QWERTY,
1048 KEYBOARD_12KEY = ACONFIGURATION_KEYBOARD_12KEY,
1049 };
1050
1051 enum {
1052 NAVIGATION_ANY = ACONFIGURATION_NAVIGATION_ANY,
1053 NAVIGATION_NONAV = ACONFIGURATION_NAVIGATION_NONAV,
1054 NAVIGATION_DPAD = ACONFIGURATION_NAVIGATION_DPAD,
1055 NAVIGATION_TRACKBALL = ACONFIGURATION_NAVIGATION_TRACKBALL,
1056 NAVIGATION_WHEEL = ACONFIGURATION_NAVIGATION_WHEEL,
1057 };
1058
1059 enum {
1060 MASK_KEYSHIDDEN = 0x0003,
1061 KEYSHIDDEN_ANY = ACONFIGURATION_KEYSHIDDEN_ANY,
1062 KEYSHIDDEN_NO = ACONFIGURATION_KEYSHIDDEN_NO,
1063 KEYSHIDDEN_YES = ACONFIGURATION_KEYSHIDDEN_YES,
1064 KEYSHIDDEN_SOFT = ACONFIGURATION_KEYSHIDDEN_SOFT,
1065 };
1066
1067 enum {
1068 MASK_NAVHIDDEN = 0x000c,
1069 SHIFT_NAVHIDDEN = 2,
1070 NAVHIDDEN_ANY = ACONFIGURATION_NAVHIDDEN_ANY << SHIFT_NAVHIDDEN,
1071 NAVHIDDEN_NO = ACONFIGURATION_NAVHIDDEN_NO << SHIFT_NAVHIDDEN,
1072 NAVHIDDEN_YES = ACONFIGURATION_NAVHIDDEN_YES << SHIFT_NAVHIDDEN,
1073 };
1074
1075 enum {
1076 GRAMMATICAL_GENDER_ANY = ACONFIGURATION_GRAMMATICAL_GENDER_ANY,
1077 GRAMMATICAL_GENDER_NEUTER = ACONFIGURATION_GRAMMATICAL_GENDER_NEUTER,
1078 GRAMMATICAL_GENDER_FEMININE = ACONFIGURATION_GRAMMATICAL_GENDER_FEMININE,
1079 GRAMMATICAL_GENDER_MASCULINE = ACONFIGURATION_GRAMMATICAL_GENDER_MASCULINE,
1080 GRAMMATICAL_INFLECTION_GENDER_MASK = 0b11,
1081 };
1082
1083 struct {
1084 union {
1085 struct {
1086 uint8_t keyboard;
1087 uint8_t navigation;
1088 uint8_t inputFlags;
1089 uint8_t inputFieldPad0;
1090 };
1091 struct {
1092 uint32_t input : 24;
1093 uint32_t inputFullPad0 : 8;
1094 };
1095 struct {
1096 uint8_t grammaticalInflectionPad0[3];
1097 uint8_t grammaticalInflection;
1098 };
1099 };
1100 };
1101
1102 enum {
1103 SCREENWIDTH_ANY = 0
1104 };
1105
1106 enum {
1107 SCREENHEIGHT_ANY = 0
1108 };
1109
1110 union {
1111 struct {
1112 uint16_t screenWidth;
1113 uint16_t screenHeight;
1114 };
1115 uint32_t screenSize;
1116 };
1117
1118 enum {
1119 SDKVERSION_ANY = 0
1120 };
1121
1122 enum {
1123 MINORVERSION_ANY = 0
1124 };
1125
1126 union {
1127 struct {
1128 uint16_t sdkVersion;
1129 // For now minorVersion must always be 0!!! Its meaning
1130 // is currently undefined.
1131 uint16_t minorVersion;
1132 };
1133 uint32_t version;
1134 };
1135
1136 enum {
1137 // screenLayout bits for screen size class.
1138 MASK_SCREENSIZE = 0x0f,
1139 SCREENSIZE_ANY = ACONFIGURATION_SCREENSIZE_ANY,
1140 SCREENSIZE_SMALL = ACONFIGURATION_SCREENSIZE_SMALL,
1141 SCREENSIZE_NORMAL = ACONFIGURATION_SCREENSIZE_NORMAL,
1142 SCREENSIZE_LARGE = ACONFIGURATION_SCREENSIZE_LARGE,
1143 SCREENSIZE_XLARGE = ACONFIGURATION_SCREENSIZE_XLARGE,
1144
1145 // screenLayout bits for wide/long screen variation.
1146 MASK_SCREENLONG = 0x30,
1147 SHIFT_SCREENLONG = 4,
1148 SCREENLONG_ANY = ACONFIGURATION_SCREENLONG_ANY << SHIFT_SCREENLONG,
1149 SCREENLONG_NO = ACONFIGURATION_SCREENLONG_NO << SHIFT_SCREENLONG,
1150 SCREENLONG_YES = ACONFIGURATION_SCREENLONG_YES << SHIFT_SCREENLONG,
1151
1152 // screenLayout bits for layout direction.
1153 MASK_LAYOUTDIR = 0xC0,
1154 SHIFT_LAYOUTDIR = 6,
1155 LAYOUTDIR_ANY = ACONFIGURATION_LAYOUTDIR_ANY << SHIFT_LAYOUTDIR,
1156 LAYOUTDIR_LTR = ACONFIGURATION_LAYOUTDIR_LTR << SHIFT_LAYOUTDIR,
1157 LAYOUTDIR_RTL = ACONFIGURATION_LAYOUTDIR_RTL << SHIFT_LAYOUTDIR,
1158 };
1159
1160 enum {
1161 // uiMode bits for the mode type.
1162 MASK_UI_MODE_TYPE = 0x0f,
1163 UI_MODE_TYPE_ANY = ACONFIGURATION_UI_MODE_TYPE_ANY,
1164 UI_MODE_TYPE_NORMAL = ACONFIGURATION_UI_MODE_TYPE_NORMAL,
1165 UI_MODE_TYPE_DESK = ACONFIGURATION_UI_MODE_TYPE_DESK,
1166 UI_MODE_TYPE_CAR = ACONFIGURATION_UI_MODE_TYPE_CAR,
1167 UI_MODE_TYPE_TELEVISION = ACONFIGURATION_UI_MODE_TYPE_TELEVISION,
1168 UI_MODE_TYPE_APPLIANCE = ACONFIGURATION_UI_MODE_TYPE_APPLIANCE,
1169 UI_MODE_TYPE_WATCH = ACONFIGURATION_UI_MODE_TYPE_WATCH,
1170 UI_MODE_TYPE_VR_HEADSET = ACONFIGURATION_UI_MODE_TYPE_VR_HEADSET,
1171
1172 // uiMode bits for the night switch.
1173 MASK_UI_MODE_NIGHT = 0x30,
1174 SHIFT_UI_MODE_NIGHT = 4,
1175 UI_MODE_NIGHT_ANY = ACONFIGURATION_UI_MODE_NIGHT_ANY << SHIFT_UI_MODE_NIGHT,
1176 UI_MODE_NIGHT_NO = ACONFIGURATION_UI_MODE_NIGHT_NO << SHIFT_UI_MODE_NIGHT,
1177 UI_MODE_NIGHT_YES = ACONFIGURATION_UI_MODE_NIGHT_YES << SHIFT_UI_MODE_NIGHT,
1178 };
1179
1180 union {
1181 struct {
1182 uint8_t screenLayout;
1183 uint8_t uiMode;
1184 uint16_t smallestScreenWidthDp;
1185 };
1186 uint32_t screenConfig;
1187 };
1188
1189 union {
1190 struct {
1191 uint16_t screenWidthDp;
1192 uint16_t screenHeightDp;
1193 };
1194 uint32_t screenSizeDp;
1195 };
1196
1197 // The ISO-15924 short name for the script corresponding to this
1198 // configuration. (eg. Hant, Latn, etc.). Interpreted in conjunction with
1199 // the locale field.
1200 char localeScript[4];
1201
1202 // A single BCP-47 variant subtag. Will vary in length between 4 and 8
1203 // chars. Interpreted in conjunction with the locale field.
1204 char localeVariant[8];
1205
1206 enum {
1207 // screenLayout2 bits for round/notround.
1208 MASK_SCREENROUND = 0x03,
1209 SCREENROUND_ANY = ACONFIGURATION_SCREENROUND_ANY,
1210 SCREENROUND_NO = ACONFIGURATION_SCREENROUND_NO,
1211 SCREENROUND_YES = ACONFIGURATION_SCREENROUND_YES,
1212 };
1213
1214 enum {
1215 // colorMode bits for wide-color gamut/narrow-color gamut.
1216 MASK_WIDE_COLOR_GAMUT = 0x03,
1217 WIDE_COLOR_GAMUT_ANY = ACONFIGURATION_WIDE_COLOR_GAMUT_ANY,
1218 WIDE_COLOR_GAMUT_NO = ACONFIGURATION_WIDE_COLOR_GAMUT_NO,
1219 WIDE_COLOR_GAMUT_YES = ACONFIGURATION_WIDE_COLOR_GAMUT_YES,
1220
1221 // colorMode bits for HDR/LDR.
1222 MASK_HDR = 0x0c,
1223 SHIFT_COLOR_MODE_HDR = 2,
1224 HDR_ANY = ACONFIGURATION_HDR_ANY << SHIFT_COLOR_MODE_HDR,
1225 HDR_NO = ACONFIGURATION_HDR_NO << SHIFT_COLOR_MODE_HDR,
1226 HDR_YES = ACONFIGURATION_HDR_YES << SHIFT_COLOR_MODE_HDR,
1227 };
1228
1229 // An extension of screenConfig.
1230 union {
1231 struct {
1232 uint8_t screenLayout2; // Contains round/notround qualifier.
1233 uint8_t colorMode; // Wide-gamut, HDR, etc.
1234 uint16_t screenConfigPad2; // Reserved padding.
1235 };
1236 uint32_t screenConfig2;
1237 };
1238
1239 // If false and localeScript is set, it means that the script of the locale
1240 // was explicitly provided.
1241 //
1242 // If true, it means that localeScript was automatically computed.
1243 // localeScript may still not be set in this case, which means that we
1244 // tried but could not compute a script.
1245 bool localeScriptWasComputed;
1246
1247 // The value of BCP 47 Unicode extension for key 'nu' (numbering system).
1248 // Varies in length from 3 to 8 chars. Zero-filled value.
1249 char localeNumberingSystem[8];
1250
1251 void copyFromDeviceNoSwap(const ResTable_config& o);
1252
1253 void copyFromDtoH(const ResTable_config& o);
1254
1255 void swapHtoD();
1256
1257 int compare(const ResTable_config& o) const;
1258 int compareLogical(const ResTable_config& o) const;
1259
1260 inline bool operator<(const ResTable_config& o) const { return compare(o) < 0; }
1261
1262 // Flags indicating a set of config values. These flag constants must
1263 // match the corresponding ones in android.content.pm.ActivityInfo and
1264 // attrs_manifest.xml.
1265 enum {
1266 CONFIG_MCC = ACONFIGURATION_MCC,
1267 CONFIG_MNC = ACONFIGURATION_MNC,
1268 CONFIG_LOCALE = ACONFIGURATION_LOCALE,
1269 CONFIG_TOUCHSCREEN = ACONFIGURATION_TOUCHSCREEN,
1270 CONFIG_KEYBOARD = ACONFIGURATION_KEYBOARD,
1271 CONFIG_KEYBOARD_HIDDEN = ACONFIGURATION_KEYBOARD_HIDDEN,
1272 CONFIG_NAVIGATION = ACONFIGURATION_NAVIGATION,
1273 CONFIG_ORIENTATION = ACONFIGURATION_ORIENTATION,
1274 CONFIG_DENSITY = ACONFIGURATION_DENSITY,
1275 CONFIG_SCREEN_SIZE = ACONFIGURATION_SCREEN_SIZE,
1276 CONFIG_SMALLEST_SCREEN_SIZE = ACONFIGURATION_SMALLEST_SCREEN_SIZE,
1277 CONFIG_VERSION = ACONFIGURATION_VERSION,
1278 CONFIG_SCREEN_LAYOUT = ACONFIGURATION_SCREEN_LAYOUT,
1279 CONFIG_UI_MODE = ACONFIGURATION_UI_MODE,
1280 CONFIG_LAYOUTDIR = ACONFIGURATION_LAYOUTDIR,
1281 CONFIG_SCREEN_ROUND = ACONFIGURATION_SCREEN_ROUND,
1282 CONFIG_COLOR_MODE = ACONFIGURATION_COLOR_MODE,
1283 CONFIG_GRAMMATICAL_GENDER = ACONFIGURATION_GRAMMATICAL_GENDER,
1284 };
1285
1286 // Compare two configuration, returning CONFIG_* flags set for each value
1287 // that is different.
1288 int diff(const ResTable_config& o) const;
1289
1290 // Return true if 'this' is more specific than 'o'.
1291 bool isMoreSpecificThan(const ResTable_config& o) const;
1292
1293 // Return true if 'this' is a better match than 'o' for the 'requested'
1294 // configuration. This assumes that match() has already been used to
1295 // remove any configurations that don't match the requested configuration
1296 // at all; if they are not first filtered, non-matching results can be
1297 // considered better than matching ones.
1298 // The general rule per attribute: if the request cares about an attribute
1299 // (it normally does), if the two (this and o) are equal it's a tie. If
1300 // they are not equal then one must be generic because only generic and
1301 // '==requested' will pass the match() call. So if this is not generic,
1302 // it wins. If this IS generic, o wins (return false).
1303 bool isBetterThan(const ResTable_config& o, const ResTable_config* requested) const;
1304
1305 // Return true if 'this' can be considered a match for the parameters in
1306 // 'settings'.
1307 // Note this is asymetric. A default piece of data will match every request
1308 // but a request for the default should not match odd specifics
1309 // (ie, request with no mcc should not match a particular mcc's data)
1310 // settings is the requested settings
1311 bool match(const ResTable_config& settings) const;
1312
1313 // Get the string representation of the locale component of this
1314 // Config. The maximum size of this representation will be
1315 // |RESTABLE_MAX_LOCALE_LEN| (including a terminating '\0').
1316 //
1317 // Example: en-US, en-Latn-US, en-POSIX.
1318 //
1319 // If canonicalize is set, Tagalog (tl) locales get converted
1320 // to Filipino (fil).
1321 void getBcp47Locale(char* out, bool canonicalize=false) const;
1322
1323 // Append to str the resource-qualifer string representation of the
1324 // locale component of this Config. If the locale is only country
1325 // and language, it will look like en-rUS. If it has scripts and
1326 // variants, it will be a modified bcp47 tag: b+en+Latn+US.
1327 void appendDirLocale(String8& str) const;
1328
1329 // Sets the values of language, region, script, variant and numbering
1330 // system to the well formed BCP 47 locale contained in |in|.
1331 // The input locale is assumed to be valid and no validation is performed.
1332 void setBcp47Locale(const char* in);
1333
clearLocaleResTable_config1334 inline void clearLocale() {
1335 locale = 0;
1336 localeScriptWasComputed = false;
1337 memset(localeScript, 0, sizeof(localeScript));
1338 memset(localeVariant, 0, sizeof(localeVariant));
1339 memset(localeNumberingSystem, 0, sizeof(localeNumberingSystem));
1340 }
1341
computeScriptResTable_config1342 inline void computeScript() {
1343 localeDataComputeScript(localeScript, language, country);
1344 }
1345
1346 // Get the 2 or 3 letter language code of this configuration. Trailing
1347 // bytes are set to '\0'.
1348 size_t unpackLanguage(char language[4]) const;
1349 // Get the 2 or 3 letter language code of this configuration. Trailing
1350 // bytes are set to '\0'.
1351 size_t unpackRegion(char region[4]) const;
1352
1353 // Sets the language code of this configuration to the first three
1354 // chars at |language|.
1355 //
1356 // If |language| is a 2 letter code, the trailing byte must be '\0' or
1357 // the BCP-47 separator '-'.
1358 void packLanguage(const char* language);
1359 // Sets the region code of this configuration to the first three bytes
1360 // at |region|. If |region| is a 2 letter code, the trailing byte must be '\0'
1361 // or the BCP-47 separator '-'.
1362 void packRegion(const char* region);
1363
1364 // Returns a positive integer if this config is more specific than |o|
1365 // with respect to their locales, a negative integer if |o| is more specific
1366 // and 0 if they're equally specific.
1367 int isLocaleMoreSpecificThan(const ResTable_config &o) const;
1368
1369 // Returns an integer representng the imporance score of the configuration locale.
1370 int getImportanceScoreOfLocale() const;
1371
1372 // Return true if 'this' is a better locale match than 'o' for the
1373 // 'requested' configuration. Similar to isBetterThan(), this assumes that
1374 // match() has already been used to remove any configurations that don't
1375 // match the requested configuration at all.
1376 bool isLocaleBetterThan(const ResTable_config& o, const ResTable_config* requested) const;
1377
1378 String8 toString() const;
1379 };
1380
1381 /**
1382 * A specification of the resources defined by a particular type.
1383 *
1384 * There should be one of these chunks for each resource type.
1385 *
1386 * This structure is followed by an array of integers providing the set of
1387 * configuration change flags (ResTable_config::CONFIG_*) that have multiple
1388 * resources for that configuration. In addition, the high bit is set if that
1389 * resource has been made public.
1390 */
1391 struct ResTable_typeSpec
1392 {
1393 struct ResChunk_header header;
1394
1395 // The type identifier this chunk is holding. Type IDs start
1396 // at 1 (corresponding to the value of the type bits in a
1397 // resource identifier). 0 is invalid.
1398 uint8_t id;
1399
1400 // Must be 0.
1401 uint8_t res0;
1402 // Must be 0.
1403 uint16_t res1;
1404
1405 // Number of uint32_t entry configuration masks that follow.
1406 uint32_t entryCount;
1407
1408 enum : uint32_t {
1409 // Additional flag indicating an entry is public.
1410 SPEC_PUBLIC = 0x40000000u,
1411
1412 // Additional flag indicating the resource id for this resource may change in a future
1413 // build. If this flag is set, the SPEC_PUBLIC flag is also set since the resource must be
1414 // public to be exposed as an API to other applications.
1415 SPEC_STAGED_API = 0x20000000u,
1416 };
1417 };
1418
1419 /**
1420 * A collection of resource entries for a particular resource data
1421 * type.
1422 *
1423 * If the flag FLAG_SPARSE is not set in `flags`, then this struct is
1424 * followed by an array of uint32_t defining the resource
1425 * values, corresponding to the array of type strings in the
1426 * ResTable_package::typeStrings string block. Each of these hold an
1427 * index from entriesStart; a value of NO_ENTRY means that entry is
1428 * not defined.
1429 *
1430 * If the flag FLAG_SPARSE is set in `flags`, then this struct is followed
1431 * by an array of ResTable_sparseTypeEntry defining only the entries that
1432 * have values for this type. Each entry is sorted by their entry ID such
1433 * that a binary search can be performed over the entries. The ID and offset
1434 * are encoded in a uint32_t. See ResTabe_sparseTypeEntry.
1435 *
1436 * There may be multiple of these chunks for a particular resource type,
1437 * supply different configuration variations for the resource values of
1438 * that type.
1439 *
1440 * It would be nice to have an additional ordered index of entries, so
1441 * we can do a binary search if trying to find a resource by string name.
1442 */
1443 struct ResTable_type
1444 {
1445 struct ResChunk_header header;
1446
1447 enum {
1448 NO_ENTRY = 0xFFFFFFFF
1449 };
1450
1451 // The type identifier this chunk is holding. Type IDs start
1452 // at 1 (corresponding to the value of the type bits in a
1453 // resource identifier). 0 is invalid.
1454 uint8_t id;
1455
1456 enum {
1457 // If set, the entry is sparse, and encodes both the entry ID and offset into each entry,
1458 // and a binary search is used to find the key. Only available on platforms >= O.
1459 // Mark any types that use this with a v26 qualifier to prevent runtime issues on older
1460 // platforms.
1461 FLAG_SPARSE = 0x01,
1462
1463 // If set, the offsets to the entries are encoded in 16-bit, real_offset = offset * 4u
1464 // An 16-bit offset of 0xffffu means a NO_ENTRY
1465 FLAG_OFFSET16 = 0x02,
1466 };
1467 uint8_t flags;
1468
1469 // Must be 0.
1470 uint16_t reserved;
1471
1472 // Number of uint32_t entry indices that follow.
1473 uint32_t entryCount;
1474
1475 // Offset from header where ResTable_entry data starts.
1476 uint32_t entriesStart;
1477
1478 // Configuration this collection of entries is designed for. This must always be last.
1479 ResTable_config config;
1480 };
1481
1482 // Convert a 16-bit offset to 32-bit if FLAG_OFFSET16 is set
offset_from16(uint16_t off16)1483 static inline uint32_t offset_from16(uint16_t off16) {
1484 return dtohs(off16) == 0xffffu ? ResTable_type::NO_ENTRY : dtohs(off16) * 4u;
1485 }
1486
1487 // The minimum size required to read any version of ResTable_type.
1488 constexpr size_t kResTableTypeMinSize =
1489 sizeof(ResTable_type) - sizeof(ResTable_config) + sizeof(ResTable_config::size);
1490
1491 // Assert that the ResTable_config is always the last field. This poses a problem for extending
1492 // ResTable_type in the future, as ResTable_config is variable (over different releases).
1493 static_assert(sizeof(ResTable_type) == offsetof(ResTable_type, config) + sizeof(ResTable_config),
1494 "ResTable_config must be last field in ResTable_type");
1495
1496 /**
1497 * An entry in a ResTable_type with the flag `FLAG_SPARSE` set.
1498 */
1499 union ResTable_sparseTypeEntry {
1500 // Holds the raw uint32_t encoded value. Do not read this.
1501 uint32_t entry;
1502 struct {
1503 // The index of the entry.
1504 uint16_t idx;
1505
1506 // The offset from ResTable_type::entriesStart, divided by 4.
1507 uint16_t offset;
1508 };
1509 };
1510
1511 static_assert(sizeof(ResTable_sparseTypeEntry) == sizeof(uint32_t),
1512 "ResTable_sparseTypeEntry must be 4 bytes in size");
1513
1514 struct ResTable_map_entry;
1515
1516 /**
1517 * This is the beginning of information about an entry in the resource
1518 * table. It holds the reference to the name of this entry, and is
1519 * immediately followed by one of:
1520 * * A Res_value structure, if FLAG_COMPLEX is -not- set.
1521 * * An array of ResTable_map structures, if FLAG_COMPLEX is set.
1522 * These supply a set of name/value mappings of data.
1523 * * If FLAG_COMPACT is set, this entry is a compact entry for
1524 * simple values only
1525 */
1526 union ResTable_entry
1527 {
1528 enum {
1529 // If set, this is a complex entry, holding a set of name/value
1530 // mappings. It is followed by an array of ResTable_map structures.
1531 FLAG_COMPLEX = 0x0001,
1532 // If set, this resource has been declared public, so libraries
1533 // are allowed to reference it.
1534 FLAG_PUBLIC = 0x0002,
1535 // If set, this is a weak resource and may be overriden by strong
1536 // resources of the same name/type. This is only useful during
1537 // linking with other resource tables.
1538 FLAG_WEAK = 0x0004,
1539 // If set, this is a compact entry with data type and value directly
1540 // encoded in the this entry, see ResTable_entry::compact
1541 FLAG_COMPACT = 0x0008,
1542 };
1543
1544 struct Full {
1545 // Number of bytes in this structure.
1546 uint16_t size;
1547
1548 uint16_t flags;
1549
1550 // Reference into ResTable_package::keyStrings identifying this entry.
1551 struct ResStringPool_ref key;
1552 } full;
1553
1554 /* A compact entry is indicated by FLAG_COMPACT, with flags at the same
1555 * offset as a normal entry. This is only for simple data values where
1556 *
1557 * - size for entry or value can be inferred (both being 8 bytes).
1558 * - key index is encoded in 16-bit
1559 * - dataType is encoded as the higher 8-bit of flags
1560 * - data is encoded directly in this entry
1561 */
1562 struct Compact {
1563 uint16_t key;
1564 uint16_t flags;
1565 uint32_t data;
1566 } compact;
1567
flags()1568 uint16_t flags() const { return dtohs(full.flags); };
is_compact()1569 bool is_compact() const { return flags() & FLAG_COMPACT; }
is_complex()1570 bool is_complex() const { return flags() & FLAG_COMPLEX; }
1571
size()1572 size_t size() const {
1573 return is_compact() ? sizeof(ResTable_entry) : dtohs(this->full.size);
1574 }
1575
key()1576 uint32_t key() const {
1577 return is_compact() ? dtohs(this->compact.key) : dtohl(this->full.key.index);
1578 }
1579
1580 /* Always verify the memory associated with this entry and its value
1581 * before calling value() or map_entry()
1582 */
value()1583 Res_value value() const {
1584 Res_value v;
1585 if (is_compact()) {
1586 v.size = sizeof(Res_value);
1587 v.res0 = 0;
1588 v.data = dtohl(this->compact.data);
1589 v.dataType = dtohs(compact.flags) >> 8;
1590 } else {
1591 auto vaddr = reinterpret_cast<const uint8_t*>(this) + dtohs(this->full.size);
1592 auto value = reinterpret_cast<const Res_value*>(vaddr);
1593 v.size = dtohs(value->size);
1594 v.res0 = value->res0;
1595 v.data = dtohl(value->data);
1596 v.dataType = value->dataType;
1597 }
1598 return v;
1599 }
1600
map_entry()1601 const ResTable_map_entry* map_entry() const {
1602 return is_complex() && !is_compact() ?
1603 reinterpret_cast<const ResTable_map_entry*>(this) : nullptr;
1604 }
1605 };
1606
1607 /* Make sure size of ResTable_entry::Full and ResTable_entry::Compact
1608 * be the same as ResTable_entry. This is to allow iteration of entries
1609 * to work in either cases.
1610 *
1611 * The offset of flags must be at the same place for both structures,
1612 * to ensure the correct reading to decide whether this is a full entry
1613 * or a compact entry.
1614 */
1615 static_assert(sizeof(ResTable_entry) == sizeof(ResTable_entry::Full));
1616 static_assert(sizeof(ResTable_entry) == sizeof(ResTable_entry::Compact));
1617 static_assert(offsetof(ResTable_entry, full.flags) == offsetof(ResTable_entry, compact.flags));
1618
1619 /**
1620 * Extended form of a ResTable_entry for map entries, defining a parent map
1621 * resource from which to inherit values.
1622 */
1623 struct ResTable_map_entry : public ResTable_entry::Full
1624 {
1625 // Resource identifier of the parent mapping, or 0 if there is none.
1626 // This is always treated as a TYPE_DYNAMIC_REFERENCE.
1627 ResTable_ref parent;
1628 // Number of name/value pairs that follow for FLAG_COMPLEX.
1629 uint32_t count;
1630 };
1631
1632 /**
1633 * A single name/value mapping that is part of a complex resource
1634 * entry.
1635 */
1636 struct ResTable_map
1637 {
1638 // The resource identifier defining this mapping's name. For attribute
1639 // resources, 'name' can be one of the following special resource types
1640 // to supply meta-data about the attribute; for all other resource types
1641 // it must be an attribute resource.
1642 ResTable_ref name;
1643
1644 // Special values for 'name' when defining attribute resources.
1645 enum {
1646 // This entry holds the attribute's type code.
1647 ATTR_TYPE = Res_MAKEINTERNAL(0),
1648
1649 // For integral attributes, this is the minimum value it can hold.
1650 ATTR_MIN = Res_MAKEINTERNAL(1),
1651
1652 // For integral attributes, this is the maximum value it can hold.
1653 ATTR_MAX = Res_MAKEINTERNAL(2),
1654
1655 // Localization of this resource is can be encouraged or required with
1656 // an aapt flag if this is set
1657 ATTR_L10N = Res_MAKEINTERNAL(3),
1658
1659 // for plural support, see android.content.res.PluralRules#attrForQuantity(int)
1660 ATTR_OTHER = Res_MAKEINTERNAL(4),
1661 ATTR_ZERO = Res_MAKEINTERNAL(5),
1662 ATTR_ONE = Res_MAKEINTERNAL(6),
1663 ATTR_TWO = Res_MAKEINTERNAL(7),
1664 ATTR_FEW = Res_MAKEINTERNAL(8),
1665 ATTR_MANY = Res_MAKEINTERNAL(9)
1666
1667 };
1668
1669 // Bit mask of allowed types, for use with ATTR_TYPE.
1670 enum {
1671 // No type has been defined for this attribute, use generic
1672 // type handling. The low 16 bits are for types that can be
1673 // handled generically; the upper 16 require additional information
1674 // in the bag so can not be handled generically for TYPE_ANY.
1675 TYPE_ANY = 0x0000FFFF,
1676
1677 // Attribute holds a references to another resource.
1678 TYPE_REFERENCE = 1<<0,
1679
1680 // Attribute holds a generic string.
1681 TYPE_STRING = 1<<1,
1682
1683 // Attribute holds an integer value. ATTR_MIN and ATTR_MIN can
1684 // optionally specify a constrained range of possible integer values.
1685 TYPE_INTEGER = 1<<2,
1686
1687 // Attribute holds a boolean integer.
1688 TYPE_BOOLEAN = 1<<3,
1689
1690 // Attribute holds a color value.
1691 TYPE_COLOR = 1<<4,
1692
1693 // Attribute holds a floating point value.
1694 TYPE_FLOAT = 1<<5,
1695
1696 // Attribute holds a dimension value, such as "20px".
1697 TYPE_DIMENSION = 1<<6,
1698
1699 // Attribute holds a fraction value, such as "20%".
1700 TYPE_FRACTION = 1<<7,
1701
1702 // Attribute holds an enumeration. The enumeration values are
1703 // supplied as additional entries in the map.
1704 TYPE_ENUM = 1<<16,
1705
1706 // Attribute holds a bitmaks of flags. The flag bit values are
1707 // supplied as additional entries in the map.
1708 TYPE_FLAGS = 1<<17
1709 };
1710
1711 // Enum of localization modes, for use with ATTR_L10N.
1712 enum {
1713 L10N_NOT_REQUIRED = 0,
1714 L10N_SUGGESTED = 1
1715 };
1716
1717 // This mapping's value.
1718 Res_value value;
1719 };
1720
1721 /**
1722 * A package-id to package name mapping for any shared libraries used
1723 * in this resource table. The package-id's encoded in this resource
1724 * table may be different than the id's assigned at runtime. We must
1725 * be able to translate the package-id's based on the package name.
1726 */
1727 struct ResTable_lib_header
1728 {
1729 struct ResChunk_header header;
1730
1731 // The number of shared libraries linked in this resource table.
1732 uint32_t count;
1733 };
1734
1735 /**
1736 * A shared library package-id to package name entry.
1737 */
1738 struct ResTable_lib_entry
1739 {
1740 // The package-id this shared library was assigned at build time.
1741 // We use a uint32 to keep the structure aligned on a uint32 boundary.
1742 uint32_t packageId;
1743
1744 // The package name of the shared library. \0 terminated.
1745 uint16_t packageName[128];
1746 };
1747
1748 /**
1749 * A map that allows rewriting staged (non-finalized) resource ids to their finalized counterparts.
1750 */
1751 struct ResTable_staged_alias_header
1752 {
1753 struct ResChunk_header header;
1754
1755 // The number of ResTable_staged_alias_entry that follow this header.
1756 uint32_t count;
1757 };
1758
1759 /**
1760 * Maps the staged (non-finalized) resource id to its finalized resource id.
1761 */
1762 struct ResTable_staged_alias_entry
1763 {
1764 // The compile-time staged resource id to rewrite.
1765 uint32_t stagedResId;
1766
1767 // The compile-time finalized resource id to which the staged resource id should be rewritten.
1768 uint32_t finalizedResId;
1769 };
1770
1771 /**
1772 * Specifies the set of resources that are explicitly allowed to be overlaid by RROs.
1773 */
1774 struct ResTable_overlayable_header
1775 {
1776 struct ResChunk_header header;
1777
1778 // The name of the overlayable set of resources that overlays target.
1779 uint16_t name[256];
1780
1781 // The component responsible for enabling and disabling overlays targeting this chunk.
1782 uint16_t actor[256];
1783 };
1784
1785 /**
1786 * Holds a list of resource ids that are protected from being overlaid by a set of policies. If
1787 * the overlay fulfils at least one of the policies, then the overlay can overlay the list of
1788 * resources.
1789 */
1790 struct ResTable_overlayable_policy_header
1791 {
1792 /**
1793 * Flags for a bitmask for all possible overlayable policy options.
1794 *
1795 * Any changes to this set should also update aidl/android/os/OverlayablePolicy.aidl
1796 */
1797 enum PolicyFlags : uint32_t {
1798 // Base
1799 NONE = 0x00000000,
1800
1801 // Any overlay can overlay these resources.
1802 PUBLIC = 0x00000001,
1803
1804 // The overlay must reside of the system partition or must have existed on the system partition
1805 // before an upgrade to overlay these resources.
1806 SYSTEM_PARTITION = 0x00000002,
1807
1808 // The overlay must reside of the vendor partition or must have existed on the vendor partition
1809 // before an upgrade to overlay these resources.
1810 VENDOR_PARTITION = 0x00000004,
1811
1812 // The overlay must reside of the product partition or must have existed on the product
1813 // partition before an upgrade to overlay these resources.
1814 PRODUCT_PARTITION = 0x00000008,
1815
1816 // The overlay must be signed with the same signature as the package containing the target
1817 // resource
1818 SIGNATURE = 0x00000010,
1819
1820 // The overlay must reside of the odm partition or must have existed on the odm
1821 // partition before an upgrade to overlay these resources.
1822 ODM_PARTITION = 0x00000020,
1823
1824 // The overlay must reside of the oem partition or must have existed on the oem
1825 // partition before an upgrade to overlay these resources.
1826 OEM_PARTITION = 0x00000040,
1827
1828 // The overlay must be signed with the same signature as the actor declared for the target
1829 // resource
1830 ACTOR_SIGNATURE = 0x00000080,
1831
1832 // The overlay must be signed with the same signature as the reference package declared
1833 // in the SystemConfig
1834 CONFIG_SIGNATURE = 0x00000100,
1835 };
1836
1837 using PolicyBitmask = uint32_t;
1838
1839 struct ResChunk_header header;
1840
1841 PolicyFlags policy_flags;
1842
1843 // The number of ResTable_ref that follow this header.
1844 uint32_t entry_count;
1845 };
1846
1847 inline ResTable_overlayable_policy_header::PolicyFlags& operator |=(
1848 ResTable_overlayable_policy_header::PolicyFlags& first,
1849 ResTable_overlayable_policy_header::PolicyFlags second) {
1850 first = static_cast<ResTable_overlayable_policy_header::PolicyFlags>(first | second);
1851 return first;
1852 }
1853
1854 using ResourceId = uint32_t; // 0xpptteeee
1855
1856 using DataType = uint8_t; // Res_value::dataType
1857 using DataValue = uint32_t; // Res_value::data
1858
1859 struct OverlayManifestInfo {
1860 std::string package_name; // NOLINT(misc-non-private-member-variables-in-classes)
1861 std::string name; // NOLINT(misc-non-private-member-variables-in-classes)
1862 std::string target_package; // NOLINT(misc-non-private-member-variables-in-classes)
1863 std::string target_name; // NOLINT(misc-non-private-member-variables-in-classes)
1864 ResourceId resource_mapping; // NOLINT(misc-non-private-member-variables-in-classes)
1865 };
1866
1867 struct FabricatedOverlayEntryParameters {
1868 std::string resource_name;
1869 DataType data_type;
1870 DataValue data_value;
1871 std::string data_string_value;
1872 std::optional<android::base::borrowed_fd> data_binary_value;
1873 std::string configuration;
1874 };
1875
1876 class AssetManager2;
1877
1878 /**
1879 * Holds the shared library ID table. Shared libraries are assigned package IDs at
1880 * build time, but they may be loaded in a different order, so we need to maintain
1881 * a mapping of build-time package ID to run-time assigned package ID.
1882 *
1883 * Dynamic references are not currently supported in overlays. Only the base package
1884 * may have dynamic references.
1885 */
1886 class DynamicRefTable
1887 {
1888 friend class AssetManager2;
1889 public:
1890 DynamicRefTable();
1891 DynamicRefTable(uint8_t packageId, bool appAsLib);
1892 virtual ~DynamicRefTable() = default;
1893
1894 // Loads an unmapped reference table from the package.
1895 status_t load(const ResTable_lib_header* const header);
1896
1897 // Adds mappings from the other DynamicRefTable
1898 status_t addMappings(const DynamicRefTable& other);
1899
1900 // Creates a mapping from build-time package ID to run-time package ID for
1901 // the given package.
1902 status_t addMapping(const String16& packageName, uint8_t packageId);
1903
1904 void addMapping(uint8_t buildPackageId, uint8_t runtimePackageId);
1905
1906 using AliasMap = std::vector<std::pair<uint32_t, uint32_t>>;
setAliases(AliasMap aliases)1907 void setAliases(AliasMap aliases) {
1908 mAliasId = std::move(aliases);
1909 }
1910
1911 // Returns whether or not the value must be looked up.
1912 bool requiresLookup(const Res_value* value) const;
1913
1914 // Performs the actual conversion of build-time resource ID to run-time
1915 // resource ID.
1916 virtual status_t lookupResourceId(uint32_t* resId) const;
1917 status_t lookupResourceValue(Res_value* value) const;
1918
entries()1919 inline const KeyedVector<String16, uint8_t>& entries() const {
1920 return mEntries;
1921 }
1922
1923 private:
1924 uint8_t mLookupTable[256];
1925 uint8_t mAssignedPackageId;
1926 bool mAppAsLib;
1927 KeyedVector<String16, uint8_t> mEntries;
1928 AliasMap mAliasId;
1929 };
1930
1931 bool U16StringToInt(const char16_t* s, size_t len, Res_value* outValue);
1932
1933 template<typename TChar, typename E>
UnpackOptionalString(base::expected<BasicStringPiece<TChar>,E> && result,size_t * outLen)1934 static const TChar* UnpackOptionalString(base::expected<BasicStringPiece<TChar>, E>&& result,
1935 size_t* outLen) {
1936 if (result.has_value()) {
1937 *outLen = result->size();
1938 return result->data();
1939 }
1940 return NULL;
1941 }
1942
1943 /**
1944 * Convenience class for accessing data in a ResTable resource.
1945 */
1946 class ResTable
1947 {
1948 public:
1949 ResTable();
1950 ResTable(const void* data, size_t size, const int32_t cookie,
1951 bool copyData=false);
1952 ~ResTable();
1953
1954 status_t add(const void* data, size_t size, const int32_t cookie=-1, bool copyData=false);
1955 status_t add(const void* data, size_t size, const void* idmapData, size_t idmapDataSize,
1956 const int32_t cookie=-1, bool copyData=false, bool appAsLib=false);
1957
1958 status_t add(Asset* asset, const int32_t cookie=-1, bool copyData=false);
1959 status_t add(Asset* asset, Asset* idmapAsset, const int32_t cookie=-1, bool copyData=false,
1960 bool appAsLib=false, bool isSystemAsset=false);
1961
1962 status_t add(ResTable* src, bool isSystemAsset=false);
1963 status_t addEmpty(const int32_t cookie);
1964
1965 status_t getError() const;
1966
1967 void uninit();
1968
1969 struct resource_name
1970 {
1971 const char16_t* package = NULL;
1972 size_t packageLen;
1973 const char16_t* type = NULL;
1974 const char* type8 = NULL;
1975 size_t typeLen;
1976 const char16_t* name = NULL;
1977 const char* name8 = NULL;
1978 size_t nameLen;
1979 };
1980
1981 bool getResourceName(uint32_t resID, bool allowUtf8, resource_name* outName) const;
1982
1983 bool getResourceFlags(uint32_t resID, uint32_t* outFlags) const;
1984
1985 /**
1986 * Returns whether or not the package for the given resource has been dynamically assigned.
1987 * If the resource can't be found, returns 'false'.
1988 */
1989 bool isResourceDynamic(uint32_t resID) const;
1990
1991 /**
1992 * Returns whether or not the given package has been dynamically assigned.
1993 * If the package can't be found, returns 'false'.
1994 */
1995 bool isPackageDynamic(uint8_t packageID) const;
1996
1997 /**
1998 * Retrieve the value of a resource. If the resource is found, returns a
1999 * value >= 0 indicating the table it is in (for use with
2000 * getTableStringBlock() and getTableCookie()) and fills in 'outValue'. If
2001 * not found, returns a negative error code.
2002 *
2003 * Note that this function does not do reference traversal. If you want
2004 * to follow references to other resources to get the "real" value to
2005 * use, you need to call resolveReference() after this function.
2006 *
2007 * @param resID The desired resoruce identifier.
2008 * @param outValue Filled in with the resource data that was found.
2009 *
2010 * @return ssize_t Either a >= 0 table index or a negative error code.
2011 */
2012 ssize_t getResource(uint32_t resID, Res_value* outValue, bool mayBeBag = false,
2013 uint16_t density = 0,
2014 uint32_t* outSpecFlags = NULL,
2015 ResTable_config* outConfig = NULL) const;
2016
2017 inline ssize_t getResource(const ResTable_ref& res, Res_value* outValue,
2018 uint32_t* outSpecFlags=NULL) const {
2019 return getResource(res.ident, outValue, false, 0, outSpecFlags, NULL);
2020 }
2021
2022 ssize_t resolveReference(Res_value* inOutValue,
2023 ssize_t blockIndex,
2024 uint32_t* outLastRef = NULL,
2025 uint32_t* inoutTypeSpecFlags = NULL,
2026 ResTable_config* outConfig = NULL) const;
2027
2028 enum {
2029 TMP_BUFFER_SIZE = 16
2030 };
2031 const char16_t* valueToString(const Res_value* value, size_t stringBlock,
2032 char16_t tmpBuffer[TMP_BUFFER_SIZE],
2033 size_t* outLen) const;
2034
2035 struct bag_entry {
2036 ssize_t stringBlock;
2037 ResTable_map map;
2038 };
2039
2040 /**
2041 * Retrieve the bag of a resource. If the resoruce is found, returns the
2042 * number of bags it contains and 'outBag' points to an array of their
2043 * values. If not found, a negative error code is returned.
2044 *
2045 * Note that this function -does- do reference traversal of the bag data.
2046 *
2047 * @param resID The desired resource identifier.
2048 * @param outBag Filled inm with a pointer to the bag mappings.
2049 *
2050 * @return ssize_t Either a >= 0 bag count of negative error code.
2051 */
2052 ssize_t lockBag(uint32_t resID, const bag_entry** outBag) const;
2053
2054 void unlockBag(const bag_entry* bag) const;
2055
2056 void lock() const;
2057
2058 ssize_t getBagLocked(uint32_t resID, const bag_entry** outBag,
2059 uint32_t* outTypeSpecFlags=NULL) const;
2060
2061 void unlock() const;
2062
2063 class Theme {
2064 public:
2065 explicit Theme(const ResTable& table);
2066 ~Theme();
2067
getResTable()2068 inline const ResTable& getResTable() const { return mTable; }
2069
2070 status_t applyStyle(uint32_t resID, bool force=false);
2071 status_t setTo(const Theme& other);
2072 status_t clear();
2073
2074 /**
2075 * Retrieve a value in the theme. If the theme defines this
2076 * value, returns a value >= 0 indicating the table it is in
2077 * (for use with getTableStringBlock() and getTableCookie) and
2078 * fills in 'outValue'. If not found, returns a negative error
2079 * code.
2080 *
2081 * Note that this function does not do reference traversal. If you want
2082 * to follow references to other resources to get the "real" value to
2083 * use, you need to call resolveReference() after this function.
2084 *
2085 * @param resID A resource identifier naming the desired theme
2086 * attribute.
2087 * @param outValue Filled in with the theme value that was
2088 * found.
2089 *
2090 * @return ssize_t Either a >= 0 table index or a negative error code.
2091 */
2092 ssize_t getAttribute(uint32_t resID, Res_value* outValue,
2093 uint32_t* outTypeSpecFlags = NULL) const;
2094
2095 /**
2096 * This is like ResTable::resolveReference(), but also takes
2097 * care of resolving attribute references to the theme.
2098 */
2099 ssize_t resolveAttributeReference(Res_value* inOutValue,
2100 ssize_t blockIndex, uint32_t* outLastRef = NULL,
2101 uint32_t* inoutTypeSpecFlags = NULL,
2102 ResTable_config* inoutConfig = NULL) const;
2103
2104 /**
2105 * Returns a bit mask of configuration changes that will impact this
2106 * theme (and thus require completely reloading it).
2107 */
2108 uint32_t getChangingConfigurations() const;
2109
2110 void dumpToLog() const;
2111
2112 private:
2113 Theme(const Theme&);
2114 Theme& operator=(const Theme&);
2115
2116 struct theme_entry {
2117 ssize_t stringBlock;
2118 uint32_t typeSpecFlags;
2119 Res_value value;
2120 };
2121
2122 struct type_info {
2123 size_t numEntries;
2124 theme_entry* entries;
2125 };
2126
2127 struct package_info {
2128 type_info types[Res_MAXTYPE + 1];
2129 };
2130
2131 void free_package(package_info* pi);
2132 package_info* copy_package(package_info* pi);
2133
2134 const ResTable& mTable;
2135 package_info* mPackages[Res_MAXPACKAGE];
2136 uint32_t mTypeSpecFlags;
2137 };
2138
2139 void setParameters(const ResTable_config* params);
2140 void getParameters(ResTable_config* params) const;
2141
2142 // Retrieve an identifier (which can be passed to getResource)
2143 // for a given resource name. The 'name' can be fully qualified
2144 // (<package>:<type>.<basename>) or the package or type components
2145 // can be dropped if default values are supplied here.
2146 //
2147 // Returns 0 if no such resource was found, else a valid resource ID.
2148 uint32_t identifierForName(const char16_t* name, size_t nameLen,
2149 const char16_t* type = 0, size_t typeLen = 0,
2150 const char16_t* defPackage = 0,
2151 size_t defPackageLen = 0,
2152 uint32_t* outTypeSpecFlags = NULL) const;
2153
2154 static bool expandResourceRef(const char16_t* refStr, size_t refLen,
2155 String16* outPackage,
2156 String16* outType,
2157 String16* outName,
2158 const String16* defType = NULL,
2159 const String16* defPackage = NULL,
2160 const char** outErrorMsg = NULL,
2161 bool* outPublicOnly = NULL);
2162
2163 static bool stringToInt(const char16_t* s, size_t len, Res_value* outValue);
2164 static bool stringToFloat(const char16_t* s, size_t len, Res_value* outValue);
2165
2166 // Used with stringToValue.
2167 class Accessor
2168 {
2169 public:
~Accessor()2170 inline virtual ~Accessor() { }
2171
2172 virtual const String16& getAssetsPackage() const = 0;
2173
2174 virtual uint32_t getCustomResource(const String16& package,
2175 const String16& type,
2176 const String16& name) const = 0;
2177 virtual uint32_t getCustomResourceWithCreation(const String16& package,
2178 const String16& type,
2179 const String16& name,
2180 const bool createIfNeeded = false) = 0;
2181 virtual uint32_t getRemappedPackage(uint32_t origPackage) const = 0;
2182 virtual bool getAttributeType(uint32_t attrID, uint32_t* outType) = 0;
2183 virtual bool getAttributeMin(uint32_t attrID, uint32_t* outMin) = 0;
2184 virtual bool getAttributeMax(uint32_t attrID, uint32_t* outMax) = 0;
2185 virtual bool getAttributeEnum(uint32_t attrID,
2186 const char16_t* name, size_t nameLen,
2187 Res_value* outValue) = 0;
2188 virtual bool getAttributeFlags(uint32_t attrID,
2189 const char16_t* name, size_t nameLen,
2190 Res_value* outValue) = 0;
2191 virtual uint32_t getAttributeL10N(uint32_t attrID) = 0;
2192 virtual bool getLocalizationSetting() = 0;
2193 virtual void reportError(void* accessorCookie, const char* fmt, ...) = 0;
2194 };
2195
2196 // Convert a string to a resource value. Handles standard "@res",
2197 // "#color", "123", and "0x1bd" types; performs escaping of strings.
2198 // The resulting value is placed in 'outValue'; if it is a string type,
2199 // 'outString' receives the string. If 'attrID' is supplied, the value is
2200 // type checked against this attribute and it is used to perform enum
2201 // evaluation. If 'acccessor' is supplied, it will be used to attempt to
2202 // resolve resources that do not exist in this ResTable. If 'attrType' is
2203 // supplied, the value will be type checked for this format if 'attrID'
2204 // is not supplied or found.
2205 bool stringToValue(Res_value* outValue, String16* outString,
2206 const char16_t* s, size_t len,
2207 bool preserveSpaces, bool coerceType,
2208 uint32_t attrID = 0,
2209 const String16* defType = NULL,
2210 const String16* defPackage = NULL,
2211 Accessor* accessor = NULL,
2212 void* accessorCookie = NULL,
2213 uint32_t attrType = ResTable_map::TYPE_ANY,
2214 bool enforcePrivate = true) const;
2215
2216 // Perform processing of escapes and quotes in a string.
2217 static bool collectString(String16* outString,
2218 const char16_t* s, size_t len,
2219 bool preserveSpaces,
2220 const char** outErrorMsg = NULL,
2221 bool append = false);
2222
2223 size_t getBasePackageCount() const;
2224 const String16 getBasePackageName(size_t idx) const;
2225 uint32_t getBasePackageId(size_t idx) const;
2226 uint32_t getLastTypeIdForPackage(size_t idx) const;
2227
2228 // Return the number of resource tables that the object contains.
2229 size_t getTableCount() const;
2230 // Return the values string pool for the resource table at the given
2231 // index. This string pool contains all of the strings for values
2232 // contained in the resource table -- that is the item values themselves,
2233 // but not the names their entries or types.
2234 const ResStringPool* getTableStringBlock(size_t index) const;
2235 // Return unique cookie identifier for the given resource table.
2236 int32_t getTableCookie(size_t index) const;
2237
2238 const DynamicRefTable* getDynamicRefTableForCookie(int32_t cookie) const;
2239
2240 // Return the configurations (ResTable_config) that we know about
2241 void getConfigurations(Vector<ResTable_config>* configs, bool ignoreMipmap=false,
2242 bool ignoreAndroidPackage=false, bool includeSystemConfigs=true) const;
2243
2244 void getLocales(Vector<String8>* locales, bool includeSystemLocales=true,
2245 bool mergeEquivalentLangs=false) const;
2246
2247 // Generate an idmap.
2248 //
2249 // Return value: on success: NO_ERROR; caller is responsible for free-ing
2250 // outData (using free(3)). On failure, any status_t value other than
2251 // NO_ERROR; the caller should not free outData.
2252 status_t createIdmap(const ResTable& targetResTable,
2253 uint32_t targetCrc, uint32_t overlayCrc,
2254 const char* targetPath, const char* overlayPath,
2255 void** outData, size_t* outSize) const;
2256
2257 static const size_t IDMAP_HEADER_SIZE_BYTES = 4 * sizeof(uint32_t) + 2 * 256;
2258 static const uint32_t IDMAP_CURRENT_VERSION = 0x00000001;
2259
2260 // Retrieve idmap meta-data.
2261 //
2262 // This function only requires the idmap header (the first
2263 // IDMAP_HEADER_SIZE_BYTES) bytes of an idmap file.
2264 static bool getIdmapInfo(const void* idmap, size_t size,
2265 uint32_t* pVersion,
2266 uint32_t* pTargetCrc, uint32_t* pOverlayCrc,
2267 String8* pTargetPath, String8* pOverlayPath);
2268
2269 void print(bool inclValues) const;
2270 static String8 normalizeForOutput(const char* input);
2271
2272 private:
2273 struct Header;
2274 struct Type;
2275 struct Entry;
2276 struct Package;
2277 struct PackageGroup;
2278 typedef Vector<Type*> TypeList;
2279
2280 struct bag_set {
2281 size_t numAttrs; // number in array
2282 size_t availAttrs; // total space in array
2283 uint32_t typeSpecFlags;
2284 // Followed by 'numAttr' bag_entry structures.
2285 };
2286
2287 /**
2288 * Configuration dependent cached data. This must be cleared when the configuration is
2289 * changed (setParameters).
2290 */
2291 struct TypeCacheEntry {
TypeCacheEntryTypeCacheEntry2292 TypeCacheEntry() : cachedBags(NULL) {}
2293
2294 // Computed attribute bags for this type.
2295 bag_set** cachedBags;
2296
2297 // Pre-filtered list of configurations (per asset path) that match the parameters set on this
2298 // ResTable.
2299 Vector<std::shared_ptr<Vector<const ResTable_type*>>> filteredConfigs;
2300 };
2301
2302 status_t addInternal(const void* data, size_t size, const void* idmapData, size_t idmapDataSize,
2303 bool appAsLib, const int32_t cookie, bool copyData, bool isSystemAsset=false);
2304
2305 ssize_t getResourcePackageIndex(uint32_t resID) const;
2306 ssize_t getResourcePackageIndexFromPackage(uint8_t packageID) const;
2307
2308 status_t getEntry(
2309 const PackageGroup* packageGroup, int typeIndex, int entryIndex,
2310 const ResTable_config* config,
2311 Entry* outEntry) const;
2312
2313 uint32_t findEntry(const PackageGroup* group, ssize_t typeIndex, const char16_t* name,
2314 size_t nameLen, uint32_t* outTypeSpecFlags) const;
2315
2316 status_t parsePackage(
2317 const ResTable_package* const pkg, const Header* const header,
2318 bool appAsLib, bool isSystemAsset);
2319
2320 void print_value(const Package* pkg, const Res_value& value) const;
2321
2322 template <typename Func>
2323 void forEachConfiguration(bool ignoreMipmap, bool ignoreAndroidPackage,
2324 bool includeSystemConfigs, const Func& f) const;
2325
2326 mutable Mutex mLock;
2327
2328 // Mutex that controls access to the list of pre-filtered configurations
2329 // to check when looking up entries.
2330 // When iterating over a bag, the mLock mutex is locked. While mLock is locked,
2331 // we do resource lookups.
2332 // Mutex is not reentrant, so we must use a different lock than mLock.
2333 mutable Mutex mFilteredConfigLock;
2334
2335 status_t mError;
2336
2337 ResTable_config mParams;
2338
2339 // Array of all resource tables.
2340 Vector<Header*> mHeaders;
2341
2342 // Array of packages in all resource tables.
2343 Vector<PackageGroup*> mPackageGroups;
2344
2345 // Mapping from resource package IDs to indices into the internal
2346 // package array.
2347 uint8_t mPackageMap[256];
2348
2349 uint8_t mNextPackageId;
2350 };
2351
2352 } // namespace android
2353
2354 #endif // _LIBS_UTILS_RESOURCE_TYPES_H
2355