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