blob: 1348be356bf8ad23064571039d72deca0b00e30a [file] [log] [blame]
Adam Lesinski282e1812014-01-23 18:17:42 -08001//
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#include "CrunchCache.h"
14#include "FileFinder.h"
15#include "CacheUpdater.h"
16
17#include "WorkQueue.h"
18
19#if HAVE_PRINTF_ZD
20# define ZD "%zd"
21# define ZD_TYPE ssize_t
22#else
23# define ZD "%ld"
24# define ZD_TYPE long
25#endif
26
27#define NOISY(x) // x
28
29// Number of threads to use for preprocessing images.
30static const size_t MAX_THREADS = 4;
31
32// ==========================================================================
33// ==========================================================================
34// ==========================================================================
35
36class PackageInfo
37{
38public:
39 PackageInfo()
40 {
41 }
42 ~PackageInfo()
43 {
44 }
45
46 status_t parsePackage(const sp<AaptGroup>& grp);
47};
48
49// ==========================================================================
50// ==========================================================================
51// ==========================================================================
52
53static String8 parseResourceName(const String8& leaf)
54{
55 const char* firstDot = strchr(leaf.string(), '.');
56 const char* str = leaf.string();
57
58 if (firstDot) {
59 return String8(str, firstDot-str);
60 } else {
61 return String8(str);
62 }
63}
64
65ResourceTypeSet::ResourceTypeSet()
66 :RefBase(),
67 KeyedVector<String8,sp<AaptGroup> >()
68{
69}
70
71FilePathStore::FilePathStore()
72 :RefBase(),
73 Vector<String8>()
74{
75}
76
77class ResourceDirIterator
78{
79public:
80 ResourceDirIterator(const sp<ResourceTypeSet>& set, const String8& resType)
81 : mResType(resType), mSet(set), mSetPos(0), mGroupPos(0)
82 {
Narayan Kamath91447d82014-01-21 15:32:36 +000083 memset(&mParams, 0, sizeof(ResTable_config));
Adam Lesinski282e1812014-01-23 18:17:42 -080084 }
85
86 inline const sp<AaptGroup>& getGroup() const { return mGroup; }
87 inline const sp<AaptFile>& getFile() const { return mFile; }
88
89 inline const String8& getBaseName() const { return mBaseName; }
90 inline const String8& getLeafName() const { return mLeafName; }
91 inline String8 getPath() const { return mPath; }
92 inline const ResTable_config& getParams() const { return mParams; }
93
94 enum {
95 EOD = 1
96 };
97
98 ssize_t next()
99 {
100 while (true) {
101 sp<AaptGroup> group;
102 sp<AaptFile> file;
103
104 // Try to get next file in this current group.
105 if (mGroup != NULL && mGroupPos < mGroup->getFiles().size()) {
106 group = mGroup;
107 file = group->getFiles().valueAt(mGroupPos++);
108
109 // Try to get the next group/file in this directory
110 } else if (mSetPos < mSet->size()) {
111 mGroup = group = mSet->valueAt(mSetPos++);
112 if (group->getFiles().size() < 1) {
113 continue;
114 }
115 file = group->getFiles().valueAt(0);
116 mGroupPos = 1;
117
118 // All done!
119 } else {
120 return EOD;
121 }
122
123 mFile = file;
124
125 String8 leaf(group->getLeaf());
126 mLeafName = String8(leaf);
127 mParams = file->getGroupEntry().toParams();
128 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",
129 group->getPath().string(), mParams.mcc, mParams.mnc,
130 mParams.language[0] ? mParams.language[0] : '-',
131 mParams.language[1] ? mParams.language[1] : '-',
132 mParams.country[0] ? mParams.country[0] : '-',
133 mParams.country[1] ? mParams.country[1] : '-',
134 mParams.orientation, mParams.uiMode,
135 mParams.density, mParams.touchscreen, mParams.keyboard,
136 mParams.inputFlags, mParams.navigation));
137 mPath = "res";
138 mPath.appendPath(file->getGroupEntry().toDirName(mResType));
139 mPath.appendPath(leaf);
140 mBaseName = parseResourceName(leaf);
141 if (mBaseName == "") {
142 fprintf(stderr, "Error: malformed resource filename %s\n",
143 file->getPrintableSource().string());
144 return UNKNOWN_ERROR;
145 }
146
147 NOISY(printf("file name=%s\n", mBaseName.string()));
148
149 return NO_ERROR;
150 }
151 }
152
153private:
154 String8 mResType;
155
156 const sp<ResourceTypeSet> mSet;
157 size_t mSetPos;
158
159 sp<AaptGroup> mGroup;
160 size_t mGroupPos;
161
162 sp<AaptFile> mFile;
163 String8 mBaseName;
164 String8 mLeafName;
165 String8 mPath;
166 ResTable_config mParams;
167};
168
169// ==========================================================================
170// ==========================================================================
171// ==========================================================================
172
173bool isValidResourceType(const String8& type)
174{
175 return type == "anim" || type == "animator" || type == "interpolator"
Chet Haase7cce7bb2013-09-04 17:41:11 -0700176 || type == "transition"
Adam Lesinski282e1812014-01-23 18:17:42 -0800177 || type == "drawable" || type == "layout"
178 || type == "values" || type == "xml" || type == "raw"
179 || type == "color" || type == "menu" || type == "mipmap";
180}
181
182static sp<AaptFile> getResourceFile(const sp<AaptAssets>& assets, bool makeIfNecessary=true)
183{
184 sp<AaptGroup> group = assets->getFiles().valueFor(String8("resources.arsc"));
185 sp<AaptFile> file;
186 if (group != NULL) {
187 file = group->getFiles().valueFor(AaptGroupEntry());
188 if (file != NULL) {
189 return file;
190 }
191 }
192
193 if (!makeIfNecessary) {
194 return NULL;
195 }
196 return assets->addFile(String8("resources.arsc"), AaptGroupEntry(), String8(),
197 NULL, String8());
198}
199
200static status_t parsePackage(Bundle* bundle, const sp<AaptAssets>& assets,
201 const sp<AaptGroup>& grp)
202{
203 if (grp->getFiles().size() != 1) {
204 fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
205 grp->getFiles().valueAt(0)->getPrintableSource().string());
206 }
207
208 sp<AaptFile> file = grp->getFiles().valueAt(0);
209
210 ResXMLTree block;
211 status_t err = parseXMLResource(file, &block);
212 if (err != NO_ERROR) {
213 return err;
214 }
215 //printXMLBlock(&block);
216
217 ResXMLTree::event_code_t code;
218 while ((code=block.next()) != ResXMLTree::START_TAG
219 && code != ResXMLTree::END_DOCUMENT
220 && code != ResXMLTree::BAD_DOCUMENT) {
221 }
222
223 size_t len;
224 if (code != ResXMLTree::START_TAG) {
225 fprintf(stderr, "%s:%d: No start tag found\n",
226 file->getPrintableSource().string(), block.getLineNumber());
227 return UNKNOWN_ERROR;
228 }
229 if (strcmp16(block.getElementName(&len), String16("manifest").string()) != 0) {
230 fprintf(stderr, "%s:%d: Invalid start tag %s, expected <manifest>\n",
231 file->getPrintableSource().string(), block.getLineNumber(),
232 String8(block.getElementName(&len)).string());
233 return UNKNOWN_ERROR;
234 }
235
236 ssize_t nameIndex = block.indexOfAttribute(NULL, "package");
237 if (nameIndex < 0) {
238 fprintf(stderr, "%s:%d: <manifest> does not have package attribute.\n",
239 file->getPrintableSource().string(), block.getLineNumber());
240 return UNKNOWN_ERROR;
241 }
242
243 assets->setPackage(String8(block.getAttributeStringValue(nameIndex, &len)));
244
245 String16 uses_sdk16("uses-sdk");
246 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
247 && code != ResXMLTree::BAD_DOCUMENT) {
248 if (code == ResXMLTree::START_TAG) {
249 if (strcmp16(block.getElementName(&len), uses_sdk16.string()) == 0) {
250 ssize_t minSdkIndex = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE,
251 "minSdkVersion");
252 if (minSdkIndex >= 0) {
253 const uint16_t* minSdk16 = block.getAttributeStringValue(minSdkIndex, &len);
254 const char* minSdk8 = strdup(String8(minSdk16).string());
255 bundle->setManifestMinSdkVersion(minSdk8);
256 }
257 }
258 }
259 }
260
261 return NO_ERROR;
262}
263
264// ==========================================================================
265// ==========================================================================
266// ==========================================================================
267
268static status_t makeFileResources(Bundle* bundle, const sp<AaptAssets>& assets,
269 ResourceTable* table,
270 const sp<ResourceTypeSet>& set,
271 const char* resType)
272{
273 String8 type8(resType);
274 String16 type16(resType);
275
276 bool hasErrors = false;
277
278 ResourceDirIterator it(set, String8(resType));
279 ssize_t res;
280 while ((res=it.next()) == NO_ERROR) {
281 if (bundle->getVerbose()) {
282 printf(" (new resource id %s from %s)\n",
283 it.getBaseName().string(), it.getFile()->getPrintableSource().string());
284 }
285 String16 baseName(it.getBaseName());
286 const char16_t* str = baseName.string();
287 const char16_t* const end = str + baseName.size();
288 while (str < end) {
289 if (!((*str >= 'a' && *str <= 'z')
290 || (*str >= '0' && *str <= '9')
291 || *str == '_' || *str == '.')) {
292 fprintf(stderr, "%s: Invalid file name: must contain only [a-z0-9_.]\n",
293 it.getPath().string());
294 hasErrors = true;
295 }
296 str++;
297 }
298 String8 resPath = it.getPath();
299 resPath.convertToResPath();
300 table->addEntry(SourcePos(it.getPath(), 0), String16(assets->getPackage()),
301 type16,
302 baseName,
303 String16(resPath),
304 NULL,
305 &it.getParams());
306 assets->addResource(it.getLeafName(), resPath, it.getFile(), type8);
307 }
308
309 return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
310}
311
312class PreProcessImageWorkUnit : public WorkQueue::WorkUnit {
313public:
314 PreProcessImageWorkUnit(const Bundle* bundle, const sp<AaptAssets>& assets,
315 const sp<AaptFile>& file, volatile bool* hasErrors) :
316 mBundle(bundle), mAssets(assets), mFile(file), mHasErrors(hasErrors) {
317 }
318
319 virtual bool run() {
320 status_t status = preProcessImage(mBundle, mAssets, mFile, NULL);
321 if (status) {
322 *mHasErrors = true;
323 }
324 return true; // continue even if there are errors
325 }
326
327private:
328 const Bundle* mBundle;
329 sp<AaptAssets> mAssets;
330 sp<AaptFile> mFile;
331 volatile bool* mHasErrors;
332};
333
334static status_t preProcessImages(const Bundle* bundle, const sp<AaptAssets>& assets,
335 const sp<ResourceTypeSet>& set, const char* type)
336{
337 volatile bool hasErrors = false;
338 ssize_t res = NO_ERROR;
339 if (bundle->getUseCrunchCache() == false) {
340 WorkQueue wq(MAX_THREADS, false);
341 ResourceDirIterator it(set, String8(type));
342 while ((res=it.next()) == NO_ERROR) {
343 PreProcessImageWorkUnit* w = new PreProcessImageWorkUnit(
344 bundle, assets, it.getFile(), &hasErrors);
345 status_t status = wq.schedule(w);
346 if (status) {
347 fprintf(stderr, "preProcessImages failed: schedule() returned %d\n", status);
348 hasErrors = true;
349 delete w;
350 break;
351 }
352 }
353 status_t status = wq.finish();
354 if (status) {
355 fprintf(stderr, "preProcessImages failed: finish() returned %d\n", status);
356 hasErrors = true;
357 }
358 }
359 return (hasErrors || (res < NO_ERROR)) ? UNKNOWN_ERROR : NO_ERROR;
360}
361
362status_t postProcessImages(const sp<AaptAssets>& assets,
363 ResourceTable* table,
364 const sp<ResourceTypeSet>& set)
365{
366 ResourceDirIterator it(set, String8("drawable"));
367 bool hasErrors = false;
368 ssize_t res;
369 while ((res=it.next()) == NO_ERROR) {
370 res = postProcessImage(assets, table, it.getFile());
371 if (res < NO_ERROR) {
372 hasErrors = true;
373 }
374 }
375
376 return (hasErrors || (res < NO_ERROR)) ? UNKNOWN_ERROR : NO_ERROR;
377}
378
379static void collect_files(const sp<AaptDir>& dir,
380 KeyedVector<String8, sp<ResourceTypeSet> >* resources)
381{
382 const DefaultKeyedVector<String8, sp<AaptGroup> >& groups = dir->getFiles();
383 int N = groups.size();
384 for (int i=0; i<N; i++) {
385 String8 leafName = groups.keyAt(i);
386 const sp<AaptGroup>& group = groups.valueAt(i);
387
388 const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files
389 = group->getFiles();
390
391 if (files.size() == 0) {
392 continue;
393 }
394
395 String8 resType = files.valueAt(0)->getResourceType();
396
397 ssize_t index = resources->indexOfKey(resType);
398
399 if (index < 0) {
400 sp<ResourceTypeSet> set = new ResourceTypeSet();
401 NOISY(printf("Creating new resource type set for leaf %s with group %s (%p)\n",
402 leafName.string(), group->getPath().string(), group.get()));
403 set->add(leafName, group);
404 resources->add(resType, set);
405 } else {
406 sp<ResourceTypeSet> set = resources->valueAt(index);
407 index = set->indexOfKey(leafName);
408 if (index < 0) {
409 NOISY(printf("Adding to resource type set for leaf %s group %s (%p)\n",
410 leafName.string(), group->getPath().string(), group.get()));
411 set->add(leafName, group);
412 } else {
413 sp<AaptGroup> existingGroup = set->valueAt(index);
414 NOISY(printf("Extending to resource type set for leaf %s group %s (%p)\n",
415 leafName.string(), group->getPath().string(), group.get()));
416 for (size_t j=0; j<files.size(); j++) {
417 NOISY(printf("Adding file %s in group %s resType %s\n",
418 files.valueAt(j)->getSourceFile().string(),
419 files.keyAt(j).toDirName(String8()).string(),
420 resType.string()));
421 status_t err = existingGroup->addFile(files.valueAt(j));
422 }
423 }
424 }
425 }
426}
427
428static void collect_files(const sp<AaptAssets>& ass,
429 KeyedVector<String8, sp<ResourceTypeSet> >* resources)
430{
431 const Vector<sp<AaptDir> >& dirs = ass->resDirs();
432 int N = dirs.size();
433
434 for (int i=0; i<N; i++) {
435 sp<AaptDir> d = dirs.itemAt(i);
436 NOISY(printf("Collecting dir #%d %p: %s, leaf %s\n", i, d.get(), d->getPath().string(),
437 d->getLeaf().string()));
438 collect_files(d, resources);
439
440 // don't try to include the res dir
441 NOISY(printf("Removing dir leaf %s\n", d->getLeaf().string()));
442 ass->removeDir(d->getLeaf());
443 }
444}
445
446enum {
447 ATTR_OKAY = -1,
448 ATTR_NOT_FOUND = -2,
449 ATTR_LEADING_SPACES = -3,
450 ATTR_TRAILING_SPACES = -4
451};
452static int validateAttr(const String8& path, const ResTable& table,
453 const ResXMLParser& parser,
454 const char* ns, const char* attr, const char* validChars, bool required)
455{
456 size_t len;
457
458 ssize_t index = parser.indexOfAttribute(ns, attr);
459 const uint16_t* str;
460 Res_value value;
461 if (index >= 0 && parser.getAttributeValue(index, &value) >= 0) {
462 const ResStringPool* pool = &parser.getStrings();
463 if (value.dataType == Res_value::TYPE_REFERENCE) {
464 uint32_t specFlags = 0;
465 int strIdx;
466 if ((strIdx=table.resolveReference(&value, 0x10000000, NULL, &specFlags)) < 0) {
467 fprintf(stderr, "%s:%d: Tag <%s> attribute %s references unknown resid 0x%08x.\n",
468 path.string(), parser.getLineNumber(),
469 String8(parser.getElementName(&len)).string(), attr,
470 value.data);
471 return ATTR_NOT_FOUND;
472 }
473
474 pool = table.getTableStringBlock(strIdx);
475 #if 0
476 if (pool != NULL) {
477 str = pool->stringAt(value.data, &len);
478 }
479 printf("***** RES ATTR: %s specFlags=0x%x strIdx=%d: %s\n", attr,
480 specFlags, strIdx, str != NULL ? String8(str).string() : "???");
481 #endif
482 if ((specFlags&~ResTable_typeSpec::SPEC_PUBLIC) != 0 && false) {
483 fprintf(stderr, "%s:%d: Tag <%s> attribute %s varies by configurations 0x%x.\n",
484 path.string(), parser.getLineNumber(),
485 String8(parser.getElementName(&len)).string(), attr,
486 specFlags);
487 return ATTR_NOT_FOUND;
488 }
489 }
490 if (value.dataType == Res_value::TYPE_STRING) {
491 if (pool == NULL) {
492 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has no string block.\n",
493 path.string(), parser.getLineNumber(),
494 String8(parser.getElementName(&len)).string(), attr);
495 return ATTR_NOT_FOUND;
496 }
497 if ((str=pool->stringAt(value.data, &len)) == NULL) {
498 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has corrupt string value.\n",
499 path.string(), parser.getLineNumber(),
500 String8(parser.getElementName(&len)).string(), attr);
501 return ATTR_NOT_FOUND;
502 }
503 } else {
504 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has invalid type %d.\n",
505 path.string(), parser.getLineNumber(),
506 String8(parser.getElementName(&len)).string(), attr,
507 value.dataType);
508 return ATTR_NOT_FOUND;
509 }
510 if (validChars) {
511 for (size_t i=0; i<len; i++) {
512 uint16_t c = str[i];
513 const char* p = validChars;
514 bool okay = false;
515 while (*p) {
516 if (c == *p) {
517 okay = true;
518 break;
519 }
520 p++;
521 }
522 if (!okay) {
523 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has invalid character '%c'.\n",
524 path.string(), parser.getLineNumber(),
525 String8(parser.getElementName(&len)).string(), attr, (char)str[i]);
526 return (int)i;
527 }
528 }
529 }
530 if (*str == ' ') {
531 fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not start with a space.\n",
532 path.string(), parser.getLineNumber(),
533 String8(parser.getElementName(&len)).string(), attr);
534 return ATTR_LEADING_SPACES;
535 }
536 if (str[len-1] == ' ') {
537 fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not end with a space.\n",
538 path.string(), parser.getLineNumber(),
539 String8(parser.getElementName(&len)).string(), attr);
540 return ATTR_TRAILING_SPACES;
541 }
542 return ATTR_OKAY;
543 }
544 if (required) {
545 fprintf(stderr, "%s:%d: Tag <%s> missing required attribute %s.\n",
546 path.string(), parser.getLineNumber(),
547 String8(parser.getElementName(&len)).string(), attr);
548 return ATTR_NOT_FOUND;
549 }
550 return ATTR_OKAY;
551}
552
553static void checkForIds(const String8& path, ResXMLParser& parser)
554{
555 ResXMLTree::event_code_t code;
556 while ((code=parser.next()) != ResXMLTree::END_DOCUMENT
557 && code > ResXMLTree::BAD_DOCUMENT) {
558 if (code == ResXMLTree::START_TAG) {
559 ssize_t index = parser.indexOfAttribute(NULL, "id");
560 if (index >= 0) {
561 fprintf(stderr, "%s:%d: warning: found plain 'id' attribute; did you mean the new 'android:id' name?\n",
562 path.string(), parser.getLineNumber());
563 }
564 }
565 }
566}
567
568static bool applyFileOverlay(Bundle *bundle,
569 const sp<AaptAssets>& assets,
570 sp<ResourceTypeSet> *baseSet,
571 const char *resType)
572{
573 if (bundle->getVerbose()) {
574 printf("applyFileOverlay for %s\n", resType);
575 }
576
577 // Replace any base level files in this category with any found from the overlay
578 // Also add any found only in the overlay.
579 sp<AaptAssets> overlay = assets->getOverlay();
580 String8 resTypeString(resType);
581
582 // work through the linked list of overlays
583 while (overlay.get()) {
584 KeyedVector<String8, sp<ResourceTypeSet> >* overlayRes = overlay->getResources();
585
586 // get the overlay resources of the requested type
587 ssize_t index = overlayRes->indexOfKey(resTypeString);
588 if (index >= 0) {
589 sp<ResourceTypeSet> overlaySet = overlayRes->valueAt(index);
590
591 // for each of the resources, check for a match in the previously built
592 // non-overlay "baseset".
593 size_t overlayCount = overlaySet->size();
594 for (size_t overlayIndex=0; overlayIndex<overlayCount; overlayIndex++) {
595 if (bundle->getVerbose()) {
596 printf("trying overlaySet Key=%s\n",overlaySet->keyAt(overlayIndex).string());
597 }
598 size_t baseIndex = UNKNOWN_ERROR;
599 if (baseSet->get() != NULL) {
600 baseIndex = (*baseSet)->indexOfKey(overlaySet->keyAt(overlayIndex));
601 }
602 if (baseIndex < UNKNOWN_ERROR) {
603 // look for same flavor. For a given file (strings.xml, for example)
604 // there may be a locale specific or other flavors - we want to match
605 // the same flavor.
606 sp<AaptGroup> overlayGroup = overlaySet->valueAt(overlayIndex);
607 sp<AaptGroup> baseGroup = (*baseSet)->valueAt(baseIndex);
608
609 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > overlayFiles =
610 overlayGroup->getFiles();
611 if (bundle->getVerbose()) {
612 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > baseFiles =
613 baseGroup->getFiles();
614 for (size_t i=0; i < baseFiles.size(); i++) {
615 printf("baseFile " ZD " has flavor %s\n", (ZD_TYPE) i,
616 baseFiles.keyAt(i).toString().string());
617 }
618 for (size_t i=0; i < overlayFiles.size(); i++) {
619 printf("overlayFile " ZD " has flavor %s\n", (ZD_TYPE) i,
620 overlayFiles.keyAt(i).toString().string());
621 }
622 }
623
624 size_t overlayGroupSize = overlayFiles.size();
625 for (size_t overlayGroupIndex = 0;
626 overlayGroupIndex<overlayGroupSize;
627 overlayGroupIndex++) {
628 size_t baseFileIndex =
629 baseGroup->getFiles().indexOfKey(overlayFiles.
630 keyAt(overlayGroupIndex));
631 if (baseFileIndex < UNKNOWN_ERROR) {
632 if (bundle->getVerbose()) {
633 printf("found a match (" ZD ") for overlay file %s, for flavor %s\n",
634 (ZD_TYPE) baseFileIndex,
635 overlayGroup->getLeaf().string(),
636 overlayFiles.keyAt(overlayGroupIndex).toString().string());
637 }
638 baseGroup->removeFile(baseFileIndex);
639 } else {
640 // didn't find a match fall through and add it..
641 if (true || bundle->getVerbose()) {
642 printf("nothing matches overlay file %s, for flavor %s\n",
643 overlayGroup->getLeaf().string(),
644 overlayFiles.keyAt(overlayGroupIndex).toString().string());
645 }
646 }
647 baseGroup->addFile(overlayFiles.valueAt(overlayGroupIndex));
648 assets->addGroupEntry(overlayFiles.keyAt(overlayGroupIndex));
649 }
650 } else {
651 if (baseSet->get() == NULL) {
652 *baseSet = new ResourceTypeSet();
653 assets->getResources()->add(String8(resType), *baseSet);
654 }
655 // this group doesn't exist (a file that's only in the overlay)
656 (*baseSet)->add(overlaySet->keyAt(overlayIndex),
657 overlaySet->valueAt(overlayIndex));
658 // make sure all flavors are defined in the resources.
659 sp<AaptGroup> overlayGroup = overlaySet->valueAt(overlayIndex);
660 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > overlayFiles =
661 overlayGroup->getFiles();
662 size_t overlayGroupSize = overlayFiles.size();
663 for (size_t overlayGroupIndex = 0;
664 overlayGroupIndex<overlayGroupSize;
665 overlayGroupIndex++) {
666 assets->addGroupEntry(overlayFiles.keyAt(overlayGroupIndex));
667 }
668 }
669 }
670 // this overlay didn't have resources for this type
671 }
672 // try next overlay
673 overlay = overlay->getOverlay();
674 }
675 return true;
676}
677
678/*
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800679 * Inserts an attribute in a given node.
Adam Lesinski282e1812014-01-23 18:17:42 -0800680 * If errorOnFailedInsert is true, and the attribute already exists, returns false.
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800681 * If replaceExisting is true, the attribute will be updated if it already exists.
682 * Returns true otherwise, even if the attribute already exists, and does not modify
683 * the existing attribute's value.
Adam Lesinski282e1812014-01-23 18:17:42 -0800684 */
685bool addTagAttribute(const sp<XMLNode>& node, const char* ns8,
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800686 const char* attr8, const char* value, bool errorOnFailedInsert,
687 bool replaceExisting)
Adam Lesinski282e1812014-01-23 18:17:42 -0800688{
689 if (value == NULL) {
690 return true;
691 }
692
693 const String16 ns(ns8);
694 const String16 attr(attr8);
695
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800696 XMLNode::attribute_entry* existingEntry = node->editAttribute(ns, attr);
697 if (existingEntry != NULL) {
698 if (replaceExisting) {
699 NOISY(printf("Info: AndroidManifest.xml already defines %s (in %s);"
700 " overwriting existing value from manifest.\n",
701 String8(attr).string(), String8(ns).string()));
702 existingEntry->string = String16(value);
703 return true;
704 }
705
Adam Lesinski282e1812014-01-23 18:17:42 -0800706 if (errorOnFailedInsert) {
707 fprintf(stderr, "Error: AndroidManifest.xml already defines %s (in %s);"
708 " cannot insert new value %s.\n",
709 String8(attr).string(), String8(ns).string(), value);
710 return false;
711 }
712
713 fprintf(stderr, "Warning: AndroidManifest.xml already defines %s (in %s);"
714 " using existing value in manifest.\n",
715 String8(attr).string(), String8(ns).string());
716
717 // don't stop the build.
718 return true;
719 }
720
721 node->addAttribute(ns, attr, String16(value));
722 return true;
723}
724
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800725/*
726 * Inserts an attribute in a given node, only if the attribute does not
727 * exist.
728 * If errorOnFailedInsert is true, and the attribute already exists, returns false.
729 * Returns true otherwise, even if the attribute already exists.
730 */
731bool addTagAttribute(const sp<XMLNode>& node, const char* ns8,
732 const char* attr8, const char* value, bool errorOnFailedInsert)
733{
734 return addTagAttribute(node, ns8, attr8, value, errorOnFailedInsert, false);
735}
736
Adam Lesinski282e1812014-01-23 18:17:42 -0800737static void fullyQualifyClassName(const String8& package, sp<XMLNode> node,
738 const String16& attrName) {
739 XMLNode::attribute_entry* attr = node->editAttribute(
740 String16("http://schemas.android.com/apk/res/android"), attrName);
741 if (attr != NULL) {
742 String8 name(attr->string);
743
744 // asdf --> package.asdf
745 // .asdf .a.b --> package.asdf package.a.b
746 // asdf.adsf --> asdf.asdf
747 String8 className;
748 const char* p = name.string();
749 const char* q = strchr(p, '.');
750 if (p == q) {
751 className += package;
752 className += name;
753 } else if (q == NULL) {
754 className += package;
755 className += ".";
756 className += name;
757 } else {
758 className += name;
759 }
760 NOISY(printf("Qualifying class '%s' to '%s'", name.string(), className.string()));
761 attr->string.setTo(String16(className));
762 }
763}
764
765status_t massageManifest(Bundle* bundle, sp<XMLNode> root)
766{
767 root = root->searchElement(String16(), String16("manifest"));
768 if (root == NULL) {
769 fprintf(stderr, "No <manifest> tag.\n");
770 return UNKNOWN_ERROR;
771 }
772
773 bool errorOnFailedInsert = bundle->getErrorOnFailedInsert();
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800774 bool replaceVersion = bundle->getReplaceVersion();
Adam Lesinski282e1812014-01-23 18:17:42 -0800775
776 if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionCode",
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800777 bundle->getVersionCode(), errorOnFailedInsert, replaceVersion)) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800778 return UNKNOWN_ERROR;
779 }
780 if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionName",
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800781 bundle->getVersionName(), errorOnFailedInsert, replaceVersion)) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800782 return UNKNOWN_ERROR;
783 }
784
785 if (bundle->getMinSdkVersion() != NULL
786 || bundle->getTargetSdkVersion() != NULL
787 || bundle->getMaxSdkVersion() != NULL) {
788 sp<XMLNode> vers = root->getChildElement(String16(), String16("uses-sdk"));
789 if (vers == NULL) {
790 vers = XMLNode::newElement(root->getFilename(), String16(), String16("uses-sdk"));
791 root->insertChildAt(vers, 0);
792 }
793
794 if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "minSdkVersion",
795 bundle->getMinSdkVersion(), errorOnFailedInsert)) {
796 return UNKNOWN_ERROR;
797 }
798 if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "targetSdkVersion",
799 bundle->getTargetSdkVersion(), errorOnFailedInsert)) {
800 return UNKNOWN_ERROR;
801 }
802 if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "maxSdkVersion",
803 bundle->getMaxSdkVersion(), errorOnFailedInsert)) {
804 return UNKNOWN_ERROR;
805 }
806 }
807
808 if (bundle->getDebugMode()) {
809 sp<XMLNode> application = root->getChildElement(String16(), String16("application"));
810 if (application != NULL) {
811 if (!addTagAttribute(application, RESOURCES_ANDROID_NAMESPACE, "debuggable", "true",
812 errorOnFailedInsert)) {
813 return UNKNOWN_ERROR;
814 }
815 }
816 }
817
818 // Deal with manifest package name overrides
819 const char* manifestPackageNameOverride = bundle->getManifestPackageNameOverride();
820 if (manifestPackageNameOverride != NULL) {
821 // Update the actual package name
822 XMLNode::attribute_entry* attr = root->editAttribute(String16(), String16("package"));
823 if (attr == NULL) {
824 fprintf(stderr, "package name is required with --rename-manifest-package.\n");
825 return UNKNOWN_ERROR;
826 }
827 String8 origPackage(attr->string);
828 attr->string.setTo(String16(manifestPackageNameOverride));
829 NOISY(printf("Overriding package '%s' to be '%s'\n", origPackage.string(), manifestPackageNameOverride));
830
831 // Make class names fully qualified
832 sp<XMLNode> application = root->getChildElement(String16(), String16("application"));
833 if (application != NULL) {
834 fullyQualifyClassName(origPackage, application, String16("name"));
835 fullyQualifyClassName(origPackage, application, String16("backupAgent"));
836
837 Vector<sp<XMLNode> >& children = const_cast<Vector<sp<XMLNode> >&>(application->getChildren());
838 for (size_t i = 0; i < children.size(); i++) {
839 sp<XMLNode> child = children.editItemAt(i);
840 String8 tag(child->getElementName());
841 if (tag == "activity" || tag == "service" || tag == "receiver" || tag == "provider") {
842 fullyQualifyClassName(origPackage, child, String16("name"));
843 } else if (tag == "activity-alias") {
844 fullyQualifyClassName(origPackage, child, String16("name"));
845 fullyQualifyClassName(origPackage, child, String16("targetActivity"));
846 }
847 }
848 }
849 }
850
851 // Deal with manifest package name overrides
852 const char* instrumentationPackageNameOverride = bundle->getInstrumentationPackageNameOverride();
853 if (instrumentationPackageNameOverride != NULL) {
854 // Fix up instrumentation targets.
855 Vector<sp<XMLNode> >& children = const_cast<Vector<sp<XMLNode> >&>(root->getChildren());
856 for (size_t i = 0; i < children.size(); i++) {
857 sp<XMLNode> child = children.editItemAt(i);
858 String8 tag(child->getElementName());
859 if (tag == "instrumentation") {
860 XMLNode::attribute_entry* attr = child->editAttribute(
861 String16("http://schemas.android.com/apk/res/android"), String16("targetPackage"));
862 if (attr != NULL) {
863 attr->string.setTo(String16(instrumentationPackageNameOverride));
864 }
865 }
866 }
867 }
868
869 return NO_ERROR;
870}
871
872#define ASSIGN_IT(n) \
873 do { \
874 ssize_t index = resources->indexOfKey(String8(#n)); \
875 if (index >= 0) { \
876 n ## s = resources->valueAt(index); \
877 } \
878 } while (0)
879
880status_t updatePreProcessedCache(Bundle* bundle)
881{
882 #if BENCHMARK
883 fprintf(stdout, "BENCHMARK: Starting PNG PreProcessing \n");
884 long startPNGTime = clock();
885 #endif /* BENCHMARK */
886
887 String8 source(bundle->getResourceSourceDirs()[0]);
888 String8 dest(bundle->getCrunchedOutputDir());
889
890 FileFinder* ff = new SystemFileFinder();
891 CrunchCache cc(source,dest,ff);
892
893 CacheUpdater* cu = new SystemCacheUpdater(bundle);
894 size_t numFiles = cc.crunch(cu);
895
896 if (bundle->getVerbose())
897 fprintf(stdout, "Crunched %d PNG files to update cache\n", (int)numFiles);
898
899 delete ff;
900 delete cu;
901
902 #if BENCHMARK
903 fprintf(stdout, "BENCHMARK: End PNG PreProcessing. Time Elapsed: %f ms \n"
904 ,(clock() - startPNGTime)/1000.0);
905 #endif /* BENCHMARK */
906 return 0;
907}
908
909status_t buildResources(Bundle* bundle, const sp<AaptAssets>& assets)
910{
911 // First, look for a package file to parse. This is required to
912 // be able to generate the resource information.
913 sp<AaptGroup> androidManifestFile =
914 assets->getFiles().valueFor(String8("AndroidManifest.xml"));
915 if (androidManifestFile == NULL) {
916 fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n");
917 return UNKNOWN_ERROR;
918 }
919
920 status_t err = parsePackage(bundle, assets, androidManifestFile);
921 if (err != NO_ERROR) {
922 return err;
923 }
924
925 NOISY(printf("Creating resources for package %s\n",
926 assets->getPackage().string()));
927
928 ResourceTable table(bundle, String16(assets->getPackage()));
929 err = table.addIncludedResources(bundle, assets);
930 if (err != NO_ERROR) {
931 return err;
932 }
933
934 NOISY(printf("Found %d included resource packages\n", (int)table.size()));
935
936 // Standard flags for compiled XML and optional UTF-8 encoding
937 int xmlFlags = XML_COMPILE_STANDARD_RESOURCE;
938
939 /* Only enable UTF-8 if the caller of aapt didn't specifically
940 * request UTF-16 encoding and the parameters of this package
941 * allow UTF-8 to be used.
942 */
943 if (!bundle->getUTF16StringsOption()) {
944 xmlFlags |= XML_COMPILE_UTF8;
945 }
946
947 // --------------------------------------------------------------
948 // First, gather all resource information.
949 // --------------------------------------------------------------
950
951 // resType -> leafName -> group
952 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
953 new KeyedVector<String8, sp<ResourceTypeSet> >;
954 collect_files(assets, resources);
955
956 sp<ResourceTypeSet> drawables;
957 sp<ResourceTypeSet> layouts;
958 sp<ResourceTypeSet> anims;
959 sp<ResourceTypeSet> animators;
960 sp<ResourceTypeSet> interpolators;
961 sp<ResourceTypeSet> transitions;
Adam Lesinski282e1812014-01-23 18:17:42 -0800962 sp<ResourceTypeSet> xmls;
963 sp<ResourceTypeSet> raws;
964 sp<ResourceTypeSet> colors;
965 sp<ResourceTypeSet> menus;
966 sp<ResourceTypeSet> mipmaps;
967
968 ASSIGN_IT(drawable);
969 ASSIGN_IT(layout);
970 ASSIGN_IT(anim);
971 ASSIGN_IT(animator);
972 ASSIGN_IT(interpolator);
973 ASSIGN_IT(transition);
Adam Lesinski282e1812014-01-23 18:17:42 -0800974 ASSIGN_IT(xml);
975 ASSIGN_IT(raw);
976 ASSIGN_IT(color);
977 ASSIGN_IT(menu);
978 ASSIGN_IT(mipmap);
979
980 assets->setResources(resources);
981 // now go through any resource overlays and collect their files
982 sp<AaptAssets> current = assets->getOverlay();
983 while(current.get()) {
984 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
985 new KeyedVector<String8, sp<ResourceTypeSet> >;
986 current->setResources(resources);
987 collect_files(current, resources);
988 current = current->getOverlay();
989 }
990 // apply the overlay files to the base set
991 if (!applyFileOverlay(bundle, assets, &drawables, "drawable") ||
992 !applyFileOverlay(bundle, assets, &layouts, "layout") ||
993 !applyFileOverlay(bundle, assets, &anims, "anim") ||
994 !applyFileOverlay(bundle, assets, &animators, "animator") ||
995 !applyFileOverlay(bundle, assets, &interpolators, "interpolator") ||
996 !applyFileOverlay(bundle, assets, &transitions, "transition") ||
Adam Lesinski282e1812014-01-23 18:17:42 -0800997 !applyFileOverlay(bundle, assets, &xmls, "xml") ||
998 !applyFileOverlay(bundle, assets, &raws, "raw") ||
999 !applyFileOverlay(bundle, assets, &colors, "color") ||
1000 !applyFileOverlay(bundle, assets, &menus, "menu") ||
1001 !applyFileOverlay(bundle, assets, &mipmaps, "mipmap")) {
1002 return UNKNOWN_ERROR;
1003 }
1004
1005 bool hasErrors = false;
1006
1007 if (drawables != NULL) {
1008 if (bundle->getOutputAPKFile() != NULL) {
1009 err = preProcessImages(bundle, assets, drawables, "drawable");
1010 }
1011 if (err == NO_ERROR) {
1012 err = makeFileResources(bundle, assets, &table, drawables, "drawable");
1013 if (err != NO_ERROR) {
1014 hasErrors = true;
1015 }
1016 } else {
1017 hasErrors = true;
1018 }
1019 }
1020
1021 if (mipmaps != NULL) {
1022 if (bundle->getOutputAPKFile() != NULL) {
1023 err = preProcessImages(bundle, assets, mipmaps, "mipmap");
1024 }
1025 if (err == NO_ERROR) {
1026 err = makeFileResources(bundle, assets, &table, mipmaps, "mipmap");
1027 if (err != NO_ERROR) {
1028 hasErrors = true;
1029 }
1030 } else {
1031 hasErrors = true;
1032 }
1033 }
1034
1035 if (layouts != NULL) {
1036 err = makeFileResources(bundle, assets, &table, layouts, "layout");
1037 if (err != NO_ERROR) {
1038 hasErrors = true;
1039 }
1040 }
1041
1042 if (anims != NULL) {
1043 err = makeFileResources(bundle, assets, &table, anims, "anim");
1044 if (err != NO_ERROR) {
1045 hasErrors = true;
1046 }
1047 }
1048
1049 if (animators != NULL) {
1050 err = makeFileResources(bundle, assets, &table, animators, "animator");
1051 if (err != NO_ERROR) {
1052 hasErrors = true;
1053 }
1054 }
1055
1056 if (transitions != NULL) {
1057 err = makeFileResources(bundle, assets, &table, transitions, "transition");
1058 if (err != NO_ERROR) {
1059 hasErrors = true;
1060 }
1061 }
1062
Adam Lesinski282e1812014-01-23 18:17:42 -08001063 if (interpolators != NULL) {
1064 err = makeFileResources(bundle, assets, &table, interpolators, "interpolator");
1065 if (err != NO_ERROR) {
1066 hasErrors = true;
1067 }
1068 }
1069
1070 if (xmls != NULL) {
1071 err = makeFileResources(bundle, assets, &table, xmls, "xml");
1072 if (err != NO_ERROR) {
1073 hasErrors = true;
1074 }
1075 }
1076
1077 if (raws != NULL) {
1078 err = makeFileResources(bundle, assets, &table, raws, "raw");
1079 if (err != NO_ERROR) {
1080 hasErrors = true;
1081 }
1082 }
1083
1084 // compile resources
1085 current = assets;
1086 while(current.get()) {
1087 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
1088 current->getResources();
1089
1090 ssize_t index = resources->indexOfKey(String8("values"));
1091 if (index >= 0) {
1092 ResourceDirIterator it(resources->valueAt(index), String8("values"));
1093 ssize_t res;
1094 while ((res=it.next()) == NO_ERROR) {
1095 sp<AaptFile> file = it.getFile();
1096 res = compileResourceFile(bundle, assets, file, it.getParams(),
1097 (current!=assets), &table);
1098 if (res != NO_ERROR) {
1099 hasErrors = true;
1100 }
1101 }
1102 }
1103 current = current->getOverlay();
1104 }
1105
1106 if (colors != NULL) {
1107 err = makeFileResources(bundle, assets, &table, colors, "color");
1108 if (err != NO_ERROR) {
1109 hasErrors = true;
1110 }
1111 }
1112
1113 if (menus != NULL) {
1114 err = makeFileResources(bundle, assets, &table, menus, "menu");
1115 if (err != NO_ERROR) {
1116 hasErrors = true;
1117 }
1118 }
1119
1120 // --------------------------------------------------------------------
1121 // Assignment of resource IDs and initial generation of resource table.
1122 // --------------------------------------------------------------------
1123
1124 if (table.hasResources()) {
1125 sp<AaptFile> resFile(getResourceFile(assets));
1126 if (resFile == NULL) {
1127 fprintf(stderr, "Error: unable to generate entry for resource data\n");
1128 return UNKNOWN_ERROR;
1129 }
1130
1131 err = table.assignResourceIds();
1132 if (err < NO_ERROR) {
1133 return err;
1134 }
1135 }
1136
1137 // --------------------------------------------------------------
1138 // Finally, we can now we can compile XML files, which may reference
1139 // resources.
1140 // --------------------------------------------------------------
1141
1142 if (layouts != NULL) {
1143 ResourceDirIterator it(layouts, String8("layout"));
1144 while ((err=it.next()) == NO_ERROR) {
1145 String8 src = it.getFile()->getPrintableSource();
1146 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
1147 if (err == NO_ERROR) {
1148 ResXMLTree block;
1149 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
1150 checkForIds(src, block);
1151 } else {
1152 hasErrors = true;
1153 }
1154 }
1155
1156 if (err < NO_ERROR) {
1157 hasErrors = true;
1158 }
1159 err = NO_ERROR;
1160 }
1161
1162 if (anims != NULL) {
1163 ResourceDirIterator it(anims, String8("anim"));
1164 while ((err=it.next()) == NO_ERROR) {
1165 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
1166 if (err != NO_ERROR) {
1167 hasErrors = true;
1168 }
1169 }
1170
1171 if (err < NO_ERROR) {
1172 hasErrors = true;
1173 }
1174 err = NO_ERROR;
1175 }
1176
1177 if (animators != NULL) {
1178 ResourceDirIterator it(animators, String8("animator"));
1179 while ((err=it.next()) == NO_ERROR) {
1180 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
1181 if (err != NO_ERROR) {
1182 hasErrors = true;
1183 }
1184 }
1185
1186 if (err < NO_ERROR) {
1187 hasErrors = true;
1188 }
1189 err = NO_ERROR;
1190 }
1191
1192 if (interpolators != NULL) {
1193 ResourceDirIterator it(interpolators, String8("interpolator"));
1194 while ((err=it.next()) == NO_ERROR) {
1195 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
1196 if (err != NO_ERROR) {
1197 hasErrors = true;
1198 }
1199 }
1200
1201 if (err < NO_ERROR) {
1202 hasErrors = true;
1203 }
1204 err = NO_ERROR;
1205 }
1206
1207 if (transitions != NULL) {
1208 ResourceDirIterator it(transitions, String8("transition"));
1209 while ((err=it.next()) == NO_ERROR) {
1210 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
1211 if (err != NO_ERROR) {
1212 hasErrors = true;
1213 }
1214 }
1215
1216 if (err < NO_ERROR) {
1217 hasErrors = true;
1218 }
1219 err = NO_ERROR;
1220 }
1221
Adam Lesinski282e1812014-01-23 18:17:42 -08001222 if (xmls != NULL) {
1223 ResourceDirIterator it(xmls, String8("xml"));
1224 while ((err=it.next()) == NO_ERROR) {
1225 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
1226 if (err != NO_ERROR) {
1227 hasErrors = true;
1228 }
1229 }
1230
1231 if (err < NO_ERROR) {
1232 hasErrors = true;
1233 }
1234 err = NO_ERROR;
1235 }
1236
1237 if (drawables != NULL) {
1238 err = postProcessImages(assets, &table, drawables);
1239 if (err != NO_ERROR) {
1240 hasErrors = true;
1241 }
1242 }
1243
1244 if (colors != NULL) {
1245 ResourceDirIterator it(colors, String8("color"));
1246 while ((err=it.next()) == NO_ERROR) {
1247 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
1248 if (err != NO_ERROR) {
1249 hasErrors = true;
1250 }
1251 }
1252
1253 if (err < NO_ERROR) {
1254 hasErrors = true;
1255 }
1256 err = NO_ERROR;
1257 }
1258
1259 if (menus != NULL) {
1260 ResourceDirIterator it(menus, String8("menu"));
1261 while ((err=it.next()) == NO_ERROR) {
1262 String8 src = it.getFile()->getPrintableSource();
1263 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
Adam Lesinskif2d2c872014-04-08 12:01:38 -07001264 if (err == NO_ERROR) {
1265 ResXMLTree block;
1266 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
1267 checkForIds(src, block);
1268 } else {
Adam Lesinski282e1812014-01-23 18:17:42 -08001269 hasErrors = true;
1270 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001271 }
1272
1273 if (err < NO_ERROR) {
1274 hasErrors = true;
1275 }
1276 err = NO_ERROR;
1277 }
1278
1279 if (table.validateLocalizations()) {
1280 hasErrors = true;
1281 }
1282
1283 if (hasErrors) {
1284 return UNKNOWN_ERROR;
1285 }
1286
1287 const sp<AaptFile> manifestFile(androidManifestFile->getFiles().valueAt(0));
1288 String8 manifestPath(manifestFile->getPrintableSource());
1289
1290 // Generate final compiled manifest file.
1291 manifestFile->clearData();
1292 sp<XMLNode> manifestTree = XMLNode::parse(manifestFile);
1293 if (manifestTree == NULL) {
1294 return UNKNOWN_ERROR;
1295 }
1296 err = massageManifest(bundle, manifestTree);
1297 if (err < NO_ERROR) {
1298 return err;
1299 }
1300 err = compileXmlFile(assets, manifestTree, manifestFile, &table);
1301 if (err < NO_ERROR) {
1302 return err;
1303 }
1304
1305 //block.restart();
1306 //printXMLBlock(&block);
1307
1308 // --------------------------------------------------------------
1309 // Generate the final resource table.
1310 // Re-flatten because we may have added new resource IDs
1311 // --------------------------------------------------------------
1312
1313 ResTable finalResTable;
1314 sp<AaptFile> resFile;
1315
1316 if (table.hasResources()) {
1317 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1318 err = table.addSymbols(symbols);
1319 if (err < NO_ERROR) {
1320 return err;
1321 }
1322
1323 resFile = getResourceFile(assets);
1324 if (resFile == NULL) {
1325 fprintf(stderr, "Error: unable to generate entry for resource data\n");
1326 return UNKNOWN_ERROR;
1327 }
1328
1329 err = table.flatten(bundle, resFile);
1330 if (err < NO_ERROR) {
1331 return err;
1332 }
1333
1334 if (bundle->getPublicOutputFile()) {
1335 FILE* fp = fopen(bundle->getPublicOutputFile(), "w+");
1336 if (fp == NULL) {
1337 fprintf(stderr, "ERROR: Unable to open public definitions output file %s: %s\n",
1338 (const char*)bundle->getPublicOutputFile(), strerror(errno));
1339 return UNKNOWN_ERROR;
1340 }
1341 if (bundle->getVerbose()) {
1342 printf(" Writing public definitions to %s.\n", bundle->getPublicOutputFile());
1343 }
1344 table.writePublicDefinitions(String16(assets->getPackage()), fp);
1345 fclose(fp);
1346 }
1347
1348 // Read resources back in,
Narayan Kamath00b31442014-01-27 17:32:37 +00001349 finalResTable.add(resFile->getData(), resFile->getSize());
Adam Lesinski282e1812014-01-23 18:17:42 -08001350
1351#if 0
1352 NOISY(
1353 printf("Generated resources:\n");
1354 finalResTable.print();
1355 )
1356#endif
1357 }
1358
1359 // Perform a basic validation of the manifest file. This time we
1360 // parse it with the comments intact, so that we can use them to
1361 // generate java docs... so we are not going to write this one
1362 // back out to the final manifest data.
1363 sp<AaptFile> outManifestFile = new AaptFile(manifestFile->getSourceFile(),
1364 manifestFile->getGroupEntry(),
1365 manifestFile->getResourceType());
1366 err = compileXmlFile(assets, manifestFile,
1367 outManifestFile, &table,
1368 XML_COMPILE_ASSIGN_ATTRIBUTE_IDS
1369 | XML_COMPILE_STRIP_WHITESPACE | XML_COMPILE_STRIP_RAW_VALUES);
1370 if (err < NO_ERROR) {
1371 return err;
1372 }
1373 ResXMLTree block;
1374 block.setTo(outManifestFile->getData(), outManifestFile->getSize(), true);
1375 String16 manifest16("manifest");
1376 String16 permission16("permission");
1377 String16 permission_group16("permission-group");
1378 String16 uses_permission16("uses-permission");
1379 String16 instrumentation16("instrumentation");
1380 String16 application16("application");
1381 String16 provider16("provider");
1382 String16 service16("service");
1383 String16 receiver16("receiver");
1384 String16 activity16("activity");
1385 String16 action16("action");
1386 String16 category16("category");
1387 String16 data16("scheme");
1388 const char* packageIdentChars = "abcdefghijklmnopqrstuvwxyz"
1389 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789";
1390 const char* packageIdentCharsWithTheStupid = "abcdefghijklmnopqrstuvwxyz"
1391 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
1392 const char* classIdentChars = "abcdefghijklmnopqrstuvwxyz"
1393 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789$";
1394 const char* processIdentChars = "abcdefghijklmnopqrstuvwxyz"
1395 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:";
1396 const char* authoritiesIdentChars = "abcdefghijklmnopqrstuvwxyz"
1397 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-:;";
1398 const char* typeIdentChars = "abcdefghijklmnopqrstuvwxyz"
1399 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:-/*+";
1400 const char* schemeIdentChars = "abcdefghijklmnopqrstuvwxyz"
1401 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
1402 ResXMLTree::event_code_t code;
1403 sp<AaptSymbols> permissionSymbols;
1404 sp<AaptSymbols> permissionGroupSymbols;
1405 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1406 && code > ResXMLTree::BAD_DOCUMENT) {
1407 if (code == ResXMLTree::START_TAG) {
1408 size_t len;
1409 if (block.getElementNamespace(&len) != NULL) {
1410 continue;
1411 }
1412 if (strcmp16(block.getElementName(&len), manifest16.string()) == 0) {
1413 if (validateAttr(manifestPath, finalResTable, block, NULL, "package",
1414 packageIdentChars, true) != ATTR_OKAY) {
1415 hasErrors = true;
1416 }
1417 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1418 "sharedUserId", packageIdentChars, false) != ATTR_OKAY) {
1419 hasErrors = true;
1420 }
1421 } else if (strcmp16(block.getElementName(&len), permission16.string()) == 0
1422 || strcmp16(block.getElementName(&len), permission_group16.string()) == 0) {
1423 const bool isGroup = strcmp16(block.getElementName(&len),
1424 permission_group16.string()) == 0;
1425 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1426 "name", isGroup ? packageIdentCharsWithTheStupid
1427 : packageIdentChars, true) != ATTR_OKAY) {
1428 hasErrors = true;
1429 }
1430 SourcePos srcPos(manifestPath, block.getLineNumber());
1431 sp<AaptSymbols> syms;
1432 if (!isGroup) {
1433 syms = permissionSymbols;
1434 if (syms == NULL) {
1435 sp<AaptSymbols> symbols =
1436 assets->getSymbolsFor(String8("Manifest"));
1437 syms = permissionSymbols = symbols->addNestedSymbol(
1438 String8("permission"), srcPos);
1439 }
1440 } else {
1441 syms = permissionGroupSymbols;
1442 if (syms == NULL) {
1443 sp<AaptSymbols> symbols =
1444 assets->getSymbolsFor(String8("Manifest"));
1445 syms = permissionGroupSymbols = symbols->addNestedSymbol(
1446 String8("permission_group"), srcPos);
1447 }
1448 }
1449 size_t len;
1450 ssize_t index = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "name");
1451 const uint16_t* id = block.getAttributeStringValue(index, &len);
1452 if (id == NULL) {
1453 fprintf(stderr, "%s:%d: missing name attribute in element <%s>.\n",
1454 manifestPath.string(), block.getLineNumber(),
1455 String8(block.getElementName(&len)).string());
1456 hasErrors = true;
1457 break;
1458 }
1459 String8 idStr(id);
1460 char* p = idStr.lockBuffer(idStr.size());
1461 char* e = p + idStr.size();
1462 bool begins_with_digit = true; // init to true so an empty string fails
1463 while (e > p) {
1464 e--;
1465 if (*e >= '0' && *e <= '9') {
1466 begins_with_digit = true;
1467 continue;
1468 }
1469 if ((*e >= 'a' && *e <= 'z') ||
1470 (*e >= 'A' && *e <= 'Z') ||
1471 (*e == '_')) {
1472 begins_with_digit = false;
1473 continue;
1474 }
1475 if (isGroup && (*e == '-')) {
1476 *e = '_';
1477 begins_with_digit = false;
1478 continue;
1479 }
1480 e++;
1481 break;
1482 }
1483 idStr.unlockBuffer();
1484 // verify that we stopped because we hit a period or
1485 // the beginning of the string, and that the
1486 // identifier didn't begin with a digit.
1487 if (begins_with_digit || (e != p && *(e-1) != '.')) {
1488 fprintf(stderr,
1489 "%s:%d: Permission name <%s> is not a valid Java symbol\n",
1490 manifestPath.string(), block.getLineNumber(), idStr.string());
1491 hasErrors = true;
1492 }
1493 syms->addStringSymbol(String8(e), idStr, srcPos);
1494 const uint16_t* cmt = block.getComment(&len);
1495 if (cmt != NULL && *cmt != 0) {
1496 //printf("Comment of %s: %s\n", String8(e).string(),
1497 // String8(cmt).string());
1498 syms->appendComment(String8(e), String16(cmt), srcPos);
1499 } else {
1500 //printf("No comment for %s\n", String8(e).string());
1501 }
1502 syms->makeSymbolPublic(String8(e), srcPos);
1503 } else if (strcmp16(block.getElementName(&len), uses_permission16.string()) == 0) {
1504 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1505 "name", packageIdentChars, true) != ATTR_OKAY) {
1506 hasErrors = true;
1507 }
1508 } else if (strcmp16(block.getElementName(&len), instrumentation16.string()) == 0) {
1509 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1510 "name", classIdentChars, true) != ATTR_OKAY) {
1511 hasErrors = true;
1512 }
1513 if (validateAttr(manifestPath, finalResTable, block,
1514 RESOURCES_ANDROID_NAMESPACE, "targetPackage",
1515 packageIdentChars, true) != ATTR_OKAY) {
1516 hasErrors = true;
1517 }
1518 } else if (strcmp16(block.getElementName(&len), application16.string()) == 0) {
1519 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1520 "name", classIdentChars, false) != ATTR_OKAY) {
1521 hasErrors = true;
1522 }
1523 if (validateAttr(manifestPath, finalResTable, block,
1524 RESOURCES_ANDROID_NAMESPACE, "permission",
1525 packageIdentChars, false) != ATTR_OKAY) {
1526 hasErrors = true;
1527 }
1528 if (validateAttr(manifestPath, finalResTable, block,
1529 RESOURCES_ANDROID_NAMESPACE, "process",
1530 processIdentChars, false) != ATTR_OKAY) {
1531 hasErrors = true;
1532 }
1533 if (validateAttr(manifestPath, finalResTable, block,
1534 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
1535 processIdentChars, false) != ATTR_OKAY) {
1536 hasErrors = true;
1537 }
1538 } else if (strcmp16(block.getElementName(&len), provider16.string()) == 0) {
1539 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1540 "name", classIdentChars, true) != ATTR_OKAY) {
1541 hasErrors = true;
1542 }
1543 if (validateAttr(manifestPath, finalResTable, block,
1544 RESOURCES_ANDROID_NAMESPACE, "authorities",
1545 authoritiesIdentChars, true) != ATTR_OKAY) {
1546 hasErrors = true;
1547 }
1548 if (validateAttr(manifestPath, finalResTable, block,
1549 RESOURCES_ANDROID_NAMESPACE, "permission",
1550 packageIdentChars, false) != ATTR_OKAY) {
1551 hasErrors = true;
1552 }
1553 if (validateAttr(manifestPath, finalResTable, block,
1554 RESOURCES_ANDROID_NAMESPACE, "process",
1555 processIdentChars, false) != ATTR_OKAY) {
1556 hasErrors = true;
1557 }
1558 } else if (strcmp16(block.getElementName(&len), service16.string()) == 0
1559 || strcmp16(block.getElementName(&len), receiver16.string()) == 0
1560 || strcmp16(block.getElementName(&len), activity16.string()) == 0) {
1561 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1562 "name", classIdentChars, true) != ATTR_OKAY) {
1563 hasErrors = true;
1564 }
1565 if (validateAttr(manifestPath, finalResTable, block,
1566 RESOURCES_ANDROID_NAMESPACE, "permission",
1567 packageIdentChars, false) != ATTR_OKAY) {
1568 hasErrors = true;
1569 }
1570 if (validateAttr(manifestPath, finalResTable, block,
1571 RESOURCES_ANDROID_NAMESPACE, "process",
1572 processIdentChars, false) != ATTR_OKAY) {
1573 hasErrors = true;
1574 }
1575 if (validateAttr(manifestPath, finalResTable, block,
1576 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
1577 processIdentChars, false) != ATTR_OKAY) {
1578 hasErrors = true;
1579 }
1580 } else if (strcmp16(block.getElementName(&len), action16.string()) == 0
1581 || strcmp16(block.getElementName(&len), category16.string()) == 0) {
1582 if (validateAttr(manifestPath, finalResTable, block,
1583 RESOURCES_ANDROID_NAMESPACE, "name",
1584 packageIdentChars, true) != ATTR_OKAY) {
1585 hasErrors = true;
1586 }
1587 } else if (strcmp16(block.getElementName(&len), data16.string()) == 0) {
1588 if (validateAttr(manifestPath, finalResTable, block,
1589 RESOURCES_ANDROID_NAMESPACE, "mimeType",
1590 typeIdentChars, true) != ATTR_OKAY) {
1591 hasErrors = true;
1592 }
1593 if (validateAttr(manifestPath, finalResTable, block,
1594 RESOURCES_ANDROID_NAMESPACE, "scheme",
1595 schemeIdentChars, true) != ATTR_OKAY) {
1596 hasErrors = true;
1597 }
1598 }
1599 }
1600 }
1601
1602 if (resFile != NULL) {
1603 // These resources are now considered to be a part of the included
1604 // resources, for others to reference.
1605 err = assets->addIncludedResources(resFile);
1606 if (err < NO_ERROR) {
1607 fprintf(stderr, "ERROR: Unable to parse generated resources, aborting.\n");
1608 return err;
1609 }
1610 }
1611
1612 return err;
1613}
1614
1615static const char* getIndentSpace(int indent)
1616{
1617static const char whitespace[] =
1618" ";
1619
1620 return whitespace + sizeof(whitespace) - 1 - indent*4;
1621}
1622
1623static String8 flattenSymbol(const String8& symbol) {
1624 String8 result(symbol);
1625 ssize_t first;
1626 if ((first = symbol.find(":", 0)) >= 0
1627 || (first = symbol.find(".", 0)) >= 0) {
1628 size_t size = symbol.size();
1629 char* buf = result.lockBuffer(size);
1630 for (size_t i = first; i < size; i++) {
1631 if (buf[i] == ':' || buf[i] == '.') {
1632 buf[i] = '_';
1633 }
1634 }
1635 result.unlockBuffer(size);
1636 }
1637 return result;
1638}
1639
1640static String8 getSymbolPackage(const String8& symbol, const sp<AaptAssets>& assets, bool pub) {
1641 ssize_t colon = symbol.find(":", 0);
1642 if (colon >= 0) {
1643 return String8(symbol.string(), colon);
1644 }
1645 return pub ? assets->getPackage() : assets->getSymbolsPrivatePackage();
1646}
1647
1648static String8 getSymbolName(const String8& symbol) {
1649 ssize_t colon = symbol.find(":", 0);
1650 if (colon >= 0) {
1651 return String8(symbol.string() + colon + 1);
1652 }
1653 return symbol;
1654}
1655
1656static String16 getAttributeComment(const sp<AaptAssets>& assets,
1657 const String8& name,
1658 String16* outTypeComment = NULL)
1659{
1660 sp<AaptSymbols> asym = assets->getSymbolsFor(String8("R"));
1661 if (asym != NULL) {
1662 //printf("Got R symbols!\n");
1663 asym = asym->getNestedSymbols().valueFor(String8("attr"));
1664 if (asym != NULL) {
1665 //printf("Got attrs symbols! comment %s=%s\n",
1666 // name.string(), String8(asym->getComment(name)).string());
1667 if (outTypeComment != NULL) {
1668 *outTypeComment = asym->getTypeComment(name);
1669 }
1670 return asym->getComment(name);
1671 }
1672 }
1673 return String16();
1674}
1675
1676static status_t writeLayoutClasses(
1677 FILE* fp, const sp<AaptAssets>& assets,
1678 const sp<AaptSymbols>& symbols, int indent, bool includePrivate)
1679{
1680 const char* indentStr = getIndentSpace(indent);
1681 if (!includePrivate) {
1682 fprintf(fp, "%s/** @doconly */\n", indentStr);
1683 }
1684 fprintf(fp, "%spublic static final class styleable {\n", indentStr);
1685 indent++;
1686
1687 String16 attr16("attr");
1688 String16 package16(assets->getPackage());
1689
1690 indentStr = getIndentSpace(indent);
1691 bool hasErrors = false;
1692
1693 size_t i;
1694 size_t N = symbols->getNestedSymbols().size();
1695 for (i=0; i<N; i++) {
1696 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
1697 String8 realClassName(symbols->getNestedSymbols().keyAt(i));
1698 String8 nclassName(flattenSymbol(realClassName));
1699
1700 SortedVector<uint32_t> idents;
1701 Vector<uint32_t> origOrder;
1702 Vector<bool> publicFlags;
1703
1704 size_t a;
1705 size_t NA = nsymbols->getSymbols().size();
1706 for (a=0; a<NA; a++) {
1707 const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a));
1708 int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32
1709 ? sym.int32Val : 0;
1710 bool isPublic = true;
1711 if (code == 0) {
1712 String16 name16(sym.name);
1713 uint32_t typeSpecFlags;
1714 code = assets->getIncludedResources().identifierForName(
1715 name16.string(), name16.size(),
1716 attr16.string(), attr16.size(),
1717 package16.string(), package16.size(), &typeSpecFlags);
1718 if (code == 0) {
1719 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
1720 nclassName.string(), sym.name.string());
1721 hasErrors = true;
1722 }
1723 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
1724 }
1725 idents.add(code);
1726 origOrder.add(code);
1727 publicFlags.add(isPublic);
1728 }
1729
1730 NA = idents.size();
1731
1732 bool deprecated = false;
1733
1734 String16 comment = symbols->getComment(realClassName);
1735 fprintf(fp, "%s/** ", indentStr);
1736 if (comment.size() > 0) {
1737 String8 cmt(comment);
1738 fprintf(fp, "%s\n", cmt.string());
1739 if (strstr(cmt.string(), "@deprecated") != NULL) {
1740 deprecated = true;
1741 }
1742 } else {
1743 fprintf(fp, "Attributes that can be used with a %s.\n", nclassName.string());
1744 }
1745 bool hasTable = false;
1746 for (a=0; a<NA; a++) {
1747 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1748 if (pos >= 0) {
1749 if (!hasTable) {
1750 hasTable = true;
1751 fprintf(fp,
1752 "%s <p>Includes the following attributes:</p>\n"
1753 "%s <table>\n"
1754 "%s <colgroup align=\"left\" />\n"
1755 "%s <colgroup align=\"left\" />\n"
1756 "%s <tr><th>Attribute</th><th>Description</th></tr>\n",
1757 indentStr,
1758 indentStr,
1759 indentStr,
1760 indentStr,
1761 indentStr);
1762 }
1763 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1764 if (!publicFlags.itemAt(a) && !includePrivate) {
1765 continue;
1766 }
1767 String8 name8(sym.name);
1768 String16 comment(sym.comment);
1769 if (comment.size() <= 0) {
1770 comment = getAttributeComment(assets, name8);
1771 }
1772 if (comment.size() > 0) {
1773 const char16_t* p = comment.string();
1774 while (*p != 0 && *p != '.') {
1775 if (*p == '{') {
1776 while (*p != 0 && *p != '}') {
1777 p++;
1778 }
1779 } else {
1780 p++;
1781 }
1782 }
1783 if (*p == '.') {
1784 p++;
1785 }
1786 comment = String16(comment.string(), p-comment.string());
1787 }
1788 fprintf(fp, "%s <tr><td><code>{@link #%s_%s %s:%s}</code></td><td>%s</td></tr>\n",
1789 indentStr, nclassName.string(),
1790 flattenSymbol(name8).string(),
1791 getSymbolPackage(name8, assets, true).string(),
1792 getSymbolName(name8).string(),
1793 String8(comment).string());
1794 }
1795 }
1796 if (hasTable) {
1797 fprintf(fp, "%s </table>\n", indentStr);
1798 }
1799 for (a=0; a<NA; a++) {
1800 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1801 if (pos >= 0) {
1802 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1803 if (!publicFlags.itemAt(a) && !includePrivate) {
1804 continue;
1805 }
1806 fprintf(fp, "%s @see #%s_%s\n",
1807 indentStr, nclassName.string(),
1808 flattenSymbol(sym.name).string());
1809 }
1810 }
1811 fprintf(fp, "%s */\n", getIndentSpace(indent));
1812
1813 if (deprecated) {
1814 fprintf(fp, "%s@Deprecated\n", indentStr);
1815 }
1816
1817 fprintf(fp,
1818 "%spublic static final int[] %s = {\n"
1819 "%s",
1820 indentStr, nclassName.string(),
1821 getIndentSpace(indent+1));
1822
1823 for (a=0; a<NA; a++) {
1824 if (a != 0) {
1825 if ((a&3) == 0) {
1826 fprintf(fp, ",\n%s", getIndentSpace(indent+1));
1827 } else {
1828 fprintf(fp, ", ");
1829 }
1830 }
1831 fprintf(fp, "0x%08x", idents[a]);
1832 }
1833
1834 fprintf(fp, "\n%s};\n", indentStr);
1835
1836 for (a=0; a<NA; a++) {
1837 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1838 if (pos >= 0) {
1839 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1840 if (!publicFlags.itemAt(a) && !includePrivate) {
1841 continue;
1842 }
1843 String8 name8(sym.name);
1844 String16 comment(sym.comment);
1845 String16 typeComment;
1846 if (comment.size() <= 0) {
1847 comment = getAttributeComment(assets, name8, &typeComment);
1848 } else {
1849 getAttributeComment(assets, name8, &typeComment);
1850 }
1851
1852 uint32_t typeSpecFlags = 0;
1853 String16 name16(sym.name);
1854 assets->getIncludedResources().identifierForName(
1855 name16.string(), name16.size(),
1856 attr16.string(), attr16.size(),
1857 package16.string(), package16.size(), &typeSpecFlags);
1858 //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
1859 // String8(attr16).string(), String8(name16).string(), typeSpecFlags);
1860 const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
1861
1862 bool deprecated = false;
1863
1864 fprintf(fp, "%s/**\n", indentStr);
1865 if (comment.size() > 0) {
1866 String8 cmt(comment);
1867 fprintf(fp, "%s <p>\n%s @attr description\n", indentStr, indentStr);
1868 fprintf(fp, "%s %s\n", indentStr, cmt.string());
1869 if (strstr(cmt.string(), "@deprecated") != NULL) {
1870 deprecated = true;
1871 }
1872 } else {
1873 fprintf(fp,
1874 "%s <p>This symbol is the offset where the {@link %s.R.attr#%s}\n"
1875 "%s attribute's value can be found in the {@link #%s} array.\n",
1876 indentStr,
1877 getSymbolPackage(name8, assets, pub).string(),
1878 getSymbolName(name8).string(),
1879 indentStr, nclassName.string());
1880 }
1881 if (typeComment.size() > 0) {
1882 String8 cmt(typeComment);
1883 fprintf(fp, "\n\n%s %s\n", indentStr, cmt.string());
1884 if (strstr(cmt.string(), "@deprecated") != NULL) {
1885 deprecated = true;
1886 }
1887 }
1888 if (comment.size() > 0) {
1889 if (pub) {
1890 fprintf(fp,
1891 "%s <p>This corresponds to the global attribute\n"
1892 "%s resource symbol {@link %s.R.attr#%s}.\n",
1893 indentStr, indentStr,
1894 getSymbolPackage(name8, assets, true).string(),
1895 getSymbolName(name8).string());
1896 } else {
1897 fprintf(fp,
1898 "%s <p>This is a private symbol.\n", indentStr);
1899 }
1900 }
1901 fprintf(fp, "%s @attr name %s:%s\n", indentStr,
1902 getSymbolPackage(name8, assets, pub).string(),
1903 getSymbolName(name8).string());
1904 fprintf(fp, "%s*/\n", indentStr);
1905 if (deprecated) {
1906 fprintf(fp, "%s@Deprecated\n", indentStr);
1907 }
1908 fprintf(fp,
1909 "%spublic static final int %s_%s = %d;\n",
1910 indentStr, nclassName.string(),
1911 flattenSymbol(name8).string(), (int)pos);
1912 }
1913 }
1914 }
1915
1916 indent--;
1917 fprintf(fp, "%s};\n", getIndentSpace(indent));
1918 return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
1919}
1920
1921static status_t writeTextLayoutClasses(
1922 FILE* fp, const sp<AaptAssets>& assets,
1923 const sp<AaptSymbols>& symbols, bool includePrivate)
1924{
1925 String16 attr16("attr");
1926 String16 package16(assets->getPackage());
1927
1928 bool hasErrors = false;
1929
1930 size_t i;
1931 size_t N = symbols->getNestedSymbols().size();
1932 for (i=0; i<N; i++) {
1933 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
1934 String8 realClassName(symbols->getNestedSymbols().keyAt(i));
1935 String8 nclassName(flattenSymbol(realClassName));
1936
1937 SortedVector<uint32_t> idents;
1938 Vector<uint32_t> origOrder;
1939 Vector<bool> publicFlags;
1940
1941 size_t a;
1942 size_t NA = nsymbols->getSymbols().size();
1943 for (a=0; a<NA; a++) {
1944 const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a));
1945 int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32
1946 ? sym.int32Val : 0;
1947 bool isPublic = true;
1948 if (code == 0) {
1949 String16 name16(sym.name);
1950 uint32_t typeSpecFlags;
1951 code = assets->getIncludedResources().identifierForName(
1952 name16.string(), name16.size(),
1953 attr16.string(), attr16.size(),
1954 package16.string(), package16.size(), &typeSpecFlags);
1955 if (code == 0) {
1956 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
1957 nclassName.string(), sym.name.string());
1958 hasErrors = true;
1959 }
1960 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
1961 }
1962 idents.add(code);
1963 origOrder.add(code);
1964 publicFlags.add(isPublic);
1965 }
1966
1967 NA = idents.size();
1968
1969 fprintf(fp, "int[] styleable %s {", nclassName.string());
1970
1971 for (a=0; a<NA; a++) {
1972 if (a != 0) {
1973 fprintf(fp, ",");
1974 }
1975 fprintf(fp, " 0x%08x", idents[a]);
1976 }
1977
1978 fprintf(fp, " }\n");
1979
1980 for (a=0; a<NA; a++) {
1981 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1982 if (pos >= 0) {
1983 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1984 if (!publicFlags.itemAt(a) && !includePrivate) {
1985 continue;
1986 }
1987 String8 name8(sym.name);
1988 String16 comment(sym.comment);
1989 String16 typeComment;
1990 if (comment.size() <= 0) {
1991 comment = getAttributeComment(assets, name8, &typeComment);
1992 } else {
1993 getAttributeComment(assets, name8, &typeComment);
1994 }
1995
1996 uint32_t typeSpecFlags = 0;
1997 String16 name16(sym.name);
1998 assets->getIncludedResources().identifierForName(
1999 name16.string(), name16.size(),
2000 attr16.string(), attr16.size(),
2001 package16.string(), package16.size(), &typeSpecFlags);
2002 //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
2003 // String8(attr16).string(), String8(name16).string(), typeSpecFlags);
2004 const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
2005
2006 fprintf(fp,
2007 "int styleable %s_%s %d\n",
2008 nclassName.string(),
2009 flattenSymbol(name8).string(), (int)pos);
2010 }
2011 }
2012 }
2013
2014 return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
2015}
2016
2017static status_t writeSymbolClass(
2018 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2019 const sp<AaptSymbols>& symbols, const String8& className, int indent,
2020 bool nonConstantId)
2021{
2022 fprintf(fp, "%spublic %sfinal class %s {\n",
2023 getIndentSpace(indent),
2024 indent != 0 ? "static " : "", className.string());
2025 indent++;
2026
2027 size_t i;
2028 status_t err = NO_ERROR;
2029
2030 const char * id_format = nonConstantId ?
2031 "%spublic static int %s=0x%08x;\n" :
2032 "%spublic static final int %s=0x%08x;\n";
2033
2034 size_t N = symbols->getSymbols().size();
2035 for (i=0; i<N; i++) {
2036 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2037 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
2038 continue;
2039 }
2040 if (!assets->isJavaSymbol(sym, includePrivate)) {
2041 continue;
2042 }
2043 String8 name8(sym.name);
2044 String16 comment(sym.comment);
2045 bool haveComment = false;
2046 bool deprecated = false;
2047 if (comment.size() > 0) {
2048 haveComment = true;
2049 String8 cmt(comment);
2050 fprintf(fp,
2051 "%s/** %s\n",
2052 getIndentSpace(indent), cmt.string());
2053 if (strstr(cmt.string(), "@deprecated") != NULL) {
2054 deprecated = true;
2055 }
2056 } else if (sym.isPublic && !includePrivate) {
2057 sym.sourcePos.warning("No comment for public symbol %s:%s/%s",
2058 assets->getPackage().string(), className.string(),
2059 String8(sym.name).string());
2060 }
2061 String16 typeComment(sym.typeComment);
2062 if (typeComment.size() > 0) {
2063 String8 cmt(typeComment);
2064 if (!haveComment) {
2065 haveComment = true;
2066 fprintf(fp,
2067 "%s/** %s\n", getIndentSpace(indent), cmt.string());
2068 } else {
2069 fprintf(fp,
2070 "%s %s\n", getIndentSpace(indent), cmt.string());
2071 }
2072 if (strstr(cmt.string(), "@deprecated") != NULL) {
2073 deprecated = true;
2074 }
2075 }
2076 if (haveComment) {
2077 fprintf(fp,"%s */\n", getIndentSpace(indent));
2078 }
2079 if (deprecated) {
2080 fprintf(fp, "%s@Deprecated\n", getIndentSpace(indent));
2081 }
2082 fprintf(fp, id_format,
2083 getIndentSpace(indent),
2084 flattenSymbol(name8).string(), (int)sym.int32Val);
2085 }
2086
2087 for (i=0; i<N; i++) {
2088 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2089 if (sym.typeCode != AaptSymbolEntry::TYPE_STRING) {
2090 continue;
2091 }
2092 if (!assets->isJavaSymbol(sym, includePrivate)) {
2093 continue;
2094 }
2095 String8 name8(sym.name);
2096 String16 comment(sym.comment);
2097 bool deprecated = false;
2098 if (comment.size() > 0) {
2099 String8 cmt(comment);
2100 fprintf(fp,
2101 "%s/** %s\n"
2102 "%s */\n",
2103 getIndentSpace(indent), cmt.string(),
2104 getIndentSpace(indent));
2105 if (strstr(cmt.string(), "@deprecated") != NULL) {
2106 deprecated = true;
2107 }
2108 } else if (sym.isPublic && !includePrivate) {
2109 sym.sourcePos.warning("No comment for public symbol %s:%s/%s",
2110 assets->getPackage().string(), className.string(),
2111 String8(sym.name).string());
2112 }
2113 if (deprecated) {
2114 fprintf(fp, "%s@Deprecated\n", getIndentSpace(indent));
2115 }
2116 fprintf(fp, "%spublic static final String %s=\"%s\";\n",
2117 getIndentSpace(indent),
2118 flattenSymbol(name8).string(), sym.stringVal.string());
2119 }
2120
2121 sp<AaptSymbols> styleableSymbols;
2122
2123 N = symbols->getNestedSymbols().size();
2124 for (i=0; i<N; i++) {
2125 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2126 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2127 if (nclassName == "styleable") {
2128 styleableSymbols = nsymbols;
2129 } else {
2130 err = writeSymbolClass(fp, assets, includePrivate, nsymbols, nclassName, indent, nonConstantId);
2131 }
2132 if (err != NO_ERROR) {
2133 return err;
2134 }
2135 }
2136
2137 if (styleableSymbols != NULL) {
2138 err = writeLayoutClasses(fp, assets, styleableSymbols, indent, includePrivate);
2139 if (err != NO_ERROR) {
2140 return err;
2141 }
2142 }
2143
2144 indent--;
2145 fprintf(fp, "%s}\n", getIndentSpace(indent));
2146 return NO_ERROR;
2147}
2148
2149static status_t writeTextSymbolClass(
2150 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2151 const sp<AaptSymbols>& symbols, const String8& className)
2152{
2153 size_t i;
2154 status_t err = NO_ERROR;
2155
2156 size_t N = symbols->getSymbols().size();
2157 for (i=0; i<N; i++) {
2158 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2159 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
2160 continue;
2161 }
2162
2163 if (!assets->isJavaSymbol(sym, includePrivate)) {
2164 continue;
2165 }
2166
2167 String8 name8(sym.name);
2168 fprintf(fp, "int %s %s 0x%08x\n",
2169 className.string(),
2170 flattenSymbol(name8).string(), (int)sym.int32Val);
2171 }
2172
2173 N = symbols->getNestedSymbols().size();
2174 for (i=0; i<N; i++) {
2175 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2176 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2177 if (nclassName == "styleable") {
2178 err = writeTextLayoutClasses(fp, assets, nsymbols, includePrivate);
2179 } else {
2180 err = writeTextSymbolClass(fp, assets, includePrivate, nsymbols, nclassName);
2181 }
2182 if (err != NO_ERROR) {
2183 return err;
2184 }
2185 }
2186
2187 return NO_ERROR;
2188}
2189
2190status_t writeResourceSymbols(Bundle* bundle, const sp<AaptAssets>& assets,
2191 const String8& package, bool includePrivate)
2192{
2193 if (!bundle->getRClassDir()) {
2194 return NO_ERROR;
2195 }
2196
2197 const char* textSymbolsDest = bundle->getOutputTextSymbols();
2198
2199 String8 R("R");
2200 const size_t N = assets->getSymbols().size();
2201 for (size_t i=0; i<N; i++) {
2202 sp<AaptSymbols> symbols = assets->getSymbols().valueAt(i);
2203 String8 className(assets->getSymbols().keyAt(i));
2204 String8 dest(bundle->getRClassDir());
2205
2206 if (bundle->getMakePackageDirs()) {
2207 String8 pkg(package);
2208 const char* last = pkg.string();
2209 const char* s = last-1;
2210 do {
2211 s++;
2212 if (s > last && (*s == '.' || *s == 0)) {
2213 String8 part(last, s-last);
2214 dest.appendPath(part);
2215#ifdef HAVE_MS_C_RUNTIME
2216 _mkdir(dest.string());
2217#else
2218 mkdir(dest.string(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP);
2219#endif
2220 last = s+1;
2221 }
2222 } while (*s);
2223 }
2224 dest.appendPath(className);
2225 dest.append(".java");
2226 FILE* fp = fopen(dest.string(), "w+");
2227 if (fp == NULL) {
2228 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
2229 dest.string(), strerror(errno));
2230 return UNKNOWN_ERROR;
2231 }
2232 if (bundle->getVerbose()) {
2233 printf(" Writing symbols for class %s.\n", className.string());
2234 }
2235
2236 fprintf(fp,
2237 "/* AUTO-GENERATED FILE. DO NOT MODIFY.\n"
2238 " *\n"
2239 " * This class was automatically generated by the\n"
2240 " * aapt tool from the resource data it found. It\n"
2241 " * should not be modified by hand.\n"
2242 " */\n"
2243 "\n"
2244 "package %s;\n\n", package.string());
2245
2246 status_t err = writeSymbolClass(fp, assets, includePrivate, symbols,
2247 className, 0, bundle->getNonConstantId());
Elliott Hughesb30296b2013-10-29 15:25:52 -07002248 fclose(fp);
Adam Lesinski282e1812014-01-23 18:17:42 -08002249 if (err != NO_ERROR) {
2250 return err;
2251 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002252
2253 if (textSymbolsDest != NULL && R == className) {
2254 String8 textDest(textSymbolsDest);
2255 textDest.appendPath(className);
2256 textDest.append(".txt");
2257
2258 FILE* fp = fopen(textDest.string(), "w+");
2259 if (fp == NULL) {
2260 fprintf(stderr, "ERROR: Unable to open text symbol file %s: %s\n",
2261 textDest.string(), strerror(errno));
2262 return UNKNOWN_ERROR;
2263 }
2264 if (bundle->getVerbose()) {
2265 printf(" Writing text symbols for class %s.\n", className.string());
2266 }
2267
2268 status_t err = writeTextSymbolClass(fp, assets, includePrivate, symbols,
2269 className);
Elliott Hughesb30296b2013-10-29 15:25:52 -07002270 fclose(fp);
Adam Lesinski282e1812014-01-23 18:17:42 -08002271 if (err != NO_ERROR) {
2272 return err;
2273 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002274 }
2275
2276 // If we were asked to generate a dependency file, we'll go ahead and add this R.java
2277 // as a target in the dependency file right next to it.
2278 if (bundle->getGenDependencies() && R == className) {
2279 // Add this R.java to the dependency file
2280 String8 dependencyFile(bundle->getRClassDir());
2281 dependencyFile.appendPath("R.java.d");
2282
2283 FILE *fp = fopen(dependencyFile.string(), "a");
2284 fprintf(fp,"%s \\\n", dest.string());
2285 fclose(fp);
2286 }
2287 }
2288
2289 return NO_ERROR;
2290}
2291
2292
2293class ProguardKeepSet
2294{
2295public:
2296 // { rule --> { file locations } }
2297 KeyedVector<String8, SortedVector<String8> > rules;
2298
2299 void add(const String8& rule, const String8& where);
2300};
2301
2302void ProguardKeepSet::add(const String8& rule, const String8& where)
2303{
2304 ssize_t index = rules.indexOfKey(rule);
2305 if (index < 0) {
2306 index = rules.add(rule, SortedVector<String8>());
2307 }
2308 rules.editValueAt(index).add(where);
2309}
2310
2311void
2312addProguardKeepRule(ProguardKeepSet* keep, const String8& inClassName,
2313 const char* pkg, const String8& srcName, int line)
2314{
2315 String8 className(inClassName);
2316 if (pkg != NULL) {
2317 // asdf --> package.asdf
2318 // .asdf .a.b --> package.asdf package.a.b
2319 // asdf.adsf --> asdf.asdf
2320 const char* p = className.string();
2321 const char* q = strchr(p, '.');
2322 if (p == q) {
2323 className = pkg;
2324 className.append(inClassName);
2325 } else if (q == NULL) {
2326 className = pkg;
2327 className.append(".");
2328 className.append(inClassName);
2329 }
2330 }
2331
2332 String8 rule("-keep class ");
2333 rule += className;
2334 rule += " { <init>(...); }";
2335
2336 String8 location("view ");
2337 location += srcName;
2338 char lineno[20];
2339 sprintf(lineno, ":%d", line);
2340 location += lineno;
2341
2342 keep->add(rule, location);
2343}
2344
2345void
2346addProguardKeepMethodRule(ProguardKeepSet* keep, const String8& memberName,
2347 const char* pkg, const String8& srcName, int line)
2348{
2349 String8 rule("-keepclassmembers class * { *** ");
2350 rule += memberName;
2351 rule += "(...); }";
2352
2353 String8 location("onClick ");
2354 location += srcName;
2355 char lineno[20];
2356 sprintf(lineno, ":%d", line);
2357 location += lineno;
2358
2359 keep->add(rule, location);
2360}
2361
2362status_t
2363writeProguardForAndroidManifest(ProguardKeepSet* keep, const sp<AaptAssets>& assets)
2364{
2365 status_t err;
2366 ResXMLTree tree;
2367 size_t len;
2368 ResXMLTree::event_code_t code;
2369 int depth = 0;
2370 bool inApplication = false;
2371 String8 error;
2372 sp<AaptGroup> assGroup;
2373 sp<AaptFile> assFile;
2374 String8 pkg;
2375
2376 // First, look for a package file to parse. This is required to
2377 // be able to generate the resource information.
2378 assGroup = assets->getFiles().valueFor(String8("AndroidManifest.xml"));
2379 if (assGroup == NULL) {
2380 fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n");
2381 return -1;
2382 }
2383
2384 if (assGroup->getFiles().size() != 1) {
2385 fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
2386 assGroup->getFiles().valueAt(0)->getPrintableSource().string());
2387 }
2388
2389 assFile = assGroup->getFiles().valueAt(0);
2390
2391 err = parseXMLResource(assFile, &tree);
2392 if (err != NO_ERROR) {
2393 return err;
2394 }
2395
2396 tree.restart();
2397
2398 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
2399 if (code == ResXMLTree::END_TAG) {
2400 if (/* name == "Application" && */ depth == 2) {
2401 inApplication = false;
2402 }
2403 depth--;
2404 continue;
2405 }
2406 if (code != ResXMLTree::START_TAG) {
2407 continue;
2408 }
2409 depth++;
2410 String8 tag(tree.getElementName(&len));
2411 // printf("Depth %d tag %s\n", depth, tag.string());
2412 bool keepTag = false;
2413 if (depth == 1) {
2414 if (tag != "manifest") {
2415 fprintf(stderr, "ERROR: manifest does not start with <manifest> tag\n");
2416 return -1;
2417 }
2418 pkg = getAttribute(tree, NULL, "package", NULL);
2419 } else if (depth == 2) {
2420 if (tag == "application") {
2421 inApplication = true;
2422 keepTag = true;
2423
2424 String8 agent = getAttribute(tree, "http://schemas.android.com/apk/res/android",
2425 "backupAgent", &error);
2426 if (agent.length() > 0) {
2427 addProguardKeepRule(keep, agent, pkg.string(),
2428 assFile->getPrintableSource(), tree.getLineNumber());
2429 }
2430 } else if (tag == "instrumentation") {
2431 keepTag = true;
2432 }
2433 }
2434 if (!keepTag && inApplication && depth == 3) {
2435 if (tag == "activity" || tag == "service" || tag == "receiver" || tag == "provider") {
2436 keepTag = true;
2437 }
2438 }
2439 if (keepTag) {
2440 String8 name = getAttribute(tree, "http://schemas.android.com/apk/res/android",
2441 "name", &error);
2442 if (error != "") {
2443 fprintf(stderr, "ERROR: %s\n", error.string());
2444 return -1;
2445 }
2446 if (name.length() > 0) {
2447 addProguardKeepRule(keep, name, pkg.string(),
2448 assFile->getPrintableSource(), tree.getLineNumber());
2449 }
2450 }
2451 }
2452
2453 return NO_ERROR;
2454}
2455
2456struct NamespaceAttributePair {
2457 const char* ns;
2458 const char* attr;
2459
2460 NamespaceAttributePair(const char* n, const char* a) : ns(n), attr(a) {}
2461 NamespaceAttributePair() : ns(NULL), attr(NULL) {}
2462};
2463
2464status_t
2465writeProguardForXml(ProguardKeepSet* keep, const sp<AaptFile>& layoutFile,
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07002466 const Vector<String8>& startTags, const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs)
Adam Lesinski282e1812014-01-23 18:17:42 -08002467{
2468 status_t err;
2469 ResXMLTree tree;
2470 size_t len;
2471 ResXMLTree::event_code_t code;
2472
2473 err = parseXMLResource(layoutFile, &tree);
2474 if (err != NO_ERROR) {
2475 return err;
2476 }
2477
2478 tree.restart();
2479
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07002480 if (!startTags.isEmpty()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002481 bool haveStart = false;
2482 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
2483 if (code != ResXMLTree::START_TAG) {
2484 continue;
2485 }
2486 String8 tag(tree.getElementName(&len));
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07002487 const size_t numStartTags = startTags.size();
2488 for (size_t i = 0; i < numStartTags; i++) {
2489 if (tag == startTags[i]) {
2490 haveStart = true;
2491 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002492 }
2493 break;
2494 }
2495 if (!haveStart) {
2496 return NO_ERROR;
2497 }
2498 }
2499
2500 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
2501 if (code != ResXMLTree::START_TAG) {
2502 continue;
2503 }
2504 String8 tag(tree.getElementName(&len));
2505
2506 // If there is no '.', we'll assume that it's one of the built in names.
2507 if (strchr(tag.string(), '.')) {
2508 addProguardKeepRule(keep, tag, NULL,
2509 layoutFile->getPrintableSource(), tree.getLineNumber());
2510 } else if (tagAttrPairs != NULL) {
2511 ssize_t tagIndex = tagAttrPairs->indexOfKey(tag);
2512 if (tagIndex >= 0) {
2513 const Vector<NamespaceAttributePair>& nsAttrVector = tagAttrPairs->valueAt(tagIndex);
2514 for (size_t i = 0; i < nsAttrVector.size(); i++) {
2515 const NamespaceAttributePair& nsAttr = nsAttrVector[i];
2516
2517 ssize_t attrIndex = tree.indexOfAttribute(nsAttr.ns, nsAttr.attr);
2518 if (attrIndex < 0) {
2519 // fprintf(stderr, "%s:%d: <%s> does not have attribute %s:%s.\n",
2520 // layoutFile->getPrintableSource().string(), tree.getLineNumber(),
2521 // tag.string(), nsAttr.ns, nsAttr.attr);
2522 } else {
2523 size_t len;
2524 addProguardKeepRule(keep,
2525 String8(tree.getAttributeStringValue(attrIndex, &len)), NULL,
2526 layoutFile->getPrintableSource(), tree.getLineNumber());
2527 }
2528 }
2529 }
2530 }
2531 ssize_t attrIndex = tree.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "onClick");
2532 if (attrIndex >= 0) {
2533 size_t len;
2534 addProguardKeepMethodRule(keep,
2535 String8(tree.getAttributeStringValue(attrIndex, &len)), NULL,
2536 layoutFile->getPrintableSource(), tree.getLineNumber());
2537 }
2538 }
2539
2540 return NO_ERROR;
2541}
2542
2543static void addTagAttrPair(KeyedVector<String8, Vector<NamespaceAttributePair> >* dest,
2544 const char* tag, const char* ns, const char* attr) {
2545 String8 tagStr(tag);
2546 ssize_t index = dest->indexOfKey(tagStr);
2547
2548 if (index < 0) {
2549 Vector<NamespaceAttributePair> vector;
2550 vector.add(NamespaceAttributePair(ns, attr));
2551 dest->add(tagStr, vector);
2552 } else {
2553 dest->editValueAt(index).add(NamespaceAttributePair(ns, attr));
2554 }
2555}
2556
2557status_t
2558writeProguardForLayouts(ProguardKeepSet* keep, const sp<AaptAssets>& assets)
2559{
2560 status_t err;
2561
2562 // tag:attribute pairs that should be checked in layout files.
2563 KeyedVector<String8, Vector<NamespaceAttributePair> > kLayoutTagAttrPairs;
2564 addTagAttrPair(&kLayoutTagAttrPairs, "view", NULL, "class");
2565 addTagAttrPair(&kLayoutTagAttrPairs, "fragment", NULL, "class");
2566 addTagAttrPair(&kLayoutTagAttrPairs, "fragment", RESOURCES_ANDROID_NAMESPACE, "name");
2567
2568 // tag:attribute pairs that should be checked in xml files.
2569 KeyedVector<String8, Vector<NamespaceAttributePair> > kXmlTagAttrPairs;
2570 addTagAttrPair(&kXmlTagAttrPairs, "PreferenceScreen", RESOURCES_ANDROID_NAMESPACE, "fragment");
2571 addTagAttrPair(&kXmlTagAttrPairs, "header", RESOURCES_ANDROID_NAMESPACE, "fragment");
2572
2573 const Vector<sp<AaptDir> >& dirs = assets->resDirs();
2574 const size_t K = dirs.size();
2575 for (size_t k=0; k<K; k++) {
2576 const sp<AaptDir>& d = dirs.itemAt(k);
2577 const String8& dirName = d->getLeaf();
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07002578 Vector<String8> startTags;
Adam Lesinski282e1812014-01-23 18:17:42 -08002579 const char* startTag = NULL;
2580 const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs = NULL;
2581 if ((dirName == String8("layout")) || (strncmp(dirName.string(), "layout-", 7) == 0)) {
2582 tagAttrPairs = &kLayoutTagAttrPairs;
2583 } else if ((dirName == String8("xml")) || (strncmp(dirName.string(), "xml-", 4) == 0)) {
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07002584 startTags.add(String8("PreferenceScreen"));
2585 startTags.add(String8("preference-headers"));
Adam Lesinski282e1812014-01-23 18:17:42 -08002586 tagAttrPairs = &kXmlTagAttrPairs;
2587 } else if ((dirName == String8("menu")) || (strncmp(dirName.string(), "menu-", 5) == 0)) {
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07002588 startTags.add(String8("menu"));
Adam Lesinski282e1812014-01-23 18:17:42 -08002589 tagAttrPairs = NULL;
2590 } else {
2591 continue;
2592 }
2593
2594 const KeyedVector<String8,sp<AaptGroup> > groups = d->getFiles();
2595 const size_t N = groups.size();
2596 for (size_t i=0; i<N; i++) {
2597 const sp<AaptGroup>& group = groups.valueAt(i);
2598 const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files = group->getFiles();
2599 const size_t M = files.size();
2600 for (size_t j=0; j<M; j++) {
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07002601 err = writeProguardForXml(keep, files.valueAt(j), startTags, tagAttrPairs);
Adam Lesinski282e1812014-01-23 18:17:42 -08002602 if (err < 0) {
2603 return err;
2604 }
2605 }
2606 }
2607 }
2608 // Handle the overlays
2609 sp<AaptAssets> overlay = assets->getOverlay();
2610 if (overlay.get()) {
2611 return writeProguardForLayouts(keep, overlay);
2612 }
2613
2614 return NO_ERROR;
2615}
2616
2617status_t
2618writeProguardFile(Bundle* bundle, const sp<AaptAssets>& assets)
2619{
2620 status_t err = -1;
2621
2622 if (!bundle->getProguardFile()) {
2623 return NO_ERROR;
2624 }
2625
2626 ProguardKeepSet keep;
2627
2628 err = writeProguardForAndroidManifest(&keep, assets);
2629 if (err < 0) {
2630 return err;
2631 }
2632
2633 err = writeProguardForLayouts(&keep, assets);
2634 if (err < 0) {
2635 return err;
2636 }
2637
2638 FILE* fp = fopen(bundle->getProguardFile(), "w+");
2639 if (fp == NULL) {
2640 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
2641 bundle->getProguardFile(), strerror(errno));
2642 return UNKNOWN_ERROR;
2643 }
2644
2645 const KeyedVector<String8, SortedVector<String8> >& rules = keep.rules;
2646 const size_t N = rules.size();
2647 for (size_t i=0; i<N; i++) {
2648 const SortedVector<String8>& locations = rules.valueAt(i);
2649 const size_t M = locations.size();
2650 for (size_t j=0; j<M; j++) {
2651 fprintf(fp, "# %s\n", locations.itemAt(j).string());
2652 }
2653 fprintf(fp, "%s\n\n", rules.keyAt(i).string());
2654 }
2655 fclose(fp);
2656
2657 return err;
2658}
2659
2660// Loops through the string paths and writes them to the file pointer
2661// Each file path is written on its own line with a terminating backslash.
2662status_t writePathsToFile(const sp<FilePathStore>& files, FILE* fp)
2663{
2664 status_t deps = -1;
2665 for (size_t file_i = 0; file_i < files->size(); ++file_i) {
2666 // Add the full file path to the dependency file
2667 fprintf(fp, "%s \\\n", files->itemAt(file_i).string());
2668 deps++;
2669 }
2670 return deps;
2671}
2672
2673status_t
2674writeDependencyPreReqs(Bundle* bundle, const sp<AaptAssets>& assets, FILE* fp, bool includeRaw)
2675{
2676 status_t deps = -1;
2677 deps += writePathsToFile(assets->getFullResPaths(), fp);
2678 if (includeRaw) {
2679 deps += writePathsToFile(assets->getFullAssetPaths(), fp);
2680 }
2681 return deps;
2682}