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