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