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