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