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