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