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