Resource.cpp revision 2cfc8482267707a671cbe4275ea8927c1aef991a
1// 2// Copyright 2006 The Android Open Source Project 3// 4// Build resource files from raw assets. 5// 6#include "Main.h" 7#include "AaptAssets.h" 8#include "StringPool.h" 9#include "XMLNode.h" 10#include "ResourceTable.h" 11#include "Images.h" 12 13#include "CrunchCache.h" 14#include "FileFinder.h" 15#include "CacheUpdater.h" 16 17#include "WorkQueue.h" 18 19#if HAVE_PRINTF_ZD 20# define ZD "%zd" 21# define ZD_TYPE ssize_t 22#else 23# define ZD "%ld" 24# define ZD_TYPE long 25#endif 26 27#define NOISY(x) // x 28 29// Number of threads to use for preprocessing images. 30static const size_t MAX_THREADS = 4; 31 32// ========================================================================== 33// ========================================================================== 34// ========================================================================== 35 36class PackageInfo 37{ 38public: 39 PackageInfo() 40 { 41 } 42 ~PackageInfo() 43 { 44 } 45 46 status_t parsePackage(const sp<AaptGroup>& grp); 47}; 48 49// ========================================================================== 50// ========================================================================== 51// ========================================================================== 52 53static String8 parseResourceName(const String8& leaf) 54{ 55 const char* firstDot = strchr(leaf.string(), '.'); 56 const char* str = leaf.string(); 57 58 if (firstDot) { 59 return String8(str, firstDot-str); 60 } else { 61 return String8(str); 62 } 63} 64 65ResourceTypeSet::ResourceTypeSet() 66 :RefBase(), 67 KeyedVector<String8,sp<AaptGroup> >() 68{ 69} 70 71FilePathStore::FilePathStore() 72 :RefBase(), 73 Vector<String8>() 74{ 75} 76 77class ResourceDirIterator 78{ 79public: 80 ResourceDirIterator(const sp<ResourceTypeSet>& set, const String8& resType) 81 : mResType(resType), mSet(set), mSetPos(0), mGroupPos(0) 82 { 83 memset(&mParams, 0, sizeof(ResTable_config)); 84 } 85 86 inline const sp<AaptGroup>& getGroup() const { return mGroup; } 87 inline const sp<AaptFile>& getFile() const { return mFile; } 88 89 inline const String8& getBaseName() const { return mBaseName; } 90 inline const String8& getLeafName() const { return mLeafName; } 91 inline String8 getPath() const { return mPath; } 92 inline const ResTable_config& getParams() const { return mParams; } 93 94 enum { 95 EOD = 1 96 }; 97 98 ssize_t next() 99 { 100 while (true) { 101 sp<AaptGroup> group; 102 sp<AaptFile> file; 103 104 // Try to get next file in this current group. 105 if (mGroup != NULL && mGroupPos < mGroup->getFiles().size()) { 106 group = mGroup; 107 file = group->getFiles().valueAt(mGroupPos++); 108 109 // Try to get the next group/file in this directory 110 } else if (mSetPos < mSet->size()) { 111 mGroup = group = mSet->valueAt(mSetPos++); 112 if (group->getFiles().size() < 1) { 113 continue; 114 } 115 file = group->getFiles().valueAt(0); 116 mGroupPos = 1; 117 118 // All done! 119 } else { 120 return EOD; 121 } 122 123 mFile = file; 124 125 String8 leaf(group->getLeaf()); 126 mLeafName = String8(leaf); 127 mParams = file->getGroupEntry().toParams(); 128 NOISY(printf("Dir %s: mcc=%d mnc=%d lang=%c%c cnt=%c%c orient=%d ui=%d density=%d touch=%d key=%d inp=%d nav=%d\n", 129 group->getPath().string(), mParams.mcc, mParams.mnc, 130 mParams.language[0] ? mParams.language[0] : '-', 131 mParams.language[1] ? mParams.language[1] : '-', 132 mParams.country[0] ? mParams.country[0] : '-', 133 mParams.country[1] ? mParams.country[1] : '-', 134 mParams.orientation, mParams.uiMode, 135 mParams.density, mParams.touchscreen, mParams.keyboard, 136 mParams.inputFlags, mParams.navigation)); 137 mPath = "res"; 138 mPath.appendPath(file->getGroupEntry().toDirName(mResType)); 139 mPath.appendPath(leaf); 140 mBaseName = parseResourceName(leaf); 141 if (mBaseName == "") { 142 fprintf(stderr, "Error: malformed resource filename %s\n", 143 file->getPrintableSource().string()); 144 return UNKNOWN_ERROR; 145 } 146 147 NOISY(printf("file name=%s\n", mBaseName.string())); 148 149 return NO_ERROR; 150 } 151 } 152 153private: 154 String8 mResType; 155 156 const sp<ResourceTypeSet> mSet; 157 size_t mSetPos; 158 159 sp<AaptGroup> mGroup; 160 size_t mGroupPos; 161 162 sp<AaptFile> mFile; 163 String8 mBaseName; 164 String8 mLeafName; 165 String8 mPath; 166 ResTable_config mParams; 167}; 168 169class AnnotationProcessor { 170public: 171 AnnotationProcessor() : mDeprecated(false), mSystemApi(false) { } 172 173 void preprocessComment(String8& comment) { 174 if (comment.size() > 0) { 175 if (comment.contains("@deprecated")) { 176 mDeprecated = true; 177 } 178 if (comment.removeAll("@SystemApi")) { 179 mSystemApi = true; 180 } 181 } 182 } 183 184 void printAnnotations(FILE* fp, const char* indentStr) { 185 if (mDeprecated) { 186 fprintf(fp, "%s@Deprecated\n", indentStr); 187 } 188 if (mSystemApi) { 189 fprintf(fp, "%s@android.annotation.SystemApi\n", indentStr); 190 } 191 } 192 193private: 194 bool mDeprecated; 195 bool mSystemApi; 196}; 197 198// ========================================================================== 199// ========================================================================== 200// ========================================================================== 201 202bool isValidResourceType(const String8& type) 203{ 204 return type == "anim" || type == "animator" || type == "interpolator" 205 || type == "transition" 206 || type == "drawable" || type == "layout" 207 || type == "values" || type == "xml" || type == "raw" 208 || type == "color" || type == "menu" || type == "mipmap"; 209} 210 211static status_t parsePackage(Bundle* bundle, const sp<AaptAssets>& assets, 212 const sp<AaptGroup>& grp) 213{ 214 if (grp->getFiles().size() != 1) { 215 fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n", 216 grp->getFiles().valueAt(0)->getPrintableSource().string()); 217 } 218 219 sp<AaptFile> file = grp->getFiles().valueAt(0); 220 221 ResXMLTree block; 222 status_t err = parseXMLResource(file, &block); 223 if (err != NO_ERROR) { 224 return err; 225 } 226 //printXMLBlock(&block); 227 228 ResXMLTree::event_code_t code; 229 while ((code=block.next()) != ResXMLTree::START_TAG 230 && code != ResXMLTree::END_DOCUMENT 231 && code != ResXMLTree::BAD_DOCUMENT) { 232 } 233 234 size_t len; 235 if (code != ResXMLTree::START_TAG) { 236 fprintf(stderr, "%s:%d: No start tag found\n", 237 file->getPrintableSource().string(), block.getLineNumber()); 238 return UNKNOWN_ERROR; 239 } 240 if (strcmp16(block.getElementName(&len), String16("manifest").string()) != 0) { 241 fprintf(stderr, "%s:%d: Invalid start tag %s, expected <manifest>\n", 242 file->getPrintableSource().string(), block.getLineNumber(), 243 String8(block.getElementName(&len)).string()); 244 return UNKNOWN_ERROR; 245 } 246 247 ssize_t nameIndex = block.indexOfAttribute(NULL, "package"); 248 if (nameIndex < 0) { 249 fprintf(stderr, "%s:%d: <manifest> does not have package attribute.\n", 250 file->getPrintableSource().string(), block.getLineNumber()); 251 return UNKNOWN_ERROR; 252 } 253 254 assets->setPackage(String8(block.getAttributeStringValue(nameIndex, &len))); 255 256 String16 uses_sdk16("uses-sdk"); 257 while ((code=block.next()) != ResXMLTree::END_DOCUMENT 258 && code != ResXMLTree::BAD_DOCUMENT) { 259 if (code == ResXMLTree::START_TAG) { 260 if (strcmp16(block.getElementName(&len), uses_sdk16.string()) == 0) { 261 ssize_t minSdkIndex = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, 262 "minSdkVersion"); 263 if (minSdkIndex >= 0) { 264 const uint16_t* minSdk16 = block.getAttributeStringValue(minSdkIndex, &len); 265 const char* minSdk8 = strdup(String8(minSdk16).string()); 266 bundle->setManifestMinSdkVersion(minSdk8); 267 } 268 } 269 } 270 } 271 272 return NO_ERROR; 273} 274 275// ========================================================================== 276// ========================================================================== 277// ========================================================================== 278 279static status_t makeFileResources(Bundle* bundle, const sp<AaptAssets>& assets, 280 ResourceTable* table, 281 const sp<ResourceTypeSet>& set, 282 const char* resType) 283{ 284 String8 type8(resType); 285 String16 type16(resType); 286 287 bool hasErrors = false; 288 289 ResourceDirIterator it(set, String8(resType)); 290 ssize_t res; 291 while ((res=it.next()) == NO_ERROR) { 292 if (bundle->getVerbose()) { 293 printf(" (new resource id %s from %s)\n", 294 it.getBaseName().string(), it.getFile()->getPrintableSource().string()); 295 } 296 String16 baseName(it.getBaseName()); 297 const char16_t* str = baseName.string(); 298 const char16_t* const end = str + baseName.size(); 299 while (str < end) { 300 if (!((*str >= 'a' && *str <= 'z') 301 || (*str >= '0' && *str <= '9') 302 || *str == '_' || *str == '.')) { 303 fprintf(stderr, "%s: Invalid file name: must contain only [a-z0-9_.]\n", 304 it.getPath().string()); 305 hasErrors = true; 306 } 307 str++; 308 } 309 String8 resPath = it.getPath(); 310 resPath.convertToResPath(); 311 table->addEntry(SourcePos(it.getPath(), 0), String16(assets->getPackage()), 312 type16, 313 baseName, 314 String16(resPath), 315 NULL, 316 &it.getParams()); 317 assets->addResource(it.getLeafName(), resPath, it.getFile(), type8); 318 } 319 320 return hasErrors ? UNKNOWN_ERROR : NO_ERROR; 321} 322 323class PreProcessImageWorkUnit : public WorkQueue::WorkUnit { 324public: 325 PreProcessImageWorkUnit(const Bundle* bundle, const sp<AaptAssets>& assets, 326 const sp<AaptFile>& file, volatile bool* hasErrors) : 327 mBundle(bundle), mAssets(assets), mFile(file), mHasErrors(hasErrors) { 328 } 329 330 virtual bool run() { 331 status_t status = preProcessImage(mBundle, mAssets, mFile, NULL); 332 if (status) { 333 *mHasErrors = true; 334 } 335 return true; // continue even if there are errors 336 } 337 338private: 339 const Bundle* mBundle; 340 sp<AaptAssets> mAssets; 341 sp<AaptFile> mFile; 342 volatile bool* mHasErrors; 343}; 344 345static status_t preProcessImages(const Bundle* bundle, const sp<AaptAssets>& assets, 346 const sp<ResourceTypeSet>& set, const char* type) 347{ 348 volatile bool hasErrors = false; 349 ssize_t res = NO_ERROR; 350 if (bundle->getUseCrunchCache() == false) { 351 WorkQueue wq(MAX_THREADS, false); 352 ResourceDirIterator it(set, String8(type)); 353 while ((res=it.next()) == NO_ERROR) { 354 PreProcessImageWorkUnit* w = new PreProcessImageWorkUnit( 355 bundle, assets, it.getFile(), &hasErrors); 356 status_t status = wq.schedule(w); 357 if (status) { 358 fprintf(stderr, "preProcessImages failed: schedule() returned %d\n", status); 359 hasErrors = true; 360 delete w; 361 break; 362 } 363 } 364 status_t status = wq.finish(); 365 if (status) { 366 fprintf(stderr, "preProcessImages failed: finish() returned %d\n", status); 367 hasErrors = true; 368 } 369 } 370 return (hasErrors || (res < NO_ERROR)) ? UNKNOWN_ERROR : NO_ERROR; 371} 372 373static void collect_files(const sp<AaptDir>& dir, 374 KeyedVector<String8, sp<ResourceTypeSet> >* resources) 375{ 376 const DefaultKeyedVector<String8, sp<AaptGroup> >& groups = dir->getFiles(); 377 int N = groups.size(); 378 for (int i=0; i<N; i++) { 379 String8 leafName = groups.keyAt(i); 380 const sp<AaptGroup>& group = groups.valueAt(i); 381 382 const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files 383 = group->getFiles(); 384 385 if (files.size() == 0) { 386 continue; 387 } 388 389 String8 resType = files.valueAt(0)->getResourceType(); 390 391 ssize_t index = resources->indexOfKey(resType); 392 393 if (index < 0) { 394 sp<ResourceTypeSet> set = new ResourceTypeSet(); 395 NOISY(printf("Creating new resource type set for leaf %s with group %s (%p)\n", 396 leafName.string(), group->getPath().string(), group.get())); 397 set->add(leafName, group); 398 resources->add(resType, set); 399 } else { 400 sp<ResourceTypeSet> set = resources->valueAt(index); 401 index = set->indexOfKey(leafName); 402 if (index < 0) { 403 NOISY(printf("Adding to resource type set for leaf %s group %s (%p)\n", 404 leafName.string(), group->getPath().string(), group.get())); 405 set->add(leafName, group); 406 } else { 407 sp<AaptGroup> existingGroup = set->valueAt(index); 408 NOISY(printf("Extending to resource type set for leaf %s group %s (%p)\n", 409 leafName.string(), group->getPath().string(), group.get())); 410 for (size_t j=0; j<files.size(); j++) { 411 NOISY(printf("Adding file %s in group %s resType %s\n", 412 files.valueAt(j)->getSourceFile().string(), 413 files.keyAt(j).toDirName(String8()).string(), 414 resType.string())); 415 status_t err = existingGroup->addFile(files.valueAt(j)); 416 } 417 } 418 } 419 } 420} 421 422static void collect_files(const sp<AaptAssets>& ass, 423 KeyedVector<String8, sp<ResourceTypeSet> >* resources) 424{ 425 const Vector<sp<AaptDir> >& dirs = ass->resDirs(); 426 int N = dirs.size(); 427 428 for (int i=0; i<N; i++) { 429 sp<AaptDir> d = dirs.itemAt(i); 430 NOISY(printf("Collecting dir #%d %p: %s, leaf %s\n", i, d.get(), d->getPath().string(), 431 d->getLeaf().string())); 432 collect_files(d, resources); 433 434 // don't try to include the res dir 435 NOISY(printf("Removing dir leaf %s\n", d->getLeaf().string())); 436 ass->removeDir(d->getLeaf()); 437 } 438} 439 440enum { 441 ATTR_OKAY = -1, 442 ATTR_NOT_FOUND = -2, 443 ATTR_LEADING_SPACES = -3, 444 ATTR_TRAILING_SPACES = -4 445}; 446static int validateAttr(const String8& path, const ResTable& table, 447 const ResXMLParser& parser, 448 const char* ns, const char* attr, const char* validChars, bool required) 449{ 450 size_t len; 451 452 ssize_t index = parser.indexOfAttribute(ns, attr); 453 const uint16_t* str; 454 Res_value value; 455 if (index >= 0 && parser.getAttributeValue(index, &value) >= 0) { 456 const ResStringPool* pool = &parser.getStrings(); 457 if (value.dataType == Res_value::TYPE_REFERENCE) { 458 uint32_t specFlags = 0; 459 int strIdx; 460 if ((strIdx=table.resolveReference(&value, 0x10000000, NULL, &specFlags)) < 0) { 461 fprintf(stderr, "%s:%d: Tag <%s> attribute %s references unknown resid 0x%08x.\n", 462 path.string(), parser.getLineNumber(), 463 String8(parser.getElementName(&len)).string(), attr, 464 value.data); 465 return ATTR_NOT_FOUND; 466 } 467 468 pool = table.getTableStringBlock(strIdx); 469 #if 0 470 if (pool != NULL) { 471 str = pool->stringAt(value.data, &len); 472 } 473 printf("***** RES ATTR: %s specFlags=0x%x strIdx=%d: %s\n", attr, 474 specFlags, strIdx, str != NULL ? String8(str).string() : "???"); 475 #endif 476 if ((specFlags&~ResTable_typeSpec::SPEC_PUBLIC) != 0 && false) { 477 fprintf(stderr, "%s:%d: Tag <%s> attribute %s varies by configurations 0x%x.\n", 478 path.string(), parser.getLineNumber(), 479 String8(parser.getElementName(&len)).string(), attr, 480 specFlags); 481 return ATTR_NOT_FOUND; 482 } 483 } 484 if (value.dataType == Res_value::TYPE_STRING) { 485 if (pool == NULL) { 486 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has no string block.\n", 487 path.string(), parser.getLineNumber(), 488 String8(parser.getElementName(&len)).string(), attr); 489 return ATTR_NOT_FOUND; 490 } 491 if ((str=pool->stringAt(value.data, &len)) == NULL) { 492 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has corrupt string value.\n", 493 path.string(), parser.getLineNumber(), 494 String8(parser.getElementName(&len)).string(), attr); 495 return ATTR_NOT_FOUND; 496 } 497 } else { 498 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has invalid type %d.\n", 499 path.string(), parser.getLineNumber(), 500 String8(parser.getElementName(&len)).string(), attr, 501 value.dataType); 502 return ATTR_NOT_FOUND; 503 } 504 if (validChars) { 505 for (size_t i=0; i<len; i++) { 506 uint16_t c = str[i]; 507 const char* p = validChars; 508 bool okay = false; 509 while (*p) { 510 if (c == *p) { 511 okay = true; 512 break; 513 } 514 p++; 515 } 516 if (!okay) { 517 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has invalid character '%c'.\n", 518 path.string(), parser.getLineNumber(), 519 String8(parser.getElementName(&len)).string(), attr, (char)str[i]); 520 return (int)i; 521 } 522 } 523 } 524 if (*str == ' ') { 525 fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not start with a space.\n", 526 path.string(), parser.getLineNumber(), 527 String8(parser.getElementName(&len)).string(), attr); 528 return ATTR_LEADING_SPACES; 529 } 530 if (str[len-1] == ' ') { 531 fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not end with a space.\n", 532 path.string(), parser.getLineNumber(), 533 String8(parser.getElementName(&len)).string(), attr); 534 return ATTR_TRAILING_SPACES; 535 } 536 return ATTR_OKAY; 537 } 538 if (required) { 539 fprintf(stderr, "%s:%d: Tag <%s> missing required attribute %s.\n", 540 path.string(), parser.getLineNumber(), 541 String8(parser.getElementName(&len)).string(), attr); 542 return ATTR_NOT_FOUND; 543 } 544 return ATTR_OKAY; 545} 546 547static void checkForIds(const String8& path, ResXMLParser& parser) 548{ 549 ResXMLTree::event_code_t code; 550 while ((code=parser.next()) != ResXMLTree::END_DOCUMENT 551 && code > ResXMLTree::BAD_DOCUMENT) { 552 if (code == ResXMLTree::START_TAG) { 553 ssize_t index = parser.indexOfAttribute(NULL, "id"); 554 if (index >= 0) { 555 fprintf(stderr, "%s:%d: warning: found plain 'id' attribute; did you mean the new 'android:id' name?\n", 556 path.string(), parser.getLineNumber()); 557 } 558 } 559 } 560} 561 562static bool applyFileOverlay(Bundle *bundle, 563 const sp<AaptAssets>& assets, 564 sp<ResourceTypeSet> *baseSet, 565 const char *resType) 566{ 567 if (bundle->getVerbose()) { 568 printf("applyFileOverlay for %s\n", resType); 569 } 570 571 // Replace any base level files in this category with any found from the overlay 572 // Also add any found only in the overlay. 573 sp<AaptAssets> overlay = assets->getOverlay(); 574 String8 resTypeString(resType); 575 576 // work through the linked list of overlays 577 while (overlay.get()) { 578 KeyedVector<String8, sp<ResourceTypeSet> >* overlayRes = overlay->getResources(); 579 580 // get the overlay resources of the requested type 581 ssize_t index = overlayRes->indexOfKey(resTypeString); 582 if (index >= 0) { 583 sp<ResourceTypeSet> overlaySet = overlayRes->valueAt(index); 584 585 // for each of the resources, check for a match in the previously built 586 // non-overlay "baseset". 587 size_t overlayCount = overlaySet->size(); 588 for (size_t overlayIndex=0; overlayIndex<overlayCount; overlayIndex++) { 589 if (bundle->getVerbose()) { 590 printf("trying overlaySet Key=%s\n",overlaySet->keyAt(overlayIndex).string()); 591 } 592 ssize_t baseIndex = -1; 593 if (baseSet->get() != NULL) { 594 baseIndex = (*baseSet)->indexOfKey(overlaySet->keyAt(overlayIndex)); 595 } 596 if (baseIndex >= 0) { 597 // look for same flavor. For a given file (strings.xml, for example) 598 // there may be a locale specific or other flavors - we want to match 599 // the same flavor. 600 sp<AaptGroup> overlayGroup = overlaySet->valueAt(overlayIndex); 601 sp<AaptGroup> baseGroup = (*baseSet)->valueAt(baseIndex); 602 603 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > overlayFiles = 604 overlayGroup->getFiles(); 605 if (bundle->getVerbose()) { 606 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > baseFiles = 607 baseGroup->getFiles(); 608 for (size_t i=0; i < baseFiles.size(); i++) { 609 printf("baseFile " ZD " has flavor %s\n", (ZD_TYPE) i, 610 baseFiles.keyAt(i).toString().string()); 611 } 612 for (size_t i=0; i < overlayFiles.size(); i++) { 613 printf("overlayFile " ZD " has flavor %s\n", (ZD_TYPE) i, 614 overlayFiles.keyAt(i).toString().string()); 615 } 616 } 617 618 size_t overlayGroupSize = overlayFiles.size(); 619 for (size_t overlayGroupIndex = 0; 620 overlayGroupIndex<overlayGroupSize; 621 overlayGroupIndex++) { 622 ssize_t baseFileIndex = 623 baseGroup->getFiles().indexOfKey(overlayFiles. 624 keyAt(overlayGroupIndex)); 625 if (baseFileIndex >= 0) { 626 if (bundle->getVerbose()) { 627 printf("found a match (" ZD ") for overlay file %s, for flavor %s\n", 628 (ZD_TYPE) baseFileIndex, 629 overlayGroup->getLeaf().string(), 630 overlayFiles.keyAt(overlayGroupIndex).toString().string()); 631 } 632 baseGroup->removeFile(baseFileIndex); 633 } else { 634 // didn't find a match fall through and add it.. 635 if (true || bundle->getVerbose()) { 636 printf("nothing matches overlay file %s, for flavor %s\n", 637 overlayGroup->getLeaf().string(), 638 overlayFiles.keyAt(overlayGroupIndex).toString().string()); 639 } 640 } 641 baseGroup->addFile(overlayFiles.valueAt(overlayGroupIndex)); 642 assets->addGroupEntry(overlayFiles.keyAt(overlayGroupIndex)); 643 } 644 } else { 645 if (baseSet->get() == NULL) { 646 *baseSet = new ResourceTypeSet(); 647 assets->getResources()->add(String8(resType), *baseSet); 648 } 649 // this group doesn't exist (a file that's only in the overlay) 650 (*baseSet)->add(overlaySet->keyAt(overlayIndex), 651 overlaySet->valueAt(overlayIndex)); 652 // make sure all flavors are defined in the resources. 653 sp<AaptGroup> overlayGroup = overlaySet->valueAt(overlayIndex); 654 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > overlayFiles = 655 overlayGroup->getFiles(); 656 size_t overlayGroupSize = overlayFiles.size(); 657 for (size_t overlayGroupIndex = 0; 658 overlayGroupIndex<overlayGroupSize; 659 overlayGroupIndex++) { 660 assets->addGroupEntry(overlayFiles.keyAt(overlayGroupIndex)); 661 } 662 } 663 } 664 // this overlay didn't have resources for this type 665 } 666 // try next overlay 667 overlay = overlay->getOverlay(); 668 } 669 return true; 670} 671 672/* 673 * Inserts an attribute in a given node. 674 * If errorOnFailedInsert is true, and the attribute already exists, returns false. 675 * If replaceExisting is true, the attribute will be updated if it already exists. 676 * Returns true otherwise, even if the attribute already exists, and does not modify 677 * the existing attribute's value. 678 */ 679bool addTagAttribute(const sp<XMLNode>& node, const char* ns8, 680 const char* attr8, const char* value, bool errorOnFailedInsert, 681 bool replaceExisting) 682{ 683 if (value == NULL) { 684 return true; 685 } 686 687 const String16 ns(ns8); 688 const String16 attr(attr8); 689 690 XMLNode::attribute_entry* existingEntry = node->editAttribute(ns, attr); 691 if (existingEntry != NULL) { 692 if (replaceExisting) { 693 NOISY(printf("Info: AndroidManifest.xml already defines %s (in %s);" 694 " overwriting existing value from manifest.\n", 695 String8(attr).string(), String8(ns).string())); 696 existingEntry->string = String16(value); 697 return true; 698 } 699 700 if (errorOnFailedInsert) { 701 fprintf(stderr, "Error: AndroidManifest.xml already defines %s (in %s);" 702 " cannot insert new value %s.\n", 703 String8(attr).string(), String8(ns).string(), value); 704 return false; 705 } 706 707 fprintf(stderr, "Warning: AndroidManifest.xml already defines %s (in %s);" 708 " using existing value in manifest.\n", 709 String8(attr).string(), String8(ns).string()); 710 711 // don't stop the build. 712 return true; 713 } 714 715 node->addAttribute(ns, attr, String16(value)); 716 return true; 717} 718 719/* 720 * Inserts an attribute in a given node, only if the attribute does not 721 * exist. 722 * If errorOnFailedInsert is true, and the attribute already exists, returns false. 723 * Returns true otherwise, even if the attribute already exists. 724 */ 725bool addTagAttribute(const sp<XMLNode>& node, const char* ns8, 726 const char* attr8, const char* value, bool errorOnFailedInsert) 727{ 728 return addTagAttribute(node, ns8, attr8, value, errorOnFailedInsert, false); 729} 730 731static void fullyQualifyClassName(const String8& package, sp<XMLNode> node, 732 const String16& attrName) { 733 XMLNode::attribute_entry* attr = node->editAttribute( 734 String16("http://schemas.android.com/apk/res/android"), attrName); 735 if (attr != NULL) { 736 String8 name(attr->string); 737 738 // asdf --> package.asdf 739 // .asdf .a.b --> package.asdf package.a.b 740 // asdf.adsf --> asdf.asdf 741 String8 className; 742 const char* p = name.string(); 743 const char* q = strchr(p, '.'); 744 if (p == q) { 745 className += package; 746 className += name; 747 } else if (q == NULL) { 748 className += package; 749 className += "."; 750 className += name; 751 } else { 752 className += name; 753 } 754 NOISY(printf("Qualifying class '%s' to '%s'", name.string(), className.string())); 755 attr->string.setTo(String16(className)); 756 } 757} 758 759status_t massageManifest(Bundle* bundle, sp<XMLNode> root) 760{ 761 root = root->searchElement(String16(), String16("manifest")); 762 if (root == NULL) { 763 fprintf(stderr, "No <manifest> tag.\n"); 764 return UNKNOWN_ERROR; 765 } 766 767 bool errorOnFailedInsert = bundle->getErrorOnFailedInsert(); 768 bool replaceVersion = bundle->getReplaceVersion(); 769 770 if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionCode", 771 bundle->getVersionCode(), errorOnFailedInsert, replaceVersion)) { 772 return UNKNOWN_ERROR; 773 } 774 if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionName", 775 bundle->getVersionName(), errorOnFailedInsert, replaceVersion)) { 776 return UNKNOWN_ERROR; 777 } 778 779 if (bundle->getMinSdkVersion() != NULL 780 || bundle->getTargetSdkVersion() != NULL 781 || bundle->getMaxSdkVersion() != NULL) { 782 sp<XMLNode> vers = root->getChildElement(String16(), String16("uses-sdk")); 783 if (vers == NULL) { 784 vers = XMLNode::newElement(root->getFilename(), String16(), String16("uses-sdk")); 785 root->insertChildAt(vers, 0); 786 } 787 788 if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "minSdkVersion", 789 bundle->getMinSdkVersion(), errorOnFailedInsert)) { 790 return UNKNOWN_ERROR; 791 } 792 if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "targetSdkVersion", 793 bundle->getTargetSdkVersion(), errorOnFailedInsert)) { 794 return UNKNOWN_ERROR; 795 } 796 if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "maxSdkVersion", 797 bundle->getMaxSdkVersion(), errorOnFailedInsert)) { 798 return UNKNOWN_ERROR; 799 } 800 } 801 802 if (bundle->getDebugMode()) { 803 sp<XMLNode> application = root->getChildElement(String16(), String16("application")); 804 if (application != NULL) { 805 if (!addTagAttribute(application, RESOURCES_ANDROID_NAMESPACE, "debuggable", "true", 806 errorOnFailedInsert)) { 807 return UNKNOWN_ERROR; 808 } 809 } 810 } 811 812 // Deal with manifest package name overrides 813 const char* manifestPackageNameOverride = bundle->getManifestPackageNameOverride(); 814 if (manifestPackageNameOverride != NULL) { 815 // Update the actual package name 816 XMLNode::attribute_entry* attr = root->editAttribute(String16(), String16("package")); 817 if (attr == NULL) { 818 fprintf(stderr, "package name is required with --rename-manifest-package.\n"); 819 return UNKNOWN_ERROR; 820 } 821 String8 origPackage(attr->string); 822 attr->string.setTo(String16(manifestPackageNameOverride)); 823 NOISY(printf("Overriding package '%s' to be '%s'\n", origPackage.string(), manifestPackageNameOverride)); 824 825 // Make class names fully qualified 826 sp<XMLNode> application = root->getChildElement(String16(), String16("application")); 827 if (application != NULL) { 828 fullyQualifyClassName(origPackage, application, String16("name")); 829 fullyQualifyClassName(origPackage, application, String16("backupAgent")); 830 831 Vector<sp<XMLNode> >& children = const_cast<Vector<sp<XMLNode> >&>(application->getChildren()); 832 for (size_t i = 0; i < children.size(); i++) { 833 sp<XMLNode> child = children.editItemAt(i); 834 String8 tag(child->getElementName()); 835 if (tag == "activity" || tag == "service" || tag == "receiver" || tag == "provider") { 836 fullyQualifyClassName(origPackage, child, String16("name")); 837 } else if (tag == "activity-alias") { 838 fullyQualifyClassName(origPackage, child, String16("name")); 839 fullyQualifyClassName(origPackage, child, String16("targetActivity")); 840 } 841 } 842 } 843 } 844 845 // Deal with manifest package name overrides 846 const char* instrumentationPackageNameOverride = bundle->getInstrumentationPackageNameOverride(); 847 if (instrumentationPackageNameOverride != NULL) { 848 // Fix up instrumentation targets. 849 Vector<sp<XMLNode> >& children = const_cast<Vector<sp<XMLNode> >&>(root->getChildren()); 850 for (size_t i = 0; i < children.size(); i++) { 851 sp<XMLNode> child = children.editItemAt(i); 852 String8 tag(child->getElementName()); 853 if (tag == "instrumentation") { 854 XMLNode::attribute_entry* attr = child->editAttribute( 855 String16("http://schemas.android.com/apk/res/android"), String16("targetPackage")); 856 if (attr != NULL) { 857 attr->string.setTo(String16(instrumentationPackageNameOverride)); 858 } 859 } 860 } 861 } 862 863 return NO_ERROR; 864} 865 866#define ASSIGN_IT(n) \ 867 do { \ 868 ssize_t index = resources->indexOfKey(String8(#n)); \ 869 if (index >= 0) { \ 870 n ## s = resources->valueAt(index); \ 871 } \ 872 } while (0) 873 874status_t updatePreProcessedCache(Bundle* bundle) 875{ 876 #if BENCHMARK 877 fprintf(stdout, "BENCHMARK: Starting PNG PreProcessing \n"); 878 long startPNGTime = clock(); 879 #endif /* BENCHMARK */ 880 881 String8 source(bundle->getResourceSourceDirs()[0]); 882 String8 dest(bundle->getCrunchedOutputDir()); 883 884 FileFinder* ff = new SystemFileFinder(); 885 CrunchCache cc(source,dest,ff); 886 887 CacheUpdater* cu = new SystemCacheUpdater(bundle); 888 size_t numFiles = cc.crunch(cu); 889 890 if (bundle->getVerbose()) 891 fprintf(stdout, "Crunched %d PNG files to update cache\n", (int)numFiles); 892 893 delete ff; 894 delete cu; 895 896 #if BENCHMARK 897 fprintf(stdout, "BENCHMARK: End PNG PreProcessing. Time Elapsed: %f ms \n" 898 ,(clock() - startPNGTime)/1000.0); 899 #endif /* BENCHMARK */ 900 return 0; 901} 902 903status_t generateAndroidManifestForSplit(Bundle* bundle, const sp<AaptAssets>& assets, 904 const sp<ApkSplit>& split, sp<AaptFile>& outFile, ResourceTable* table) { 905 const String8 filename("AndroidManifest.xml"); 906 const String16 androidPrefix("android"); 907 const String16 androidNSUri("http://schemas.android.com/apk/res/android"); 908 sp<XMLNode> root = XMLNode::newNamespace(filename, androidPrefix, androidNSUri); 909 910 // Build the <manifest> tag 911 sp<XMLNode> manifest = XMLNode::newElement(filename, String16(), String16("manifest")); 912 913 // Add the 'package' attribute which is set to the package name. 914 const char* packageName = assets->getPackage(); 915 const char* manifestPackageNameOverride = bundle->getManifestPackageNameOverride(); 916 if (manifestPackageNameOverride != NULL) { 917 packageName = manifestPackageNameOverride; 918 } 919 manifest->addAttribute(String16(), String16("package"), String16(packageName)); 920 921 // Add the 'versionCode' attribute which is set to the original version code. 922 if (!addTagAttribute(manifest, RESOURCES_ANDROID_NAMESPACE, "versionCode", 923 bundle->getVersionCode(), true, true)) { 924 return UNKNOWN_ERROR; 925 } 926 927 // Add the 'split' attribute which describes the configurations included. 928 String8 splitName("config_"); 929 splitName.append(split->getDirectorySafeName()); 930 manifest->addAttribute(String16(), String16("split"), String16(splitName)); 931 932 // Build an empty <application> tag (required). 933 sp<XMLNode> app = XMLNode::newElement(filename, String16(), String16("application")); 934 manifest->addChild(app); 935 root->addChild(manifest); 936 937 int err = compileXmlFile(assets, root, outFile, table); 938 if (err < NO_ERROR) { 939 return err; 940 } 941 outFile->setCompressionMethod(ZipEntry::kCompressDeflated); 942 return NO_ERROR; 943} 944 945status_t buildResources(Bundle* bundle, const sp<AaptAssets>& assets, sp<ApkBuilder>& builder) 946{ 947 // First, look for a package file to parse. This is required to 948 // be able to generate the resource information. 949 sp<AaptGroup> androidManifestFile = 950 assets->getFiles().valueFor(String8("AndroidManifest.xml")); 951 if (androidManifestFile == NULL) { 952 fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n"); 953 return UNKNOWN_ERROR; 954 } 955 956 status_t err = parsePackage(bundle, assets, androidManifestFile); 957 if (err != NO_ERROR) { 958 return err; 959 } 960 961 NOISY(printf("Creating resources for package %s\n", 962 assets->getPackage().string())); 963 964 ResourceTable table(bundle, String16(assets->getPackage())); 965 err = table.addIncludedResources(bundle, assets); 966 if (err != NO_ERROR) { 967 return err; 968 } 969 970 NOISY(printf("Found %d included resource packages\n", (int)table.size())); 971 972 // Standard flags for compiled XML and optional UTF-8 encoding 973 int xmlFlags = XML_COMPILE_STANDARD_RESOURCE; 974 975 /* Only enable UTF-8 if the caller of aapt didn't specifically 976 * request UTF-16 encoding and the parameters of this package 977 * allow UTF-8 to be used. 978 */ 979 if (!bundle->getUTF16StringsOption()) { 980 xmlFlags |= XML_COMPILE_UTF8; 981 } 982 983 // -------------------------------------------------------------- 984 // First, gather all resource information. 985 // -------------------------------------------------------------- 986 987 // resType -> leafName -> group 988 KeyedVector<String8, sp<ResourceTypeSet> > *resources = 989 new KeyedVector<String8, sp<ResourceTypeSet> >; 990 collect_files(assets, resources); 991 992 sp<ResourceTypeSet> drawables; 993 sp<ResourceTypeSet> layouts; 994 sp<ResourceTypeSet> anims; 995 sp<ResourceTypeSet> animators; 996 sp<ResourceTypeSet> interpolators; 997 sp<ResourceTypeSet> transitions; 998 sp<ResourceTypeSet> xmls; 999 sp<ResourceTypeSet> raws; 1000 sp<ResourceTypeSet> colors; 1001 sp<ResourceTypeSet> menus; 1002 sp<ResourceTypeSet> mipmaps; 1003 1004 ASSIGN_IT(drawable); 1005 ASSIGN_IT(layout); 1006 ASSIGN_IT(anim); 1007 ASSIGN_IT(animator); 1008 ASSIGN_IT(interpolator); 1009 ASSIGN_IT(transition); 1010 ASSIGN_IT(xml); 1011 ASSIGN_IT(raw); 1012 ASSIGN_IT(color); 1013 ASSIGN_IT(menu); 1014 ASSIGN_IT(mipmap); 1015 1016 assets->setResources(resources); 1017 // now go through any resource overlays and collect their files 1018 sp<AaptAssets> current = assets->getOverlay(); 1019 while(current.get()) { 1020 KeyedVector<String8, sp<ResourceTypeSet> > *resources = 1021 new KeyedVector<String8, sp<ResourceTypeSet> >; 1022 current->setResources(resources); 1023 collect_files(current, resources); 1024 current = current->getOverlay(); 1025 } 1026 // apply the overlay files to the base set 1027 if (!applyFileOverlay(bundle, assets, &drawables, "drawable") || 1028 !applyFileOverlay(bundle, assets, &layouts, "layout") || 1029 !applyFileOverlay(bundle, assets, &anims, "anim") || 1030 !applyFileOverlay(bundle, assets, &animators, "animator") || 1031 !applyFileOverlay(bundle, assets, &interpolators, "interpolator") || 1032 !applyFileOverlay(bundle, assets, &transitions, "transition") || 1033 !applyFileOverlay(bundle, assets, &xmls, "xml") || 1034 !applyFileOverlay(bundle, assets, &raws, "raw") || 1035 !applyFileOverlay(bundle, assets, &colors, "color") || 1036 !applyFileOverlay(bundle, assets, &menus, "menu") || 1037 !applyFileOverlay(bundle, assets, &mipmaps, "mipmap")) { 1038 return UNKNOWN_ERROR; 1039 } 1040 1041 bool hasErrors = false; 1042 1043 if (drawables != NULL) { 1044 if (bundle->getOutputAPKFile() != NULL) { 1045 err = preProcessImages(bundle, assets, drawables, "drawable"); 1046 } 1047 if (err == NO_ERROR) { 1048 err = makeFileResources(bundle, assets, &table, drawables, "drawable"); 1049 if (err != NO_ERROR) { 1050 hasErrors = true; 1051 } 1052 } else { 1053 hasErrors = true; 1054 } 1055 } 1056 1057 if (mipmaps != NULL) { 1058 if (bundle->getOutputAPKFile() != NULL) { 1059 err = preProcessImages(bundle, assets, mipmaps, "mipmap"); 1060 } 1061 if (err == NO_ERROR) { 1062 err = makeFileResources(bundle, assets, &table, mipmaps, "mipmap"); 1063 if (err != NO_ERROR) { 1064 hasErrors = true; 1065 } 1066 } else { 1067 hasErrors = true; 1068 } 1069 } 1070 1071 if (layouts != NULL) { 1072 err = makeFileResources(bundle, assets, &table, layouts, "layout"); 1073 if (err != NO_ERROR) { 1074 hasErrors = true; 1075 } 1076 } 1077 1078 if (anims != NULL) { 1079 err = makeFileResources(bundle, assets, &table, anims, "anim"); 1080 if (err != NO_ERROR) { 1081 hasErrors = true; 1082 } 1083 } 1084 1085 if (animators != NULL) { 1086 err = makeFileResources(bundle, assets, &table, animators, "animator"); 1087 if (err != NO_ERROR) { 1088 hasErrors = true; 1089 } 1090 } 1091 1092 if (transitions != NULL) { 1093 err = makeFileResources(bundle, assets, &table, transitions, "transition"); 1094 if (err != NO_ERROR) { 1095 hasErrors = true; 1096 } 1097 } 1098 1099 if (interpolators != NULL) { 1100 err = makeFileResources(bundle, assets, &table, interpolators, "interpolator"); 1101 if (err != NO_ERROR) { 1102 hasErrors = true; 1103 } 1104 } 1105 1106 if (xmls != NULL) { 1107 err = makeFileResources(bundle, assets, &table, xmls, "xml"); 1108 if (err != NO_ERROR) { 1109 hasErrors = true; 1110 } 1111 } 1112 1113 if (raws != NULL) { 1114 err = makeFileResources(bundle, assets, &table, raws, "raw"); 1115 if (err != NO_ERROR) { 1116 hasErrors = true; 1117 } 1118 } 1119 1120 // compile resources 1121 current = assets; 1122 while(current.get()) { 1123 KeyedVector<String8, sp<ResourceTypeSet> > *resources = 1124 current->getResources(); 1125 1126 ssize_t index = resources->indexOfKey(String8("values")); 1127 if (index >= 0) { 1128 ResourceDirIterator it(resources->valueAt(index), String8("values")); 1129 ssize_t res; 1130 while ((res=it.next()) == NO_ERROR) { 1131 sp<AaptFile> file = it.getFile(); 1132 res = compileResourceFile(bundle, assets, file, it.getParams(), 1133 (current!=assets), &table); 1134 if (res != NO_ERROR) { 1135 hasErrors = true; 1136 } 1137 } 1138 } 1139 current = current->getOverlay(); 1140 } 1141 1142 if (colors != NULL) { 1143 err = makeFileResources(bundle, assets, &table, colors, "color"); 1144 if (err != NO_ERROR) { 1145 hasErrors = true; 1146 } 1147 } 1148 1149 if (menus != NULL) { 1150 err = makeFileResources(bundle, assets, &table, menus, "menu"); 1151 if (err != NO_ERROR) { 1152 hasErrors = true; 1153 } 1154 } 1155 1156 // -------------------------------------------------------------------- 1157 // Assignment of resource IDs and initial generation of resource table. 1158 // -------------------------------------------------------------------- 1159 1160 if (table.hasResources()) { 1161 err = table.assignResourceIds(); 1162 if (err < NO_ERROR) { 1163 return err; 1164 } 1165 } 1166 1167 // -------------------------------------------------------------- 1168 // Finally, we can now we can compile XML files, which may reference 1169 // resources. 1170 // -------------------------------------------------------------- 1171 1172 if (layouts != NULL) { 1173 ResourceDirIterator it(layouts, String8("layout")); 1174 while ((err=it.next()) == NO_ERROR) { 1175 String8 src = it.getFile()->getPrintableSource(); 1176 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags); 1177 if (err == NO_ERROR) { 1178 ResXMLTree block; 1179 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true); 1180 checkForIds(src, block); 1181 } else { 1182 hasErrors = true; 1183 } 1184 } 1185 1186 if (err < NO_ERROR) { 1187 hasErrors = true; 1188 } 1189 err = NO_ERROR; 1190 } 1191 1192 if (anims != NULL) { 1193 ResourceDirIterator it(anims, String8("anim")); 1194 while ((err=it.next()) == NO_ERROR) { 1195 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags); 1196 if (err != NO_ERROR) { 1197 hasErrors = true; 1198 } 1199 } 1200 1201 if (err < NO_ERROR) { 1202 hasErrors = true; 1203 } 1204 err = NO_ERROR; 1205 } 1206 1207 if (animators != NULL) { 1208 ResourceDirIterator it(animators, String8("animator")); 1209 while ((err=it.next()) == NO_ERROR) { 1210 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags); 1211 if (err != NO_ERROR) { 1212 hasErrors = true; 1213 } 1214 } 1215 1216 if (err < NO_ERROR) { 1217 hasErrors = true; 1218 } 1219 err = NO_ERROR; 1220 } 1221 1222 if (interpolators != NULL) { 1223 ResourceDirIterator it(interpolators, String8("interpolator")); 1224 while ((err=it.next()) == NO_ERROR) { 1225 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags); 1226 if (err != NO_ERROR) { 1227 hasErrors = true; 1228 } 1229 } 1230 1231 if (err < NO_ERROR) { 1232 hasErrors = true; 1233 } 1234 err = NO_ERROR; 1235 } 1236 1237 if (transitions != NULL) { 1238 ResourceDirIterator it(transitions, String8("transition")); 1239 while ((err=it.next()) == NO_ERROR) { 1240 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags); 1241 if (err != NO_ERROR) { 1242 hasErrors = true; 1243 } 1244 } 1245 1246 if (err < NO_ERROR) { 1247 hasErrors = true; 1248 } 1249 err = NO_ERROR; 1250 } 1251 1252 if (xmls != NULL) { 1253 ResourceDirIterator it(xmls, String8("xml")); 1254 while ((err=it.next()) == NO_ERROR) { 1255 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags); 1256 if (err != NO_ERROR) { 1257 hasErrors = true; 1258 } 1259 } 1260 1261 if (err < NO_ERROR) { 1262 hasErrors = true; 1263 } 1264 err = NO_ERROR; 1265 } 1266 1267 if (drawables != NULL) { 1268 ResourceDirIterator it(drawables, String8("drawable")); 1269 while ((err=it.next()) == NO_ERROR) { 1270 err = postProcessImage(assets, &table, it.getFile()); 1271 if (err != NO_ERROR) { 1272 hasErrors = true; 1273 } 1274 } 1275 1276 if (err < NO_ERROR) { 1277 hasErrors = true; 1278 } 1279 err = NO_ERROR; 1280 } 1281 1282 if (colors != NULL) { 1283 ResourceDirIterator it(colors, String8("color")); 1284 while ((err=it.next()) == NO_ERROR) { 1285 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags); 1286 if (err != NO_ERROR) { 1287 hasErrors = true; 1288 } 1289 } 1290 1291 if (err < NO_ERROR) { 1292 hasErrors = true; 1293 } 1294 err = NO_ERROR; 1295 } 1296 1297 if (menus != NULL) { 1298 ResourceDirIterator it(menus, String8("menu")); 1299 while ((err=it.next()) == NO_ERROR) { 1300 String8 src = it.getFile()->getPrintableSource(); 1301 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags); 1302 if (err == NO_ERROR) { 1303 ResXMLTree block; 1304 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true); 1305 checkForIds(src, block); 1306 } else { 1307 hasErrors = true; 1308 } 1309 } 1310 1311 if (err < NO_ERROR) { 1312 hasErrors = true; 1313 } 1314 err = NO_ERROR; 1315 } 1316 1317 if (table.validateLocalizations()) { 1318 hasErrors = true; 1319 } 1320 1321 if (hasErrors) { 1322 return UNKNOWN_ERROR; 1323 } 1324 1325 const sp<AaptFile> manifestFile(androidManifestFile->getFiles().valueAt(0)); 1326 String8 manifestPath(manifestFile->getPrintableSource()); 1327 1328 // Generate final compiled manifest file. 1329 manifestFile->clearData(); 1330 sp<XMLNode> manifestTree = XMLNode::parse(manifestFile); 1331 if (manifestTree == NULL) { 1332 return UNKNOWN_ERROR; 1333 } 1334 err = massageManifest(bundle, manifestTree); 1335 if (err < NO_ERROR) { 1336 return err; 1337 } 1338 err = compileXmlFile(assets, manifestTree, manifestFile, &table); 1339 if (err < NO_ERROR) { 1340 return err; 1341 } 1342 1343 //block.restart(); 1344 //printXMLBlock(&block); 1345 1346 // -------------------------------------------------------------- 1347 // Generate the final resource table. 1348 // Re-flatten because we may have added new resource IDs 1349 // -------------------------------------------------------------- 1350 1351 ResTable finalResTable; 1352 sp<AaptFile> resFile; 1353 1354 if (table.hasResources()) { 1355 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R")); 1356 err = table.addSymbols(symbols); 1357 if (err < NO_ERROR) { 1358 return err; 1359 } 1360 1361 Vector<sp<ApkSplit> >& splits = builder->getSplits(); 1362 const size_t numSplits = splits.size(); 1363 for (size_t i = 0; i < numSplits; i++) { 1364 sp<ApkSplit>& split = splits.editItemAt(i); 1365 sp<AaptFile> flattenedTable = new AaptFile(String8("resources.arsc"), 1366 AaptGroupEntry(), String8()); 1367 err = table.flatten(bundle, split->getResourceFilter(), flattenedTable); 1368 if (err != NO_ERROR) { 1369 fprintf(stderr, "Failed to generate resource table for split '%s'\n", 1370 split->getPrintableName().string()); 1371 return err; 1372 } 1373 split->addEntry(String8("resources.arsc"), flattenedTable); 1374 1375 if (split->isBase()) { 1376 resFile = flattenedTable; 1377 err = finalResTable.add(flattenedTable->getData(), flattenedTable->getSize()); 1378 if (err != NO_ERROR) { 1379 fprintf(stderr, "Generated resource table is corrupt.\n"); 1380 return err; 1381 } 1382 } else { 1383 sp<AaptFile> generatedManifest = new AaptFile(String8("AndroidManifest.xml"), 1384 AaptGroupEntry(), String8()); 1385 err = generateAndroidManifestForSplit(bundle, assets, split, 1386 generatedManifest, &table); 1387 if (err != NO_ERROR) { 1388 fprintf(stderr, "Failed to generate AndroidManifest.xml for split '%s'\n", 1389 split->getPrintableName().string()); 1390 return err; 1391 } 1392 split->addEntry(String8("AndroidManifest.xml"), generatedManifest); 1393 } 1394 } 1395 1396 if (bundle->getPublicOutputFile()) { 1397 FILE* fp = fopen(bundle->getPublicOutputFile(), "w+"); 1398 if (fp == NULL) { 1399 fprintf(stderr, "ERROR: Unable to open public definitions output file %s: %s\n", 1400 (const char*)bundle->getPublicOutputFile(), strerror(errno)); 1401 return UNKNOWN_ERROR; 1402 } 1403 if (bundle->getVerbose()) { 1404 printf(" Writing public definitions to %s.\n", bundle->getPublicOutputFile()); 1405 } 1406 table.writePublicDefinitions(String16(assets->getPackage()), fp); 1407 fclose(fp); 1408 } 1409 1410 if (finalResTable.getTableCount() == 0 || resFile == NULL) { 1411 fprintf(stderr, "No resource table was generated.\n"); 1412 return UNKNOWN_ERROR; 1413 } 1414 } 1415 1416 // Perform a basic validation of the manifest file. This time we 1417 // parse it with the comments intact, so that we can use them to 1418 // generate java docs... so we are not going to write this one 1419 // back out to the final manifest data. 1420 sp<AaptFile> outManifestFile = new AaptFile(manifestFile->getSourceFile(), 1421 manifestFile->getGroupEntry(), 1422 manifestFile->getResourceType()); 1423 err = compileXmlFile(assets, manifestFile, 1424 outManifestFile, &table, 1425 XML_COMPILE_ASSIGN_ATTRIBUTE_IDS 1426 | XML_COMPILE_STRIP_WHITESPACE | XML_COMPILE_STRIP_RAW_VALUES); 1427 if (err < NO_ERROR) { 1428 return err; 1429 } 1430 ResXMLTree block; 1431 block.setTo(outManifestFile->getData(), outManifestFile->getSize(), true); 1432 String16 manifest16("manifest"); 1433 String16 permission16("permission"); 1434 String16 permission_group16("permission-group"); 1435 String16 uses_permission16("uses-permission"); 1436 String16 instrumentation16("instrumentation"); 1437 String16 application16("application"); 1438 String16 provider16("provider"); 1439 String16 service16("service"); 1440 String16 receiver16("receiver"); 1441 String16 activity16("activity"); 1442 String16 action16("action"); 1443 String16 category16("category"); 1444 String16 data16("scheme"); 1445 const char* packageIdentChars = "abcdefghijklmnopqrstuvwxyz" 1446 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789"; 1447 const char* packageIdentCharsWithTheStupid = "abcdefghijklmnopqrstuvwxyz" 1448 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-"; 1449 const char* classIdentChars = "abcdefghijklmnopqrstuvwxyz" 1450 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789$"; 1451 const char* processIdentChars = "abcdefghijklmnopqrstuvwxyz" 1452 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:"; 1453 const char* authoritiesIdentChars = "abcdefghijklmnopqrstuvwxyz" 1454 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-:;"; 1455 const char* typeIdentChars = "abcdefghijklmnopqrstuvwxyz" 1456 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:-/*+"; 1457 const char* schemeIdentChars = "abcdefghijklmnopqrstuvwxyz" 1458 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-"; 1459 ResXMLTree::event_code_t code; 1460 sp<AaptSymbols> permissionSymbols; 1461 sp<AaptSymbols> permissionGroupSymbols; 1462 while ((code=block.next()) != ResXMLTree::END_DOCUMENT 1463 && code > ResXMLTree::BAD_DOCUMENT) { 1464 if (code == ResXMLTree::START_TAG) { 1465 size_t len; 1466 if (block.getElementNamespace(&len) != NULL) { 1467 continue; 1468 } 1469 if (strcmp16(block.getElementName(&len), manifest16.string()) == 0) { 1470 if (validateAttr(manifestPath, finalResTable, block, NULL, "package", 1471 packageIdentChars, true) != ATTR_OKAY) { 1472 hasErrors = true; 1473 } 1474 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE, 1475 "sharedUserId", packageIdentChars, false) != ATTR_OKAY) { 1476 hasErrors = true; 1477 } 1478 } else if (strcmp16(block.getElementName(&len), permission16.string()) == 0 1479 || strcmp16(block.getElementName(&len), permission_group16.string()) == 0) { 1480 const bool isGroup = strcmp16(block.getElementName(&len), 1481 permission_group16.string()) == 0; 1482 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE, 1483 "name", isGroup ? packageIdentCharsWithTheStupid 1484 : packageIdentChars, true) != ATTR_OKAY) { 1485 hasErrors = true; 1486 } 1487 SourcePos srcPos(manifestPath, block.getLineNumber()); 1488 sp<AaptSymbols> syms; 1489 if (!isGroup) { 1490 syms = permissionSymbols; 1491 if (syms == NULL) { 1492 sp<AaptSymbols> symbols = 1493 assets->getSymbolsFor(String8("Manifest")); 1494 syms = permissionSymbols = symbols->addNestedSymbol( 1495 String8("permission"), srcPos); 1496 } 1497 } else { 1498 syms = permissionGroupSymbols; 1499 if (syms == NULL) { 1500 sp<AaptSymbols> symbols = 1501 assets->getSymbolsFor(String8("Manifest")); 1502 syms = permissionGroupSymbols = symbols->addNestedSymbol( 1503 String8("permission_group"), srcPos); 1504 } 1505 } 1506 size_t len; 1507 ssize_t index = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "name"); 1508 const uint16_t* id = block.getAttributeStringValue(index, &len); 1509 if (id == NULL) { 1510 fprintf(stderr, "%s:%d: missing name attribute in element <%s>.\n", 1511 manifestPath.string(), block.getLineNumber(), 1512 String8(block.getElementName(&len)).string()); 1513 hasErrors = true; 1514 break; 1515 } 1516 String8 idStr(id); 1517 char* p = idStr.lockBuffer(idStr.size()); 1518 char* e = p + idStr.size(); 1519 bool begins_with_digit = true; // init to true so an empty string fails 1520 while (e > p) { 1521 e--; 1522 if (*e >= '0' && *e <= '9') { 1523 begins_with_digit = true; 1524 continue; 1525 } 1526 if ((*e >= 'a' && *e <= 'z') || 1527 (*e >= 'A' && *e <= 'Z') || 1528 (*e == '_')) { 1529 begins_with_digit = false; 1530 continue; 1531 } 1532 if (isGroup && (*e == '-')) { 1533 *e = '_'; 1534 begins_with_digit = false; 1535 continue; 1536 } 1537 e++; 1538 break; 1539 } 1540 idStr.unlockBuffer(); 1541 // verify that we stopped because we hit a period or 1542 // the beginning of the string, and that the 1543 // identifier didn't begin with a digit. 1544 if (begins_with_digit || (e != p && *(e-1) != '.')) { 1545 fprintf(stderr, 1546 "%s:%d: Permission name <%s> is not a valid Java symbol\n", 1547 manifestPath.string(), block.getLineNumber(), idStr.string()); 1548 hasErrors = true; 1549 } 1550 syms->addStringSymbol(String8(e), idStr, srcPos); 1551 const uint16_t* cmt = block.getComment(&len); 1552 if (cmt != NULL && *cmt != 0) { 1553 //printf("Comment of %s: %s\n", String8(e).string(), 1554 // String8(cmt).string()); 1555 syms->appendComment(String8(e), String16(cmt), srcPos); 1556 } else { 1557 //printf("No comment for %s\n", String8(e).string()); 1558 } 1559 syms->makeSymbolPublic(String8(e), srcPos); 1560 } else if (strcmp16(block.getElementName(&len), uses_permission16.string()) == 0) { 1561 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE, 1562 "name", packageIdentChars, true) != ATTR_OKAY) { 1563 hasErrors = true; 1564 } 1565 } else if (strcmp16(block.getElementName(&len), instrumentation16.string()) == 0) { 1566 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE, 1567 "name", classIdentChars, true) != ATTR_OKAY) { 1568 hasErrors = true; 1569 } 1570 if (validateAttr(manifestPath, finalResTable, block, 1571 RESOURCES_ANDROID_NAMESPACE, "targetPackage", 1572 packageIdentChars, true) != ATTR_OKAY) { 1573 hasErrors = true; 1574 } 1575 } else if (strcmp16(block.getElementName(&len), application16.string()) == 0) { 1576 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE, 1577 "name", classIdentChars, false) != ATTR_OKAY) { 1578 hasErrors = true; 1579 } 1580 if (validateAttr(manifestPath, finalResTable, block, 1581 RESOURCES_ANDROID_NAMESPACE, "permission", 1582 packageIdentChars, false) != ATTR_OKAY) { 1583 hasErrors = true; 1584 } 1585 if (validateAttr(manifestPath, finalResTable, block, 1586 RESOURCES_ANDROID_NAMESPACE, "process", 1587 processIdentChars, false) != ATTR_OKAY) { 1588 hasErrors = true; 1589 } 1590 if (validateAttr(manifestPath, finalResTable, block, 1591 RESOURCES_ANDROID_NAMESPACE, "taskAffinity", 1592 processIdentChars, false) != ATTR_OKAY) { 1593 hasErrors = true; 1594 } 1595 } else if (strcmp16(block.getElementName(&len), provider16.string()) == 0) { 1596 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE, 1597 "name", classIdentChars, true) != ATTR_OKAY) { 1598 hasErrors = true; 1599 } 1600 if (validateAttr(manifestPath, finalResTable, block, 1601 RESOURCES_ANDROID_NAMESPACE, "authorities", 1602 authoritiesIdentChars, true) != ATTR_OKAY) { 1603 hasErrors = true; 1604 } 1605 if (validateAttr(manifestPath, finalResTable, block, 1606 RESOURCES_ANDROID_NAMESPACE, "permission", 1607 packageIdentChars, false) != ATTR_OKAY) { 1608 hasErrors = true; 1609 } 1610 if (validateAttr(manifestPath, finalResTable, block, 1611 RESOURCES_ANDROID_NAMESPACE, "process", 1612 processIdentChars, false) != ATTR_OKAY) { 1613 hasErrors = true; 1614 } 1615 } else if (strcmp16(block.getElementName(&len), service16.string()) == 0 1616 || strcmp16(block.getElementName(&len), receiver16.string()) == 0 1617 || strcmp16(block.getElementName(&len), activity16.string()) == 0) { 1618 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE, 1619 "name", classIdentChars, true) != ATTR_OKAY) { 1620 hasErrors = true; 1621 } 1622 if (validateAttr(manifestPath, finalResTable, block, 1623 RESOURCES_ANDROID_NAMESPACE, "permission", 1624 packageIdentChars, false) != ATTR_OKAY) { 1625 hasErrors = true; 1626 } 1627 if (validateAttr(manifestPath, finalResTable, block, 1628 RESOURCES_ANDROID_NAMESPACE, "process", 1629 processIdentChars, false) != ATTR_OKAY) { 1630 hasErrors = true; 1631 } 1632 if (validateAttr(manifestPath, finalResTable, block, 1633 RESOURCES_ANDROID_NAMESPACE, "taskAffinity", 1634 processIdentChars, false) != ATTR_OKAY) { 1635 hasErrors = true; 1636 } 1637 } else if (strcmp16(block.getElementName(&len), action16.string()) == 0 1638 || strcmp16(block.getElementName(&len), category16.string()) == 0) { 1639 if (validateAttr(manifestPath, finalResTable, block, 1640 RESOURCES_ANDROID_NAMESPACE, "name", 1641 packageIdentChars, true) != ATTR_OKAY) { 1642 hasErrors = true; 1643 } 1644 } else if (strcmp16(block.getElementName(&len), data16.string()) == 0) { 1645 if (validateAttr(manifestPath, finalResTable, block, 1646 RESOURCES_ANDROID_NAMESPACE, "mimeType", 1647 typeIdentChars, true) != ATTR_OKAY) { 1648 hasErrors = true; 1649 } 1650 if (validateAttr(manifestPath, finalResTable, block, 1651 RESOURCES_ANDROID_NAMESPACE, "scheme", 1652 schemeIdentChars, true) != ATTR_OKAY) { 1653 hasErrors = true; 1654 } 1655 } 1656 } 1657 } 1658 1659 if (resFile != NULL) { 1660 // These resources are now considered to be a part of the included 1661 // resources, for others to reference. 1662 err = assets->addIncludedResources(resFile); 1663 if (err < NO_ERROR) { 1664 fprintf(stderr, "ERROR: Unable to parse generated resources, aborting.\n"); 1665 return err; 1666 } 1667 } 1668 1669 return err; 1670} 1671 1672static const char* getIndentSpace(int indent) 1673{ 1674static const char whitespace[] = 1675" "; 1676 1677 return whitespace + sizeof(whitespace) - 1 - indent*4; 1678} 1679 1680static String8 flattenSymbol(const String8& symbol) { 1681 String8 result(symbol); 1682 ssize_t first; 1683 if ((first = symbol.find(":", 0)) >= 0 1684 || (first = symbol.find(".", 0)) >= 0) { 1685 size_t size = symbol.size(); 1686 char* buf = result.lockBuffer(size); 1687 for (size_t i = first; i < size; i++) { 1688 if (buf[i] == ':' || buf[i] == '.') { 1689 buf[i] = '_'; 1690 } 1691 } 1692 result.unlockBuffer(size); 1693 } 1694 return result; 1695} 1696 1697static String8 getSymbolPackage(const String8& symbol, const sp<AaptAssets>& assets, bool pub) { 1698 ssize_t colon = symbol.find(":", 0); 1699 if (colon >= 0) { 1700 return String8(symbol.string(), colon); 1701 } 1702 return pub ? assets->getPackage() : assets->getSymbolsPrivatePackage(); 1703} 1704 1705static String8 getSymbolName(const String8& symbol) { 1706 ssize_t colon = symbol.find(":", 0); 1707 if (colon >= 0) { 1708 return String8(symbol.string() + colon + 1); 1709 } 1710 return symbol; 1711} 1712 1713static String16 getAttributeComment(const sp<AaptAssets>& assets, 1714 const String8& name, 1715 String16* outTypeComment = NULL) 1716{ 1717 sp<AaptSymbols> asym = assets->getSymbolsFor(String8("R")); 1718 if (asym != NULL) { 1719 //printf("Got R symbols!\n"); 1720 asym = asym->getNestedSymbols().valueFor(String8("attr")); 1721 if (asym != NULL) { 1722 //printf("Got attrs symbols! comment %s=%s\n", 1723 // name.string(), String8(asym->getComment(name)).string()); 1724 if (outTypeComment != NULL) { 1725 *outTypeComment = asym->getTypeComment(name); 1726 } 1727 return asym->getComment(name); 1728 } 1729 } 1730 return String16(); 1731} 1732 1733static status_t writeLayoutClasses( 1734 FILE* fp, const sp<AaptAssets>& assets, 1735 const sp<AaptSymbols>& symbols, int indent, bool includePrivate) 1736{ 1737 const char* indentStr = getIndentSpace(indent); 1738 if (!includePrivate) { 1739 fprintf(fp, "%s/** @doconly */\n", indentStr); 1740 } 1741 fprintf(fp, "%spublic static final class styleable {\n", indentStr); 1742 indent++; 1743 1744 String16 attr16("attr"); 1745 String16 package16(assets->getPackage()); 1746 1747 indentStr = getIndentSpace(indent); 1748 bool hasErrors = false; 1749 1750 size_t i; 1751 size_t N = symbols->getNestedSymbols().size(); 1752 for (i=0; i<N; i++) { 1753 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i); 1754 String8 realClassName(symbols->getNestedSymbols().keyAt(i)); 1755 String8 nclassName(flattenSymbol(realClassName)); 1756 1757 SortedVector<uint32_t> idents; 1758 Vector<uint32_t> origOrder; 1759 Vector<bool> publicFlags; 1760 1761 size_t a; 1762 size_t NA = nsymbols->getSymbols().size(); 1763 for (a=0; a<NA; a++) { 1764 const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a)); 1765 int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32 1766 ? sym.int32Val : 0; 1767 bool isPublic = true; 1768 if (code == 0) { 1769 String16 name16(sym.name); 1770 uint32_t typeSpecFlags; 1771 code = assets->getIncludedResources().identifierForName( 1772 name16.string(), name16.size(), 1773 attr16.string(), attr16.size(), 1774 package16.string(), package16.size(), &typeSpecFlags); 1775 if (code == 0) { 1776 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n", 1777 nclassName.string(), sym.name.string()); 1778 hasErrors = true; 1779 } 1780 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0; 1781 } 1782 idents.add(code); 1783 origOrder.add(code); 1784 publicFlags.add(isPublic); 1785 } 1786 1787 NA = idents.size(); 1788 1789 String16 comment = symbols->getComment(realClassName); 1790 AnnotationProcessor ann; 1791 fprintf(fp, "%s/** ", indentStr); 1792 if (comment.size() > 0) { 1793 String8 cmt(comment); 1794 ann.preprocessComment(cmt); 1795 fprintf(fp, "%s\n", cmt.string()); 1796 } else { 1797 fprintf(fp, "Attributes that can be used with a %s.\n", nclassName.string()); 1798 } 1799 bool hasTable = false; 1800 for (a=0; a<NA; a++) { 1801 ssize_t pos = idents.indexOf(origOrder.itemAt(a)); 1802 if (pos >= 0) { 1803 if (!hasTable) { 1804 hasTable = true; 1805 fprintf(fp, 1806 "%s <p>Includes the following attributes:</p>\n" 1807 "%s <table>\n" 1808 "%s <colgroup align=\"left\" />\n" 1809 "%s <colgroup align=\"left\" />\n" 1810 "%s <tr><th>Attribute</th><th>Description</th></tr>\n", 1811 indentStr, 1812 indentStr, 1813 indentStr, 1814 indentStr, 1815 indentStr); 1816 } 1817 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a); 1818 if (!publicFlags.itemAt(a) && !includePrivate) { 1819 continue; 1820 } 1821 String8 name8(sym.name); 1822 String16 comment(sym.comment); 1823 if (comment.size() <= 0) { 1824 comment = getAttributeComment(assets, name8); 1825 } 1826 if (comment.size() > 0) { 1827 const char16_t* p = comment.string(); 1828 while (*p != 0 && *p != '.') { 1829 if (*p == '{') { 1830 while (*p != 0 && *p != '}') { 1831 p++; 1832 } 1833 } else { 1834 p++; 1835 } 1836 } 1837 if (*p == '.') { 1838 p++; 1839 } 1840 comment = String16(comment.string(), p-comment.string()); 1841 } 1842 fprintf(fp, "%s <tr><td><code>{@link #%s_%s %s:%s}</code></td><td>%s</td></tr>\n", 1843 indentStr, nclassName.string(), 1844 flattenSymbol(name8).string(), 1845 getSymbolPackage(name8, assets, true).string(), 1846 getSymbolName(name8).string(), 1847 String8(comment).string()); 1848 } 1849 } 1850 if (hasTable) { 1851 fprintf(fp, "%s </table>\n", indentStr); 1852 } 1853 for (a=0; a<NA; a++) { 1854 ssize_t pos = idents.indexOf(origOrder.itemAt(a)); 1855 if (pos >= 0) { 1856 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a); 1857 if (!publicFlags.itemAt(a) && !includePrivate) { 1858 continue; 1859 } 1860 fprintf(fp, "%s @see #%s_%s\n", 1861 indentStr, nclassName.string(), 1862 flattenSymbol(sym.name).string()); 1863 } 1864 } 1865 fprintf(fp, "%s */\n", getIndentSpace(indent)); 1866 1867 ann.printAnnotations(fp, indentStr); 1868 1869 fprintf(fp, 1870 "%spublic static final int[] %s = {\n" 1871 "%s", 1872 indentStr, nclassName.string(), 1873 getIndentSpace(indent+1)); 1874 1875 for (a=0; a<NA; a++) { 1876 if (a != 0) { 1877 if ((a&3) == 0) { 1878 fprintf(fp, ",\n%s", getIndentSpace(indent+1)); 1879 } else { 1880 fprintf(fp, ", "); 1881 } 1882 } 1883 fprintf(fp, "0x%08x", idents[a]); 1884 } 1885 1886 fprintf(fp, "\n%s};\n", indentStr); 1887 1888 for (a=0; a<NA; a++) { 1889 ssize_t pos = idents.indexOf(origOrder.itemAt(a)); 1890 if (pos >= 0) { 1891 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a); 1892 if (!publicFlags.itemAt(a) && !includePrivate) { 1893 continue; 1894 } 1895 String8 name8(sym.name); 1896 String16 comment(sym.comment); 1897 String16 typeComment; 1898 if (comment.size() <= 0) { 1899 comment = getAttributeComment(assets, name8, &typeComment); 1900 } else { 1901 getAttributeComment(assets, name8, &typeComment); 1902 } 1903 1904 uint32_t typeSpecFlags = 0; 1905 String16 name16(sym.name); 1906 assets->getIncludedResources().identifierForName( 1907 name16.string(), name16.size(), 1908 attr16.string(), attr16.size(), 1909 package16.string(), package16.size(), &typeSpecFlags); 1910 //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(), 1911 // String8(attr16).string(), String8(name16).string(), typeSpecFlags); 1912 const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0; 1913 1914 AnnotationProcessor ann; 1915 fprintf(fp, "%s/**\n", indentStr); 1916 if (comment.size() > 0) { 1917 String8 cmt(comment); 1918 ann.preprocessComment(cmt); 1919 fprintf(fp, "%s <p>\n%s @attr description\n", indentStr, indentStr); 1920 fprintf(fp, "%s %s\n", indentStr, cmt.string()); 1921 } else { 1922 fprintf(fp, 1923 "%s <p>This symbol is the offset where the {@link %s.R.attr#%s}\n" 1924 "%s attribute's value can be found in the {@link #%s} array.\n", 1925 indentStr, 1926 getSymbolPackage(name8, assets, pub).string(), 1927 getSymbolName(name8).string(), 1928 indentStr, nclassName.string()); 1929 } 1930 if (typeComment.size() > 0) { 1931 String8 cmt(typeComment); 1932 ann.preprocessComment(cmt); 1933 fprintf(fp, "\n\n%s %s\n", indentStr, cmt.string()); 1934 } 1935 if (comment.size() > 0) { 1936 if (pub) { 1937 fprintf(fp, 1938 "%s <p>This corresponds to the global attribute\n" 1939 "%s resource symbol {@link %s.R.attr#%s}.\n", 1940 indentStr, indentStr, 1941 getSymbolPackage(name8, assets, true).string(), 1942 getSymbolName(name8).string()); 1943 } else { 1944 fprintf(fp, 1945 "%s <p>This is a private symbol.\n", indentStr); 1946 } 1947 } 1948 fprintf(fp, "%s @attr name %s:%s\n", indentStr, 1949 getSymbolPackage(name8, assets, pub).string(), 1950 getSymbolName(name8).string()); 1951 fprintf(fp, "%s*/\n", indentStr); 1952 ann.printAnnotations(fp, indentStr); 1953 fprintf(fp, 1954 "%spublic static final int %s_%s = %d;\n", 1955 indentStr, nclassName.string(), 1956 flattenSymbol(name8).string(), (int)pos); 1957 } 1958 } 1959 } 1960 1961 indent--; 1962 fprintf(fp, "%s};\n", getIndentSpace(indent)); 1963 return hasErrors ? UNKNOWN_ERROR : NO_ERROR; 1964} 1965 1966static status_t writeTextLayoutClasses( 1967 FILE* fp, const sp<AaptAssets>& assets, 1968 const sp<AaptSymbols>& symbols, bool includePrivate) 1969{ 1970 String16 attr16("attr"); 1971 String16 package16(assets->getPackage()); 1972 1973 bool hasErrors = false; 1974 1975 size_t i; 1976 size_t N = symbols->getNestedSymbols().size(); 1977 for (i=0; i<N; i++) { 1978 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i); 1979 String8 realClassName(symbols->getNestedSymbols().keyAt(i)); 1980 String8 nclassName(flattenSymbol(realClassName)); 1981 1982 SortedVector<uint32_t> idents; 1983 Vector<uint32_t> origOrder; 1984 Vector<bool> publicFlags; 1985 1986 size_t a; 1987 size_t NA = nsymbols->getSymbols().size(); 1988 for (a=0; a<NA; a++) { 1989 const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a)); 1990 int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32 1991 ? sym.int32Val : 0; 1992 bool isPublic = true; 1993 if (code == 0) { 1994 String16 name16(sym.name); 1995 uint32_t typeSpecFlags; 1996 code = assets->getIncludedResources().identifierForName( 1997 name16.string(), name16.size(), 1998 attr16.string(), attr16.size(), 1999 package16.string(), package16.size(), &typeSpecFlags); 2000 if (code == 0) { 2001 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n", 2002 nclassName.string(), sym.name.string()); 2003 hasErrors = true; 2004 } 2005 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0; 2006 } 2007 idents.add(code); 2008 origOrder.add(code); 2009 publicFlags.add(isPublic); 2010 } 2011 2012 NA = idents.size(); 2013 2014 fprintf(fp, "int[] styleable %s {", nclassName.string()); 2015 2016 for (a=0; a<NA; a++) { 2017 if (a != 0) { 2018 fprintf(fp, ","); 2019 } 2020 fprintf(fp, " 0x%08x", idents[a]); 2021 } 2022 2023 fprintf(fp, " }\n"); 2024 2025 for (a=0; a<NA; a++) { 2026 ssize_t pos = idents.indexOf(origOrder.itemAt(a)); 2027 if (pos >= 0) { 2028 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a); 2029 if (!publicFlags.itemAt(a) && !includePrivate) { 2030 continue; 2031 } 2032 String8 name8(sym.name); 2033 String16 comment(sym.comment); 2034 String16 typeComment; 2035 if (comment.size() <= 0) { 2036 comment = getAttributeComment(assets, name8, &typeComment); 2037 } else { 2038 getAttributeComment(assets, name8, &typeComment); 2039 } 2040 2041 uint32_t typeSpecFlags = 0; 2042 String16 name16(sym.name); 2043 assets->getIncludedResources().identifierForName( 2044 name16.string(), name16.size(), 2045 attr16.string(), attr16.size(), 2046 package16.string(), package16.size(), &typeSpecFlags); 2047 //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(), 2048 // String8(attr16).string(), String8(name16).string(), typeSpecFlags); 2049 const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0; 2050 2051 fprintf(fp, 2052 "int styleable %s_%s %d\n", 2053 nclassName.string(), 2054 flattenSymbol(name8).string(), (int)pos); 2055 } 2056 } 2057 } 2058 2059 return hasErrors ? UNKNOWN_ERROR : NO_ERROR; 2060} 2061 2062static status_t writeSymbolClass( 2063 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate, 2064 const sp<AaptSymbols>& symbols, const String8& className, int indent, 2065 bool nonConstantId) 2066{ 2067 fprintf(fp, "%spublic %sfinal class %s {\n", 2068 getIndentSpace(indent), 2069 indent != 0 ? "static " : "", className.string()); 2070 indent++; 2071 2072 size_t i; 2073 status_t err = NO_ERROR; 2074 2075 const char * id_format = nonConstantId ? 2076 "%spublic static int %s=0x%08x;\n" : 2077 "%spublic static final int %s=0x%08x;\n"; 2078 2079 size_t N = symbols->getSymbols().size(); 2080 for (i=0; i<N; i++) { 2081 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i); 2082 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) { 2083 continue; 2084 } 2085 if (!assets->isJavaSymbol(sym, includePrivate)) { 2086 continue; 2087 } 2088 String8 name8(sym.name); 2089 String16 comment(sym.comment); 2090 bool haveComment = false; 2091 AnnotationProcessor ann; 2092 if (comment.size() > 0) { 2093 haveComment = true; 2094 String8 cmt(comment); 2095 ann.preprocessComment(cmt); 2096 fprintf(fp, 2097 "%s/** %s\n", 2098 getIndentSpace(indent), cmt.string()); 2099 } else if (sym.isPublic && !includePrivate) { 2100 sym.sourcePos.warning("No comment for public symbol %s:%s/%s", 2101 assets->getPackage().string(), className.string(), 2102 String8(sym.name).string()); 2103 } 2104 String16 typeComment(sym.typeComment); 2105 if (typeComment.size() > 0) { 2106 String8 cmt(typeComment); 2107 ann.preprocessComment(cmt); 2108 if (!haveComment) { 2109 haveComment = true; 2110 fprintf(fp, 2111 "%s/** %s\n", getIndentSpace(indent), cmt.string()); 2112 } else { 2113 fprintf(fp, 2114 "%s %s\n", getIndentSpace(indent), cmt.string()); 2115 } 2116 } 2117 if (haveComment) { 2118 fprintf(fp,"%s */\n", getIndentSpace(indent)); 2119 } 2120 ann.printAnnotations(fp, getIndentSpace(indent)); 2121 fprintf(fp, id_format, 2122 getIndentSpace(indent), 2123 flattenSymbol(name8).string(), (int)sym.int32Val); 2124 } 2125 2126 for (i=0; i<N; i++) { 2127 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i); 2128 if (sym.typeCode != AaptSymbolEntry::TYPE_STRING) { 2129 continue; 2130 } 2131 if (!assets->isJavaSymbol(sym, includePrivate)) { 2132 continue; 2133 } 2134 String8 name8(sym.name); 2135 String16 comment(sym.comment); 2136 AnnotationProcessor ann; 2137 if (comment.size() > 0) { 2138 String8 cmt(comment); 2139 ann.preprocessComment(cmt); 2140 fprintf(fp, 2141 "%s/** %s\n" 2142 "%s */\n", 2143 getIndentSpace(indent), cmt.string(), 2144 getIndentSpace(indent)); 2145 } else if (sym.isPublic && !includePrivate) { 2146 sym.sourcePos.warning("No comment for public symbol %s:%s/%s", 2147 assets->getPackage().string(), className.string(), 2148 String8(sym.name).string()); 2149 } 2150 ann.printAnnotations(fp, getIndentSpace(indent)); 2151 fprintf(fp, "%spublic static final String %s=\"%s\";\n", 2152 getIndentSpace(indent), 2153 flattenSymbol(name8).string(), sym.stringVal.string()); 2154 } 2155 2156 sp<AaptSymbols> styleableSymbols; 2157 2158 N = symbols->getNestedSymbols().size(); 2159 for (i=0; i<N; i++) { 2160 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i); 2161 String8 nclassName(symbols->getNestedSymbols().keyAt(i)); 2162 if (nclassName == "styleable") { 2163 styleableSymbols = nsymbols; 2164 } else { 2165 err = writeSymbolClass(fp, assets, includePrivate, nsymbols, nclassName, indent, nonConstantId); 2166 } 2167 if (err != NO_ERROR) { 2168 return err; 2169 } 2170 } 2171 2172 if (styleableSymbols != NULL) { 2173 err = writeLayoutClasses(fp, assets, styleableSymbols, indent, includePrivate); 2174 if (err != NO_ERROR) { 2175 return err; 2176 } 2177 } 2178 2179 indent--; 2180 fprintf(fp, "%s}\n", getIndentSpace(indent)); 2181 return NO_ERROR; 2182} 2183 2184static status_t writeTextSymbolClass( 2185 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate, 2186 const sp<AaptSymbols>& symbols, const String8& className) 2187{ 2188 size_t i; 2189 status_t err = NO_ERROR; 2190 2191 size_t N = symbols->getSymbols().size(); 2192 for (i=0; i<N; i++) { 2193 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i); 2194 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) { 2195 continue; 2196 } 2197 2198 if (!assets->isJavaSymbol(sym, includePrivate)) { 2199 continue; 2200 } 2201 2202 String8 name8(sym.name); 2203 fprintf(fp, "int %s %s 0x%08x\n", 2204 className.string(), 2205 flattenSymbol(name8).string(), (int)sym.int32Val); 2206 } 2207 2208 N = symbols->getNestedSymbols().size(); 2209 for (i=0; i<N; i++) { 2210 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i); 2211 String8 nclassName(symbols->getNestedSymbols().keyAt(i)); 2212 if (nclassName == "styleable") { 2213 err = writeTextLayoutClasses(fp, assets, nsymbols, includePrivate); 2214 } else { 2215 err = writeTextSymbolClass(fp, assets, includePrivate, nsymbols, nclassName); 2216 } 2217 if (err != NO_ERROR) { 2218 return err; 2219 } 2220 } 2221 2222 return NO_ERROR; 2223} 2224 2225status_t writeResourceSymbols(Bundle* bundle, const sp<AaptAssets>& assets, 2226 const String8& package, bool includePrivate) 2227{ 2228 if (!bundle->getRClassDir()) { 2229 return NO_ERROR; 2230 } 2231 2232 const char* textSymbolsDest = bundle->getOutputTextSymbols(); 2233 2234 String8 R("R"); 2235 const size_t N = assets->getSymbols().size(); 2236 for (size_t i=0; i<N; i++) { 2237 sp<AaptSymbols> symbols = assets->getSymbols().valueAt(i); 2238 String8 className(assets->getSymbols().keyAt(i)); 2239 String8 dest(bundle->getRClassDir()); 2240 2241 if (bundle->getMakePackageDirs()) { 2242 String8 pkg(package); 2243 const char* last = pkg.string(); 2244 const char* s = last-1; 2245 do { 2246 s++; 2247 if (s > last && (*s == '.' || *s == 0)) { 2248 String8 part(last, s-last); 2249 dest.appendPath(part); 2250#ifdef HAVE_MS_C_RUNTIME 2251 _mkdir(dest.string()); 2252#else 2253 mkdir(dest.string(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP); 2254#endif 2255 last = s+1; 2256 } 2257 } while (*s); 2258 } 2259 dest.appendPath(className); 2260 dest.append(".java"); 2261 FILE* fp = fopen(dest.string(), "w+"); 2262 if (fp == NULL) { 2263 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n", 2264 dest.string(), strerror(errno)); 2265 return UNKNOWN_ERROR; 2266 } 2267 if (bundle->getVerbose()) { 2268 printf(" Writing symbols for class %s.\n", className.string()); 2269 } 2270 2271 fprintf(fp, 2272 "/* AUTO-GENERATED FILE. DO NOT MODIFY.\n" 2273 " *\n" 2274 " * This class was automatically generated by the\n" 2275 " * aapt tool from the resource data it found. It\n" 2276 " * should not be modified by hand.\n" 2277 " */\n" 2278 "\n" 2279 "package %s;\n\n", package.string()); 2280 2281 status_t err = writeSymbolClass(fp, assets, includePrivate, symbols, 2282 className, 0, bundle->getNonConstantId()); 2283 fclose(fp); 2284 if (err != NO_ERROR) { 2285 return err; 2286 } 2287 2288 if (textSymbolsDest != NULL && R == className) { 2289 String8 textDest(textSymbolsDest); 2290 textDest.appendPath(className); 2291 textDest.append(".txt"); 2292 2293 FILE* fp = fopen(textDest.string(), "w+"); 2294 if (fp == NULL) { 2295 fprintf(stderr, "ERROR: Unable to open text symbol file %s: %s\n", 2296 textDest.string(), strerror(errno)); 2297 return UNKNOWN_ERROR; 2298 } 2299 if (bundle->getVerbose()) { 2300 printf(" Writing text symbols for class %s.\n", className.string()); 2301 } 2302 2303 status_t err = writeTextSymbolClass(fp, assets, includePrivate, symbols, 2304 className); 2305 fclose(fp); 2306 if (err != NO_ERROR) { 2307 return err; 2308 } 2309 } 2310 2311 // If we were asked to generate a dependency file, we'll go ahead and add this R.java 2312 // as a target in the dependency file right next to it. 2313 if (bundle->getGenDependencies() && R == className) { 2314 // Add this R.java to the dependency file 2315 String8 dependencyFile(bundle->getRClassDir()); 2316 dependencyFile.appendPath("R.java.d"); 2317 2318 FILE *fp = fopen(dependencyFile.string(), "a"); 2319 fprintf(fp,"%s \\\n", dest.string()); 2320 fclose(fp); 2321 } 2322 } 2323 2324 return NO_ERROR; 2325} 2326 2327 2328class ProguardKeepSet 2329{ 2330public: 2331 // { rule --> { file locations } } 2332 KeyedVector<String8, SortedVector<String8> > rules; 2333 2334 void add(const String8& rule, const String8& where); 2335}; 2336 2337void ProguardKeepSet::add(const String8& rule, const String8& where) 2338{ 2339 ssize_t index = rules.indexOfKey(rule); 2340 if (index < 0) { 2341 index = rules.add(rule, SortedVector<String8>()); 2342 } 2343 rules.editValueAt(index).add(where); 2344} 2345 2346void 2347addProguardKeepRule(ProguardKeepSet* keep, const String8& inClassName, 2348 const char* pkg, const String8& srcName, int line) 2349{ 2350 String8 className(inClassName); 2351 if (pkg != NULL) { 2352 // asdf --> package.asdf 2353 // .asdf .a.b --> package.asdf package.a.b 2354 // asdf.adsf --> asdf.asdf 2355 const char* p = className.string(); 2356 const char* q = strchr(p, '.'); 2357 if (p == q) { 2358 className = pkg; 2359 className.append(inClassName); 2360 } else if (q == NULL) { 2361 className = pkg; 2362 className.append("."); 2363 className.append(inClassName); 2364 } 2365 } 2366 2367 String8 rule("-keep class "); 2368 rule += className; 2369 rule += " { <init>(...); }"; 2370 2371 String8 location("view "); 2372 location += srcName; 2373 char lineno[20]; 2374 sprintf(lineno, ":%d", line); 2375 location += lineno; 2376 2377 keep->add(rule, location); 2378} 2379 2380void 2381addProguardKeepMethodRule(ProguardKeepSet* keep, const String8& memberName, 2382 const char* pkg, const String8& srcName, int line) 2383{ 2384 String8 rule("-keepclassmembers class * { *** "); 2385 rule += memberName; 2386 rule += "(...); }"; 2387 2388 String8 location("onClick "); 2389 location += srcName; 2390 char lineno[20]; 2391 sprintf(lineno, ":%d", line); 2392 location += lineno; 2393 2394 keep->add(rule, location); 2395} 2396 2397status_t 2398writeProguardForAndroidManifest(ProguardKeepSet* keep, const sp<AaptAssets>& assets) 2399{ 2400 status_t err; 2401 ResXMLTree tree; 2402 size_t len; 2403 ResXMLTree::event_code_t code; 2404 int depth = 0; 2405 bool inApplication = false; 2406 String8 error; 2407 sp<AaptGroup> assGroup; 2408 sp<AaptFile> assFile; 2409 String8 pkg; 2410 2411 // First, look for a package file to parse. This is required to 2412 // be able to generate the resource information. 2413 assGroup = assets->getFiles().valueFor(String8("AndroidManifest.xml")); 2414 if (assGroup == NULL) { 2415 fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n"); 2416 return -1; 2417 } 2418 2419 if (assGroup->getFiles().size() != 1) { 2420 fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n", 2421 assGroup->getFiles().valueAt(0)->getPrintableSource().string()); 2422 } 2423 2424 assFile = assGroup->getFiles().valueAt(0); 2425 2426 err = parseXMLResource(assFile, &tree); 2427 if (err != NO_ERROR) { 2428 return err; 2429 } 2430 2431 tree.restart(); 2432 2433 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) { 2434 if (code == ResXMLTree::END_TAG) { 2435 if (/* name == "Application" && */ depth == 2) { 2436 inApplication = false; 2437 } 2438 depth--; 2439 continue; 2440 } 2441 if (code != ResXMLTree::START_TAG) { 2442 continue; 2443 } 2444 depth++; 2445 String8 tag(tree.getElementName(&len)); 2446 // printf("Depth %d tag %s\n", depth, tag.string()); 2447 bool keepTag = false; 2448 if (depth == 1) { 2449 if (tag != "manifest") { 2450 fprintf(stderr, "ERROR: manifest does not start with <manifest> tag\n"); 2451 return -1; 2452 } 2453 pkg = getAttribute(tree, NULL, "package", NULL); 2454 } else if (depth == 2) { 2455 if (tag == "application") { 2456 inApplication = true; 2457 keepTag = true; 2458 2459 String8 agent = getAttribute(tree, "http://schemas.android.com/apk/res/android", 2460 "backupAgent", &error); 2461 if (agent.length() > 0) { 2462 addProguardKeepRule(keep, agent, pkg.string(), 2463 assFile->getPrintableSource(), tree.getLineNumber()); 2464 } 2465 } else if (tag == "instrumentation") { 2466 keepTag = true; 2467 } 2468 } 2469 if (!keepTag && inApplication && depth == 3) { 2470 if (tag == "activity" || tag == "service" || tag == "receiver" || tag == "provider") { 2471 keepTag = true; 2472 } 2473 } 2474 if (keepTag) { 2475 String8 name = getAttribute(tree, "http://schemas.android.com/apk/res/android", 2476 "name", &error); 2477 if (error != "") { 2478 fprintf(stderr, "ERROR: %s\n", error.string()); 2479 return -1; 2480 } 2481 if (name.length() > 0) { 2482 addProguardKeepRule(keep, name, pkg.string(), 2483 assFile->getPrintableSource(), tree.getLineNumber()); 2484 } 2485 } 2486 } 2487 2488 return NO_ERROR; 2489} 2490 2491struct NamespaceAttributePair { 2492 const char* ns; 2493 const char* attr; 2494 2495 NamespaceAttributePair(const char* n, const char* a) : ns(n), attr(a) {} 2496 NamespaceAttributePair() : ns(NULL), attr(NULL) {} 2497}; 2498 2499status_t 2500writeProguardForXml(ProguardKeepSet* keep, const sp<AaptFile>& layoutFile, 2501 const Vector<String8>& startTags, const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs) 2502{ 2503 status_t err; 2504 ResXMLTree tree; 2505 size_t len; 2506 ResXMLTree::event_code_t code; 2507 2508 err = parseXMLResource(layoutFile, &tree); 2509 if (err != NO_ERROR) { 2510 return err; 2511 } 2512 2513 tree.restart(); 2514 2515 if (!startTags.isEmpty()) { 2516 bool haveStart = false; 2517 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) { 2518 if (code != ResXMLTree::START_TAG) { 2519 continue; 2520 } 2521 String8 tag(tree.getElementName(&len)); 2522 const size_t numStartTags = startTags.size(); 2523 for (size_t i = 0; i < numStartTags; i++) { 2524 if (tag == startTags[i]) { 2525 haveStart = true; 2526 } 2527 } 2528 break; 2529 } 2530 if (!haveStart) { 2531 return NO_ERROR; 2532 } 2533 } 2534 2535 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) { 2536 if (code != ResXMLTree::START_TAG) { 2537 continue; 2538 } 2539 String8 tag(tree.getElementName(&len)); 2540 2541 // If there is no '.', we'll assume that it's one of the built in names. 2542 if (strchr(tag.string(), '.')) { 2543 addProguardKeepRule(keep, tag, NULL, 2544 layoutFile->getPrintableSource(), tree.getLineNumber()); 2545 } else if (tagAttrPairs != NULL) { 2546 ssize_t tagIndex = tagAttrPairs->indexOfKey(tag); 2547 if (tagIndex >= 0) { 2548 const Vector<NamespaceAttributePair>& nsAttrVector = tagAttrPairs->valueAt(tagIndex); 2549 for (size_t i = 0; i < nsAttrVector.size(); i++) { 2550 const NamespaceAttributePair& nsAttr = nsAttrVector[i]; 2551 2552 ssize_t attrIndex = tree.indexOfAttribute(nsAttr.ns, nsAttr.attr); 2553 if (attrIndex < 0) { 2554 // fprintf(stderr, "%s:%d: <%s> does not have attribute %s:%s.\n", 2555 // layoutFile->getPrintableSource().string(), tree.getLineNumber(), 2556 // tag.string(), nsAttr.ns, nsAttr.attr); 2557 } else { 2558 size_t len; 2559 addProguardKeepRule(keep, 2560 String8(tree.getAttributeStringValue(attrIndex, &len)), NULL, 2561 layoutFile->getPrintableSource(), tree.getLineNumber()); 2562 } 2563 } 2564 } 2565 } 2566 ssize_t attrIndex = tree.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "onClick"); 2567 if (attrIndex >= 0) { 2568 size_t len; 2569 addProguardKeepMethodRule(keep, 2570 String8(tree.getAttributeStringValue(attrIndex, &len)), NULL, 2571 layoutFile->getPrintableSource(), tree.getLineNumber()); 2572 } 2573 } 2574 2575 return NO_ERROR; 2576} 2577 2578static void addTagAttrPair(KeyedVector<String8, Vector<NamespaceAttributePair> >* dest, 2579 const char* tag, const char* ns, const char* attr) { 2580 String8 tagStr(tag); 2581 ssize_t index = dest->indexOfKey(tagStr); 2582 2583 if (index < 0) { 2584 Vector<NamespaceAttributePair> vector; 2585 vector.add(NamespaceAttributePair(ns, attr)); 2586 dest->add(tagStr, vector); 2587 } else { 2588 dest->editValueAt(index).add(NamespaceAttributePair(ns, attr)); 2589 } 2590} 2591 2592status_t 2593writeProguardForLayouts(ProguardKeepSet* keep, const sp<AaptAssets>& assets) 2594{ 2595 status_t err; 2596 2597 // tag:attribute pairs that should be checked in layout files. 2598 KeyedVector<String8, Vector<NamespaceAttributePair> > kLayoutTagAttrPairs; 2599 addTagAttrPair(&kLayoutTagAttrPairs, "view", NULL, "class"); 2600 addTagAttrPair(&kLayoutTagAttrPairs, "fragment", NULL, "class"); 2601 addTagAttrPair(&kLayoutTagAttrPairs, "fragment", RESOURCES_ANDROID_NAMESPACE, "name"); 2602 2603 // tag:attribute pairs that should be checked in xml files. 2604 KeyedVector<String8, Vector<NamespaceAttributePair> > kXmlTagAttrPairs; 2605 addTagAttrPair(&kXmlTagAttrPairs, "PreferenceScreen", RESOURCES_ANDROID_NAMESPACE, "fragment"); 2606 addTagAttrPair(&kXmlTagAttrPairs, "header", RESOURCES_ANDROID_NAMESPACE, "fragment"); 2607 2608 const Vector<sp<AaptDir> >& dirs = assets->resDirs(); 2609 const size_t K = dirs.size(); 2610 for (size_t k=0; k<K; k++) { 2611 const sp<AaptDir>& d = dirs.itemAt(k); 2612 const String8& dirName = d->getLeaf(); 2613 Vector<String8> startTags; 2614 const char* startTag = NULL; 2615 const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs = NULL; 2616 if ((dirName == String8("layout")) || (strncmp(dirName.string(), "layout-", 7) == 0)) { 2617 tagAttrPairs = &kLayoutTagAttrPairs; 2618 } else if ((dirName == String8("xml")) || (strncmp(dirName.string(), "xml-", 4) == 0)) { 2619 startTags.add(String8("PreferenceScreen")); 2620 startTags.add(String8("preference-headers")); 2621 tagAttrPairs = &kXmlTagAttrPairs; 2622 } else if ((dirName == String8("menu")) || (strncmp(dirName.string(), "menu-", 5) == 0)) { 2623 startTags.add(String8("menu")); 2624 tagAttrPairs = NULL; 2625 } else { 2626 continue; 2627 } 2628 2629 const KeyedVector<String8,sp<AaptGroup> > groups = d->getFiles(); 2630 const size_t N = groups.size(); 2631 for (size_t i=0; i<N; i++) { 2632 const sp<AaptGroup>& group = groups.valueAt(i); 2633 const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files = group->getFiles(); 2634 const size_t M = files.size(); 2635 for (size_t j=0; j<M; j++) { 2636 err = writeProguardForXml(keep, files.valueAt(j), startTags, tagAttrPairs); 2637 if (err < 0) { 2638 return err; 2639 } 2640 } 2641 } 2642 } 2643 // Handle the overlays 2644 sp<AaptAssets> overlay = assets->getOverlay(); 2645 if (overlay.get()) { 2646 return writeProguardForLayouts(keep, overlay); 2647 } 2648 2649 return NO_ERROR; 2650} 2651 2652status_t 2653writeProguardFile(Bundle* bundle, const sp<AaptAssets>& assets) 2654{ 2655 status_t err = -1; 2656 2657 if (!bundle->getProguardFile()) { 2658 return NO_ERROR; 2659 } 2660 2661 ProguardKeepSet keep; 2662 2663 err = writeProguardForAndroidManifest(&keep, assets); 2664 if (err < 0) { 2665 return err; 2666 } 2667 2668 err = writeProguardForLayouts(&keep, assets); 2669 if (err < 0) { 2670 return err; 2671 } 2672 2673 FILE* fp = fopen(bundle->getProguardFile(), "w+"); 2674 if (fp == NULL) { 2675 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n", 2676 bundle->getProguardFile(), strerror(errno)); 2677 return UNKNOWN_ERROR; 2678 } 2679 2680 const KeyedVector<String8, SortedVector<String8> >& rules = keep.rules; 2681 const size_t N = rules.size(); 2682 for (size_t i=0; i<N; i++) { 2683 const SortedVector<String8>& locations = rules.valueAt(i); 2684 const size_t M = locations.size(); 2685 for (size_t j=0; j<M; j++) { 2686 fprintf(fp, "# %s\n", locations.itemAt(j).string()); 2687 } 2688 fprintf(fp, "%s\n\n", rules.keyAt(i).string()); 2689 } 2690 fclose(fp); 2691 2692 return err; 2693} 2694 2695// Loops through the string paths and writes them to the file pointer 2696// Each file path is written on its own line with a terminating backslash. 2697status_t writePathsToFile(const sp<FilePathStore>& files, FILE* fp) 2698{ 2699 status_t deps = -1; 2700 for (size_t file_i = 0; file_i < files->size(); ++file_i) { 2701 // Add the full file path to the dependency file 2702 fprintf(fp, "%s \\\n", files->itemAt(file_i).string()); 2703 deps++; 2704 } 2705 return deps; 2706} 2707 2708status_t 2709writeDependencyPreReqs(Bundle* bundle, const sp<AaptAssets>& assets, FILE* fp, bool includeRaw) 2710{ 2711 status_t deps = -1; 2712 deps += writePathsToFile(assets->getFullResPaths(), fp); 2713 if (includeRaw) { 2714 deps += writePathsToFile(assets->getFullAssetPaths(), fp); 2715 } 2716 return deps; 2717} 2718