ResourceTable.cpp revision 010df88f90a40f8c521ccde8d6a541e70a044fb7
1// 2// Copyright 2006 The Android Open Source Project 3// 4// Build resource files from raw assets. 5// 6 7#include "ResourceTable.h" 8 9#include "AaptUtil.h" 10#include "XMLNode.h" 11#include "ResourceFilter.h" 12#include "ResourceIdCache.h" 13#include "SdkConstants.h" 14 15#include <algorithm> 16#include <androidfw/ResourceTypes.h> 17#include <utils/ByteOrder.h> 18#include <utils/TypeHelpers.h> 19#include <stdarg.h> 20 21// SSIZE: mingw does not have signed size_t == ssize_t. 22// STATUST: mingw does seem to redefine UNKNOWN_ERROR from our enum value, so a cast is necessary. 23#if !defined(_WIN32) 24# define SSIZE(x) x 25# define STATUST(x) x 26#else 27# define SSIZE(x) (signed size_t)x 28# define STATUST(x) (status_t)x 29#endif 30 31// Set to true for noisy debug output. 32static const bool kIsDebug = false; 33 34#if PRINT_STRING_METRICS 35static const bool kPrintStringMetrics = true; 36#else 37static const bool kPrintStringMetrics = false; 38#endif 39 40static const char* kAttrPrivateType = "^attr-private"; 41 42status_t compileXmlFile(const Bundle* bundle, 43 const sp<AaptAssets>& assets, 44 const String16& resourceName, 45 const sp<AaptFile>& target, 46 ResourceTable* table, 47 int options) 48{ 49 sp<XMLNode> root = XMLNode::parse(target); 50 if (root == NULL) { 51 return UNKNOWN_ERROR; 52 } 53 54 return compileXmlFile(bundle, assets, resourceName, root, target, table, options); 55} 56 57status_t compileXmlFile(const Bundle* bundle, 58 const sp<AaptAssets>& assets, 59 const String16& resourceName, 60 const sp<AaptFile>& target, 61 const sp<AaptFile>& outTarget, 62 ResourceTable* table, 63 int options) 64{ 65 sp<XMLNode> root = XMLNode::parse(target); 66 if (root == NULL) { 67 return UNKNOWN_ERROR; 68 } 69 70 return compileXmlFile(bundle, assets, resourceName, root, outTarget, table, options); 71} 72 73status_t compileXmlFile(const Bundle* bundle, 74 const sp<AaptAssets>& assets, 75 const String16& resourceName, 76 const sp<XMLNode>& root, 77 const sp<AaptFile>& target, 78 ResourceTable* table, 79 int options) 80{ 81 if ((options&XML_COMPILE_STRIP_WHITESPACE) != 0) { 82 root->removeWhitespace(true, NULL); 83 } else if ((options&XML_COMPILE_COMPACT_WHITESPACE) != 0) { 84 root->removeWhitespace(false, NULL); 85 } 86 87 if ((options&XML_COMPILE_UTF8) != 0) { 88 root->setUTF8(true); 89 } 90 91 if (table->processBundleFormat(bundle, resourceName, target, root) != NO_ERROR) { 92 return UNKNOWN_ERROR; 93 } 94 95 bool hasErrors = false; 96 if ((options&XML_COMPILE_ASSIGN_ATTRIBUTE_IDS) != 0) { 97 status_t err = root->assignResourceIds(assets, table); 98 if (err != NO_ERROR) { 99 hasErrors = true; 100 } 101 } 102 103 if ((options&XML_COMPILE_PARSE_VALUES) != 0) { 104 status_t err = root->parseValues(assets, table); 105 if (err != NO_ERROR) { 106 hasErrors = true; 107 } 108 } 109 110 if (hasErrors) { 111 return UNKNOWN_ERROR; 112 } 113 114 if (table->modifyForCompat(bundle, resourceName, target, root) != NO_ERROR) { 115 return UNKNOWN_ERROR; 116 } 117 118 if (kIsDebug) { 119 printf("Input XML Resource:\n"); 120 root->print(); 121 } 122 status_t err = root->flatten(target, 123 (options&XML_COMPILE_STRIP_COMMENTS) != 0, 124 (options&XML_COMPILE_STRIP_RAW_VALUES) != 0); 125 if (err != NO_ERROR) { 126 return err; 127 } 128 129 if (kIsDebug) { 130 printf("Output XML Resource:\n"); 131 ResXMLTree tree; 132 tree.setTo(target->getData(), target->getSize()); 133 printXMLBlock(&tree); 134 } 135 136 target->setCompressionMethod(ZipEntry::kCompressDeflated); 137 138 return err; 139} 140 141struct flag_entry 142{ 143 const char16_t* name; 144 size_t nameLen; 145 uint32_t value; 146 const char* description; 147}; 148 149static const char16_t referenceArray[] = 150 { 'r', 'e', 'f', 'e', 'r', 'e', 'n', 'c', 'e' }; 151static const char16_t stringArray[] = 152 { 's', 't', 'r', 'i', 'n', 'g' }; 153static const char16_t integerArray[] = 154 { 'i', 'n', 't', 'e', 'g', 'e', 'r' }; 155static const char16_t booleanArray[] = 156 { 'b', 'o', 'o', 'l', 'e', 'a', 'n' }; 157static const char16_t colorArray[] = 158 { 'c', 'o', 'l', 'o', 'r' }; 159static const char16_t floatArray[] = 160 { 'f', 'l', 'o', 'a', 't' }; 161static const char16_t dimensionArray[] = 162 { 'd', 'i', 'm', 'e', 'n', 's', 'i', 'o', 'n' }; 163static const char16_t fractionArray[] = 164 { 'f', 'r', 'a', 'c', 't', 'i', 'o', 'n' }; 165static const char16_t enumArray[] = 166 { 'e', 'n', 'u', 'm' }; 167static const char16_t flagsArray[] = 168 { 'f', 'l', 'a', 'g', 's' }; 169 170static const flag_entry gFormatFlags[] = { 171 { referenceArray, sizeof(referenceArray)/2, ResTable_map::TYPE_REFERENCE, 172 "a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\n" 173 "or to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\"."}, 174 { stringArray, sizeof(stringArray)/2, ResTable_map::TYPE_STRING, 175 "a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character." }, 176 { integerArray, sizeof(integerArray)/2, ResTable_map::TYPE_INTEGER, 177 "an integer value, such as \"<code>100</code>\"." }, 178 { booleanArray, sizeof(booleanArray)/2, ResTable_map::TYPE_BOOLEAN, 179 "a boolean value, either \"<code>true</code>\" or \"<code>false</code>\"." }, 180 { colorArray, sizeof(colorArray)/2, ResTable_map::TYPE_COLOR, 181 "a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n" 182 "\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\"." }, 183 { floatArray, sizeof(floatArray)/2, ResTable_map::TYPE_FLOAT, 184 "a floating point value, such as \"<code>1.2</code>\"."}, 185 { dimensionArray, sizeof(dimensionArray)/2, ResTable_map::TYPE_DIMENSION, 186 "a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\n" 187 "Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\n" 188 "in (inches), mm (millimeters)." }, 189 { fractionArray, sizeof(fractionArray)/2, ResTable_map::TYPE_FRACTION, 190 "a fractional value, which is a floating point number appended with either % or %p, such as \"<code>14.5%</code>\".\n" 191 "The % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to\n" 192 "some parent container." }, 193 { enumArray, sizeof(enumArray)/2, ResTable_map::TYPE_ENUM, NULL }, 194 { flagsArray, sizeof(flagsArray)/2, ResTable_map::TYPE_FLAGS, NULL }, 195 { NULL, 0, 0, NULL } 196}; 197 198static const char16_t suggestedArray[] = { 's', 'u', 'g', 'g', 'e', 's', 't', 'e', 'd' }; 199 200static const flag_entry l10nRequiredFlags[] = { 201 { suggestedArray, sizeof(suggestedArray)/2, ResTable_map::L10N_SUGGESTED, NULL }, 202 { NULL, 0, 0, NULL } 203}; 204 205static const char16_t nulStr[] = { 0 }; 206 207static uint32_t parse_flags(const char16_t* str, size_t len, 208 const flag_entry* flags, bool* outError = NULL) 209{ 210 while (len > 0 && isspace(*str)) { 211 str++; 212 len--; 213 } 214 while (len > 0 && isspace(str[len-1])) { 215 len--; 216 } 217 218 const char16_t* const end = str + len; 219 uint32_t value = 0; 220 221 while (str < end) { 222 const char16_t* div = str; 223 while (div < end && *div != '|') { 224 div++; 225 } 226 227 const flag_entry* cur = flags; 228 while (cur->name) { 229 if (strzcmp16(cur->name, cur->nameLen, str, div-str) == 0) { 230 value |= cur->value; 231 break; 232 } 233 cur++; 234 } 235 236 if (!cur->name) { 237 if (outError) *outError = true; 238 return 0; 239 } 240 241 str = div < end ? div+1 : div; 242 } 243 244 if (outError) *outError = false; 245 return value; 246} 247 248static String16 mayOrMust(int type, int flags) 249{ 250 if ((type&(~flags)) == 0) { 251 return String16("<p>Must"); 252 } 253 254 return String16("<p>May"); 255} 256 257static void appendTypeInfo(ResourceTable* outTable, const String16& pkg, 258 const String16& typeName, const String16& ident, int type, 259 const flag_entry* flags) 260{ 261 bool hadType = false; 262 while (flags->name) { 263 if ((type&flags->value) != 0 && flags->description != NULL) { 264 String16 fullMsg(mayOrMust(type, flags->value)); 265 fullMsg.append(String16(" be ")); 266 fullMsg.append(String16(flags->description)); 267 outTable->appendTypeComment(pkg, typeName, ident, fullMsg); 268 hadType = true; 269 } 270 flags++; 271 } 272 if (hadType && (type&ResTable_map::TYPE_REFERENCE) == 0) { 273 outTable->appendTypeComment(pkg, typeName, ident, 274 String16("<p>This may also be a reference to a resource (in the form\n" 275 "\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\n" 276 "theme attribute (in the form\n" 277 "\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\n" 278 "containing a value of this type.")); 279 } 280} 281 282struct PendingAttribute 283{ 284 const String16 myPackage; 285 const SourcePos sourcePos; 286 const bool appendComment; 287 int32_t type; 288 String16 ident; 289 String16 comment; 290 bool hasErrors; 291 bool added; 292 293 PendingAttribute(String16 _package, const sp<AaptFile>& in, 294 ResXMLTree& block, bool _appendComment) 295 : myPackage(_package) 296 , sourcePos(in->getPrintableSource(), block.getLineNumber()) 297 , appendComment(_appendComment) 298 , type(ResTable_map::TYPE_ANY) 299 , hasErrors(false) 300 , added(false) 301 { 302 } 303 304 status_t createIfNeeded(ResourceTable* outTable) 305 { 306 if (added || hasErrors) { 307 return NO_ERROR; 308 } 309 added = true; 310 311 if (!outTable->makeAttribute(myPackage, ident, sourcePos, type, comment, appendComment)) { 312 hasErrors = true; 313 return UNKNOWN_ERROR; 314 } 315 return NO_ERROR; 316 } 317}; 318 319static status_t compileAttribute(const sp<AaptFile>& in, 320 ResXMLTree& block, 321 const String16& myPackage, 322 ResourceTable* outTable, 323 String16* outIdent = NULL, 324 bool inStyleable = false) 325{ 326 PendingAttribute attr(myPackage, in, block, inStyleable); 327 328 const String16 attr16("attr"); 329 const String16 id16("id"); 330 331 // Attribute type constants. 332 const String16 enum16("enum"); 333 const String16 flag16("flag"); 334 335 ResXMLTree::event_code_t code; 336 size_t len; 337 status_t err; 338 339 ssize_t identIdx = block.indexOfAttribute(NULL, "name"); 340 if (identIdx >= 0) { 341 attr.ident = String16(block.getAttributeStringValue(identIdx, &len)); 342 if (outIdent) { 343 *outIdent = attr.ident; 344 } 345 } else { 346 attr.sourcePos.error("A 'name' attribute is required for <attr>\n"); 347 attr.hasErrors = true; 348 } 349 350 attr.comment = String16( 351 block.getComment(&len) ? block.getComment(&len) : nulStr); 352 353 ssize_t typeIdx = block.indexOfAttribute(NULL, "format"); 354 if (typeIdx >= 0) { 355 String16 typeStr = String16(block.getAttributeStringValue(typeIdx, &len)); 356 attr.type = parse_flags(typeStr.string(), typeStr.size(), gFormatFlags); 357 if (attr.type == 0) { 358 attr.sourcePos.error("Tag <attr> 'format' attribute value \"%s\" not valid\n", 359 String8(typeStr).string()); 360 attr.hasErrors = true; 361 } 362 attr.createIfNeeded(outTable); 363 } else if (!inStyleable) { 364 // Attribute definitions outside of styleables always define the 365 // attribute as a generic value. 366 attr.createIfNeeded(outTable); 367 } 368 369 //printf("Attribute %s: type=0x%08x\n", String8(attr.ident).string(), attr.type); 370 371 ssize_t minIdx = block.indexOfAttribute(NULL, "min"); 372 if (minIdx >= 0) { 373 String16 val = String16(block.getAttributeStringValue(minIdx, &len)); 374 if (!ResTable::stringToInt(val.string(), val.size(), NULL)) { 375 attr.sourcePos.error("Tag <attr> 'min' attribute must be a number, not \"%s\"\n", 376 String8(val).string()); 377 attr.hasErrors = true; 378 } 379 attr.createIfNeeded(outTable); 380 if (!attr.hasErrors) { 381 err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident, 382 String16(""), String16("^min"), String16(val), NULL, NULL); 383 if (err != NO_ERROR) { 384 attr.hasErrors = true; 385 } 386 } 387 } 388 389 ssize_t maxIdx = block.indexOfAttribute(NULL, "max"); 390 if (maxIdx >= 0) { 391 String16 val = String16(block.getAttributeStringValue(maxIdx, &len)); 392 if (!ResTable::stringToInt(val.string(), val.size(), NULL)) { 393 attr.sourcePos.error("Tag <attr> 'max' attribute must be a number, not \"%s\"\n", 394 String8(val).string()); 395 attr.hasErrors = true; 396 } 397 attr.createIfNeeded(outTable); 398 if (!attr.hasErrors) { 399 err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident, 400 String16(""), String16("^max"), String16(val), NULL, NULL); 401 attr.hasErrors = true; 402 } 403 } 404 405 if ((minIdx >= 0 || maxIdx >= 0) && (attr.type&ResTable_map::TYPE_INTEGER) == 0) { 406 attr.sourcePos.error("Tag <attr> must have format=integer attribute if using max or min\n"); 407 attr.hasErrors = true; 408 } 409 410 ssize_t l10nIdx = block.indexOfAttribute(NULL, "localization"); 411 if (l10nIdx >= 0) { 412 const char16_t* str = block.getAttributeStringValue(l10nIdx, &len); 413 bool error; 414 uint32_t l10n_required = parse_flags(str, len, l10nRequiredFlags, &error); 415 if (error) { 416 attr.sourcePos.error("Tag <attr> 'localization' attribute value \"%s\" not valid\n", 417 String8(str).string()); 418 attr.hasErrors = true; 419 } 420 attr.createIfNeeded(outTable); 421 if (!attr.hasErrors) { 422 char buf[11]; 423 sprintf(buf, "%d", l10n_required); 424 err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident, 425 String16(""), String16("^l10n"), String16(buf), NULL, NULL); 426 if (err != NO_ERROR) { 427 attr.hasErrors = true; 428 } 429 } 430 } 431 432 String16 enumOrFlagsComment; 433 434 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) { 435 if (code == ResXMLTree::START_TAG) { 436 uint32_t localType = 0; 437 if (strcmp16(block.getElementName(&len), enum16.string()) == 0) { 438 localType = ResTable_map::TYPE_ENUM; 439 } else if (strcmp16(block.getElementName(&len), flag16.string()) == 0) { 440 localType = ResTable_map::TYPE_FLAGS; 441 } else { 442 SourcePos(in->getPrintableSource(), block.getLineNumber()) 443 .error("Tag <%s> can not appear inside <attr>, only <enum> or <flag>\n", 444 String8(block.getElementName(&len)).string()); 445 return UNKNOWN_ERROR; 446 } 447 448 attr.createIfNeeded(outTable); 449 450 if (attr.type == ResTable_map::TYPE_ANY) { 451 // No type was explicitly stated, so supplying enum tags 452 // implicitly creates an enum or flag. 453 attr.type = 0; 454 } 455 456 if ((attr.type&(ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS)) == 0) { 457 // Wasn't originally specified as an enum, so update its type. 458 attr.type |= localType; 459 if (!attr.hasErrors) { 460 char numberStr[16]; 461 sprintf(numberStr, "%d", attr.type); 462 err = outTable->addBag(SourcePos(in->getPrintableSource(), block.getLineNumber()), 463 myPackage, attr16, attr.ident, String16(""), 464 String16("^type"), String16(numberStr), NULL, NULL, true); 465 if (err != NO_ERROR) { 466 attr.hasErrors = true; 467 } 468 } 469 } else if ((uint32_t)(attr.type&(ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS)) != localType) { 470 if (localType == ResTable_map::TYPE_ENUM) { 471 SourcePos(in->getPrintableSource(), block.getLineNumber()) 472 .error("<enum> attribute can not be used inside a flags format\n"); 473 attr.hasErrors = true; 474 } else { 475 SourcePos(in->getPrintableSource(), block.getLineNumber()) 476 .error("<flag> attribute can not be used inside a enum format\n"); 477 attr.hasErrors = true; 478 } 479 } 480 481 String16 itemIdent; 482 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "name"); 483 if (itemIdentIdx >= 0) { 484 itemIdent = String16(block.getAttributeStringValue(itemIdentIdx, &len)); 485 } else { 486 SourcePos(in->getPrintableSource(), block.getLineNumber()) 487 .error("A 'name' attribute is required for <enum> or <flag>\n"); 488 attr.hasErrors = true; 489 } 490 491 String16 value; 492 ssize_t valueIdx = block.indexOfAttribute(NULL, "value"); 493 if (valueIdx >= 0) { 494 value = String16(block.getAttributeStringValue(valueIdx, &len)); 495 } else { 496 SourcePos(in->getPrintableSource(), block.getLineNumber()) 497 .error("A 'value' attribute is required for <enum> or <flag>\n"); 498 attr.hasErrors = true; 499 } 500 if (!attr.hasErrors && !ResTable::stringToInt(value.string(), value.size(), NULL)) { 501 SourcePos(in->getPrintableSource(), block.getLineNumber()) 502 .error("Tag <enum> or <flag> 'value' attribute must be a number," 503 " not \"%s\"\n", 504 String8(value).string()); 505 attr.hasErrors = true; 506 } 507 508 if (!attr.hasErrors) { 509 if (enumOrFlagsComment.size() == 0) { 510 enumOrFlagsComment.append(mayOrMust(attr.type, 511 ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS)); 512 enumOrFlagsComment.append((attr.type&ResTable_map::TYPE_ENUM) 513 ? String16(" be one of the following constant values.") 514 : String16(" be one or more (separated by '|') of the following constant values.")); 515 enumOrFlagsComment.append(String16("</p>\n<table>\n" 516 "<colgroup align=\"left\" />\n" 517 "<colgroup align=\"left\" />\n" 518 "<colgroup align=\"left\" />\n" 519 "<tr><th>Constant</th><th>Value</th><th>Description</th></tr>")); 520 } 521 522 enumOrFlagsComment.append(String16("\n<tr><td><code>")); 523 enumOrFlagsComment.append(itemIdent); 524 enumOrFlagsComment.append(String16("</code></td><td>")); 525 enumOrFlagsComment.append(value); 526 enumOrFlagsComment.append(String16("</td><td>")); 527 if (block.getComment(&len)) { 528 enumOrFlagsComment.append(String16(block.getComment(&len))); 529 } 530 enumOrFlagsComment.append(String16("</td></tr>")); 531 532 err = outTable->addBag(SourcePos(in->getPrintableSource(), block.getLineNumber()), 533 myPackage, 534 attr16, attr.ident, String16(""), 535 itemIdent, value, NULL, NULL, false, true); 536 if (err != NO_ERROR) { 537 attr.hasErrors = true; 538 } 539 } 540 } else if (code == ResXMLTree::END_TAG) { 541 if (strcmp16(block.getElementName(&len), attr16.string()) == 0) { 542 break; 543 } 544 if ((attr.type&ResTable_map::TYPE_ENUM) != 0) { 545 if (strcmp16(block.getElementName(&len), enum16.string()) != 0) { 546 SourcePos(in->getPrintableSource(), block.getLineNumber()) 547 .error("Found tag </%s> where </enum> is expected\n", 548 String8(block.getElementName(&len)).string()); 549 return UNKNOWN_ERROR; 550 } 551 } else { 552 if (strcmp16(block.getElementName(&len), flag16.string()) != 0) { 553 SourcePos(in->getPrintableSource(), block.getLineNumber()) 554 .error("Found tag </%s> where </flag> is expected\n", 555 String8(block.getElementName(&len)).string()); 556 return UNKNOWN_ERROR; 557 } 558 } 559 } 560 } 561 562 if (!attr.hasErrors && attr.added) { 563 appendTypeInfo(outTable, myPackage, attr16, attr.ident, attr.type, gFormatFlags); 564 } 565 566 if (!attr.hasErrors && enumOrFlagsComment.size() > 0) { 567 enumOrFlagsComment.append(String16("\n</table>")); 568 outTable->appendTypeComment(myPackage, attr16, attr.ident, enumOrFlagsComment); 569 } 570 571 572 return NO_ERROR; 573} 574 575bool localeIsDefined(const ResTable_config& config) 576{ 577 return config.locale == 0; 578} 579 580status_t parseAndAddBag(Bundle* bundle, 581 const sp<AaptFile>& in, 582 ResXMLTree* block, 583 const ResTable_config& config, 584 const String16& myPackage, 585 const String16& curType, 586 const String16& ident, 587 const String16& parentIdent, 588 const String16& itemIdent, 589 int32_t curFormat, 590 bool isFormatted, 591 const String16& /* product */, 592 PseudolocalizationMethod pseudolocalize, 593 const bool overwrite, 594 ResourceTable* outTable) 595{ 596 status_t err; 597 const String16 item16("item"); 598 599 String16 str; 600 Vector<StringPool::entry_style_span> spans; 601 err = parseStyledString(bundle, in->getPrintableSource().string(), 602 block, item16, &str, &spans, isFormatted, 603 pseudolocalize); 604 if (err != NO_ERROR) { 605 return err; 606 } 607 608 if (kIsDebug) { 609 printf("Adding resource bag entry l=%c%c c=%c%c orien=%d d=%d " 610 " pid=%s, bag=%s, id=%s: %s\n", 611 config.language[0], config.language[1], 612 config.country[0], config.country[1], 613 config.orientation, config.density, 614 String8(parentIdent).string(), 615 String8(ident).string(), 616 String8(itemIdent).string(), 617 String8(str).string()); 618 } 619 620 err = outTable->addBag(SourcePos(in->getPrintableSource(), block->getLineNumber()), 621 myPackage, curType, ident, parentIdent, itemIdent, str, 622 &spans, &config, overwrite, false, curFormat); 623 return err; 624} 625 626/* 627 * Returns true if needle is one of the elements in the comma-separated list 628 * haystack, false otherwise. 629 */ 630bool isInProductList(const String16& needle, const String16& haystack) { 631 const char16_t *needle2 = needle.string(); 632 const char16_t *haystack2 = haystack.string(); 633 size_t needlesize = needle.size(); 634 635 while (*haystack2 != '\0') { 636 if (strncmp16(haystack2, needle2, needlesize) == 0) { 637 if (haystack2[needlesize] == '\0' || haystack2[needlesize] == ',') { 638 return true; 639 } 640 } 641 642 while (*haystack2 != '\0' && *haystack2 != ',') { 643 haystack2++; 644 } 645 if (*haystack2 == ',') { 646 haystack2++; 647 } 648 } 649 650 return false; 651} 652 653/* 654 * A simple container that holds a resource type and name. It is ordered first by type then 655 * by name. 656 */ 657struct type_ident_pair_t { 658 String16 type; 659 String16 ident; 660 661 type_ident_pair_t() { }; 662 type_ident_pair_t(const String16& t, const String16& i) : type(t), ident(i) { } 663 type_ident_pair_t(const type_ident_pair_t& o) : type(o.type), ident(o.ident) { } 664 inline bool operator < (const type_ident_pair_t& o) const { 665 int cmp = compare_type(type, o.type); 666 if (cmp < 0) { 667 return true; 668 } else if (cmp > 0) { 669 return false; 670 } else { 671 return strictly_order_type(ident, o.ident); 672 } 673 } 674}; 675 676 677status_t parseAndAddEntry(Bundle* bundle, 678 const sp<AaptFile>& in, 679 ResXMLTree* block, 680 const ResTable_config& config, 681 const String16& myPackage, 682 const String16& curType, 683 const String16& ident, 684 const String16& curTag, 685 bool curIsStyled, 686 int32_t curFormat, 687 bool isFormatted, 688 const String16& product, 689 PseudolocalizationMethod pseudolocalize, 690 const bool overwrite, 691 KeyedVector<type_ident_pair_t, bool>* skippedResourceNames, 692 ResourceTable* outTable) 693{ 694 status_t err; 695 696 String16 str; 697 Vector<StringPool::entry_style_span> spans; 698 err = parseStyledString(bundle, in->getPrintableSource().string(), block, 699 curTag, &str, curIsStyled ? &spans : NULL, 700 isFormatted, pseudolocalize); 701 702 if (err < NO_ERROR) { 703 return err; 704 } 705 706 /* 707 * If a product type was specified on the command line 708 * and also in the string, and the two are not the same, 709 * return without adding the string. 710 */ 711 712 const char *bundleProduct = bundle->getProduct(); 713 if (bundleProduct == NULL) { 714 bundleProduct = ""; 715 } 716 717 if (product.size() != 0) { 718 /* 719 * If the command-line-specified product is empty, only "default" 720 * matches. Other variants are skipped. This is so generation 721 * of the R.java file when the product is not known is predictable. 722 */ 723 724 if (bundleProduct[0] == '\0') { 725 if (strcmp16(String16("default").string(), product.string()) != 0) { 726 /* 727 * This string has a product other than 'default'. Do not add it, 728 * but record it so that if we do not see the same string with 729 * product 'default' or no product, then report an error. 730 */ 731 skippedResourceNames->replaceValueFor( 732 type_ident_pair_t(curType, ident), true); 733 return NO_ERROR; 734 } 735 } else { 736 /* 737 * The command-line product is not empty. 738 * If the product for this string is on the command-line list, 739 * it matches. "default" also matches, but only if nothing 740 * else has matched already. 741 */ 742 743 if (isInProductList(product, String16(bundleProduct))) { 744 ; 745 } else if (strcmp16(String16("default").string(), product.string()) == 0 && 746 !outTable->hasBagOrEntry(myPackage, curType, ident, config)) { 747 ; 748 } else { 749 return NO_ERROR; 750 } 751 } 752 } 753 754 if (kIsDebug) { 755 printf("Adding resource entry l=%c%c c=%c%c orien=%d d=%d id=%s: %s\n", 756 config.language[0], config.language[1], 757 config.country[0], config.country[1], 758 config.orientation, config.density, 759 String8(ident).string(), String8(str).string()); 760 } 761 762 err = outTable->addEntry(SourcePos(in->getPrintableSource(), block->getLineNumber()), 763 myPackage, curType, ident, str, &spans, &config, 764 false, curFormat, overwrite); 765 766 return err; 767} 768 769status_t compileResourceFile(Bundle* bundle, 770 const sp<AaptAssets>& assets, 771 const sp<AaptFile>& in, 772 const ResTable_config& defParams, 773 const bool overwrite, 774 ResourceTable* outTable) 775{ 776 ResXMLTree block; 777 status_t err = parseXMLResource(in, &block, false, true); 778 if (err != NO_ERROR) { 779 return err; 780 } 781 782 // Top-level tag. 783 const String16 resources16("resources"); 784 785 // Identifier declaration tags. 786 const String16 declare_styleable16("declare-styleable"); 787 const String16 attr16("attr"); 788 789 // Data creation organizational tags. 790 const String16 string16("string"); 791 const String16 drawable16("drawable"); 792 const String16 color16("color"); 793 const String16 bool16("bool"); 794 const String16 integer16("integer"); 795 const String16 dimen16("dimen"); 796 const String16 fraction16("fraction"); 797 const String16 style16("style"); 798 const String16 plurals16("plurals"); 799 const String16 array16("array"); 800 const String16 string_array16("string-array"); 801 const String16 integer_array16("integer-array"); 802 const String16 public16("public"); 803 const String16 public_padding16("public-padding"); 804 const String16 private_symbols16("private-symbols"); 805 const String16 java_symbol16("java-symbol"); 806 const String16 add_resource16("add-resource"); 807 const String16 skip16("skip"); 808 const String16 eat_comment16("eat-comment"); 809 810 // Data creation tags. 811 const String16 bag16("bag"); 812 const String16 item16("item"); 813 814 // Attribute type constants. 815 const String16 enum16("enum"); 816 817 // plural values 818 const String16 other16("other"); 819 const String16 quantityOther16("^other"); 820 const String16 zero16("zero"); 821 const String16 quantityZero16("^zero"); 822 const String16 one16("one"); 823 const String16 quantityOne16("^one"); 824 const String16 two16("two"); 825 const String16 quantityTwo16("^two"); 826 const String16 few16("few"); 827 const String16 quantityFew16("^few"); 828 const String16 many16("many"); 829 const String16 quantityMany16("^many"); 830 831 // useful attribute names and special values 832 const String16 name16("name"); 833 const String16 translatable16("translatable"); 834 const String16 formatted16("formatted"); 835 const String16 false16("false"); 836 837 const String16 myPackage(assets->getPackage()); 838 839 bool hasErrors = false; 840 841 bool fileIsTranslatable = true; 842 if (strstr(in->getPrintableSource().string(), "donottranslate") != NULL) { 843 fileIsTranslatable = false; 844 } 845 846 DefaultKeyedVector<String16, uint32_t> nextPublicId(0); 847 848 // Stores the resource names that were skipped. Typically this happens when 849 // AAPT is invoked without a product specified and a resource has no 850 // 'default' product attribute. 851 KeyedVector<type_ident_pair_t, bool> skippedResourceNames; 852 853 ResXMLTree::event_code_t code; 854 do { 855 code = block.next(); 856 } while (code == ResXMLTree::START_NAMESPACE); 857 858 size_t len; 859 if (code != ResXMLTree::START_TAG) { 860 SourcePos(in->getPrintableSource(), block.getLineNumber()).error( 861 "No start tag found\n"); 862 return UNKNOWN_ERROR; 863 } 864 if (strcmp16(block.getElementName(&len), resources16.string()) != 0) { 865 SourcePos(in->getPrintableSource(), block.getLineNumber()).error( 866 "Invalid start tag %s\n", String8(block.getElementName(&len)).string()); 867 return UNKNOWN_ERROR; 868 } 869 870 ResTable_config curParams(defParams); 871 872 ResTable_config pseudoParams(curParams); 873 pseudoParams.language[0] = 'e'; 874 pseudoParams.language[1] = 'n'; 875 pseudoParams.country[0] = 'X'; 876 pseudoParams.country[1] = 'A'; 877 878 ResTable_config pseudoBidiParams(curParams); 879 pseudoBidiParams.language[0] = 'a'; 880 pseudoBidiParams.language[1] = 'r'; 881 pseudoBidiParams.country[0] = 'X'; 882 pseudoBidiParams.country[1] = 'B'; 883 884 // We should skip resources for pseudolocales if they were 885 // already added automatically. This is a fix for a transition period when 886 // manually pseudolocalized resources may be expected. 887 // TODO: remove this check after next SDK version release. 888 if ((bundle->getPseudolocalize() & PSEUDO_ACCENTED && 889 curParams.locale == pseudoParams.locale) || 890 (bundle->getPseudolocalize() & PSEUDO_BIDI && 891 curParams.locale == pseudoBidiParams.locale)) { 892 SourcePos(in->getPrintableSource(), 0).warning( 893 "Resource file %s is skipped as pseudolocalization" 894 " was done automatically.", 895 in->getPrintableSource().string()); 896 return NO_ERROR; 897 } 898 899 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) { 900 if (code == ResXMLTree::START_TAG) { 901 const String16* curTag = NULL; 902 String16 curType; 903 String16 curName; 904 int32_t curFormat = ResTable_map::TYPE_ANY; 905 bool curIsBag = false; 906 bool curIsBagReplaceOnOverwrite = false; 907 bool curIsStyled = false; 908 bool curIsPseudolocalizable = false; 909 bool curIsFormatted = fileIsTranslatable; 910 bool localHasErrors = false; 911 912 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) { 913 while ((code=block.next()) != ResXMLTree::END_DOCUMENT 914 && code != ResXMLTree::BAD_DOCUMENT) { 915 if (code == ResXMLTree::END_TAG) { 916 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) { 917 break; 918 } 919 } 920 } 921 continue; 922 923 } else if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) { 924 while ((code=block.next()) != ResXMLTree::END_DOCUMENT 925 && code != ResXMLTree::BAD_DOCUMENT) { 926 if (code == ResXMLTree::END_TAG) { 927 if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) { 928 break; 929 } 930 } 931 } 932 continue; 933 934 } else if (strcmp16(block.getElementName(&len), public16.string()) == 0) { 935 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber()); 936 937 String16 type; 938 ssize_t typeIdx = block.indexOfAttribute(NULL, "type"); 939 if (typeIdx < 0) { 940 srcPos.error("A 'type' attribute is required for <public>\n"); 941 hasErrors = localHasErrors = true; 942 } 943 type = String16(block.getAttributeStringValue(typeIdx, &len)); 944 945 String16 name; 946 ssize_t nameIdx = block.indexOfAttribute(NULL, "name"); 947 if (nameIdx < 0) { 948 srcPos.error("A 'name' attribute is required for <public>\n"); 949 hasErrors = localHasErrors = true; 950 } 951 name = String16(block.getAttributeStringValue(nameIdx, &len)); 952 953 uint32_t ident = 0; 954 ssize_t identIdx = block.indexOfAttribute(NULL, "id"); 955 if (identIdx >= 0) { 956 const char16_t* identStr = block.getAttributeStringValue(identIdx, &len); 957 Res_value identValue; 958 if (!ResTable::stringToInt(identStr, len, &identValue)) { 959 srcPos.error("Given 'id' attribute is not an integer: %s\n", 960 String8(block.getAttributeStringValue(identIdx, &len)).string()); 961 hasErrors = localHasErrors = true; 962 } else { 963 ident = identValue.data; 964 nextPublicId.replaceValueFor(type, ident+1); 965 } 966 } else if (nextPublicId.indexOfKey(type) < 0) { 967 srcPos.error("No 'id' attribute supplied <public>," 968 " and no previous id defined in this file.\n"); 969 hasErrors = localHasErrors = true; 970 } else if (!localHasErrors) { 971 ident = nextPublicId.valueFor(type); 972 nextPublicId.replaceValueFor(type, ident+1); 973 } 974 975 if (!localHasErrors) { 976 err = outTable->addPublic(srcPos, myPackage, type, name, ident); 977 if (err < NO_ERROR) { 978 hasErrors = localHasErrors = true; 979 } 980 } 981 if (!localHasErrors) { 982 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R")); 983 if (symbols != NULL) { 984 symbols = symbols->addNestedSymbol(String8(type), srcPos); 985 } 986 if (symbols != NULL) { 987 symbols->makeSymbolPublic(String8(name), srcPos); 988 String16 comment( 989 block.getComment(&len) ? block.getComment(&len) : nulStr); 990 symbols->appendComment(String8(name), comment, srcPos); 991 } else { 992 srcPos.error("Unable to create symbols!\n"); 993 hasErrors = localHasErrors = true; 994 } 995 } 996 997 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) { 998 if (code == ResXMLTree::END_TAG) { 999 if (strcmp16(block.getElementName(&len), public16.string()) == 0) { 1000 break; 1001 } 1002 } 1003 } 1004 continue; 1005 1006 } else if (strcmp16(block.getElementName(&len), public_padding16.string()) == 0) { 1007 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber()); 1008 1009 String16 type; 1010 ssize_t typeIdx = block.indexOfAttribute(NULL, "type"); 1011 if (typeIdx < 0) { 1012 srcPos.error("A 'type' attribute is required for <public-padding>\n"); 1013 hasErrors = localHasErrors = true; 1014 } 1015 type = String16(block.getAttributeStringValue(typeIdx, &len)); 1016 1017 String16 name; 1018 ssize_t nameIdx = block.indexOfAttribute(NULL, "name"); 1019 if (nameIdx < 0) { 1020 srcPos.error("A 'name' attribute is required for <public-padding>\n"); 1021 hasErrors = localHasErrors = true; 1022 } 1023 name = String16(block.getAttributeStringValue(nameIdx, &len)); 1024 1025 uint32_t start = 0; 1026 ssize_t startIdx = block.indexOfAttribute(NULL, "start"); 1027 if (startIdx >= 0) { 1028 const char16_t* startStr = block.getAttributeStringValue(startIdx, &len); 1029 Res_value startValue; 1030 if (!ResTable::stringToInt(startStr, len, &startValue)) { 1031 srcPos.error("Given 'start' attribute is not an integer: %s\n", 1032 String8(block.getAttributeStringValue(startIdx, &len)).string()); 1033 hasErrors = localHasErrors = true; 1034 } else { 1035 start = startValue.data; 1036 } 1037 } else if (nextPublicId.indexOfKey(type) < 0) { 1038 srcPos.error("No 'start' attribute supplied <public-padding>," 1039 " and no previous id defined in this file.\n"); 1040 hasErrors = localHasErrors = true; 1041 } else if (!localHasErrors) { 1042 start = nextPublicId.valueFor(type); 1043 } 1044 1045 uint32_t end = 0; 1046 ssize_t endIdx = block.indexOfAttribute(NULL, "end"); 1047 if (endIdx >= 0) { 1048 const char16_t* endStr = block.getAttributeStringValue(endIdx, &len); 1049 Res_value endValue; 1050 if (!ResTable::stringToInt(endStr, len, &endValue)) { 1051 srcPos.error("Given 'end' attribute is not an integer: %s\n", 1052 String8(block.getAttributeStringValue(endIdx, &len)).string()); 1053 hasErrors = localHasErrors = true; 1054 } else { 1055 end = endValue.data; 1056 } 1057 } else { 1058 srcPos.error("No 'end' attribute supplied <public-padding>\n"); 1059 hasErrors = localHasErrors = true; 1060 } 1061 1062 if (end >= start) { 1063 nextPublicId.replaceValueFor(type, end+1); 1064 } else { 1065 srcPos.error("Padding start '%ul' is after end '%ul'\n", 1066 start, end); 1067 hasErrors = localHasErrors = true; 1068 } 1069 1070 String16 comment( 1071 block.getComment(&len) ? block.getComment(&len) : nulStr); 1072 for (uint32_t curIdent=start; curIdent<=end; curIdent++) { 1073 if (localHasErrors) { 1074 break; 1075 } 1076 String16 curName(name); 1077 char buf[64]; 1078 sprintf(buf, "%d", (int)(end-curIdent+1)); 1079 curName.append(String16(buf)); 1080 1081 err = outTable->addEntry(srcPos, myPackage, type, curName, 1082 String16("padding"), NULL, &curParams, false, 1083 ResTable_map::TYPE_STRING, overwrite); 1084 if (err < NO_ERROR) { 1085 hasErrors = localHasErrors = true; 1086 break; 1087 } 1088 err = outTable->addPublic(srcPos, myPackage, type, 1089 curName, curIdent); 1090 if (err < NO_ERROR) { 1091 hasErrors = localHasErrors = true; 1092 break; 1093 } 1094 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R")); 1095 if (symbols != NULL) { 1096 symbols = symbols->addNestedSymbol(String8(type), srcPos); 1097 } 1098 if (symbols != NULL) { 1099 symbols->makeSymbolPublic(String8(curName), srcPos); 1100 symbols->appendComment(String8(curName), comment, srcPos); 1101 } else { 1102 srcPos.error("Unable to create symbols!\n"); 1103 hasErrors = localHasErrors = true; 1104 } 1105 } 1106 1107 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) { 1108 if (code == ResXMLTree::END_TAG) { 1109 if (strcmp16(block.getElementName(&len), public_padding16.string()) == 0) { 1110 break; 1111 } 1112 } 1113 } 1114 continue; 1115 1116 } else if (strcmp16(block.getElementName(&len), private_symbols16.string()) == 0) { 1117 String16 pkg; 1118 ssize_t pkgIdx = block.indexOfAttribute(NULL, "package"); 1119 if (pkgIdx < 0) { 1120 SourcePos(in->getPrintableSource(), block.getLineNumber()).error( 1121 "A 'package' attribute is required for <private-symbols>\n"); 1122 hasErrors = localHasErrors = true; 1123 } 1124 pkg = String16(block.getAttributeStringValue(pkgIdx, &len)); 1125 if (!localHasErrors) { 1126 SourcePos(in->getPrintableSource(), block.getLineNumber()).warning( 1127 "<private-symbols> is deprecated. Use the command line flag " 1128 "--private-symbols instead.\n"); 1129 if (assets->havePrivateSymbols()) { 1130 SourcePos(in->getPrintableSource(), block.getLineNumber()).warning( 1131 "private symbol package already specified. Ignoring...\n"); 1132 } else { 1133 assets->setSymbolsPrivatePackage(String8(pkg)); 1134 } 1135 } 1136 1137 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) { 1138 if (code == ResXMLTree::END_TAG) { 1139 if (strcmp16(block.getElementName(&len), private_symbols16.string()) == 0) { 1140 break; 1141 } 1142 } 1143 } 1144 continue; 1145 1146 } else if (strcmp16(block.getElementName(&len), java_symbol16.string()) == 0) { 1147 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber()); 1148 1149 String16 type; 1150 ssize_t typeIdx = block.indexOfAttribute(NULL, "type"); 1151 if (typeIdx < 0) { 1152 srcPos.error("A 'type' attribute is required for <public>\n"); 1153 hasErrors = localHasErrors = true; 1154 } 1155 type = String16(block.getAttributeStringValue(typeIdx, &len)); 1156 1157 String16 name; 1158 ssize_t nameIdx = block.indexOfAttribute(NULL, "name"); 1159 if (nameIdx < 0) { 1160 srcPos.error("A 'name' attribute is required for <public>\n"); 1161 hasErrors = localHasErrors = true; 1162 } 1163 name = String16(block.getAttributeStringValue(nameIdx, &len)); 1164 1165 sp<AaptSymbols> symbols = assets->getJavaSymbolsFor(String8("R")); 1166 if (symbols != NULL) { 1167 symbols = symbols->addNestedSymbol(String8(type), srcPos); 1168 } 1169 if (symbols != NULL) { 1170 symbols->makeSymbolJavaSymbol(String8(name), srcPos); 1171 String16 comment( 1172 block.getComment(&len) ? block.getComment(&len) : nulStr); 1173 symbols->appendComment(String8(name), comment, srcPos); 1174 } else { 1175 srcPos.error("Unable to create symbols!\n"); 1176 hasErrors = localHasErrors = true; 1177 } 1178 1179 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) { 1180 if (code == ResXMLTree::END_TAG) { 1181 if (strcmp16(block.getElementName(&len), java_symbol16.string()) == 0) { 1182 break; 1183 } 1184 } 1185 } 1186 continue; 1187 1188 1189 } else if (strcmp16(block.getElementName(&len), add_resource16.string()) == 0) { 1190 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber()); 1191 1192 String16 typeName; 1193 ssize_t typeIdx = block.indexOfAttribute(NULL, "type"); 1194 if (typeIdx < 0) { 1195 srcPos.error("A 'type' attribute is required for <add-resource>\n"); 1196 hasErrors = localHasErrors = true; 1197 } 1198 typeName = String16(block.getAttributeStringValue(typeIdx, &len)); 1199 1200 String16 name; 1201 ssize_t nameIdx = block.indexOfAttribute(NULL, "name"); 1202 if (nameIdx < 0) { 1203 srcPos.error("A 'name' attribute is required for <add-resource>\n"); 1204 hasErrors = localHasErrors = true; 1205 } 1206 name = String16(block.getAttributeStringValue(nameIdx, &len)); 1207 1208 outTable->canAddEntry(srcPos, myPackage, typeName, name); 1209 1210 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) { 1211 if (code == ResXMLTree::END_TAG) { 1212 if (strcmp16(block.getElementName(&len), add_resource16.string()) == 0) { 1213 break; 1214 } 1215 } 1216 } 1217 continue; 1218 1219 } else if (strcmp16(block.getElementName(&len), declare_styleable16.string()) == 0) { 1220 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber()); 1221 1222 String16 ident; 1223 ssize_t identIdx = block.indexOfAttribute(NULL, "name"); 1224 if (identIdx < 0) { 1225 srcPos.error("A 'name' attribute is required for <declare-styleable>\n"); 1226 hasErrors = localHasErrors = true; 1227 } 1228 ident = String16(block.getAttributeStringValue(identIdx, &len)); 1229 1230 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R")); 1231 if (!localHasErrors) { 1232 if (symbols != NULL) { 1233 symbols = symbols->addNestedSymbol(String8("styleable"), srcPos); 1234 } 1235 sp<AaptSymbols> styleSymbols = symbols; 1236 if (symbols != NULL) { 1237 symbols = symbols->addNestedSymbol(String8(ident), srcPos); 1238 } 1239 if (symbols == NULL) { 1240 srcPos.error("Unable to create symbols!\n"); 1241 return UNKNOWN_ERROR; 1242 } 1243 1244 String16 comment( 1245 block.getComment(&len) ? block.getComment(&len) : nulStr); 1246 styleSymbols->appendComment(String8(ident), comment, srcPos); 1247 } else { 1248 symbols = NULL; 1249 } 1250 1251 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) { 1252 if (code == ResXMLTree::START_TAG) { 1253 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) { 1254 while ((code=block.next()) != ResXMLTree::END_DOCUMENT 1255 && code != ResXMLTree::BAD_DOCUMENT) { 1256 if (code == ResXMLTree::END_TAG) { 1257 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) { 1258 break; 1259 } 1260 } 1261 } 1262 continue; 1263 } else if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) { 1264 while ((code=block.next()) != ResXMLTree::END_DOCUMENT 1265 && code != ResXMLTree::BAD_DOCUMENT) { 1266 if (code == ResXMLTree::END_TAG) { 1267 if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) { 1268 break; 1269 } 1270 } 1271 } 1272 continue; 1273 } else if (strcmp16(block.getElementName(&len), attr16.string()) != 0) { 1274 SourcePos(in->getPrintableSource(), block.getLineNumber()).error( 1275 "Tag <%s> can not appear inside <declare-styleable>, only <attr>\n", 1276 String8(block.getElementName(&len)).string()); 1277 return UNKNOWN_ERROR; 1278 } 1279 1280 String16 comment( 1281 block.getComment(&len) ? block.getComment(&len) : nulStr); 1282 String16 itemIdent; 1283 err = compileAttribute(in, block, myPackage, outTable, &itemIdent, true); 1284 if (err != NO_ERROR) { 1285 hasErrors = localHasErrors = true; 1286 } 1287 1288 if (symbols != NULL) { 1289 SourcePos srcPos(String8(in->getPrintableSource()), block.getLineNumber()); 1290 symbols->addSymbol(String8(itemIdent), 0, srcPos); 1291 symbols->appendComment(String8(itemIdent), comment, srcPos); 1292 //printf("Attribute %s comment: %s\n", String8(itemIdent).string(), 1293 // String8(comment).string()); 1294 } 1295 } else if (code == ResXMLTree::END_TAG) { 1296 if (strcmp16(block.getElementName(&len), declare_styleable16.string()) == 0) { 1297 break; 1298 } 1299 1300 SourcePos(in->getPrintableSource(), block.getLineNumber()).error( 1301 "Found tag </%s> where </attr> is expected\n", 1302 String8(block.getElementName(&len)).string()); 1303 return UNKNOWN_ERROR; 1304 } 1305 } 1306 continue; 1307 1308 } else if (strcmp16(block.getElementName(&len), attr16.string()) == 0) { 1309 err = compileAttribute(in, block, myPackage, outTable, NULL); 1310 if (err != NO_ERROR) { 1311 hasErrors = true; 1312 } 1313 continue; 1314 1315 } else if (strcmp16(block.getElementName(&len), item16.string()) == 0) { 1316 curTag = &item16; 1317 ssize_t attri = block.indexOfAttribute(NULL, "type"); 1318 if (attri >= 0) { 1319 curType = String16(block.getAttributeStringValue(attri, &len)); 1320 ssize_t nameIdx = block.indexOfAttribute(NULL, "name"); 1321 if (nameIdx >= 0) { 1322 curName = String16(block.getAttributeStringValue(nameIdx, &len)); 1323 } 1324 ssize_t formatIdx = block.indexOfAttribute(NULL, "format"); 1325 if (formatIdx >= 0) { 1326 String16 formatStr = String16(block.getAttributeStringValue( 1327 formatIdx, &len)); 1328 curFormat = parse_flags(formatStr.string(), formatStr.size(), 1329 gFormatFlags); 1330 if (curFormat == 0) { 1331 SourcePos(in->getPrintableSource(), block.getLineNumber()).error( 1332 "Tag <item> 'format' attribute value \"%s\" not valid\n", 1333 String8(formatStr).string()); 1334 hasErrors = localHasErrors = true; 1335 } 1336 } 1337 } else { 1338 SourcePos(in->getPrintableSource(), block.getLineNumber()).error( 1339 "A 'type' attribute is required for <item>\n"); 1340 hasErrors = localHasErrors = true; 1341 } 1342 curIsStyled = true; 1343 } else if (strcmp16(block.getElementName(&len), string16.string()) == 0) { 1344 // Note the existence and locale of every string we process 1345 char rawLocale[RESTABLE_MAX_LOCALE_LEN]; 1346 curParams.getBcp47Locale(rawLocale); 1347 String8 locale(rawLocale); 1348 String16 name; 1349 String16 translatable; 1350 String16 formatted; 1351 1352 size_t n = block.getAttributeCount(); 1353 for (size_t i = 0; i < n; i++) { 1354 size_t length; 1355 const char16_t* attr = block.getAttributeName(i, &length); 1356 if (strcmp16(attr, name16.string()) == 0) { 1357 name.setTo(block.getAttributeStringValue(i, &length)); 1358 } else if (strcmp16(attr, translatable16.string()) == 0) { 1359 translatable.setTo(block.getAttributeStringValue(i, &length)); 1360 } else if (strcmp16(attr, formatted16.string()) == 0) { 1361 formatted.setTo(block.getAttributeStringValue(i, &length)); 1362 } 1363 } 1364 1365 if (name.size() > 0) { 1366 if (locale.size() == 0) { 1367 outTable->addDefaultLocalization(name); 1368 } 1369 if (translatable == false16) { 1370 curIsFormatted = false; 1371 // Untranslatable strings must only exist in the default [empty] locale 1372 if (locale.size() > 0) { 1373 SourcePos(in->getPrintableSource(), block.getLineNumber()).warning( 1374 "string '%s' marked untranslatable but exists in locale '%s'\n", 1375 String8(name).string(), 1376 locale.string()); 1377 // hasErrors = localHasErrors = true; 1378 } else { 1379 // Intentionally empty block: 1380 // 1381 // Don't add untranslatable strings to the localization table; that 1382 // way if we later see localizations of them, they'll be flagged as 1383 // having no default translation. 1384 } 1385 } else { 1386 outTable->addLocalization( 1387 name, 1388 locale, 1389 SourcePos(in->getPrintableSource(), block.getLineNumber())); 1390 } 1391 1392 if (formatted == false16) { 1393 curIsFormatted = false; 1394 } 1395 } 1396 1397 curTag = &string16; 1398 curType = string16; 1399 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING; 1400 curIsStyled = true; 1401 curIsPseudolocalizable = fileIsTranslatable && (translatable != false16); 1402 } else if (strcmp16(block.getElementName(&len), drawable16.string()) == 0) { 1403 curTag = &drawable16; 1404 curType = drawable16; 1405 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR; 1406 } else if (strcmp16(block.getElementName(&len), color16.string()) == 0) { 1407 curTag = &color16; 1408 curType = color16; 1409 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR; 1410 } else if (strcmp16(block.getElementName(&len), bool16.string()) == 0) { 1411 curTag = &bool16; 1412 curType = bool16; 1413 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_BOOLEAN; 1414 } else if (strcmp16(block.getElementName(&len), integer16.string()) == 0) { 1415 curTag = &integer16; 1416 curType = integer16; 1417 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER; 1418 } else if (strcmp16(block.getElementName(&len), dimen16.string()) == 0) { 1419 curTag = &dimen16; 1420 curType = dimen16; 1421 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_DIMENSION; 1422 } else if (strcmp16(block.getElementName(&len), fraction16.string()) == 0) { 1423 curTag = &fraction16; 1424 curType = fraction16; 1425 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_FRACTION; 1426 } else if (strcmp16(block.getElementName(&len), bag16.string()) == 0) { 1427 curTag = &bag16; 1428 curIsBag = true; 1429 ssize_t attri = block.indexOfAttribute(NULL, "type"); 1430 if (attri >= 0) { 1431 curType = String16(block.getAttributeStringValue(attri, &len)); 1432 } else { 1433 SourcePos(in->getPrintableSource(), block.getLineNumber()).error( 1434 "A 'type' attribute is required for <bag>\n"); 1435 hasErrors = localHasErrors = true; 1436 } 1437 } else if (strcmp16(block.getElementName(&len), style16.string()) == 0) { 1438 curTag = &style16; 1439 curType = style16; 1440 curIsBag = true; 1441 } else if (strcmp16(block.getElementName(&len), plurals16.string()) == 0) { 1442 curTag = &plurals16; 1443 curType = plurals16; 1444 curIsBag = true; 1445 curIsPseudolocalizable = fileIsTranslatable; 1446 } else if (strcmp16(block.getElementName(&len), array16.string()) == 0) { 1447 curTag = &array16; 1448 curType = array16; 1449 curIsBag = true; 1450 curIsBagReplaceOnOverwrite = true; 1451 ssize_t formatIdx = block.indexOfAttribute(NULL, "format"); 1452 if (formatIdx >= 0) { 1453 String16 formatStr = String16(block.getAttributeStringValue( 1454 formatIdx, &len)); 1455 curFormat = parse_flags(formatStr.string(), formatStr.size(), 1456 gFormatFlags); 1457 if (curFormat == 0) { 1458 SourcePos(in->getPrintableSource(), block.getLineNumber()).error( 1459 "Tag <array> 'format' attribute value \"%s\" not valid\n", 1460 String8(formatStr).string()); 1461 hasErrors = localHasErrors = true; 1462 } 1463 } 1464 } else if (strcmp16(block.getElementName(&len), string_array16.string()) == 0) { 1465 // Check whether these strings need valid formats. 1466 // (simplified form of what string16 does above) 1467 bool isTranslatable = false; 1468 size_t n = block.getAttributeCount(); 1469 1470 // Pseudolocalizable by default, unless this string array isn't 1471 // translatable. 1472 for (size_t i = 0; i < n; i++) { 1473 size_t length; 1474 const char16_t* attr = block.getAttributeName(i, &length); 1475 if (strcmp16(attr, formatted16.string()) == 0) { 1476 const char16_t* value = block.getAttributeStringValue(i, &length); 1477 if (strcmp16(value, false16.string()) == 0) { 1478 curIsFormatted = false; 1479 } 1480 } else if (strcmp16(attr, translatable16.string()) == 0) { 1481 const char16_t* value = block.getAttributeStringValue(i, &length); 1482 if (strcmp16(value, false16.string()) == 0) { 1483 isTranslatable = false; 1484 } 1485 } 1486 } 1487 1488 curTag = &string_array16; 1489 curType = array16; 1490 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING; 1491 curIsBag = true; 1492 curIsBagReplaceOnOverwrite = true; 1493 curIsPseudolocalizable = isTranslatable && fileIsTranslatable; 1494 } else if (strcmp16(block.getElementName(&len), integer_array16.string()) == 0) { 1495 curTag = &integer_array16; 1496 curType = array16; 1497 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER; 1498 curIsBag = true; 1499 curIsBagReplaceOnOverwrite = true; 1500 } else { 1501 SourcePos(in->getPrintableSource(), block.getLineNumber()).error( 1502 "Found tag %s where item is expected\n", 1503 String8(block.getElementName(&len)).string()); 1504 return UNKNOWN_ERROR; 1505 } 1506 1507 String16 ident; 1508 ssize_t identIdx = block.indexOfAttribute(NULL, "name"); 1509 if (identIdx >= 0) { 1510 ident = String16(block.getAttributeStringValue(identIdx, &len)); 1511 } else { 1512 SourcePos(in->getPrintableSource(), block.getLineNumber()).error( 1513 "A 'name' attribute is required for <%s>\n", 1514 String8(*curTag).string()); 1515 hasErrors = localHasErrors = true; 1516 } 1517 1518 String16 product; 1519 identIdx = block.indexOfAttribute(NULL, "product"); 1520 if (identIdx >= 0) { 1521 product = String16(block.getAttributeStringValue(identIdx, &len)); 1522 } 1523 1524 String16 comment(block.getComment(&len) ? block.getComment(&len) : nulStr); 1525 1526 if (curIsBag) { 1527 // Figure out the parent of this bag... 1528 String16 parentIdent; 1529 ssize_t parentIdentIdx = block.indexOfAttribute(NULL, "parent"); 1530 if (parentIdentIdx >= 0) { 1531 parentIdent = String16(block.getAttributeStringValue(parentIdentIdx, &len)); 1532 } else { 1533 ssize_t sep = ident.findLast('.'); 1534 if (sep >= 0) { 1535 parentIdent.setTo(ident, sep); 1536 } 1537 } 1538 1539 if (!localHasErrors) { 1540 err = outTable->startBag(SourcePos(in->getPrintableSource(), 1541 block.getLineNumber()), myPackage, curType, ident, 1542 parentIdent, &curParams, 1543 overwrite, curIsBagReplaceOnOverwrite); 1544 if (err != NO_ERROR) { 1545 hasErrors = localHasErrors = true; 1546 } 1547 } 1548 1549 ssize_t elmIndex = 0; 1550 char elmIndexStr[14]; 1551 while ((code=block.next()) != ResXMLTree::END_DOCUMENT 1552 && code != ResXMLTree::BAD_DOCUMENT) { 1553 1554 if (code == ResXMLTree::START_TAG) { 1555 if (strcmp16(block.getElementName(&len), item16.string()) != 0) { 1556 SourcePos(in->getPrintableSource(), block.getLineNumber()).error( 1557 "Tag <%s> can not appear inside <%s>, only <item>\n", 1558 String8(block.getElementName(&len)).string(), 1559 String8(*curTag).string()); 1560 return UNKNOWN_ERROR; 1561 } 1562 1563 String16 itemIdent; 1564 if (curType == array16) { 1565 sprintf(elmIndexStr, "^index_%d", (int)elmIndex++); 1566 itemIdent = String16(elmIndexStr); 1567 } else if (curType == plurals16) { 1568 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "quantity"); 1569 if (itemIdentIdx >= 0) { 1570 String16 quantity16(block.getAttributeStringValue(itemIdentIdx, &len)); 1571 if (quantity16 == other16) { 1572 itemIdent = quantityOther16; 1573 } 1574 else if (quantity16 == zero16) { 1575 itemIdent = quantityZero16; 1576 } 1577 else if (quantity16 == one16) { 1578 itemIdent = quantityOne16; 1579 } 1580 else if (quantity16 == two16) { 1581 itemIdent = quantityTwo16; 1582 } 1583 else if (quantity16 == few16) { 1584 itemIdent = quantityFew16; 1585 } 1586 else if (quantity16 == many16) { 1587 itemIdent = quantityMany16; 1588 } 1589 else { 1590 SourcePos(in->getPrintableSource(), block.getLineNumber()).error( 1591 "Illegal 'quantity' attribute is <item> inside <plurals>\n"); 1592 hasErrors = localHasErrors = true; 1593 } 1594 } else { 1595 SourcePos(in->getPrintableSource(), block.getLineNumber()).error( 1596 "A 'quantity' attribute is required for <item> inside <plurals>\n"); 1597 hasErrors = localHasErrors = true; 1598 } 1599 } else { 1600 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "name"); 1601 if (itemIdentIdx >= 0) { 1602 itemIdent = String16(block.getAttributeStringValue(itemIdentIdx, &len)); 1603 } else { 1604 SourcePos(in->getPrintableSource(), block.getLineNumber()).error( 1605 "A 'name' attribute is required for <item>\n"); 1606 hasErrors = localHasErrors = true; 1607 } 1608 } 1609 1610 ResXMLParser::ResXMLPosition parserPosition; 1611 block.getPosition(&parserPosition); 1612 1613 err = parseAndAddBag(bundle, in, &block, curParams, myPackage, curType, 1614 ident, parentIdent, itemIdent, curFormat, curIsFormatted, 1615 product, NO_PSEUDOLOCALIZATION, overwrite, outTable); 1616 if (err == NO_ERROR) { 1617 if (curIsPseudolocalizable && localeIsDefined(curParams) 1618 && bundle->getPseudolocalize() > 0) { 1619 // pseudolocalize here 1620 if ((PSEUDO_ACCENTED & bundle->getPseudolocalize()) == 1621 PSEUDO_ACCENTED) { 1622 block.setPosition(parserPosition); 1623 err = parseAndAddBag(bundle, in, &block, pseudoParams, myPackage, 1624 curType, ident, parentIdent, itemIdent, curFormat, 1625 curIsFormatted, product, PSEUDO_ACCENTED, 1626 overwrite, outTable); 1627 } 1628 if ((PSEUDO_BIDI & bundle->getPseudolocalize()) == 1629 PSEUDO_BIDI) { 1630 block.setPosition(parserPosition); 1631 err = parseAndAddBag(bundle, in, &block, pseudoBidiParams, myPackage, 1632 curType, ident, parentIdent, itemIdent, curFormat, 1633 curIsFormatted, product, PSEUDO_BIDI, 1634 overwrite, outTable); 1635 } 1636 } 1637 } 1638 if (err != NO_ERROR) { 1639 hasErrors = localHasErrors = true; 1640 } 1641 } else if (code == ResXMLTree::END_TAG) { 1642 if (strcmp16(block.getElementName(&len), curTag->string()) != 0) { 1643 SourcePos(in->getPrintableSource(), block.getLineNumber()).error( 1644 "Found tag </%s> where </%s> is expected\n", 1645 String8(block.getElementName(&len)).string(), 1646 String8(*curTag).string()); 1647 return UNKNOWN_ERROR; 1648 } 1649 break; 1650 } 1651 } 1652 } else { 1653 ResXMLParser::ResXMLPosition parserPosition; 1654 block.getPosition(&parserPosition); 1655 1656 err = parseAndAddEntry(bundle, in, &block, curParams, myPackage, curType, ident, 1657 *curTag, curIsStyled, curFormat, curIsFormatted, 1658 product, NO_PSEUDOLOCALIZATION, overwrite, &skippedResourceNames, outTable); 1659 1660 if (err < NO_ERROR) { // Why err < NO_ERROR instead of err != NO_ERROR? 1661 hasErrors = localHasErrors = true; 1662 } 1663 else if (err == NO_ERROR) { 1664 if (curType == string16 && !curParams.language[0] && !curParams.country[0]) { 1665 outTable->addDefaultLocalization(curName); 1666 } 1667 if (curIsPseudolocalizable && localeIsDefined(curParams) 1668 && bundle->getPseudolocalize() > 0) { 1669 // pseudolocalize here 1670 if ((PSEUDO_ACCENTED & bundle->getPseudolocalize()) == 1671 PSEUDO_ACCENTED) { 1672 block.setPosition(parserPosition); 1673 err = parseAndAddEntry(bundle, in, &block, pseudoParams, myPackage, curType, 1674 ident, *curTag, curIsStyled, curFormat, 1675 curIsFormatted, product, 1676 PSEUDO_ACCENTED, overwrite, &skippedResourceNames, outTable); 1677 } 1678 if ((PSEUDO_BIDI & bundle->getPseudolocalize()) == 1679 PSEUDO_BIDI) { 1680 block.setPosition(parserPosition); 1681 err = parseAndAddEntry(bundle, in, &block, pseudoBidiParams, 1682 myPackage, curType, ident, *curTag, curIsStyled, curFormat, 1683 curIsFormatted, product, 1684 PSEUDO_BIDI, overwrite, &skippedResourceNames, outTable); 1685 } 1686 if (err != NO_ERROR) { 1687 hasErrors = localHasErrors = true; 1688 } 1689 } 1690 } 1691 } 1692 1693#if 0 1694 if (comment.size() > 0) { 1695 printf("Comment for @%s:%s/%s: %s\n", String8(myPackage).string(), 1696 String8(curType).string(), String8(ident).string(), 1697 String8(comment).string()); 1698 } 1699#endif 1700 if (!localHasErrors) { 1701 outTable->appendComment(myPackage, curType, ident, comment, false); 1702 } 1703 } 1704 else if (code == ResXMLTree::END_TAG) { 1705 if (strcmp16(block.getElementName(&len), resources16.string()) != 0) { 1706 SourcePos(in->getPrintableSource(), block.getLineNumber()).error( 1707 "Unexpected end tag %s\n", String8(block.getElementName(&len)).string()); 1708 return UNKNOWN_ERROR; 1709 } 1710 } 1711 else if (code == ResXMLTree::START_NAMESPACE || code == ResXMLTree::END_NAMESPACE) { 1712 } 1713 else if (code == ResXMLTree::TEXT) { 1714 if (isWhitespace(block.getText(&len))) { 1715 continue; 1716 } 1717 SourcePos(in->getPrintableSource(), block.getLineNumber()).error( 1718 "Found text \"%s\" where item tag is expected\n", 1719 String8(block.getText(&len)).string()); 1720 return UNKNOWN_ERROR; 1721 } 1722 } 1723 1724 // For every resource defined, there must be exist one variant with a product attribute 1725 // set to 'default' (or no product attribute at all). 1726 // We check to see that for every resource that was ignored because of a mismatched 1727 // product attribute, some product variant of that resource was processed. 1728 for (size_t i = 0; i < skippedResourceNames.size(); i++) { 1729 if (skippedResourceNames[i]) { 1730 const type_ident_pair_t& p = skippedResourceNames.keyAt(i); 1731 if (!outTable->hasBagOrEntry(myPackage, p.type, p.ident)) { 1732 const char* bundleProduct = 1733 (bundle->getProduct() == NULL) ? "" : bundle->getProduct(); 1734 fprintf(stderr, "In resource file %s: %s\n", 1735 in->getPrintableSource().string(), 1736 curParams.toString().string()); 1737 1738 fprintf(stderr, "\t%s '%s' does not match product %s.\n" 1739 "\tYou may have forgotten to include a 'default' product variant" 1740 " of the resource.\n", 1741 String8(p.type).string(), String8(p.ident).string(), 1742 bundleProduct[0] == 0 ? "default" : bundleProduct); 1743 return UNKNOWN_ERROR; 1744 } 1745 } 1746 } 1747 1748 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR; 1749} 1750 1751ResourceTable::ResourceTable(Bundle* bundle, const String16& assetsPackage, ResourceTable::PackageType type) 1752 : mAssetsPackage(assetsPackage) 1753 , mPackageType(type) 1754 , mTypeIdOffset(0) 1755 , mNumLocal(0) 1756 , mBundle(bundle) 1757{ 1758 ssize_t packageId = -1; 1759 switch (mPackageType) { 1760 case App: 1761 case AppFeature: 1762 packageId = 0x7f; 1763 break; 1764 1765 case System: 1766 packageId = 0x01; 1767 break; 1768 1769 case SharedLibrary: 1770 packageId = 0x00; 1771 break; 1772 1773 default: 1774 assert(0); 1775 break; 1776 } 1777 sp<Package> package = new Package(mAssetsPackage, packageId); 1778 mPackages.add(assetsPackage, package); 1779 mOrderedPackages.add(package); 1780 1781 // Every resource table always has one first entry, the bag attributes. 1782 const SourcePos unknown(String8("????"), 0); 1783 getType(mAssetsPackage, String16("attr"), unknown); 1784} 1785 1786static uint32_t findLargestTypeIdForPackage(const ResTable& table, const String16& packageName) { 1787 const size_t basePackageCount = table.getBasePackageCount(); 1788 for (size_t i = 0; i < basePackageCount; i++) { 1789 if (packageName == table.getBasePackageName(i)) { 1790 return table.getLastTypeIdForPackage(i); 1791 } 1792 } 1793 return 0; 1794} 1795 1796status_t ResourceTable::addIncludedResources(Bundle* bundle, const sp<AaptAssets>& assets) 1797{ 1798 status_t err = assets->buildIncludedResources(bundle); 1799 if (err != NO_ERROR) { 1800 return err; 1801 } 1802 1803 mAssets = assets; 1804 mTypeIdOffset = findLargestTypeIdForPackage(assets->getIncludedResources(), mAssetsPackage); 1805 1806 const String8& featureAfter = bundle->getFeatureAfterPackage(); 1807 if (!featureAfter.isEmpty()) { 1808 AssetManager featureAssetManager; 1809 if (!featureAssetManager.addAssetPath(featureAfter, NULL)) { 1810 fprintf(stderr, "ERROR: Feature package '%s' not found.\n", 1811 featureAfter.string()); 1812 return UNKNOWN_ERROR; 1813 } 1814 1815 const ResTable& featureTable = featureAssetManager.getResources(false); 1816 mTypeIdOffset = std::max(mTypeIdOffset, 1817 findLargestTypeIdForPackage(featureTable, mAssetsPackage)); 1818 } 1819 1820 return NO_ERROR; 1821} 1822 1823status_t ResourceTable::addPublic(const SourcePos& sourcePos, 1824 const String16& package, 1825 const String16& type, 1826 const String16& name, 1827 const uint32_t ident) 1828{ 1829 uint32_t rid = mAssets->getIncludedResources() 1830 .identifierForName(name.string(), name.size(), 1831 type.string(), type.size(), 1832 package.string(), package.size()); 1833 if (rid != 0) { 1834 sourcePos.error("Error declaring public resource %s/%s for included package %s\n", 1835 String8(type).string(), String8(name).string(), 1836 String8(package).string()); 1837 return UNKNOWN_ERROR; 1838 } 1839 1840 sp<Type> t = getType(package, type, sourcePos); 1841 if (t == NULL) { 1842 return UNKNOWN_ERROR; 1843 } 1844 return t->addPublic(sourcePos, name, ident); 1845} 1846 1847status_t ResourceTable::addEntry(const SourcePos& sourcePos, 1848 const String16& package, 1849 const String16& type, 1850 const String16& name, 1851 const String16& value, 1852 const Vector<StringPool::entry_style_span>* style, 1853 const ResTable_config* params, 1854 const bool doSetIndex, 1855 const int32_t format, 1856 const bool overwrite) 1857{ 1858 uint32_t rid = mAssets->getIncludedResources() 1859 .identifierForName(name.string(), name.size(), 1860 type.string(), type.size(), 1861 package.string(), package.size()); 1862 if (rid != 0) { 1863 sourcePos.error("Resource entry %s/%s is already defined in package %s.", 1864 String8(type).string(), String8(name).string(), String8(package).string()); 1865 return UNKNOWN_ERROR; 1866 } 1867 1868 sp<Entry> e = getEntry(package, type, name, sourcePos, overwrite, 1869 params, doSetIndex); 1870 if (e == NULL) { 1871 return UNKNOWN_ERROR; 1872 } 1873 status_t err = e->setItem(sourcePos, value, style, format, overwrite); 1874 if (err == NO_ERROR) { 1875 mNumLocal++; 1876 } 1877 return err; 1878} 1879 1880status_t ResourceTable::startBag(const SourcePos& sourcePos, 1881 const String16& package, 1882 const String16& type, 1883 const String16& name, 1884 const String16& bagParent, 1885 const ResTable_config* params, 1886 bool overlay, 1887 bool replace, bool /* isId */) 1888{ 1889 status_t result = NO_ERROR; 1890 1891 // Check for adding entries in other packages... for now we do 1892 // nothing. We need to do the right thing here to support skinning. 1893 uint32_t rid = mAssets->getIncludedResources() 1894 .identifierForName(name.string(), name.size(), 1895 type.string(), type.size(), 1896 package.string(), package.size()); 1897 if (rid != 0) { 1898 sourcePos.error("Resource entry %s/%s is already defined in package %s.", 1899 String8(type).string(), String8(name).string(), String8(package).string()); 1900 return UNKNOWN_ERROR; 1901 } 1902 1903 if (overlay && !mBundle->getAutoAddOverlay() && !hasBagOrEntry(package, type, name)) { 1904 bool canAdd = false; 1905 sp<Package> p = mPackages.valueFor(package); 1906 if (p != NULL) { 1907 sp<Type> t = p->getTypes().valueFor(type); 1908 if (t != NULL) { 1909 if (t->getCanAddEntries().indexOf(name) >= 0) { 1910 canAdd = true; 1911 } 1912 } 1913 } 1914 if (!canAdd) { 1915 sourcePos.error("Resource does not already exist in overlay at '%s'; use <add-resource> to add.\n", 1916 String8(name).string()); 1917 return UNKNOWN_ERROR; 1918 } 1919 } 1920 sp<Entry> e = getEntry(package, type, name, sourcePos, overlay, params); 1921 if (e == NULL) { 1922 return UNKNOWN_ERROR; 1923 } 1924 1925 // If a parent is explicitly specified, set it. 1926 if (bagParent.size() > 0) { 1927 e->setParent(bagParent); 1928 } 1929 1930 if ((result = e->makeItABag(sourcePos)) != NO_ERROR) { 1931 return result; 1932 } 1933 1934 if (overlay && replace) { 1935 return e->emptyBag(sourcePos); 1936 } 1937 return result; 1938} 1939 1940status_t ResourceTable::addBag(const SourcePos& sourcePos, 1941 const String16& package, 1942 const String16& type, 1943 const String16& name, 1944 const String16& bagParent, 1945 const String16& bagKey, 1946 const String16& value, 1947 const Vector<StringPool::entry_style_span>* style, 1948 const ResTable_config* params, 1949 bool replace, bool isId, const int32_t format) 1950{ 1951 // Check for adding entries in other packages... for now we do 1952 // nothing. We need to do the right thing here to support skinning. 1953 uint32_t rid = mAssets->getIncludedResources() 1954 .identifierForName(name.string(), name.size(), 1955 type.string(), type.size(), 1956 package.string(), package.size()); 1957 if (rid != 0) { 1958 return NO_ERROR; 1959 } 1960 1961#if 0 1962 if (name == String16("left")) { 1963 printf("Adding bag left: file=%s, line=%d, type=%s\n", 1964 sourcePos.file.striing(), sourcePos.line, String8(type).string()); 1965 } 1966#endif 1967 sp<Entry> e = getEntry(package, type, name, sourcePos, replace, params); 1968 if (e == NULL) { 1969 return UNKNOWN_ERROR; 1970 } 1971 1972 // If a parent is explicitly specified, set it. 1973 if (bagParent.size() > 0) { 1974 e->setParent(bagParent); 1975 } 1976 1977 const bool first = e->getBag().indexOfKey(bagKey) < 0; 1978 status_t err = e->addToBag(sourcePos, bagKey, value, style, replace, isId, format); 1979 if (err == NO_ERROR && first) { 1980 mNumLocal++; 1981 } 1982 return err; 1983} 1984 1985bool ResourceTable::hasBagOrEntry(const String16& package, 1986 const String16& type, 1987 const String16& name) const 1988{ 1989 // First look for this in the included resources... 1990 uint32_t rid = mAssets->getIncludedResources() 1991 .identifierForName(name.string(), name.size(), 1992 type.string(), type.size(), 1993 package.string(), package.size()); 1994 if (rid != 0) { 1995 return true; 1996 } 1997 1998 sp<Package> p = mPackages.valueFor(package); 1999 if (p != NULL) { 2000 sp<Type> t = p->getTypes().valueFor(type); 2001 if (t != NULL) { 2002 sp<ConfigList> c = t->getConfigs().valueFor(name); 2003 if (c != NULL) return true; 2004 } 2005 } 2006 2007 return false; 2008} 2009 2010bool ResourceTable::hasBagOrEntry(const String16& package, 2011 const String16& type, 2012 const String16& name, 2013 const ResTable_config& config) const 2014{ 2015 // First look for this in the included resources... 2016 uint32_t rid = mAssets->getIncludedResources() 2017 .identifierForName(name.string(), name.size(), 2018 type.string(), type.size(), 2019 package.string(), package.size()); 2020 if (rid != 0) { 2021 return true; 2022 } 2023 2024 sp<Package> p = mPackages.valueFor(package); 2025 if (p != NULL) { 2026 sp<Type> t = p->getTypes().valueFor(type); 2027 if (t != NULL) { 2028 sp<ConfigList> c = t->getConfigs().valueFor(name); 2029 if (c != NULL) { 2030 sp<Entry> e = c->getEntries().valueFor(config); 2031 if (e != NULL) { 2032 return true; 2033 } 2034 } 2035 } 2036 } 2037 2038 return false; 2039} 2040 2041bool ResourceTable::hasBagOrEntry(const String16& ref, 2042 const String16* defType, 2043 const String16* defPackage) 2044{ 2045 String16 package, type, name; 2046 if (!ResTable::expandResourceRef(ref.string(), ref.size(), &package, &type, &name, 2047 defType, defPackage ? defPackage:&mAssetsPackage, NULL)) { 2048 return false; 2049 } 2050 return hasBagOrEntry(package, type, name); 2051} 2052 2053bool ResourceTable::appendComment(const String16& package, 2054 const String16& type, 2055 const String16& name, 2056 const String16& comment, 2057 bool onlyIfEmpty) 2058{ 2059 if (comment.size() <= 0) { 2060 return true; 2061 } 2062 2063 sp<Package> p = mPackages.valueFor(package); 2064 if (p != NULL) { 2065 sp<Type> t = p->getTypes().valueFor(type); 2066 if (t != NULL) { 2067 sp<ConfigList> c = t->getConfigs().valueFor(name); 2068 if (c != NULL) { 2069 c->appendComment(comment, onlyIfEmpty); 2070 return true; 2071 } 2072 } 2073 } 2074 return false; 2075} 2076 2077bool ResourceTable::appendTypeComment(const String16& package, 2078 const String16& type, 2079 const String16& name, 2080 const String16& comment) 2081{ 2082 if (comment.size() <= 0) { 2083 return true; 2084 } 2085 2086 sp<Package> p = mPackages.valueFor(package); 2087 if (p != NULL) { 2088 sp<Type> t = p->getTypes().valueFor(type); 2089 if (t != NULL) { 2090 sp<ConfigList> c = t->getConfigs().valueFor(name); 2091 if (c != NULL) { 2092 c->appendTypeComment(comment); 2093 return true; 2094 } 2095 } 2096 } 2097 return false; 2098} 2099 2100bool ResourceTable::makeAttribute(const String16& package, 2101 const String16& name, 2102 const SourcePos& source, 2103 int32_t format, 2104 const String16& comment, 2105 bool shouldAppendComment) { 2106 const String16 attr16("attr"); 2107 2108 // First look for this in the included resources... 2109 uint32_t rid = mAssets->getIncludedResources() 2110 .identifierForName(name.string(), name.size(), 2111 attr16.string(), attr16.size(), 2112 package.string(), package.size()); 2113 if (rid != 0) { 2114 source.error("Attribute \"%s\" has already been defined", String8(name).string()); 2115 return false; 2116 } 2117 2118 sp<ResourceTable::Entry> entry = getEntry(package, attr16, name, source, false); 2119 if (entry == NULL) { 2120 source.error("Failed to create entry attr/%s", String8(name).string()); 2121 return false; 2122 } 2123 2124 if (entry->makeItABag(source) != NO_ERROR) { 2125 return false; 2126 } 2127 2128 const String16 formatKey16("^type"); 2129 const String16 formatValue16(String8::format("%d", format)); 2130 2131 ssize_t idx = entry->getBag().indexOfKey(formatKey16); 2132 if (idx >= 0) { 2133 // We have already set a format for this attribute, check if they are different. 2134 // We allow duplicate attribute definitions so long as they are identical. 2135 // This is to ensure inter-operation with libraries that define the same generic attribute. 2136 const Item& formatItem = entry->getBag().valueAt(idx); 2137 if ((format & (ResTable_map::TYPE_ENUM | ResTable_map::TYPE_FLAGS)) || 2138 formatItem.value != formatValue16) { 2139 source.error("Attribute \"%s\" already defined with incompatible format.\n" 2140 "%s:%d: Original attribute defined here.", 2141 String8(name).string(), formatItem.sourcePos.file.string(), 2142 formatItem.sourcePos.line); 2143 return false; 2144 } 2145 } else { 2146 entry->addToBag(source, formatKey16, formatValue16); 2147 // Increment the number of resources we have. This is used to determine if we should 2148 // even generate a resource table. 2149 mNumLocal++; 2150 } 2151 appendComment(package, attr16, name, comment, shouldAppendComment); 2152 return true; 2153} 2154 2155void ResourceTable::canAddEntry(const SourcePos& pos, 2156 const String16& package, const String16& type, const String16& name) 2157{ 2158 sp<Type> t = getType(package, type, pos); 2159 if (t != NULL) { 2160 t->canAddEntry(name); 2161 } 2162} 2163 2164size_t ResourceTable::size() const { 2165 return mPackages.size(); 2166} 2167 2168size_t ResourceTable::numLocalResources() const { 2169 return mNumLocal; 2170} 2171 2172bool ResourceTable::hasResources() const { 2173 return mNumLocal > 0; 2174} 2175 2176sp<AaptFile> ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& filter, 2177 const bool isBase) 2178{ 2179 sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8()); 2180 status_t err = flatten(bundle, filter, data, isBase); 2181 return err == NO_ERROR ? data : NULL; 2182} 2183 2184inline uint32_t ResourceTable::getResId(const sp<Package>& p, 2185 const sp<Type>& t, 2186 uint32_t nameId) 2187{ 2188 return makeResId(p->getAssignedId(), t->getIndex(), nameId); 2189} 2190 2191uint32_t ResourceTable::getResId(const String16& package, 2192 const String16& type, 2193 const String16& name, 2194 bool onlyPublic) const 2195{ 2196 uint32_t id = ResourceIdCache::lookup(package, type, name, onlyPublic); 2197 if (id != 0) return id; // cache hit 2198 2199 // First look for this in the included resources... 2200 uint32_t specFlags = 0; 2201 uint32_t rid = mAssets->getIncludedResources() 2202 .identifierForName(name.string(), name.size(), 2203 type.string(), type.size(), 2204 package.string(), package.size(), 2205 &specFlags); 2206 if (rid != 0) { 2207 if (onlyPublic && (specFlags & ResTable_typeSpec::SPEC_PUBLIC) == 0) { 2208 // If this is a feature split and the resource has the same 2209 // package name as us, then everything is public. 2210 if (mPackageType != AppFeature || mAssetsPackage != package) { 2211 return 0; 2212 } 2213 } 2214 2215 return ResourceIdCache::store(package, type, name, onlyPublic, rid); 2216 } 2217 2218 sp<Package> p = mPackages.valueFor(package); 2219 if (p == NULL) return 0; 2220 sp<Type> t = p->getTypes().valueFor(type); 2221 if (t == NULL) return 0; 2222 sp<ConfigList> c = t->getConfigs().valueFor(name); 2223 if (c == NULL) { 2224 if (type != String16("attr")) { 2225 return 0; 2226 } 2227 t = p->getTypes().valueFor(String16(kAttrPrivateType)); 2228 if (t == NULL) return 0; 2229 c = t->getConfigs().valueFor(name); 2230 if (c == NULL) return 0; 2231 } 2232 int32_t ei = c->getEntryIndex(); 2233 if (ei < 0) return 0; 2234 2235 return ResourceIdCache::store(package, type, name, onlyPublic, 2236 getResId(p, t, ei)); 2237} 2238 2239uint32_t ResourceTable::getResId(const String16& ref, 2240 const String16* defType, 2241 const String16* defPackage, 2242 const char** outErrorMsg, 2243 bool onlyPublic) const 2244{ 2245 String16 package, type, name; 2246 bool refOnlyPublic = true; 2247 if (!ResTable::expandResourceRef( 2248 ref.string(), ref.size(), &package, &type, &name, 2249 defType, defPackage ? defPackage:&mAssetsPackage, 2250 outErrorMsg, &refOnlyPublic)) { 2251 if (kIsDebug) { 2252 printf("Expanding resource: ref=%s\n", String8(ref).string()); 2253 printf("Expanding resource: defType=%s\n", 2254 defType ? String8(*defType).string() : "NULL"); 2255 printf("Expanding resource: defPackage=%s\n", 2256 defPackage ? String8(*defPackage).string() : "NULL"); 2257 printf("Expanding resource: ref=%s\n", String8(ref).string()); 2258 printf("Expanded resource: p=%s, t=%s, n=%s, res=0\n", 2259 String8(package).string(), String8(type).string(), 2260 String8(name).string()); 2261 } 2262 return 0; 2263 } 2264 uint32_t res = getResId(package, type, name, onlyPublic && refOnlyPublic); 2265 if (kIsDebug) { 2266 printf("Expanded resource: p=%s, t=%s, n=%s, res=%d\n", 2267 String8(package).string(), String8(type).string(), 2268 String8(name).string(), res); 2269 } 2270 if (res == 0) { 2271 if (outErrorMsg) 2272 *outErrorMsg = "No resource found that matches the given name"; 2273 } 2274 return res; 2275} 2276 2277bool ResourceTable::isValidResourceName(const String16& s) 2278{ 2279 const char16_t* p = s.string(); 2280 bool first = true; 2281 while (*p) { 2282 if ((*p >= 'a' && *p <= 'z') 2283 || (*p >= 'A' && *p <= 'Z') 2284 || *p == '_' 2285 || (!first && *p >= '0' && *p <= '9')) { 2286 first = false; 2287 p++; 2288 continue; 2289 } 2290 return false; 2291 } 2292 return true; 2293} 2294 2295bool ResourceTable::stringToValue(Res_value* outValue, StringPool* pool, 2296 const String16& str, 2297 bool preserveSpaces, bool coerceType, 2298 uint32_t attrID, 2299 const Vector<StringPool::entry_style_span>* style, 2300 String16* outStr, void* accessorCookie, 2301 uint32_t attrType, const String8* configTypeName, 2302 const ConfigDescription* config) 2303{ 2304 String16 finalStr; 2305 2306 bool res = true; 2307 if (style == NULL || style->size() == 0) { 2308 // Text is not styled so it can be any type... let's figure it out. 2309 res = mAssets->getIncludedResources() 2310 .stringToValue(outValue, &finalStr, str.string(), str.size(), preserveSpaces, 2311 coerceType, attrID, NULL, &mAssetsPackage, this, 2312 accessorCookie, attrType); 2313 } else { 2314 // Styled text can only be a string, and while collecting the style 2315 // information we have already processed that string! 2316 outValue->size = sizeof(Res_value); 2317 outValue->res0 = 0; 2318 outValue->dataType = outValue->TYPE_STRING; 2319 outValue->data = 0; 2320 finalStr = str; 2321 } 2322 2323 if (!res) { 2324 return false; 2325 } 2326 2327 if (outValue->dataType == outValue->TYPE_STRING) { 2328 // Should do better merging styles. 2329 if (pool) { 2330 String8 configStr; 2331 if (config != NULL) { 2332 configStr = config->toString(); 2333 } else { 2334 configStr = "(null)"; 2335 } 2336 if (kIsDebug) { 2337 printf("Adding to pool string style #%zu config %s: %s\n", 2338 style != NULL ? style->size() : 0U, 2339 configStr.string(), String8(finalStr).string()); 2340 } 2341 if (style != NULL && style->size() > 0) { 2342 outValue->data = pool->add(finalStr, *style, configTypeName, config); 2343 } else { 2344 outValue->data = pool->add(finalStr, true, configTypeName, config); 2345 } 2346 } else { 2347 // Caller will fill this in later. 2348 outValue->data = 0; 2349 } 2350 2351 if (outStr) { 2352 *outStr = finalStr; 2353 } 2354 2355 } 2356 2357 return true; 2358} 2359 2360uint32_t ResourceTable::getCustomResource( 2361 const String16& package, const String16& type, const String16& name) const 2362{ 2363 //printf("getCustomResource: %s %s %s\n", String8(package).string(), 2364 // String8(type).string(), String8(name).string()); 2365 sp<Package> p = mPackages.valueFor(package); 2366 if (p == NULL) return 0; 2367 sp<Type> t = p->getTypes().valueFor(type); 2368 if (t == NULL) return 0; 2369 sp<ConfigList> c = t->getConfigs().valueFor(name); 2370 if (c == NULL) { 2371 if (type != String16("attr")) { 2372 return 0; 2373 } 2374 t = p->getTypes().valueFor(String16(kAttrPrivateType)); 2375 if (t == NULL) return 0; 2376 c = t->getConfigs().valueFor(name); 2377 if (c == NULL) return 0; 2378 } 2379 int32_t ei = c->getEntryIndex(); 2380 if (ei < 0) return 0; 2381 return getResId(p, t, ei); 2382} 2383 2384uint32_t ResourceTable::getCustomResourceWithCreation( 2385 const String16& package, const String16& type, const String16& name, 2386 const bool createIfNotFound) 2387{ 2388 uint32_t resId = getCustomResource(package, type, name); 2389 if (resId != 0 || !createIfNotFound) { 2390 return resId; 2391 } 2392 2393 if (mAssetsPackage != package) { 2394 mCurrentXmlPos.error("creating resource for external package %s: %s/%s.", 2395 String8(package).string(), String8(type).string(), String8(name).string()); 2396 if (package == String16("android")) { 2397 mCurrentXmlPos.printf("did you mean to use @+id instead of @+android:id?"); 2398 } 2399 return 0; 2400 } 2401 2402 String16 value("false"); 2403 status_t status = addEntry(mCurrentXmlPos, package, type, name, value, NULL, NULL, true); 2404 if (status == NO_ERROR) { 2405 resId = getResId(package, type, name); 2406 return resId; 2407 } 2408 return 0; 2409} 2410 2411uint32_t ResourceTable::getRemappedPackage(uint32_t origPackage) const 2412{ 2413 return origPackage; 2414} 2415 2416bool ResourceTable::getAttributeType(uint32_t attrID, uint32_t* outType) 2417{ 2418 //printf("getAttributeType #%08x\n", attrID); 2419 Res_value value; 2420 if (getItemValue(attrID, ResTable_map::ATTR_TYPE, &value)) { 2421 //printf("getAttributeType #%08x (%s): #%08x\n", attrID, 2422 // String8(getEntry(attrID)->getName()).string(), value.data); 2423 *outType = value.data; 2424 return true; 2425 } 2426 return false; 2427} 2428 2429bool ResourceTable::getAttributeMin(uint32_t attrID, uint32_t* outMin) 2430{ 2431 //printf("getAttributeMin #%08x\n", attrID); 2432 Res_value value; 2433 if (getItemValue(attrID, ResTable_map::ATTR_MIN, &value)) { 2434 *outMin = value.data; 2435 return true; 2436 } 2437 return false; 2438} 2439 2440bool ResourceTable::getAttributeMax(uint32_t attrID, uint32_t* outMax) 2441{ 2442 //printf("getAttributeMax #%08x\n", attrID); 2443 Res_value value; 2444 if (getItemValue(attrID, ResTable_map::ATTR_MAX, &value)) { 2445 *outMax = value.data; 2446 return true; 2447 } 2448 return false; 2449} 2450 2451uint32_t ResourceTable::getAttributeL10N(uint32_t attrID) 2452{ 2453 //printf("getAttributeL10N #%08x\n", attrID); 2454 Res_value value; 2455 if (getItemValue(attrID, ResTable_map::ATTR_L10N, &value)) { 2456 return value.data; 2457 } 2458 return ResTable_map::L10N_NOT_REQUIRED; 2459} 2460 2461bool ResourceTable::getLocalizationSetting() 2462{ 2463 return mBundle->getRequireLocalization(); 2464} 2465 2466void ResourceTable::reportError(void* accessorCookie, const char* fmt, ...) 2467{ 2468 if (accessorCookie != NULL && fmt != NULL) { 2469 AccessorCookie* ac = (AccessorCookie*)accessorCookie; 2470 int retval=0; 2471 char buf[1024]; 2472 va_list ap; 2473 va_start(ap, fmt); 2474 retval = vsnprintf(buf, sizeof(buf), fmt, ap); 2475 va_end(ap); 2476 ac->sourcePos.error("Error: %s (at '%s' with value '%s').\n", 2477 buf, ac->attr.string(), ac->value.string()); 2478 } 2479} 2480 2481bool ResourceTable::getAttributeKeys( 2482 uint32_t attrID, Vector<String16>* outKeys) 2483{ 2484 sp<const Entry> e = getEntry(attrID); 2485 if (e != NULL) { 2486 const size_t N = e->getBag().size(); 2487 for (size_t i=0; i<N; i++) { 2488 const String16& key = e->getBag().keyAt(i); 2489 if (key.size() > 0 && key.string()[0] != '^') { 2490 outKeys->add(key); 2491 } 2492 } 2493 return true; 2494 } 2495 return false; 2496} 2497 2498bool ResourceTable::getAttributeEnum( 2499 uint32_t attrID, const char16_t* name, size_t nameLen, 2500 Res_value* outValue) 2501{ 2502 //printf("getAttributeEnum #%08x %s\n", attrID, String8(name, nameLen).string()); 2503 String16 nameStr(name, nameLen); 2504 sp<const Entry> e = getEntry(attrID); 2505 if (e != NULL) { 2506 const size_t N = e->getBag().size(); 2507 for (size_t i=0; i<N; i++) { 2508 //printf("Comparing %s to %s\n", String8(name, nameLen).string(), 2509 // String8(e->getBag().keyAt(i)).string()); 2510 if (e->getBag().keyAt(i) == nameStr) { 2511 return getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, outValue); 2512 } 2513 } 2514 } 2515 return false; 2516} 2517 2518bool ResourceTable::getAttributeFlags( 2519 uint32_t attrID, const char16_t* name, size_t nameLen, 2520 Res_value* outValue) 2521{ 2522 outValue->dataType = Res_value::TYPE_INT_HEX; 2523 outValue->data = 0; 2524 2525 //printf("getAttributeFlags #%08x %s\n", attrID, String8(name, nameLen).string()); 2526 String16 nameStr(name, nameLen); 2527 sp<const Entry> e = getEntry(attrID); 2528 if (e != NULL) { 2529 const size_t N = e->getBag().size(); 2530 2531 const char16_t* end = name + nameLen; 2532 const char16_t* pos = name; 2533 while (pos < end) { 2534 const char16_t* start = pos; 2535 while (pos < end && *pos != '|') { 2536 pos++; 2537 } 2538 2539 String16 nameStr(start, pos-start); 2540 size_t i; 2541 for (i=0; i<N; i++) { 2542 //printf("Comparing \"%s\" to \"%s\"\n", String8(nameStr).string(), 2543 // String8(e->getBag().keyAt(i)).string()); 2544 if (e->getBag().keyAt(i) == nameStr) { 2545 Res_value val; 2546 bool got = getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, &val); 2547 if (!got) { 2548 return false; 2549 } 2550 //printf("Got value: 0x%08x\n", val.data); 2551 outValue->data |= val.data; 2552 break; 2553 } 2554 } 2555 2556 if (i >= N) { 2557 // Didn't find this flag identifier. 2558 return false; 2559 } 2560 pos++; 2561 } 2562 2563 return true; 2564 } 2565 return false; 2566} 2567 2568status_t ResourceTable::assignResourceIds() 2569{ 2570 const size_t N = mOrderedPackages.size(); 2571 size_t pi; 2572 status_t firstError = NO_ERROR; 2573 2574 // First generate all bag attributes and assign indices. 2575 for (pi=0; pi<N; pi++) { 2576 sp<Package> p = mOrderedPackages.itemAt(pi); 2577 if (p == NULL || p->getTypes().size() == 0) { 2578 // Empty, skip! 2579 continue; 2580 } 2581 2582 if (mPackageType == System) { 2583 p->movePrivateAttrs(); 2584 } 2585 2586 // This has no sense for packages being built as AppFeature (aka with a non-zero offset). 2587 status_t err = p->applyPublicTypeOrder(); 2588 if (err != NO_ERROR && firstError == NO_ERROR) { 2589 firstError = err; 2590 } 2591 2592 // Generate attributes... 2593 const size_t N = p->getOrderedTypes().size(); 2594 size_t ti; 2595 for (ti=0; ti<N; ti++) { 2596 sp<Type> t = p->getOrderedTypes().itemAt(ti); 2597 if (t == NULL) { 2598 continue; 2599 } 2600 const size_t N = t->getOrderedConfigs().size(); 2601 for (size_t ci=0; ci<N; ci++) { 2602 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci); 2603 if (c == NULL) { 2604 continue; 2605 } 2606 const size_t N = c->getEntries().size(); 2607 for (size_t ei=0; ei<N; ei++) { 2608 sp<Entry> e = c->getEntries().valueAt(ei); 2609 if (e == NULL) { 2610 continue; 2611 } 2612 status_t err = e->generateAttributes(this, p->getName()); 2613 if (err != NO_ERROR && firstError == NO_ERROR) { 2614 firstError = err; 2615 } 2616 } 2617 } 2618 } 2619 2620 uint32_t typeIdOffset = 0; 2621 if (mPackageType == AppFeature && p->getName() == mAssetsPackage) { 2622 typeIdOffset = mTypeIdOffset; 2623 } 2624 2625 const SourcePos unknown(String8("????"), 0); 2626 sp<Type> attr = p->getType(String16("attr"), unknown); 2627 2628 // Force creation of ID if we are building feature splits. 2629 // Auto-generated ID resources won't apply the type ID offset correctly unless 2630 // the offset is applied here first. 2631 // b/30607637 2632 if (mPackageType == AppFeature && p->getName() == mAssetsPackage) { 2633 sp<Type> id = p->getType(String16("id"), unknown); 2634 } 2635 2636 // Assign indices... 2637 const size_t typeCount = p->getOrderedTypes().size(); 2638 for (size_t ti = 0; ti < typeCount; ti++) { 2639 sp<Type> t = p->getOrderedTypes().itemAt(ti); 2640 if (t == NULL) { 2641 continue; 2642 } 2643 2644 err = t->applyPublicEntryOrder(); 2645 if (err != NO_ERROR && firstError == NO_ERROR) { 2646 firstError = err; 2647 } 2648 2649 const size_t N = t->getOrderedConfigs().size(); 2650 t->setIndex(ti + 1 + typeIdOffset); 2651 2652 LOG_ALWAYS_FATAL_IF(ti == 0 && attr != t, 2653 "First type is not attr!"); 2654 2655 for (size_t ei=0; ei<N; ei++) { 2656 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ei); 2657 if (c == NULL) { 2658 continue; 2659 } 2660 c->setEntryIndex(ei); 2661 } 2662 } 2663 2664 2665 // Assign resource IDs to keys in bags... 2666 for (size_t ti = 0; ti < typeCount; ti++) { 2667 sp<Type> t = p->getOrderedTypes().itemAt(ti); 2668 if (t == NULL) { 2669 continue; 2670 } 2671 2672 const size_t N = t->getOrderedConfigs().size(); 2673 for (size_t ci=0; ci<N; ci++) { 2674 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci); 2675 if (c == NULL) { 2676 continue; 2677 } 2678 //printf("Ordered config #%d: %p\n", ci, c.get()); 2679 const size_t N = c->getEntries().size(); 2680 for (size_t ei=0; ei<N; ei++) { 2681 sp<Entry> e = c->getEntries().valueAt(ei); 2682 if (e == NULL) { 2683 continue; 2684 } 2685 status_t err = e->assignResourceIds(this, p->getName()); 2686 if (err != NO_ERROR && firstError == NO_ERROR) { 2687 firstError = err; 2688 } 2689 } 2690 } 2691 } 2692 } 2693 return firstError; 2694} 2695 2696status_t ResourceTable::addSymbols(const sp<AaptSymbols>& outSymbols, 2697 bool skipSymbolsWithoutDefaultLocalization) { 2698 const size_t N = mOrderedPackages.size(); 2699 const String8 defaultLocale; 2700 const String16 stringType("string"); 2701 size_t pi; 2702 2703 for (pi=0; pi<N; pi++) { 2704 sp<Package> p = mOrderedPackages.itemAt(pi); 2705 if (p->getTypes().size() == 0) { 2706 // Empty, skip! 2707 continue; 2708 } 2709 2710 const size_t N = p->getOrderedTypes().size(); 2711 size_t ti; 2712 2713 for (ti=0; ti<N; ti++) { 2714 sp<Type> t = p->getOrderedTypes().itemAt(ti); 2715 if (t == NULL) { 2716 continue; 2717 } 2718 2719 const size_t N = t->getOrderedConfigs().size(); 2720 sp<AaptSymbols> typeSymbols; 2721 if (t->getName() == String16(kAttrPrivateType)) { 2722 typeSymbols = outSymbols->addNestedSymbol(String8("attr"), t->getPos()); 2723 } else { 2724 typeSymbols = outSymbols->addNestedSymbol(String8(t->getName()), t->getPos()); 2725 } 2726 2727 if (typeSymbols == NULL) { 2728 return UNKNOWN_ERROR; 2729 } 2730 2731 for (size_t ci=0; ci<N; ci++) { 2732 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci); 2733 if (c == NULL) { 2734 continue; 2735 } 2736 uint32_t rid = getResId(p, t, ci); 2737 if (rid == 0) { 2738 return UNKNOWN_ERROR; 2739 } 2740 if (Res_GETPACKAGE(rid) + 1 == p->getAssignedId()) { 2741 2742 if (skipSymbolsWithoutDefaultLocalization && 2743 t->getName() == stringType) { 2744 2745 // Don't generate symbols for strings without a default localization. 2746 if (mHasDefaultLocalization.find(c->getName()) 2747 == mHasDefaultLocalization.end()) { 2748 // printf("Skip symbol [%08x] %s\n", rid, 2749 // String8(c->getName()).string()); 2750 continue; 2751 } 2752 } 2753 2754 typeSymbols->addSymbol(String8(c->getName()), rid, c->getPos()); 2755 2756 String16 comment(c->getComment()); 2757 typeSymbols->appendComment(String8(c->getName()), comment, c->getPos()); 2758 //printf("Type symbol [%08x] %s comment: %s\n", rid, 2759 // String8(c->getName()).string(), String8(comment).string()); 2760 comment = c->getTypeComment(); 2761 typeSymbols->appendTypeComment(String8(c->getName()), comment); 2762 } 2763 } 2764 } 2765 } 2766 return NO_ERROR; 2767} 2768 2769 2770void 2771ResourceTable::addLocalization(const String16& name, const String8& locale, const SourcePos& src) 2772{ 2773 mLocalizations[name][locale] = src; 2774} 2775 2776void 2777ResourceTable::addDefaultLocalization(const String16& name) 2778{ 2779 mHasDefaultLocalization.insert(name); 2780} 2781 2782 2783/*! 2784 * Flag various sorts of localization problems. '+' indicates checks already implemented; 2785 * '-' indicates checks that will be implemented in the future. 2786 * 2787 * + A localized string for which no default-locale version exists => warning 2788 * + A string for which no version in an explicitly-requested locale exists => warning 2789 * + A localized translation of an translateable="false" string => warning 2790 * - A localized string not provided in every locale used by the table 2791 */ 2792status_t 2793ResourceTable::validateLocalizations(void) 2794{ 2795 status_t err = NO_ERROR; 2796 const String8 defaultLocale; 2797 2798 // For all strings... 2799 for (const auto& nameIter : mLocalizations) { 2800 const std::map<String8, SourcePos>& configSrcMap = nameIter.second; 2801 2802 // Look for strings with no default localization 2803 if (configSrcMap.count(defaultLocale) == 0) { 2804 SourcePos().warning("string '%s' has no default translation.", 2805 String8(nameIter.first).string()); 2806 if (mBundle->getVerbose()) { 2807 for (const auto& locale : configSrcMap) { 2808 locale.second.printf("locale %s found", locale.first.string()); 2809 } 2810 } 2811 // !!! TODO: throw an error here in some circumstances 2812 } 2813 2814 // Check that all requested localizations are present for this string 2815 if (mBundle->getConfigurations().size() > 0 && mBundle->getRequireLocalization()) { 2816 const char* allConfigs = mBundle->getConfigurations().string(); 2817 const char* start = allConfigs; 2818 const char* comma; 2819 2820 std::set<String8> missingConfigs; 2821 AaptLocaleValue locale; 2822 do { 2823 String8 config; 2824 comma = strchr(start, ','); 2825 if (comma != NULL) { 2826 config.setTo(start, comma - start); 2827 start = comma + 1; 2828 } else { 2829 config.setTo(start); 2830 } 2831 2832 if (!locale.initFromFilterString(config)) { 2833 continue; 2834 } 2835 2836 // don't bother with the pseudolocale "en_XA" or "ar_XB" 2837 if (config != "en_XA" && config != "ar_XB") { 2838 if (configSrcMap.find(config) == configSrcMap.end()) { 2839 // okay, no specific localization found. it's possible that we are 2840 // requiring a specific regional localization [e.g. de_DE] but there is an 2841 // available string in the generic language localization [e.g. de]; 2842 // consider that string to have fulfilled the localization requirement. 2843 String8 region(config.string(), 2); 2844 if (configSrcMap.find(region) == configSrcMap.end() && 2845 configSrcMap.count(defaultLocale) == 0) { 2846 missingConfigs.insert(config); 2847 } 2848 } 2849 } 2850 } while (comma != NULL); 2851 2852 if (!missingConfigs.empty()) { 2853 String8 configStr; 2854 for (const auto& iter : missingConfigs) { 2855 configStr.appendFormat(" %s", iter.string()); 2856 } 2857 SourcePos().warning("string '%s' is missing %u required localizations:%s", 2858 String8(nameIter.first).string(), 2859 (unsigned int)missingConfigs.size(), 2860 configStr.string()); 2861 } 2862 } 2863 } 2864 2865 return err; 2866} 2867 2868status_t ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& filter, 2869 const sp<AaptFile>& dest, 2870 const bool isBase) 2871{ 2872 const ConfigDescription nullConfig; 2873 2874 const size_t N = mOrderedPackages.size(); 2875 size_t pi; 2876 2877 const static String16 mipmap16("mipmap"); 2878 2879 bool useUTF8 = !bundle->getUTF16StringsOption(); 2880 2881 // The libraries this table references. 2882 Vector<sp<Package> > libraryPackages; 2883 const ResTable& table = mAssets->getIncludedResources(); 2884 const size_t basePackageCount = table.getBasePackageCount(); 2885 for (size_t i = 0; i < basePackageCount; i++) { 2886 size_t packageId = table.getBasePackageId(i); 2887 String16 packageName(table.getBasePackageName(i)); 2888 if (packageId > 0x01 && packageId != 0x7f && 2889 packageName != String16("android")) { 2890 libraryPackages.add(sp<Package>(new Package(packageName, packageId))); 2891 } 2892 } 2893 2894 // Iterate through all data, collecting all values (strings, 2895 // references, etc). 2896 StringPool valueStrings(useUTF8); 2897 Vector<sp<Entry> > allEntries; 2898 for (pi=0; pi<N; pi++) { 2899 sp<Package> p = mOrderedPackages.itemAt(pi); 2900 if (p->getTypes().size() == 0) { 2901 continue; 2902 } 2903 2904 StringPool typeStrings(useUTF8); 2905 StringPool keyStrings(useUTF8); 2906 2907 ssize_t stringsAdded = 0; 2908 const size_t N = p->getOrderedTypes().size(); 2909 for (size_t ti=0; ti<N; ti++) { 2910 sp<Type> t = p->getOrderedTypes().itemAt(ti); 2911 if (t == NULL) { 2912 typeStrings.add(String16("<empty>"), false); 2913 stringsAdded++; 2914 continue; 2915 } 2916 2917 while (stringsAdded < t->getIndex() - 1) { 2918 typeStrings.add(String16("<empty>"), false); 2919 stringsAdded++; 2920 } 2921 2922 const String16 typeName(t->getName()); 2923 typeStrings.add(typeName, false); 2924 stringsAdded++; 2925 2926 // This is a hack to tweak the sorting order of the final strings, 2927 // to put stuff that is generally not language-specific first. 2928 String8 configTypeName(typeName); 2929 if (configTypeName == "drawable" || configTypeName == "layout" 2930 || configTypeName == "color" || configTypeName == "anim" 2931 || configTypeName == "interpolator" || configTypeName == "animator" 2932 || configTypeName == "xml" || configTypeName == "menu" 2933 || configTypeName == "mipmap" || configTypeName == "raw") { 2934 configTypeName = "1complex"; 2935 } else { 2936 configTypeName = "2value"; 2937 } 2938 2939 // mipmaps don't get filtered, so they will 2940 // allways end up in the base. Make sure they 2941 // don't end up in a split. 2942 if (typeName == mipmap16 && !isBase) { 2943 continue; 2944 } 2945 2946 const bool filterable = (typeName != mipmap16); 2947 2948 const size_t N = t->getOrderedConfigs().size(); 2949 for (size_t ci=0; ci<N; ci++) { 2950 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci); 2951 if (c == NULL) { 2952 continue; 2953 } 2954 const size_t N = c->getEntries().size(); 2955 for (size_t ei=0; ei<N; ei++) { 2956 ConfigDescription config = c->getEntries().keyAt(ei); 2957 if (filterable && !filter->match(config)) { 2958 continue; 2959 } 2960 sp<Entry> e = c->getEntries().valueAt(ei); 2961 if (e == NULL) { 2962 continue; 2963 } 2964 e->setNameIndex(keyStrings.add(e->getName(), true)); 2965 2966 // If this entry has no values for other configs, 2967 // and is the default config, then it is special. Otherwise 2968 // we want to add it with the config info. 2969 ConfigDescription* valueConfig = NULL; 2970 if (N != 1 || config == nullConfig) { 2971 valueConfig = &config; 2972 } 2973 2974 status_t err = e->prepareFlatten(&valueStrings, this, 2975 &configTypeName, &config); 2976 if (err != NO_ERROR) { 2977 return err; 2978 } 2979 allEntries.add(e); 2980 } 2981 } 2982 } 2983 2984 p->setTypeStrings(typeStrings.createStringBlock()); 2985 p->setKeyStrings(keyStrings.createStringBlock()); 2986 } 2987 2988 if (bundle->getOutputAPKFile() != NULL) { 2989 // Now we want to sort the value strings for better locality. This will 2990 // cause the positions of the strings to change, so we need to go back 2991 // through out resource entries and update them accordingly. Only need 2992 // to do this if actually writing the output file. 2993 valueStrings.sortByConfig(); 2994 for (pi=0; pi<allEntries.size(); pi++) { 2995 allEntries[pi]->remapStringValue(&valueStrings); 2996 } 2997 } 2998 2999 ssize_t strAmt = 0; 3000 3001 // Now build the array of package chunks. 3002 Vector<sp<AaptFile> > flatPackages; 3003 for (pi=0; pi<N; pi++) { 3004 sp<Package> p = mOrderedPackages.itemAt(pi); 3005 if (p->getTypes().size() == 0) { 3006 // Empty, skip! 3007 continue; 3008 } 3009 3010 const size_t N = p->getTypeStrings().size(); 3011 3012 const size_t baseSize = sizeof(ResTable_package); 3013 3014 // Start the package data. 3015 sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8()); 3016 ResTable_package* header = (ResTable_package*)data->editData(baseSize); 3017 if (header == NULL) { 3018 fprintf(stderr, "ERROR: out of memory creating ResTable_package\n"); 3019 return NO_MEMORY; 3020 } 3021 memset(header, 0, sizeof(*header)); 3022 header->header.type = htods(RES_TABLE_PACKAGE_TYPE); 3023 header->header.headerSize = htods(sizeof(*header)); 3024 header->id = htodl(static_cast<uint32_t>(p->getAssignedId())); 3025 strcpy16_htod(header->name, p->getName().string()); 3026 3027 // Write the string blocks. 3028 const size_t typeStringsStart = data->getSize(); 3029 sp<AaptFile> strFile = p->getTypeStringsData(); 3030 ssize_t amt = data->writeData(strFile->getData(), strFile->getSize()); 3031 if (kPrintStringMetrics) { 3032 fprintf(stderr, "**** type strings: %zd\n", SSIZE(amt)); 3033 } 3034 strAmt += amt; 3035 if (amt < 0) { 3036 return amt; 3037 } 3038 const size_t keyStringsStart = data->getSize(); 3039 strFile = p->getKeyStringsData(); 3040 amt = data->writeData(strFile->getData(), strFile->getSize()); 3041 if (kPrintStringMetrics) { 3042 fprintf(stderr, "**** key strings: %zd\n", SSIZE(amt)); 3043 } 3044 strAmt += amt; 3045 if (amt < 0) { 3046 return amt; 3047 } 3048 3049 if (isBase) { 3050 status_t err = flattenLibraryTable(data, libraryPackages); 3051 if (err != NO_ERROR) { 3052 fprintf(stderr, "ERROR: failed to write library table\n"); 3053 return err; 3054 } 3055 } 3056 3057 // Build the type chunks inside of this package. 3058 for (size_t ti=0; ti<N; ti++) { 3059 // Retrieve them in the same order as the type string block. 3060 size_t len; 3061 String16 typeName(p->getTypeStrings().stringAt(ti, &len)); 3062 sp<Type> t = p->getTypes().valueFor(typeName); 3063 LOG_ALWAYS_FATAL_IF(t == NULL && typeName != String16("<empty>"), 3064 "Type name %s not found", 3065 String8(typeName).string()); 3066 if (t == NULL) { 3067 continue; 3068 } 3069 const bool filterable = (typeName != mipmap16); 3070 const bool skipEntireType = (typeName == mipmap16 && !isBase); 3071 3072 const size_t N = t != NULL ? t->getOrderedConfigs().size() : 0; 3073 3074 // Until a non-NO_ENTRY value has been written for a resource, 3075 // that resource is invalid; validResources[i] represents 3076 // the item at t->getOrderedConfigs().itemAt(i). 3077 Vector<bool> validResources; 3078 validResources.insertAt(false, 0, N); 3079 3080 // First write the typeSpec chunk, containing information about 3081 // each resource entry in this type. 3082 { 3083 const size_t typeSpecSize = sizeof(ResTable_typeSpec) + sizeof(uint32_t)*N; 3084 const size_t typeSpecStart = data->getSize(); 3085 ResTable_typeSpec* tsHeader = (ResTable_typeSpec*) 3086 (((uint8_t*)data->editData(typeSpecStart+typeSpecSize)) + typeSpecStart); 3087 if (tsHeader == NULL) { 3088 fprintf(stderr, "ERROR: out of memory creating ResTable_typeSpec\n"); 3089 return NO_MEMORY; 3090 } 3091 memset(tsHeader, 0, sizeof(*tsHeader)); 3092 tsHeader->header.type = htods(RES_TABLE_TYPE_SPEC_TYPE); 3093 tsHeader->header.headerSize = htods(sizeof(*tsHeader)); 3094 tsHeader->header.size = htodl(typeSpecSize); 3095 tsHeader->id = ti+1; 3096 tsHeader->entryCount = htodl(N); 3097 3098 uint32_t* typeSpecFlags = (uint32_t*) 3099 (((uint8_t*)data->editData()) 3100 + typeSpecStart + sizeof(ResTable_typeSpec)); 3101 memset(typeSpecFlags, 0, sizeof(uint32_t)*N); 3102 3103 for (size_t ei=0; ei<N; ei++) { 3104 sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei); 3105 if (cl == NULL) { 3106 continue; 3107 } 3108 3109 if (cl->getPublic()) { 3110 typeSpecFlags[ei] |= htodl(ResTable_typeSpec::SPEC_PUBLIC); 3111 } 3112 3113 if (skipEntireType) { 3114 continue; 3115 } 3116 3117 const size_t CN = cl->getEntries().size(); 3118 for (size_t ci=0; ci<CN; ci++) { 3119 if (filterable && !filter->match(cl->getEntries().keyAt(ci))) { 3120 continue; 3121 } 3122 for (size_t cj=ci+1; cj<CN; cj++) { 3123 if (filterable && !filter->match(cl->getEntries().keyAt(cj))) { 3124 continue; 3125 } 3126 typeSpecFlags[ei] |= htodl( 3127 cl->getEntries().keyAt(ci).diff(cl->getEntries().keyAt(cj))); 3128 } 3129 } 3130 } 3131 } 3132 3133 if (skipEntireType) { 3134 continue; 3135 } 3136 3137 // We need to write one type chunk for each configuration for 3138 // which we have entries in this type. 3139 SortedVector<ConfigDescription> uniqueConfigs; 3140 if (t != NULL) { 3141 uniqueConfigs = t->getUniqueConfigs(); 3142 } 3143 3144 const size_t typeSize = sizeof(ResTable_type) + sizeof(uint32_t)*N; 3145 3146 const size_t NC = uniqueConfigs.size(); 3147 for (size_t ci=0; ci<NC; ci++) { 3148 const ConfigDescription& config = uniqueConfigs[ci]; 3149 3150 if (kIsDebug) { 3151 printf("Writing config %zu config: imsi:%d/%d lang:%c%c cnt:%c%c " 3152 "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d " 3153 "sw%ddp w%ddp h%ddp layout:%d\n", 3154 ti + 1, 3155 config.mcc, config.mnc, 3156 config.language[0] ? config.language[0] : '-', 3157 config.language[1] ? config.language[1] : '-', 3158 config.country[0] ? config.country[0] : '-', 3159 config.country[1] ? config.country[1] : '-', 3160 config.orientation, 3161 config.uiMode, 3162 config.touchscreen, 3163 config.density, 3164 config.keyboard, 3165 config.inputFlags, 3166 config.navigation, 3167 config.screenWidth, 3168 config.screenHeight, 3169 config.smallestScreenWidthDp, 3170 config.screenWidthDp, 3171 config.screenHeightDp, 3172 config.screenLayout); 3173 } 3174 3175 if (filterable && !filter->match(config)) { 3176 continue; 3177 } 3178 3179 const size_t typeStart = data->getSize(); 3180 3181 ResTable_type* tHeader = (ResTable_type*) 3182 (((uint8_t*)data->editData(typeStart+typeSize)) + typeStart); 3183 if (tHeader == NULL) { 3184 fprintf(stderr, "ERROR: out of memory creating ResTable_type\n"); 3185 return NO_MEMORY; 3186 } 3187 3188 memset(tHeader, 0, sizeof(*tHeader)); 3189 tHeader->header.type = htods(RES_TABLE_TYPE_TYPE); 3190 tHeader->header.headerSize = htods(sizeof(*tHeader)); 3191 tHeader->id = ti+1; 3192 tHeader->entryCount = htodl(N); 3193 tHeader->entriesStart = htodl(typeSize); 3194 tHeader->config = config; 3195 if (kIsDebug) { 3196 printf("Writing type %zu config: imsi:%d/%d lang:%c%c cnt:%c%c " 3197 "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d " 3198 "sw%ddp w%ddp h%ddp layout:%d\n", 3199 ti + 1, 3200 tHeader->config.mcc, tHeader->config.mnc, 3201 tHeader->config.language[0] ? tHeader->config.language[0] : '-', 3202 tHeader->config.language[1] ? tHeader->config.language[1] : '-', 3203 tHeader->config.country[0] ? tHeader->config.country[0] : '-', 3204 tHeader->config.country[1] ? tHeader->config.country[1] : '-', 3205 tHeader->config.orientation, 3206 tHeader->config.uiMode, 3207 tHeader->config.touchscreen, 3208 tHeader->config.density, 3209 tHeader->config.keyboard, 3210 tHeader->config.inputFlags, 3211 tHeader->config.navigation, 3212 tHeader->config.screenWidth, 3213 tHeader->config.screenHeight, 3214 tHeader->config.smallestScreenWidthDp, 3215 tHeader->config.screenWidthDp, 3216 tHeader->config.screenHeightDp, 3217 tHeader->config.screenLayout); 3218 } 3219 tHeader->config.swapHtoD(); 3220 3221 // Build the entries inside of this type. 3222 for (size_t ei=0; ei<N; ei++) { 3223 sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei); 3224 sp<Entry> e = NULL; 3225 if (cl != NULL) { 3226 e = cl->getEntries().valueFor(config); 3227 } 3228 3229 // Set the offset for this entry in its type. 3230 uint32_t* index = (uint32_t*) 3231 (((uint8_t*)data->editData()) 3232 + typeStart + sizeof(ResTable_type)); 3233 if (e != NULL) { 3234 index[ei] = htodl(data->getSize()-typeStart-typeSize); 3235 3236 // Create the entry. 3237 ssize_t amt = e->flatten(bundle, data, cl->getPublic()); 3238 if (amt < 0) { 3239 return amt; 3240 } 3241 validResources.editItemAt(ei) = true; 3242 } else { 3243 index[ei] = htodl(ResTable_type::NO_ENTRY); 3244 } 3245 } 3246 3247 // Fill in the rest of the type information. 3248 tHeader = (ResTable_type*) 3249 (((uint8_t*)data->editData()) + typeStart); 3250 tHeader->header.size = htodl(data->getSize()-typeStart); 3251 } 3252 3253 // If we're building splits, then each invocation of the flattening 3254 // step will have 'missing' entries. Don't warn/error for this case. 3255 if (bundle->getSplitConfigurations().isEmpty()) { 3256 bool missing_entry = false; 3257 const char* log_prefix = bundle->getErrorOnMissingConfigEntry() ? 3258 "error" : "warning"; 3259 for (size_t i = 0; i < N; ++i) { 3260 if (!validResources[i]) { 3261 sp<ConfigList> c = t->getOrderedConfigs().itemAt(i); 3262 if (c != NULL) { 3263 fprintf(stderr, "%s: no entries written for %s/%s (0x%08zx)\n", log_prefix, 3264 String8(typeName).string(), String8(c->getName()).string(), 3265 Res_MAKEID(p->getAssignedId() - 1, ti, i)); 3266 } 3267 missing_entry = true; 3268 } 3269 } 3270 if (bundle->getErrorOnMissingConfigEntry() && missing_entry) { 3271 fprintf(stderr, "Error: Missing entries, quit!\n"); 3272 return NOT_ENOUGH_DATA; 3273 } 3274 } 3275 } 3276 3277 // Fill in the rest of the package information. 3278 header = (ResTable_package*)data->editData(); 3279 header->header.size = htodl(data->getSize()); 3280 header->typeStrings = htodl(typeStringsStart); 3281 header->lastPublicType = htodl(p->getTypeStrings().size()); 3282 header->keyStrings = htodl(keyStringsStart); 3283 header->lastPublicKey = htodl(p->getKeyStrings().size()); 3284 3285 flatPackages.add(data); 3286 } 3287 3288 // And now write out the final chunks. 3289 const size_t dataStart = dest->getSize(); 3290 3291 { 3292 // blah 3293 ResTable_header header; 3294 memset(&header, 0, sizeof(header)); 3295 header.header.type = htods(RES_TABLE_TYPE); 3296 header.header.headerSize = htods(sizeof(header)); 3297 header.packageCount = htodl(flatPackages.size()); 3298 status_t err = dest->writeData(&header, sizeof(header)); 3299 if (err != NO_ERROR) { 3300 fprintf(stderr, "ERROR: out of memory creating ResTable_header\n"); 3301 return err; 3302 } 3303 } 3304 3305 ssize_t strStart = dest->getSize(); 3306 status_t err = valueStrings.writeStringBlock(dest); 3307 if (err != NO_ERROR) { 3308 return err; 3309 } 3310 3311 ssize_t amt = (dest->getSize()-strStart); 3312 strAmt += amt; 3313 if (kPrintStringMetrics) { 3314 fprintf(stderr, "**** value strings: %zd\n", SSIZE(amt)); 3315 fprintf(stderr, "**** total strings: %zd\n", SSIZE(strAmt)); 3316 } 3317 3318 for (pi=0; pi<flatPackages.size(); pi++) { 3319 err = dest->writeData(flatPackages[pi]->getData(), 3320 flatPackages[pi]->getSize()); 3321 if (err != NO_ERROR) { 3322 fprintf(stderr, "ERROR: out of memory creating package chunk for ResTable_header\n"); 3323 return err; 3324 } 3325 } 3326 3327 ResTable_header* header = (ResTable_header*) 3328 (((uint8_t*)dest->getData()) + dataStart); 3329 header->header.size = htodl(dest->getSize() - dataStart); 3330 3331 if (kPrintStringMetrics) { 3332 fprintf(stderr, "**** total resource table size: %zu / %zu%% strings\n", 3333 dest->getSize(), (size_t)(strAmt*100)/dest->getSize()); 3334 } 3335 3336 return NO_ERROR; 3337} 3338 3339status_t ResourceTable::flattenLibraryTable(const sp<AaptFile>& dest, const Vector<sp<Package> >& libs) { 3340 // Write out the library table if necessary 3341 if (libs.size() > 0) { 3342 if (kIsDebug) { 3343 fprintf(stderr, "Writing library reference table\n"); 3344 } 3345 3346 const size_t libStart = dest->getSize(); 3347 const size_t count = libs.size(); 3348 ResTable_lib_header* libHeader = (ResTable_lib_header*) dest->editDataInRange( 3349 libStart, sizeof(ResTable_lib_header)); 3350 3351 memset(libHeader, 0, sizeof(*libHeader)); 3352 libHeader->header.type = htods(RES_TABLE_LIBRARY_TYPE); 3353 libHeader->header.headerSize = htods(sizeof(*libHeader)); 3354 libHeader->header.size = htodl(sizeof(*libHeader) + (sizeof(ResTable_lib_entry) * count)); 3355 libHeader->count = htodl(count); 3356 3357 // Write the library entries 3358 for (size_t i = 0; i < count; i++) { 3359 const size_t entryStart = dest->getSize(); 3360 sp<Package> libPackage = libs[i]; 3361 if (kIsDebug) { 3362 fprintf(stderr, " Entry %s -> 0x%02x\n", 3363 String8(libPackage->getName()).string(), 3364 (uint8_t)libPackage->getAssignedId()); 3365 } 3366 3367 ResTable_lib_entry* entry = (ResTable_lib_entry*) dest->editDataInRange( 3368 entryStart, sizeof(ResTable_lib_entry)); 3369 memset(entry, 0, sizeof(*entry)); 3370 entry->packageId = htodl(libPackage->getAssignedId()); 3371 strcpy16_htod(entry->packageName, libPackage->getName().string()); 3372 } 3373 } 3374 return NO_ERROR; 3375} 3376 3377void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp) 3378{ 3379 fprintf(fp, 3380 "<!-- This file contains <public> resource definitions for all\n" 3381 " resources that were generated from the source data. -->\n" 3382 "\n" 3383 "<resources>\n"); 3384 3385 writePublicDefinitions(package, fp, true); 3386 writePublicDefinitions(package, fp, false); 3387 3388 fprintf(fp, 3389 "\n" 3390 "</resources>\n"); 3391} 3392 3393void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp, bool pub) 3394{ 3395 bool didHeader = false; 3396 3397 sp<Package> pkg = mPackages.valueFor(package); 3398 if (pkg != NULL) { 3399 const size_t NT = pkg->getOrderedTypes().size(); 3400 for (size_t i=0; i<NT; i++) { 3401 sp<Type> t = pkg->getOrderedTypes().itemAt(i); 3402 if (t == NULL) { 3403 continue; 3404 } 3405 3406 bool didType = false; 3407 3408 const size_t NC = t->getOrderedConfigs().size(); 3409 for (size_t j=0; j<NC; j++) { 3410 sp<ConfigList> c = t->getOrderedConfigs().itemAt(j); 3411 if (c == NULL) { 3412 continue; 3413 } 3414 3415 if (c->getPublic() != pub) { 3416 continue; 3417 } 3418 3419 if (!didType) { 3420 fprintf(fp, "\n"); 3421 didType = true; 3422 } 3423 if (!didHeader) { 3424 if (pub) { 3425 fprintf(fp," <!-- PUBLIC SECTION. These resources have been declared public.\n"); 3426 fprintf(fp," Changes to these definitions will break binary compatibility. -->\n\n"); 3427 } else { 3428 fprintf(fp," <!-- PRIVATE SECTION. These resources have not been declared public.\n"); 3429 fprintf(fp," You can make them public my moving these lines into a file in res/values. -->\n\n"); 3430 } 3431 didHeader = true; 3432 } 3433 if (!pub) { 3434 const size_t NE = c->getEntries().size(); 3435 for (size_t k=0; k<NE; k++) { 3436 const SourcePos& pos = c->getEntries().valueAt(k)->getPos(); 3437 if (pos.file != "") { 3438 fprintf(fp," <!-- Declared at %s:%d -->\n", 3439 pos.file.string(), pos.line); 3440 } 3441 } 3442 } 3443 fprintf(fp, " <public type=\"%s\" name=\"%s\" id=\"0x%08x\" />\n", 3444 String8(t->getName()).string(), 3445 String8(c->getName()).string(), 3446 getResId(pkg, t, c->getEntryIndex())); 3447 } 3448 } 3449 } 3450} 3451 3452ResourceTable::Item::Item(const SourcePos& _sourcePos, 3453 bool _isId, 3454 const String16& _value, 3455 const Vector<StringPool::entry_style_span>* _style, 3456 int32_t _format) 3457 : sourcePos(_sourcePos) 3458 , isId(_isId) 3459 , value(_value) 3460 , format(_format) 3461 , bagKeyId(0) 3462 , evaluating(false) 3463{ 3464 if (_style) { 3465 style = *_style; 3466 } 3467} 3468 3469ResourceTable::Entry::Entry(const Entry& entry) 3470 : RefBase() 3471 , mName(entry.mName) 3472 , mParent(entry.mParent) 3473 , mType(entry.mType) 3474 , mItem(entry.mItem) 3475 , mItemFormat(entry.mItemFormat) 3476 , mBag(entry.mBag) 3477 , mNameIndex(entry.mNameIndex) 3478 , mParentId(entry.mParentId) 3479 , mPos(entry.mPos) {} 3480 3481ResourceTable::Entry& ResourceTable::Entry::operator=(const Entry& entry) { 3482 mName = entry.mName; 3483 mParent = entry.mParent; 3484 mType = entry.mType; 3485 mItem = entry.mItem; 3486 mItemFormat = entry.mItemFormat; 3487 mBag = entry.mBag; 3488 mNameIndex = entry.mNameIndex; 3489 mParentId = entry.mParentId; 3490 mPos = entry.mPos; 3491 return *this; 3492} 3493 3494status_t ResourceTable::Entry::makeItABag(const SourcePos& sourcePos) 3495{ 3496 if (mType == TYPE_BAG) { 3497 return NO_ERROR; 3498 } 3499 if (mType == TYPE_UNKNOWN) { 3500 mType = TYPE_BAG; 3501 return NO_ERROR; 3502 } 3503 sourcePos.error("Resource entry %s is already defined as a single item.\n" 3504 "%s:%d: Originally defined here.\n", 3505 String8(mName).string(), 3506 mItem.sourcePos.file.string(), mItem.sourcePos.line); 3507 return UNKNOWN_ERROR; 3508} 3509 3510status_t ResourceTable::Entry::setItem(const SourcePos& sourcePos, 3511 const String16& value, 3512 const Vector<StringPool::entry_style_span>* style, 3513 int32_t format, 3514 const bool overwrite) 3515{ 3516 Item item(sourcePos, false, value, style); 3517 3518 if (mType == TYPE_BAG) { 3519 if (mBag.size() == 0) { 3520 sourcePos.error("Resource entry %s is already defined as a bag.", 3521 String8(mName).string()); 3522 } else { 3523 const Item& item(mBag.valueAt(0)); 3524 sourcePos.error("Resource entry %s is already defined as a bag.\n" 3525 "%s:%d: Originally defined here.\n", 3526 String8(mName).string(), 3527 item.sourcePos.file.string(), item.sourcePos.line); 3528 } 3529 return UNKNOWN_ERROR; 3530 } 3531 if ( (mType != TYPE_UNKNOWN) && (overwrite == false) ) { 3532 sourcePos.error("Resource entry %s is already defined.\n" 3533 "%s:%d: Originally defined here.\n", 3534 String8(mName).string(), 3535 mItem.sourcePos.file.string(), mItem.sourcePos.line); 3536 return UNKNOWN_ERROR; 3537 } 3538 3539 mType = TYPE_ITEM; 3540 mItem = item; 3541 mItemFormat = format; 3542 return NO_ERROR; 3543} 3544 3545status_t ResourceTable::Entry::addToBag(const SourcePos& sourcePos, 3546 const String16& key, const String16& value, 3547 const Vector<StringPool::entry_style_span>* style, 3548 bool replace, bool isId, int32_t format) 3549{ 3550 status_t err = makeItABag(sourcePos); 3551 if (err != NO_ERROR) { 3552 return err; 3553 } 3554 3555 Item item(sourcePos, isId, value, style, format); 3556 3557 // XXX NOTE: there is an error if you try to have a bag with two keys, 3558 // one an attr and one an id, with the same name. Not something we 3559 // currently ever have to worry about. 3560 ssize_t origKey = mBag.indexOfKey(key); 3561 if (origKey >= 0) { 3562 if (!replace) { 3563 const Item& item(mBag.valueAt(origKey)); 3564 sourcePos.error("Resource entry %s already has bag item %s.\n" 3565 "%s:%d: Originally defined here.\n", 3566 String8(mName).string(), String8(key).string(), 3567 item.sourcePos.file.string(), item.sourcePos.line); 3568 return UNKNOWN_ERROR; 3569 } 3570 //printf("Replacing %s with %s\n", 3571 // String8(mBag.valueFor(key).value).string(), String8(value).string()); 3572 mBag.replaceValueFor(key, item); 3573 } 3574 3575 mBag.add(key, item); 3576 return NO_ERROR; 3577} 3578 3579status_t ResourceTable::Entry::removeFromBag(const String16& key) { 3580 if (mType != Entry::TYPE_BAG) { 3581 return NO_ERROR; 3582 } 3583 3584 if (mBag.removeItem(key) >= 0) { 3585 return NO_ERROR; 3586 } 3587 return UNKNOWN_ERROR; 3588} 3589 3590status_t ResourceTable::Entry::emptyBag(const SourcePos& sourcePos) 3591{ 3592 status_t err = makeItABag(sourcePos); 3593 if (err != NO_ERROR) { 3594 return err; 3595 } 3596 3597 mBag.clear(); 3598 return NO_ERROR; 3599} 3600 3601status_t ResourceTable::Entry::generateAttributes(ResourceTable* table, 3602 const String16& package) 3603{ 3604 const String16 attr16("attr"); 3605 const String16 id16("id"); 3606 const size_t N = mBag.size(); 3607 for (size_t i=0; i<N; i++) { 3608 const String16& key = mBag.keyAt(i); 3609 const Item& it = mBag.valueAt(i); 3610 if (it.isId) { 3611 if (!table->hasBagOrEntry(key, &id16, &package)) { 3612 String16 value("false"); 3613 if (kIsDebug) { 3614 fprintf(stderr, "Generating %s:id/%s\n", 3615 String8(package).string(), 3616 String8(key).string()); 3617 } 3618 status_t err = table->addEntry(SourcePos(String8("<generated>"), 0), package, 3619 id16, key, value); 3620 if (err != NO_ERROR) { 3621 return err; 3622 } 3623 } 3624 } else if (!table->hasBagOrEntry(key, &attr16, &package)) { 3625 3626#if 1 3627// fprintf(stderr, "ERROR: Bag attribute '%s' has not been defined.\n", 3628// String8(key).string()); 3629// const Item& item(mBag.valueAt(i)); 3630// fprintf(stderr, "Referenced from file %s line %d\n", 3631// item.sourcePos.file.string(), item.sourcePos.line); 3632// return UNKNOWN_ERROR; 3633#else 3634 char numberStr[16]; 3635 sprintf(numberStr, "%d", ResTable_map::TYPE_ANY); 3636 status_t err = table->addBag(SourcePos("<generated>", 0), package, 3637 attr16, key, String16(""), 3638 String16("^type"), 3639 String16(numberStr), NULL, NULL); 3640 if (err != NO_ERROR) { 3641 return err; 3642 } 3643#endif 3644 } 3645 } 3646 return NO_ERROR; 3647} 3648 3649status_t ResourceTable::Entry::assignResourceIds(ResourceTable* table, 3650 const String16& /* package */) 3651{ 3652 bool hasErrors = false; 3653 3654 if (mType == TYPE_BAG) { 3655 const char* errorMsg; 3656 const String16 style16("style"); 3657 const String16 attr16("attr"); 3658 const String16 id16("id"); 3659 mParentId = 0; 3660 if (mParent.size() > 0) { 3661 mParentId = table->getResId(mParent, &style16, NULL, &errorMsg); 3662 if (mParentId == 0) { 3663 mPos.error("Error retrieving parent for item: %s '%s'.\n", 3664 errorMsg, String8(mParent).string()); 3665 hasErrors = true; 3666 } 3667 } 3668 const size_t N = mBag.size(); 3669 for (size_t i=0; i<N; i++) { 3670 const String16& key = mBag.keyAt(i); 3671 Item& it = mBag.editValueAt(i); 3672 it.bagKeyId = table->getResId(key, 3673 it.isId ? &id16 : &attr16, NULL, &errorMsg); 3674 //printf("Bag key of %s: #%08x\n", String8(key).string(), it.bagKeyId); 3675 if (it.bagKeyId == 0) { 3676 it.sourcePos.error("Error: %s: %s '%s'.\n", errorMsg, 3677 String8(it.isId ? id16 : attr16).string(), 3678 String8(key).string()); 3679 hasErrors = true; 3680 } 3681 } 3682 } 3683 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR; 3684} 3685 3686status_t ResourceTable::Entry::prepareFlatten(StringPool* strings, ResourceTable* table, 3687 const String8* configTypeName, const ConfigDescription* config) 3688{ 3689 if (mType == TYPE_ITEM) { 3690 Item& it = mItem; 3691 AccessorCookie ac(it.sourcePos, String8(mName), String8(it.value)); 3692 if (!table->stringToValue(&it.parsedValue, strings, 3693 it.value, false, true, 0, 3694 &it.style, NULL, &ac, mItemFormat, 3695 configTypeName, config)) { 3696 return UNKNOWN_ERROR; 3697 } 3698 } else if (mType == TYPE_BAG) { 3699 const size_t N = mBag.size(); 3700 for (size_t i=0; i<N; i++) { 3701 const String16& key = mBag.keyAt(i); 3702 Item& it = mBag.editValueAt(i); 3703 AccessorCookie ac(it.sourcePos, String8(key), String8(it.value)); 3704 if (!table->stringToValue(&it.parsedValue, strings, 3705 it.value, false, true, it.bagKeyId, 3706 &it.style, NULL, &ac, it.format, 3707 configTypeName, config)) { 3708 return UNKNOWN_ERROR; 3709 } 3710 } 3711 } else { 3712 mPos.error("Error: entry %s is not a single item or a bag.\n", 3713 String8(mName).string()); 3714 return UNKNOWN_ERROR; 3715 } 3716 return NO_ERROR; 3717} 3718 3719status_t ResourceTable::Entry::remapStringValue(StringPool* strings) 3720{ 3721 if (mType == TYPE_ITEM) { 3722 Item& it = mItem; 3723 if (it.parsedValue.dataType == Res_value::TYPE_STRING) { 3724 it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data); 3725 } 3726 } else if (mType == TYPE_BAG) { 3727 const size_t N = mBag.size(); 3728 for (size_t i=0; i<N; i++) { 3729 Item& it = mBag.editValueAt(i); 3730 if (it.parsedValue.dataType == Res_value::TYPE_STRING) { 3731 it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data); 3732 } 3733 } 3734 } else { 3735 mPos.error("Error: entry %s is not a single item or a bag.\n", 3736 String8(mName).string()); 3737 return UNKNOWN_ERROR; 3738 } 3739 return NO_ERROR; 3740} 3741 3742ssize_t ResourceTable::Entry::flatten(Bundle* /* bundle */, const sp<AaptFile>& data, bool isPublic) 3743{ 3744 size_t amt = 0; 3745 ResTable_entry header; 3746 memset(&header, 0, sizeof(header)); 3747 header.size = htods(sizeof(header)); 3748 const type ty = mType; 3749 if (ty == TYPE_BAG) { 3750 header.flags |= htods(header.FLAG_COMPLEX); 3751 } 3752 if (isPublic) { 3753 header.flags |= htods(header.FLAG_PUBLIC); 3754 } 3755 header.key.index = htodl(mNameIndex); 3756 if (ty != TYPE_BAG) { 3757 status_t err = data->writeData(&header, sizeof(header)); 3758 if (err != NO_ERROR) { 3759 fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n"); 3760 return err; 3761 } 3762 3763 const Item& it = mItem; 3764 Res_value par; 3765 memset(&par, 0, sizeof(par)); 3766 par.size = htods(it.parsedValue.size); 3767 par.dataType = it.parsedValue.dataType; 3768 par.res0 = it.parsedValue.res0; 3769 par.data = htodl(it.parsedValue.data); 3770 #if 0 3771 printf("Writing item (%s): type=%d, data=0x%x, res0=0x%x\n", 3772 String8(mName).string(), it.parsedValue.dataType, 3773 it.parsedValue.data, par.res0); 3774 #endif 3775 err = data->writeData(&par, it.parsedValue.size); 3776 if (err != NO_ERROR) { 3777 fprintf(stderr, "ERROR: out of memory creating Res_value\n"); 3778 return err; 3779 } 3780 amt += it.parsedValue.size; 3781 } else { 3782 size_t N = mBag.size(); 3783 size_t i; 3784 // Create correct ordering of items. 3785 KeyedVector<uint32_t, const Item*> items; 3786 for (i=0; i<N; i++) { 3787 const Item& it = mBag.valueAt(i); 3788 items.add(it.bagKeyId, &it); 3789 } 3790 N = items.size(); 3791 3792 ResTable_map_entry mapHeader; 3793 memcpy(&mapHeader, &header, sizeof(header)); 3794 mapHeader.size = htods(sizeof(mapHeader)); 3795 mapHeader.parent.ident = htodl(mParentId); 3796 mapHeader.count = htodl(N); 3797 status_t err = data->writeData(&mapHeader, sizeof(mapHeader)); 3798 if (err != NO_ERROR) { 3799 fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n"); 3800 return err; 3801 } 3802 3803 for (i=0; i<N; i++) { 3804 const Item& it = *items.valueAt(i); 3805 ResTable_map map; 3806 map.name.ident = htodl(it.bagKeyId); 3807 map.value.size = htods(it.parsedValue.size); 3808 map.value.dataType = it.parsedValue.dataType; 3809 map.value.res0 = it.parsedValue.res0; 3810 map.value.data = htodl(it.parsedValue.data); 3811 err = data->writeData(&map, sizeof(map)); 3812 if (err != NO_ERROR) { 3813 fprintf(stderr, "ERROR: out of memory creating Res_value\n"); 3814 return err; 3815 } 3816 amt += sizeof(map); 3817 } 3818 } 3819 return amt; 3820} 3821 3822void ResourceTable::ConfigList::appendComment(const String16& comment, 3823 bool onlyIfEmpty) 3824{ 3825 if (comment.size() <= 0) { 3826 return; 3827 } 3828 if (onlyIfEmpty && mComment.size() > 0) { 3829 return; 3830 } 3831 if (mComment.size() > 0) { 3832 mComment.append(String16("\n")); 3833 } 3834 mComment.append(comment); 3835} 3836 3837void ResourceTable::ConfigList::appendTypeComment(const String16& comment) 3838{ 3839 if (comment.size() <= 0) { 3840 return; 3841 } 3842 if (mTypeComment.size() > 0) { 3843 mTypeComment.append(String16("\n")); 3844 } 3845 mTypeComment.append(comment); 3846} 3847 3848status_t ResourceTable::Type::addPublic(const SourcePos& sourcePos, 3849 const String16& name, 3850 const uint32_t ident) 3851{ 3852 #if 0 3853 int32_t entryIdx = Res_GETENTRY(ident); 3854 if (entryIdx < 0) { 3855 sourcePos.error("Public resource %s/%s has an invalid 0 identifier (0x%08x).\n", 3856 String8(mName).string(), String8(name).string(), ident); 3857 return UNKNOWN_ERROR; 3858 } 3859 #endif 3860 3861 int32_t typeIdx = Res_GETTYPE(ident); 3862 if (typeIdx >= 0) { 3863 typeIdx++; 3864 if (mPublicIndex > 0 && mPublicIndex != typeIdx) { 3865 sourcePos.error("Public resource %s/%s has conflicting type codes for its" 3866 " public identifiers (0x%x vs 0x%x).\n", 3867 String8(mName).string(), String8(name).string(), 3868 mPublicIndex, typeIdx); 3869 return UNKNOWN_ERROR; 3870 } 3871 mPublicIndex = typeIdx; 3872 } 3873 3874 if (mFirstPublicSourcePos == NULL) { 3875 mFirstPublicSourcePos = new SourcePos(sourcePos); 3876 } 3877 3878 if (mPublic.indexOfKey(name) < 0) { 3879 mPublic.add(name, Public(sourcePos, String16(), ident)); 3880 } else { 3881 Public& p = mPublic.editValueFor(name); 3882 if (p.ident != ident) { 3883 sourcePos.error("Public resource %s/%s has conflicting public identifiers" 3884 " (0x%08x vs 0x%08x).\n" 3885 "%s:%d: Originally defined here.\n", 3886 String8(mName).string(), String8(name).string(), p.ident, ident, 3887 p.sourcePos.file.string(), p.sourcePos.line); 3888 return UNKNOWN_ERROR; 3889 } 3890 } 3891 3892 return NO_ERROR; 3893} 3894 3895void ResourceTable::Type::canAddEntry(const String16& name) 3896{ 3897 mCanAddEntries.add(name); 3898} 3899 3900sp<ResourceTable::Entry> ResourceTable::Type::getEntry(const String16& entry, 3901 const SourcePos& sourcePos, 3902 const ResTable_config* config, 3903 bool doSetIndex, 3904 bool overlay, 3905 bool autoAddOverlay) 3906{ 3907 int pos = -1; 3908 sp<ConfigList> c = mConfigs.valueFor(entry); 3909 if (c == NULL) { 3910 if (overlay && !autoAddOverlay && mCanAddEntries.indexOf(entry) < 0) { 3911 sourcePos.error("Resource at %s appears in overlay but not" 3912 " in the base package; use <add-resource> to add.\n", 3913 String8(entry).string()); 3914 return NULL; 3915 } 3916 c = new ConfigList(entry, sourcePos); 3917 mConfigs.add(entry, c); 3918 pos = (int)mOrderedConfigs.size(); 3919 mOrderedConfigs.add(c); 3920 if (doSetIndex) { 3921 c->setEntryIndex(pos); 3922 } 3923 } 3924 3925 ConfigDescription cdesc; 3926 if (config) cdesc = *config; 3927 3928 sp<Entry> e = c->getEntries().valueFor(cdesc); 3929 if (e == NULL) { 3930 if (kIsDebug) { 3931 if (config != NULL) { 3932 printf("New entry at %s:%d: imsi:%d/%d lang:%c%c cnt:%c%c " 3933 "orien:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d " 3934 "sw%ddp w%ddp h%ddp layout:%d\n", 3935 sourcePos.file.string(), sourcePos.line, 3936 config->mcc, config->mnc, 3937 config->language[0] ? config->language[0] : '-', 3938 config->language[1] ? config->language[1] : '-', 3939 config->country[0] ? config->country[0] : '-', 3940 config->country[1] ? config->country[1] : '-', 3941 config->orientation, 3942 config->touchscreen, 3943 config->density, 3944 config->keyboard, 3945 config->inputFlags, 3946 config->navigation, 3947 config->screenWidth, 3948 config->screenHeight, 3949 config->smallestScreenWidthDp, 3950 config->screenWidthDp, 3951 config->screenHeightDp, 3952 config->screenLayout); 3953 } else { 3954 printf("New entry at %s:%d: NULL config\n", 3955 sourcePos.file.string(), sourcePos.line); 3956 } 3957 } 3958 e = new Entry(entry, sourcePos); 3959 c->addEntry(cdesc, e); 3960 /* 3961 if (doSetIndex) { 3962 if (pos < 0) { 3963 for (pos=0; pos<(int)mOrderedConfigs.size(); pos++) { 3964 if (mOrderedConfigs[pos] == c) { 3965 break; 3966 } 3967 } 3968 if (pos >= (int)mOrderedConfigs.size()) { 3969 sourcePos.error("Internal error: config not found in mOrderedConfigs when adding entry"); 3970 return NULL; 3971 } 3972 } 3973 e->setEntryIndex(pos); 3974 } 3975 */ 3976 } 3977 3978 return e; 3979} 3980 3981sp<ResourceTable::ConfigList> ResourceTable::Type::removeEntry(const String16& entry) { 3982 ssize_t idx = mConfigs.indexOfKey(entry); 3983 if (idx < 0) { 3984 return NULL; 3985 } 3986 3987 sp<ConfigList> removed = mConfigs.valueAt(idx); 3988 mConfigs.removeItemsAt(idx); 3989 3990 Vector<sp<ConfigList> >::iterator iter = std::find( 3991 mOrderedConfigs.begin(), mOrderedConfigs.end(), removed); 3992 if (iter != mOrderedConfigs.end()) { 3993 mOrderedConfigs.erase(iter); 3994 } 3995 3996 mPublic.removeItem(entry); 3997 return removed; 3998} 3999 4000SortedVector<ConfigDescription> ResourceTable::Type::getUniqueConfigs() const { 4001 SortedVector<ConfigDescription> unique; 4002 const size_t entryCount = mOrderedConfigs.size(); 4003 for (size_t i = 0; i < entryCount; i++) { 4004 if (mOrderedConfigs[i] == NULL) { 4005 continue; 4006 } 4007 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& configs = 4008 mOrderedConfigs[i]->getEntries(); 4009 const size_t configCount = configs.size(); 4010 for (size_t j = 0; j < configCount; j++) { 4011 unique.add(configs.keyAt(j)); 4012 } 4013 } 4014 return unique; 4015} 4016 4017status_t ResourceTable::Type::applyPublicEntryOrder() 4018{ 4019 size_t N = mOrderedConfigs.size(); 4020 Vector<sp<ConfigList> > origOrder(mOrderedConfigs); 4021 bool hasError = false; 4022 4023 size_t i; 4024 for (i=0; i<N; i++) { 4025 mOrderedConfigs.replaceAt(NULL, i); 4026 } 4027 4028 const size_t NP = mPublic.size(); 4029 //printf("Ordering %d configs from %d public defs\n", N, NP); 4030 size_t j; 4031 for (j=0; j<NP; j++) { 4032 const String16& name = mPublic.keyAt(j); 4033 const Public& p = mPublic.valueAt(j); 4034 int32_t idx = Res_GETENTRY(p.ident); 4035 //printf("Looking for entry \"%s\"/\"%s\" (0x%08x) in %d...\n", 4036 // String8(mName).string(), String8(name).string(), p.ident, N); 4037 bool found = false; 4038 for (i=0; i<N; i++) { 4039 sp<ConfigList> e = origOrder.itemAt(i); 4040 //printf("#%d: \"%s\"\n", i, String8(e->getName()).string()); 4041 if (e->getName() == name) { 4042 if (idx >= (int32_t)mOrderedConfigs.size()) { 4043 mOrderedConfigs.resize(idx + 1); 4044 } 4045 4046 if (mOrderedConfigs.itemAt(idx) == NULL) { 4047 e->setPublic(true); 4048 e->setPublicSourcePos(p.sourcePos); 4049 mOrderedConfigs.replaceAt(e, idx); 4050 origOrder.removeAt(i); 4051 N--; 4052 found = true; 4053 break; 4054 } else { 4055 sp<ConfigList> oe = mOrderedConfigs.itemAt(idx); 4056 4057 p.sourcePos.error("Multiple entry names declared for public entry" 4058 " identifier 0x%x in type %s (%s vs %s).\n" 4059 "%s:%d: Originally defined here.", 4060 idx+1, String8(mName).string(), 4061 String8(oe->getName()).string(), 4062 String8(name).string(), 4063 oe->getPublicSourcePos().file.string(), 4064 oe->getPublicSourcePos().line); 4065 hasError = true; 4066 } 4067 } 4068 } 4069 4070 if (!found) { 4071 p.sourcePos.error("Public symbol %s/%s declared here is not defined.", 4072 String8(mName).string(), String8(name).string()); 4073 hasError = true; 4074 } 4075 } 4076 4077 //printf("Copying back in %d non-public configs, have %d\n", N, origOrder.size()); 4078 4079 if (N != origOrder.size()) { 4080 printf("Internal error: remaining private symbol count mismatch\n"); 4081 N = origOrder.size(); 4082 } 4083 4084 j = 0; 4085 for (i=0; i<N; i++) { 4086 const sp<ConfigList>& e = origOrder.itemAt(i); 4087 // There will always be enough room for the remaining entries. 4088 while (mOrderedConfigs.itemAt(j) != NULL) { 4089 j++; 4090 } 4091 mOrderedConfigs.replaceAt(e, j); 4092 j++; 4093 } 4094 4095 return hasError ? STATUST(UNKNOWN_ERROR) : NO_ERROR; 4096} 4097 4098ResourceTable::Package::Package(const String16& name, size_t packageId) 4099 : mName(name), mPackageId(packageId), 4100 mTypeStringsMapping(0xffffffff), 4101 mKeyStringsMapping(0xffffffff) 4102{ 4103} 4104 4105sp<ResourceTable::Type> ResourceTable::Package::getType(const String16& type, 4106 const SourcePos& sourcePos, 4107 bool doSetIndex) 4108{ 4109 sp<Type> t = mTypes.valueFor(type); 4110 if (t == NULL) { 4111 t = new Type(type, sourcePos); 4112 mTypes.add(type, t); 4113 mOrderedTypes.add(t); 4114 if (doSetIndex) { 4115 // For some reason the type's index is set to one plus the index 4116 // in the mOrderedTypes list, rather than just the index. 4117 t->setIndex(mOrderedTypes.size()); 4118 } 4119 } 4120 return t; 4121} 4122 4123status_t ResourceTable::Package::setTypeStrings(const sp<AaptFile>& data) 4124{ 4125 status_t err = setStrings(data, &mTypeStrings, &mTypeStringsMapping); 4126 if (err != NO_ERROR) { 4127 fprintf(stderr, "ERROR: Type string data is corrupt!\n"); 4128 return err; 4129 } 4130 4131 // Retain a reference to the new data after we've successfully replaced 4132 // all uses of the old reference (in setStrings() ). 4133 mTypeStringsData = data; 4134 return NO_ERROR; 4135} 4136 4137status_t ResourceTable::Package::setKeyStrings(const sp<AaptFile>& data) 4138{ 4139 status_t err = setStrings(data, &mKeyStrings, &mKeyStringsMapping); 4140 if (err != NO_ERROR) { 4141 fprintf(stderr, "ERROR: Key string data is corrupt!\n"); 4142 return err; 4143 } 4144 4145 // Retain a reference to the new data after we've successfully replaced 4146 // all uses of the old reference (in setStrings() ). 4147 mKeyStringsData = data; 4148 return NO_ERROR; 4149} 4150 4151status_t ResourceTable::Package::setStrings(const sp<AaptFile>& data, 4152 ResStringPool* strings, 4153 DefaultKeyedVector<String16, uint32_t>* mappings) 4154{ 4155 if (data->getData() == NULL) { 4156 return UNKNOWN_ERROR; 4157 } 4158 4159 status_t err = strings->setTo(data->getData(), data->getSize()); 4160 if (err == NO_ERROR) { 4161 const size_t N = strings->size(); 4162 for (size_t i=0; i<N; i++) { 4163 size_t len; 4164 mappings->add(String16(strings->stringAt(i, &len)), i); 4165 } 4166 } 4167 return err; 4168} 4169 4170status_t ResourceTable::Package::applyPublicTypeOrder() 4171{ 4172 size_t N = mOrderedTypes.size(); 4173 Vector<sp<Type> > origOrder(mOrderedTypes); 4174 4175 size_t i; 4176 for (i=0; i<N; i++) { 4177 mOrderedTypes.replaceAt(NULL, i); 4178 } 4179 4180 for (i=0; i<N; i++) { 4181 sp<Type> t = origOrder.itemAt(i); 4182 int32_t idx = t->getPublicIndex(); 4183 if (idx > 0) { 4184 idx--; 4185 while (idx >= (int32_t)mOrderedTypes.size()) { 4186 mOrderedTypes.add(); 4187 } 4188 if (mOrderedTypes.itemAt(idx) != NULL) { 4189 sp<Type> ot = mOrderedTypes.itemAt(idx); 4190 t->getFirstPublicSourcePos().error("Multiple type names declared for public type" 4191 " identifier 0x%x (%s vs %s).\n" 4192 "%s:%d: Originally defined here.", 4193 idx, String8(ot->getName()).string(), 4194 String8(t->getName()).string(), 4195 ot->getFirstPublicSourcePos().file.string(), 4196 ot->getFirstPublicSourcePos().line); 4197 return UNKNOWN_ERROR; 4198 } 4199 mOrderedTypes.replaceAt(t, idx); 4200 origOrder.removeAt(i); 4201 i--; 4202 N--; 4203 } 4204 } 4205 4206 size_t j=0; 4207 for (i=0; i<N; i++) { 4208 const sp<Type>& t = origOrder.itemAt(i); 4209 // There will always be enough room for the remaining types. 4210 while (mOrderedTypes.itemAt(j) != NULL) { 4211 j++; 4212 } 4213 mOrderedTypes.replaceAt(t, j); 4214 } 4215 4216 return NO_ERROR; 4217} 4218 4219void ResourceTable::Package::movePrivateAttrs() { 4220 sp<Type> attr = mTypes.valueFor(String16("attr")); 4221 if (attr == NULL) { 4222 // Nothing to do. 4223 return; 4224 } 4225 4226 Vector<sp<ConfigList> > privateAttrs; 4227 4228 bool hasPublic = false; 4229 const Vector<sp<ConfigList> >& configs = attr->getOrderedConfigs(); 4230 const size_t configCount = configs.size(); 4231 for (size_t i = 0; i < configCount; i++) { 4232 if (configs[i] == NULL) { 4233 continue; 4234 } 4235 4236 if (attr->isPublic(configs[i]->getName())) { 4237 hasPublic = true; 4238 } else { 4239 privateAttrs.add(configs[i]); 4240 } 4241 } 4242 4243 // Only if we have public attributes do we create a separate type for 4244 // private attributes. 4245 if (!hasPublic) { 4246 return; 4247 } 4248 4249 // Create a new type for private attributes. 4250 sp<Type> privateAttrType = getType(String16(kAttrPrivateType), SourcePos()); 4251 4252 const size_t privateAttrCount = privateAttrs.size(); 4253 for (size_t i = 0; i < privateAttrCount; i++) { 4254 const sp<ConfigList>& cl = privateAttrs[i]; 4255 4256 // Remove the private attributes from their current type. 4257 attr->removeEntry(cl->getName()); 4258 4259 // Add it to the new type. 4260 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& entries = cl->getEntries(); 4261 const size_t entryCount = entries.size(); 4262 for (size_t j = 0; j < entryCount; j++) { 4263 const sp<Entry>& oldEntry = entries[j]; 4264 sp<Entry> entry = privateAttrType->getEntry( 4265 cl->getName(), oldEntry->getPos(), &entries.keyAt(j)); 4266 *entry = *oldEntry; 4267 } 4268 4269 // Move the symbols to the new type. 4270 4271 } 4272} 4273 4274sp<ResourceTable::Package> ResourceTable::getPackage(const String16& package) 4275{ 4276 if (package != mAssetsPackage) { 4277 return NULL; 4278 } 4279 return mPackages.valueFor(package); 4280} 4281 4282sp<ResourceTable::Type> ResourceTable::getType(const String16& package, 4283 const String16& type, 4284 const SourcePos& sourcePos, 4285 bool doSetIndex) 4286{ 4287 sp<Package> p = getPackage(package); 4288 if (p == NULL) { 4289 return NULL; 4290 } 4291 return p->getType(type, sourcePos, doSetIndex); 4292} 4293 4294sp<ResourceTable::Entry> ResourceTable::getEntry(const String16& package, 4295 const String16& type, 4296 const String16& name, 4297 const SourcePos& sourcePos, 4298 bool overlay, 4299 const ResTable_config* config, 4300 bool doSetIndex) 4301{ 4302 sp<Type> t = getType(package, type, sourcePos, doSetIndex); 4303 if (t == NULL) { 4304 return NULL; 4305 } 4306 return t->getEntry(name, sourcePos, config, doSetIndex, overlay, mBundle->getAutoAddOverlay()); 4307} 4308 4309sp<ResourceTable::ConfigList> ResourceTable::getConfigList(const String16& package, 4310 const String16& type, const String16& name) const 4311{ 4312 const size_t packageCount = mOrderedPackages.size(); 4313 for (size_t pi = 0; pi < packageCount; pi++) { 4314 const sp<Package>& p = mOrderedPackages[pi]; 4315 if (p == NULL || p->getName() != package) { 4316 continue; 4317 } 4318 4319 const Vector<sp<Type> >& types = p->getOrderedTypes(); 4320 const size_t typeCount = types.size(); 4321 for (size_t ti = 0; ti < typeCount; ti++) { 4322 const sp<Type>& t = types[ti]; 4323 if (t == NULL || t->getName() != type) { 4324 continue; 4325 } 4326 4327 const Vector<sp<ConfigList> >& configs = t->getOrderedConfigs(); 4328 const size_t configCount = configs.size(); 4329 for (size_t ci = 0; ci < configCount; ci++) { 4330 const sp<ConfigList>& cl = configs[ci]; 4331 if (cl == NULL || cl->getName() != name) { 4332 continue; 4333 } 4334 4335 return cl; 4336 } 4337 } 4338 } 4339 return NULL; 4340} 4341 4342sp<const ResourceTable::Entry> ResourceTable::getEntry(uint32_t resID, 4343 const ResTable_config* config) const 4344{ 4345 size_t pid = Res_GETPACKAGE(resID)+1; 4346 const size_t N = mOrderedPackages.size(); 4347 sp<Package> p; 4348 for (size_t i = 0; i < N; i++) { 4349 sp<Package> check = mOrderedPackages[i]; 4350 if (check->getAssignedId() == pid) { 4351 p = check; 4352 break; 4353 } 4354 4355 } 4356 if (p == NULL) { 4357 fprintf(stderr, "warning: Package not found for resource #%08x\n", resID); 4358 return NULL; 4359 } 4360 4361 int tid = Res_GETTYPE(resID); 4362 if (tid < 0 || tid >= (int)p->getOrderedTypes().size()) { 4363 fprintf(stderr, "warning: Type not found for resource #%08x\n", resID); 4364 return NULL; 4365 } 4366 sp<Type> t = p->getOrderedTypes()[tid]; 4367 4368 int eid = Res_GETENTRY(resID); 4369 if (eid < 0 || eid >= (int)t->getOrderedConfigs().size()) { 4370 fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID); 4371 return NULL; 4372 } 4373 4374 sp<ConfigList> c = t->getOrderedConfigs()[eid]; 4375 if (c == NULL) { 4376 fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID); 4377 return NULL; 4378 } 4379 4380 ConfigDescription cdesc; 4381 if (config) cdesc = *config; 4382 sp<Entry> e = c->getEntries().valueFor(cdesc); 4383 if (c == NULL) { 4384 fprintf(stderr, "warning: Entry configuration not found for resource #%08x\n", resID); 4385 return NULL; 4386 } 4387 4388 return e; 4389} 4390 4391const ResourceTable::Item* ResourceTable::getItem(uint32_t resID, uint32_t attrID) const 4392{ 4393 sp<const Entry> e = getEntry(resID); 4394 if (e == NULL) { 4395 return NULL; 4396 } 4397 4398 const size_t N = e->getBag().size(); 4399 for (size_t i=0; i<N; i++) { 4400 const Item& it = e->getBag().valueAt(i); 4401 if (it.bagKeyId == 0) { 4402 fprintf(stderr, "warning: ID not yet assigned to '%s' in bag '%s'\n", 4403 String8(e->getName()).string(), 4404 String8(e->getBag().keyAt(i)).string()); 4405 } 4406 if (it.bagKeyId == attrID) { 4407 return ⁢ 4408 } 4409 } 4410 4411 return NULL; 4412} 4413 4414bool ResourceTable::getItemValue( 4415 uint32_t resID, uint32_t attrID, Res_value* outValue) 4416{ 4417 const Item* item = getItem(resID, attrID); 4418 4419 bool res = false; 4420 if (item != NULL) { 4421 if (item->evaluating) { 4422 sp<const Entry> e = getEntry(resID); 4423 const size_t N = e->getBag().size(); 4424 size_t i; 4425 for (i=0; i<N; i++) { 4426 if (&e->getBag().valueAt(i) == item) { 4427 break; 4428 } 4429 } 4430 fprintf(stderr, "warning: Circular reference detected in key '%s' of bag '%s'\n", 4431 String8(e->getName()).string(), 4432 String8(e->getBag().keyAt(i)).string()); 4433 return false; 4434 } 4435 item->evaluating = true; 4436 res = stringToValue(outValue, NULL, item->value, false, false, item->bagKeyId); 4437 if (kIsDebug) { 4438 if (res) { 4439 printf("getItemValue of #%08x[#%08x] (%s): type=#%08x, data=#%08x\n", 4440 resID, attrID, String8(getEntry(resID)->getName()).string(), 4441 outValue->dataType, outValue->data); 4442 } else { 4443 printf("getItemValue of #%08x[#%08x]: failed\n", 4444 resID, attrID); 4445 } 4446 } 4447 item->evaluating = false; 4448 } 4449 return res; 4450} 4451 4452/** 4453 * Returns the SDK version at which the attribute was 4454 * made public, or -1 if the resource ID is not an attribute 4455 * or is not public. 4456 */ 4457int ResourceTable::getPublicAttributeSdkLevel(uint32_t attrId) const { 4458 if (Res_GETPACKAGE(attrId) + 1 != 0x01 || Res_GETTYPE(attrId) + 1 != 0x01) { 4459 return -1; 4460 } 4461 4462 uint32_t specFlags; 4463 if (!mAssets->getIncludedResources().getResourceFlags(attrId, &specFlags)) { 4464 return -1; 4465 } 4466 4467 if ((specFlags & ResTable_typeSpec::SPEC_PUBLIC) == 0) { 4468 return -1; 4469 } 4470 4471 const size_t entryId = Res_GETENTRY(attrId); 4472 if (entryId <= 0x021c) { 4473 return 1; 4474 } else if (entryId <= 0x021d) { 4475 return 2; 4476 } else if (entryId <= 0x0269) { 4477 return SDK_CUPCAKE; 4478 } else if (entryId <= 0x028d) { 4479 return SDK_DONUT; 4480 } else if (entryId <= 0x02ad) { 4481 return SDK_ECLAIR; 4482 } else if (entryId <= 0x02b3) { 4483 return SDK_ECLAIR_0_1; 4484 } else if (entryId <= 0x02b5) { 4485 return SDK_ECLAIR_MR1; 4486 } else if (entryId <= 0x02bd) { 4487 return SDK_FROYO; 4488 } else if (entryId <= 0x02cb) { 4489 return SDK_GINGERBREAD; 4490 } else if (entryId <= 0x0361) { 4491 return SDK_HONEYCOMB; 4492 } else if (entryId <= 0x0366) { 4493 return SDK_HONEYCOMB_MR1; 4494 } else if (entryId <= 0x03a6) { 4495 return SDK_HONEYCOMB_MR2; 4496 } else if (entryId <= 0x03ae) { 4497 return SDK_JELLY_BEAN; 4498 } else if (entryId <= 0x03cc) { 4499 return SDK_JELLY_BEAN_MR1; 4500 } else if (entryId <= 0x03da) { 4501 return SDK_JELLY_BEAN_MR2; 4502 } else if (entryId <= 0x03f1) { 4503 return SDK_KITKAT; 4504 } else if (entryId <= 0x03f6) { 4505 return SDK_KITKAT_WATCH; 4506 } else if (entryId <= 0x04ce) { 4507 return SDK_LOLLIPOP; 4508 } else { 4509 // Anything else is marked as defined in 4510 // SDK_LOLLIPOP_MR1 since after this 4511 // version no attribute compat work 4512 // needs to be done. 4513 return SDK_LOLLIPOP_MR1; 4514 } 4515} 4516 4517/** 4518 * First check the Manifest, then check the command line flag. 4519 */ 4520static int getMinSdkVersion(const Bundle* bundle) { 4521 if (bundle->getManifestMinSdkVersion() != NULL && strlen(bundle->getManifestMinSdkVersion()) > 0) { 4522 return atoi(bundle->getManifestMinSdkVersion()); 4523 } else if (bundle->getMinSdkVersion() != NULL && strlen(bundle->getMinSdkVersion()) > 0) { 4524 return atoi(bundle->getMinSdkVersion()); 4525 } 4526 return 0; 4527} 4528 4529bool ResourceTable::shouldGenerateVersionedResource( 4530 const sp<ResourceTable::ConfigList>& configList, 4531 const ConfigDescription& sourceConfig, 4532 const int sdkVersionToGenerate) { 4533 assert(sdkVersionToGenerate > sourceConfig.sdkVersion); 4534 assert(configList != NULL); 4535 const DefaultKeyedVector<ConfigDescription, sp<ResourceTable::Entry>>& entries 4536 = configList->getEntries(); 4537 ssize_t idx = entries.indexOfKey(sourceConfig); 4538 4539 // The source config came from this list, so it should be here. 4540 assert(idx >= 0); 4541 4542 // The next configuration either only varies in sdkVersion, or it is completely different 4543 // and therefore incompatible. If it is incompatible, we must generate the versioned resource. 4544 4545 // NOTE: The ordering of configurations takes sdkVersion as higher precedence than other 4546 // qualifiers, so we need to iterate through the entire list to be sure there 4547 // are no higher sdk level versions of this resource. 4548 ConfigDescription tempConfig(sourceConfig); 4549 for (size_t i = static_cast<size_t>(idx) + 1; i < entries.size(); i++) { 4550 const ConfigDescription& nextConfig = entries.keyAt(i); 4551 tempConfig.sdkVersion = nextConfig.sdkVersion; 4552 if (tempConfig == nextConfig) { 4553 // The two configs are the same, check the sdk version. 4554 return sdkVersionToGenerate < nextConfig.sdkVersion; 4555 } 4556 } 4557 4558 // No match was found, so we should generate the versioned resource. 4559 return true; 4560} 4561 4562/** 4563 * Modifies the entries in the resource table to account for compatibility 4564 * issues with older versions of Android. 4565 * 4566 * This primarily handles the issue of private/public attribute clashes 4567 * in framework resources. 4568 * 4569 * AAPT has traditionally assigned resource IDs to public attributes, 4570 * and then followed those public definitions with private attributes. 4571 * 4572 * --- PUBLIC --- 4573 * | 0x01010234 | attr/color 4574 * | 0x01010235 | attr/background 4575 * 4576 * --- PRIVATE --- 4577 * | 0x01010236 | attr/secret 4578 * | 0x01010237 | attr/shhh 4579 * 4580 * Each release, when attributes are added, they take the place of the private 4581 * attributes and the private attributes are shifted down again. 4582 * 4583 * --- PUBLIC --- 4584 * | 0x01010234 | attr/color 4585 * | 0x01010235 | attr/background 4586 * | 0x01010236 | attr/shinyNewAttr 4587 * | 0x01010237 | attr/highlyValuedFeature 4588 * 4589 * --- PRIVATE --- 4590 * | 0x01010238 | attr/secret 4591 * | 0x01010239 | attr/shhh 4592 * 4593 * Platform code may look for private attributes set in a theme. If an app 4594 * compiled against a newer version of the platform uses a new public 4595 * attribute that happens to have the same ID as the private attribute 4596 * the older platform is expecting, then the behavior is undefined. 4597 * 4598 * We get around this by detecting any newly defined attributes (in L), 4599 * copy the resource into a -v21 qualified resource, and delete the 4600 * attribute from the original resource. This ensures that older platforms 4601 * don't see the new attribute, but when running on L+ platforms, the 4602 * attribute will be respected. 4603 */ 4604status_t ResourceTable::modifyForCompat(const Bundle* bundle) { 4605 const int minSdk = getMinSdkVersion(bundle); 4606 if (minSdk >= SDK_LOLLIPOP_MR1) { 4607 // Lollipop MR1 and up handles public attributes differently, no 4608 // need to do any compat modifications. 4609 return NO_ERROR; 4610 } 4611 4612 const String16 attr16("attr"); 4613 4614 const size_t packageCount = mOrderedPackages.size(); 4615 for (size_t pi = 0; pi < packageCount; pi++) { 4616 sp<Package> p = mOrderedPackages.itemAt(pi); 4617 if (p == NULL || p->getTypes().size() == 0) { 4618 // Empty, skip! 4619 continue; 4620 } 4621 4622 const size_t typeCount = p->getOrderedTypes().size(); 4623 for (size_t ti = 0; ti < typeCount; ti++) { 4624 sp<Type> t = p->getOrderedTypes().itemAt(ti); 4625 if (t == NULL) { 4626 continue; 4627 } 4628 4629 const size_t configCount = t->getOrderedConfigs().size(); 4630 for (size_t ci = 0; ci < configCount; ci++) { 4631 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci); 4632 if (c == NULL) { 4633 continue; 4634 } 4635 4636 Vector<key_value_pair_t<ConfigDescription, sp<Entry> > > entriesToAdd; 4637 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& entries = 4638 c->getEntries(); 4639 const size_t entryCount = entries.size(); 4640 for (size_t ei = 0; ei < entryCount; ei++) { 4641 const sp<Entry>& e = entries.valueAt(ei); 4642 if (e == NULL || e->getType() != Entry::TYPE_BAG) { 4643 continue; 4644 } 4645 4646 const ConfigDescription& config = entries.keyAt(ei); 4647 if (config.sdkVersion >= SDK_LOLLIPOP_MR1) { 4648 continue; 4649 } 4650 4651 KeyedVector<int, Vector<String16> > attributesToRemove; 4652 const KeyedVector<String16, Item>& bag = e->getBag(); 4653 const size_t bagCount = bag.size(); 4654 for (size_t bi = 0; bi < bagCount; bi++) { 4655 const uint32_t attrId = getResId(bag.keyAt(bi), &attr16); 4656 const int sdkLevel = getPublicAttributeSdkLevel(attrId); 4657 if (sdkLevel > 1 && sdkLevel > config.sdkVersion && sdkLevel > minSdk) { 4658 AaptUtil::appendValue(attributesToRemove, sdkLevel, bag.keyAt(bi)); 4659 } 4660 } 4661 4662 if (attributesToRemove.isEmpty()) { 4663 continue; 4664 } 4665 4666 const size_t sdkCount = attributesToRemove.size(); 4667 for (size_t i = 0; i < sdkCount; i++) { 4668 const int sdkLevel = attributesToRemove.keyAt(i); 4669 4670 if (!shouldGenerateVersionedResource(c, config, sdkLevel)) { 4671 // There is a style that will override this generated one. 4672 continue; 4673 } 4674 4675 // Duplicate the entry under the same configuration 4676 // but with sdkVersion == sdkLevel. 4677 ConfigDescription newConfig(config); 4678 newConfig.sdkVersion = sdkLevel; 4679 4680 sp<Entry> newEntry = new Entry(*e); 4681 4682 // Remove all items that have a higher SDK level than 4683 // the one we are synthesizing. 4684 for (size_t j = 0; j < sdkCount; j++) { 4685 if (j == i) { 4686 continue; 4687 } 4688 4689 if (attributesToRemove.keyAt(j) > sdkLevel) { 4690 const size_t attrCount = attributesToRemove[j].size(); 4691 for (size_t k = 0; k < attrCount; k++) { 4692 newEntry->removeFromBag(attributesToRemove[j][k]); 4693 } 4694 } 4695 } 4696 4697 entriesToAdd.add(key_value_pair_t<ConfigDescription, sp<Entry> >( 4698 newConfig, newEntry)); 4699 } 4700 4701 // Remove the attribute from the original. 4702 for (size_t i = 0; i < attributesToRemove.size(); i++) { 4703 for (size_t j = 0; j < attributesToRemove[i].size(); j++) { 4704 e->removeFromBag(attributesToRemove[i][j]); 4705 } 4706 } 4707 } 4708 4709 const size_t entriesToAddCount = entriesToAdd.size(); 4710 for (size_t i = 0; i < entriesToAddCount; i++) { 4711 assert(entries.indexOfKey(entriesToAdd[i].key) < 0); 4712 4713 if (bundle->getVerbose()) { 4714 entriesToAdd[i].value->getPos() 4715 .printf("using v%d attributes; synthesizing resource %s:%s/%s for configuration %s.", 4716 entriesToAdd[i].key.sdkVersion, 4717 String8(p->getName()).string(), 4718 String8(t->getName()).string(), 4719 String8(entriesToAdd[i].value->getName()).string(), 4720 entriesToAdd[i].key.toString().string()); 4721 } 4722 4723 sp<Entry> newEntry = t->getEntry(c->getName(), 4724 entriesToAdd[i].value->getPos(), 4725 &entriesToAdd[i].key); 4726 4727 *newEntry = *entriesToAdd[i].value; 4728 } 4729 } 4730 } 4731 } 4732 return NO_ERROR; 4733} 4734 4735const String16 kTransitionElements[] = { 4736 String16("fade"), 4737 String16("changeBounds"), 4738 String16("slide"), 4739 String16("explode"), 4740 String16("changeImageTransform"), 4741 String16("changeTransform"), 4742 String16("changeClipBounds"), 4743 String16("autoTransition"), 4744 String16("recolor"), 4745 String16("changeScroll"), 4746 String16("transitionSet"), 4747 String16("transition"), 4748 String16("transitionManager"), 4749}; 4750 4751static bool IsTransitionElement(const String16& name) { 4752 for (int i = 0, size = sizeof(kTransitionElements) / sizeof(kTransitionElements[0]); 4753 i < size; ++i) { 4754 if (name == kTransitionElements[i]) { 4755 return true; 4756 } 4757 } 4758 return false; 4759} 4760 4761status_t ResourceTable::modifyForCompat(const Bundle* bundle, 4762 const String16& resourceName, 4763 const sp<AaptFile>& target, 4764 const sp<XMLNode>& root) { 4765 const String16 vector16("vector"); 4766 const String16 animatedVector16("animated-vector"); 4767 const String16 pathInterpolator16("pathInterpolator"); 4768 4769 const int minSdk = getMinSdkVersion(bundle); 4770 if (minSdk >= SDK_LOLLIPOP_MR1) { 4771 // Lollipop MR1 and up handles public attributes differently, no 4772 // need to do any compat modifications. 4773 return NO_ERROR; 4774 } 4775 4776 const ConfigDescription config(target->getGroupEntry().toParams()); 4777 if (target->getResourceType() == "" || config.sdkVersion >= SDK_LOLLIPOP_MR1) { 4778 // Skip resources that have no type (AndroidManifest.xml) or are already version qualified 4779 // with v21 or higher. 4780 return NO_ERROR; 4781 } 4782 4783 sp<XMLNode> newRoot = NULL; 4784 int sdkVersionToGenerate = SDK_LOLLIPOP_MR1; 4785 4786 Vector<sp<XMLNode> > nodesToVisit; 4787 nodesToVisit.push(root); 4788 while (!nodesToVisit.isEmpty()) { 4789 sp<XMLNode> node = nodesToVisit.top(); 4790 nodesToVisit.pop(); 4791 4792 if (bundle->getNoVersionVectors() && (node->getElementName() == vector16 || 4793 node->getElementName() == animatedVector16 || 4794 node->getElementName() == pathInterpolator16)) { 4795 // We were told not to version vector tags, so skip the children here. 4796 continue; 4797 } 4798 4799 if (bundle->getNoVersionTransitions() && (IsTransitionElement(node->getElementName()))) { 4800 // We were told not to version transition tags, so skip the children here. 4801 continue; 4802 } 4803 4804 const Vector<XMLNode::attribute_entry>& attrs = node->getAttributes(); 4805 for (size_t i = 0; i < attrs.size(); i++) { 4806 const XMLNode::attribute_entry& attr = attrs[i]; 4807 const int sdkLevel = getPublicAttributeSdkLevel(attr.nameResId); 4808 if (sdkLevel > 1 && sdkLevel > config.sdkVersion && sdkLevel > minSdk) { 4809 if (newRoot == NULL) { 4810 newRoot = root->clone(); 4811 } 4812 4813 // Find the smallest sdk version that we need to synthesize for 4814 // and do that one. Subsequent versions will be processed on 4815 // the next pass. 4816 sdkVersionToGenerate = std::min(sdkLevel, sdkVersionToGenerate); 4817 4818 if (bundle->getVerbose()) { 4819 SourcePos(node->getFilename(), node->getStartLineNumber()).printf( 4820 "removing attribute %s%s%s from <%s>", 4821 String8(attr.ns).string(), 4822 (attr.ns.size() == 0 ? "" : ":"), 4823 String8(attr.name).string(), 4824 String8(node->getElementName()).string()); 4825 } 4826 node->removeAttribute(i); 4827 i--; 4828 } 4829 } 4830 4831 // Schedule a visit to the children. 4832 const Vector<sp<XMLNode> >& children = node->getChildren(); 4833 const size_t childCount = children.size(); 4834 for (size_t i = 0; i < childCount; i++) { 4835 nodesToVisit.push(children[i]); 4836 } 4837 } 4838 4839 if (newRoot == NULL) { 4840 return NO_ERROR; 4841 } 4842 4843 // Look to see if we already have an overriding v21 configuration. 4844 sp<ConfigList> cl = getConfigList(String16(mAssets->getPackage()), 4845 String16(target->getResourceType()), resourceName); 4846 if (shouldGenerateVersionedResource(cl, config, sdkVersionToGenerate)) { 4847 // We don't have an overriding entry for v21, so we must duplicate this one. 4848 ConfigDescription newConfig(config); 4849 newConfig.sdkVersion = sdkVersionToGenerate; 4850 sp<AaptFile> newFile = new AaptFile(target->getSourceFile(), 4851 AaptGroupEntry(newConfig), target->getResourceType()); 4852 String8 resPath = String8::format("res/%s/%s.xml", 4853 newFile->getGroupEntry().toDirName(target->getResourceType()).string(), 4854 String8(resourceName).string()); 4855 resPath.convertToResPath(); 4856 4857 // Add a resource table entry. 4858 if (bundle->getVerbose()) { 4859 SourcePos(target->getSourceFile(), -1).printf( 4860 "using v%d attributes; synthesizing resource %s:%s/%s for configuration %s.", 4861 newConfig.sdkVersion, 4862 mAssets->getPackage().string(), 4863 newFile->getResourceType().string(), 4864 String8(resourceName).string(), 4865 newConfig.toString().string()); 4866 } 4867 4868 addEntry(SourcePos(), 4869 String16(mAssets->getPackage()), 4870 String16(target->getResourceType()), 4871 resourceName, 4872 String16(resPath), 4873 NULL, 4874 &newConfig); 4875 4876 // Schedule this to be compiled. 4877 CompileResourceWorkItem item; 4878 item.resourceName = resourceName; 4879 item.resPath = resPath; 4880 item.file = newFile; 4881 item.xmlRoot = newRoot; 4882 item.needsCompiling = false; // This step occurs after we parse/assign, so we don't need 4883 // to do it again. 4884 mWorkQueue.push(item); 4885 } 4886 return NO_ERROR; 4887} 4888 4889void ResourceTable::getDensityVaryingResources( 4890 KeyedVector<Symbol, Vector<SymbolDefinition> >& resources) { 4891 const ConfigDescription nullConfig; 4892 4893 const size_t packageCount = mOrderedPackages.size(); 4894 for (size_t p = 0; p < packageCount; p++) { 4895 const Vector<sp<Type> >& types = mOrderedPackages[p]->getOrderedTypes(); 4896 const size_t typeCount = types.size(); 4897 for (size_t t = 0; t < typeCount; t++) { 4898 const sp<Type>& type = types[t]; 4899 if (type == NULL) { 4900 continue; 4901 } 4902 4903 const Vector<sp<ConfigList> >& configs = type->getOrderedConfigs(); 4904 const size_t configCount = configs.size(); 4905 for (size_t c = 0; c < configCount; c++) { 4906 const sp<ConfigList>& configList = configs[c]; 4907 if (configList == NULL) { 4908 continue; 4909 } 4910 4911 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& configEntries 4912 = configList->getEntries(); 4913 const size_t configEntryCount = configEntries.size(); 4914 for (size_t ce = 0; ce < configEntryCount; ce++) { 4915 const sp<Entry>& entry = configEntries.valueAt(ce); 4916 if (entry == NULL) { 4917 continue; 4918 } 4919 4920 const ConfigDescription& config = configEntries.keyAt(ce); 4921 if (AaptConfig::isDensityOnly(config)) { 4922 // This configuration only varies with regards to density. 4923 const Symbol symbol( 4924 mOrderedPackages[p]->getName(), 4925 type->getName(), 4926 configList->getName(), 4927 getResId(mOrderedPackages[p], types[t], 4928 configList->getEntryIndex())); 4929 4930 4931 AaptUtil::appendValue(resources, symbol, 4932 SymbolDefinition(symbol, config, entry->getPos())); 4933 } 4934 } 4935 } 4936 } 4937 } 4938} 4939 4940static String16 buildNamespace(const String16& package) { 4941 return String16("http://schemas.android.com/apk/res/") + package; 4942} 4943 4944static sp<XMLNode> findOnlyChildElement(const sp<XMLNode>& parent) { 4945 const Vector<sp<XMLNode> >& children = parent->getChildren(); 4946 sp<XMLNode> onlyChild; 4947 for (size_t i = 0; i < children.size(); i++) { 4948 if (children[i]->getType() != XMLNode::TYPE_CDATA) { 4949 if (onlyChild != NULL) { 4950 return NULL; 4951 } 4952 onlyChild = children[i]; 4953 } 4954 } 4955 return onlyChild; 4956} 4957 4958/** 4959 * Detects use of the `bundle' format and extracts nested resources into their own top level 4960 * resources. The bundle format looks like this: 4961 * 4962 * <!-- res/drawable/bundle.xml --> 4963 * <animated-vector xmlns:aapt="http://schemas.android.com/aapt"> 4964 * <aapt:attr name="android:drawable"> 4965 * <vector android:width="60dp" 4966 * android:height="60dp"> 4967 * <path android:name="v" 4968 * android:fillColor="#000000" 4969 * android:pathData="M300,70 l 0,-70 70,..." /> 4970 * </vector> 4971 * </aapt:attr> 4972 * </animated-vector> 4973 * 4974 * When AAPT sees the <aapt:attr> tag, it will extract its single element and its children 4975 * into a new high-level resource, assigning it a name and ID. Then value of the `name` 4976 * attribute must be a resource attribute. That resource attribute is inserted into the parent 4977 * with the reference to the extracted resource as the value. 4978 * 4979 * <!-- res/drawable/bundle.xml --> 4980 * <animated-vector android:drawable="@drawable/bundle_1.xml"> 4981 * </animated-vector> 4982 * 4983 * <!-- res/drawable/bundle_1.xml --> 4984 * <vector android:width="60dp" 4985 * android:height="60dp"> 4986 * <path android:name="v" 4987 * android:fillColor="#000000" 4988 * android:pathData="M300,70 l 0,-70 70,..." /> 4989 * </vector> 4990 */ 4991status_t ResourceTable::processBundleFormat(const Bundle* bundle, 4992 const String16& resourceName, 4993 const sp<AaptFile>& target, 4994 const sp<XMLNode>& root) { 4995 Vector<sp<XMLNode> > namespaces; 4996 if (root->getType() == XMLNode::TYPE_NAMESPACE) { 4997 namespaces.push(root); 4998 } 4999 return processBundleFormatImpl(bundle, resourceName, target, root, &namespaces); 5000} 5001 5002status_t ResourceTable::processBundleFormatImpl(const Bundle* bundle, 5003 const String16& resourceName, 5004 const sp<AaptFile>& target, 5005 const sp<XMLNode>& parent, 5006 Vector<sp<XMLNode> >* namespaces) { 5007 const String16 kAaptNamespaceUri16("http://schemas.android.com/aapt"); 5008 const String16 kName16("name"); 5009 const String16 kAttr16("attr"); 5010 const String16 kAssetPackage16(mAssets->getPackage()); 5011 5012 Vector<sp<XMLNode> >& children = parent->getChildren(); 5013 for (size_t i = 0; i < children.size(); i++) { 5014 const sp<XMLNode>& child = children[i]; 5015 5016 if (child->getType() == XMLNode::TYPE_CDATA) { 5017 continue; 5018 } else if (child->getType() == XMLNode::TYPE_NAMESPACE) { 5019 namespaces->push(child); 5020 } 5021 5022 if (child->getElementNamespace() != kAaptNamespaceUri16 || 5023 child->getElementName() != kAttr16) { 5024 status_t result = processBundleFormatImpl(bundle, resourceName, target, child, 5025 namespaces); 5026 if (result != NO_ERROR) { 5027 return result; 5028 } 5029 5030 if (child->getType() == XMLNode::TYPE_NAMESPACE) { 5031 namespaces->pop(); 5032 } 5033 continue; 5034 } 5035 5036 // This is the <aapt:attr> tag. Look for the 'name' attribute. 5037 SourcePos source(child->getFilename(), child->getStartLineNumber()); 5038 5039 sp<XMLNode> nestedRoot = findOnlyChildElement(child); 5040 if (nestedRoot == NULL) { 5041 source.error("<%s:%s> must have exactly one child element", 5042 String8(child->getElementNamespace()).string(), 5043 String8(child->getElementName()).string()); 5044 return UNKNOWN_ERROR; 5045 } 5046 5047 // Find the special attribute 'parent-attr'. This attribute's value contains 5048 // the resource attribute for which this element should be assigned in the parent. 5049 const XMLNode::attribute_entry* attr = child->getAttribute(String16(), kName16); 5050 if (attr == NULL) { 5051 source.error("inline resource definition must specify an attribute via 'name'"); 5052 return UNKNOWN_ERROR; 5053 } 5054 5055 // Parse the attribute name. 5056 const char* errorMsg = NULL; 5057 String16 attrPackage, attrType, attrName; 5058 bool result = ResTable::expandResourceRef(attr->string.string(), 5059 attr->string.size(), 5060 &attrPackage, &attrType, &attrName, 5061 &kAttr16, &kAssetPackage16, 5062 &errorMsg, NULL); 5063 if (!result) { 5064 source.error("invalid attribute name for 'name': %s", errorMsg); 5065 return UNKNOWN_ERROR; 5066 } 5067 5068 if (attrType != kAttr16) { 5069 // The value of the 'name' attribute must be an attribute reference. 5070 source.error("value of 'name' must be an attribute reference."); 5071 return UNKNOWN_ERROR; 5072 } 5073 5074 // Generate a name for this nested resource and try to add it to the table. 5075 // We do this in a loop because the name may be taken, in which case we will 5076 // increment a suffix until we succeed. 5077 String8 nestedResourceName; 5078 String8 nestedResourcePath; 5079 int suffix = 1; 5080 while (true) { 5081 // This child element will be extracted into its own resource file. 5082 // Generate a name and path for it from its parent. 5083 nestedResourceName = String8::format("%s_%d", 5084 String8(resourceName).string(), suffix++); 5085 nestedResourcePath = String8::format("res/%s/%s.xml", 5086 target->getGroupEntry().toDirName(target->getResourceType()) 5087 .string(), 5088 nestedResourceName.string()); 5089 5090 // Lookup or create the entry for this name. 5091 sp<Entry> entry = getEntry(kAssetPackage16, 5092 String16(target->getResourceType()), 5093 String16(nestedResourceName), 5094 source, 5095 false, 5096 &target->getGroupEntry().toParams(), 5097 true); 5098 if (entry == NULL) { 5099 return UNKNOWN_ERROR; 5100 } 5101 5102 if (entry->getType() == Entry::TYPE_UNKNOWN) { 5103 // The value for this resource has never been set, 5104 // meaning we're good! 5105 entry->setItem(source, String16(nestedResourcePath)); 5106 break; 5107 } 5108 5109 // We failed (name already exists), so try with a different name 5110 // (increment the suffix). 5111 } 5112 5113 if (bundle->getVerbose()) { 5114 source.printf("generating nested resource %s:%s/%s", 5115 mAssets->getPackage().string(), target->getResourceType().string(), 5116 nestedResourceName.string()); 5117 } 5118 5119 // Build the attribute reference and assign it to the parent. 5120 String16 nestedResourceRef = String16(String8::format("@%s:%s/%s", 5121 mAssets->getPackage().string(), target->getResourceType().string(), 5122 nestedResourceName.string())); 5123 5124 String16 attrNs = buildNamespace(attrPackage); 5125 if (parent->getAttribute(attrNs, attrName) != NULL) { 5126 SourcePos(parent->getFilename(), parent->getStartLineNumber()) 5127 .error("parent of nested resource already defines attribute '%s:%s'", 5128 String8(attrPackage).string(), String8(attrName).string()); 5129 return UNKNOWN_ERROR; 5130 } 5131 5132 // Add the reference to the inline resource. 5133 parent->addAttribute(attrNs, attrName, nestedResourceRef); 5134 5135 // Remove the <aapt:attr> child element from here. 5136 children.removeAt(i); 5137 i--; 5138 5139 // Append all namespace declarations that we've seen on this branch in the XML tree 5140 // to this resource. 5141 // We do this because the order of namespace declarations and prefix usage is determined 5142 // by the developer and we do not want to override any decisions. Be conservative. 5143 for (size_t nsIndex = namespaces->size(); nsIndex > 0; nsIndex--) { 5144 const sp<XMLNode>& ns = namespaces->itemAt(nsIndex - 1); 5145 sp<XMLNode> newNs = XMLNode::newNamespace(ns->getFilename(), ns->getNamespacePrefix(), 5146 ns->getNamespaceUri()); 5147 newNs->addChild(nestedRoot); 5148 nestedRoot = newNs; 5149 } 5150 5151 // Schedule compilation of the nested resource. 5152 CompileResourceWorkItem workItem; 5153 workItem.resPath = nestedResourcePath; 5154 workItem.resourceName = String16(nestedResourceName); 5155 workItem.xmlRoot = nestedRoot; 5156 workItem.file = new AaptFile(target->getSourceFile(), target->getGroupEntry(), 5157 target->getResourceType()); 5158 mWorkQueue.push(workItem); 5159 } 5160 return NO_ERROR; 5161} 5162