]> git.saurik.com Git - android/aapt.git/blame - Resource.cpp
am 57f03f0b: Merge snapshot version of donut back into the main tree
[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();
104 NOISY(printf("Dir %s: mcc=%d mnc=%d lang=%c%c cnt=%c%c orient=%d density=%d touch=%d key=%d inp=%d nav=%d\n",
105 group->getPath().string(), mParams.mcc, mParams.mnc,
106 mParams.language[0] ? mParams.language[0] : '-',
107 mParams.language[1] ? mParams.language[1] : '-',
108 mParams.country[0] ? mParams.country[0] : '-',
109 mParams.country[1] ? mParams.country[1] : '-',
110 mParams.orientation,
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
174static status_t parsePackage(const sp<AaptAssets>& assets, const sp<AaptGroup>& grp)
175{
176 if (grp->getFiles().size() != 1) {
406a85e3 177 fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
a534180c
TAOSP
178 grp->getFiles().valueAt(0)->getPrintableSource().string());
179 }
180
181 sp<AaptFile> file = grp->getFiles().valueAt(0);
182
183 ResXMLTree block;
184 status_t err = parseXMLResource(file, &block);
185 if (err != NO_ERROR) {
186 return err;
187 }
188 //printXMLBlock(&block);
189
190 ResXMLTree::event_code_t code;
191 while ((code=block.next()) != ResXMLTree::START_TAG
192 && code != ResXMLTree::END_DOCUMENT
193 && code != ResXMLTree::BAD_DOCUMENT) {
194 }
195
196 size_t len;
197 if (code != ResXMLTree::START_TAG) {
198 fprintf(stderr, "%s:%d: No start tag found\n",
199 file->getPrintableSource().string(), block.getLineNumber());
200 return UNKNOWN_ERROR;
201 }
202 if (strcmp16(block.getElementName(&len), String16("manifest").string()) != 0) {
203 fprintf(stderr, "%s:%d: Invalid start tag %s, expected <manifest>\n",
204 file->getPrintableSource().string(), block.getLineNumber(),
205 String8(block.getElementName(&len)).string());
206 return UNKNOWN_ERROR;
207 }
208
209 ssize_t nameIndex = block.indexOfAttribute(NULL, "package");
210 if (nameIndex < 0) {
211 fprintf(stderr, "%s:%d: <manifest> does not have package attribute.\n",
212 file->getPrintableSource().string(), block.getLineNumber());
213 return UNKNOWN_ERROR;
214 }
215
216 assets->setPackage(String8(block.getAttributeStringValue(nameIndex, &len)));
217
218 return NO_ERROR;
219}
220
221// ==========================================================================
222// ==========================================================================
223// ==========================================================================
224
225static status_t makeFileResources(Bundle* bundle, const sp<AaptAssets>& assets,
226 ResourceTable* table,
227 const sp<ResourceTypeSet>& set,
228 const char* resType)
229{
230 String8 type8(resType);
231 String16 type16(resType);
232
233 bool hasErrors = false;
234
235 ResourceDirIterator it(set, String8(resType));
236 ssize_t res;
237 while ((res=it.next()) == NO_ERROR) {
238 if (bundle->getVerbose()) {
239 printf(" (new resource id %s from %s)\n",
240 it.getBaseName().string(), it.getFile()->getPrintableSource().string());
241 }
242 String16 baseName(it.getBaseName());
243 const char16_t* str = baseName.string();
244 const char16_t* const end = str + baseName.size();
245 while (str < end) {
246 if (!((*str >= 'a' && *str <= 'z')
247 || (*str >= '0' && *str <= '9')
248 || *str == '_' || *str == '.')) {
249 fprintf(stderr, "%s: Invalid file name: must contain only [a-z0-9_.]\n",
250 it.getPath().string());
251 hasErrors = true;
252 }
253 str++;
254 }
255 String8 resPath = it.getPath();
256 resPath.convertToResPath();
257 table->addEntry(SourcePos(it.getPath(), 0), String16(assets->getPackage()),
258 type16,
259 baseName,
260 String16(resPath),
261 NULL,
262 &it.getParams());
263 assets->addResource(it.getLeafName(), resPath, it.getFile(), type8);
264 }
265
266 return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
267}
268
269static status_t preProcessImages(Bundle* bundle, const sp<AaptAssets>& assets,
270 const sp<ResourceTypeSet>& set)
271{
272 ResourceDirIterator it(set, String8("drawable"));
273 Vector<sp<AaptFile> > newNameFiles;
274 Vector<String8> newNamePaths;
8f940cc4 275 bool hasErrors = false;
a534180c
TAOSP
276 ssize_t res;
277 while ((res=it.next()) == NO_ERROR) {
278 res = preProcessImage(bundle, assets, it.getFile(), NULL);
8f940cc4
DS
279 if (res < NO_ERROR) {
280 hasErrors = true;
a534180c
TAOSP
281 }
282 }
283
8f940cc4 284 return (hasErrors || (res < NO_ERROR)) ? UNKNOWN_ERROR : NO_ERROR;
a534180c
TAOSP
285}
286
287status_t postProcessImages(const sp<AaptAssets>& assets,
288 ResourceTable* table,
289 const sp<ResourceTypeSet>& set)
290{
291 ResourceDirIterator it(set, String8("drawable"));
8f940cc4 292 bool hasErrors = false;
a534180c
TAOSP
293 ssize_t res;
294 while ((res=it.next()) == NO_ERROR) {
295 res = postProcessImage(assets, table, it.getFile());
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
304static void collect_files(const sp<AaptDir>& dir,
305 KeyedVector<String8, sp<ResourceTypeSet> >* resources)
306{
307 const DefaultKeyedVector<String8, sp<AaptGroup> >& groups = dir->getFiles();
308 int N = groups.size();
309 for (int i=0; i<N; i++) {
310 String8 leafName = groups.keyAt(i);
311 const sp<AaptGroup>& group = groups.valueAt(i);
312
313 const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files
314 = group->getFiles();
315
316 if (files.size() == 0) {
317 continue;
318 }
319
320 String8 resType = files.valueAt(0)->getResourceType();
321
322 ssize_t index = resources->indexOfKey(resType);
323
324 if (index < 0) {
325 sp<ResourceTypeSet> set = new ResourceTypeSet();
326 set->add(leafName, group);
327 resources->add(resType, set);
328 } else {
329 sp<ResourceTypeSet> set = resources->valueAt(index);
330 index = set->indexOfKey(leafName);
331 if (index < 0) {
332 set->add(leafName, group);
333 } else {
334 sp<AaptGroup> existingGroup = set->valueAt(index);
335 int M = files.size();
336 for (int j=0; j<M; j++) {
337 existingGroup->addFile(files.valueAt(j));
338 }
339 }
340 }
341 }
342}
343
344static void collect_files(const sp<AaptAssets>& ass,
345 KeyedVector<String8, sp<ResourceTypeSet> >* resources)
346{
347 const Vector<sp<AaptDir> >& dirs = ass->resDirs();
348 int N = dirs.size();
349
350 for (int i=0; i<N; i++) {
351 sp<AaptDir> d = dirs.itemAt(i);
352 collect_files(d, resources);
353
354 // don't try to include the res dir
355 ass->removeDir(d->getLeaf());
356 }
357}
358
359enum {
360 ATTR_OKAY = -1,
361 ATTR_NOT_FOUND = -2,
362 ATTR_LEADING_SPACES = -3,
363 ATTR_TRAILING_SPACES = -4
364};
365static int validateAttr(const String8& path, const ResXMLParser& parser,
366 const char* ns, const char* attr, const char* validChars, bool required)
367{
368 size_t len;
369
370 ssize_t index = parser.indexOfAttribute(ns, attr);
371 const uint16_t* str;
372 if (index >= 0 && (str=parser.getAttributeStringValue(index, &len)) != NULL) {
373 if (validChars) {
374 for (size_t i=0; i<len; i++) {
375 uint16_t c = str[i];
376 const char* p = validChars;
377 bool okay = false;
378 while (*p) {
379 if (c == *p) {
380 okay = true;
381 break;
382 }
383 p++;
384 }
385 if (!okay) {
386 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has invalid character '%c'.\n",
387 path.string(), parser.getLineNumber(),
388 String8(parser.getElementName(&len)).string(), attr, (char)str[i]);
389 return (int)i;
390 }
391 }
392 }
393 if (*str == ' ') {
394 fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not start with a space.\n",
395 path.string(), parser.getLineNumber(),
396 String8(parser.getElementName(&len)).string(), attr);
397 return ATTR_LEADING_SPACES;
398 }
399 if (str[len-1] == ' ') {
400 fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not end with a space.\n",
401 path.string(), parser.getLineNumber(),
402 String8(parser.getElementName(&len)).string(), attr);
403 return ATTR_TRAILING_SPACES;
404 }
405 return ATTR_OKAY;
406 }
407 if (required) {
408 fprintf(stderr, "%s:%d: Tag <%s> missing required attribute %s.\n",
409 path.string(), parser.getLineNumber(),
410 String8(parser.getElementName(&len)).string(), attr);
411 return ATTR_NOT_FOUND;
412 }
413 return ATTR_OKAY;
414}
415
416static void checkForIds(const String8& path, ResXMLParser& parser)
417{
418 ResXMLTree::event_code_t code;
419 while ((code=parser.next()) != ResXMLTree::END_DOCUMENT
420 && code > ResXMLTree::BAD_DOCUMENT) {
421 if (code == ResXMLTree::START_TAG) {
422 ssize_t index = parser.indexOfAttribute(NULL, "id");
423 if (index >= 0) {
406a85e3 424 fprintf(stderr, "%s:%d: warning: found plain 'id' attribute; did you mean the new 'android:id' name?\n",
a534180c
TAOSP
425 path.string(), parser.getLineNumber());
426 }
427 }
428 }
429}
430
dd854d4c 431static bool applyFileOverlay(const sp<AaptAssets>& assets,
a534180c
TAOSP
432 const sp<ResourceTypeSet>& baseSet,
433 const char *resType)
434{
435 // Replace any base level files in this category with any found from the overlay
436 // Also add any found only in the overlay.
437 sp<AaptAssets> overlay = assets->getOverlay();
438 String8 resTypeString(resType);
dd854d4c 439
a534180c
TAOSP
440 // work through the linked list of overlays
441 while (overlay.get()) {
442 KeyedVector<String8, sp<ResourceTypeSet> >* overlayRes = overlay->getResources();
443
444 // get the overlay resources of the requested type
445 ssize_t index = overlayRes->indexOfKey(resTypeString);
446 if (index >= 0) {
447 sp<ResourceTypeSet> overlaySet = overlayRes->valueAt(index);
448
449 // for each of the resources, check for a match in the previously built
450 // non-overlay "baseset".
451 size_t overlayCount = overlaySet->size();
452 for (size_t overlayIndex=0; overlayIndex<overlayCount; overlayIndex++) {
453 size_t baseIndex = baseSet->indexOfKey(overlaySet->keyAt(overlayIndex));
dd854d4c 454 if (baseIndex < UNKNOWN_ERROR) {
a534180c
TAOSP
455 // look for same flavor. For a given file (strings.xml, for example)
456 // there may be a locale specific or other flavors - we want to match
457 // the same flavor.
458 sp<AaptGroup> overlayGroup = overlaySet->valueAt(overlayIndex);
459 sp<AaptGroup> baseGroup = baseSet->valueAt(baseIndex);
460
461 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > baseFiles =
462 baseGroup->getFiles();
463 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > overlayFiles =
464 overlayGroup->getFiles();
465 size_t overlayGroupSize = overlayFiles.size();
466 for (size_t overlayGroupIndex = 0;
467 overlayGroupIndex<overlayGroupSize;
468 overlayGroupIndex++) {
469 size_t baseFileIndex =
470 baseFiles.indexOfKey(overlayFiles.keyAt(overlayGroupIndex));
471 if(baseFileIndex < UNKNOWN_ERROR) {
472 baseGroup->removeFile(baseFileIndex);
473 } else {
474 // didn't find a match fall through and add it..
475 }
476 baseGroup->addFile(overlayFiles.valueAt(overlayGroupIndex));
a76631e8 477 assets->addGroupEntry(overlayFiles.keyAt(overlayGroupIndex));
a534180c
TAOSP
478 }
479 } else {
480 // this group doesn't exist (a file that's only in the overlay)
a8c9cd56
DH
481 baseSet->add(overlaySet->keyAt(overlayIndex),
482 overlaySet->valueAt(overlayIndex));
a76631e8
DH
483 // make sure all flavors are defined in the resources.
484 sp<AaptGroup> overlayGroup = overlaySet->valueAt(overlayIndex);
485 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > overlayFiles =
486 overlayGroup->getFiles();
487 size_t overlayGroupSize = overlayFiles.size();
488 for (size_t overlayGroupIndex = 0;
489 overlayGroupIndex<overlayGroupSize;
490 overlayGroupIndex++) {
491 assets->addGroupEntry(overlayFiles.keyAt(overlayGroupIndex));
492 }
a534180c
TAOSP
493 }
494 }
495 // this overlay didn't have resources for this type
496 }
497 // try next overlay
498 overlay = overlay->getOverlay();
499 }
dd854d4c 500 return true;
a534180c
TAOSP
501}
502
e942a5c2
DH
503void addTagAttribute(const sp<XMLNode>& node, const char* ns8,
504 const char* attr8, const char* value)
505{
506 if (value == NULL) {
507 return;
508 }
509
510 const String16 ns(ns8);
511 const String16 attr(attr8);
512
513 if (node->getAttribute(ns, attr) != NULL) {
514 fprintf(stderr, "Warning: AndroidManifest.xml already defines %s (in %s)\n",
515 String8(attr).string(), String8(ns).string());
516 return;
517 }
518
519 node->addAttribute(ns, attr, String16(value));
520}
521
522status_t massageManifest(Bundle* bundle, sp<XMLNode> root)
523{
524 root = root->searchElement(String16(), String16("manifest"));
525 if (root == NULL) {
526 fprintf(stderr, "No <manifest> tag.\n");
527 return UNKNOWN_ERROR;
528 }
529
530 addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionCode",
531 bundle->getVersionCode());
532 addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionName",
533 bundle->getVersionName());
534
535 if (bundle->getMinSdkVersion() != NULL
536 || bundle->getTargetSdkVersion() != NULL
537 || bundle->getMaxSdkVersion() != NULL) {
538 sp<XMLNode> vers = root->getChildElement(String16(), String16("uses-sdk"));
539 if (vers == NULL) {
540 vers = XMLNode::newElement(root->getFilename(), String16(), String16("uses-sdk"));
541 root->insertChildAt(vers, 0);
542 }
543
544 addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "minSdkVersion",
545 bundle->getMinSdkVersion());
546 addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "targetSdkVersion",
547 bundle->getTargetSdkVersion());
548 addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "maxSdkVersion",
549 bundle->getMaxSdkVersion());
550 }
551
552 return NO_ERROR;
553}
554
a534180c
TAOSP
555#define ASSIGN_IT(n) \
556 do { \
557 ssize_t index = resources->indexOfKey(String8(#n)); \
558 if (index >= 0) { \
559 n ## s = resources->valueAt(index); \
560 } \
561 } while (0)
562
563status_t buildResources(Bundle* bundle, const sp<AaptAssets>& assets)
564{
565 // First, look for a package file to parse. This is required to
566 // be able to generate the resource information.
567 sp<AaptGroup> androidManifestFile =
568 assets->getFiles().valueFor(String8("AndroidManifest.xml"));
569 if (androidManifestFile == NULL) {
570 fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n");
571 return UNKNOWN_ERROR;
572 }
573
574 status_t err = parsePackage(assets, androidManifestFile);
575 if (err != NO_ERROR) {
576 return err;
577 }
578
579 NOISY(printf("Creating resources for package %s\n",
580 assets->getPackage().string()));
581
582 ResourceTable table(bundle, String16(assets->getPackage()));
583 err = table.addIncludedResources(bundle, assets);
584 if (err != NO_ERROR) {
585 return err;
586 }
587
588 NOISY(printf("Found %d included resource packages\n", (int)table.size()));
589
590 // --------------------------------------------------------------
591 // First, gather all resource information.
592 // --------------------------------------------------------------
593
594 // resType -> leafName -> group
595 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
596 new KeyedVector<String8, sp<ResourceTypeSet> >;
597 collect_files(assets, resources);
598
599 sp<ResourceTypeSet> drawables;
600 sp<ResourceTypeSet> layouts;
601 sp<ResourceTypeSet> anims;
602 sp<ResourceTypeSet> xmls;
603 sp<ResourceTypeSet> raws;
604 sp<ResourceTypeSet> colors;
605 sp<ResourceTypeSet> menus;
606
607 ASSIGN_IT(drawable);
608 ASSIGN_IT(layout);
609 ASSIGN_IT(anim);
610 ASSIGN_IT(xml);
611 ASSIGN_IT(raw);
612 ASSIGN_IT(color);
613 ASSIGN_IT(menu);
614
615 assets->setResources(resources);
616 // now go through any resource overlays and collect their files
617 sp<AaptAssets> current = assets->getOverlay();
618 while(current.get()) {
619 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
620 new KeyedVector<String8, sp<ResourceTypeSet> >;
621 current->setResources(resources);
622 collect_files(current, resources);
623 current = current->getOverlay();
624 }
625 // apply the overlay files to the base set
dd854d4c
RG
626 if (!applyFileOverlay(assets, drawables, "drawable") ||
627 !applyFileOverlay(assets, layouts, "layout") ||
628 !applyFileOverlay(assets, anims, "anim") ||
629 !applyFileOverlay(assets, xmls, "xml") ||
630 !applyFileOverlay(assets, raws, "raw") ||
631 !applyFileOverlay(assets, colors, "color") ||
632 !applyFileOverlay(assets, menus, "menu")) {
633 return UNKNOWN_ERROR;
634 }
a534180c
TAOSP
635
636 bool hasErrors = false;
637
638 if (drawables != NULL) {
639 err = preProcessImages(bundle, assets, drawables);
640 if (err == NO_ERROR) {
641 err = makeFileResources(bundle, assets, &table, drawables, "drawable");
642 if (err != NO_ERROR) {
643 hasErrors = true;
644 }
645 } else {
646 hasErrors = true;
647 }
648 }
649
650 if (layouts != NULL) {
651 err = makeFileResources(bundle, assets, &table, layouts, "layout");
652 if (err != NO_ERROR) {
653 hasErrors = true;
654 }
655 }
656
657 if (anims != NULL) {
658 err = makeFileResources(bundle, assets, &table, anims, "anim");
659 if (err != NO_ERROR) {
660 hasErrors = true;
661 }
662 }
663
664 if (xmls != NULL) {
665 err = makeFileResources(bundle, assets, &table, xmls, "xml");
666 if (err != NO_ERROR) {
667 hasErrors = true;
668 }
669 }
670
671 if (raws != NULL) {
672 err = makeFileResources(bundle, assets, &table, raws, "raw");
673 if (err != NO_ERROR) {
674 hasErrors = true;
675 }
676 }
677
678 // compile resources
679 current = assets;
680 while(current.get()) {
681 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
682 current->getResources();
683
684 ssize_t index = resources->indexOfKey(String8("values"));
685 if (index >= 0) {
686 ResourceDirIterator it(resources->valueAt(index), String8("values"));
687 ssize_t res;
688 while ((res=it.next()) == NO_ERROR) {
689 sp<AaptFile> file = it.getFile();
690 res = compileResourceFile(bundle, assets, file, it.getParams(),
691 (current!=assets), &table);
692 if (res != NO_ERROR) {
693 hasErrors = true;
694 }
695 }
696 }
697 current = current->getOverlay();
698 }
699
700 if (colors != NULL) {
701 err = makeFileResources(bundle, assets, &table, colors, "color");
702 if (err != NO_ERROR) {
703 hasErrors = true;
704 }
705 }
706
707 if (menus != NULL) {
708 err = makeFileResources(bundle, assets, &table, menus, "menu");
709 if (err != NO_ERROR) {
710 hasErrors = true;
711 }
712 }
713
714 // --------------------------------------------------------------------
715 // Assignment of resource IDs and initial generation of resource table.
716 // --------------------------------------------------------------------
717
718 if (table.hasResources()) {
719 sp<AaptFile> resFile(getResourceFile(assets));
720 if (resFile == NULL) {
721 fprintf(stderr, "Error: unable to generate entry for resource data\n");
722 return UNKNOWN_ERROR;
723 }
724
725 err = table.assignResourceIds();
726 if (err < NO_ERROR) {
727 return err;
728 }
729 }
730
731 // --------------------------------------------------------------
732 // Finally, we can now we can compile XML files, which may reference
733 // resources.
734 // --------------------------------------------------------------
735
736 if (layouts != NULL) {
737 ResourceDirIterator it(layouts, String8("layout"));
738 while ((err=it.next()) == NO_ERROR) {
739 String8 src = it.getFile()->getPrintableSource();
740 err = compileXmlFile(assets, it.getFile(), &table);
741 if (err == NO_ERROR) {
742 ResXMLTree block;
743 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
744 checkForIds(src, block);
745 } else {
746 hasErrors = true;
747 }
748 }
749
750 if (err < NO_ERROR) {
751 hasErrors = true;
752 }
753 err = NO_ERROR;
754 }
755
756 if (anims != NULL) {
757 ResourceDirIterator it(anims, String8("anim"));
758 while ((err=it.next()) == NO_ERROR) {
759 err = compileXmlFile(assets, it.getFile(), &table);
760 if (err != NO_ERROR) {
761 hasErrors = true;
762 }
763 }
764
765 if (err < NO_ERROR) {
766 hasErrors = true;
767 }
768 err = NO_ERROR;
769 }
770
771 if (xmls != NULL) {
772 ResourceDirIterator it(xmls, String8("xml"));
773 while ((err=it.next()) == NO_ERROR) {
774 err = compileXmlFile(assets, it.getFile(), &table);
775 if (err != NO_ERROR) {
776 hasErrors = true;
777 }
778 }
779
780 if (err < NO_ERROR) {
781 hasErrors = true;
782 }
783 err = NO_ERROR;
784 }
785
786 if (drawables != NULL) {
787 err = postProcessImages(assets, &table, drawables);
788 if (err != NO_ERROR) {
789 hasErrors = true;
790 }
791 }
792
793 if (colors != NULL) {
794 ResourceDirIterator it(colors, String8("color"));
795 while ((err=it.next()) == NO_ERROR) {
796 err = compileXmlFile(assets, it.getFile(), &table);
797 if (err != NO_ERROR) {
798 hasErrors = true;
799 }
800 }
801
802 if (err < NO_ERROR) {
803 hasErrors = true;
804 }
805 err = NO_ERROR;
806 }
807
808 if (menus != NULL) {
809 ResourceDirIterator it(menus, String8("menu"));
810 while ((err=it.next()) == NO_ERROR) {
811 String8 src = it.getFile()->getPrintableSource();
812 err = compileXmlFile(assets, it.getFile(), &table);
813 if (err != NO_ERROR) {
814 hasErrors = true;
815 }
816 ResXMLTree block;
817 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
818 checkForIds(src, block);
819 }
820
821 if (err < NO_ERROR) {
822 hasErrors = true;
823 }
824 err = NO_ERROR;
825 }
826
827 const sp<AaptFile> manifestFile(androidManifestFile->getFiles().valueAt(0));
828 String8 manifestPath(manifestFile->getPrintableSource());
829
830 // Perform a basic validation of the manifest file. This time we
831 // parse it with the comments intact, so that we can use them to
832 // generate java docs... so we are not going to write this one
833 // back out to the final manifest data.
834 err = compileXmlFile(assets, manifestFile, &table,
835 XML_COMPILE_ASSIGN_ATTRIBUTE_IDS
836 | XML_COMPILE_STRIP_WHITESPACE | XML_COMPILE_STRIP_RAW_VALUES);
837 if (err < NO_ERROR) {
838 return err;
839 }
840 ResXMLTree block;
841 block.setTo(manifestFile->getData(), manifestFile->getSize(), true);
842 String16 manifest16("manifest");
843 String16 permission16("permission");
844 String16 permission_group16("permission-group");
845 String16 uses_permission16("uses-permission");
846 String16 instrumentation16("instrumentation");
847 String16 application16("application");
848 String16 provider16("provider");
849 String16 service16("service");
850 String16 receiver16("receiver");
851 String16 activity16("activity");
852 String16 action16("action");
853 String16 category16("category");
854 String16 data16("scheme");
855 const char* packageIdentChars = "abcdefghijklmnopqrstuvwxyz"
856 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789";
857 const char* packageIdentCharsWithTheStupid = "abcdefghijklmnopqrstuvwxyz"
858 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
859 const char* classIdentChars = "abcdefghijklmnopqrstuvwxyz"
860 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789$";
861 const char* processIdentChars = "abcdefghijklmnopqrstuvwxyz"
862 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:";
863 const char* authoritiesIdentChars = "abcdefghijklmnopqrstuvwxyz"
864 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-:;";
865 const char* typeIdentChars = "abcdefghijklmnopqrstuvwxyz"
866 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:-/*+";
867 const char* schemeIdentChars = "abcdefghijklmnopqrstuvwxyz"
868 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
869 ResXMLTree::event_code_t code;
870 sp<AaptSymbols> permissionSymbols;
871 sp<AaptSymbols> permissionGroupSymbols;
872 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
873 && code > ResXMLTree::BAD_DOCUMENT) {
874 if (code == ResXMLTree::START_TAG) {
875 size_t len;
876 if (block.getElementNamespace(&len) != NULL) {
877 continue;
878 }
879 if (strcmp16(block.getElementName(&len), manifest16.string()) == 0) {
880 if (validateAttr(manifestPath, block, NULL, "package",
881 packageIdentChars, true) != ATTR_OKAY) {
882 hasErrors = true;
883 }
884 } else if (strcmp16(block.getElementName(&len), permission16.string()) == 0
885 || strcmp16(block.getElementName(&len), permission_group16.string()) == 0) {
886 const bool isGroup = strcmp16(block.getElementName(&len),
887 permission_group16.string()) == 0;
888 if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
889 isGroup ? packageIdentCharsWithTheStupid
890 : packageIdentChars, true) != ATTR_OKAY) {
891 hasErrors = true;
892 }
893 SourcePos srcPos(manifestPath, block.getLineNumber());
894 sp<AaptSymbols> syms;
895 if (!isGroup) {
896 syms = permissionSymbols;
897 if (syms == NULL) {
898 sp<AaptSymbols> symbols =
899 assets->getSymbolsFor(String8("Manifest"));
900 syms = permissionSymbols = symbols->addNestedSymbol(
901 String8("permission"), srcPos);
902 }
903 } else {
904 syms = permissionGroupSymbols;
905 if (syms == NULL) {
906 sp<AaptSymbols> symbols =
907 assets->getSymbolsFor(String8("Manifest"));
908 syms = permissionGroupSymbols = symbols->addNestedSymbol(
909 String8("permission_group"), srcPos);
910 }
911 }
912 size_t len;
913 ssize_t index = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "name");
914 const uint16_t* id = block.getAttributeStringValue(index, &len);
915 if (id == NULL) {
916 fprintf(stderr, "%s:%d: missing name attribute in element <%s>.\n",
917 manifestPath.string(), block.getLineNumber(),
918 String8(block.getElementName(&len)).string());
919 hasErrors = true;
920 break;
921 }
922 String8 idStr(id);
923 char* p = idStr.lockBuffer(idStr.size());
924 char* e = p + idStr.size();
925 bool begins_with_digit = true; // init to true so an empty string fails
926 while (e > p) {
927 e--;
928 if (*e >= '0' && *e <= '9') {
929 begins_with_digit = true;
930 continue;
931 }
932 if ((*e >= 'a' && *e <= 'z') ||
933 (*e >= 'A' && *e <= 'Z') ||
934 (*e == '_')) {
935 begins_with_digit = false;
936 continue;
937 }
938 if (isGroup && (*e == '-')) {
939 *e = '_';
940 begins_with_digit = false;
941 continue;
942 }
943 e++;
944 break;
945 }
946 idStr.unlockBuffer();
947 // verify that we stopped because we hit a period or
948 // the beginning of the string, and that the
949 // identifier didn't begin with a digit.
950 if (begins_with_digit || (e != p && *(e-1) != '.')) {
951 fprintf(stderr,
952 "%s:%d: Permission name <%s> is not a valid Java symbol\n",
953 manifestPath.string(), block.getLineNumber(), idStr.string());
954 hasErrors = true;
955 }
956 syms->addStringSymbol(String8(e), idStr, srcPos);
957 const uint16_t* cmt = block.getComment(&len);
958 if (cmt != NULL && *cmt != 0) {
959 //printf("Comment of %s: %s\n", String8(e).string(),
960 // String8(cmt).string());
961 syms->appendComment(String8(e), String16(cmt), srcPos);
962 } else {
963 //printf("No comment for %s\n", String8(e).string());
964 }
965 syms->makeSymbolPublic(String8(e), srcPos);
966 } else if (strcmp16(block.getElementName(&len), uses_permission16.string()) == 0) {
967 if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
968 packageIdentChars, true) != ATTR_OKAY) {
969 hasErrors = true;
970 }
971 } else if (strcmp16(block.getElementName(&len), instrumentation16.string()) == 0) {
972 if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
973 classIdentChars, true) != ATTR_OKAY) {
974 hasErrors = true;
975 }
976 if (validateAttr(manifestPath, block,
977 RESOURCES_ANDROID_NAMESPACE, "targetPackage",
978 packageIdentChars, true) != ATTR_OKAY) {
979 hasErrors = true;
980 }
981 } else if (strcmp16(block.getElementName(&len), application16.string()) == 0) {
982 if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
983 classIdentChars, false) != ATTR_OKAY) {
984 hasErrors = true;
985 }
986 if (validateAttr(manifestPath, block,
987 RESOURCES_ANDROID_NAMESPACE, "permission",
988 packageIdentChars, false) != ATTR_OKAY) {
989 hasErrors = true;
990 }
991 if (validateAttr(manifestPath, block,
992 RESOURCES_ANDROID_NAMESPACE, "process",
993 processIdentChars, false) != ATTR_OKAY) {
994 hasErrors = true;
995 }
996 if (validateAttr(manifestPath, block,
997 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
998 processIdentChars, false) != ATTR_OKAY) {
999 hasErrors = true;
1000 }
1001 } else if (strcmp16(block.getElementName(&len), provider16.string()) == 0) {
1002 if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
1003 classIdentChars, true) != ATTR_OKAY) {
1004 hasErrors = true;
1005 }
1006 if (validateAttr(manifestPath, block,
1007 RESOURCES_ANDROID_NAMESPACE, "authorities",
1008 authoritiesIdentChars, true) != ATTR_OKAY) {
1009 hasErrors = true;
1010 }
1011 if (validateAttr(manifestPath, block,
1012 RESOURCES_ANDROID_NAMESPACE, "permission",
1013 packageIdentChars, false) != ATTR_OKAY) {
1014 hasErrors = true;
1015 }
1016 if (validateAttr(manifestPath, block,
1017 RESOURCES_ANDROID_NAMESPACE, "process",
1018 processIdentChars, false) != ATTR_OKAY) {
1019 hasErrors = true;
1020 }
1021 } else if (strcmp16(block.getElementName(&len), service16.string()) == 0
1022 || strcmp16(block.getElementName(&len), receiver16.string()) == 0
1023 || strcmp16(block.getElementName(&len), activity16.string()) == 0) {
1024 if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
1025 classIdentChars, true) != ATTR_OKAY) {
1026 hasErrors = true;
1027 }
1028 if (validateAttr(manifestPath, block,
1029 RESOURCES_ANDROID_NAMESPACE, "permission",
1030 packageIdentChars, false) != ATTR_OKAY) {
1031 hasErrors = true;
1032 }
1033 if (validateAttr(manifestPath, block,
1034 RESOURCES_ANDROID_NAMESPACE, "process",
1035 processIdentChars, false) != ATTR_OKAY) {
1036 hasErrors = true;
1037 }
1038 if (validateAttr(manifestPath, block,
1039 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
1040 processIdentChars, false) != ATTR_OKAY) {
1041 hasErrors = true;
1042 }
1043 } else if (strcmp16(block.getElementName(&len), action16.string()) == 0
1044 || strcmp16(block.getElementName(&len), category16.string()) == 0) {
1045 if (validateAttr(manifestPath, block,
1046 RESOURCES_ANDROID_NAMESPACE, "name",
1047 packageIdentChars, true) != ATTR_OKAY) {
1048 hasErrors = true;
1049 }
1050 } else if (strcmp16(block.getElementName(&len), data16.string()) == 0) {
1051 if (validateAttr(manifestPath, block,
1052 RESOURCES_ANDROID_NAMESPACE, "mimeType",
1053 typeIdentChars, true) != ATTR_OKAY) {
1054 hasErrors = true;
1055 }
1056 if (validateAttr(manifestPath, block,
1057 RESOURCES_ANDROID_NAMESPACE, "scheme",
1058 schemeIdentChars, true) != ATTR_OKAY) {
1059 hasErrors = true;
1060 }
1061 }
1062 }
1063 }
1064
1065 if (table.validateLocalizations()) {
1066 hasErrors = true;
1067 }
1068
1069 if (hasErrors) {
1070 return UNKNOWN_ERROR;
1071 }
1072
1073 // Generate final compiled manifest file.
1074 manifestFile->clearData();
e942a5c2
DH
1075 sp<XMLNode> manifestTree = XMLNode::parse(manifestFile);
1076 if (manifestTree == NULL) {
1077 return UNKNOWN_ERROR;
1078 }
1079 err = massageManifest(bundle, manifestTree);
1080 if (err < NO_ERROR) {
1081 return err;
1082 }
1083 err = compileXmlFile(assets, manifestTree, manifestFile, &table);
a534180c
TAOSP
1084 if (err < NO_ERROR) {
1085 return err;
1086 }
1087
1088 //block.restart();
1089 //printXMLBlock(&block);
1090
1091 // --------------------------------------------------------------
1092 // Generate the final resource table.
1093 // Re-flatten because we may have added new resource IDs
1094 // --------------------------------------------------------------
1095
1096 if (table.hasResources()) {
1097 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1098 err = table.addSymbols(symbols);
1099 if (err < NO_ERROR) {
1100 return err;
1101 }
1102
1103 sp<AaptFile> resFile(getResourceFile(assets));
1104 if (resFile == NULL) {
1105 fprintf(stderr, "Error: unable to generate entry for resource data\n");
1106 return UNKNOWN_ERROR;
1107 }
1108
1109 err = table.flatten(bundle, resFile);
1110 if (err < NO_ERROR) {
1111 return err;
1112 }
1113
1114 if (bundle->getPublicOutputFile()) {
1115 FILE* fp = fopen(bundle->getPublicOutputFile(), "w+");
1116 if (fp == NULL) {
1117 fprintf(stderr, "ERROR: Unable to open public definitions output file %s: %s\n",
1118 (const char*)bundle->getPublicOutputFile(), strerror(errno));
1119 return UNKNOWN_ERROR;
1120 }
1121 if (bundle->getVerbose()) {
1122 printf(" Writing public definitions to %s.\n", bundle->getPublicOutputFile());
1123 }
1124 table.writePublicDefinitions(String16(assets->getPackage()), fp);
981d1579 1125 fclose(fp);
a534180c
TAOSP
1126 }
1127
1128 NOISY(
1129 ResTable rt;
1130 rt.add(resFile->getData(), resFile->getSize(), NULL);
1131 printf("Generated resources:\n");
1132 rt.print();
1133 )
1134
1135 // These resources are now considered to be a part of the included
1136 // resources, for others to reference.
1137 err = assets->addIncludedResources(resFile);
1138 if (err < NO_ERROR) {
1139 fprintf(stderr, "ERROR: Unable to parse generated resources, aborting.\n");
1140 return err;
1141 }
1142 }
a534180c
TAOSP
1143 return err;
1144}
1145
1146static const char* getIndentSpace(int indent)
1147{
1148static const char whitespace[] =
1149" ";
1150
1151 return whitespace + sizeof(whitespace) - 1 - indent*4;
1152}
1153
1154static status_t fixupSymbol(String16* inoutSymbol)
1155{
1156 inoutSymbol->replaceAll('.', '_');
1157 inoutSymbol->replaceAll(':', '_');
1158 return NO_ERROR;
1159}
1160
1161static String16 getAttributeComment(const sp<AaptAssets>& assets,
1162 const String8& name,
1163 String16* outTypeComment = NULL)
1164{
1165 sp<AaptSymbols> asym = assets->getSymbolsFor(String8("R"));
1166 if (asym != NULL) {
1167 //printf("Got R symbols!\n");
1168 asym = asym->getNestedSymbols().valueFor(String8("attr"));
1169 if (asym != NULL) {
1170 //printf("Got attrs symbols! comment %s=%s\n",
1171 // name.string(), String8(asym->getComment(name)).string());
1172 if (outTypeComment != NULL) {
1173 *outTypeComment = asym->getTypeComment(name);
1174 }
1175 return asym->getComment(name);
1176 }
1177 }
1178 return String16();
1179}
1180
1181static status_t writeLayoutClasses(
1182 FILE* fp, const sp<AaptAssets>& assets,
1183 const sp<AaptSymbols>& symbols, int indent, bool includePrivate)
1184{
1185 const char* indentStr = getIndentSpace(indent);
1186 if (!includePrivate) {
1187 fprintf(fp, "%s/** @doconly */\n", indentStr);
1188 }
1189 fprintf(fp, "%spublic static final class styleable {\n", indentStr);
1190 indent++;
1191
1192 String16 attr16("attr");
1193 String16 package16(assets->getPackage());
1194
1195 indentStr = getIndentSpace(indent);
1196 bool hasErrors = false;
1197
1198 size_t i;
1199 size_t N = symbols->getNestedSymbols().size();
1200 for (i=0; i<N; i++) {
1201 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
1202 String16 nclassName16(symbols->getNestedSymbols().keyAt(i));
1203 String8 realClassName(nclassName16);
1204 if (fixupSymbol(&nclassName16) != NO_ERROR) {
1205 hasErrors = true;
1206 }
1207 String8 nclassName(nclassName16);
1208
1209 SortedVector<uint32_t> idents;
1210 Vector<uint32_t> origOrder;
1211 Vector<bool> publicFlags;
1212
1213 size_t a;
1214 size_t NA = nsymbols->getSymbols().size();
1215 for (a=0; a<NA; a++) {
1216 const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a));
1217 int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32
1218 ? sym.int32Val : 0;
1219 bool isPublic = true;
1220 if (code == 0) {
1221 String16 name16(sym.name);
1222 uint32_t typeSpecFlags;
1223 code = assets->getIncludedResources().identifierForName(
1224 name16.string(), name16.size(),
1225 attr16.string(), attr16.size(),
1226 package16.string(), package16.size(), &typeSpecFlags);
1227 if (code == 0) {
1228 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
1229 nclassName.string(), sym.name.string());
1230 hasErrors = true;
1231 }
1232 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
1233 }
1234 idents.add(code);
1235 origOrder.add(code);
1236 publicFlags.add(isPublic);
1237 }
1238
1239 NA = idents.size();
1240
f3cd0b05
DH
1241 bool deprecated = false;
1242
a534180c
TAOSP
1243 String16 comment = symbols->getComment(realClassName);
1244 fprintf(fp, "%s/** ", indentStr);
1245 if (comment.size() > 0) {
f3cd0b05
DH
1246 String8 cmt(comment);
1247 fprintf(fp, "%s\n", cmt.string());
1248 if (strstr(cmt.string(), "@deprecated") != NULL) {
1249 deprecated = true;
1250 }
a534180c
TAOSP
1251 } else {
1252 fprintf(fp, "Attributes that can be used with a %s.\n", nclassName.string());
1253 }
1254 bool hasTable = false;
1255 for (a=0; a<NA; a++) {
1256 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1257 if (pos >= 0) {
1258 if (!hasTable) {
1259 hasTable = true;
1260 fprintf(fp,
1261 "%s <p>Includes the following attributes:</p>\n"
1262 "%s <table border=\"2\" width=\"85%%\" align=\"center\" frame=\"hsides\" rules=\"all\" cellpadding=\"5\">\n"
1263 "%s <colgroup align=\"left\" />\n"
1264 "%s <colgroup align=\"left\" />\n"
1265 "%s <tr><th>Attribute<th>Summary</tr>\n",
1266 indentStr,
1267 indentStr,
1268 indentStr,
1269 indentStr,
1270 indentStr);
1271 }
1272 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1273 if (!publicFlags.itemAt(a) && !includePrivate) {
1274 continue;
1275 }
1276 String8 name8(sym.name);
1277 String16 comment(sym.comment);
1278 if (comment.size() <= 0) {
1279 comment = getAttributeComment(assets, name8);
1280 }
1281 if (comment.size() > 0) {
1282 const char16_t* p = comment.string();
1283 while (*p != 0 && *p != '.') {
1284 if (*p == '{') {
1285 while (*p != 0 && *p != '}') {
1286 p++;
1287 }
1288 } else {
1289 p++;
1290 }
1291 }
1292 if (*p == '.') {
1293 p++;
1294 }
1295 comment = String16(comment.string(), p-comment.string());
1296 }
1297 String16 name(name8);
1298 fixupSymbol(&name);
1299 fprintf(fp, "%s <tr><th><code>{@link #%s_%s %s:%s}</code><td>%s</tr>\n",
1300 indentStr, nclassName.string(),
1301 String8(name).string(),
1302 assets->getPackage().string(),
1303 String8(name).string(),
1304 String8(comment).string());
1305 }
1306 }
1307 if (hasTable) {
1308 fprintf(fp, "%s </table>\n", indentStr);
1309 }
1310 for (a=0; a<NA; a++) {
1311 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1312 if (pos >= 0) {
1313 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1314 if (!publicFlags.itemAt(a) && !includePrivate) {
1315 continue;
1316 }
1317 String16 name(sym.name);
1318 fixupSymbol(&name);
1319 fprintf(fp, "%s @see #%s_%s\n",
1320 indentStr, nclassName.string(),
1321 String8(name).string());
1322 }
1323 }
1324 fprintf(fp, "%s */\n", getIndentSpace(indent));
1325
f3cd0b05
DH
1326 if (deprecated) {
1327 fprintf(fp, "%s@Deprecated\n", indentStr);
1328 }
1329
a534180c
TAOSP
1330 fprintf(fp,
1331 "%spublic static final int[] %s = {\n"
1332 "%s",
1333 indentStr, nclassName.string(),
1334 getIndentSpace(indent+1));
1335
1336 for (a=0; a<NA; a++) {
1337 if (a != 0) {
1338 if ((a&3) == 0) {
1339 fprintf(fp, ",\n%s", getIndentSpace(indent+1));
1340 } else {
1341 fprintf(fp, ", ");
1342 }
1343 }
1344 fprintf(fp, "0x%08x", idents[a]);
1345 }
1346
1347 fprintf(fp, "\n%s};\n", indentStr);
1348
1349 for (a=0; a<NA; a++) {
1350 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1351 if (pos >= 0) {
1352 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1353 if (!publicFlags.itemAt(a) && !includePrivate) {
1354 continue;
1355 }
1356 String8 name8(sym.name);
1357 String16 comment(sym.comment);
1358 String16 typeComment;
1359 if (comment.size() <= 0) {
1360 comment = getAttributeComment(assets, name8, &typeComment);
1361 } else {
1362 getAttributeComment(assets, name8, &typeComment);
1363 }
1364 String16 name(name8);
1365 if (fixupSymbol(&name) != NO_ERROR) {
1366 hasErrors = true;
1367 }
1368
1369 uint32_t typeSpecFlags = 0;
1370 String16 name16(sym.name);
1371 assets->getIncludedResources().identifierForName(
1372 name16.string(), name16.size(),
1373 attr16.string(), attr16.size(),
1374 package16.string(), package16.size(), &typeSpecFlags);
1375 //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
1376 // String8(attr16).string(), String8(name16).string(), typeSpecFlags);
1377 const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
f3cd0b05
DH
1378
1379 bool deprecated = false;
1380
a534180c
TAOSP
1381 fprintf(fp, "%s/**\n", indentStr);
1382 if (comment.size() > 0) {
f3cd0b05 1383 String8 cmt(comment);
a534180c 1384 fprintf(fp, "%s <p>\n%s @attr description\n", indentStr, indentStr);
f3cd0b05
DH
1385 fprintf(fp, "%s %s\n", indentStr, cmt.string());
1386 if (strstr(cmt.string(), "@deprecated") != NULL) {
1387 deprecated = true;
1388 }
a534180c
TAOSP
1389 } else {
1390 fprintf(fp,
1391 "%s <p>This symbol is the offset where the {@link %s.R.attr#%s}\n"
1392 "%s attribute's value can be found in the {@link #%s} array.\n",
1393 indentStr,
1394 pub ? assets->getPackage().string()
1395 : assets->getSymbolsPrivatePackage().string(),
1396 String8(name).string(),
1397 indentStr, nclassName.string());
1398 }
1399 if (typeComment.size() > 0) {
f3cd0b05
DH
1400 String8 cmt(typeComment);
1401 fprintf(fp, "\n\n%s %s\n", indentStr, cmt.string());
1402 if (strstr(cmt.string(), "@deprecated") != NULL) {
1403 deprecated = true;
1404 }
a534180c
TAOSP
1405 }
1406 if (comment.size() > 0) {
1407 if (pub) {
1408 fprintf(fp,
1409 "%s <p>This corresponds to the global attribute"
1410 "%s resource symbol {@link %s.R.attr#%s}.\n",
1411 indentStr, indentStr,
1412 assets->getPackage().string(),
1413 String8(name).string());
1414 } else {
1415 fprintf(fp,
1416 "%s <p>This is a private symbol.\n", indentStr);
1417 }
1418 }
1419 fprintf(fp, "%s @attr name %s:%s\n", indentStr,
1420 "android", String8(name).string());
1421 fprintf(fp, "%s*/\n", indentStr);
f3cd0b05
DH
1422 if (deprecated) {
1423 fprintf(fp, "%s@Deprecated\n", indentStr);
1424 }
a534180c
TAOSP
1425 fprintf(fp,
1426 "%spublic static final int %s_%s = %d;\n",
1427 indentStr, nclassName.string(),
1428 String8(name).string(), (int)pos);
1429 }
1430 }
1431 }
1432
1433 indent--;
1434 fprintf(fp, "%s};\n", getIndentSpace(indent));
1435 return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
1436}
1437
1438static status_t writeSymbolClass(
1439 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
1440 const sp<AaptSymbols>& symbols, const String8& className, int indent)
1441{
1442 fprintf(fp, "%spublic %sfinal class %s {\n",
1443 getIndentSpace(indent),
1444 indent != 0 ? "static " : "", className.string());
1445 indent++;
1446
1447 size_t i;
1448 status_t err = NO_ERROR;
1449
1450 size_t N = symbols->getSymbols().size();
1451 for (i=0; i<N; i++) {
1452 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
1453 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
1454 continue;
1455 }
1456 if (!includePrivate && !sym.isPublic) {
1457 continue;
1458 }
1459 String16 name(sym.name);
1460 String8 realName(name);
1461 if (fixupSymbol(&name) != NO_ERROR) {
1462 return UNKNOWN_ERROR;
1463 }
1464 String16 comment(sym.comment);
1465 bool haveComment = false;
f3cd0b05 1466 bool deprecated = false;
a534180c
TAOSP
1467 if (comment.size() > 0) {
1468 haveComment = true;
f3cd0b05 1469 String8 cmt(comment);
a534180c
TAOSP
1470 fprintf(fp,
1471 "%s/** %s\n",
f3cd0b05
DH
1472 getIndentSpace(indent), cmt.string());
1473 if (strstr(cmt.string(), "@deprecated") != NULL) {
1474 deprecated = true;
1475 }
a534180c
TAOSP
1476 } else if (sym.isPublic && !includePrivate) {
1477 sym.sourcePos.warning("No comment for public symbol %s:%s/%s",
1478 assets->getPackage().string(), className.string(),
1479 String8(sym.name).string());
1480 }
1481 String16 typeComment(sym.typeComment);
1482 if (typeComment.size() > 0) {
f3cd0b05 1483 String8 cmt(typeComment);
a534180c
TAOSP
1484 if (!haveComment) {
1485 haveComment = true;
1486 fprintf(fp,
f3cd0b05 1487 "%s/** %s\n", getIndentSpace(indent), cmt.string());
a534180c
TAOSP
1488 } else {
1489 fprintf(fp,
f3cd0b05
DH
1490 "%s %s\n", getIndentSpace(indent), cmt.string());
1491 }
1492 if (strstr(cmt.string(), "@deprecated") != NULL) {
1493 deprecated = true;
a534180c
TAOSP
1494 }
1495 }
1496 if (haveComment) {
1497 fprintf(fp,"%s */\n", getIndentSpace(indent));
1498 }
f3cd0b05
DH
1499 if (deprecated) {
1500 fprintf(fp, "%s@Deprecated\n", getIndentSpace(indent));
1501 }
a534180c
TAOSP
1502 fprintf(fp, "%spublic static final int %s=0x%08x;\n",
1503 getIndentSpace(indent),
1504 String8(name).string(), (int)sym.int32Val);
1505 }
1506
1507 for (i=0; i<N; i++) {
1508 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
1509 if (sym.typeCode != AaptSymbolEntry::TYPE_STRING) {
1510 continue;
1511 }
1512 if (!includePrivate && !sym.isPublic) {
1513 continue;
1514 }
1515 String16 name(sym.name);
1516 if (fixupSymbol(&name) != NO_ERROR) {
1517 return UNKNOWN_ERROR;
1518 }
1519 String16 comment(sym.comment);
f3cd0b05 1520 bool deprecated = false;
a534180c 1521 if (comment.size() > 0) {
f3cd0b05 1522 String8 cmt(comment);
a534180c
TAOSP
1523 fprintf(fp,
1524 "%s/** %s\n"
1525 "%s */\n",
f3cd0b05 1526 getIndentSpace(indent), cmt.string(),
a534180c 1527 getIndentSpace(indent));
f3cd0b05
DH
1528 if (strstr(cmt.string(), "@deprecated") != NULL) {
1529 deprecated = true;
1530 }
a534180c
TAOSP
1531 } else if (sym.isPublic && !includePrivate) {
1532 sym.sourcePos.warning("No comment for public symbol %s:%s/%s",
1533 assets->getPackage().string(), className.string(),
1534 String8(sym.name).string());
1535 }
f3cd0b05
DH
1536 if (deprecated) {
1537 fprintf(fp, "%s@Deprecated\n", getIndentSpace(indent));
1538 }
a534180c
TAOSP
1539 fprintf(fp, "%spublic static final String %s=\"%s\";\n",
1540 getIndentSpace(indent),
1541 String8(name).string(), sym.stringVal.string());
1542 }
1543
1544 sp<AaptSymbols> styleableSymbols;
1545
1546 N = symbols->getNestedSymbols().size();
1547 for (i=0; i<N; i++) {
1548 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
1549 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
1550 if (nclassName == "styleable") {
1551 styleableSymbols = nsymbols;
1552 } else {
1553 err = writeSymbolClass(fp, assets, includePrivate, nsymbols, nclassName, indent);
1554 }
1555 if (err != NO_ERROR) {
1556 return err;
1557 }
1558 }
1559
1560 if (styleableSymbols != NULL) {
1561 err = writeLayoutClasses(fp, assets, styleableSymbols, indent, includePrivate);
1562 if (err != NO_ERROR) {
1563 return err;
1564 }
1565 }
1566
1567 indent--;
1568 fprintf(fp, "%s}\n", getIndentSpace(indent));
1569 return NO_ERROR;
1570}
1571
1572status_t writeResourceSymbols(Bundle* bundle, const sp<AaptAssets>& assets,
1573 const String8& package, bool includePrivate)
1574{
1575 if (!bundle->getRClassDir()) {
1576 return NO_ERROR;
1577 }
1578
1579 const size_t N = assets->getSymbols().size();
1580 for (size_t i=0; i<N; i++) {
1581 sp<AaptSymbols> symbols = assets->getSymbols().valueAt(i);
1582 String8 className(assets->getSymbols().keyAt(i));
1583 String8 dest(bundle->getRClassDir());
1584 if (bundle->getMakePackageDirs()) {
1585 String8 pkg(package);
1586 const char* last = pkg.string();
1587 const char* s = last-1;
1588 do {
1589 s++;
1590 if (s > last && (*s == '.' || *s == 0)) {
1591 String8 part(last, s-last);
1592 dest.appendPath(part);
1593#ifdef HAVE_MS_C_RUNTIME
1594 _mkdir(dest.string());
1595#else
1596 mkdir(dest.string(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP);
1597#endif
1598 last = s+1;
1599 }
1600 } while (*s);
1601 }
1602 dest.appendPath(className);
1603 dest.append(".java");
1604 FILE* fp = fopen(dest.string(), "w+");
1605 if (fp == NULL) {
1606 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
1607 dest.string(), strerror(errno));
1608 return UNKNOWN_ERROR;
1609 }
1610 if (bundle->getVerbose()) {
1611 printf(" Writing symbols for class %s.\n", className.string());
1612 }
1613
1614 fprintf(fp,
1615 "/* AUTO-GENERATED FILE. DO NOT MODIFY.\n"
1616 " *\n"
1617 " * This class was automatically generated by the\n"
1618 " * aapt tool from the resource data it found. It\n"
1619 " * should not be modified by hand.\n"
1620 " */\n"
1621 "\n"
1622 "package %s;\n\n", package.string());
1623
1624 status_t err = writeSymbolClass(fp, assets, includePrivate, symbols, className, 0);
1625 if (err != NO_ERROR) {
1626 return err;
1627 }
1628 fclose(fp);
1629 }
1630
1631 return NO_ERROR;
1632}
6648ff78
JO
1633
1634
1635
1636class ProguardKeepSet
1637{
1638public:
1639 // { rule --> { file locations } }
1640 KeyedVector<String8, SortedVector<String8> > rules;
1641
1642 void add(const String8& rule, const String8& where);
1643};
1644
1645void ProguardKeepSet::add(const String8& rule, const String8& where)
1646{
1647 ssize_t index = rules.indexOfKey(rule);
1648 if (index < 0) {
1649 index = rules.add(rule, SortedVector<String8>());
1650 }
1651 rules.editValueAt(index).add(where);
1652}
1653
1654status_t
1655writeProguardForAndroidManifest(ProguardKeepSet* keep, const sp<AaptAssets>& assets)
1656{
1657 status_t err;
1658 ResXMLTree tree;
1659 size_t len;
1660 ResXMLTree::event_code_t code;
1661 int depth = 0;
1662 bool inApplication = false;
1663 String8 error;
1664 sp<AaptGroup> assGroup;
1665 sp<AaptFile> assFile;
1666 String8 pkg;
1667
1668 // First, look for a package file to parse. This is required to
1669 // be able to generate the resource information.
1670 assGroup = assets->getFiles().valueFor(String8("AndroidManifest.xml"));
1671 if (assGroup == NULL) {
1672 fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n");
1673 return -1;
1674 }
1675
1676 if (assGroup->getFiles().size() != 1) {
1677 fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
1678 assGroup->getFiles().valueAt(0)->getPrintableSource().string());
1679 }
1680
1681 assFile = assGroup->getFiles().valueAt(0);
1682
1683 err = parseXMLResource(assFile, &tree);
1684 if (err != NO_ERROR) {
1685 return err;
1686 }
1687
1688 tree.restart();
1689
1690 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1691 if (code == ResXMLTree::END_TAG) {
1692 if (/* name == "Application" && */ depth == 2) {
1693 inApplication = false;
1694 }
1695 depth--;
1696 continue;
1697 }
1698 if (code != ResXMLTree::START_TAG) {
1699 continue;
1700 }
1701 depth++;
1702 String8 tag(tree.getElementName(&len));
1703 // printf("Depth %d tag %s\n", depth, tag.string());
1704 if (depth == 1) {
1705 if (tag != "manifest") {
1706 fprintf(stderr, "ERROR: manifest does not start with <manifest> tag\n");
1707 return -1;
1708 }
1709 pkg = getAttribute(tree, NULL, "package", NULL);
1710 } else if (depth == 2 && tag == "application") {
1711 inApplication = true;
1712 }
1d78615e 1713 if (inApplication) {
6648ff78
JO
1714 if (tag == "application" || tag == "activity" || tag == "service" || tag == "receiver"
1715 || tag == "provider") {
1716 String8 name = getAttribute(tree, "http://schemas.android.com/apk/res/android",
1717 "name", &error);
1718 if (error != "") {
1719 fprintf(stderr, "ERROR: %s\n", error.string());
1720 return -1;
1721 }
1722 // asdf --> package.asdf
1723 // .asdf .a.b --> package.asdf package.a.b
1724 // asdf.adsf --> asdf.asdf
1725 String8 rule("-keep class ");
1726 const char* p = name.string();
1727 const char* q = strchr(p, '.');
1728 if (p == q) {
1729 rule += pkg;
1730 rule += name;
1731 } else if (q == NULL) {
1732 rule += pkg;
1733 rule += ".";
1734 rule += name;
1735 } else {
1736 rule += name;
1737 }
1738
1739 String8 location = tag;
1740 location += " ";
1741 location += assFile->getSourceFile();
1742 char lineno[20];
1743 sprintf(lineno, ":%d", tree.getLineNumber());
1744 location += lineno;
1745
1746 keep->add(rule, location);
1747 }
1748 }
1749 }
1750
1751 return NO_ERROR;
1752}
1753
1754status_t
1755writeProguardForLayout(ProguardKeepSet* keep, const sp<AaptFile>& layoutFile)
1756{
1757 status_t err;
1758 ResXMLTree tree;
1759 size_t len;
1760 ResXMLTree::event_code_t code;
1761
1762 err = parseXMLResource(layoutFile, &tree);
1763 if (err != NO_ERROR) {
1764 return err;
1765 }
1766
1767 tree.restart();
1768
1769 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1770 if (code != ResXMLTree::START_TAG) {
1771 continue;
1772 }
1773 String8 tag(tree.getElementName(&len));
1774
1775 // If there is no '.', we'll assume that it's one of the built in names.
1776 if (strchr(tag.string(), '.')) {
1777 String8 rule("-keep class ");
1778 rule += tag;
1779 rule += " { <init>(...); }";
1780
1781 String8 location("view ");
1782 location += layoutFile->getSourceFile();
1783 char lineno[20];
1784 sprintf(lineno, ":%d", tree.getLineNumber());
1785 location += lineno;
1786
1787 keep->add(rule, location);
1788 }
1789 }
1790
1791 return NO_ERROR;
1792}
1793
1794status_t
1795writeProguardForLayouts(ProguardKeepSet* keep, const sp<AaptAssets>& assets)
1796{
1797 status_t err;
1798 sp<AaptDir> layout = assets->resDir(String8("layout"));
1799
1800 if (layout != NULL) {
1801 const KeyedVector<String8,sp<AaptGroup> > groups = layout->getFiles();
1802 const size_t N = groups.size();
1803 for (size_t i=0; i<N; i++) {
1804 const sp<AaptGroup>& group = groups.valueAt(i);
1805 const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files = group->getFiles();
1806 const size_t M = files.size();
1807 for (size_t j=0; j<M; j++) {
1808 err = writeProguardForLayout(keep, files.valueAt(j));
1809 if (err < 0) {
1810 return err;
1811 }
1812 }
1813 }
1814 }
1815 return NO_ERROR;
1816}
1817
1818status_t
1819writeProguardFile(Bundle* bundle, const sp<AaptAssets>& assets)
1820{
1821 status_t err = -1;
1822
1823 if (!bundle->getProguardFile()) {
1824 return NO_ERROR;
1825 }
1826
1827 ProguardKeepSet keep;
1828
1829 err = writeProguardForAndroidManifest(&keep, assets);
1830 if (err < 0) {
1831 return err;
1832 }
1833
1834 err = writeProguardForLayouts(&keep, assets);
1835 if (err < 0) {
1836 return err;
1837 }
1838
1839 FILE* fp = fopen(bundle->getProguardFile(), "w+");
1840 if (fp == NULL) {
1841 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
1842 bundle->getProguardFile(), strerror(errno));
1843 return UNKNOWN_ERROR;
1844 }
1845
1846 const KeyedVector<String8, SortedVector<String8> >& rules = keep.rules;
1847 const size_t N = rules.size();
1848 for (size_t i=0; i<N; i++) {
1849 const SortedVector<String8>& locations = rules.valueAt(i);
1850 const size_t M = locations.size();
1851 for (size_t j=0; j<M; j++) {
1852 fprintf(fp, "# %s\n", locations.itemAt(j).string());
1853 }
1854 fprintf(fp, "%s\n\n", rules.keyAt(i).string());
1855 }
1856 fclose(fp);
1857
1858 return err;
1859}