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