]> git.saurik.com Git - android/aapt.git/blob - Resource.cpp
Change assets to use 64-bit API
[android/aapt.git] / Resource.cpp
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:
22 PackageInfo()
23 {
24 }
25 ~PackageInfo()
26 {
27 }
28
29 status_t parsePackage(const sp<AaptGroup>& grp);
30 };
31
32 // ==========================================================================
33 // ==========================================================================
34 // ==========================================================================
35
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
48 ResourceTypeSet::ResourceTypeSet()
49 :RefBase(),
50 KeyedVector<String8,sp<AaptGroup> >()
51 {
52 }
53
54 class ResourceDirIterator
55 {
56 public:
57 ResourceDirIterator(const sp<ResourceTypeSet>& set, const String8& resType)
58 : mResType(resType), mSet(set), mSetPos(0), mGroupPos(0)
59 {
60 }
61
62 inline const sp<AaptGroup>& getGroup() const { return mGroup; }
63 inline const sp<AaptFile>& getFile() const { return mFile; }
64
65 inline const String8& getBaseName() const { return mBaseName; }
66 inline const String8& getLeafName() const { return mLeafName; }
67 inline String8 getPath() const { return mPath; }
68 inline const ResTable_config& getParams() const { return mParams; }
69
70 enum {
71 EOD = 1
72 };
73
74 ssize_t next()
75 {
76 while (true) {
77 sp<AaptGroup> group;
78 sp<AaptFile> file;
79
80 // Try to get next file in this current group.
81 if (mGroup != NULL && mGroupPos < mGroup->getFiles().size()) {
82 group = mGroup;
83 file = group->getFiles().valueAt(mGroupPos++);
84
85 // Try to get the next group/file in this directory
86 } else if (mSetPos < mSet->size()) {
87 mGroup = group = mSet->valueAt(mSetPos++);
88 if (group->getFiles().size() < 1) {
89 continue;
90 }
91 file = group->getFiles().valueAt(0);
92 mGroupPos = 1;
93
94 // All done!
95 } else {
96 return EOD;
97 }
98
99 mFile = file;
100
101 String8 leaf(group->getLeaf());
102 mLeafName = String8(leaf);
103 mParams = file->getGroupEntry().toParams();
104 NOISY(printf("Dir %s: mcc=%d mnc=%d lang=%c%c cnt=%c%c orient=%d ui=%d density=%d touch=%d key=%d inp=%d nav=%d\n",
105 group->getPath().string(), mParams.mcc, mParams.mnc,
106 mParams.language[0] ? mParams.language[0] : '-',
107 mParams.language[1] ? mParams.language[1] : '-',
108 mParams.country[0] ? mParams.country[0] : '-',
109 mParams.country[1] ? mParams.country[1] : '-',
110 mParams.orientation, mParams.uiMode,
111 mParams.density, mParams.touchscreen, mParams.keyboard,
112 mParams.inputFlags, mParams.navigation));
113 mPath = "res";
114 mPath.appendPath(file->getGroupEntry().toDirName(mResType));
115 mPath.appendPath(leaf);
116 mBaseName = parseResourceName(leaf);
117 if (mBaseName == "") {
118 fprintf(stderr, "Error: malformed resource filename %s\n",
119 file->getPrintableSource().string());
120 return UNKNOWN_ERROR;
121 }
122
123 NOISY(printf("file name=%s\n", mBaseName.string()));
124
125 return NO_ERROR;
126 }
127 }
128
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
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" || type == "mipmap";
154 }
155
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
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
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
286 static status_t preProcessImages(Bundle* bundle, const sp<AaptAssets>& assets,
287 const sp<ResourceTypeSet>& set, const char* type)
288 {
289 ResourceDirIterator it(set, String8(type));
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
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
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
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 };
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
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
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 %zd 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 %zd 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 (%zd) 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
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
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
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
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 sp<ResourceTypeSet> mipmaps;
806
807 ASSIGN_IT(drawable);
808 ASSIGN_IT(layout);
809 ASSIGN_IT(anim);
810 ASSIGN_IT(xml);
811 ASSIGN_IT(raw);
812 ASSIGN_IT(color);
813 ASSIGN_IT(menu);
814 ASSIGN_IT(mipmap);
815
816 assets->setResources(resources);
817 // now go through any resource overlays and collect their files
818 sp<AaptAssets> current = assets->getOverlay();
819 while(current.get()) {
820 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
821 new KeyedVector<String8, sp<ResourceTypeSet> >;
822 current->setResources(resources);
823 collect_files(current, resources);
824 current = current->getOverlay();
825 }
826 // apply the overlay files to the base set
827 if (!applyFileOverlay(bundle, assets, &drawables, "drawable") ||
828 !applyFileOverlay(bundle, assets, &layouts, "layout") ||
829 !applyFileOverlay(bundle, assets, &anims, "anim") ||
830 !applyFileOverlay(bundle, assets, &xmls, "xml") ||
831 !applyFileOverlay(bundle, assets, &raws, "raw") ||
832 !applyFileOverlay(bundle, assets, &colors, "color") ||
833 !applyFileOverlay(bundle, assets, &menus, "menu") ||
834 !applyFileOverlay(bundle, assets, &mipmaps, "mipmap")) {
835 return UNKNOWN_ERROR;
836 }
837
838 bool hasErrors = false;
839
840 if (drawables != NULL) {
841 if (bundle->getOutputAPKFile() != NULL) {
842 err = preProcessImages(bundle, assets, drawables, "drawable");
843 }
844 if (err == NO_ERROR) {
845 err = makeFileResources(bundle, assets, &table, drawables, "drawable");
846 if (err != NO_ERROR) {
847 hasErrors = true;
848 }
849 } else {
850 hasErrors = true;
851 }
852 }
853
854 if (mipmaps != NULL) {
855 if (bundle->getOutputAPKFile() != NULL) {
856 err = preProcessImages(bundle, assets, mipmaps, "mipmap");
857 }
858 if (err == NO_ERROR) {
859 err = makeFileResources(bundle, assets, &table, mipmaps, "mipmap");
860 if (err != NO_ERROR) {
861 hasErrors = true;
862 }
863 } else {
864 hasErrors = true;
865 }
866 }
867
868 if (layouts != NULL) {
869 err = makeFileResources(bundle, assets, &table, layouts, "layout");
870 if (err != NO_ERROR) {
871 hasErrors = true;
872 }
873 }
874
875 if (anims != NULL) {
876 err = makeFileResources(bundle, assets, &table, anims, "anim");
877 if (err != NO_ERROR) {
878 hasErrors = true;
879 }
880 }
881
882 if (xmls != NULL) {
883 err = makeFileResources(bundle, assets, &table, xmls, "xml");
884 if (err != NO_ERROR) {
885 hasErrors = true;
886 }
887 }
888
889 if (raws != NULL) {
890 err = makeFileResources(bundle, assets, &table, raws, "raw");
891 if (err != NO_ERROR) {
892 hasErrors = true;
893 }
894 }
895
896 // compile resources
897 current = assets;
898 while(current.get()) {
899 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
900 current->getResources();
901
902 ssize_t index = resources->indexOfKey(String8("values"));
903 if (index >= 0) {
904 ResourceDirIterator it(resources->valueAt(index), String8("values"));
905 ssize_t res;
906 while ((res=it.next()) == NO_ERROR) {
907 sp<AaptFile> file = it.getFile();
908 res = compileResourceFile(bundle, assets, file, it.getParams(),
909 (current!=assets), &table);
910 if (res != NO_ERROR) {
911 hasErrors = true;
912 }
913 }
914 }
915 current = current->getOverlay();
916 }
917
918 if (colors != NULL) {
919 err = makeFileResources(bundle, assets, &table, colors, "color");
920 if (err != NO_ERROR) {
921 hasErrors = true;
922 }
923 }
924
925 if (menus != NULL) {
926 err = makeFileResources(bundle, assets, &table, menus, "menu");
927 if (err != NO_ERROR) {
928 hasErrors = true;
929 }
930 }
931
932 // --------------------------------------------------------------------
933 // Assignment of resource IDs and initial generation of resource table.
934 // --------------------------------------------------------------------
935
936 if (table.hasResources()) {
937 sp<AaptFile> resFile(getResourceFile(assets));
938 if (resFile == NULL) {
939 fprintf(stderr, "Error: unable to generate entry for resource data\n");
940 return UNKNOWN_ERROR;
941 }
942
943 err = table.assignResourceIds();
944 if (err < NO_ERROR) {
945 return err;
946 }
947 }
948
949 // --------------------------------------------------------------
950 // Finally, we can now we can compile XML files, which may reference
951 // resources.
952 // --------------------------------------------------------------
953
954 if (layouts != NULL) {
955 ResourceDirIterator it(layouts, String8("layout"));
956 while ((err=it.next()) == NO_ERROR) {
957 String8 src = it.getFile()->getPrintableSource();
958 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
959 if (err == NO_ERROR) {
960 ResXMLTree block;
961 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
962 checkForIds(src, block);
963 } else {
964 hasErrors = true;
965 }
966 }
967
968 if (err < NO_ERROR) {
969 hasErrors = true;
970 }
971 err = NO_ERROR;
972 }
973
974 if (anims != NULL) {
975 ResourceDirIterator it(anims, String8("anim"));
976 while ((err=it.next()) == NO_ERROR) {
977 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
978 if (err != NO_ERROR) {
979 hasErrors = true;
980 }
981 }
982
983 if (err < NO_ERROR) {
984 hasErrors = true;
985 }
986 err = NO_ERROR;
987 }
988
989 if (xmls != NULL) {
990 ResourceDirIterator it(xmls, String8("xml"));
991 while ((err=it.next()) == NO_ERROR) {
992 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
993 if (err != NO_ERROR) {
994 hasErrors = true;
995 }
996 }
997
998 if (err < NO_ERROR) {
999 hasErrors = true;
1000 }
1001 err = NO_ERROR;
1002 }
1003
1004 if (drawables != NULL) {
1005 err = postProcessImages(assets, &table, drawables);
1006 if (err != NO_ERROR) {
1007 hasErrors = true;
1008 }
1009 }
1010
1011 if (colors != NULL) {
1012 ResourceDirIterator it(colors, String8("color"));
1013 while ((err=it.next()) == NO_ERROR) {
1014 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
1015 if (err != NO_ERROR) {
1016 hasErrors = true;
1017 }
1018 }
1019
1020 if (err < NO_ERROR) {
1021 hasErrors = true;
1022 }
1023 err = NO_ERROR;
1024 }
1025
1026 if (menus != NULL) {
1027 ResourceDirIterator it(menus, String8("menu"));
1028 while ((err=it.next()) == NO_ERROR) {
1029 String8 src = it.getFile()->getPrintableSource();
1030 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
1031 if (err != NO_ERROR) {
1032 hasErrors = true;
1033 }
1034 ResXMLTree block;
1035 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
1036 checkForIds(src, block);
1037 }
1038
1039 if (err < NO_ERROR) {
1040 hasErrors = true;
1041 }
1042 err = NO_ERROR;
1043 }
1044
1045 if (table.validateLocalizations()) {
1046 hasErrors = true;
1047 }
1048
1049 if (hasErrors) {
1050 return UNKNOWN_ERROR;
1051 }
1052
1053 const sp<AaptFile> manifestFile(androidManifestFile->getFiles().valueAt(0));
1054 String8 manifestPath(manifestFile->getPrintableSource());
1055
1056 // Generate final compiled manifest file.
1057 manifestFile->clearData();
1058 sp<XMLNode> manifestTree = XMLNode::parse(manifestFile);
1059 if (manifestTree == NULL) {
1060 return UNKNOWN_ERROR;
1061 }
1062 err = massageManifest(bundle, manifestTree);
1063 if (err < NO_ERROR) {
1064 return err;
1065 }
1066 err = compileXmlFile(assets, manifestTree, manifestFile, &table);
1067 if (err < NO_ERROR) {
1068 return err;
1069 }
1070
1071 //block.restart();
1072 //printXMLBlock(&block);
1073
1074 // --------------------------------------------------------------
1075 // Generate the final resource table.
1076 // Re-flatten because we may have added new resource IDs
1077 // --------------------------------------------------------------
1078
1079 ResTable finalResTable;
1080 sp<AaptFile> resFile;
1081
1082 if (table.hasResources()) {
1083 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1084 err = table.addSymbols(symbols);
1085 if (err < NO_ERROR) {
1086 return err;
1087 }
1088
1089 resFile = getResourceFile(assets);
1090 if (resFile == NULL) {
1091 fprintf(stderr, "Error: unable to generate entry for resource data\n");
1092 return UNKNOWN_ERROR;
1093 }
1094
1095 err = table.flatten(bundle, resFile);
1096 if (err < NO_ERROR) {
1097 return err;
1098 }
1099
1100 if (bundle->getPublicOutputFile()) {
1101 FILE* fp = fopen(bundle->getPublicOutputFile(), "w+");
1102 if (fp == NULL) {
1103 fprintf(stderr, "ERROR: Unable to open public definitions output file %s: %s\n",
1104 (const char*)bundle->getPublicOutputFile(), strerror(errno));
1105 return UNKNOWN_ERROR;
1106 }
1107 if (bundle->getVerbose()) {
1108 printf(" Writing public definitions to %s.\n", bundle->getPublicOutputFile());
1109 }
1110 table.writePublicDefinitions(String16(assets->getPackage()), fp);
1111 fclose(fp);
1112 }
1113
1114 // Read resources back in,
1115 finalResTable.add(resFile->getData(), resFile->getSize(), NULL);
1116
1117 #if 0
1118 NOISY(
1119 printf("Generated resources:\n");
1120 finalResTable.print();
1121 )
1122 #endif
1123 }
1124
1125 // Perform a basic validation of the manifest file. This time we
1126 // parse it with the comments intact, so that we can use them to
1127 // generate java docs... so we are not going to write this one
1128 // back out to the final manifest data.
1129 sp<AaptFile> outManifestFile = new AaptFile(manifestFile->getSourceFile(),
1130 manifestFile->getGroupEntry(),
1131 manifestFile->getResourceType());
1132 err = compileXmlFile(assets, manifestFile,
1133 outManifestFile, &table,
1134 XML_COMPILE_ASSIGN_ATTRIBUTE_IDS
1135 | XML_COMPILE_STRIP_WHITESPACE | XML_COMPILE_STRIP_RAW_VALUES);
1136 if (err < NO_ERROR) {
1137 return err;
1138 }
1139 ResXMLTree block;
1140 block.setTo(outManifestFile->getData(), outManifestFile->getSize(), true);
1141 String16 manifest16("manifest");
1142 String16 permission16("permission");
1143 String16 permission_group16("permission-group");
1144 String16 uses_permission16("uses-permission");
1145 String16 instrumentation16("instrumentation");
1146 String16 application16("application");
1147 String16 provider16("provider");
1148 String16 service16("service");
1149 String16 receiver16("receiver");
1150 String16 activity16("activity");
1151 String16 action16("action");
1152 String16 category16("category");
1153 String16 data16("scheme");
1154 const char* packageIdentChars = "abcdefghijklmnopqrstuvwxyz"
1155 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789";
1156 const char* packageIdentCharsWithTheStupid = "abcdefghijklmnopqrstuvwxyz"
1157 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
1158 const char* classIdentChars = "abcdefghijklmnopqrstuvwxyz"
1159 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789$";
1160 const char* processIdentChars = "abcdefghijklmnopqrstuvwxyz"
1161 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:";
1162 const char* authoritiesIdentChars = "abcdefghijklmnopqrstuvwxyz"
1163 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-:;";
1164 const char* typeIdentChars = "abcdefghijklmnopqrstuvwxyz"
1165 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:-/*+";
1166 const char* schemeIdentChars = "abcdefghijklmnopqrstuvwxyz"
1167 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
1168 ResXMLTree::event_code_t code;
1169 sp<AaptSymbols> permissionSymbols;
1170 sp<AaptSymbols> permissionGroupSymbols;
1171 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1172 && code > ResXMLTree::BAD_DOCUMENT) {
1173 if (code == ResXMLTree::START_TAG) {
1174 size_t len;
1175 if (block.getElementNamespace(&len) != NULL) {
1176 continue;
1177 }
1178 if (strcmp16(block.getElementName(&len), manifest16.string()) == 0) {
1179 if (validateAttr(manifestPath, finalResTable, block, NULL, "package",
1180 packageIdentChars, true) != ATTR_OKAY) {
1181 hasErrors = true;
1182 }
1183 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1184 "sharedUserId", packageIdentChars, false) != ATTR_OKAY) {
1185 hasErrors = true;
1186 }
1187 } else if (strcmp16(block.getElementName(&len), permission16.string()) == 0
1188 || strcmp16(block.getElementName(&len), permission_group16.string()) == 0) {
1189 const bool isGroup = strcmp16(block.getElementName(&len),
1190 permission_group16.string()) == 0;
1191 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1192 "name", isGroup ? packageIdentCharsWithTheStupid
1193 : packageIdentChars, true) != ATTR_OKAY) {
1194 hasErrors = true;
1195 }
1196 SourcePos srcPos(manifestPath, block.getLineNumber());
1197 sp<AaptSymbols> syms;
1198 if (!isGroup) {
1199 syms = permissionSymbols;
1200 if (syms == NULL) {
1201 sp<AaptSymbols> symbols =
1202 assets->getSymbolsFor(String8("Manifest"));
1203 syms = permissionSymbols = symbols->addNestedSymbol(
1204 String8("permission"), srcPos);
1205 }
1206 } else {
1207 syms = permissionGroupSymbols;
1208 if (syms == NULL) {
1209 sp<AaptSymbols> symbols =
1210 assets->getSymbolsFor(String8("Manifest"));
1211 syms = permissionGroupSymbols = symbols->addNestedSymbol(
1212 String8("permission_group"), srcPos);
1213 }
1214 }
1215 size_t len;
1216 ssize_t index = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "name");
1217 const uint16_t* id = block.getAttributeStringValue(index, &len);
1218 if (id == NULL) {
1219 fprintf(stderr, "%s:%d: missing name attribute in element <%s>.\n",
1220 manifestPath.string(), block.getLineNumber(),
1221 String8(block.getElementName(&len)).string());
1222 hasErrors = true;
1223 break;
1224 }
1225 String8 idStr(id);
1226 char* p = idStr.lockBuffer(idStr.size());
1227 char* e = p + idStr.size();
1228 bool begins_with_digit = true; // init to true so an empty string fails
1229 while (e > p) {
1230 e--;
1231 if (*e >= '0' && *e <= '9') {
1232 begins_with_digit = true;
1233 continue;
1234 }
1235 if ((*e >= 'a' && *e <= 'z') ||
1236 (*e >= 'A' && *e <= 'Z') ||
1237 (*e == '_')) {
1238 begins_with_digit = false;
1239 continue;
1240 }
1241 if (isGroup && (*e == '-')) {
1242 *e = '_';
1243 begins_with_digit = false;
1244 continue;
1245 }
1246 e++;
1247 break;
1248 }
1249 idStr.unlockBuffer();
1250 // verify that we stopped because we hit a period or
1251 // the beginning of the string, and that the
1252 // identifier didn't begin with a digit.
1253 if (begins_with_digit || (e != p && *(e-1) != '.')) {
1254 fprintf(stderr,
1255 "%s:%d: Permission name <%s> is not a valid Java symbol\n",
1256 manifestPath.string(), block.getLineNumber(), idStr.string());
1257 hasErrors = true;
1258 }
1259 syms->addStringSymbol(String8(e), idStr, srcPos);
1260 const uint16_t* cmt = block.getComment(&len);
1261 if (cmt != NULL && *cmt != 0) {
1262 //printf("Comment of %s: %s\n", String8(e).string(),
1263 // String8(cmt).string());
1264 syms->appendComment(String8(e), String16(cmt), srcPos);
1265 } else {
1266 //printf("No comment for %s\n", String8(e).string());
1267 }
1268 syms->makeSymbolPublic(String8(e), srcPos);
1269 } else if (strcmp16(block.getElementName(&len), uses_permission16.string()) == 0) {
1270 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1271 "name", packageIdentChars, true) != ATTR_OKAY) {
1272 hasErrors = true;
1273 }
1274 } else if (strcmp16(block.getElementName(&len), instrumentation16.string()) == 0) {
1275 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1276 "name", classIdentChars, true) != ATTR_OKAY) {
1277 hasErrors = true;
1278 }
1279 if (validateAttr(manifestPath, finalResTable, block,
1280 RESOURCES_ANDROID_NAMESPACE, "targetPackage",
1281 packageIdentChars, true) != ATTR_OKAY) {
1282 hasErrors = true;
1283 }
1284 } else if (strcmp16(block.getElementName(&len), application16.string()) == 0) {
1285 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1286 "name", classIdentChars, false) != ATTR_OKAY) {
1287 hasErrors = true;
1288 }
1289 if (validateAttr(manifestPath, finalResTable, block,
1290 RESOURCES_ANDROID_NAMESPACE, "permission",
1291 packageIdentChars, false) != ATTR_OKAY) {
1292 hasErrors = true;
1293 }
1294 if (validateAttr(manifestPath, finalResTable, block,
1295 RESOURCES_ANDROID_NAMESPACE, "process",
1296 processIdentChars, false) != ATTR_OKAY) {
1297 hasErrors = true;
1298 }
1299 if (validateAttr(manifestPath, finalResTable, block,
1300 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
1301 processIdentChars, false) != ATTR_OKAY) {
1302 hasErrors = true;
1303 }
1304 } else if (strcmp16(block.getElementName(&len), provider16.string()) == 0) {
1305 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1306 "name", classIdentChars, true) != ATTR_OKAY) {
1307 hasErrors = true;
1308 }
1309 if (validateAttr(manifestPath, finalResTable, block,
1310 RESOURCES_ANDROID_NAMESPACE, "authorities",
1311 authoritiesIdentChars, 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 } else if (strcmp16(block.getElementName(&len), service16.string()) == 0
1325 || strcmp16(block.getElementName(&len), receiver16.string()) == 0
1326 || strcmp16(block.getElementName(&len), activity16.string()) == 0) {
1327 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1328 "name", classIdentChars, true) != ATTR_OKAY) {
1329 hasErrors = true;
1330 }
1331 if (validateAttr(manifestPath, finalResTable, block,
1332 RESOURCES_ANDROID_NAMESPACE, "permission",
1333 packageIdentChars, false) != ATTR_OKAY) {
1334 hasErrors = true;
1335 }
1336 if (validateAttr(manifestPath, finalResTable, block,
1337 RESOURCES_ANDROID_NAMESPACE, "process",
1338 processIdentChars, false) != ATTR_OKAY) {
1339 hasErrors = true;
1340 }
1341 if (validateAttr(manifestPath, finalResTable, block,
1342 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
1343 processIdentChars, false) != ATTR_OKAY) {
1344 hasErrors = true;
1345 }
1346 } else if (strcmp16(block.getElementName(&len), action16.string()) == 0
1347 || strcmp16(block.getElementName(&len), category16.string()) == 0) {
1348 if (validateAttr(manifestPath, finalResTable, block,
1349 RESOURCES_ANDROID_NAMESPACE, "name",
1350 packageIdentChars, true) != ATTR_OKAY) {
1351 hasErrors = true;
1352 }
1353 } else if (strcmp16(block.getElementName(&len), data16.string()) == 0) {
1354 if (validateAttr(manifestPath, finalResTable, block,
1355 RESOURCES_ANDROID_NAMESPACE, "mimeType",
1356 typeIdentChars, true) != ATTR_OKAY) {
1357 hasErrors = true;
1358 }
1359 if (validateAttr(manifestPath, finalResTable, block,
1360 RESOURCES_ANDROID_NAMESPACE, "scheme",
1361 schemeIdentChars, true) != ATTR_OKAY) {
1362 hasErrors = true;
1363 }
1364 }
1365 }
1366 }
1367
1368 if (resFile != NULL) {
1369 // These resources are now considered to be a part of the included
1370 // resources, for others to reference.
1371 err = assets->addIncludedResources(resFile);
1372 if (err < NO_ERROR) {
1373 fprintf(stderr, "ERROR: Unable to parse generated resources, aborting.\n");
1374 return err;
1375 }
1376 }
1377
1378 return err;
1379 }
1380
1381 static const char* getIndentSpace(int indent)
1382 {
1383 static const char whitespace[] =
1384 " ";
1385
1386 return whitespace + sizeof(whitespace) - 1 - indent*4;
1387 }
1388
1389 static status_t fixupSymbol(String16* inoutSymbol)
1390 {
1391 inoutSymbol->replaceAll('.', '_');
1392 inoutSymbol->replaceAll(':', '_');
1393 return NO_ERROR;
1394 }
1395
1396 static String16 getAttributeComment(const sp<AaptAssets>& assets,
1397 const String8& name,
1398 String16* outTypeComment = NULL)
1399 {
1400 sp<AaptSymbols> asym = assets->getSymbolsFor(String8("R"));
1401 if (asym != NULL) {
1402 //printf("Got R symbols!\n");
1403 asym = asym->getNestedSymbols().valueFor(String8("attr"));
1404 if (asym != NULL) {
1405 //printf("Got attrs symbols! comment %s=%s\n",
1406 // name.string(), String8(asym->getComment(name)).string());
1407 if (outTypeComment != NULL) {
1408 *outTypeComment = asym->getTypeComment(name);
1409 }
1410 return asym->getComment(name);
1411 }
1412 }
1413 return String16();
1414 }
1415
1416 static status_t writeLayoutClasses(
1417 FILE* fp, const sp<AaptAssets>& assets,
1418 const sp<AaptSymbols>& symbols, int indent, bool includePrivate)
1419 {
1420 const char* indentStr = getIndentSpace(indent);
1421 if (!includePrivate) {
1422 fprintf(fp, "%s/** @doconly */\n", indentStr);
1423 }
1424 fprintf(fp, "%spublic static final class styleable {\n", indentStr);
1425 indent++;
1426
1427 String16 attr16("attr");
1428 String16 package16(assets->getPackage());
1429
1430 indentStr = getIndentSpace(indent);
1431 bool hasErrors = false;
1432
1433 size_t i;
1434 size_t N = symbols->getNestedSymbols().size();
1435 for (i=0; i<N; i++) {
1436 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
1437 String16 nclassName16(symbols->getNestedSymbols().keyAt(i));
1438 String8 realClassName(nclassName16);
1439 if (fixupSymbol(&nclassName16) != NO_ERROR) {
1440 hasErrors = true;
1441 }
1442 String8 nclassName(nclassName16);
1443
1444 SortedVector<uint32_t> idents;
1445 Vector<uint32_t> origOrder;
1446 Vector<bool> publicFlags;
1447
1448 size_t a;
1449 size_t NA = nsymbols->getSymbols().size();
1450 for (a=0; a<NA; a++) {
1451 const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a));
1452 int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32
1453 ? sym.int32Val : 0;
1454 bool isPublic = true;
1455 if (code == 0) {
1456 String16 name16(sym.name);
1457 uint32_t typeSpecFlags;
1458 code = assets->getIncludedResources().identifierForName(
1459 name16.string(), name16.size(),
1460 attr16.string(), attr16.size(),
1461 package16.string(), package16.size(), &typeSpecFlags);
1462 if (code == 0) {
1463 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
1464 nclassName.string(), sym.name.string());
1465 hasErrors = true;
1466 }
1467 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
1468 }
1469 idents.add(code);
1470 origOrder.add(code);
1471 publicFlags.add(isPublic);
1472 }
1473
1474 NA = idents.size();
1475
1476 bool deprecated = false;
1477
1478 String16 comment = symbols->getComment(realClassName);
1479 fprintf(fp, "%s/** ", indentStr);
1480 if (comment.size() > 0) {
1481 String8 cmt(comment);
1482 fprintf(fp, "%s\n", cmt.string());
1483 if (strstr(cmt.string(), "@deprecated") != NULL) {
1484 deprecated = true;
1485 }
1486 } else {
1487 fprintf(fp, "Attributes that can be used with a %s.\n", nclassName.string());
1488 }
1489 bool hasTable = false;
1490 for (a=0; a<NA; a++) {
1491 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1492 if (pos >= 0) {
1493 if (!hasTable) {
1494 hasTable = true;
1495 fprintf(fp,
1496 "%s <p>Includes the following attributes:</p>\n"
1497 "%s <table>\n"
1498 "%s <colgroup align=\"left\" />\n"
1499 "%s <colgroup align=\"left\" />\n"
1500 "%s <tr><th>Attribute</th><th>Description</th></tr>\n",
1501 indentStr,
1502 indentStr,
1503 indentStr,
1504 indentStr,
1505 indentStr);
1506 }
1507 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1508 if (!publicFlags.itemAt(a) && !includePrivate) {
1509 continue;
1510 }
1511 String8 name8(sym.name);
1512 String16 comment(sym.comment);
1513 if (comment.size() <= 0) {
1514 comment = getAttributeComment(assets, name8);
1515 }
1516 if (comment.size() > 0) {
1517 const char16_t* p = comment.string();
1518 while (*p != 0 && *p != '.') {
1519 if (*p == '{') {
1520 while (*p != 0 && *p != '}') {
1521 p++;
1522 }
1523 } else {
1524 p++;
1525 }
1526 }
1527 if (*p == '.') {
1528 p++;
1529 }
1530 comment = String16(comment.string(), p-comment.string());
1531 }
1532 String16 name(name8);
1533 fixupSymbol(&name);
1534 fprintf(fp, "%s <tr><td><code>{@link #%s_%s %s:%s}</code></td><td>%s</td></tr>\n",
1535 indentStr, nclassName.string(),
1536 String8(name).string(),
1537 assets->getPackage().string(),
1538 String8(name).string(),
1539 String8(comment).string());
1540 }
1541 }
1542 if (hasTable) {
1543 fprintf(fp, "%s </table>\n", indentStr);
1544 }
1545 for (a=0; a<NA; a++) {
1546 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1547 if (pos >= 0) {
1548 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1549 if (!publicFlags.itemAt(a) && !includePrivate) {
1550 continue;
1551 }
1552 String16 name(sym.name);
1553 fixupSymbol(&name);
1554 fprintf(fp, "%s @see #%s_%s\n",
1555 indentStr, nclassName.string(),
1556 String8(name).string());
1557 }
1558 }
1559 fprintf(fp, "%s */\n", getIndentSpace(indent));
1560
1561 if (deprecated) {
1562 fprintf(fp, "%s@Deprecated\n", indentStr);
1563 }
1564
1565 fprintf(fp,
1566 "%spublic static final int[] %s = {\n"
1567 "%s",
1568 indentStr, nclassName.string(),
1569 getIndentSpace(indent+1));
1570
1571 for (a=0; a<NA; a++) {
1572 if (a != 0) {
1573 if ((a&3) == 0) {
1574 fprintf(fp, ",\n%s", getIndentSpace(indent+1));
1575 } else {
1576 fprintf(fp, ", ");
1577 }
1578 }
1579 fprintf(fp, "0x%08x", idents[a]);
1580 }
1581
1582 fprintf(fp, "\n%s};\n", indentStr);
1583
1584 for (a=0; a<NA; a++) {
1585 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1586 if (pos >= 0) {
1587 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1588 if (!publicFlags.itemAt(a) && !includePrivate) {
1589 continue;
1590 }
1591 String8 name8(sym.name);
1592 String16 comment(sym.comment);
1593 String16 typeComment;
1594 if (comment.size() <= 0) {
1595 comment = getAttributeComment(assets, name8, &typeComment);
1596 } else {
1597 getAttributeComment(assets, name8, &typeComment);
1598 }
1599 String16 name(name8);
1600 if (fixupSymbol(&name) != NO_ERROR) {
1601 hasErrors = true;
1602 }
1603
1604 uint32_t typeSpecFlags = 0;
1605 String16 name16(sym.name);
1606 assets->getIncludedResources().identifierForName(
1607 name16.string(), name16.size(),
1608 attr16.string(), attr16.size(),
1609 package16.string(), package16.size(), &typeSpecFlags);
1610 //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
1611 // String8(attr16).string(), String8(name16).string(), typeSpecFlags);
1612 const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
1613
1614 bool deprecated = false;
1615
1616 fprintf(fp, "%s/**\n", indentStr);
1617 if (comment.size() > 0) {
1618 String8 cmt(comment);
1619 fprintf(fp, "%s <p>\n%s @attr description\n", indentStr, indentStr);
1620 fprintf(fp, "%s %s\n", indentStr, cmt.string());
1621 if (strstr(cmt.string(), "@deprecated") != NULL) {
1622 deprecated = true;
1623 }
1624 } else {
1625 fprintf(fp,
1626 "%s <p>This symbol is the offset where the {@link %s.R.attr#%s}\n"
1627 "%s attribute's value can be found in the {@link #%s} array.\n",
1628 indentStr,
1629 pub ? assets->getPackage().string()
1630 : assets->getSymbolsPrivatePackage().string(),
1631 String8(name).string(),
1632 indentStr, nclassName.string());
1633 }
1634 if (typeComment.size() > 0) {
1635 String8 cmt(typeComment);
1636 fprintf(fp, "\n\n%s %s\n", indentStr, cmt.string());
1637 if (strstr(cmt.string(), "@deprecated") != NULL) {
1638 deprecated = true;
1639 }
1640 }
1641 if (comment.size() > 0) {
1642 if (pub) {
1643 fprintf(fp,
1644 "%s <p>This corresponds to the global attribute"
1645 "%s resource symbol {@link %s.R.attr#%s}.\n",
1646 indentStr, indentStr,
1647 assets->getPackage().string(),
1648 String8(name).string());
1649 } else {
1650 fprintf(fp,
1651 "%s <p>This is a private symbol.\n", indentStr);
1652 }
1653 }
1654 fprintf(fp, "%s @attr name %s:%s\n", indentStr,
1655 "android", String8(name).string());
1656 fprintf(fp, "%s*/\n", indentStr);
1657 if (deprecated) {
1658 fprintf(fp, "%s@Deprecated\n", indentStr);
1659 }
1660 fprintf(fp,
1661 "%spublic static final int %s_%s = %d;\n",
1662 indentStr, nclassName.string(),
1663 String8(name).string(), (int)pos);
1664 }
1665 }
1666 }
1667
1668 indent--;
1669 fprintf(fp, "%s};\n", getIndentSpace(indent));
1670 return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
1671 }
1672
1673 static status_t writeSymbolClass(
1674 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
1675 const sp<AaptSymbols>& symbols, const String8& className, int indent)
1676 {
1677 fprintf(fp, "%spublic %sfinal class %s {\n",
1678 getIndentSpace(indent),
1679 indent != 0 ? "static " : "", className.string());
1680 indent++;
1681
1682 size_t i;
1683 status_t err = NO_ERROR;
1684
1685 size_t N = symbols->getSymbols().size();
1686 for (i=0; i<N; i++) {
1687 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
1688 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
1689 continue;
1690 }
1691 if (!includePrivate && !sym.isPublic) {
1692 continue;
1693 }
1694 String16 name(sym.name);
1695 String8 realName(name);
1696 if (fixupSymbol(&name) != NO_ERROR) {
1697 return UNKNOWN_ERROR;
1698 }
1699 String16 comment(sym.comment);
1700 bool haveComment = false;
1701 bool deprecated = false;
1702 if (comment.size() > 0) {
1703 haveComment = true;
1704 String8 cmt(comment);
1705 fprintf(fp,
1706 "%s/** %s\n",
1707 getIndentSpace(indent), cmt.string());
1708 if (strstr(cmt.string(), "@deprecated") != NULL) {
1709 deprecated = true;
1710 }
1711 } else if (sym.isPublic && !includePrivate) {
1712 sym.sourcePos.warning("No comment for public symbol %s:%s/%s",
1713 assets->getPackage().string(), className.string(),
1714 String8(sym.name).string());
1715 }
1716 String16 typeComment(sym.typeComment);
1717 if (typeComment.size() > 0) {
1718 String8 cmt(typeComment);
1719 if (!haveComment) {
1720 haveComment = true;
1721 fprintf(fp,
1722 "%s/** %s\n", getIndentSpace(indent), cmt.string());
1723 } else {
1724 fprintf(fp,
1725 "%s %s\n", getIndentSpace(indent), cmt.string());
1726 }
1727 if (strstr(cmt.string(), "@deprecated") != NULL) {
1728 deprecated = true;
1729 }
1730 }
1731 if (haveComment) {
1732 fprintf(fp,"%s */\n", getIndentSpace(indent));
1733 }
1734 if (deprecated) {
1735 fprintf(fp, "%s@Deprecated\n", getIndentSpace(indent));
1736 }
1737 fprintf(fp, "%spublic static final int %s=0x%08x;\n",
1738 getIndentSpace(indent),
1739 String8(name).string(), (int)sym.int32Val);
1740 }
1741
1742 for (i=0; i<N; i++) {
1743 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
1744 if (sym.typeCode != AaptSymbolEntry::TYPE_STRING) {
1745 continue;
1746 }
1747 if (!includePrivate && !sym.isPublic) {
1748 continue;
1749 }
1750 String16 name(sym.name);
1751 if (fixupSymbol(&name) != NO_ERROR) {
1752 return UNKNOWN_ERROR;
1753 }
1754 String16 comment(sym.comment);
1755 bool deprecated = false;
1756 if (comment.size() > 0) {
1757 String8 cmt(comment);
1758 fprintf(fp,
1759 "%s/** %s\n"
1760 "%s */\n",
1761 getIndentSpace(indent), cmt.string(),
1762 getIndentSpace(indent));
1763 if (strstr(cmt.string(), "@deprecated") != NULL) {
1764 deprecated = true;
1765 }
1766 } else if (sym.isPublic && !includePrivate) {
1767 sym.sourcePos.warning("No comment for public symbol %s:%s/%s",
1768 assets->getPackage().string(), className.string(),
1769 String8(sym.name).string());
1770 }
1771 if (deprecated) {
1772 fprintf(fp, "%s@Deprecated\n", getIndentSpace(indent));
1773 }
1774 fprintf(fp, "%spublic static final String %s=\"%s\";\n",
1775 getIndentSpace(indent),
1776 String8(name).string(), sym.stringVal.string());
1777 }
1778
1779 sp<AaptSymbols> styleableSymbols;
1780
1781 N = symbols->getNestedSymbols().size();
1782 for (i=0; i<N; i++) {
1783 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
1784 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
1785 if (nclassName == "styleable") {
1786 styleableSymbols = nsymbols;
1787 } else {
1788 err = writeSymbolClass(fp, assets, includePrivate, nsymbols, nclassName, indent);
1789 }
1790 if (err != NO_ERROR) {
1791 return err;
1792 }
1793 }
1794
1795 if (styleableSymbols != NULL) {
1796 err = writeLayoutClasses(fp, assets, styleableSymbols, indent, includePrivate);
1797 if (err != NO_ERROR) {
1798 return err;
1799 }
1800 }
1801
1802 indent--;
1803 fprintf(fp, "%s}\n", getIndentSpace(indent));
1804 return NO_ERROR;
1805 }
1806
1807 status_t writeResourceSymbols(Bundle* bundle, const sp<AaptAssets>& assets,
1808 const String8& package, bool includePrivate)
1809 {
1810 if (!bundle->getRClassDir()) {
1811 return NO_ERROR;
1812 }
1813
1814 const size_t N = assets->getSymbols().size();
1815 for (size_t i=0; i<N; i++) {
1816 sp<AaptSymbols> symbols = assets->getSymbols().valueAt(i);
1817 String8 className(assets->getSymbols().keyAt(i));
1818 String8 dest(bundle->getRClassDir());
1819 if (bundle->getMakePackageDirs()) {
1820 String8 pkg(package);
1821 const char* last = pkg.string();
1822 const char* s = last-1;
1823 do {
1824 s++;
1825 if (s > last && (*s == '.' || *s == 0)) {
1826 String8 part(last, s-last);
1827 dest.appendPath(part);
1828 #ifdef HAVE_MS_C_RUNTIME
1829 _mkdir(dest.string());
1830 #else
1831 mkdir(dest.string(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP);
1832 #endif
1833 last = s+1;
1834 }
1835 } while (*s);
1836 }
1837 dest.appendPath(className);
1838 dest.append(".java");
1839 FILE* fp = fopen(dest.string(), "w+");
1840 if (fp == NULL) {
1841 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
1842 dest.string(), strerror(errno));
1843 return UNKNOWN_ERROR;
1844 }
1845 if (bundle->getVerbose()) {
1846 printf(" Writing symbols for class %s.\n", className.string());
1847 }
1848
1849 fprintf(fp,
1850 "/* AUTO-GENERATED FILE. DO NOT MODIFY.\n"
1851 " *\n"
1852 " * This class was automatically generated by the\n"
1853 " * aapt tool from the resource data it found. It\n"
1854 " * should not be modified by hand.\n"
1855 " */\n"
1856 "\n"
1857 "package %s;\n\n", package.string());
1858
1859 status_t err = writeSymbolClass(fp, assets, includePrivate, symbols, className, 0);
1860 if (err != NO_ERROR) {
1861 return err;
1862 }
1863 fclose(fp);
1864 }
1865
1866 return NO_ERROR;
1867 }
1868
1869
1870
1871 class ProguardKeepSet
1872 {
1873 public:
1874 // { rule --> { file locations } }
1875 KeyedVector<String8, SortedVector<String8> > rules;
1876
1877 void add(const String8& rule, const String8& where);
1878 };
1879
1880 void ProguardKeepSet::add(const String8& rule, const String8& where)
1881 {
1882 ssize_t index = rules.indexOfKey(rule);
1883 if (index < 0) {
1884 index = rules.add(rule, SortedVector<String8>());
1885 }
1886 rules.editValueAt(index).add(where);
1887 }
1888
1889 void
1890 addProguardKeepRule(ProguardKeepSet* keep, const String8& inClassName,
1891 const char* pkg, const String8& srcName, int line)
1892 {
1893 String8 className(inClassName);
1894 if (pkg != NULL) {
1895 // asdf --> package.asdf
1896 // .asdf .a.b --> package.asdf package.a.b
1897 // asdf.adsf --> asdf.asdf
1898 const char* p = className.string();
1899 const char* q = strchr(p, '.');
1900 if (p == q) {
1901 className = pkg;
1902 className.append(inClassName);
1903 } else if (q == NULL) {
1904 className = pkg;
1905 className.append(".");
1906 className.append(inClassName);
1907 }
1908 }
1909
1910 String8 rule("-keep class ");
1911 rule += className;
1912 rule += " { <init>(...); }";
1913
1914 String8 location("view ");
1915 location += srcName;
1916 char lineno[20];
1917 sprintf(lineno, ":%d", line);
1918 location += lineno;
1919
1920 keep->add(rule, location);
1921 }
1922
1923 status_t
1924 writeProguardForAndroidManifest(ProguardKeepSet* keep, const sp<AaptAssets>& assets)
1925 {
1926 status_t err;
1927 ResXMLTree tree;
1928 size_t len;
1929 ResXMLTree::event_code_t code;
1930 int depth = 0;
1931 bool inApplication = false;
1932 String8 error;
1933 sp<AaptGroup> assGroup;
1934 sp<AaptFile> assFile;
1935 String8 pkg;
1936
1937 // First, look for a package file to parse. This is required to
1938 // be able to generate the resource information.
1939 assGroup = assets->getFiles().valueFor(String8("AndroidManifest.xml"));
1940 if (assGroup == NULL) {
1941 fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n");
1942 return -1;
1943 }
1944
1945 if (assGroup->getFiles().size() != 1) {
1946 fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
1947 assGroup->getFiles().valueAt(0)->getPrintableSource().string());
1948 }
1949
1950 assFile = assGroup->getFiles().valueAt(0);
1951
1952 err = parseXMLResource(assFile, &tree);
1953 if (err != NO_ERROR) {
1954 return err;
1955 }
1956
1957 tree.restart();
1958
1959 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1960 if (code == ResXMLTree::END_TAG) {
1961 if (/* name == "Application" && */ depth == 2) {
1962 inApplication = false;
1963 }
1964 depth--;
1965 continue;
1966 }
1967 if (code != ResXMLTree::START_TAG) {
1968 continue;
1969 }
1970 depth++;
1971 String8 tag(tree.getElementName(&len));
1972 // printf("Depth %d tag %s\n", depth, tag.string());
1973 bool keepTag = false;
1974 if (depth == 1) {
1975 if (tag != "manifest") {
1976 fprintf(stderr, "ERROR: manifest does not start with <manifest> tag\n");
1977 return -1;
1978 }
1979 pkg = getAttribute(tree, NULL, "package", NULL);
1980 } else if (depth == 2) {
1981 if (tag == "application") {
1982 inApplication = true;
1983 keepTag = true;
1984
1985 String8 agent = getAttribute(tree, "http://schemas.android.com/apk/res/android",
1986 "backupAgent", &error);
1987 if (agent.length() > 0) {
1988 addProguardKeepRule(keep, agent, pkg.string(),
1989 assFile->getPrintableSource(), tree.getLineNumber());
1990 }
1991 } else if (tag == "instrumentation") {
1992 keepTag = true;
1993 }
1994 }
1995 if (!keepTag && inApplication && depth == 3) {
1996 if (tag == "activity" || tag == "service" || tag == "receiver" || tag == "provider") {
1997 keepTag = true;
1998 }
1999 }
2000 if (keepTag) {
2001 String8 name = getAttribute(tree, "http://schemas.android.com/apk/res/android",
2002 "name", &error);
2003 if (error != "") {
2004 fprintf(stderr, "ERROR: %s\n", error.string());
2005 return -1;
2006 }
2007 if (name.length() > 0) {
2008 addProguardKeepRule(keep, name, pkg.string(),
2009 assFile->getPrintableSource(), tree.getLineNumber());
2010 }
2011 }
2012 }
2013
2014 return NO_ERROR;
2015 }
2016
2017 struct NamespaceAttributePair {
2018 const char* ns;
2019 const char* attr;
2020
2021 NamespaceAttributePair(const char* n, const char* a) : ns(n), attr(a) {}
2022 NamespaceAttributePair() : ns(NULL), attr(NULL) {}
2023 };
2024
2025 status_t
2026 writeProguardForXml(ProguardKeepSet* keep, const sp<AaptFile>& layoutFile,
2027 const char* startTag, const KeyedVector<String8, NamespaceAttributePair>* tagAttrPairs)
2028 {
2029 status_t err;
2030 ResXMLTree tree;
2031 size_t len;
2032 ResXMLTree::event_code_t code;
2033
2034 err = parseXMLResource(layoutFile, &tree);
2035 if (err != NO_ERROR) {
2036 return err;
2037 }
2038
2039 tree.restart();
2040
2041 if (startTag != NULL) {
2042 bool haveStart = false;
2043 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
2044 if (code != ResXMLTree::START_TAG) {
2045 continue;
2046 }
2047 String8 tag(tree.getElementName(&len));
2048 if (tag == startTag) {
2049 haveStart = true;
2050 }
2051 break;
2052 }
2053 if (!haveStart) {
2054 return NO_ERROR;
2055 }
2056 }
2057
2058 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
2059 if (code != ResXMLTree::START_TAG) {
2060 continue;
2061 }
2062 String8 tag(tree.getElementName(&len));
2063
2064 // If there is no '.', we'll assume that it's one of the built in names.
2065 if (strchr(tag.string(), '.')) {
2066 addProguardKeepRule(keep, tag, NULL,
2067 layoutFile->getPrintableSource(), tree.getLineNumber());
2068 } else if (tagAttrPairs != NULL) {
2069 ssize_t tagIndex = tagAttrPairs->indexOfKey(tag);
2070 if (tagIndex >= 0) {
2071 const NamespaceAttributePair& nsAttr = tagAttrPairs->valueAt(tagIndex);
2072 ssize_t attrIndex = tree.indexOfAttribute(nsAttr.ns, nsAttr.attr);
2073 if (attrIndex < 0) {
2074 // fprintf(stderr, "%s:%d: <%s> does not have attribute %s:%s.\n",
2075 // layoutFile->getPrintableSource().string(), tree.getLineNumber(),
2076 // tag.string(), nsAttr.ns, nsAttr.attr);
2077 } else {
2078 size_t len;
2079 addProguardKeepRule(keep,
2080 String8(tree.getAttributeStringValue(attrIndex, &len)), NULL,
2081 layoutFile->getPrintableSource(), tree.getLineNumber());
2082 }
2083 }
2084 }
2085 }
2086
2087 return NO_ERROR;
2088 }
2089
2090 static void addTagAttrPair(KeyedVector<String8, NamespaceAttributePair>* dest,
2091 const char* tag, const char* ns, const char* attr) {
2092 dest->add(String8(tag), NamespaceAttributePair(ns, attr));
2093 }
2094
2095 status_t
2096 writeProguardForLayouts(ProguardKeepSet* keep, const sp<AaptAssets>& assets)
2097 {
2098 status_t err;
2099
2100 // tag:attribute pairs that should be checked in layout files.
2101 KeyedVector<String8, NamespaceAttributePair> kLayoutTagAttrPairs;
2102 addTagAttrPair(&kLayoutTagAttrPairs, "view", NULL, "class");
2103 addTagAttrPair(&kLayoutTagAttrPairs, "fragment", NULL, "class");
2104 addTagAttrPair(&kLayoutTagAttrPairs, "fragment", RESOURCES_ANDROID_NAMESPACE, "name");
2105
2106 // tag:attribute pairs that should be checked in xml files.
2107 KeyedVector<String8, NamespaceAttributePair> kXmlTagAttrPairs;
2108 addTagAttrPair(&kXmlTagAttrPairs, "PreferenceScreen", RESOURCES_ANDROID_NAMESPACE, "fragment");
2109 addTagAttrPair(&kXmlTagAttrPairs, "header", RESOURCES_ANDROID_NAMESPACE, "fragment");
2110
2111 const Vector<sp<AaptDir> >& dirs = assets->resDirs();
2112 const size_t K = dirs.size();
2113 for (size_t k=0; k<K; k++) {
2114 const sp<AaptDir>& d = dirs.itemAt(k);
2115 const String8& dirName = d->getLeaf();
2116 const char* startTag = NULL;
2117 const KeyedVector<String8, NamespaceAttributePair>* tagAttrPairs = NULL;
2118 if ((dirName == String8("layout")) || (strncmp(dirName.string(), "layout-", 7) == 0)) {
2119 tagAttrPairs = &kLayoutTagAttrPairs;
2120 } else if ((dirName == String8("xml")) || (strncmp(dirName.string(), "xml-", 4) == 0)) {
2121 startTag = "PreferenceScreen";
2122 tagAttrPairs = &kXmlTagAttrPairs;
2123 } else {
2124 continue;
2125 }
2126
2127 const KeyedVector<String8,sp<AaptGroup> > groups = d->getFiles();
2128 const size_t N = groups.size();
2129 for (size_t i=0; i<N; i++) {
2130 const sp<AaptGroup>& group = groups.valueAt(i);
2131 const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files = group->getFiles();
2132 const size_t M = files.size();
2133 for (size_t j=0; j<M; j++) {
2134 err = writeProguardForXml(keep, files.valueAt(j), startTag, tagAttrPairs);
2135 if (err < 0) {
2136 return err;
2137 }
2138 }
2139 }
2140 }
2141 return NO_ERROR;
2142 }
2143
2144 status_t
2145 writeProguardFile(Bundle* bundle, const sp<AaptAssets>& assets)
2146 {
2147 status_t err = -1;
2148
2149 if (!bundle->getProguardFile()) {
2150 return NO_ERROR;
2151 }
2152
2153 ProguardKeepSet keep;
2154
2155 err = writeProguardForAndroidManifest(&keep, assets);
2156 if (err < 0) {
2157 return err;
2158 }
2159
2160 err = writeProguardForLayouts(&keep, assets);
2161 if (err < 0) {
2162 return err;
2163 }
2164
2165 FILE* fp = fopen(bundle->getProguardFile(), "w+");
2166 if (fp == NULL) {
2167 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
2168 bundle->getProguardFile(), strerror(errno));
2169 return UNKNOWN_ERROR;
2170 }
2171
2172 const KeyedVector<String8, SortedVector<String8> >& rules = keep.rules;
2173 const size_t N = rules.size();
2174 for (size_t i=0; i<N; i++) {
2175 const SortedVector<String8>& locations = rules.valueAt(i);
2176 const size_t M = locations.size();
2177 for (size_t j=0; j<M; j++) {
2178 fprintf(fp, "# %s\n", locations.itemAt(j).string());
2179 }
2180 fprintf(fp, "%s\n\n", rules.keyAt(i).string());
2181 }
2182 fclose(fp);
2183
2184 return err;
2185 }