Resource.cpp revision eb490d6194bd79adbe144a1230fc126f4c180a2f
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                size_t baseIndex = UNKNOWN_ERROR;
593                if (baseSet->get() != NULL) {
594                    baseIndex = (*baseSet)->indexOfKey(overlaySet->keyAt(overlayIndex));
595                }
596                if (baseIndex < UNKNOWN_ERROR) {
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                        size_t baseFileIndex =
623                                baseGroup->getFiles().indexOfKey(overlayFiles.
624                                keyAt(overlayGroupIndex));
625                        if (baseFileIndex < UNKNOWN_ERROR) {
626                            if (bundle->getVerbose()) {
627                                printf("found a match (" ZD ") for overlay file %s, for flavor %s\n",
628                                        (ZD_TYPE) baseFileIndex,
629                                        overlayGroup->getLeaf().string(),
630                                        overlayFiles.keyAt(overlayGroupIndex).toString().string());
631                            }
632                            baseGroup->removeFile(baseFileIndex);
633                        } else {
634                            // didn't find a match fall through and add it..
635                            if (true || bundle->getVerbose()) {
636                                printf("nothing matches overlay file %s, for flavor %s\n",
637                                        overlayGroup->getLeaf().string(),
638                                        overlayFiles.keyAt(overlayGroupIndex).toString().string());
639                            }
640                        }
641                        baseGroup->addFile(overlayFiles.valueAt(overlayGroupIndex));
642                        assets->addGroupEntry(overlayFiles.keyAt(overlayGroupIndex));
643                    }
644                } else {
645                    if (baseSet->get() == NULL) {
646                        *baseSet = new ResourceTypeSet();
647                        assets->getResources()->add(String8(resType), *baseSet);
648                    }
649                    // this group doesn't exist (a file that's only in the overlay)
650                    (*baseSet)->add(overlaySet->keyAt(overlayIndex),
651                            overlaySet->valueAt(overlayIndex));
652                    // make sure all flavors are defined in the resources.
653                    sp<AaptGroup> overlayGroup = overlaySet->valueAt(overlayIndex);
654                    DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > overlayFiles =
655                            overlayGroup->getFiles();
656                    size_t overlayGroupSize = overlayFiles.size();
657                    for (size_t overlayGroupIndex = 0;
658                            overlayGroupIndex<overlayGroupSize;
659                            overlayGroupIndex++) {
660                        assets->addGroupEntry(overlayFiles.keyAt(overlayGroupIndex));
661                    }
662                }
663            }
664            // this overlay didn't have resources for this type
665        }
666        // try next overlay
667        overlay = overlay->getOverlay();
668    }
669    return true;
670}
671
672/*
673 * Inserts an attribute in a given node.
674 * If errorOnFailedInsert is true, and the attribute already exists, returns false.
675 * If replaceExisting is true, the attribute will be updated if it already exists.
676 * Returns true otherwise, even if the attribute already exists, and does not modify
677 * the existing attribute's value.
678 */
679bool addTagAttribute(const sp<XMLNode>& node, const char* ns8,
680        const char* attr8, const char* value, bool errorOnFailedInsert,
681        bool replaceExisting)
682{
683    if (value == NULL) {
684        return true;
685    }
686
687    const String16 ns(ns8);
688    const String16 attr(attr8);
689
690    XMLNode::attribute_entry* existingEntry = node->editAttribute(ns, attr);
691    if (existingEntry != NULL) {
692        if (replaceExisting) {
693            NOISY(printf("Info: AndroidManifest.xml already defines %s (in %s);"
694                         " overwriting existing value from manifest.\n",
695                         String8(attr).string(), String8(ns).string()));
696            existingEntry->string = String16(value);
697            return true;
698        }
699
700        if (errorOnFailedInsert) {
701            fprintf(stderr, "Error: AndroidManifest.xml already defines %s (in %s);"
702                            " cannot insert new value %s.\n",
703                    String8(attr).string(), String8(ns).string(), value);
704            return false;
705        }
706
707        fprintf(stderr, "Warning: AndroidManifest.xml already defines %s (in %s);"
708                        " using existing value in manifest.\n",
709                String8(attr).string(), String8(ns).string());
710
711        // don't stop the build.
712        return true;
713    }
714
715    node->addAttribute(ns, attr, String16(value));
716    return true;
717}
718
719/*
720 * Inserts an attribute in a given node, only if the attribute does not
721 * exist.
722 * If errorOnFailedInsert is true, and the attribute already exists, returns false.
723 * Returns true otherwise, even if the attribute already exists.
724 */
725bool addTagAttribute(const sp<XMLNode>& node, const char* ns8,
726        const char* attr8, const char* value, bool errorOnFailedInsert)
727{
728    return addTagAttribute(node, ns8, attr8, value, errorOnFailedInsert, false);
729}
730
731static void fullyQualifyClassName(const String8& package, sp<XMLNode> node,
732        const String16& attrName) {
733    XMLNode::attribute_entry* attr = node->editAttribute(
734            String16("http://schemas.android.com/apk/res/android"), attrName);
735    if (attr != NULL) {
736        String8 name(attr->string);
737
738        // asdf     --> package.asdf
739        // .asdf  .a.b  --> package.asdf package.a.b
740        // asdf.adsf --> asdf.asdf
741        String8 className;
742        const char* p = name.string();
743        const char* q = strchr(p, '.');
744        if (p == q) {
745            className += package;
746            className += name;
747        } else if (q == NULL) {
748            className += package;
749            className += ".";
750            className += name;
751        } else {
752            className += name;
753        }
754        NOISY(printf("Qualifying class '%s' to '%s'", name.string(), className.string()));
755        attr->string.setTo(String16(className));
756    }
757}
758
759status_t massageManifest(Bundle* bundle, sp<XMLNode> root)
760{
761    root = root->searchElement(String16(), String16("manifest"));
762    if (root == NULL) {
763        fprintf(stderr, "No <manifest> tag.\n");
764        return UNKNOWN_ERROR;
765    }
766
767    bool errorOnFailedInsert = bundle->getErrorOnFailedInsert();
768    bool replaceVersion = bundle->getReplaceVersion();
769
770    if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionCode",
771            bundle->getVersionCode(), errorOnFailedInsert, replaceVersion)) {
772        return UNKNOWN_ERROR;
773    }
774    if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionName",
775            bundle->getVersionName(), errorOnFailedInsert, replaceVersion)) {
776        return UNKNOWN_ERROR;
777    }
778
779    if (bundle->getMinSdkVersion() != NULL
780            || bundle->getTargetSdkVersion() != NULL
781            || bundle->getMaxSdkVersion() != NULL) {
782        sp<XMLNode> vers = root->getChildElement(String16(), String16("uses-sdk"));
783        if (vers == NULL) {
784            vers = XMLNode::newElement(root->getFilename(), String16(), String16("uses-sdk"));
785            root->insertChildAt(vers, 0);
786        }
787
788        if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "minSdkVersion",
789                bundle->getMinSdkVersion(), errorOnFailedInsert)) {
790            return UNKNOWN_ERROR;
791        }
792        if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "targetSdkVersion",
793                bundle->getTargetSdkVersion(), errorOnFailedInsert)) {
794            return UNKNOWN_ERROR;
795        }
796        if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "maxSdkVersion",
797                bundle->getMaxSdkVersion(), errorOnFailedInsert)) {
798            return UNKNOWN_ERROR;
799        }
800    }
801
802    if (bundle->getDebugMode()) {
803        sp<XMLNode> application = root->getChildElement(String16(), String16("application"));
804        if (application != NULL) {
805            if (!addTagAttribute(application, RESOURCES_ANDROID_NAMESPACE, "debuggable", "true",
806                    errorOnFailedInsert)) {
807                return UNKNOWN_ERROR;
808            }
809        }
810    }
811
812    // Deal with manifest package name overrides
813    const char* manifestPackageNameOverride = bundle->getManifestPackageNameOverride();
814    if (manifestPackageNameOverride != NULL) {
815        // Update the actual package name
816        XMLNode::attribute_entry* attr = root->editAttribute(String16(), String16("package"));
817        if (attr == NULL) {
818            fprintf(stderr, "package name is required with --rename-manifest-package.\n");
819            return UNKNOWN_ERROR;
820        }
821        String8 origPackage(attr->string);
822        attr->string.setTo(String16(manifestPackageNameOverride));
823        NOISY(printf("Overriding package '%s' to be '%s'\n", origPackage.string(), manifestPackageNameOverride));
824
825        // Make class names fully qualified
826        sp<XMLNode> application = root->getChildElement(String16(), String16("application"));
827        if (application != NULL) {
828            fullyQualifyClassName(origPackage, application, String16("name"));
829            fullyQualifyClassName(origPackage, application, String16("backupAgent"));
830
831            Vector<sp<XMLNode> >& children = const_cast<Vector<sp<XMLNode> >&>(application->getChildren());
832            for (size_t i = 0; i < children.size(); i++) {
833                sp<XMLNode> child = children.editItemAt(i);
834                String8 tag(child->getElementName());
835                if (tag == "activity" || tag == "service" || tag == "receiver" || tag == "provider") {
836                    fullyQualifyClassName(origPackage, child, String16("name"));
837                } else if (tag == "activity-alias") {
838                    fullyQualifyClassName(origPackage, child, String16("name"));
839                    fullyQualifyClassName(origPackage, child, String16("targetActivity"));
840                }
841            }
842        }
843    }
844
845    // Deal with manifest package name overrides
846    const char* instrumentationPackageNameOverride = bundle->getInstrumentationPackageNameOverride();
847    if (instrumentationPackageNameOverride != NULL) {
848        // Fix up instrumentation targets.
849        Vector<sp<XMLNode> >& children = const_cast<Vector<sp<XMLNode> >&>(root->getChildren());
850        for (size_t i = 0; i < children.size(); i++) {
851            sp<XMLNode> child = children.editItemAt(i);
852            String8 tag(child->getElementName());
853            if (tag == "instrumentation") {
854                XMLNode::attribute_entry* attr = child->editAttribute(
855                        String16("http://schemas.android.com/apk/res/android"), String16("targetPackage"));
856                if (attr != NULL) {
857                    attr->string.setTo(String16(instrumentationPackageNameOverride));
858                }
859            }
860        }
861    }
862
863    return NO_ERROR;
864}
865
866#define ASSIGN_IT(n) \
867        do { \
868            ssize_t index = resources->indexOfKey(String8(#n)); \
869            if (index >= 0) { \
870                n ## s = resources->valueAt(index); \
871            } \
872        } while (0)
873
874status_t updatePreProcessedCache(Bundle* bundle)
875{
876    #if BENCHMARK
877    fprintf(stdout, "BENCHMARK: Starting PNG PreProcessing \n");
878    long startPNGTime = clock();
879    #endif /* BENCHMARK */
880
881    String8 source(bundle->getResourceSourceDirs()[0]);
882    String8 dest(bundle->getCrunchedOutputDir());
883
884    FileFinder* ff = new SystemFileFinder();
885    CrunchCache cc(source,dest,ff);
886
887    CacheUpdater* cu = new SystemCacheUpdater(bundle);
888    size_t numFiles = cc.crunch(cu);
889
890    if (bundle->getVerbose())
891        fprintf(stdout, "Crunched %d PNG files to update cache\n", (int)numFiles);
892
893    delete ff;
894    delete cu;
895
896    #if BENCHMARK
897    fprintf(stdout, "BENCHMARK: End PNG PreProcessing. Time Elapsed: %f ms \n"
898            ,(clock() - startPNGTime)/1000.0);
899    #endif /* BENCHMARK */
900    return 0;
901}
902
903status_t generateAndroidManifestForSplit(const String16& package, const sp<ApkSplit>& split,
904        sp<AaptFile>& outFile) {
905    const String8 filename("AndroidManifest.xml");
906    const String16 androidPrefix("android");
907    const String16 androidNSUri("http://schemas.android.com/apk/res/android");
908    sp<XMLNode> root = XMLNode::newNamespace(filename, androidPrefix, androidNSUri);
909
910    // Build the <manifest> tag
911    sp<XMLNode> manifest = XMLNode::newElement(filename, String16(), String16("manifest"));
912
913    // Add the 'package' attribute which is set to the original package name.
914    manifest->addAttribute(String16(), String16("package"), package);
915
916    // Add the 'split' attribute which describes the configurations included.
917    String8 splitName("config_");
918    splitName.append(split->getDirectorySafeName());
919    manifest->addAttribute(String16(), String16("split"), String16(splitName));
920
921    // Build an empty <application> tag (required).
922    sp<XMLNode> app = XMLNode::newElement(filename, String16(), String16("application"));
923    manifest->addChild(app);
924    root->addChild(manifest);
925
926    status_t err = root->flatten(outFile, true, true);
927    if (err != NO_ERROR) {
928        return err;
929    }
930    outFile->setCompressionMethod(ZipEntry::kCompressDeflated);
931    return NO_ERROR;
932}
933
934status_t buildResources(Bundle* bundle, const sp<AaptAssets>& assets, sp<ApkBuilder>& builder)
935{
936    // First, look for a package file to parse.  This is required to
937    // be able to generate the resource information.
938    sp<AaptGroup> androidManifestFile =
939            assets->getFiles().valueFor(String8("AndroidManifest.xml"));
940    if (androidManifestFile == NULL) {
941        fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n");
942        return UNKNOWN_ERROR;
943    }
944
945    status_t err = parsePackage(bundle, assets, androidManifestFile);
946    if (err != NO_ERROR) {
947        return err;
948    }
949
950    NOISY(printf("Creating resources for package %s\n",
951                 assets->getPackage().string()));
952
953    ResourceTable table(bundle, String16(assets->getPackage()));
954    err = table.addIncludedResources(bundle, assets);
955    if (err != NO_ERROR) {
956        return err;
957    }
958
959    NOISY(printf("Found %d included resource packages\n", (int)table.size()));
960
961    // Standard flags for compiled XML and optional UTF-8 encoding
962    int xmlFlags = XML_COMPILE_STANDARD_RESOURCE;
963
964    /* Only enable UTF-8 if the caller of aapt didn't specifically
965     * request UTF-16 encoding and the parameters of this package
966     * allow UTF-8 to be used.
967     */
968    if (!bundle->getUTF16StringsOption()) {
969        xmlFlags |= XML_COMPILE_UTF8;
970    }
971
972    // --------------------------------------------------------------
973    // First, gather all resource information.
974    // --------------------------------------------------------------
975
976    // resType -> leafName -> group
977    KeyedVector<String8, sp<ResourceTypeSet> > *resources =
978            new KeyedVector<String8, sp<ResourceTypeSet> >;
979    collect_files(assets, resources);
980
981    sp<ResourceTypeSet> drawables;
982    sp<ResourceTypeSet> layouts;
983    sp<ResourceTypeSet> anims;
984    sp<ResourceTypeSet> animators;
985    sp<ResourceTypeSet> interpolators;
986    sp<ResourceTypeSet> transitions;
987    sp<ResourceTypeSet> xmls;
988    sp<ResourceTypeSet> raws;
989    sp<ResourceTypeSet> colors;
990    sp<ResourceTypeSet> menus;
991    sp<ResourceTypeSet> mipmaps;
992
993    ASSIGN_IT(drawable);
994    ASSIGN_IT(layout);
995    ASSIGN_IT(anim);
996    ASSIGN_IT(animator);
997    ASSIGN_IT(interpolator);
998    ASSIGN_IT(transition);
999    ASSIGN_IT(xml);
1000    ASSIGN_IT(raw);
1001    ASSIGN_IT(color);
1002    ASSIGN_IT(menu);
1003    ASSIGN_IT(mipmap);
1004
1005    assets->setResources(resources);
1006    // now go through any resource overlays and collect their files
1007    sp<AaptAssets> current = assets->getOverlay();
1008    while(current.get()) {
1009        KeyedVector<String8, sp<ResourceTypeSet> > *resources =
1010                new KeyedVector<String8, sp<ResourceTypeSet> >;
1011        current->setResources(resources);
1012        collect_files(current, resources);
1013        current = current->getOverlay();
1014    }
1015    // apply the overlay files to the base set
1016    if (!applyFileOverlay(bundle, assets, &drawables, "drawable") ||
1017            !applyFileOverlay(bundle, assets, &layouts, "layout") ||
1018            !applyFileOverlay(bundle, assets, &anims, "anim") ||
1019            !applyFileOverlay(bundle, assets, &animators, "animator") ||
1020            !applyFileOverlay(bundle, assets, &interpolators, "interpolator") ||
1021            !applyFileOverlay(bundle, assets, &transitions, "transition") ||
1022            !applyFileOverlay(bundle, assets, &xmls, "xml") ||
1023            !applyFileOverlay(bundle, assets, &raws, "raw") ||
1024            !applyFileOverlay(bundle, assets, &colors, "color") ||
1025            !applyFileOverlay(bundle, assets, &menus, "menu") ||
1026            !applyFileOverlay(bundle, assets, &mipmaps, "mipmap")) {
1027        return UNKNOWN_ERROR;
1028    }
1029
1030    bool hasErrors = false;
1031
1032    if (drawables != NULL) {
1033        if (bundle->getOutputAPKFile() != NULL) {
1034            err = preProcessImages(bundle, assets, drawables, "drawable");
1035        }
1036        if (err == NO_ERROR) {
1037            err = makeFileResources(bundle, assets, &table, drawables, "drawable");
1038            if (err != NO_ERROR) {
1039                hasErrors = true;
1040            }
1041        } else {
1042            hasErrors = true;
1043        }
1044    }
1045
1046    if (mipmaps != NULL) {
1047        if (bundle->getOutputAPKFile() != NULL) {
1048            err = preProcessImages(bundle, assets, mipmaps, "mipmap");
1049        }
1050        if (err == NO_ERROR) {
1051            err = makeFileResources(bundle, assets, &table, mipmaps, "mipmap");
1052            if (err != NO_ERROR) {
1053                hasErrors = true;
1054            }
1055        } else {
1056            hasErrors = true;
1057        }
1058    }
1059
1060    if (layouts != NULL) {
1061        err = makeFileResources(bundle, assets, &table, layouts, "layout");
1062        if (err != NO_ERROR) {
1063            hasErrors = true;
1064        }
1065    }
1066
1067    if (anims != NULL) {
1068        err = makeFileResources(bundle, assets, &table, anims, "anim");
1069        if (err != NO_ERROR) {
1070            hasErrors = true;
1071        }
1072    }
1073
1074    if (animators != NULL) {
1075        err = makeFileResources(bundle, assets, &table, animators, "animator");
1076        if (err != NO_ERROR) {
1077            hasErrors = true;
1078        }
1079    }
1080
1081    if (transitions != NULL) {
1082        err = makeFileResources(bundle, assets, &table, transitions, "transition");
1083        if (err != NO_ERROR) {
1084            hasErrors = true;
1085        }
1086    }
1087
1088    if (interpolators != NULL) {
1089        err = makeFileResources(bundle, assets, &table, interpolators, "interpolator");
1090        if (err != NO_ERROR) {
1091            hasErrors = true;
1092        }
1093    }
1094
1095    if (xmls != NULL) {
1096        err = makeFileResources(bundle, assets, &table, xmls, "xml");
1097        if (err != NO_ERROR) {
1098            hasErrors = true;
1099        }
1100    }
1101
1102    if (raws != NULL) {
1103        err = makeFileResources(bundle, assets, &table, raws, "raw");
1104        if (err != NO_ERROR) {
1105            hasErrors = true;
1106        }
1107    }
1108
1109    // compile resources
1110    current = assets;
1111    while(current.get()) {
1112        KeyedVector<String8, sp<ResourceTypeSet> > *resources =
1113                current->getResources();
1114
1115        ssize_t index = resources->indexOfKey(String8("values"));
1116        if (index >= 0) {
1117            ResourceDirIterator it(resources->valueAt(index), String8("values"));
1118            ssize_t res;
1119            while ((res=it.next()) == NO_ERROR) {
1120                sp<AaptFile> file = it.getFile();
1121                res = compileResourceFile(bundle, assets, file, it.getParams(),
1122                                          (current!=assets), &table);
1123                if (res != NO_ERROR) {
1124                    hasErrors = true;
1125                }
1126            }
1127        }
1128        current = current->getOverlay();
1129    }
1130
1131    if (colors != NULL) {
1132        err = makeFileResources(bundle, assets, &table, colors, "color");
1133        if (err != NO_ERROR) {
1134            hasErrors = true;
1135        }
1136    }
1137
1138    if (menus != NULL) {
1139        err = makeFileResources(bundle, assets, &table, menus, "menu");
1140        if (err != NO_ERROR) {
1141            hasErrors = true;
1142        }
1143    }
1144
1145    // --------------------------------------------------------------------
1146    // Assignment of resource IDs and initial generation of resource table.
1147    // --------------------------------------------------------------------
1148
1149    if (table.hasResources()) {
1150        err = table.assignResourceIds();
1151        if (err < NO_ERROR) {
1152            return err;
1153        }
1154    }
1155
1156    // --------------------------------------------------------------
1157    // Finally, we can now we can compile XML files, which may reference
1158    // resources.
1159    // --------------------------------------------------------------
1160
1161    if (layouts != NULL) {
1162        ResourceDirIterator it(layouts, String8("layout"));
1163        while ((err=it.next()) == NO_ERROR) {
1164            String8 src = it.getFile()->getPrintableSource();
1165            err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
1166            if (err == NO_ERROR) {
1167                ResXMLTree block;
1168                block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
1169                checkForIds(src, block);
1170            } else {
1171                hasErrors = true;
1172            }
1173        }
1174
1175        if (err < NO_ERROR) {
1176            hasErrors = true;
1177        }
1178        err = NO_ERROR;
1179    }
1180
1181    if (anims != NULL) {
1182        ResourceDirIterator it(anims, String8("anim"));
1183        while ((err=it.next()) == NO_ERROR) {
1184            err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
1185            if (err != NO_ERROR) {
1186                hasErrors = true;
1187            }
1188        }
1189
1190        if (err < NO_ERROR) {
1191            hasErrors = true;
1192        }
1193        err = NO_ERROR;
1194    }
1195
1196    if (animators != NULL) {
1197        ResourceDirIterator it(animators, String8("animator"));
1198        while ((err=it.next()) == NO_ERROR) {
1199            err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
1200            if (err != NO_ERROR) {
1201                hasErrors = true;
1202            }
1203        }
1204
1205        if (err < NO_ERROR) {
1206            hasErrors = true;
1207        }
1208        err = NO_ERROR;
1209    }
1210
1211    if (interpolators != NULL) {
1212        ResourceDirIterator it(interpolators, String8("interpolator"));
1213        while ((err=it.next()) == NO_ERROR) {
1214            err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
1215            if (err != NO_ERROR) {
1216                hasErrors = true;
1217            }
1218        }
1219
1220        if (err < NO_ERROR) {
1221            hasErrors = true;
1222        }
1223        err = NO_ERROR;
1224    }
1225
1226    if (transitions != NULL) {
1227        ResourceDirIterator it(transitions, String8("transition"));
1228        while ((err=it.next()) == NO_ERROR) {
1229            err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
1230            if (err != NO_ERROR) {
1231                hasErrors = true;
1232            }
1233        }
1234
1235        if (err < NO_ERROR) {
1236            hasErrors = true;
1237        }
1238        err = NO_ERROR;
1239    }
1240
1241    if (xmls != NULL) {
1242        ResourceDirIterator it(xmls, String8("xml"));
1243        while ((err=it.next()) == NO_ERROR) {
1244            err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
1245            if (err != NO_ERROR) {
1246                hasErrors = true;
1247            }
1248        }
1249
1250        if (err < NO_ERROR) {
1251            hasErrors = true;
1252        }
1253        err = NO_ERROR;
1254    }
1255
1256    if (drawables != NULL) {
1257        ResourceDirIterator it(drawables, String8("drawable"));
1258        while ((err=it.next()) == NO_ERROR) {
1259            err = postProcessImage(assets, &table, it.getFile());
1260            if (err != NO_ERROR) {
1261                hasErrors = true;
1262            }
1263        }
1264
1265        if (err < NO_ERROR) {
1266            hasErrors = true;
1267        }
1268        err = NO_ERROR;
1269    }
1270
1271    if (colors != NULL) {
1272        ResourceDirIterator it(colors, String8("color"));
1273        while ((err=it.next()) == NO_ERROR) {
1274            err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
1275            if (err != NO_ERROR) {
1276                hasErrors = true;
1277            }
1278        }
1279
1280        if (err < NO_ERROR) {
1281            hasErrors = true;
1282        }
1283        err = NO_ERROR;
1284    }
1285
1286    if (menus != NULL) {
1287        ResourceDirIterator it(menus, String8("menu"));
1288        while ((err=it.next()) == NO_ERROR) {
1289            String8 src = it.getFile()->getPrintableSource();
1290            err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
1291            if (err == NO_ERROR) {
1292                ResXMLTree block;
1293                block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
1294                checkForIds(src, block);
1295            } else {
1296                hasErrors = true;
1297            }
1298        }
1299
1300        if (err < NO_ERROR) {
1301            hasErrors = true;
1302        }
1303        err = NO_ERROR;
1304    }
1305
1306    if (table.validateLocalizations()) {
1307        hasErrors = true;
1308    }
1309
1310    if (hasErrors) {
1311        return UNKNOWN_ERROR;
1312    }
1313
1314    const sp<AaptFile> manifestFile(androidManifestFile->getFiles().valueAt(0));
1315    String8 manifestPath(manifestFile->getPrintableSource());
1316
1317    // Generate final compiled manifest file.
1318    manifestFile->clearData();
1319    sp<XMLNode> manifestTree = XMLNode::parse(manifestFile);
1320    if (manifestTree == NULL) {
1321        return UNKNOWN_ERROR;
1322    }
1323    err = massageManifest(bundle, manifestTree);
1324    if (err < NO_ERROR) {
1325        return err;
1326    }
1327    err = compileXmlFile(assets, manifestTree, manifestFile, &table);
1328    if (err < NO_ERROR) {
1329        return err;
1330    }
1331
1332    //block.restart();
1333    //printXMLBlock(&block);
1334
1335    // --------------------------------------------------------------
1336    // Generate the final resource table.
1337    // Re-flatten because we may have added new resource IDs
1338    // --------------------------------------------------------------
1339
1340    ResTable finalResTable;
1341    sp<AaptFile> resFile;
1342
1343    if (table.hasResources()) {
1344        sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1345        err = table.addSymbols(symbols);
1346        if (err < NO_ERROR) {
1347            return err;
1348        }
1349
1350        Vector<sp<ApkSplit> >& splits = builder->getSplits();
1351        const size_t numSplits = splits.size();
1352        for (size_t i = 0; i < numSplits; i++) {
1353            sp<ApkSplit>& split = splits.editItemAt(i);
1354            sp<AaptFile> flattenedTable = new AaptFile(String8("resources.arsc"),
1355                    AaptGroupEntry(), String8());
1356            err = table.flatten(bundle, split->getResourceFilter(), flattenedTable);
1357            if (err != NO_ERROR) {
1358                fprintf(stderr, "Failed to generate resource table for split '%s'\n",
1359                        split->getPrintableName().string());
1360                return err;
1361            }
1362            split->addEntry(String8("resources.arsc"), flattenedTable);
1363
1364            if (split->isBase()) {
1365                resFile = flattenedTable;
1366                finalResTable.add(flattenedTable->getData(), flattenedTable->getSize());
1367            } else {
1368                sp<AaptFile> generatedManifest = new AaptFile(String8("AndroidManifest.xml"),
1369                        AaptGroupEntry(), String8());
1370                err = generateAndroidManifestForSplit(String16(assets->getPackage()), split,
1371                        generatedManifest);
1372                if (err != NO_ERROR) {
1373                    fprintf(stderr, "Failed to generate AndroidManifest.xml for split '%s'\n",
1374                            split->getPrintableName().string());
1375                    return err;
1376                }
1377                split->addEntry(String8("AndroidManifest.xml"), generatedManifest);
1378            }
1379        }
1380
1381        if (bundle->getPublicOutputFile()) {
1382            FILE* fp = fopen(bundle->getPublicOutputFile(), "w+");
1383            if (fp == NULL) {
1384                fprintf(stderr, "ERROR: Unable to open public definitions output file %s: %s\n",
1385                        (const char*)bundle->getPublicOutputFile(), strerror(errno));
1386                return UNKNOWN_ERROR;
1387            }
1388            if (bundle->getVerbose()) {
1389                printf("  Writing public definitions to %s.\n", bundle->getPublicOutputFile());
1390            }
1391            table.writePublicDefinitions(String16(assets->getPackage()), fp);
1392            fclose(fp);
1393        }
1394
1395        if (finalResTable.getTableCount() == 0 || resFile == NULL) {
1396            fprintf(stderr, "No resource table was generated.\n");
1397            return UNKNOWN_ERROR;
1398        }
1399    }
1400
1401    // Perform a basic validation of the manifest file.  This time we
1402    // parse it with the comments intact, so that we can use them to
1403    // generate java docs...  so we are not going to write this one
1404    // back out to the final manifest data.
1405    sp<AaptFile> outManifestFile = new AaptFile(manifestFile->getSourceFile(),
1406            manifestFile->getGroupEntry(),
1407            manifestFile->getResourceType());
1408    err = compileXmlFile(assets, manifestFile,
1409            outManifestFile, &table,
1410            XML_COMPILE_ASSIGN_ATTRIBUTE_IDS
1411            | XML_COMPILE_STRIP_WHITESPACE | XML_COMPILE_STRIP_RAW_VALUES);
1412    if (err < NO_ERROR) {
1413        return err;
1414    }
1415    ResXMLTree block;
1416    block.setTo(outManifestFile->getData(), outManifestFile->getSize(), true);
1417    String16 manifest16("manifest");
1418    String16 permission16("permission");
1419    String16 permission_group16("permission-group");
1420    String16 uses_permission16("uses-permission");
1421    String16 instrumentation16("instrumentation");
1422    String16 application16("application");
1423    String16 provider16("provider");
1424    String16 service16("service");
1425    String16 receiver16("receiver");
1426    String16 activity16("activity");
1427    String16 action16("action");
1428    String16 category16("category");
1429    String16 data16("scheme");
1430    const char* packageIdentChars = "abcdefghijklmnopqrstuvwxyz"
1431        "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789";
1432    const char* packageIdentCharsWithTheStupid = "abcdefghijklmnopqrstuvwxyz"
1433        "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
1434    const char* classIdentChars = "abcdefghijklmnopqrstuvwxyz"
1435        "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789$";
1436    const char* processIdentChars = "abcdefghijklmnopqrstuvwxyz"
1437        "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:";
1438    const char* authoritiesIdentChars = "abcdefghijklmnopqrstuvwxyz"
1439        "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-:;";
1440    const char* typeIdentChars = "abcdefghijklmnopqrstuvwxyz"
1441        "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:-/*+";
1442    const char* schemeIdentChars = "abcdefghijklmnopqrstuvwxyz"
1443        "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
1444    ResXMLTree::event_code_t code;
1445    sp<AaptSymbols> permissionSymbols;
1446    sp<AaptSymbols> permissionGroupSymbols;
1447    while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1448           && code > ResXMLTree::BAD_DOCUMENT) {
1449        if (code == ResXMLTree::START_TAG) {
1450            size_t len;
1451            if (block.getElementNamespace(&len) != NULL) {
1452                continue;
1453            }
1454            if (strcmp16(block.getElementName(&len), manifest16.string()) == 0) {
1455                if (validateAttr(manifestPath, finalResTable, block, NULL, "package",
1456                                 packageIdentChars, true) != ATTR_OKAY) {
1457                    hasErrors = true;
1458                }
1459                if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1460                                 "sharedUserId", packageIdentChars, false) != ATTR_OKAY) {
1461                    hasErrors = true;
1462                }
1463            } else if (strcmp16(block.getElementName(&len), permission16.string()) == 0
1464                    || strcmp16(block.getElementName(&len), permission_group16.string()) == 0) {
1465                const bool isGroup = strcmp16(block.getElementName(&len),
1466                        permission_group16.string()) == 0;
1467                if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1468                                 "name", isGroup ? packageIdentCharsWithTheStupid
1469                                 : packageIdentChars, true) != ATTR_OKAY) {
1470                    hasErrors = true;
1471                }
1472                SourcePos srcPos(manifestPath, block.getLineNumber());
1473                sp<AaptSymbols> syms;
1474                if (!isGroup) {
1475                    syms = permissionSymbols;
1476                    if (syms == NULL) {
1477                        sp<AaptSymbols> symbols =
1478                                assets->getSymbolsFor(String8("Manifest"));
1479                        syms = permissionSymbols = symbols->addNestedSymbol(
1480                                String8("permission"), srcPos);
1481                    }
1482                } else {
1483                    syms = permissionGroupSymbols;
1484                    if (syms == NULL) {
1485                        sp<AaptSymbols> symbols =
1486                                assets->getSymbolsFor(String8("Manifest"));
1487                        syms = permissionGroupSymbols = symbols->addNestedSymbol(
1488                                String8("permission_group"), srcPos);
1489                    }
1490                }
1491                size_t len;
1492                ssize_t index = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "name");
1493                const uint16_t* id = block.getAttributeStringValue(index, &len);
1494                if (id == NULL) {
1495                    fprintf(stderr, "%s:%d: missing name attribute in element <%s>.\n",
1496                            manifestPath.string(), block.getLineNumber(),
1497                            String8(block.getElementName(&len)).string());
1498                    hasErrors = true;
1499                    break;
1500                }
1501                String8 idStr(id);
1502                char* p = idStr.lockBuffer(idStr.size());
1503                char* e = p + idStr.size();
1504                bool begins_with_digit = true;  // init to true so an empty string fails
1505                while (e > p) {
1506                    e--;
1507                    if (*e >= '0' && *e <= '9') {
1508                      begins_with_digit = true;
1509                      continue;
1510                    }
1511                    if ((*e >= 'a' && *e <= 'z') ||
1512                        (*e >= 'A' && *e <= 'Z') ||
1513                        (*e == '_')) {
1514                      begins_with_digit = false;
1515                      continue;
1516                    }
1517                    if (isGroup && (*e == '-')) {
1518                        *e = '_';
1519                        begins_with_digit = false;
1520                        continue;
1521                    }
1522                    e++;
1523                    break;
1524                }
1525                idStr.unlockBuffer();
1526                // verify that we stopped because we hit a period or
1527                // the beginning of the string, and that the
1528                // identifier didn't begin with a digit.
1529                if (begins_with_digit || (e != p && *(e-1) != '.')) {
1530                  fprintf(stderr,
1531                          "%s:%d: Permission name <%s> is not a valid Java symbol\n",
1532                          manifestPath.string(), block.getLineNumber(), idStr.string());
1533                  hasErrors = true;
1534                }
1535                syms->addStringSymbol(String8(e), idStr, srcPos);
1536                const uint16_t* cmt = block.getComment(&len);
1537                if (cmt != NULL && *cmt != 0) {
1538                    //printf("Comment of %s: %s\n", String8(e).string(),
1539                    //        String8(cmt).string());
1540                    syms->appendComment(String8(e), String16(cmt), srcPos);
1541                } else {
1542                    //printf("No comment for %s\n", String8(e).string());
1543                }
1544                syms->makeSymbolPublic(String8(e), srcPos);
1545            } else if (strcmp16(block.getElementName(&len), uses_permission16.string()) == 0) {
1546                if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1547                                 "name", packageIdentChars, true) != ATTR_OKAY) {
1548                    hasErrors = true;
1549                }
1550            } else if (strcmp16(block.getElementName(&len), instrumentation16.string()) == 0) {
1551                if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1552                                 "name", classIdentChars, true) != ATTR_OKAY) {
1553                    hasErrors = true;
1554                }
1555                if (validateAttr(manifestPath, finalResTable, block,
1556                                 RESOURCES_ANDROID_NAMESPACE, "targetPackage",
1557                                 packageIdentChars, true) != ATTR_OKAY) {
1558                    hasErrors = true;
1559                }
1560            } else if (strcmp16(block.getElementName(&len), application16.string()) == 0) {
1561                if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1562                                 "name", classIdentChars, false) != ATTR_OKAY) {
1563                    hasErrors = true;
1564                }
1565                if (validateAttr(manifestPath, finalResTable, block,
1566                                 RESOURCES_ANDROID_NAMESPACE, "permission",
1567                                 packageIdentChars, false) != ATTR_OKAY) {
1568                    hasErrors = true;
1569                }
1570                if (validateAttr(manifestPath, finalResTable, block,
1571                                 RESOURCES_ANDROID_NAMESPACE, "process",
1572                                 processIdentChars, false) != ATTR_OKAY) {
1573                    hasErrors = true;
1574                }
1575                if (validateAttr(manifestPath, finalResTable, block,
1576                                 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
1577                                 processIdentChars, false) != ATTR_OKAY) {
1578                    hasErrors = true;
1579                }
1580            } else if (strcmp16(block.getElementName(&len), provider16.string()) == 0) {
1581                if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1582                                 "name", classIdentChars, true) != ATTR_OKAY) {
1583                    hasErrors = true;
1584                }
1585                if (validateAttr(manifestPath, finalResTable, block,
1586                                 RESOURCES_ANDROID_NAMESPACE, "authorities",
1587                                 authoritiesIdentChars, true) != ATTR_OKAY) {
1588                    hasErrors = true;
1589                }
1590                if (validateAttr(manifestPath, finalResTable, block,
1591                                 RESOURCES_ANDROID_NAMESPACE, "permission",
1592                                 packageIdentChars, false) != ATTR_OKAY) {
1593                    hasErrors = true;
1594                }
1595                if (validateAttr(manifestPath, finalResTable, block,
1596                                 RESOURCES_ANDROID_NAMESPACE, "process",
1597                                 processIdentChars, false) != ATTR_OKAY) {
1598                    hasErrors = true;
1599                }
1600            } else if (strcmp16(block.getElementName(&len), service16.string()) == 0
1601                       || strcmp16(block.getElementName(&len), receiver16.string()) == 0
1602                       || strcmp16(block.getElementName(&len), activity16.string()) == 0) {
1603                if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1604                                 "name", classIdentChars, true) != ATTR_OKAY) {
1605                    hasErrors = true;
1606                }
1607                if (validateAttr(manifestPath, finalResTable, block,
1608                                 RESOURCES_ANDROID_NAMESPACE, "permission",
1609                                 packageIdentChars, false) != ATTR_OKAY) {
1610                    hasErrors = true;
1611                }
1612                if (validateAttr(manifestPath, finalResTable, block,
1613                                 RESOURCES_ANDROID_NAMESPACE, "process",
1614                                 processIdentChars, false) != ATTR_OKAY) {
1615                    hasErrors = true;
1616                }
1617                if (validateAttr(manifestPath, finalResTable, block,
1618                                 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
1619                                 processIdentChars, false) != ATTR_OKAY) {
1620                    hasErrors = true;
1621                }
1622            } else if (strcmp16(block.getElementName(&len), action16.string()) == 0
1623                       || strcmp16(block.getElementName(&len), category16.string()) == 0) {
1624                if (validateAttr(manifestPath, finalResTable, block,
1625                                 RESOURCES_ANDROID_NAMESPACE, "name",
1626                                 packageIdentChars, true) != ATTR_OKAY) {
1627                    hasErrors = true;
1628                }
1629            } else if (strcmp16(block.getElementName(&len), data16.string()) == 0) {
1630                if (validateAttr(manifestPath, finalResTable, block,
1631                                 RESOURCES_ANDROID_NAMESPACE, "mimeType",
1632                                 typeIdentChars, true) != ATTR_OKAY) {
1633                    hasErrors = true;
1634                }
1635                if (validateAttr(manifestPath, finalResTable, block,
1636                                 RESOURCES_ANDROID_NAMESPACE, "scheme",
1637                                 schemeIdentChars, true) != ATTR_OKAY) {
1638                    hasErrors = true;
1639                }
1640            }
1641        }
1642    }
1643
1644    if (resFile != NULL) {
1645        // These resources are now considered to be a part of the included
1646        // resources, for others to reference.
1647        err = assets->addIncludedResources(resFile);
1648        if (err < NO_ERROR) {
1649            fprintf(stderr, "ERROR: Unable to parse generated resources, aborting.\n");
1650            return err;
1651        }
1652    }
1653
1654    return err;
1655}
1656
1657static const char* getIndentSpace(int indent)
1658{
1659static const char whitespace[] =
1660"                                                                                       ";
1661
1662    return whitespace + sizeof(whitespace) - 1 - indent*4;
1663}
1664
1665static String8 flattenSymbol(const String8& symbol) {
1666    String8 result(symbol);
1667    ssize_t first;
1668    if ((first = symbol.find(":", 0)) >= 0
1669            || (first = symbol.find(".", 0)) >= 0) {
1670        size_t size = symbol.size();
1671        char* buf = result.lockBuffer(size);
1672        for (size_t i = first; i < size; i++) {
1673            if (buf[i] == ':' || buf[i] == '.') {
1674                buf[i] = '_';
1675            }
1676        }
1677        result.unlockBuffer(size);
1678    }
1679    return result;
1680}
1681
1682static String8 getSymbolPackage(const String8& symbol, const sp<AaptAssets>& assets, bool pub) {
1683    ssize_t colon = symbol.find(":", 0);
1684    if (colon >= 0) {
1685        return String8(symbol.string(), colon);
1686    }
1687    return pub ? assets->getPackage() : assets->getSymbolsPrivatePackage();
1688}
1689
1690static String8 getSymbolName(const String8& symbol) {
1691    ssize_t colon = symbol.find(":", 0);
1692    if (colon >= 0) {
1693        return String8(symbol.string() + colon + 1);
1694    }
1695    return symbol;
1696}
1697
1698static String16 getAttributeComment(const sp<AaptAssets>& assets,
1699                                    const String8& name,
1700                                    String16* outTypeComment = NULL)
1701{
1702    sp<AaptSymbols> asym = assets->getSymbolsFor(String8("R"));
1703    if (asym != NULL) {
1704        //printf("Got R symbols!\n");
1705        asym = asym->getNestedSymbols().valueFor(String8("attr"));
1706        if (asym != NULL) {
1707            //printf("Got attrs symbols! comment %s=%s\n",
1708            //     name.string(), String8(asym->getComment(name)).string());
1709            if (outTypeComment != NULL) {
1710                *outTypeComment = asym->getTypeComment(name);
1711            }
1712            return asym->getComment(name);
1713        }
1714    }
1715    return String16();
1716}
1717
1718static status_t writeLayoutClasses(
1719    FILE* fp, const sp<AaptAssets>& assets,
1720    const sp<AaptSymbols>& symbols, int indent, bool includePrivate)
1721{
1722    const char* indentStr = getIndentSpace(indent);
1723    if (!includePrivate) {
1724        fprintf(fp, "%s/** @doconly */\n", indentStr);
1725    }
1726    fprintf(fp, "%spublic static final class styleable {\n", indentStr);
1727    indent++;
1728
1729    String16 attr16("attr");
1730    String16 package16(assets->getPackage());
1731
1732    indentStr = getIndentSpace(indent);
1733    bool hasErrors = false;
1734
1735    size_t i;
1736    size_t N = symbols->getNestedSymbols().size();
1737    for (i=0; i<N; i++) {
1738        sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
1739        String8 realClassName(symbols->getNestedSymbols().keyAt(i));
1740        String8 nclassName(flattenSymbol(realClassName));
1741
1742        SortedVector<uint32_t> idents;
1743        Vector<uint32_t> origOrder;
1744        Vector<bool> publicFlags;
1745
1746        size_t a;
1747        size_t NA = nsymbols->getSymbols().size();
1748        for (a=0; a<NA; a++) {
1749            const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a));
1750            int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32
1751                    ? sym.int32Val : 0;
1752            bool isPublic = true;
1753            if (code == 0) {
1754                String16 name16(sym.name);
1755                uint32_t typeSpecFlags;
1756                code = assets->getIncludedResources().identifierForName(
1757                    name16.string(), name16.size(),
1758                    attr16.string(), attr16.size(),
1759                    package16.string(), package16.size(), &typeSpecFlags);
1760                if (code == 0) {
1761                    fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
1762                            nclassName.string(), sym.name.string());
1763                    hasErrors = true;
1764                }
1765                isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
1766            }
1767            idents.add(code);
1768            origOrder.add(code);
1769            publicFlags.add(isPublic);
1770        }
1771
1772        NA = idents.size();
1773
1774        String16 comment = symbols->getComment(realClassName);
1775        AnnotationProcessor ann;
1776        fprintf(fp, "%s/** ", indentStr);
1777        if (comment.size() > 0) {
1778            String8 cmt(comment);
1779            ann.preprocessComment(cmt);
1780            fprintf(fp, "%s\n", cmt.string());
1781        } else {
1782            fprintf(fp, "Attributes that can be used with a %s.\n", nclassName.string());
1783        }
1784        bool hasTable = false;
1785        for (a=0; a<NA; a++) {
1786            ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1787            if (pos >= 0) {
1788                if (!hasTable) {
1789                    hasTable = true;
1790                    fprintf(fp,
1791                            "%s   <p>Includes the following attributes:</p>\n"
1792                            "%s   <table>\n"
1793                            "%s   <colgroup align=\"left\" />\n"
1794                            "%s   <colgroup align=\"left\" />\n"
1795                            "%s   <tr><th>Attribute</th><th>Description</th></tr>\n",
1796                            indentStr,
1797                            indentStr,
1798                            indentStr,
1799                            indentStr,
1800                            indentStr);
1801                }
1802                const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1803                if (!publicFlags.itemAt(a) && !includePrivate) {
1804                    continue;
1805                }
1806                String8 name8(sym.name);
1807                String16 comment(sym.comment);
1808                if (comment.size() <= 0) {
1809                    comment = getAttributeComment(assets, name8);
1810                }
1811                if (comment.size() > 0) {
1812                    const char16_t* p = comment.string();
1813                    while (*p != 0 && *p != '.') {
1814                        if (*p == '{') {
1815                            while (*p != 0 && *p != '}') {
1816                                p++;
1817                            }
1818                        } else {
1819                            p++;
1820                        }
1821                    }
1822                    if (*p == '.') {
1823                        p++;
1824                    }
1825                    comment = String16(comment.string(), p-comment.string());
1826                }
1827                fprintf(fp, "%s   <tr><td><code>{@link #%s_%s %s:%s}</code></td><td>%s</td></tr>\n",
1828                        indentStr, nclassName.string(),
1829                        flattenSymbol(name8).string(),
1830                        getSymbolPackage(name8, assets, true).string(),
1831                        getSymbolName(name8).string(),
1832                        String8(comment).string());
1833            }
1834        }
1835        if (hasTable) {
1836            fprintf(fp, "%s   </table>\n", indentStr);
1837        }
1838        for (a=0; a<NA; a++) {
1839            ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1840            if (pos >= 0) {
1841                const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1842                if (!publicFlags.itemAt(a) && !includePrivate) {
1843                    continue;
1844                }
1845                fprintf(fp, "%s   @see #%s_%s\n",
1846                        indentStr, nclassName.string(),
1847                        flattenSymbol(sym.name).string());
1848            }
1849        }
1850        fprintf(fp, "%s */\n", getIndentSpace(indent));
1851
1852        ann.printAnnotations(fp, indentStr);
1853
1854        fprintf(fp,
1855                "%spublic static final int[] %s = {\n"
1856                "%s",
1857                indentStr, nclassName.string(),
1858                getIndentSpace(indent+1));
1859
1860        for (a=0; a<NA; a++) {
1861            if (a != 0) {
1862                if ((a&3) == 0) {
1863                    fprintf(fp, ",\n%s", getIndentSpace(indent+1));
1864                } else {
1865                    fprintf(fp, ", ");
1866                }
1867            }
1868            fprintf(fp, "0x%08x", idents[a]);
1869        }
1870
1871        fprintf(fp, "\n%s};\n", indentStr);
1872
1873        for (a=0; a<NA; a++) {
1874            ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1875            if (pos >= 0) {
1876                const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1877                if (!publicFlags.itemAt(a) && !includePrivate) {
1878                    continue;
1879                }
1880                String8 name8(sym.name);
1881                String16 comment(sym.comment);
1882                String16 typeComment;
1883                if (comment.size() <= 0) {
1884                    comment = getAttributeComment(assets, name8, &typeComment);
1885                } else {
1886                    getAttributeComment(assets, name8, &typeComment);
1887                }
1888
1889                uint32_t typeSpecFlags = 0;
1890                String16 name16(sym.name);
1891                assets->getIncludedResources().identifierForName(
1892                    name16.string(), name16.size(),
1893                    attr16.string(), attr16.size(),
1894                    package16.string(), package16.size(), &typeSpecFlags);
1895                //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
1896                //    String8(attr16).string(), String8(name16).string(), typeSpecFlags);
1897                const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
1898
1899                AnnotationProcessor ann;
1900                fprintf(fp, "%s/**\n", indentStr);
1901                if (comment.size() > 0) {
1902                    String8 cmt(comment);
1903                    ann.preprocessComment(cmt);
1904                    fprintf(fp, "%s  <p>\n%s  @attr description\n", indentStr, indentStr);
1905                    fprintf(fp, "%s  %s\n", indentStr, cmt.string());
1906                } else {
1907                    fprintf(fp,
1908                            "%s  <p>This symbol is the offset where the {@link %s.R.attr#%s}\n"
1909                            "%s  attribute's value can be found in the {@link #%s} array.\n",
1910                            indentStr,
1911                            getSymbolPackage(name8, assets, pub).string(),
1912                            getSymbolName(name8).string(),
1913                            indentStr, nclassName.string());
1914                }
1915                if (typeComment.size() > 0) {
1916                    String8 cmt(typeComment);
1917                    ann.preprocessComment(cmt);
1918                    fprintf(fp, "\n\n%s  %s\n", indentStr, cmt.string());
1919                }
1920                if (comment.size() > 0) {
1921                    if (pub) {
1922                        fprintf(fp,
1923                                "%s  <p>This corresponds to the global attribute\n"
1924                                "%s  resource symbol {@link %s.R.attr#%s}.\n",
1925                                indentStr, indentStr,
1926                                getSymbolPackage(name8, assets, true).string(),
1927                                getSymbolName(name8).string());
1928                    } else {
1929                        fprintf(fp,
1930                                "%s  <p>This is a private symbol.\n", indentStr);
1931                    }
1932                }
1933                fprintf(fp, "%s  @attr name %s:%s\n", indentStr,
1934                        getSymbolPackage(name8, assets, pub).string(),
1935                        getSymbolName(name8).string());
1936                fprintf(fp, "%s*/\n", indentStr);
1937                ann.printAnnotations(fp, indentStr);
1938                fprintf(fp,
1939                        "%spublic static final int %s_%s = %d;\n",
1940                        indentStr, nclassName.string(),
1941                        flattenSymbol(name8).string(), (int)pos);
1942            }
1943        }
1944    }
1945
1946    indent--;
1947    fprintf(fp, "%s};\n", getIndentSpace(indent));
1948    return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
1949}
1950
1951static status_t writeTextLayoutClasses(
1952    FILE* fp, const sp<AaptAssets>& assets,
1953    const sp<AaptSymbols>& symbols, bool includePrivate)
1954{
1955    String16 attr16("attr");
1956    String16 package16(assets->getPackage());
1957
1958    bool hasErrors = false;
1959
1960    size_t i;
1961    size_t N = symbols->getNestedSymbols().size();
1962    for (i=0; i<N; i++) {
1963        sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
1964        String8 realClassName(symbols->getNestedSymbols().keyAt(i));
1965        String8 nclassName(flattenSymbol(realClassName));
1966
1967        SortedVector<uint32_t> idents;
1968        Vector<uint32_t> origOrder;
1969        Vector<bool> publicFlags;
1970
1971        size_t a;
1972        size_t NA = nsymbols->getSymbols().size();
1973        for (a=0; a<NA; a++) {
1974            const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a));
1975            int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32
1976                    ? sym.int32Val : 0;
1977            bool isPublic = true;
1978            if (code == 0) {
1979                String16 name16(sym.name);
1980                uint32_t typeSpecFlags;
1981                code = assets->getIncludedResources().identifierForName(
1982                    name16.string(), name16.size(),
1983                    attr16.string(), attr16.size(),
1984                    package16.string(), package16.size(), &typeSpecFlags);
1985                if (code == 0) {
1986                    fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
1987                            nclassName.string(), sym.name.string());
1988                    hasErrors = true;
1989                }
1990                isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
1991            }
1992            idents.add(code);
1993            origOrder.add(code);
1994            publicFlags.add(isPublic);
1995        }
1996
1997        NA = idents.size();
1998
1999        fprintf(fp, "int[] styleable %s {", nclassName.string());
2000
2001        for (a=0; a<NA; a++) {
2002            if (a != 0) {
2003                fprintf(fp, ",");
2004            }
2005            fprintf(fp, " 0x%08x", idents[a]);
2006        }
2007
2008        fprintf(fp, " }\n");
2009
2010        for (a=0; a<NA; a++) {
2011            ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2012            if (pos >= 0) {
2013                const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2014                if (!publicFlags.itemAt(a) && !includePrivate) {
2015                    continue;
2016                }
2017                String8 name8(sym.name);
2018                String16 comment(sym.comment);
2019                String16 typeComment;
2020                if (comment.size() <= 0) {
2021                    comment = getAttributeComment(assets, name8, &typeComment);
2022                } else {
2023                    getAttributeComment(assets, name8, &typeComment);
2024                }
2025
2026                uint32_t typeSpecFlags = 0;
2027                String16 name16(sym.name);
2028                assets->getIncludedResources().identifierForName(
2029                    name16.string(), name16.size(),
2030                    attr16.string(), attr16.size(),
2031                    package16.string(), package16.size(), &typeSpecFlags);
2032                //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
2033                //    String8(attr16).string(), String8(name16).string(), typeSpecFlags);
2034                const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
2035
2036                fprintf(fp,
2037                        "int styleable %s_%s %d\n",
2038                        nclassName.string(),
2039                        flattenSymbol(name8).string(), (int)pos);
2040            }
2041        }
2042    }
2043
2044    return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
2045}
2046
2047static status_t writeSymbolClass(
2048    FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2049    const sp<AaptSymbols>& symbols, const String8& className, int indent,
2050    bool nonConstantId)
2051{
2052    fprintf(fp, "%spublic %sfinal class %s {\n",
2053            getIndentSpace(indent),
2054            indent != 0 ? "static " : "", className.string());
2055    indent++;
2056
2057    size_t i;
2058    status_t err = NO_ERROR;
2059
2060    const char * id_format = nonConstantId ?
2061            "%spublic static int %s=0x%08x;\n" :
2062            "%spublic static final int %s=0x%08x;\n";
2063
2064    size_t N = symbols->getSymbols().size();
2065    for (i=0; i<N; i++) {
2066        const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2067        if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
2068            continue;
2069        }
2070        if (!assets->isJavaSymbol(sym, includePrivate)) {
2071            continue;
2072        }
2073        String8 name8(sym.name);
2074        String16 comment(sym.comment);
2075        bool haveComment = false;
2076        AnnotationProcessor ann;
2077        if (comment.size() > 0) {
2078            haveComment = true;
2079            String8 cmt(comment);
2080            ann.preprocessComment(cmt);
2081            fprintf(fp,
2082                    "%s/** %s\n",
2083                    getIndentSpace(indent), cmt.string());
2084        } else if (sym.isPublic && !includePrivate) {
2085            sym.sourcePos.warning("No comment for public symbol %s:%s/%s",
2086                assets->getPackage().string(), className.string(),
2087                String8(sym.name).string());
2088        }
2089        String16 typeComment(sym.typeComment);
2090        if (typeComment.size() > 0) {
2091            String8 cmt(typeComment);
2092            ann.preprocessComment(cmt);
2093            if (!haveComment) {
2094                haveComment = true;
2095                fprintf(fp,
2096                        "%s/** %s\n", getIndentSpace(indent), cmt.string());
2097            } else {
2098                fprintf(fp,
2099                        "%s %s\n", getIndentSpace(indent), cmt.string());
2100            }
2101        }
2102        if (haveComment) {
2103            fprintf(fp,"%s */\n", getIndentSpace(indent));
2104        }
2105        ann.printAnnotations(fp, getIndentSpace(indent));
2106        fprintf(fp, id_format,
2107                getIndentSpace(indent),
2108                flattenSymbol(name8).string(), (int)sym.int32Val);
2109    }
2110
2111    for (i=0; i<N; i++) {
2112        const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2113        if (sym.typeCode != AaptSymbolEntry::TYPE_STRING) {
2114            continue;
2115        }
2116        if (!assets->isJavaSymbol(sym, includePrivate)) {
2117            continue;
2118        }
2119        String8 name8(sym.name);
2120        String16 comment(sym.comment);
2121        AnnotationProcessor ann;
2122        if (comment.size() > 0) {
2123            String8 cmt(comment);
2124            ann.preprocessComment(cmt);
2125            fprintf(fp,
2126                    "%s/** %s\n"
2127                     "%s */\n",
2128                    getIndentSpace(indent), cmt.string(),
2129                    getIndentSpace(indent));
2130        } else if (sym.isPublic && !includePrivate) {
2131            sym.sourcePos.warning("No comment for public symbol %s:%s/%s",
2132                assets->getPackage().string(), className.string(),
2133                String8(sym.name).string());
2134        }
2135        ann.printAnnotations(fp, getIndentSpace(indent));
2136        fprintf(fp, "%spublic static final String %s=\"%s\";\n",
2137                getIndentSpace(indent),
2138                flattenSymbol(name8).string(), sym.stringVal.string());
2139    }
2140
2141    sp<AaptSymbols> styleableSymbols;
2142
2143    N = symbols->getNestedSymbols().size();
2144    for (i=0; i<N; i++) {
2145        sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2146        String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2147        if (nclassName == "styleable") {
2148            styleableSymbols = nsymbols;
2149        } else {
2150            err = writeSymbolClass(fp, assets, includePrivate, nsymbols, nclassName, indent, nonConstantId);
2151        }
2152        if (err != NO_ERROR) {
2153            return err;
2154        }
2155    }
2156
2157    if (styleableSymbols != NULL) {
2158        err = writeLayoutClasses(fp, assets, styleableSymbols, indent, includePrivate);
2159        if (err != NO_ERROR) {
2160            return err;
2161        }
2162    }
2163
2164    indent--;
2165    fprintf(fp, "%s}\n", getIndentSpace(indent));
2166    return NO_ERROR;
2167}
2168
2169static status_t writeTextSymbolClass(
2170    FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2171    const sp<AaptSymbols>& symbols, const String8& className)
2172{
2173    size_t i;
2174    status_t err = NO_ERROR;
2175
2176    size_t N = symbols->getSymbols().size();
2177    for (i=0; i<N; i++) {
2178        const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2179        if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
2180            continue;
2181        }
2182
2183        if (!assets->isJavaSymbol(sym, includePrivate)) {
2184            continue;
2185        }
2186
2187        String8 name8(sym.name);
2188        fprintf(fp, "int %s %s 0x%08x\n",
2189                className.string(),
2190                flattenSymbol(name8).string(), (int)sym.int32Val);
2191    }
2192
2193    N = symbols->getNestedSymbols().size();
2194    for (i=0; i<N; i++) {
2195        sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2196        String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2197        if (nclassName == "styleable") {
2198            err = writeTextLayoutClasses(fp, assets, nsymbols, includePrivate);
2199        } else {
2200            err = writeTextSymbolClass(fp, assets, includePrivate, nsymbols, nclassName);
2201        }
2202        if (err != NO_ERROR) {
2203            return err;
2204        }
2205    }
2206
2207    return NO_ERROR;
2208}
2209
2210status_t writeResourceSymbols(Bundle* bundle, const sp<AaptAssets>& assets,
2211    const String8& package, bool includePrivate)
2212{
2213    if (!bundle->getRClassDir()) {
2214        return NO_ERROR;
2215    }
2216
2217    const char* textSymbolsDest = bundle->getOutputTextSymbols();
2218
2219    String8 R("R");
2220    const size_t N = assets->getSymbols().size();
2221    for (size_t i=0; i<N; i++) {
2222        sp<AaptSymbols> symbols = assets->getSymbols().valueAt(i);
2223        String8 className(assets->getSymbols().keyAt(i));
2224        String8 dest(bundle->getRClassDir());
2225
2226        if (bundle->getMakePackageDirs()) {
2227            String8 pkg(package);
2228            const char* last = pkg.string();
2229            const char* s = last-1;
2230            do {
2231                s++;
2232                if (s > last && (*s == '.' || *s == 0)) {
2233                    String8 part(last, s-last);
2234                    dest.appendPath(part);
2235#ifdef HAVE_MS_C_RUNTIME
2236                    _mkdir(dest.string());
2237#else
2238                    mkdir(dest.string(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP);
2239#endif
2240                    last = s+1;
2241                }
2242            } while (*s);
2243        }
2244        dest.appendPath(className);
2245        dest.append(".java");
2246        FILE* fp = fopen(dest.string(), "w+");
2247        if (fp == NULL) {
2248            fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
2249                    dest.string(), strerror(errno));
2250            return UNKNOWN_ERROR;
2251        }
2252        if (bundle->getVerbose()) {
2253            printf("  Writing symbols for class %s.\n", className.string());
2254        }
2255
2256        fprintf(fp,
2257            "/* AUTO-GENERATED FILE.  DO NOT MODIFY.\n"
2258            " *\n"
2259            " * This class was automatically generated by the\n"
2260            " * aapt tool from the resource data it found.  It\n"
2261            " * should not be modified by hand.\n"
2262            " */\n"
2263            "\n"
2264            "package %s;\n\n", package.string());
2265
2266        status_t err = writeSymbolClass(fp, assets, includePrivate, symbols,
2267                className, 0, bundle->getNonConstantId());
2268        fclose(fp);
2269        if (err != NO_ERROR) {
2270            return err;
2271        }
2272
2273        if (textSymbolsDest != NULL && R == className) {
2274            String8 textDest(textSymbolsDest);
2275            textDest.appendPath(className);
2276            textDest.append(".txt");
2277
2278            FILE* fp = fopen(textDest.string(), "w+");
2279            if (fp == NULL) {
2280                fprintf(stderr, "ERROR: Unable to open text symbol file %s: %s\n",
2281                        textDest.string(), strerror(errno));
2282                return UNKNOWN_ERROR;
2283            }
2284            if (bundle->getVerbose()) {
2285                printf("  Writing text symbols for class %s.\n", className.string());
2286            }
2287
2288            status_t err = writeTextSymbolClass(fp, assets, includePrivate, symbols,
2289                    className);
2290            fclose(fp);
2291            if (err != NO_ERROR) {
2292                return err;
2293            }
2294        }
2295
2296        // If we were asked to generate a dependency file, we'll go ahead and add this R.java
2297        // as a target in the dependency file right next to it.
2298        if (bundle->getGenDependencies() && R == className) {
2299            // Add this R.java to the dependency file
2300            String8 dependencyFile(bundle->getRClassDir());
2301            dependencyFile.appendPath("R.java.d");
2302
2303            FILE *fp = fopen(dependencyFile.string(), "a");
2304            fprintf(fp,"%s \\\n", dest.string());
2305            fclose(fp);
2306        }
2307    }
2308
2309    return NO_ERROR;
2310}
2311
2312
2313class ProguardKeepSet
2314{
2315public:
2316    // { rule --> { file locations } }
2317    KeyedVector<String8, SortedVector<String8> > rules;
2318
2319    void add(const String8& rule, const String8& where);
2320};
2321
2322void ProguardKeepSet::add(const String8& rule, const String8& where)
2323{
2324    ssize_t index = rules.indexOfKey(rule);
2325    if (index < 0) {
2326        index = rules.add(rule, SortedVector<String8>());
2327    }
2328    rules.editValueAt(index).add(where);
2329}
2330
2331void
2332addProguardKeepRule(ProguardKeepSet* keep, const String8& inClassName,
2333        const char* pkg, const String8& srcName, int line)
2334{
2335    String8 className(inClassName);
2336    if (pkg != NULL) {
2337        // asdf     --> package.asdf
2338        // .asdf  .a.b  --> package.asdf package.a.b
2339        // asdf.adsf --> asdf.asdf
2340        const char* p = className.string();
2341        const char* q = strchr(p, '.');
2342        if (p == q) {
2343            className = pkg;
2344            className.append(inClassName);
2345        } else if (q == NULL) {
2346            className = pkg;
2347            className.append(".");
2348            className.append(inClassName);
2349        }
2350    }
2351
2352    String8 rule("-keep class ");
2353    rule += className;
2354    rule += " { <init>(...); }";
2355
2356    String8 location("view ");
2357    location += srcName;
2358    char lineno[20];
2359    sprintf(lineno, ":%d", line);
2360    location += lineno;
2361
2362    keep->add(rule, location);
2363}
2364
2365void
2366addProguardKeepMethodRule(ProguardKeepSet* keep, const String8& memberName,
2367        const char* pkg, const String8& srcName, int line)
2368{
2369    String8 rule("-keepclassmembers class * { *** ");
2370    rule += memberName;
2371    rule += "(...); }";
2372
2373    String8 location("onClick ");
2374    location += srcName;
2375    char lineno[20];
2376    sprintf(lineno, ":%d", line);
2377    location += lineno;
2378
2379    keep->add(rule, location);
2380}
2381
2382status_t
2383writeProguardForAndroidManifest(ProguardKeepSet* keep, const sp<AaptAssets>& assets)
2384{
2385    status_t err;
2386    ResXMLTree tree;
2387    size_t len;
2388    ResXMLTree::event_code_t code;
2389    int depth = 0;
2390    bool inApplication = false;
2391    String8 error;
2392    sp<AaptGroup> assGroup;
2393    sp<AaptFile> assFile;
2394    String8 pkg;
2395
2396    // First, look for a package file to parse.  This is required to
2397    // be able to generate the resource information.
2398    assGroup = assets->getFiles().valueFor(String8("AndroidManifest.xml"));
2399    if (assGroup == NULL) {
2400        fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n");
2401        return -1;
2402    }
2403
2404    if (assGroup->getFiles().size() != 1) {
2405        fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
2406                assGroup->getFiles().valueAt(0)->getPrintableSource().string());
2407    }
2408
2409    assFile = assGroup->getFiles().valueAt(0);
2410
2411    err = parseXMLResource(assFile, &tree);
2412    if (err != NO_ERROR) {
2413        return err;
2414    }
2415
2416    tree.restart();
2417
2418    while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
2419        if (code == ResXMLTree::END_TAG) {
2420            if (/* name == "Application" && */ depth == 2) {
2421                inApplication = false;
2422            }
2423            depth--;
2424            continue;
2425        }
2426        if (code != ResXMLTree::START_TAG) {
2427            continue;
2428        }
2429        depth++;
2430        String8 tag(tree.getElementName(&len));
2431        // printf("Depth %d tag %s\n", depth, tag.string());
2432        bool keepTag = false;
2433        if (depth == 1) {
2434            if (tag != "manifest") {
2435                fprintf(stderr, "ERROR: manifest does not start with <manifest> tag\n");
2436                return -1;
2437            }
2438            pkg = getAttribute(tree, NULL, "package", NULL);
2439        } else if (depth == 2) {
2440            if (tag == "application") {
2441                inApplication = true;
2442                keepTag = true;
2443
2444                String8 agent = getAttribute(tree, "http://schemas.android.com/apk/res/android",
2445                        "backupAgent", &error);
2446                if (agent.length() > 0) {
2447                    addProguardKeepRule(keep, agent, pkg.string(),
2448                            assFile->getPrintableSource(), tree.getLineNumber());
2449                }
2450            } else if (tag == "instrumentation") {
2451                keepTag = true;
2452            }
2453        }
2454        if (!keepTag && inApplication && depth == 3) {
2455            if (tag == "activity" || tag == "service" || tag == "receiver" || tag == "provider") {
2456                keepTag = true;
2457            }
2458        }
2459        if (keepTag) {
2460            String8 name = getAttribute(tree, "http://schemas.android.com/apk/res/android",
2461                    "name", &error);
2462            if (error != "") {
2463                fprintf(stderr, "ERROR: %s\n", error.string());
2464                return -1;
2465            }
2466            if (name.length() > 0) {
2467                addProguardKeepRule(keep, name, pkg.string(),
2468                        assFile->getPrintableSource(), tree.getLineNumber());
2469            }
2470        }
2471    }
2472
2473    return NO_ERROR;
2474}
2475
2476struct NamespaceAttributePair {
2477    const char* ns;
2478    const char* attr;
2479
2480    NamespaceAttributePair(const char* n, const char* a) : ns(n), attr(a) {}
2481    NamespaceAttributePair() : ns(NULL), attr(NULL) {}
2482};
2483
2484status_t
2485writeProguardForXml(ProguardKeepSet* keep, const sp<AaptFile>& layoutFile,
2486        const Vector<String8>& startTags, const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs)
2487{
2488    status_t err;
2489    ResXMLTree tree;
2490    size_t len;
2491    ResXMLTree::event_code_t code;
2492
2493    err = parseXMLResource(layoutFile, &tree);
2494    if (err != NO_ERROR) {
2495        return err;
2496    }
2497
2498    tree.restart();
2499
2500    if (!startTags.isEmpty()) {
2501        bool haveStart = false;
2502        while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
2503            if (code != ResXMLTree::START_TAG) {
2504                continue;
2505            }
2506            String8 tag(tree.getElementName(&len));
2507            const size_t numStartTags = startTags.size();
2508            for (size_t i = 0; i < numStartTags; i++) {
2509                if (tag == startTags[i]) {
2510                    haveStart = true;
2511                }
2512            }
2513            break;
2514        }
2515        if (!haveStart) {
2516            return NO_ERROR;
2517        }
2518    }
2519
2520    while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
2521        if (code != ResXMLTree::START_TAG) {
2522            continue;
2523        }
2524        String8 tag(tree.getElementName(&len));
2525
2526        // If there is no '.', we'll assume that it's one of the built in names.
2527        if (strchr(tag.string(), '.')) {
2528            addProguardKeepRule(keep, tag, NULL,
2529                    layoutFile->getPrintableSource(), tree.getLineNumber());
2530        } else if (tagAttrPairs != NULL) {
2531            ssize_t tagIndex = tagAttrPairs->indexOfKey(tag);
2532            if (tagIndex >= 0) {
2533                const Vector<NamespaceAttributePair>& nsAttrVector = tagAttrPairs->valueAt(tagIndex);
2534                for (size_t i = 0; i < nsAttrVector.size(); i++) {
2535                    const NamespaceAttributePair& nsAttr = nsAttrVector[i];
2536
2537                    ssize_t attrIndex = tree.indexOfAttribute(nsAttr.ns, nsAttr.attr);
2538                    if (attrIndex < 0) {
2539                        // fprintf(stderr, "%s:%d: <%s> does not have attribute %s:%s.\n",
2540                        //        layoutFile->getPrintableSource().string(), tree.getLineNumber(),
2541                        //        tag.string(), nsAttr.ns, nsAttr.attr);
2542                    } else {
2543                        size_t len;
2544                        addProguardKeepRule(keep,
2545                                            String8(tree.getAttributeStringValue(attrIndex, &len)), NULL,
2546                                            layoutFile->getPrintableSource(), tree.getLineNumber());
2547                    }
2548                }
2549            }
2550        }
2551        ssize_t attrIndex = tree.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "onClick");
2552        if (attrIndex >= 0) {
2553            size_t len;
2554            addProguardKeepMethodRule(keep,
2555                                String8(tree.getAttributeStringValue(attrIndex, &len)), NULL,
2556                                layoutFile->getPrintableSource(), tree.getLineNumber());
2557        }
2558    }
2559
2560    return NO_ERROR;
2561}
2562
2563static void addTagAttrPair(KeyedVector<String8, Vector<NamespaceAttributePair> >* dest,
2564        const char* tag, const char* ns, const char* attr) {
2565    String8 tagStr(tag);
2566    ssize_t index = dest->indexOfKey(tagStr);
2567
2568    if (index < 0) {
2569        Vector<NamespaceAttributePair> vector;
2570        vector.add(NamespaceAttributePair(ns, attr));
2571        dest->add(tagStr, vector);
2572    } else {
2573        dest->editValueAt(index).add(NamespaceAttributePair(ns, attr));
2574    }
2575}
2576
2577status_t
2578writeProguardForLayouts(ProguardKeepSet* keep, const sp<AaptAssets>& assets)
2579{
2580    status_t err;
2581
2582    // tag:attribute pairs that should be checked in layout files.
2583    KeyedVector<String8, Vector<NamespaceAttributePair> > kLayoutTagAttrPairs;
2584    addTagAttrPair(&kLayoutTagAttrPairs, "view", NULL, "class");
2585    addTagAttrPair(&kLayoutTagAttrPairs, "fragment", NULL, "class");
2586    addTagAttrPair(&kLayoutTagAttrPairs, "fragment", RESOURCES_ANDROID_NAMESPACE, "name");
2587
2588    // tag:attribute pairs that should be checked in xml files.
2589    KeyedVector<String8, Vector<NamespaceAttributePair> > kXmlTagAttrPairs;
2590    addTagAttrPair(&kXmlTagAttrPairs, "PreferenceScreen", RESOURCES_ANDROID_NAMESPACE, "fragment");
2591    addTagAttrPair(&kXmlTagAttrPairs, "header", RESOURCES_ANDROID_NAMESPACE, "fragment");
2592
2593    const Vector<sp<AaptDir> >& dirs = assets->resDirs();
2594    const size_t K = dirs.size();
2595    for (size_t k=0; k<K; k++) {
2596        const sp<AaptDir>& d = dirs.itemAt(k);
2597        const String8& dirName = d->getLeaf();
2598        Vector<String8> startTags;
2599        const char* startTag = NULL;
2600        const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs = NULL;
2601        if ((dirName == String8("layout")) || (strncmp(dirName.string(), "layout-", 7) == 0)) {
2602            tagAttrPairs = &kLayoutTagAttrPairs;
2603        } else if ((dirName == String8("xml")) || (strncmp(dirName.string(), "xml-", 4) == 0)) {
2604            startTags.add(String8("PreferenceScreen"));
2605            startTags.add(String8("preference-headers"));
2606            tagAttrPairs = &kXmlTagAttrPairs;
2607        } else if ((dirName == String8("menu")) || (strncmp(dirName.string(), "menu-", 5) == 0)) {
2608            startTags.add(String8("menu"));
2609            tagAttrPairs = NULL;
2610        } else {
2611            continue;
2612        }
2613
2614        const KeyedVector<String8,sp<AaptGroup> > groups = d->getFiles();
2615        const size_t N = groups.size();
2616        for (size_t i=0; i<N; i++) {
2617            const sp<AaptGroup>& group = groups.valueAt(i);
2618            const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files = group->getFiles();
2619            const size_t M = files.size();
2620            for (size_t j=0; j<M; j++) {
2621                err = writeProguardForXml(keep, files.valueAt(j), startTags, tagAttrPairs);
2622                if (err < 0) {
2623                    return err;
2624                }
2625            }
2626        }
2627    }
2628    // Handle the overlays
2629    sp<AaptAssets> overlay = assets->getOverlay();
2630    if (overlay.get()) {
2631        return writeProguardForLayouts(keep, overlay);
2632    }
2633
2634    return NO_ERROR;
2635}
2636
2637status_t
2638writeProguardFile(Bundle* bundle, const sp<AaptAssets>& assets)
2639{
2640    status_t err = -1;
2641
2642    if (!bundle->getProguardFile()) {
2643        return NO_ERROR;
2644    }
2645
2646    ProguardKeepSet keep;
2647
2648    err = writeProguardForAndroidManifest(&keep, assets);
2649    if (err < 0) {
2650        return err;
2651    }
2652
2653    err = writeProguardForLayouts(&keep, assets);
2654    if (err < 0) {
2655        return err;
2656    }
2657
2658    FILE* fp = fopen(bundle->getProguardFile(), "w+");
2659    if (fp == NULL) {
2660        fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
2661                bundle->getProguardFile(), strerror(errno));
2662        return UNKNOWN_ERROR;
2663    }
2664
2665    const KeyedVector<String8, SortedVector<String8> >& rules = keep.rules;
2666    const size_t N = rules.size();
2667    for (size_t i=0; i<N; i++) {
2668        const SortedVector<String8>& locations = rules.valueAt(i);
2669        const size_t M = locations.size();
2670        for (size_t j=0; j<M; j++) {
2671            fprintf(fp, "# %s\n", locations.itemAt(j).string());
2672        }
2673        fprintf(fp, "%s\n\n", rules.keyAt(i).string());
2674    }
2675    fclose(fp);
2676
2677    return err;
2678}
2679
2680// Loops through the string paths and writes them to the file pointer
2681// Each file path is written on its own line with a terminating backslash.
2682status_t writePathsToFile(const sp<FilePathStore>& files, FILE* fp)
2683{
2684    status_t deps = -1;
2685    for (size_t file_i = 0; file_i < files->size(); ++file_i) {
2686        // Add the full file path to the dependency file
2687        fprintf(fp, "%s \\\n", files->itemAt(file_i).string());
2688        deps++;
2689    }
2690    return deps;
2691}
2692
2693status_t
2694writeDependencyPreReqs(Bundle* bundle, const sp<AaptAssets>& assets, FILE* fp, bool includeRaw)
2695{
2696    status_t deps = -1;
2697    deps += writePathsToFile(assets->getFullResPaths(), fp);
2698    if (includeRaw) {
2699        deps += writePathsToFile(assets->getFullAssetPaths(), fp);
2700    }
2701    return deps;
2702}
2703