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