Resource.cpp revision 19138468caf7050d482dc15f35a344eab11bb756
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#define NOISY(x) // x 14 15// ========================================================================== 16// ========================================================================== 17// ========================================================================== 18 19class PackageInfo 20{ 21public: 22 PackageInfo() 23 { 24 } 25 ~PackageInfo() 26 { 27 } 28 29 status_t parsePackage(const sp<AaptGroup>& grp); 30}; 31 32// ========================================================================== 33// ========================================================================== 34// ========================================================================== 35 36static String8 parseResourceName(const String8& leaf) 37{ 38 const char* firstDot = strchr(leaf.string(), '.'); 39 const char* str = leaf.string(); 40 41 if (firstDot) { 42 return String8(str, firstDot-str); 43 } else { 44 return String8(str); 45 } 46} 47 48ResourceTypeSet::ResourceTypeSet() 49 :RefBase(), 50 KeyedVector<String8,sp<AaptGroup> >() 51{ 52} 53 54class ResourceDirIterator 55{ 56public: 57 ResourceDirIterator(const sp<ResourceTypeSet>& set, const String8& resType) 58 : mResType(resType), mSet(set), mSetPos(0), mGroupPos(0) 59 { 60 } 61 62 inline const sp<AaptGroup>& getGroup() const { return mGroup; } 63 inline const sp<AaptFile>& getFile() const { return mFile; } 64 65 inline const String8& getBaseName() const { return mBaseName; } 66 inline const String8& getLeafName() const { return mLeafName; } 67 inline String8 getPath() const { return mPath; } 68 inline const ResTable_config& getParams() const { return mParams; } 69 70 enum { 71 EOD = 1 72 }; 73 74 ssize_t next() 75 { 76 while (true) { 77 sp<AaptGroup> group; 78 sp<AaptFile> file; 79 80 // Try to get next file in this current group. 81 if (mGroup != NULL && mGroupPos < mGroup->getFiles().size()) { 82 group = mGroup; 83 file = group->getFiles().valueAt(mGroupPos++); 84 85 // Try to get the next group/file in this directory 86 } else if (mSetPos < mSet->size()) { 87 mGroup = group = mSet->valueAt(mSetPos++); 88 if (group->getFiles().size() < 1) { 89 continue; 90 } 91 file = group->getFiles().valueAt(0); 92 mGroupPos = 1; 93 94 // All done! 95 } else { 96 return EOD; 97 } 98 99 mFile = file; 100 101 String8 leaf(group->getLeaf()); 102 mLeafName = String8(leaf); 103 mParams = file->getGroupEntry().toParams(); 104 NOISY(printf("Dir %s: mcc=%d mnc=%d lang=%c%c cnt=%c%c orient=%d density=%d touch=%d key=%d inp=%d nav=%d\n", 105 group->getPath().string(), mParams.mcc, mParams.mnc, 106 mParams.language[0] ? mParams.language[0] : '-', 107 mParams.language[1] ? mParams.language[1] : '-', 108 mParams.country[0] ? mParams.country[0] : '-', 109 mParams.country[1] ? mParams.country[1] : '-', 110 mParams.orientation, 111 mParams.density, mParams.touchscreen, mParams.keyboard, 112 mParams.inputFlags, mParams.navigation)); 113 mPath = "res"; 114 mPath.appendPath(file->getGroupEntry().toDirName(mResType)); 115 mPath.appendPath(leaf); 116 mBaseName = parseResourceName(leaf); 117 if (mBaseName == "") { 118 fprintf(stderr, "Error: malformed resource filename %s\n", 119 file->getPrintableSource().string()); 120 return UNKNOWN_ERROR; 121 } 122 123 NOISY(printf("file name=%s\n", mBaseName.string())); 124 125 return NO_ERROR; 126 } 127 } 128 129private: 130 String8 mResType; 131 132 const sp<ResourceTypeSet> mSet; 133 size_t mSetPos; 134 135 sp<AaptGroup> mGroup; 136 size_t mGroupPos; 137 138 sp<AaptFile> mFile; 139 String8 mBaseName; 140 String8 mLeafName; 141 String8 mPath; 142 ResTable_config mParams; 143}; 144 145// ========================================================================== 146// ========================================================================== 147// ========================================================================== 148 149bool isValidResourceType(const String8& type) 150{ 151 return type == "anim" || type == "drawable" || type == "layout" 152 || type == "values" || type == "xml" || type == "raw" 153 || type == "color" || type == "menu"; 154} 155 156static sp<AaptFile> getResourceFile(const sp<AaptAssets>& assets, bool makeIfNecessary=true) 157{ 158 sp<AaptGroup> group = assets->getFiles().valueFor(String8("resources.arsc")); 159 sp<AaptFile> file; 160 if (group != NULL) { 161 file = group->getFiles().valueFor(AaptGroupEntry()); 162 if (file != NULL) { 163 return file; 164 } 165 } 166 167 if (!makeIfNecessary) { 168 return NULL; 169 } 170 return assets->addFile(String8("resources.arsc"), AaptGroupEntry(), String8(), 171 NULL, String8()); 172} 173 174static status_t parsePackage(const sp<AaptAssets>& assets, const sp<AaptGroup>& grp) 175{ 176 if (grp->getFiles().size() != 1) { 177 fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n", 178 grp->getFiles().valueAt(0)->getPrintableSource().string()); 179 } 180 181 sp<AaptFile> file = grp->getFiles().valueAt(0); 182 183 ResXMLTree block; 184 status_t err = parseXMLResource(file, &block); 185 if (err != NO_ERROR) { 186 return err; 187 } 188 //printXMLBlock(&block); 189 190 ResXMLTree::event_code_t code; 191 while ((code=block.next()) != ResXMLTree::START_TAG 192 && code != ResXMLTree::END_DOCUMENT 193 && code != ResXMLTree::BAD_DOCUMENT) { 194 } 195 196 size_t len; 197 if (code != ResXMLTree::START_TAG) { 198 fprintf(stderr, "%s:%d: No start tag found\n", 199 file->getPrintableSource().string(), block.getLineNumber()); 200 return UNKNOWN_ERROR; 201 } 202 if (strcmp16(block.getElementName(&len), String16("manifest").string()) != 0) { 203 fprintf(stderr, "%s:%d: Invalid start tag %s, expected <manifest>\n", 204 file->getPrintableSource().string(), block.getLineNumber(), 205 String8(block.getElementName(&len)).string()); 206 return UNKNOWN_ERROR; 207 } 208 209 ssize_t nameIndex = block.indexOfAttribute(NULL, "package"); 210 if (nameIndex < 0) { 211 fprintf(stderr, "%s:%d: <manifest> does not have package attribute.\n", 212 file->getPrintableSource().string(), block.getLineNumber()); 213 return UNKNOWN_ERROR; 214 } 215 216 assets->setPackage(String8(block.getAttributeStringValue(nameIndex, &len))); 217 218 return NO_ERROR; 219} 220 221// ========================================================================== 222// ========================================================================== 223// ========================================================================== 224 225static status_t makeFileResources(Bundle* bundle, const sp<AaptAssets>& assets, 226 ResourceTable* table, 227 const sp<ResourceTypeSet>& set, 228 const char* resType) 229{ 230 String8 type8(resType); 231 String16 type16(resType); 232 233 bool hasErrors = false; 234 235 ResourceDirIterator it(set, String8(resType)); 236 ssize_t res; 237 while ((res=it.next()) == NO_ERROR) { 238 if (bundle->getVerbose()) { 239 printf(" (new resource id %s from %s)\n", 240 it.getBaseName().string(), it.getFile()->getPrintableSource().string()); 241 } 242 String16 baseName(it.getBaseName()); 243 const char16_t* str = baseName.string(); 244 const char16_t* const end = str + baseName.size(); 245 while (str < end) { 246 if (!((*str >= 'a' && *str <= 'z') 247 || (*str >= '0' && *str <= '9') 248 || *str == '_' || *str == '.')) { 249 fprintf(stderr, "%s: Invalid file name: must contain only [a-z0-9_.]\n", 250 it.getPath().string()); 251 hasErrors = true; 252 } 253 str++; 254 } 255 String8 resPath = it.getPath(); 256 resPath.convertToResPath(); 257 table->addEntry(SourcePos(it.getPath(), 0), String16(assets->getPackage()), 258 type16, 259 baseName, 260 String16(resPath), 261 NULL, 262 &it.getParams()); 263 assets->addResource(it.getLeafName(), resPath, it.getFile(), type8); 264 } 265 266 return hasErrors ? UNKNOWN_ERROR : NO_ERROR; 267} 268 269static status_t preProcessImages(Bundle* bundle, const sp<AaptAssets>& assets, 270 const sp<ResourceTypeSet>& set) 271{ 272 ResourceDirIterator it(set, String8("drawable")); 273 Vector<sp<AaptFile> > newNameFiles; 274 Vector<String8> newNamePaths; 275 bool hasErrors = false; 276 ssize_t res; 277 while ((res=it.next()) == NO_ERROR) { 278 res = preProcessImage(bundle, assets, it.getFile(), NULL); 279 if (res < NO_ERROR) { 280 hasErrors = true; 281 } 282 } 283 284 return (hasErrors || (res < NO_ERROR)) ? UNKNOWN_ERROR : NO_ERROR; 285} 286 287status_t postProcessImages(const sp<AaptAssets>& assets, 288 ResourceTable* table, 289 const sp<ResourceTypeSet>& set) 290{ 291 ResourceDirIterator it(set, String8("drawable")); 292 bool hasErrors = false; 293 ssize_t res; 294 while ((res=it.next()) == NO_ERROR) { 295 res = postProcessImage(assets, table, it.getFile()); 296 if (res < NO_ERROR) { 297 hasErrors = true; 298 } 299 } 300 301 return (hasErrors || (res < NO_ERROR)) ? UNKNOWN_ERROR : NO_ERROR; 302} 303 304static void collect_files(const sp<AaptDir>& dir, 305 KeyedVector<String8, sp<ResourceTypeSet> >* resources) 306{ 307 const DefaultKeyedVector<String8, sp<AaptGroup> >& groups = dir->getFiles(); 308 int N = groups.size(); 309 for (int i=0; i<N; i++) { 310 String8 leafName = groups.keyAt(i); 311 const sp<AaptGroup>& group = groups.valueAt(i); 312 313 const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files 314 = group->getFiles(); 315 316 if (files.size() == 0) { 317 continue; 318 } 319 320 String8 resType = files.valueAt(0)->getResourceType(); 321 322 ssize_t index = resources->indexOfKey(resType); 323 324 if (index < 0) { 325 sp<ResourceTypeSet> set = new ResourceTypeSet(); 326 set->add(leafName, group); 327 resources->add(resType, set); 328 } else { 329 sp<ResourceTypeSet> set = resources->valueAt(index); 330 index = set->indexOfKey(leafName); 331 if (index < 0) { 332 set->add(leafName, group); 333 } else { 334 sp<AaptGroup> existingGroup = set->valueAt(index); 335 int M = files.size(); 336 for (int j=0; j<M; j++) { 337 existingGroup->addFile(files.valueAt(j)); 338 } 339 } 340 } 341 } 342} 343 344static void collect_files(const sp<AaptAssets>& ass, 345 KeyedVector<String8, sp<ResourceTypeSet> >* resources) 346{ 347 const Vector<sp<AaptDir> >& dirs = ass->resDirs(); 348 int N = dirs.size(); 349 350 for (int i=0; i<N; i++) { 351 sp<AaptDir> d = dirs.itemAt(i); 352 collect_files(d, resources); 353 354 // don't try to include the res dir 355 ass->removeDir(d->getLeaf()); 356 } 357} 358 359enum { 360 ATTR_OKAY = -1, 361 ATTR_NOT_FOUND = -2, 362 ATTR_LEADING_SPACES = -3, 363 ATTR_TRAILING_SPACES = -4 364}; 365static int validateAttr(const String8& path, const ResXMLParser& parser, 366 const char* ns, const char* attr, const char* validChars, bool required) 367{ 368 size_t len; 369 370 ssize_t index = parser.indexOfAttribute(ns, attr); 371 const uint16_t* str; 372 if (index >= 0 && (str=parser.getAttributeStringValue(index, &len)) != NULL) { 373 if (validChars) { 374 for (size_t i=0; i<len; i++) { 375 uint16_t c = str[i]; 376 const char* p = validChars; 377 bool okay = false; 378 while (*p) { 379 if (c == *p) { 380 okay = true; 381 break; 382 } 383 p++; 384 } 385 if (!okay) { 386 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has invalid character '%c'.\n", 387 path.string(), parser.getLineNumber(), 388 String8(parser.getElementName(&len)).string(), attr, (char)str[i]); 389 return (int)i; 390 } 391 } 392 } 393 if (*str == ' ') { 394 fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not start with a space.\n", 395 path.string(), parser.getLineNumber(), 396 String8(parser.getElementName(&len)).string(), attr); 397 return ATTR_LEADING_SPACES; 398 } 399 if (str[len-1] == ' ') { 400 fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not end with a space.\n", 401 path.string(), parser.getLineNumber(), 402 String8(parser.getElementName(&len)).string(), attr); 403 return ATTR_TRAILING_SPACES; 404 } 405 return ATTR_OKAY; 406 } 407 if (required) { 408 fprintf(stderr, "%s:%d: Tag <%s> missing required attribute %s.\n", 409 path.string(), parser.getLineNumber(), 410 String8(parser.getElementName(&len)).string(), attr); 411 return ATTR_NOT_FOUND; 412 } 413 return ATTR_OKAY; 414} 415 416static void checkForIds(const String8& path, ResXMLParser& parser) 417{ 418 ResXMLTree::event_code_t code; 419 while ((code=parser.next()) != ResXMLTree::END_DOCUMENT 420 && code > ResXMLTree::BAD_DOCUMENT) { 421 if (code == ResXMLTree::START_TAG) { 422 ssize_t index = parser.indexOfAttribute(NULL, "id"); 423 if (index >= 0) { 424 fprintf(stderr, "%s:%d: warning: found plain 'id' attribute; did you mean the new 'android:id' name?\n", 425 path.string(), parser.getLineNumber()); 426 } 427 } 428 } 429} 430 431static bool applyFileOverlay(Bundle *bundle, 432 const sp<AaptAssets>& assets, 433 const sp<ResourceTypeSet>& baseSet, 434 const char *resType) 435{ 436 if (bundle->getVerbose()) { 437 printf("applyFileOverlay for %s\n", resType); 438 } 439 440 // Replace any base level files in this category with any found from the overlay 441 // Also add any found only in the overlay. 442 sp<AaptAssets> overlay = assets->getOverlay(); 443 String8 resTypeString(resType); 444 445 // work through the linked list of overlays 446 while (overlay.get()) { 447 KeyedVector<String8, sp<ResourceTypeSet> >* overlayRes = overlay->getResources(); 448 449 // get the overlay resources of the requested type 450 ssize_t index = overlayRes->indexOfKey(resTypeString); 451 if (index >= 0) { 452 sp<ResourceTypeSet> overlaySet = overlayRes->valueAt(index); 453 454 // for each of the resources, check for a match in the previously built 455 // non-overlay "baseset". 456 size_t overlayCount = overlaySet->size(); 457 for (size_t overlayIndex=0; overlayIndex<overlayCount; overlayIndex++) { 458 if (bundle->getVerbose()) { 459 printf("trying overlaySet Key=%s\n",overlaySet->keyAt(overlayIndex).string()); 460 } 461 size_t baseIndex = baseSet->indexOfKey(overlaySet->keyAt(overlayIndex)); 462 if (baseIndex < UNKNOWN_ERROR) { 463 // look for same flavor. For a given file (strings.xml, for example) 464 // there may be a locale specific or other flavors - we want to match 465 // the same flavor. 466 sp<AaptGroup> overlayGroup = overlaySet->valueAt(overlayIndex); 467 sp<AaptGroup> baseGroup = baseSet->valueAt(baseIndex); 468 469 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > overlayFiles = 470 overlayGroup->getFiles(); 471 if (bundle->getVerbose()) { 472 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > baseFiles = 473 baseGroup->getFiles(); 474 for (size_t i=0; i < baseFiles.size(); i++) { 475 printf("baseFile %d has flavor %s\n", i, 476 baseFiles.keyAt(i).toString().string()); 477 } 478 for (size_t i=0; i < overlayFiles.size(); i++) { 479 printf("overlayFile %d has flavor %s\n", i, 480 overlayFiles.keyAt(i).toString().string()); 481 } 482 } 483 484 size_t overlayGroupSize = overlayFiles.size(); 485 for (size_t overlayGroupIndex = 0; 486 overlayGroupIndex<overlayGroupSize; 487 overlayGroupIndex++) { 488 size_t baseFileIndex = 489 baseGroup->getFiles().indexOfKey(overlayFiles. 490 keyAt(overlayGroupIndex)); 491 if(baseFileIndex < UNKNOWN_ERROR) { 492 if (bundle->getVerbose()) { 493 printf("found a match (%d) for overlay file %s, for flavor %s\n", 494 baseFileIndex, 495 overlayGroup->getLeaf().string(), 496 overlayFiles.keyAt(overlayGroupIndex).toString().string()); 497 } 498 baseGroup->removeFile(baseFileIndex); 499 } else { 500 // didn't find a match fall through and add it.. 501 } 502 baseGroup->addFile(overlayFiles.valueAt(overlayGroupIndex)); 503 assets->addGroupEntry(overlayFiles.keyAt(overlayGroupIndex)); 504 } 505 } else { 506 // this group doesn't exist (a file that's only in the overlay) 507 baseSet->add(overlaySet->keyAt(overlayIndex), 508 overlaySet->valueAt(overlayIndex)); 509 // make sure all flavors are defined in the resources. 510 sp<AaptGroup> overlayGroup = overlaySet->valueAt(overlayIndex); 511 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > overlayFiles = 512 overlayGroup->getFiles(); 513 size_t overlayGroupSize = overlayFiles.size(); 514 for (size_t overlayGroupIndex = 0; 515 overlayGroupIndex<overlayGroupSize; 516 overlayGroupIndex++) { 517 assets->addGroupEntry(overlayFiles.keyAt(overlayGroupIndex)); 518 } 519 } 520 } 521 // this overlay didn't have resources for this type 522 } 523 // try next overlay 524 overlay = overlay->getOverlay(); 525 } 526 return true; 527} 528 529void addTagAttribute(const sp<XMLNode>& node, const char* ns8, 530 const char* attr8, const char* value) 531{ 532 if (value == NULL) { 533 return; 534 } 535 536 const String16 ns(ns8); 537 const String16 attr(attr8); 538 539 if (node->getAttribute(ns, attr) != NULL) { 540 fprintf(stderr, "Warning: AndroidManifest.xml already defines %s (in %s)\n", 541 String8(attr).string(), String8(ns).string()); 542 return; 543 } 544 545 node->addAttribute(ns, attr, String16(value)); 546} 547 548status_t massageManifest(Bundle* bundle, sp<XMLNode> root) 549{ 550 root = root->searchElement(String16(), String16("manifest")); 551 if (root == NULL) { 552 fprintf(stderr, "No <manifest> tag.\n"); 553 return UNKNOWN_ERROR; 554 } 555 556 addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionCode", 557 bundle->getVersionCode()); 558 addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionName", 559 bundle->getVersionName()); 560 561 if (bundle->getMinSdkVersion() != NULL 562 || bundle->getTargetSdkVersion() != NULL 563 || bundle->getMaxSdkVersion() != NULL) { 564 sp<XMLNode> vers = root->getChildElement(String16(), String16("uses-sdk")); 565 if (vers == NULL) { 566 vers = XMLNode::newElement(root->getFilename(), String16(), String16("uses-sdk")); 567 root->insertChildAt(vers, 0); 568 } 569 570 addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "minSdkVersion", 571 bundle->getMinSdkVersion()); 572 addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "targetSdkVersion", 573 bundle->getTargetSdkVersion()); 574 addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "maxSdkVersion", 575 bundle->getMaxSdkVersion()); 576 } 577 578 return NO_ERROR; 579} 580 581#define ASSIGN_IT(n) \ 582 do { \ 583 ssize_t index = resources->indexOfKey(String8(#n)); \ 584 if (index >= 0) { \ 585 n ## s = resources->valueAt(index); \ 586 } \ 587 } while (0) 588 589status_t buildResources(Bundle* bundle, const sp<AaptAssets>& assets) 590{ 591 // First, look for a package file to parse. This is required to 592 // be able to generate the resource information. 593 sp<AaptGroup> androidManifestFile = 594 assets->getFiles().valueFor(String8("AndroidManifest.xml")); 595 if (androidManifestFile == NULL) { 596 fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n"); 597 return UNKNOWN_ERROR; 598 } 599 600 status_t err = parsePackage(assets, androidManifestFile); 601 if (err != NO_ERROR) { 602 return err; 603 } 604 605 NOISY(printf("Creating resources for package %s\n", 606 assets->getPackage().string())); 607 608 ResourceTable table(bundle, String16(assets->getPackage())); 609 err = table.addIncludedResources(bundle, assets); 610 if (err != NO_ERROR) { 611 return err; 612 } 613 614 NOISY(printf("Found %d included resource packages\n", (int)table.size())); 615 616 // Standard flags for compiled XML and optional UTF-8 encoding 617 int xmlFlags = XML_COMPILE_STANDARD_RESOURCE; 618 if (bundle->getUTF8()) { 619 xmlFlags |= XML_COMPILE_UTF8; 620 } 621 622 // -------------------------------------------------------------- 623 // First, gather all resource information. 624 // -------------------------------------------------------------- 625 626 // resType -> leafName -> group 627 KeyedVector<String8, sp<ResourceTypeSet> > *resources = 628 new KeyedVector<String8, sp<ResourceTypeSet> >; 629 collect_files(assets, resources); 630 631 sp<ResourceTypeSet> drawables; 632 sp<ResourceTypeSet> layouts; 633 sp<ResourceTypeSet> anims; 634 sp<ResourceTypeSet> xmls; 635 sp<ResourceTypeSet> raws; 636 sp<ResourceTypeSet> colors; 637 sp<ResourceTypeSet> menus; 638 639 ASSIGN_IT(drawable); 640 ASSIGN_IT(layout); 641 ASSIGN_IT(anim); 642 ASSIGN_IT(xml); 643 ASSIGN_IT(raw); 644 ASSIGN_IT(color); 645 ASSIGN_IT(menu); 646 647 assets->setResources(resources); 648 // now go through any resource overlays and collect their files 649 sp<AaptAssets> current = assets->getOverlay(); 650 while(current.get()) { 651 KeyedVector<String8, sp<ResourceTypeSet> > *resources = 652 new KeyedVector<String8, sp<ResourceTypeSet> >; 653 current->setResources(resources); 654 collect_files(current, resources); 655 current = current->getOverlay(); 656 } 657 // apply the overlay files to the base set 658 if (!applyFileOverlay(bundle, assets, drawables, "drawable") || 659 !applyFileOverlay(bundle, assets, layouts, "layout") || 660 !applyFileOverlay(bundle, assets, anims, "anim") || 661 !applyFileOverlay(bundle, assets, xmls, "xml") || 662 !applyFileOverlay(bundle, assets, raws, "raw") || 663 !applyFileOverlay(bundle, assets, colors, "color") || 664 !applyFileOverlay(bundle, assets, menus, "menu")) { 665 return UNKNOWN_ERROR; 666 } 667 668 bool hasErrors = false; 669 670 if (drawables != NULL) { 671 err = preProcessImages(bundle, assets, drawables); 672 if (err == NO_ERROR) { 673 err = makeFileResources(bundle, assets, &table, drawables, "drawable"); 674 if (err != NO_ERROR) { 675 hasErrors = true; 676 } 677 } else { 678 hasErrors = true; 679 } 680 } 681 682 if (layouts != NULL) { 683 err = makeFileResources(bundle, assets, &table, layouts, "layout"); 684 if (err != NO_ERROR) { 685 hasErrors = true; 686 } 687 } 688 689 if (anims != NULL) { 690 err = makeFileResources(bundle, assets, &table, anims, "anim"); 691 if (err != NO_ERROR) { 692 hasErrors = true; 693 } 694 } 695 696 if (xmls != NULL) { 697 err = makeFileResources(bundle, assets, &table, xmls, "xml"); 698 if (err != NO_ERROR) { 699 hasErrors = true; 700 } 701 } 702 703 if (raws != NULL) { 704 err = makeFileResources(bundle, assets, &table, raws, "raw"); 705 if (err != NO_ERROR) { 706 hasErrors = true; 707 } 708 } 709 710 // compile resources 711 current = assets; 712 while(current.get()) { 713 KeyedVector<String8, sp<ResourceTypeSet> > *resources = 714 current->getResources(); 715 716 ssize_t index = resources->indexOfKey(String8("values")); 717 if (index >= 0) { 718 ResourceDirIterator it(resources->valueAt(index), String8("values")); 719 ssize_t res; 720 while ((res=it.next()) == NO_ERROR) { 721 sp<AaptFile> file = it.getFile(); 722 res = compileResourceFile(bundle, assets, file, it.getParams(), 723 (current!=assets), &table); 724 if (res != NO_ERROR) { 725 hasErrors = true; 726 } 727 } 728 } 729 current = current->getOverlay(); 730 } 731 732 if (colors != NULL) { 733 err = makeFileResources(bundle, assets, &table, colors, "color"); 734 if (err != NO_ERROR) { 735 hasErrors = true; 736 } 737 } 738 739 if (menus != NULL) { 740 err = makeFileResources(bundle, assets, &table, menus, "menu"); 741 if (err != NO_ERROR) { 742 hasErrors = true; 743 } 744 } 745 746 // -------------------------------------------------------------------- 747 // Assignment of resource IDs and initial generation of resource table. 748 // -------------------------------------------------------------------- 749 750 if (table.hasResources()) { 751 sp<AaptFile> resFile(getResourceFile(assets)); 752 if (resFile == NULL) { 753 fprintf(stderr, "Error: unable to generate entry for resource data\n"); 754 return UNKNOWN_ERROR; 755 } 756 757 err = table.assignResourceIds(); 758 if (err < NO_ERROR) { 759 return err; 760 } 761 } 762 763 // -------------------------------------------------------------- 764 // Finally, we can now we can compile XML files, which may reference 765 // resources. 766 // -------------------------------------------------------------- 767 768 if (layouts != NULL) { 769 ResourceDirIterator it(layouts, String8("layout")); 770 while ((err=it.next()) == NO_ERROR) { 771 String8 src = it.getFile()->getPrintableSource(); 772 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags); 773 if (err == NO_ERROR) { 774 ResXMLTree block; 775 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true); 776 checkForIds(src, block); 777 } else { 778 hasErrors = true; 779 } 780 } 781 782 if (err < NO_ERROR) { 783 hasErrors = true; 784 } 785 err = NO_ERROR; 786 } 787 788 if (anims != NULL) { 789 ResourceDirIterator it(anims, String8("anim")); 790 while ((err=it.next()) == NO_ERROR) { 791 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags); 792 if (err != NO_ERROR) { 793 hasErrors = true; 794 } 795 } 796 797 if (err < NO_ERROR) { 798 hasErrors = true; 799 } 800 err = NO_ERROR; 801 } 802 803 if (xmls != NULL) { 804 ResourceDirIterator it(xmls, String8("xml")); 805 while ((err=it.next()) == NO_ERROR) { 806 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags); 807 if (err != NO_ERROR) { 808 hasErrors = true; 809 } 810 } 811 812 if (err < NO_ERROR) { 813 hasErrors = true; 814 } 815 err = NO_ERROR; 816 } 817 818 if (drawables != NULL) { 819 err = postProcessImages(assets, &table, drawables); 820 if (err != NO_ERROR) { 821 hasErrors = true; 822 } 823 } 824 825 if (colors != NULL) { 826 ResourceDirIterator it(colors, String8("color")); 827 while ((err=it.next()) == NO_ERROR) { 828 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags); 829 if (err != NO_ERROR) { 830 hasErrors = true; 831 } 832 } 833 834 if (err < NO_ERROR) { 835 hasErrors = true; 836 } 837 err = NO_ERROR; 838 } 839 840 if (menus != NULL) { 841 ResourceDirIterator it(menus, String8("menu")); 842 while ((err=it.next()) == NO_ERROR) { 843 String8 src = it.getFile()->getPrintableSource(); 844 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags); 845 if (err != NO_ERROR) { 846 hasErrors = true; 847 } 848 ResXMLTree block; 849 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true); 850 checkForIds(src, block); 851 } 852 853 if (err < NO_ERROR) { 854 hasErrors = true; 855 } 856 err = NO_ERROR; 857 } 858 859 const sp<AaptFile> manifestFile(androidManifestFile->getFiles().valueAt(0)); 860 String8 manifestPath(manifestFile->getPrintableSource()); 861 862 // Perform a basic validation of the manifest file. This time we 863 // parse it with the comments intact, so that we can use them to 864 // generate java docs... so we are not going to write this one 865 // back out to the final manifest data. 866 err = compileXmlFile(assets, manifestFile, &table, 867 XML_COMPILE_ASSIGN_ATTRIBUTE_IDS 868 | XML_COMPILE_STRIP_WHITESPACE | XML_COMPILE_STRIP_RAW_VALUES); 869 if (err < NO_ERROR) { 870 return err; 871 } 872 ResXMLTree block; 873 block.setTo(manifestFile->getData(), manifestFile->getSize(), true); 874 String16 manifest16("manifest"); 875 String16 permission16("permission"); 876 String16 permission_group16("permission-group"); 877 String16 uses_permission16("uses-permission"); 878 String16 instrumentation16("instrumentation"); 879 String16 application16("application"); 880 String16 provider16("provider"); 881 String16 service16("service"); 882 String16 receiver16("receiver"); 883 String16 activity16("activity"); 884 String16 action16("action"); 885 String16 category16("category"); 886 String16 data16("scheme"); 887 const char* packageIdentChars = "abcdefghijklmnopqrstuvwxyz" 888 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789"; 889 const char* packageIdentCharsWithTheStupid = "abcdefghijklmnopqrstuvwxyz" 890 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-"; 891 const char* classIdentChars = "abcdefghijklmnopqrstuvwxyz" 892 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789$"; 893 const char* processIdentChars = "abcdefghijklmnopqrstuvwxyz" 894 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:"; 895 const char* authoritiesIdentChars = "abcdefghijklmnopqrstuvwxyz" 896 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-:;"; 897 const char* typeIdentChars = "abcdefghijklmnopqrstuvwxyz" 898 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:-/*+"; 899 const char* schemeIdentChars = "abcdefghijklmnopqrstuvwxyz" 900 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-"; 901 ResXMLTree::event_code_t code; 902 sp<AaptSymbols> permissionSymbols; 903 sp<AaptSymbols> permissionGroupSymbols; 904 while ((code=block.next()) != ResXMLTree::END_DOCUMENT 905 && code > ResXMLTree::BAD_DOCUMENT) { 906 if (code == ResXMLTree::START_TAG) { 907 size_t len; 908 if (block.getElementNamespace(&len) != NULL) { 909 continue; 910 } 911 if (strcmp16(block.getElementName(&len), manifest16.string()) == 0) { 912 if (validateAttr(manifestPath, block, NULL, "package", 913 packageIdentChars, true) != ATTR_OKAY) { 914 hasErrors = true; 915 } 916 } else if (strcmp16(block.getElementName(&len), permission16.string()) == 0 917 || strcmp16(block.getElementName(&len), permission_group16.string()) == 0) { 918 const bool isGroup = strcmp16(block.getElementName(&len), 919 permission_group16.string()) == 0; 920 if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name", 921 isGroup ? packageIdentCharsWithTheStupid 922 : packageIdentChars, true) != ATTR_OKAY) { 923 hasErrors = true; 924 } 925 SourcePos srcPos(manifestPath, block.getLineNumber()); 926 sp<AaptSymbols> syms; 927 if (!isGroup) { 928 syms = permissionSymbols; 929 if (syms == NULL) { 930 sp<AaptSymbols> symbols = 931 assets->getSymbolsFor(String8("Manifest")); 932 syms = permissionSymbols = symbols->addNestedSymbol( 933 String8("permission"), srcPos); 934 } 935 } else { 936 syms = permissionGroupSymbols; 937 if (syms == NULL) { 938 sp<AaptSymbols> symbols = 939 assets->getSymbolsFor(String8("Manifest")); 940 syms = permissionGroupSymbols = symbols->addNestedSymbol( 941 String8("permission_group"), srcPos); 942 } 943 } 944 size_t len; 945 ssize_t index = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "name"); 946 const uint16_t* id = block.getAttributeStringValue(index, &len); 947 if (id == NULL) { 948 fprintf(stderr, "%s:%d: missing name attribute in element <%s>.\n", 949 manifestPath.string(), block.getLineNumber(), 950 String8(block.getElementName(&len)).string()); 951 hasErrors = true; 952 break; 953 } 954 String8 idStr(id); 955 char* p = idStr.lockBuffer(idStr.size()); 956 char* e = p + idStr.size(); 957 bool begins_with_digit = true; // init to true so an empty string fails 958 while (e > p) { 959 e--; 960 if (*e >= '0' && *e <= '9') { 961 begins_with_digit = true; 962 continue; 963 } 964 if ((*e >= 'a' && *e <= 'z') || 965 (*e >= 'A' && *e <= 'Z') || 966 (*e == '_')) { 967 begins_with_digit = false; 968 continue; 969 } 970 if (isGroup && (*e == '-')) { 971 *e = '_'; 972 begins_with_digit = false; 973 continue; 974 } 975 e++; 976 break; 977 } 978 idStr.unlockBuffer(); 979 // verify that we stopped because we hit a period or 980 // the beginning of the string, and that the 981 // identifier didn't begin with a digit. 982 if (begins_with_digit || (e != p && *(e-1) != '.')) { 983 fprintf(stderr, 984 "%s:%d: Permission name <%s> is not a valid Java symbol\n", 985 manifestPath.string(), block.getLineNumber(), idStr.string()); 986 hasErrors = true; 987 } 988 syms->addStringSymbol(String8(e), idStr, srcPos); 989 const uint16_t* cmt = block.getComment(&len); 990 if (cmt != NULL && *cmt != 0) { 991 //printf("Comment of %s: %s\n", String8(e).string(), 992 // String8(cmt).string()); 993 syms->appendComment(String8(e), String16(cmt), srcPos); 994 } else { 995 //printf("No comment for %s\n", String8(e).string()); 996 } 997 syms->makeSymbolPublic(String8(e), srcPos); 998 } else if (strcmp16(block.getElementName(&len), uses_permission16.string()) == 0) { 999 if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name", 1000 packageIdentChars, true) != ATTR_OKAY) { 1001 hasErrors = true; 1002 } 1003 } else if (strcmp16(block.getElementName(&len), instrumentation16.string()) == 0) { 1004 if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name", 1005 classIdentChars, true) != ATTR_OKAY) { 1006 hasErrors = true; 1007 } 1008 if (validateAttr(manifestPath, block, 1009 RESOURCES_ANDROID_NAMESPACE, "targetPackage", 1010 packageIdentChars, true) != ATTR_OKAY) { 1011 hasErrors = true; 1012 } 1013 } else if (strcmp16(block.getElementName(&len), application16.string()) == 0) { 1014 if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name", 1015 classIdentChars, false) != ATTR_OKAY) { 1016 hasErrors = true; 1017 } 1018 if (validateAttr(manifestPath, block, 1019 RESOURCES_ANDROID_NAMESPACE, "permission", 1020 packageIdentChars, false) != ATTR_OKAY) { 1021 hasErrors = true; 1022 } 1023 if (validateAttr(manifestPath, block, 1024 RESOURCES_ANDROID_NAMESPACE, "process", 1025 processIdentChars, false) != ATTR_OKAY) { 1026 hasErrors = true; 1027 } 1028 if (validateAttr(manifestPath, block, 1029 RESOURCES_ANDROID_NAMESPACE, "taskAffinity", 1030 processIdentChars, false) != ATTR_OKAY) { 1031 hasErrors = true; 1032 } 1033 } else if (strcmp16(block.getElementName(&len), provider16.string()) == 0) { 1034 if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name", 1035 classIdentChars, true) != ATTR_OKAY) { 1036 hasErrors = true; 1037 } 1038 if (validateAttr(manifestPath, block, 1039 RESOURCES_ANDROID_NAMESPACE, "authorities", 1040 authoritiesIdentChars, true) != ATTR_OKAY) { 1041 hasErrors = true; 1042 } 1043 if (validateAttr(manifestPath, block, 1044 RESOURCES_ANDROID_NAMESPACE, "permission", 1045 packageIdentChars, false) != ATTR_OKAY) { 1046 hasErrors = true; 1047 } 1048 if (validateAttr(manifestPath, block, 1049 RESOURCES_ANDROID_NAMESPACE, "process", 1050 processIdentChars, false) != ATTR_OKAY) { 1051 hasErrors = true; 1052 } 1053 } else if (strcmp16(block.getElementName(&len), service16.string()) == 0 1054 || strcmp16(block.getElementName(&len), receiver16.string()) == 0 1055 || strcmp16(block.getElementName(&len), activity16.string()) == 0) { 1056 if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name", 1057 classIdentChars, true) != ATTR_OKAY) { 1058 hasErrors = true; 1059 } 1060 if (validateAttr(manifestPath, block, 1061 RESOURCES_ANDROID_NAMESPACE, "permission", 1062 packageIdentChars, false) != ATTR_OKAY) { 1063 hasErrors = true; 1064 } 1065 if (validateAttr(manifestPath, block, 1066 RESOURCES_ANDROID_NAMESPACE, "process", 1067 processIdentChars, false) != ATTR_OKAY) { 1068 hasErrors = true; 1069 } 1070 if (validateAttr(manifestPath, block, 1071 RESOURCES_ANDROID_NAMESPACE, "taskAffinity", 1072 processIdentChars, false) != ATTR_OKAY) { 1073 hasErrors = true; 1074 } 1075 } else if (strcmp16(block.getElementName(&len), action16.string()) == 0 1076 || strcmp16(block.getElementName(&len), category16.string()) == 0) { 1077 if (validateAttr(manifestPath, block, 1078 RESOURCES_ANDROID_NAMESPACE, "name", 1079 packageIdentChars, true) != ATTR_OKAY) { 1080 hasErrors = true; 1081 } 1082 } else if (strcmp16(block.getElementName(&len), data16.string()) == 0) { 1083 if (validateAttr(manifestPath, block, 1084 RESOURCES_ANDROID_NAMESPACE, "mimeType", 1085 typeIdentChars, true) != ATTR_OKAY) { 1086 hasErrors = true; 1087 } 1088 if (validateAttr(manifestPath, block, 1089 RESOURCES_ANDROID_NAMESPACE, "scheme", 1090 schemeIdentChars, true) != ATTR_OKAY) { 1091 hasErrors = true; 1092 } 1093 } 1094 } 1095 } 1096 1097 if (table.validateLocalizations()) { 1098 hasErrors = true; 1099 } 1100 1101 if (hasErrors) { 1102 return UNKNOWN_ERROR; 1103 } 1104 1105 // Generate final compiled manifest file. 1106 manifestFile->clearData(); 1107 sp<XMLNode> manifestTree = XMLNode::parse(manifestFile); 1108 if (manifestTree == NULL) { 1109 return UNKNOWN_ERROR; 1110 } 1111 err = massageManifest(bundle, manifestTree); 1112 if (err < NO_ERROR) { 1113 return err; 1114 } 1115 err = compileXmlFile(assets, manifestTree, manifestFile, &table); 1116 if (err < NO_ERROR) { 1117 return err; 1118 } 1119 1120 //block.restart(); 1121 //printXMLBlock(&block); 1122 1123 // -------------------------------------------------------------- 1124 // Generate the final resource table. 1125 // Re-flatten because we may have added new resource IDs 1126 // -------------------------------------------------------------- 1127 1128 if (table.hasResources()) { 1129 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R")); 1130 err = table.addSymbols(symbols); 1131 if (err < NO_ERROR) { 1132 return err; 1133 } 1134 1135 sp<AaptFile> resFile(getResourceFile(assets)); 1136 if (resFile == NULL) { 1137 fprintf(stderr, "Error: unable to generate entry for resource data\n"); 1138 return UNKNOWN_ERROR; 1139 } 1140 1141 err = table.flatten(bundle, resFile); 1142 if (err < NO_ERROR) { 1143 return err; 1144 } 1145 1146 if (bundle->getPublicOutputFile()) { 1147 FILE* fp = fopen(bundle->getPublicOutputFile(), "w+"); 1148 if (fp == NULL) { 1149 fprintf(stderr, "ERROR: Unable to open public definitions output file %s: %s\n", 1150 (const char*)bundle->getPublicOutputFile(), strerror(errno)); 1151 return UNKNOWN_ERROR; 1152 } 1153 if (bundle->getVerbose()) { 1154 printf(" Writing public definitions to %s.\n", bundle->getPublicOutputFile()); 1155 } 1156 table.writePublicDefinitions(String16(assets->getPackage()), fp); 1157 fclose(fp); 1158 } 1159 1160 NOISY( 1161 ResTable rt; 1162 rt.add(resFile->getData(), resFile->getSize(), NULL); 1163 printf("Generated resources:\n"); 1164 rt.print(); 1165 ) 1166 1167 // These resources are now considered to be a part of the included 1168 // resources, for others to reference. 1169 err = assets->addIncludedResources(resFile); 1170 if (err < NO_ERROR) { 1171 fprintf(stderr, "ERROR: Unable to parse generated resources, aborting.\n"); 1172 return err; 1173 } 1174 } 1175 return err; 1176} 1177 1178static const char* getIndentSpace(int indent) 1179{ 1180static const char whitespace[] = 1181" "; 1182 1183 return whitespace + sizeof(whitespace) - 1 - indent*4; 1184} 1185 1186static status_t fixupSymbol(String16* inoutSymbol) 1187{ 1188 inoutSymbol->replaceAll('.', '_'); 1189 inoutSymbol->replaceAll(':', '_'); 1190 return NO_ERROR; 1191} 1192 1193static String16 getAttributeComment(const sp<AaptAssets>& assets, 1194 const String8& name, 1195 String16* outTypeComment = NULL) 1196{ 1197 sp<AaptSymbols> asym = assets->getSymbolsFor(String8("R")); 1198 if (asym != NULL) { 1199 //printf("Got R symbols!\n"); 1200 asym = asym->getNestedSymbols().valueFor(String8("attr")); 1201 if (asym != NULL) { 1202 //printf("Got attrs symbols! comment %s=%s\n", 1203 // name.string(), String8(asym->getComment(name)).string()); 1204 if (outTypeComment != NULL) { 1205 *outTypeComment = asym->getTypeComment(name); 1206 } 1207 return asym->getComment(name); 1208 } 1209 } 1210 return String16(); 1211} 1212 1213static status_t writeLayoutClasses( 1214 FILE* fp, const sp<AaptAssets>& assets, 1215 const sp<AaptSymbols>& symbols, int indent, bool includePrivate) 1216{ 1217 const char* indentStr = getIndentSpace(indent); 1218 if (!includePrivate) { 1219 fprintf(fp, "%s/** @doconly */\n", indentStr); 1220 } 1221 fprintf(fp, "%spublic static final class styleable {\n", indentStr); 1222 indent++; 1223 1224 String16 attr16("attr"); 1225 String16 package16(assets->getPackage()); 1226 1227 indentStr = getIndentSpace(indent); 1228 bool hasErrors = false; 1229 1230 size_t i; 1231 size_t N = symbols->getNestedSymbols().size(); 1232 for (i=0; i<N; i++) { 1233 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i); 1234 String16 nclassName16(symbols->getNestedSymbols().keyAt(i)); 1235 String8 realClassName(nclassName16); 1236 if (fixupSymbol(&nclassName16) != NO_ERROR) { 1237 hasErrors = true; 1238 } 1239 String8 nclassName(nclassName16); 1240 1241 SortedVector<uint32_t> idents; 1242 Vector<uint32_t> origOrder; 1243 Vector<bool> publicFlags; 1244 1245 size_t a; 1246 size_t NA = nsymbols->getSymbols().size(); 1247 for (a=0; a<NA; a++) { 1248 const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a)); 1249 int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32 1250 ? sym.int32Val : 0; 1251 bool isPublic = true; 1252 if (code == 0) { 1253 String16 name16(sym.name); 1254 uint32_t typeSpecFlags; 1255 code = assets->getIncludedResources().identifierForName( 1256 name16.string(), name16.size(), 1257 attr16.string(), attr16.size(), 1258 package16.string(), package16.size(), &typeSpecFlags); 1259 if (code == 0) { 1260 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n", 1261 nclassName.string(), sym.name.string()); 1262 hasErrors = true; 1263 } 1264 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0; 1265 } 1266 idents.add(code); 1267 origOrder.add(code); 1268 publicFlags.add(isPublic); 1269 } 1270 1271 NA = idents.size(); 1272 1273 bool deprecated = false; 1274 1275 String16 comment = symbols->getComment(realClassName); 1276 fprintf(fp, "%s/** ", indentStr); 1277 if (comment.size() > 0) { 1278 String8 cmt(comment); 1279 fprintf(fp, "%s\n", cmt.string()); 1280 if (strstr(cmt.string(), "@deprecated") != NULL) { 1281 deprecated = true; 1282 } 1283 } else { 1284 fprintf(fp, "Attributes that can be used with a %s.\n", nclassName.string()); 1285 } 1286 bool hasTable = false; 1287 for (a=0; a<NA; a++) { 1288 ssize_t pos = idents.indexOf(origOrder.itemAt(a)); 1289 if (pos >= 0) { 1290 if (!hasTable) { 1291 hasTable = true; 1292 fprintf(fp, 1293 "%s <p>Includes the following attributes:</p>\n" 1294 "%s <table>\n" 1295 "%s <colgroup align=\"left\" />\n" 1296 "%s <colgroup align=\"left\" />\n" 1297 "%s <tr><th>Attribute</th><th>Description</th></tr>\n", 1298 indentStr, 1299 indentStr, 1300 indentStr, 1301 indentStr, 1302 indentStr); 1303 } 1304 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a); 1305 if (!publicFlags.itemAt(a) && !includePrivate) { 1306 continue; 1307 } 1308 String8 name8(sym.name); 1309 String16 comment(sym.comment); 1310 if (comment.size() <= 0) { 1311 comment = getAttributeComment(assets, name8); 1312 } 1313 if (comment.size() > 0) { 1314 const char16_t* p = comment.string(); 1315 while (*p != 0 && *p != '.') { 1316 if (*p == '{') { 1317 while (*p != 0 && *p != '}') { 1318 p++; 1319 } 1320 } else { 1321 p++; 1322 } 1323 } 1324 if (*p == '.') { 1325 p++; 1326 } 1327 comment = String16(comment.string(), p-comment.string()); 1328 } 1329 String16 name(name8); 1330 fixupSymbol(&name); 1331 fprintf(fp, "%s <tr><td><code>{@link #%s_%s %s:%s}</code></td><td>%s</td></tr>\n", 1332 indentStr, nclassName.string(), 1333 String8(name).string(), 1334 assets->getPackage().string(), 1335 String8(name).string(), 1336 String8(comment).string()); 1337 } 1338 } 1339 if (hasTable) { 1340 fprintf(fp, "%s </table>\n", indentStr); 1341 } 1342 for (a=0; a<NA; a++) { 1343 ssize_t pos = idents.indexOf(origOrder.itemAt(a)); 1344 if (pos >= 0) { 1345 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a); 1346 if (!publicFlags.itemAt(a) && !includePrivate) { 1347 continue; 1348 } 1349 String16 name(sym.name); 1350 fixupSymbol(&name); 1351 fprintf(fp, "%s @see #%s_%s\n", 1352 indentStr, nclassName.string(), 1353 String8(name).string()); 1354 } 1355 } 1356 fprintf(fp, "%s */\n", getIndentSpace(indent)); 1357 1358 if (deprecated) { 1359 fprintf(fp, "%s@Deprecated\n", indentStr); 1360 } 1361 1362 fprintf(fp, 1363 "%spublic static final int[] %s = {\n" 1364 "%s", 1365 indentStr, nclassName.string(), 1366 getIndentSpace(indent+1)); 1367 1368 for (a=0; a<NA; a++) { 1369 if (a != 0) { 1370 if ((a&3) == 0) { 1371 fprintf(fp, ",\n%s", getIndentSpace(indent+1)); 1372 } else { 1373 fprintf(fp, ", "); 1374 } 1375 } 1376 fprintf(fp, "0x%08x", idents[a]); 1377 } 1378 1379 fprintf(fp, "\n%s};\n", indentStr); 1380 1381 for (a=0; a<NA; a++) { 1382 ssize_t pos = idents.indexOf(origOrder.itemAt(a)); 1383 if (pos >= 0) { 1384 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a); 1385 if (!publicFlags.itemAt(a) && !includePrivate) { 1386 continue; 1387 } 1388 String8 name8(sym.name); 1389 String16 comment(sym.comment); 1390 String16 typeComment; 1391 if (comment.size() <= 0) { 1392 comment = getAttributeComment(assets, name8, &typeComment); 1393 } else { 1394 getAttributeComment(assets, name8, &typeComment); 1395 } 1396 String16 name(name8); 1397 if (fixupSymbol(&name) != NO_ERROR) { 1398 hasErrors = true; 1399 } 1400 1401 uint32_t typeSpecFlags = 0; 1402 String16 name16(sym.name); 1403 assets->getIncludedResources().identifierForName( 1404 name16.string(), name16.size(), 1405 attr16.string(), attr16.size(), 1406 package16.string(), package16.size(), &typeSpecFlags); 1407 //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(), 1408 // String8(attr16).string(), String8(name16).string(), typeSpecFlags); 1409 const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0; 1410 1411 bool deprecated = false; 1412 1413 fprintf(fp, "%s/**\n", indentStr); 1414 if (comment.size() > 0) { 1415 String8 cmt(comment); 1416 fprintf(fp, "%s <p>\n%s @attr description\n", indentStr, indentStr); 1417 fprintf(fp, "%s %s\n", indentStr, cmt.string()); 1418 if (strstr(cmt.string(), "@deprecated") != NULL) { 1419 deprecated = true; 1420 } 1421 } else { 1422 fprintf(fp, 1423 "%s <p>This symbol is the offset where the {@link %s.R.attr#%s}\n" 1424 "%s attribute's value can be found in the {@link #%s} array.\n", 1425 indentStr, 1426 pub ? assets->getPackage().string() 1427 : assets->getSymbolsPrivatePackage().string(), 1428 String8(name).string(), 1429 indentStr, nclassName.string()); 1430 } 1431 if (typeComment.size() > 0) { 1432 String8 cmt(typeComment); 1433 fprintf(fp, "\n\n%s %s\n", indentStr, cmt.string()); 1434 if (strstr(cmt.string(), "@deprecated") != NULL) { 1435 deprecated = true; 1436 } 1437 } 1438 if (comment.size() > 0) { 1439 if (pub) { 1440 fprintf(fp, 1441 "%s <p>This corresponds to the global attribute" 1442 "%s resource symbol {@link %s.R.attr#%s}.\n", 1443 indentStr, indentStr, 1444 assets->getPackage().string(), 1445 String8(name).string()); 1446 } else { 1447 fprintf(fp, 1448 "%s <p>This is a private symbol.\n", indentStr); 1449 } 1450 } 1451 fprintf(fp, "%s @attr name %s:%s\n", indentStr, 1452 "android", String8(name).string()); 1453 fprintf(fp, "%s*/\n", indentStr); 1454 if (deprecated) { 1455 fprintf(fp, "%s@Deprecated\n", indentStr); 1456 } 1457 fprintf(fp, 1458 "%spublic static final int %s_%s = %d;\n", 1459 indentStr, nclassName.string(), 1460 String8(name).string(), (int)pos); 1461 } 1462 } 1463 } 1464 1465 indent--; 1466 fprintf(fp, "%s};\n", getIndentSpace(indent)); 1467 return hasErrors ? UNKNOWN_ERROR : NO_ERROR; 1468} 1469 1470static status_t writeSymbolClass( 1471 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate, 1472 const sp<AaptSymbols>& symbols, const String8& className, int indent) 1473{ 1474 fprintf(fp, "%spublic %sfinal class %s {\n", 1475 getIndentSpace(indent), 1476 indent != 0 ? "static " : "", className.string()); 1477 indent++; 1478 1479 size_t i; 1480 status_t err = NO_ERROR; 1481 1482 size_t N = symbols->getSymbols().size(); 1483 for (i=0; i<N; i++) { 1484 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i); 1485 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) { 1486 continue; 1487 } 1488 if (!includePrivate && !sym.isPublic) { 1489 continue; 1490 } 1491 String16 name(sym.name); 1492 String8 realName(name); 1493 if (fixupSymbol(&name) != NO_ERROR) { 1494 return UNKNOWN_ERROR; 1495 } 1496 String16 comment(sym.comment); 1497 bool haveComment = false; 1498 bool deprecated = false; 1499 if (comment.size() > 0) { 1500 haveComment = true; 1501 String8 cmt(comment); 1502 fprintf(fp, 1503 "%s/** %s\n", 1504 getIndentSpace(indent), cmt.string()); 1505 if (strstr(cmt.string(), "@deprecated") != NULL) { 1506 deprecated = true; 1507 } 1508 } else if (sym.isPublic && !includePrivate) { 1509 sym.sourcePos.warning("No comment for public symbol %s:%s/%s", 1510 assets->getPackage().string(), className.string(), 1511 String8(sym.name).string()); 1512 } 1513 String16 typeComment(sym.typeComment); 1514 if (typeComment.size() > 0) { 1515 String8 cmt(typeComment); 1516 if (!haveComment) { 1517 haveComment = true; 1518 fprintf(fp, 1519 "%s/** %s\n", getIndentSpace(indent), cmt.string()); 1520 } else { 1521 fprintf(fp, 1522 "%s %s\n", getIndentSpace(indent), cmt.string()); 1523 } 1524 if (strstr(cmt.string(), "@deprecated") != NULL) { 1525 deprecated = true; 1526 } 1527 } 1528 if (haveComment) { 1529 fprintf(fp,"%s */\n", getIndentSpace(indent)); 1530 } 1531 if (deprecated) { 1532 fprintf(fp, "%s@Deprecated\n", getIndentSpace(indent)); 1533 } 1534 fprintf(fp, "%spublic static final int %s=0x%08x;\n", 1535 getIndentSpace(indent), 1536 String8(name).string(), (int)sym.int32Val); 1537 } 1538 1539 for (i=0; i<N; i++) { 1540 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i); 1541 if (sym.typeCode != AaptSymbolEntry::TYPE_STRING) { 1542 continue; 1543 } 1544 if (!includePrivate && !sym.isPublic) { 1545 continue; 1546 } 1547 String16 name(sym.name); 1548 if (fixupSymbol(&name) != NO_ERROR) { 1549 return UNKNOWN_ERROR; 1550 } 1551 String16 comment(sym.comment); 1552 bool deprecated = false; 1553 if (comment.size() > 0) { 1554 String8 cmt(comment); 1555 fprintf(fp, 1556 "%s/** %s\n" 1557 "%s */\n", 1558 getIndentSpace(indent), cmt.string(), 1559 getIndentSpace(indent)); 1560 if (strstr(cmt.string(), "@deprecated") != NULL) { 1561 deprecated = true; 1562 } 1563 } else if (sym.isPublic && !includePrivate) { 1564 sym.sourcePos.warning("No comment for public symbol %s:%s/%s", 1565 assets->getPackage().string(), className.string(), 1566 String8(sym.name).string()); 1567 } 1568 if (deprecated) { 1569 fprintf(fp, "%s@Deprecated\n", getIndentSpace(indent)); 1570 } 1571 fprintf(fp, "%spublic static final String %s=\"%s\";\n", 1572 getIndentSpace(indent), 1573 String8(name).string(), sym.stringVal.string()); 1574 } 1575 1576 sp<AaptSymbols> styleableSymbols; 1577 1578 N = symbols->getNestedSymbols().size(); 1579 for (i=0; i<N; i++) { 1580 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i); 1581 String8 nclassName(symbols->getNestedSymbols().keyAt(i)); 1582 if (nclassName == "styleable") { 1583 styleableSymbols = nsymbols; 1584 } else { 1585 err = writeSymbolClass(fp, assets, includePrivate, nsymbols, nclassName, indent); 1586 } 1587 if (err != NO_ERROR) { 1588 return err; 1589 } 1590 } 1591 1592 if (styleableSymbols != NULL) { 1593 err = writeLayoutClasses(fp, assets, styleableSymbols, indent, includePrivate); 1594 if (err != NO_ERROR) { 1595 return err; 1596 } 1597 } 1598 1599 indent--; 1600 fprintf(fp, "%s}\n", getIndentSpace(indent)); 1601 return NO_ERROR; 1602} 1603 1604status_t writeResourceSymbols(Bundle* bundle, const sp<AaptAssets>& assets, 1605 const String8& package, bool includePrivate) 1606{ 1607 if (!bundle->getRClassDir()) { 1608 return NO_ERROR; 1609 } 1610 1611 const size_t N = assets->getSymbols().size(); 1612 for (size_t i=0; i<N; i++) { 1613 sp<AaptSymbols> symbols = assets->getSymbols().valueAt(i); 1614 String8 className(assets->getSymbols().keyAt(i)); 1615 String8 dest(bundle->getRClassDir()); 1616 if (bundle->getMakePackageDirs()) { 1617 String8 pkg(package); 1618 const char* last = pkg.string(); 1619 const char* s = last-1; 1620 do { 1621 s++; 1622 if (s > last && (*s == '.' || *s == 0)) { 1623 String8 part(last, s-last); 1624 dest.appendPath(part); 1625#ifdef HAVE_MS_C_RUNTIME 1626 _mkdir(dest.string()); 1627#else 1628 mkdir(dest.string(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP); 1629#endif 1630 last = s+1; 1631 } 1632 } while (*s); 1633 } 1634 dest.appendPath(className); 1635 dest.append(".java"); 1636 FILE* fp = fopen(dest.string(), "w+"); 1637 if (fp == NULL) { 1638 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n", 1639 dest.string(), strerror(errno)); 1640 return UNKNOWN_ERROR; 1641 } 1642 if (bundle->getVerbose()) { 1643 printf(" Writing symbols for class %s.\n", className.string()); 1644 } 1645 1646 fprintf(fp, 1647 "/* AUTO-GENERATED FILE. DO NOT MODIFY.\n" 1648 " *\n" 1649 " * This class was automatically generated by the\n" 1650 " * aapt tool from the resource data it found. It\n" 1651 " * should not be modified by hand.\n" 1652 " */\n" 1653 "\n" 1654 "package %s;\n\n", package.string()); 1655 1656 status_t err = writeSymbolClass(fp, assets, includePrivate, symbols, className, 0); 1657 if (err != NO_ERROR) { 1658 return err; 1659 } 1660 fclose(fp); 1661 } 1662 1663 return NO_ERROR; 1664} 1665 1666 1667 1668class ProguardKeepSet 1669{ 1670public: 1671 // { rule --> { file locations } } 1672 KeyedVector<String8, SortedVector<String8> > rules; 1673 1674 void add(const String8& rule, const String8& where); 1675}; 1676 1677void ProguardKeepSet::add(const String8& rule, const String8& where) 1678{ 1679 ssize_t index = rules.indexOfKey(rule); 1680 if (index < 0) { 1681 index = rules.add(rule, SortedVector<String8>()); 1682 } 1683 rules.editValueAt(index).add(where); 1684} 1685 1686status_t 1687writeProguardForAndroidManifest(ProguardKeepSet* keep, const sp<AaptAssets>& assets) 1688{ 1689 status_t err; 1690 ResXMLTree tree; 1691 size_t len; 1692 ResXMLTree::event_code_t code; 1693 int depth = 0; 1694 bool inApplication = false; 1695 String8 error; 1696 sp<AaptGroup> assGroup; 1697 sp<AaptFile> assFile; 1698 String8 pkg; 1699 1700 // First, look for a package file to parse. This is required to 1701 // be able to generate the resource information. 1702 assGroup = assets->getFiles().valueFor(String8("AndroidManifest.xml")); 1703 if (assGroup == NULL) { 1704 fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n"); 1705 return -1; 1706 } 1707 1708 if (assGroup->getFiles().size() != 1) { 1709 fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n", 1710 assGroup->getFiles().valueAt(0)->getPrintableSource().string()); 1711 } 1712 1713 assFile = assGroup->getFiles().valueAt(0); 1714 1715 err = parseXMLResource(assFile, &tree); 1716 if (err != NO_ERROR) { 1717 return err; 1718 } 1719 1720 tree.restart(); 1721 1722 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) { 1723 if (code == ResXMLTree::END_TAG) { 1724 if (/* name == "Application" && */ depth == 2) { 1725 inApplication = false; 1726 } 1727 depth--; 1728 continue; 1729 } 1730 if (code != ResXMLTree::START_TAG) { 1731 continue; 1732 } 1733 depth++; 1734 String8 tag(tree.getElementName(&len)); 1735 // printf("Depth %d tag %s\n", depth, tag.string()); 1736 if (depth == 1) { 1737 if (tag != "manifest") { 1738 fprintf(stderr, "ERROR: manifest does not start with <manifest> tag\n"); 1739 return -1; 1740 } 1741 pkg = getAttribute(tree, NULL, "package", NULL); 1742 } else if (depth == 2 && tag == "application") { 1743 inApplication = true; 1744 } 1745 if (inApplication) { 1746 if (tag == "application" || tag == "activity" || tag == "service" || tag == "receiver" 1747 || tag == "provider") { 1748 String8 name = getAttribute(tree, "http://schemas.android.com/apk/res/android", 1749 "name", &error); 1750 if (error != "") { 1751 fprintf(stderr, "ERROR: %s\n", error.string()); 1752 return -1; 1753 } 1754 // asdf --> package.asdf 1755 // .asdf .a.b --> package.asdf package.a.b 1756 // asdf.adsf --> asdf.asdf 1757 String8 rule("-keep class "); 1758 const char* p = name.string(); 1759 const char* q = strchr(p, '.'); 1760 if (p == q) { 1761 rule += pkg; 1762 rule += name; 1763 } else if (q == NULL) { 1764 rule += pkg; 1765 rule += "."; 1766 rule += name; 1767 } else { 1768 rule += name; 1769 } 1770 1771 String8 location = tag; 1772 location += " "; 1773 location += assFile->getSourceFile(); 1774 char lineno[20]; 1775 sprintf(lineno, ":%d", tree.getLineNumber()); 1776 location += lineno; 1777 1778 keep->add(rule, location); 1779 } 1780 } 1781 } 1782 1783 return NO_ERROR; 1784} 1785 1786status_t 1787writeProguardForLayout(ProguardKeepSet* keep, const sp<AaptFile>& layoutFile) 1788{ 1789 status_t err; 1790 ResXMLTree tree; 1791 size_t len; 1792 ResXMLTree::event_code_t code; 1793 1794 err = parseXMLResource(layoutFile, &tree); 1795 if (err != NO_ERROR) { 1796 return err; 1797 } 1798 1799 tree.restart(); 1800 1801 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) { 1802 if (code != ResXMLTree::START_TAG) { 1803 continue; 1804 } 1805 String8 tag(tree.getElementName(&len)); 1806 1807 // If there is no '.', we'll assume that it's one of the built in names. 1808 if (strchr(tag.string(), '.')) { 1809 String8 rule("-keep class "); 1810 rule += tag; 1811 rule += " { <init>(...); }"; 1812 1813 String8 location("view "); 1814 location += layoutFile->getSourceFile(); 1815 char lineno[20]; 1816 sprintf(lineno, ":%d", tree.getLineNumber()); 1817 location += lineno; 1818 1819 keep->add(rule, location); 1820 } 1821 } 1822 1823 return NO_ERROR; 1824} 1825 1826status_t 1827writeProguardForLayouts(ProguardKeepSet* keep, const sp<AaptAssets>& assets) 1828{ 1829 status_t err; 1830 sp<AaptDir> layout = assets->resDir(String8("layout")); 1831 1832 if (layout != NULL) { 1833 const KeyedVector<String8,sp<AaptGroup> > groups = layout->getFiles(); 1834 const size_t N = groups.size(); 1835 for (size_t i=0; i<N; i++) { 1836 const sp<AaptGroup>& group = groups.valueAt(i); 1837 const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files = group->getFiles(); 1838 const size_t M = files.size(); 1839 for (size_t j=0; j<M; j++) { 1840 err = writeProguardForLayout(keep, files.valueAt(j)); 1841 if (err < 0) { 1842 return err; 1843 } 1844 } 1845 } 1846 } 1847 return NO_ERROR; 1848} 1849 1850status_t 1851writeProguardFile(Bundle* bundle, const sp<AaptAssets>& assets) 1852{ 1853 status_t err = -1; 1854 1855 if (!bundle->getProguardFile()) { 1856 return NO_ERROR; 1857 } 1858 1859 ProguardKeepSet keep; 1860 1861 err = writeProguardForAndroidManifest(&keep, assets); 1862 if (err < 0) { 1863 return err; 1864 } 1865 1866 err = writeProguardForLayouts(&keep, assets); 1867 if (err < 0) { 1868 return err; 1869 } 1870 1871 FILE* fp = fopen(bundle->getProguardFile(), "w+"); 1872 if (fp == NULL) { 1873 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n", 1874 bundle->getProguardFile(), strerror(errno)); 1875 return UNKNOWN_ERROR; 1876 } 1877 1878 const KeyedVector<String8, SortedVector<String8> >& rules = keep.rules; 1879 const size_t N = rules.size(); 1880 for (size_t i=0; i<N; i++) { 1881 const SortedVector<String8>& locations = rules.valueAt(i); 1882 const size_t M = locations.size(); 1883 for (size_t j=0; j<M; j++) { 1884 fprintf(fp, "# %s\n", locations.itemAt(j).string()); 1885 } 1886 fprintf(fp, "%s\n\n", rules.keyAt(i).string()); 1887 } 1888 fclose(fp); 1889 1890 return err; 1891} 1892