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