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