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