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