Resource.cpp revision 83f4c0994fd34f9b35eeb2c14908d9e6c2e15930
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                             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 = UNKNOWN_ERROR;
479                if (baseSet->get() != NULL) {
480                    baseIndex = (*baseSet)->indexOfKey(overlaySet->keyAt(overlayIndex));
481                }
482                if (baseIndex < UNKNOWN_ERROR) {
483                    // look for same flavor.  For a given file (strings.xml, for example)
484                    // there may be a locale specific or other flavors - we want to match
485                    // the same flavor.
486                    sp<AaptGroup> overlayGroup = overlaySet->valueAt(overlayIndex);
487                    sp<AaptGroup> baseGroup = (*baseSet)->valueAt(baseIndex);
488
489                    DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > overlayFiles =
490                            overlayGroup->getFiles();
491                    if (bundle->getVerbose()) {
492                        DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > baseFiles =
493                                baseGroup->getFiles();
494                        for (size_t i=0; i < baseFiles.size(); i++) {
495                            printf("baseFile %ld has flavor %s\n", i,
496                                    baseFiles.keyAt(i).toString().string());
497                        }
498                        for (size_t i=0; i < overlayFiles.size(); i++) {
499                            printf("overlayFile %ld has flavor %s\n", i,
500                                    overlayFiles.keyAt(i).toString().string());
501                        }
502                    }
503
504                    size_t overlayGroupSize = overlayFiles.size();
505                    for (size_t overlayGroupIndex = 0;
506                            overlayGroupIndex<overlayGroupSize;
507                            overlayGroupIndex++) {
508                        size_t baseFileIndex =
509                                baseGroup->getFiles().indexOfKey(overlayFiles.
510                                keyAt(overlayGroupIndex));
511                        if(baseFileIndex < UNKNOWN_ERROR) {
512                            if (bundle->getVerbose()) {
513                                printf("found a match (%ld) for overlay file %s, for flavor %s\n",
514                                        baseFileIndex,
515                                        overlayGroup->getLeaf().string(),
516                                        overlayFiles.keyAt(overlayGroupIndex).toString().string());
517                            }
518                            baseGroup->removeFile(baseFileIndex);
519                        } else {
520                            // didn't find a match fall through and add it..
521                        }
522                        baseGroup->addFile(overlayFiles.valueAt(overlayGroupIndex));
523                        assets->addGroupEntry(overlayFiles.keyAt(overlayGroupIndex));
524                    }
525                } else {
526                    if (baseSet->get() == NULL) {
527                        *baseSet = new ResourceTypeSet();
528                        assets->getResources()->add(String8(resType), *baseSet);
529                    }
530                    // this group doesn't exist (a file that's only in the overlay)
531                    (*baseSet)->add(overlaySet->keyAt(overlayIndex),
532                            overlaySet->valueAt(overlayIndex));
533                    // make sure all flavors are defined in the resources.
534                    sp<AaptGroup> overlayGroup = overlaySet->valueAt(overlayIndex);
535                    DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > overlayFiles =
536                            overlayGroup->getFiles();
537                    size_t overlayGroupSize = overlayFiles.size();
538                    for (size_t overlayGroupIndex = 0;
539                            overlayGroupIndex<overlayGroupSize;
540                            overlayGroupIndex++) {
541                        assets->addGroupEntry(overlayFiles.keyAt(overlayGroupIndex));
542                    }
543                }
544            }
545            // this overlay didn't have resources for this type
546        }
547        // try next overlay
548        overlay = overlay->getOverlay();
549    }
550    return true;
551}
552
553void addTagAttribute(const sp<XMLNode>& node, const char* ns8,
554        const char* attr8, const char* value)
555{
556    if (value == NULL) {
557        return;
558    }
559
560    const String16 ns(ns8);
561    const String16 attr(attr8);
562
563    if (node->getAttribute(ns, attr) != NULL) {
564        fprintf(stderr, "Warning: AndroidManifest.xml already defines %s (in %s)\n",
565                String8(attr).string(), String8(ns).string());
566        return;
567    }
568
569    node->addAttribute(ns, attr, String16(value));
570}
571
572static void fullyQualifyClassName(const String8& package, sp<XMLNode> node,
573        const String16& attrName) {
574    XMLNode::attribute_entry* attr = node->editAttribute(
575            String16("http://schemas.android.com/apk/res/android"), attrName);
576    if (attr != NULL) {
577        String8 name(attr->string);
578
579        // asdf     --> package.asdf
580        // .asdf  .a.b  --> package.asdf package.a.b
581        // asdf.adsf --> asdf.asdf
582        String8 className;
583        const char* p = name.string();
584        const char* q = strchr(p, '.');
585        if (p == q) {
586            className += package;
587            className += name;
588        } else if (q == NULL) {
589            className += package;
590            className += ".";
591            className += name;
592        } else {
593            className += name;
594        }
595        NOISY(printf("Qualifying class '%s' to '%s'", name.string(), className.string()));
596        attr->string.setTo(String16(className));
597    }
598}
599
600status_t massageManifest(Bundle* bundle, sp<XMLNode> root)
601{
602    root = root->searchElement(String16(), String16("manifest"));
603    if (root == NULL) {
604        fprintf(stderr, "No <manifest> tag.\n");
605        return UNKNOWN_ERROR;
606    }
607
608    addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionCode",
609            bundle->getVersionCode());
610    addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionName",
611            bundle->getVersionName());
612
613    if (bundle->getMinSdkVersion() != NULL
614            || bundle->getTargetSdkVersion() != NULL
615            || bundle->getMaxSdkVersion() != NULL) {
616        sp<XMLNode> vers = root->getChildElement(String16(), String16("uses-sdk"));
617        if (vers == NULL) {
618            vers = XMLNode::newElement(root->getFilename(), String16(), String16("uses-sdk"));
619            root->insertChildAt(vers, 0);
620        }
621
622        addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "minSdkVersion",
623                bundle->getMinSdkVersion());
624        addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "targetSdkVersion",
625                bundle->getTargetSdkVersion());
626        addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "maxSdkVersion",
627                bundle->getMaxSdkVersion());
628    }
629
630    // Deal with manifest package name overrides
631    const char* manifestPackageNameOverride = bundle->getManifestPackageNameOverride();
632    if (manifestPackageNameOverride != NULL) {
633        // Update the actual package name
634        XMLNode::attribute_entry* attr = root->editAttribute(String16(), String16("package"));
635        if (attr == NULL) {
636            fprintf(stderr, "package name is required with --rename-manifest-package.\n");
637            return UNKNOWN_ERROR;
638        }
639        String8 origPackage(attr->string);
640        attr->string.setTo(String16(manifestPackageNameOverride));
641        NOISY(printf("Overriding package '%s' to be '%s'\n", origPackage.string(), manifestPackageNameOverride));
642
643        // Make class names fully qualified
644        sp<XMLNode> application = root->getChildElement(String16(), String16("application"));
645        if (application != NULL) {
646            fullyQualifyClassName(origPackage, application, String16("name"));
647            fullyQualifyClassName(origPackage, application, String16("backupAgent"));
648
649            Vector<sp<XMLNode> >& children = const_cast<Vector<sp<XMLNode> >&>(application->getChildren());
650            for (size_t i = 0; i < children.size(); i++) {
651                sp<XMLNode> child = children.editItemAt(i);
652                String8 tag(child->getElementName());
653                if (tag == "activity" || tag == "service" || tag == "receiver" || tag == "provider") {
654                    fullyQualifyClassName(origPackage, child, String16("name"));
655                } else if (tag == "activity-alias") {
656                    fullyQualifyClassName(origPackage, child, String16("name"));
657                    fullyQualifyClassName(origPackage, child, String16("targetActivity"));
658                }
659            }
660        }
661    }
662
663    // Deal with manifest package name overrides
664    const char* instrumentationPackageNameOverride = bundle->getInstrumentationPackageNameOverride();
665    if (instrumentationPackageNameOverride != NULL) {
666        // Fix up instrumentation targets.
667        Vector<sp<XMLNode> >& children = const_cast<Vector<sp<XMLNode> >&>(root->getChildren());
668        for (size_t i = 0; i < children.size(); i++) {
669            sp<XMLNode> child = children.editItemAt(i);
670            String8 tag(child->getElementName());
671            if (tag == "instrumentation") {
672                XMLNode::attribute_entry* attr = child->editAttribute(
673                        String16("http://schemas.android.com/apk/res/android"), String16("targetPackage"));
674                if (attr != NULL) {
675                    attr->string.setTo(String16(instrumentationPackageNameOverride));
676                }
677            }
678        }
679    }
680
681    return NO_ERROR;
682}
683
684#define ASSIGN_IT(n) \
685        do { \
686            ssize_t index = resources->indexOfKey(String8(#n)); \
687            if (index >= 0) { \
688                n ## s = resources->valueAt(index); \
689            } \
690        } while (0)
691
692status_t buildResources(Bundle* bundle, const sp<AaptAssets>& assets)
693{
694    // First, look for a package file to parse.  This is required to
695    // be able to generate the resource information.
696    sp<AaptGroup> androidManifestFile =
697            assets->getFiles().valueFor(String8("AndroidManifest.xml"));
698    if (androidManifestFile == NULL) {
699        fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n");
700        return UNKNOWN_ERROR;
701    }
702
703    status_t err = parsePackage(bundle, assets, androidManifestFile);
704    if (err != NO_ERROR) {
705        return err;
706    }
707
708    NOISY(printf("Creating resources for package %s\n",
709                 assets->getPackage().string()));
710
711    ResourceTable table(bundle, String16(assets->getPackage()));
712    err = table.addIncludedResources(bundle, assets);
713    if (err != NO_ERROR) {
714        return err;
715    }
716
717    NOISY(printf("Found %d included resource packages\n", (int)table.size()));
718
719    // Standard flags for compiled XML and optional UTF-8 encoding
720    int xmlFlags = XML_COMPILE_STANDARD_RESOURCE;
721    if (bundle->getUTF8()) {
722        xmlFlags |= XML_COMPILE_UTF8;
723    }
724
725    // --------------------------------------------------------------
726    // First, gather all resource information.
727    // --------------------------------------------------------------
728
729    // resType -> leafName -> group
730    KeyedVector<String8, sp<ResourceTypeSet> > *resources =
731            new KeyedVector<String8, sp<ResourceTypeSet> >;
732    collect_files(assets, resources);
733
734    sp<ResourceTypeSet> drawables;
735    sp<ResourceTypeSet> layouts;
736    sp<ResourceTypeSet> anims;
737    sp<ResourceTypeSet> xmls;
738    sp<ResourceTypeSet> raws;
739    sp<ResourceTypeSet> colors;
740    sp<ResourceTypeSet> menus;
741
742    ASSIGN_IT(drawable);
743    ASSIGN_IT(layout);
744    ASSIGN_IT(anim);
745    ASSIGN_IT(xml);
746    ASSIGN_IT(raw);
747    ASSIGN_IT(color);
748    ASSIGN_IT(menu);
749
750    assets->setResources(resources);
751    // now go through any resource overlays and collect their files
752    sp<AaptAssets> current = assets->getOverlay();
753    while(current.get()) {
754        KeyedVector<String8, sp<ResourceTypeSet> > *resources =
755                new KeyedVector<String8, sp<ResourceTypeSet> >;
756        current->setResources(resources);
757        collect_files(current, resources);
758        current = current->getOverlay();
759    }
760    // apply the overlay files to the base set
761    if (!applyFileOverlay(bundle, assets, &drawables, "drawable") ||
762            !applyFileOverlay(bundle, assets, &layouts, "layout") ||
763            !applyFileOverlay(bundle, assets, &anims, "anim") ||
764            !applyFileOverlay(bundle, assets, &xmls, "xml") ||
765            !applyFileOverlay(bundle, assets, &raws, "raw") ||
766            !applyFileOverlay(bundle, assets, &colors, "color") ||
767            !applyFileOverlay(bundle, assets, &menus, "menu")) {
768        return UNKNOWN_ERROR;
769    }
770
771    bool hasErrors = false;
772
773    if (drawables != NULL) {
774        err = preProcessImages(bundle, assets, drawables);
775        if (err == NO_ERROR) {
776            err = makeFileResources(bundle, assets, &table, drawables, "drawable");
777            if (err != NO_ERROR) {
778                hasErrors = true;
779            }
780        } else {
781            hasErrors = true;
782        }
783    }
784
785    if (layouts != NULL) {
786        err = makeFileResources(bundle, assets, &table, layouts, "layout");
787        if (err != NO_ERROR) {
788            hasErrors = true;
789        }
790    }
791
792    if (anims != NULL) {
793        err = makeFileResources(bundle, assets, &table, anims, "anim");
794        if (err != NO_ERROR) {
795            hasErrors = true;
796        }
797    }
798
799    if (xmls != NULL) {
800        err = makeFileResources(bundle, assets, &table, xmls, "xml");
801        if (err != NO_ERROR) {
802            hasErrors = true;
803        }
804    }
805
806    if (raws != NULL) {
807        err = makeFileResources(bundle, assets, &table, raws, "raw");
808        if (err != NO_ERROR) {
809            hasErrors = true;
810        }
811    }
812
813    // compile resources
814    current = assets;
815    while(current.get()) {
816        KeyedVector<String8, sp<ResourceTypeSet> > *resources =
817                current->getResources();
818
819        ssize_t index = resources->indexOfKey(String8("values"));
820        if (index >= 0) {
821            ResourceDirIterator it(resources->valueAt(index), String8("values"));
822            ssize_t res;
823            while ((res=it.next()) == NO_ERROR) {
824                sp<AaptFile> file = it.getFile();
825                res = compileResourceFile(bundle, assets, file, it.getParams(),
826                                          (current!=assets), &table);
827                if (res != NO_ERROR) {
828                    hasErrors = true;
829                }
830            }
831        }
832        current = current->getOverlay();
833    }
834
835    if (colors != NULL) {
836        err = makeFileResources(bundle, assets, &table, colors, "color");
837        if (err != NO_ERROR) {
838            hasErrors = true;
839        }
840    }
841
842    if (menus != NULL) {
843        err = makeFileResources(bundle, assets, &table, menus, "menu");
844        if (err != NO_ERROR) {
845            hasErrors = true;
846        }
847    }
848
849    // --------------------------------------------------------------------
850    // Assignment of resource IDs and initial generation of resource table.
851    // --------------------------------------------------------------------
852
853    if (table.hasResources()) {
854        sp<AaptFile> resFile(getResourceFile(assets));
855        if (resFile == NULL) {
856            fprintf(stderr, "Error: unable to generate entry for resource data\n");
857            return UNKNOWN_ERROR;
858        }
859
860        err = table.assignResourceIds();
861        if (err < NO_ERROR) {
862            return err;
863        }
864    }
865
866    // --------------------------------------------------------------
867    // Finally, we can now we can compile XML files, which may reference
868    // resources.
869    // --------------------------------------------------------------
870
871    if (layouts != NULL) {
872        ResourceDirIterator it(layouts, String8("layout"));
873        while ((err=it.next()) == NO_ERROR) {
874            String8 src = it.getFile()->getPrintableSource();
875            err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
876            if (err == NO_ERROR) {
877                ResXMLTree block;
878                block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
879                checkForIds(src, block);
880            } else {
881                hasErrors = true;
882            }
883        }
884
885        if (err < NO_ERROR) {
886            hasErrors = true;
887        }
888        err = NO_ERROR;
889    }
890
891    if (anims != NULL) {
892        ResourceDirIterator it(anims, String8("anim"));
893        while ((err=it.next()) == NO_ERROR) {
894            err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
895            if (err != NO_ERROR) {
896                hasErrors = true;
897            }
898        }
899
900        if (err < NO_ERROR) {
901            hasErrors = true;
902        }
903        err = NO_ERROR;
904    }
905
906    if (xmls != NULL) {
907        ResourceDirIterator it(xmls, String8("xml"));
908        while ((err=it.next()) == NO_ERROR) {
909            err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
910            if (err != NO_ERROR) {
911                hasErrors = true;
912            }
913        }
914
915        if (err < NO_ERROR) {
916            hasErrors = true;
917        }
918        err = NO_ERROR;
919    }
920
921    if (drawables != NULL) {
922        err = postProcessImages(assets, &table, drawables);
923        if (err != NO_ERROR) {
924            hasErrors = true;
925        }
926    }
927
928    if (colors != NULL) {
929        ResourceDirIterator it(colors, String8("color"));
930        while ((err=it.next()) == NO_ERROR) {
931          err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
932            if (err != NO_ERROR) {
933                hasErrors = true;
934            }
935        }
936
937        if (err < NO_ERROR) {
938            hasErrors = true;
939        }
940        err = NO_ERROR;
941    }
942
943    if (menus != NULL) {
944        ResourceDirIterator it(menus, String8("menu"));
945        while ((err=it.next()) == NO_ERROR) {
946            String8 src = it.getFile()->getPrintableSource();
947            err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
948            if (err != NO_ERROR) {
949                hasErrors = true;
950            }
951            ResXMLTree block;
952            block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
953            checkForIds(src, block);
954        }
955
956        if (err < NO_ERROR) {
957            hasErrors = true;
958        }
959        err = NO_ERROR;
960    }
961
962    const sp<AaptFile> manifestFile(androidManifestFile->getFiles().valueAt(0));
963    String8 manifestPath(manifestFile->getPrintableSource());
964
965    // Perform a basic validation of the manifest file.  This time we
966    // parse it with the comments intact, so that we can use them to
967    // generate java docs...  so we are not going to write this one
968    // back out to the final manifest data.
969    err = compileXmlFile(assets, manifestFile, &table,
970            XML_COMPILE_ASSIGN_ATTRIBUTE_IDS
971            | XML_COMPILE_STRIP_WHITESPACE | XML_COMPILE_STRIP_RAW_VALUES);
972    if (err < NO_ERROR) {
973        return err;
974    }
975    ResXMLTree block;
976    block.setTo(manifestFile->getData(), manifestFile->getSize(), true);
977    String16 manifest16("manifest");
978    String16 permission16("permission");
979    String16 permission_group16("permission-group");
980    String16 uses_permission16("uses-permission");
981    String16 instrumentation16("instrumentation");
982    String16 application16("application");
983    String16 provider16("provider");
984    String16 service16("service");
985    String16 receiver16("receiver");
986    String16 activity16("activity");
987    String16 action16("action");
988    String16 category16("category");
989    String16 data16("scheme");
990    const char* packageIdentChars = "abcdefghijklmnopqrstuvwxyz"
991        "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789";
992    const char* packageIdentCharsWithTheStupid = "abcdefghijklmnopqrstuvwxyz"
993        "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
994    const char* classIdentChars = "abcdefghijklmnopqrstuvwxyz"
995        "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789$";
996    const char* processIdentChars = "abcdefghijklmnopqrstuvwxyz"
997        "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:";
998    const char* authoritiesIdentChars = "abcdefghijklmnopqrstuvwxyz"
999        "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-:;";
1000    const char* typeIdentChars = "abcdefghijklmnopqrstuvwxyz"
1001        "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:-/*+";
1002    const char* schemeIdentChars = "abcdefghijklmnopqrstuvwxyz"
1003        "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
1004    ResXMLTree::event_code_t code;
1005    sp<AaptSymbols> permissionSymbols;
1006    sp<AaptSymbols> permissionGroupSymbols;
1007    while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1008           && code > ResXMLTree::BAD_DOCUMENT) {
1009        if (code == ResXMLTree::START_TAG) {
1010            size_t len;
1011            if (block.getElementNamespace(&len) != NULL) {
1012                continue;
1013            }
1014            if (strcmp16(block.getElementName(&len), manifest16.string()) == 0) {
1015                if (validateAttr(manifestPath, block, NULL, "package",
1016                                 packageIdentChars, true) != ATTR_OKAY) {
1017                    hasErrors = true;
1018                }
1019            } else if (strcmp16(block.getElementName(&len), permission16.string()) == 0
1020                    || strcmp16(block.getElementName(&len), permission_group16.string()) == 0) {
1021                const bool isGroup = strcmp16(block.getElementName(&len),
1022                        permission_group16.string()) == 0;
1023                if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
1024                                 isGroup ? packageIdentCharsWithTheStupid
1025                                 : packageIdentChars, true) != ATTR_OKAY) {
1026                    hasErrors = true;
1027                }
1028                SourcePos srcPos(manifestPath, block.getLineNumber());
1029                sp<AaptSymbols> syms;
1030                if (!isGroup) {
1031                    syms = permissionSymbols;
1032                    if (syms == NULL) {
1033                        sp<AaptSymbols> symbols =
1034                                assets->getSymbolsFor(String8("Manifest"));
1035                        syms = permissionSymbols = symbols->addNestedSymbol(
1036                                String8("permission"), srcPos);
1037                    }
1038                } else {
1039                    syms = permissionGroupSymbols;
1040                    if (syms == NULL) {
1041                        sp<AaptSymbols> symbols =
1042                                assets->getSymbolsFor(String8("Manifest"));
1043                        syms = permissionGroupSymbols = symbols->addNestedSymbol(
1044                                String8("permission_group"), srcPos);
1045                    }
1046                }
1047                size_t len;
1048                ssize_t index = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "name");
1049                const uint16_t* id = block.getAttributeStringValue(index, &len);
1050                if (id == NULL) {
1051                    fprintf(stderr, "%s:%d: missing name attribute in element <%s>.\n",
1052                            manifestPath.string(), block.getLineNumber(),
1053                            String8(block.getElementName(&len)).string());
1054                    hasErrors = true;
1055                    break;
1056                }
1057                String8 idStr(id);
1058                char* p = idStr.lockBuffer(idStr.size());
1059                char* e = p + idStr.size();
1060                bool begins_with_digit = true;  // init to true so an empty string fails
1061                while (e > p) {
1062                    e--;
1063                    if (*e >= '0' && *e <= '9') {
1064                      begins_with_digit = true;
1065                      continue;
1066                    }
1067                    if ((*e >= 'a' && *e <= 'z') ||
1068                        (*e >= 'A' && *e <= 'Z') ||
1069                        (*e == '_')) {
1070                      begins_with_digit = false;
1071                      continue;
1072                    }
1073                    if (isGroup && (*e == '-')) {
1074                        *e = '_';
1075                        begins_with_digit = false;
1076                        continue;
1077                    }
1078                    e++;
1079                    break;
1080                }
1081                idStr.unlockBuffer();
1082                // verify that we stopped because we hit a period or
1083                // the beginning of the string, and that the
1084                // identifier didn't begin with a digit.
1085                if (begins_with_digit || (e != p && *(e-1) != '.')) {
1086                  fprintf(stderr,
1087                          "%s:%d: Permission name <%s> is not a valid Java symbol\n",
1088                          manifestPath.string(), block.getLineNumber(), idStr.string());
1089                  hasErrors = true;
1090                }
1091                syms->addStringSymbol(String8(e), idStr, srcPos);
1092                const uint16_t* cmt = block.getComment(&len);
1093                if (cmt != NULL && *cmt != 0) {
1094                    //printf("Comment of %s: %s\n", String8(e).string(),
1095                    //        String8(cmt).string());
1096                    syms->appendComment(String8(e), String16(cmt), srcPos);
1097                } else {
1098                    //printf("No comment for %s\n", String8(e).string());
1099                }
1100                syms->makeSymbolPublic(String8(e), srcPos);
1101            } else if (strcmp16(block.getElementName(&len), uses_permission16.string()) == 0) {
1102                if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
1103                                 packageIdentChars, true) != ATTR_OKAY) {
1104                    hasErrors = true;
1105                }
1106            } else if (strcmp16(block.getElementName(&len), instrumentation16.string()) == 0) {
1107                if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
1108                                 classIdentChars, true) != ATTR_OKAY) {
1109                    hasErrors = true;
1110                }
1111                if (validateAttr(manifestPath, block,
1112                                 RESOURCES_ANDROID_NAMESPACE, "targetPackage",
1113                                 packageIdentChars, true) != ATTR_OKAY) {
1114                    hasErrors = true;
1115                }
1116            } else if (strcmp16(block.getElementName(&len), application16.string()) == 0) {
1117                if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
1118                                 classIdentChars, false) != ATTR_OKAY) {
1119                    hasErrors = true;
1120                }
1121                if (validateAttr(manifestPath, block,
1122                                 RESOURCES_ANDROID_NAMESPACE, "permission",
1123                                 packageIdentChars, false) != ATTR_OKAY) {
1124                    hasErrors = true;
1125                }
1126                if (validateAttr(manifestPath, block,
1127                                 RESOURCES_ANDROID_NAMESPACE, "process",
1128                                 processIdentChars, false) != ATTR_OKAY) {
1129                    hasErrors = true;
1130                }
1131                if (validateAttr(manifestPath, block,
1132                                 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
1133                                 processIdentChars, false) != ATTR_OKAY) {
1134                    hasErrors = true;
1135                }
1136            } else if (strcmp16(block.getElementName(&len), provider16.string()) == 0) {
1137                if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
1138                                 classIdentChars, true) != ATTR_OKAY) {
1139                    hasErrors = true;
1140                }
1141                if (validateAttr(manifestPath, block,
1142                                 RESOURCES_ANDROID_NAMESPACE, "authorities",
1143                                 authoritiesIdentChars, true) != ATTR_OKAY) {
1144                    hasErrors = true;
1145                }
1146                if (validateAttr(manifestPath, block,
1147                                 RESOURCES_ANDROID_NAMESPACE, "permission",
1148                                 packageIdentChars, false) != ATTR_OKAY) {
1149                    hasErrors = true;
1150                }
1151                if (validateAttr(manifestPath, block,
1152                                 RESOURCES_ANDROID_NAMESPACE, "process",
1153                                 processIdentChars, false) != ATTR_OKAY) {
1154                    hasErrors = true;
1155                }
1156            } else if (strcmp16(block.getElementName(&len), service16.string()) == 0
1157                       || strcmp16(block.getElementName(&len), receiver16.string()) == 0
1158                       || strcmp16(block.getElementName(&len), activity16.string()) == 0) {
1159                if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
1160                                 classIdentChars, true) != ATTR_OKAY) {
1161                    hasErrors = true;
1162                }
1163                if (validateAttr(manifestPath, block,
1164                                 RESOURCES_ANDROID_NAMESPACE, "permission",
1165                                 packageIdentChars, false) != ATTR_OKAY) {
1166                    hasErrors = true;
1167                }
1168                if (validateAttr(manifestPath, block,
1169                                 RESOURCES_ANDROID_NAMESPACE, "process",
1170                                 processIdentChars, false) != ATTR_OKAY) {
1171                    hasErrors = true;
1172                }
1173                if (validateAttr(manifestPath, block,
1174                                 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
1175                                 processIdentChars, false) != ATTR_OKAY) {
1176                    hasErrors = true;
1177                }
1178            } else if (strcmp16(block.getElementName(&len), action16.string()) == 0
1179                       || strcmp16(block.getElementName(&len), category16.string()) == 0) {
1180                if (validateAttr(manifestPath, block,
1181                                 RESOURCES_ANDROID_NAMESPACE, "name",
1182                                 packageIdentChars, true) != ATTR_OKAY) {
1183                    hasErrors = true;
1184                }
1185            } else if (strcmp16(block.getElementName(&len), data16.string()) == 0) {
1186                if (validateAttr(manifestPath, block,
1187                                 RESOURCES_ANDROID_NAMESPACE, "mimeType",
1188                                 typeIdentChars, true) != ATTR_OKAY) {
1189                    hasErrors = true;
1190                }
1191                if (validateAttr(manifestPath, block,
1192                                 RESOURCES_ANDROID_NAMESPACE, "scheme",
1193                                 schemeIdentChars, true) != ATTR_OKAY) {
1194                    hasErrors = true;
1195                }
1196            }
1197        }
1198    }
1199
1200    if (table.validateLocalizations()) {
1201        hasErrors = true;
1202    }
1203
1204    if (hasErrors) {
1205        return UNKNOWN_ERROR;
1206    }
1207
1208    // Generate final compiled manifest file.
1209    manifestFile->clearData();
1210    sp<XMLNode> manifestTree = XMLNode::parse(manifestFile);
1211    if (manifestTree == NULL) {
1212        return UNKNOWN_ERROR;
1213    }
1214    err = massageManifest(bundle, manifestTree);
1215    if (err < NO_ERROR) {
1216        return err;
1217    }
1218    err = compileXmlFile(assets, manifestTree, manifestFile, &table);
1219    if (err < NO_ERROR) {
1220        return err;
1221    }
1222
1223    //block.restart();
1224    //printXMLBlock(&block);
1225
1226    // --------------------------------------------------------------
1227    // Generate the final resource table.
1228    // Re-flatten because we may have added new resource IDs
1229    // --------------------------------------------------------------
1230
1231    if (table.hasResources()) {
1232        sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1233        err = table.addSymbols(symbols);
1234        if (err < NO_ERROR) {
1235            return err;
1236        }
1237
1238        sp<AaptFile> resFile(getResourceFile(assets));
1239        if (resFile == NULL) {
1240            fprintf(stderr, "Error: unable to generate entry for resource data\n");
1241            return UNKNOWN_ERROR;
1242        }
1243
1244        err = table.flatten(bundle, resFile);
1245        if (err < NO_ERROR) {
1246            return err;
1247        }
1248
1249        if (bundle->getPublicOutputFile()) {
1250            FILE* fp = fopen(bundle->getPublicOutputFile(), "w+");
1251            if (fp == NULL) {
1252                fprintf(stderr, "ERROR: Unable to open public definitions output file %s: %s\n",
1253                        (const char*)bundle->getPublicOutputFile(), strerror(errno));
1254                return UNKNOWN_ERROR;
1255            }
1256            if (bundle->getVerbose()) {
1257                printf("  Writing public definitions to %s.\n", bundle->getPublicOutputFile());
1258            }
1259            table.writePublicDefinitions(String16(assets->getPackage()), fp);
1260            fclose(fp);
1261        }
1262#if 0
1263        NOISY(
1264              ResTable rt;
1265              rt.add(resFile->getData(), resFile->getSize(), NULL);
1266              printf("Generated resources:\n");
1267              rt.print();
1268        )
1269#endif
1270        // These resources are now considered to be a part of the included
1271        // resources, for others to reference.
1272        err = assets->addIncludedResources(resFile);
1273        if (err < NO_ERROR) {
1274            fprintf(stderr, "ERROR: Unable to parse generated resources, aborting.\n");
1275            return err;
1276        }
1277    }
1278    return err;
1279}
1280
1281static const char* getIndentSpace(int indent)
1282{
1283static const char whitespace[] =
1284"                                                                                       ";
1285
1286    return whitespace + sizeof(whitespace) - 1 - indent*4;
1287}
1288
1289static status_t fixupSymbol(String16* inoutSymbol)
1290{
1291    inoutSymbol->replaceAll('.', '_');
1292    inoutSymbol->replaceAll(':', '_');
1293    return NO_ERROR;
1294}
1295
1296static String16 getAttributeComment(const sp<AaptAssets>& assets,
1297                                    const String8& name,
1298                                    String16* outTypeComment = NULL)
1299{
1300    sp<AaptSymbols> asym = assets->getSymbolsFor(String8("R"));
1301    if (asym != NULL) {
1302        //printf("Got R symbols!\n");
1303        asym = asym->getNestedSymbols().valueFor(String8("attr"));
1304        if (asym != NULL) {
1305            //printf("Got attrs symbols! comment %s=%s\n",
1306            //     name.string(), String8(asym->getComment(name)).string());
1307            if (outTypeComment != NULL) {
1308                *outTypeComment = asym->getTypeComment(name);
1309            }
1310            return asym->getComment(name);
1311        }
1312    }
1313    return String16();
1314}
1315
1316static status_t writeLayoutClasses(
1317    FILE* fp, const sp<AaptAssets>& assets,
1318    const sp<AaptSymbols>& symbols, int indent, bool includePrivate)
1319{
1320    const char* indentStr = getIndentSpace(indent);
1321    if (!includePrivate) {
1322        fprintf(fp, "%s/** @doconly */\n", indentStr);
1323    }
1324    fprintf(fp, "%spublic static final class styleable {\n", indentStr);
1325    indent++;
1326
1327    String16 attr16("attr");
1328    String16 package16(assets->getPackage());
1329
1330    indentStr = getIndentSpace(indent);
1331    bool hasErrors = false;
1332
1333    size_t i;
1334    size_t N = symbols->getNestedSymbols().size();
1335    for (i=0; i<N; i++) {
1336        sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
1337        String16 nclassName16(symbols->getNestedSymbols().keyAt(i));
1338        String8 realClassName(nclassName16);
1339        if (fixupSymbol(&nclassName16) != NO_ERROR) {
1340            hasErrors = true;
1341        }
1342        String8 nclassName(nclassName16);
1343
1344        SortedVector<uint32_t> idents;
1345        Vector<uint32_t> origOrder;
1346        Vector<bool> publicFlags;
1347
1348        size_t a;
1349        size_t NA = nsymbols->getSymbols().size();
1350        for (a=0; a<NA; a++) {
1351            const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a));
1352            int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32
1353                    ? sym.int32Val : 0;
1354            bool isPublic = true;
1355            if (code == 0) {
1356                String16 name16(sym.name);
1357                uint32_t typeSpecFlags;
1358                code = assets->getIncludedResources().identifierForName(
1359                    name16.string(), name16.size(),
1360                    attr16.string(), attr16.size(),
1361                    package16.string(), package16.size(), &typeSpecFlags);
1362                if (code == 0) {
1363                    fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
1364                            nclassName.string(), sym.name.string());
1365                    hasErrors = true;
1366                }
1367                isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
1368            }
1369            idents.add(code);
1370            origOrder.add(code);
1371            publicFlags.add(isPublic);
1372        }
1373
1374        NA = idents.size();
1375
1376        bool deprecated = false;
1377
1378        String16 comment = symbols->getComment(realClassName);
1379        fprintf(fp, "%s/** ", indentStr);
1380        if (comment.size() > 0) {
1381            String8 cmt(comment);
1382            fprintf(fp, "%s\n", cmt.string());
1383            if (strstr(cmt.string(), "@deprecated") != NULL) {
1384                deprecated = true;
1385            }
1386        } else {
1387            fprintf(fp, "Attributes that can be used with a %s.\n", nclassName.string());
1388        }
1389        bool hasTable = false;
1390        for (a=0; a<NA; a++) {
1391            ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1392            if (pos >= 0) {
1393                if (!hasTable) {
1394                    hasTable = true;
1395                    fprintf(fp,
1396                            "%s   <p>Includes the following attributes:</p>\n"
1397                            "%s   <table>\n"
1398                            "%s   <colgroup align=\"left\" />\n"
1399                            "%s   <colgroup align=\"left\" />\n"
1400                            "%s   <tr><th>Attribute</th><th>Description</th></tr>\n",
1401                            indentStr,
1402                            indentStr,
1403                            indentStr,
1404                            indentStr,
1405                            indentStr);
1406                }
1407                const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1408                if (!publicFlags.itemAt(a) && !includePrivate) {
1409                    continue;
1410                }
1411                String8 name8(sym.name);
1412                String16 comment(sym.comment);
1413                if (comment.size() <= 0) {
1414                    comment = getAttributeComment(assets, name8);
1415                }
1416                if (comment.size() > 0) {
1417                    const char16_t* p = comment.string();
1418                    while (*p != 0 && *p != '.') {
1419                        if (*p == '{') {
1420                            while (*p != 0 && *p != '}') {
1421                                p++;
1422                            }
1423                        } else {
1424                            p++;
1425                        }
1426                    }
1427                    if (*p == '.') {
1428                        p++;
1429                    }
1430                    comment = String16(comment.string(), p-comment.string());
1431                }
1432                String16 name(name8);
1433                fixupSymbol(&name);
1434                fprintf(fp, "%s   <tr><td><code>{@link #%s_%s %s:%s}</code></td><td>%s</td></tr>\n",
1435                        indentStr, nclassName.string(),
1436                        String8(name).string(),
1437                        assets->getPackage().string(),
1438                        String8(name).string(),
1439                        String8(comment).string());
1440            }
1441        }
1442        if (hasTable) {
1443            fprintf(fp, "%s   </table>\n", indentStr);
1444        }
1445        for (a=0; a<NA; a++) {
1446            ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1447            if (pos >= 0) {
1448                const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1449                if (!publicFlags.itemAt(a) && !includePrivate) {
1450                    continue;
1451                }
1452                String16 name(sym.name);
1453                fixupSymbol(&name);
1454                fprintf(fp, "%s   @see #%s_%s\n",
1455                        indentStr, nclassName.string(),
1456                        String8(name).string());
1457            }
1458        }
1459        fprintf(fp, "%s */\n", getIndentSpace(indent));
1460
1461        if (deprecated) {
1462            fprintf(fp, "%s@Deprecated\n", indentStr);
1463        }
1464
1465        fprintf(fp,
1466                "%spublic static final int[] %s = {\n"
1467                "%s",
1468                indentStr, nclassName.string(),
1469                getIndentSpace(indent+1));
1470
1471        for (a=0; a<NA; a++) {
1472            if (a != 0) {
1473                if ((a&3) == 0) {
1474                    fprintf(fp, ",\n%s", getIndentSpace(indent+1));
1475                } else {
1476                    fprintf(fp, ", ");
1477                }
1478            }
1479            fprintf(fp, "0x%08x", idents[a]);
1480        }
1481
1482        fprintf(fp, "\n%s};\n", indentStr);
1483
1484        for (a=0; a<NA; a++) {
1485            ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1486            if (pos >= 0) {
1487                const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1488                if (!publicFlags.itemAt(a) && !includePrivate) {
1489                    continue;
1490                }
1491                String8 name8(sym.name);
1492                String16 comment(sym.comment);
1493                String16 typeComment;
1494                if (comment.size() <= 0) {
1495                    comment = getAttributeComment(assets, name8, &typeComment);
1496                } else {
1497                    getAttributeComment(assets, name8, &typeComment);
1498                }
1499                String16 name(name8);
1500                if (fixupSymbol(&name) != NO_ERROR) {
1501                    hasErrors = true;
1502                }
1503
1504                uint32_t typeSpecFlags = 0;
1505                String16 name16(sym.name);
1506                assets->getIncludedResources().identifierForName(
1507                    name16.string(), name16.size(),
1508                    attr16.string(), attr16.size(),
1509                    package16.string(), package16.size(), &typeSpecFlags);
1510                //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
1511                //    String8(attr16).string(), String8(name16).string(), typeSpecFlags);
1512                const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
1513
1514                bool deprecated = false;
1515
1516                fprintf(fp, "%s/**\n", indentStr);
1517                if (comment.size() > 0) {
1518                    String8 cmt(comment);
1519                    fprintf(fp, "%s  <p>\n%s  @attr description\n", indentStr, indentStr);
1520                    fprintf(fp, "%s  %s\n", indentStr, cmt.string());
1521                    if (strstr(cmt.string(), "@deprecated") != NULL) {
1522                        deprecated = true;
1523                    }
1524                } else {
1525                    fprintf(fp,
1526                            "%s  <p>This symbol is the offset where the {@link %s.R.attr#%s}\n"
1527                            "%s  attribute's value can be found in the {@link #%s} array.\n",
1528                            indentStr,
1529                            pub ? assets->getPackage().string()
1530                                : assets->getSymbolsPrivatePackage().string(),
1531                            String8(name).string(),
1532                            indentStr, nclassName.string());
1533                }
1534                if (typeComment.size() > 0) {
1535                    String8 cmt(typeComment);
1536                    fprintf(fp, "\n\n%s  %s\n", indentStr, cmt.string());
1537                    if (strstr(cmt.string(), "@deprecated") != NULL) {
1538                        deprecated = true;
1539                    }
1540                }
1541                if (comment.size() > 0) {
1542                    if (pub) {
1543                        fprintf(fp,
1544                                "%s  <p>This corresponds to the global attribute"
1545                                "%s  resource symbol {@link %s.R.attr#%s}.\n",
1546                                indentStr, indentStr,
1547                                assets->getPackage().string(),
1548                                String8(name).string());
1549                    } else {
1550                        fprintf(fp,
1551                                "%s  <p>This is a private symbol.\n", indentStr);
1552                    }
1553                }
1554                fprintf(fp, "%s  @attr name %s:%s\n", indentStr,
1555                        "android", String8(name).string());
1556                fprintf(fp, "%s*/\n", indentStr);
1557                if (deprecated) {
1558                    fprintf(fp, "%s@Deprecated\n", indentStr);
1559                }
1560                fprintf(fp,
1561                        "%spublic static final int %s_%s = %d;\n",
1562                        indentStr, nclassName.string(),
1563                        String8(name).string(), (int)pos);
1564            }
1565        }
1566    }
1567
1568    indent--;
1569    fprintf(fp, "%s};\n", getIndentSpace(indent));
1570    return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
1571}
1572
1573static status_t writeSymbolClass(
1574    FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
1575    const sp<AaptSymbols>& symbols, const String8& className, int indent)
1576{
1577    fprintf(fp, "%spublic %sfinal class %s {\n",
1578            getIndentSpace(indent),
1579            indent != 0 ? "static " : "", className.string());
1580    indent++;
1581
1582    size_t i;
1583    status_t err = NO_ERROR;
1584
1585    size_t N = symbols->getSymbols().size();
1586    for (i=0; i<N; i++) {
1587        const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
1588        if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
1589            continue;
1590        }
1591        if (!includePrivate && !sym.isPublic) {
1592            continue;
1593        }
1594        String16 name(sym.name);
1595        String8 realName(name);
1596        if (fixupSymbol(&name) != NO_ERROR) {
1597            return UNKNOWN_ERROR;
1598        }
1599        String16 comment(sym.comment);
1600        bool haveComment = false;
1601        bool deprecated = false;
1602        if (comment.size() > 0) {
1603            haveComment = true;
1604            String8 cmt(comment);
1605            fprintf(fp,
1606                    "%s/** %s\n",
1607                    getIndentSpace(indent), cmt.string());
1608            if (strstr(cmt.string(), "@deprecated") != NULL) {
1609                deprecated = true;
1610            }
1611        } else if (sym.isPublic && !includePrivate) {
1612            sym.sourcePos.warning("No comment for public symbol %s:%s/%s",
1613                assets->getPackage().string(), className.string(),
1614                String8(sym.name).string());
1615        }
1616        String16 typeComment(sym.typeComment);
1617        if (typeComment.size() > 0) {
1618            String8 cmt(typeComment);
1619            if (!haveComment) {
1620                haveComment = true;
1621                fprintf(fp,
1622                        "%s/** %s\n", getIndentSpace(indent), cmt.string());
1623            } else {
1624                fprintf(fp,
1625                        "%s %s\n", getIndentSpace(indent), cmt.string());
1626            }
1627            if (strstr(cmt.string(), "@deprecated") != NULL) {
1628                deprecated = true;
1629            }
1630        }
1631        if (haveComment) {
1632            fprintf(fp,"%s */\n", getIndentSpace(indent));
1633        }
1634        if (deprecated) {
1635            fprintf(fp, "%s@Deprecated\n", getIndentSpace(indent));
1636        }
1637        fprintf(fp, "%spublic static final int %s=0x%08x;\n",
1638                getIndentSpace(indent),
1639                String8(name).string(), (int)sym.int32Val);
1640    }
1641
1642    for (i=0; i<N; i++) {
1643        const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
1644        if (sym.typeCode != AaptSymbolEntry::TYPE_STRING) {
1645            continue;
1646        }
1647        if (!includePrivate && !sym.isPublic) {
1648            continue;
1649        }
1650        String16 name(sym.name);
1651        if (fixupSymbol(&name) != NO_ERROR) {
1652            return UNKNOWN_ERROR;
1653        }
1654        String16 comment(sym.comment);
1655        bool deprecated = false;
1656        if (comment.size() > 0) {
1657            String8 cmt(comment);
1658            fprintf(fp,
1659                    "%s/** %s\n"
1660                     "%s */\n",
1661                    getIndentSpace(indent), cmt.string(),
1662                    getIndentSpace(indent));
1663            if (strstr(cmt.string(), "@deprecated") != NULL) {
1664                deprecated = true;
1665            }
1666        } else if (sym.isPublic && !includePrivate) {
1667            sym.sourcePos.warning("No comment for public symbol %s:%s/%s",
1668                assets->getPackage().string(), className.string(),
1669                String8(sym.name).string());
1670        }
1671        if (deprecated) {
1672            fprintf(fp, "%s@Deprecated\n", getIndentSpace(indent));
1673        }
1674        fprintf(fp, "%spublic static final String %s=\"%s\";\n",
1675                getIndentSpace(indent),
1676                String8(name).string(), sym.stringVal.string());
1677    }
1678
1679    sp<AaptSymbols> styleableSymbols;
1680
1681    N = symbols->getNestedSymbols().size();
1682    for (i=0; i<N; i++) {
1683        sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
1684        String8 nclassName(symbols->getNestedSymbols().keyAt(i));
1685        if (nclassName == "styleable") {
1686            styleableSymbols = nsymbols;
1687        } else {
1688            err = writeSymbolClass(fp, assets, includePrivate, nsymbols, nclassName, indent);
1689        }
1690        if (err != NO_ERROR) {
1691            return err;
1692        }
1693    }
1694
1695    if (styleableSymbols != NULL) {
1696        err = writeLayoutClasses(fp, assets, styleableSymbols, indent, includePrivate);
1697        if (err != NO_ERROR) {
1698            return err;
1699        }
1700    }
1701
1702    indent--;
1703    fprintf(fp, "%s}\n", getIndentSpace(indent));
1704    return NO_ERROR;
1705}
1706
1707status_t writeResourceSymbols(Bundle* bundle, const sp<AaptAssets>& assets,
1708    const String8& package, bool includePrivate)
1709{
1710    if (!bundle->getRClassDir()) {
1711        return NO_ERROR;
1712    }
1713
1714    const size_t N = assets->getSymbols().size();
1715    for (size_t i=0; i<N; i++) {
1716        sp<AaptSymbols> symbols = assets->getSymbols().valueAt(i);
1717        String8 className(assets->getSymbols().keyAt(i));
1718        String8 dest(bundle->getRClassDir());
1719        if (bundle->getMakePackageDirs()) {
1720            String8 pkg(package);
1721            const char* last = pkg.string();
1722            const char* s = last-1;
1723            do {
1724                s++;
1725                if (s > last && (*s == '.' || *s == 0)) {
1726                    String8 part(last, s-last);
1727                    dest.appendPath(part);
1728#ifdef HAVE_MS_C_RUNTIME
1729                    _mkdir(dest.string());
1730#else
1731                    mkdir(dest.string(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP);
1732#endif
1733                    last = s+1;
1734                }
1735            } while (*s);
1736        }
1737        dest.appendPath(className);
1738        dest.append(".java");
1739        FILE* fp = fopen(dest.string(), "w+");
1740        if (fp == NULL) {
1741            fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
1742                    dest.string(), strerror(errno));
1743            return UNKNOWN_ERROR;
1744        }
1745        if (bundle->getVerbose()) {
1746            printf("  Writing symbols for class %s.\n", className.string());
1747        }
1748
1749        fprintf(fp,
1750        "/* AUTO-GENERATED FILE.  DO NOT MODIFY.\n"
1751        " *\n"
1752        " * This class was automatically generated by the\n"
1753        " * aapt tool from the resource data it found.  It\n"
1754        " * should not be modified by hand.\n"
1755        " */\n"
1756        "\n"
1757        "package %s;\n\n", package.string());
1758
1759        status_t err = writeSymbolClass(fp, assets, includePrivate, symbols, className, 0);
1760        if (err != NO_ERROR) {
1761            return err;
1762        }
1763        fclose(fp);
1764    }
1765
1766    return NO_ERROR;
1767}
1768
1769
1770
1771class ProguardKeepSet
1772{
1773public:
1774    // { rule --> { file locations } }
1775    KeyedVector<String8, SortedVector<String8> > rules;
1776
1777    void add(const String8& rule, const String8& where);
1778};
1779
1780void ProguardKeepSet::add(const String8& rule, const String8& where)
1781{
1782    ssize_t index = rules.indexOfKey(rule);
1783    if (index < 0) {
1784        index = rules.add(rule, SortedVector<String8>());
1785    }
1786    rules.editValueAt(index).add(where);
1787}
1788
1789void
1790addProguardKeepRule(ProguardKeepSet* keep, const String8& inClassName,
1791        const char* pkg, const String8& srcName, int line)
1792{
1793    String8 className(inClassName);
1794    if (pkg != NULL) {
1795        // asdf     --> package.asdf
1796        // .asdf  .a.b  --> package.asdf package.a.b
1797        // asdf.adsf --> asdf.asdf
1798        const char* p = className.string();
1799        const char* q = strchr(p, '.');
1800        if (p == q) {
1801            className = pkg;
1802            className.append(inClassName);
1803        } else if (q == NULL) {
1804            className = pkg;
1805            className.append(".");
1806            className.append(inClassName);
1807        }
1808    }
1809
1810    String8 rule("-keep class ");
1811    rule += className;
1812    rule += " { <init>(...); }";
1813
1814    String8 location("view ");
1815    location += srcName;
1816    char lineno[20];
1817    sprintf(lineno, ":%d", line);
1818    location += lineno;
1819
1820    keep->add(rule, location);
1821}
1822
1823status_t
1824writeProguardForAndroidManifest(ProguardKeepSet* keep, const sp<AaptAssets>& assets)
1825{
1826    status_t err;
1827    ResXMLTree tree;
1828    size_t len;
1829    ResXMLTree::event_code_t code;
1830    int depth = 0;
1831    bool inApplication = false;
1832    String8 error;
1833    sp<AaptGroup> assGroup;
1834    sp<AaptFile> assFile;
1835    String8 pkg;
1836
1837    // First, look for a package file to parse.  This is required to
1838    // be able to generate the resource information.
1839    assGroup = assets->getFiles().valueFor(String8("AndroidManifest.xml"));
1840    if (assGroup == NULL) {
1841        fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n");
1842        return -1;
1843    }
1844
1845    if (assGroup->getFiles().size() != 1) {
1846        fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
1847                assGroup->getFiles().valueAt(0)->getPrintableSource().string());
1848    }
1849
1850    assFile = assGroup->getFiles().valueAt(0);
1851
1852    err = parseXMLResource(assFile, &tree);
1853    if (err != NO_ERROR) {
1854        return err;
1855    }
1856
1857    tree.restart();
1858
1859    while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1860        if (code == ResXMLTree::END_TAG) {
1861            if (/* name == "Application" && */ depth == 2) {
1862                inApplication = false;
1863            }
1864            depth--;
1865            continue;
1866        }
1867        if (code != ResXMLTree::START_TAG) {
1868            continue;
1869        }
1870        depth++;
1871        String8 tag(tree.getElementName(&len));
1872        // printf("Depth %d tag %s\n", depth, tag.string());
1873        bool keepTag = false;
1874        if (depth == 1) {
1875            if (tag != "manifest") {
1876                fprintf(stderr, "ERROR: manifest does not start with <manifest> tag\n");
1877                return -1;
1878            }
1879            pkg = getAttribute(tree, NULL, "package", NULL);
1880        } else if (depth == 2) {
1881            if (tag == "application") {
1882                inApplication = true;
1883                keepTag = true;
1884
1885                String8 agent = getAttribute(tree, "http://schemas.android.com/apk/res/android",
1886                        "backupAgent", &error);
1887                if (agent.length() > 0) {
1888                    addProguardKeepRule(keep, agent, pkg.string(),
1889                            assFile->getPrintableSource(), tree.getLineNumber());
1890                }
1891            } else if (tag == "instrumentation") {
1892                keepTag = true;
1893            }
1894        }
1895        if (!keepTag && inApplication && depth == 3) {
1896            if (tag == "activity" || tag == "service" || tag == "receiver" || tag == "provider") {
1897                keepTag = true;
1898            }
1899        }
1900        if (keepTag) {
1901            String8 name = getAttribute(tree, "http://schemas.android.com/apk/res/android",
1902                    "name", &error);
1903            if (error != "") {
1904                fprintf(stderr, "ERROR: %s\n", error.string());
1905                return -1;
1906            }
1907            if (name.length() > 0) {
1908                addProguardKeepRule(keep, name, pkg.string(),
1909                        assFile->getPrintableSource(), tree.getLineNumber());
1910            }
1911        }
1912    }
1913
1914    return NO_ERROR;
1915}
1916
1917status_t
1918writeProguardForXml(ProguardKeepSet* keep, const sp<AaptFile>& layoutFile,
1919        const char* startTag, const char* altTag)
1920{
1921    status_t err;
1922    ResXMLTree tree;
1923    size_t len;
1924    ResXMLTree::event_code_t code;
1925
1926    err = parseXMLResource(layoutFile, &tree);
1927    if (err != NO_ERROR) {
1928        return err;
1929    }
1930
1931    tree.restart();
1932
1933    if (startTag != NULL) {
1934        bool haveStart = false;
1935        while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1936            if (code != ResXMLTree::START_TAG) {
1937                continue;
1938            }
1939            String8 tag(tree.getElementName(&len));
1940            if (tag == startTag) {
1941                haveStart = true;
1942            }
1943            break;
1944        }
1945        if (!haveStart) {
1946            return NO_ERROR;
1947        }
1948    }
1949
1950    while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1951        if (code != ResXMLTree::START_TAG) {
1952            continue;
1953        }
1954        String8 tag(tree.getElementName(&len));
1955
1956        // If there is no '.', we'll assume that it's one of the built in names.
1957        if (strchr(tag.string(), '.')) {
1958            addProguardKeepRule(keep, tag, NULL,
1959                    layoutFile->getPrintableSource(), tree.getLineNumber());
1960        } else if (altTag != NULL && tag == altTag) {
1961            ssize_t classIndex = tree.indexOfAttribute(NULL, "class");
1962            if (classIndex < 0) {
1963                fprintf(stderr, "%s:%d: <view> does not have class attribute.\n",
1964                        layoutFile->getPrintableSource().string(), tree.getLineNumber());
1965            } else {
1966                size_t len;
1967                addProguardKeepRule(keep,
1968                        String8(tree.getAttributeStringValue(classIndex, &len)), NULL,
1969                        layoutFile->getPrintableSource(), tree.getLineNumber());
1970            }
1971        }
1972    }
1973
1974    return NO_ERROR;
1975}
1976
1977status_t
1978writeProguardForLayouts(ProguardKeepSet* keep, const sp<AaptAssets>& assets)
1979{
1980    status_t err;
1981    const Vector<sp<AaptDir> >& dirs = assets->resDirs();
1982    const size_t K = dirs.size();
1983    for (size_t k=0; k<K; k++) {
1984        const sp<AaptDir>& d = dirs.itemAt(k);
1985        const String8& dirName = d->getLeaf();
1986        const char* startTag = NULL;
1987        const char* altTag = NULL;
1988        if ((dirName == String8("layout")) || (strncmp(dirName.string(), "layout-", 7) == 0)) {
1989            altTag = "view";
1990        } else if ((dirName == String8("xml")) || (strncmp(dirName.string(), "xml-", 4) == 0)) {
1991            startTag = "PreferenceScreen";
1992        } else {
1993            continue;
1994        }
1995
1996        const KeyedVector<String8,sp<AaptGroup> > groups = d->getFiles();
1997        const size_t N = groups.size();
1998        for (size_t i=0; i<N; i++) {
1999            const sp<AaptGroup>& group = groups.valueAt(i);
2000            const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files = group->getFiles();
2001            const size_t M = files.size();
2002            for (size_t j=0; j<M; j++) {
2003                err = writeProguardForXml(keep, files.valueAt(j), startTag, altTag);
2004                if (err < 0) {
2005                    return err;
2006                }
2007            }
2008        }
2009    }
2010    return NO_ERROR;
2011}
2012
2013status_t
2014writeProguardFile(Bundle* bundle, const sp<AaptAssets>& assets)
2015{
2016    status_t err = -1;
2017
2018    if (!bundle->getProguardFile()) {
2019        return NO_ERROR;
2020    }
2021
2022    ProguardKeepSet keep;
2023
2024    err = writeProguardForAndroidManifest(&keep, assets);
2025    if (err < 0) {
2026        return err;
2027    }
2028
2029    err = writeProguardForLayouts(&keep, assets);
2030    if (err < 0) {
2031        return err;
2032    }
2033
2034    FILE* fp = fopen(bundle->getProguardFile(), "w+");
2035    if (fp == NULL) {
2036        fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
2037                bundle->getProguardFile(), strerror(errno));
2038        return UNKNOWN_ERROR;
2039    }
2040
2041    const KeyedVector<String8, SortedVector<String8> >& rules = keep.rules;
2042    const size_t N = rules.size();
2043    for (size_t i=0; i<N; i++) {
2044        const SortedVector<String8>& locations = rules.valueAt(i);
2045        const size_t M = locations.size();
2046        for (size_t j=0; j<M; j++) {
2047            fprintf(fp, "# %s\n", locations.itemAt(j).string());
2048        }
2049        fprintf(fp, "%s\n\n", rules.keyAt(i).string());
2050    }
2051    fclose(fp);
2052
2053    return err;
2054}
2055