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