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