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