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