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