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