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