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