blob: 3e8abb121c42abdcccf1c3e2e65b8e9985403e71 [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 Lesinskide7de472014-11-03 12:03:08 -08007#include "AaptUtil.h"
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07008#include "AaptXml.h"
Adam Lesinski1e4663852014-08-15 14:47:28 -07009#include "CacheUpdater.h"
Adam Lesinski282e1812014-01-23 18:17:42 -080010#include "CrunchCache.h"
11#include "FileFinder.h"
Adam Lesinski1e4663852014-08-15 14:47:28 -070012#include "Images.h"
13#include "IndentPrinter.h"
14#include "Main.h"
15#include "ResourceTable.h"
16#include "StringPool.h"
Adam Lesinskide7de472014-11-03 12:03:08 -080017#include "Symbol.h"
Adam Lesinski282e1812014-01-23 18:17:42 -080018#include "WorkQueue.h"
Adam Lesinski1e4663852014-08-15 14:47:28 -070019#include "XMLNode.h"
Adam Lesinski282e1812014-01-23 18:17:42 -080020
Adam Lesinskide7de472014-11-03 12:03:08 -080021#include <algorithm>
22
Andreas Gampe2412f842014-09-30 20:55:57 -070023// STATUST: mingw does seem to redefine UNKNOWN_ERROR from our enum value, so a cast is necessary.
Adam Lesinski685d3632014-11-05 12:30:25 -080024
Elliott Hughesb12f2412015-04-03 12:56:45 -070025#if !defined(_WIN32)
Andreas Gampe2412f842014-09-30 20:55:57 -070026# define STATUST(x) x
Adam Lesinski282e1812014-01-23 18:17:42 -080027#else
Andreas Gampe2412f842014-09-30 20:55:57 -070028# define STATUST(x) (status_t)x
Adam Lesinski282e1812014-01-23 18:17:42 -080029#endif
30
Andreas Gampe2412f842014-09-30 20:55:57 -070031// Set to true for noisy debug output.
32static const bool kIsDebug = false;
Adam Lesinski282e1812014-01-23 18:17:42 -080033
34// Number of threads to use for preprocessing images.
35static const size_t MAX_THREADS = 4;
36
37// ==========================================================================
38// ==========================================================================
39// ==========================================================================
40
41class PackageInfo
42{
43public:
44 PackageInfo()
45 {
46 }
47 ~PackageInfo()
48 {
49 }
50
51 status_t parsePackage(const sp<AaptGroup>& grp);
52};
53
54// ==========================================================================
55// ==========================================================================
56// ==========================================================================
57
Adam Lesinskie572c012014-09-19 15:10:04 -070058String8 parseResourceName(const String8& leaf)
Adam Lesinski282e1812014-01-23 18:17:42 -080059{
60 const char* firstDot = strchr(leaf.string(), '.');
61 const char* str = leaf.string();
62
63 if (firstDot) {
64 return String8(str, firstDot-str);
65 } else {
66 return String8(str);
67 }
68}
69
70ResourceTypeSet::ResourceTypeSet()
71 :RefBase(),
72 KeyedVector<String8,sp<AaptGroup> >()
73{
74}
75
76FilePathStore::FilePathStore()
77 :RefBase(),
78 Vector<String8>()
79{
80}
81
82class ResourceDirIterator
83{
84public:
85 ResourceDirIterator(const sp<ResourceTypeSet>& set, const String8& resType)
86 : mResType(resType), mSet(set), mSetPos(0), mGroupPos(0)
87 {
Narayan Kamath91447d82014-01-21 15:32:36 +000088 memset(&mParams, 0, sizeof(ResTable_config));
Adam Lesinski282e1812014-01-23 18:17:42 -080089 }
90
91 inline const sp<AaptGroup>& getGroup() const { return mGroup; }
92 inline const sp<AaptFile>& getFile() const { return mFile; }
93
94 inline const String8& getBaseName() const { return mBaseName; }
95 inline const String8& getLeafName() const { return mLeafName; }
96 inline String8 getPath() const { return mPath; }
97 inline const ResTable_config& getParams() const { return mParams; }
98
99 enum {
100 EOD = 1
101 };
102
103 ssize_t next()
104 {
105 while (true) {
106 sp<AaptGroup> group;
107 sp<AaptFile> file;
108
109 // Try to get next file in this current group.
110 if (mGroup != NULL && mGroupPos < mGroup->getFiles().size()) {
111 group = mGroup;
112 file = group->getFiles().valueAt(mGroupPos++);
113
114 // Try to get the next group/file in this directory
115 } else if (mSetPos < mSet->size()) {
116 mGroup = group = mSet->valueAt(mSetPos++);
117 if (group->getFiles().size() < 1) {
118 continue;
119 }
120 file = group->getFiles().valueAt(0);
121 mGroupPos = 1;
122
123 // All done!
124 } else {
125 return EOD;
126 }
127
128 mFile = file;
129
130 String8 leaf(group->getLeaf());
131 mLeafName = String8(leaf);
132 mParams = file->getGroupEntry().toParams();
Andreas Gampe2412f842014-09-30 20:55:57 -0700133 if (kIsDebug) {
134 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",
135 group->getPath().string(), mParams.mcc, mParams.mnc,
136 mParams.language[0] ? mParams.language[0] : '-',
137 mParams.language[1] ? mParams.language[1] : '-',
138 mParams.country[0] ? mParams.country[0] : '-',
139 mParams.country[1] ? mParams.country[1] : '-',
140 mParams.orientation, mParams.uiMode,
141 mParams.density, mParams.touchscreen, mParams.keyboard,
142 mParams.inputFlags, mParams.navigation);
143 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800144 mPath = "res";
145 mPath.appendPath(file->getGroupEntry().toDirName(mResType));
146 mPath.appendPath(leaf);
147 mBaseName = parseResourceName(leaf);
148 if (mBaseName == "") {
149 fprintf(stderr, "Error: malformed resource filename %s\n",
150 file->getPrintableSource().string());
151 return UNKNOWN_ERROR;
152 }
153
Andreas Gampe2412f842014-09-30 20:55:57 -0700154 if (kIsDebug) {
155 printf("file name=%s\n", mBaseName.string());
156 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800157
158 return NO_ERROR;
159 }
160 }
161
162private:
163 String8 mResType;
164
165 const sp<ResourceTypeSet> mSet;
166 size_t mSetPos;
167
168 sp<AaptGroup> mGroup;
169 size_t mGroupPos;
170
171 sp<AaptFile> mFile;
172 String8 mBaseName;
173 String8 mLeafName;
174 String8 mPath;
175 ResTable_config mParams;
176};
177
Jeff Browneb490d62014-06-06 19:43:42 -0700178class AnnotationProcessor {
179public:
180 AnnotationProcessor() : mDeprecated(false), mSystemApi(false) { }
181
182 void preprocessComment(String8& comment) {
183 if (comment.size() > 0) {
184 if (comment.contains("@deprecated")) {
185 mDeprecated = true;
186 }
187 if (comment.removeAll("@SystemApi")) {
188 mSystemApi = true;
189 }
190 }
191 }
192
193 void printAnnotations(FILE* fp, const char* indentStr) {
194 if (mDeprecated) {
195 fprintf(fp, "%s@Deprecated\n", indentStr);
196 }
197 if (mSystemApi) {
198 fprintf(fp, "%s@android.annotation.SystemApi\n", indentStr);
199 }
200 }
201
202private:
203 bool mDeprecated;
204 bool mSystemApi;
205};
206
Adam Lesinski282e1812014-01-23 18:17:42 -0800207// ==========================================================================
208// ==========================================================================
209// ==========================================================================
210
211bool isValidResourceType(const String8& type)
212{
213 return type == "anim" || type == "animator" || type == "interpolator"
Chet Haase7cce7bb2013-09-04 17:41:11 -0700214 || type == "transition"
Adam Lesinski282e1812014-01-23 18:17:42 -0800215 || type == "drawable" || type == "layout"
216 || type == "values" || type == "xml" || type == "raw"
217 || type == "color" || type == "menu" || type == "mipmap";
218}
219
Adam Lesinski282e1812014-01-23 18:17:42 -0800220static status_t parsePackage(Bundle* bundle, const sp<AaptAssets>& assets,
221 const sp<AaptGroup>& grp)
222{
223 if (grp->getFiles().size() != 1) {
224 fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
225 grp->getFiles().valueAt(0)->getPrintableSource().string());
226 }
227
228 sp<AaptFile> file = grp->getFiles().valueAt(0);
229
230 ResXMLTree block;
231 status_t err = parseXMLResource(file, &block);
232 if (err != NO_ERROR) {
233 return err;
234 }
235 //printXMLBlock(&block);
236
237 ResXMLTree::event_code_t code;
238 while ((code=block.next()) != ResXMLTree::START_TAG
239 && code != ResXMLTree::END_DOCUMENT
240 && code != ResXMLTree::BAD_DOCUMENT) {
241 }
242
243 size_t len;
244 if (code != ResXMLTree::START_TAG) {
245 fprintf(stderr, "%s:%d: No start tag found\n",
246 file->getPrintableSource().string(), block.getLineNumber());
247 return UNKNOWN_ERROR;
248 }
249 if (strcmp16(block.getElementName(&len), String16("manifest").string()) != 0) {
250 fprintf(stderr, "%s:%d: Invalid start tag %s, expected <manifest>\n",
251 file->getPrintableSource().string(), block.getLineNumber(),
252 String8(block.getElementName(&len)).string());
253 return UNKNOWN_ERROR;
254 }
255
256 ssize_t nameIndex = block.indexOfAttribute(NULL, "package");
257 if (nameIndex < 0) {
258 fprintf(stderr, "%s:%d: <manifest> does not have package attribute.\n",
259 file->getPrintableSource().string(), block.getLineNumber());
260 return UNKNOWN_ERROR;
261 }
262
263 assets->setPackage(String8(block.getAttributeStringValue(nameIndex, &len)));
264
Adam Lesinski54de2982014-12-16 09:16:26 -0800265 ssize_t revisionCodeIndex = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "revisionCode");
266 if (revisionCodeIndex >= 0) {
267 bundle->setRevisionCode(String8(block.getAttributeStringValue(revisionCodeIndex, &len)).string());
268 }
269
Adam Lesinski282e1812014-01-23 18:17:42 -0800270 String16 uses_sdk16("uses-sdk");
271 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
272 && code != ResXMLTree::BAD_DOCUMENT) {
273 if (code == ResXMLTree::START_TAG) {
274 if (strcmp16(block.getElementName(&len), uses_sdk16.string()) == 0) {
275 ssize_t minSdkIndex = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE,
276 "minSdkVersion");
277 if (minSdkIndex >= 0) {
Dan Albertf348c152014-09-08 18:28:00 -0700278 const char16_t* minSdk16 = block.getAttributeStringValue(minSdkIndex, &len);
Adam Lesinski282e1812014-01-23 18:17:42 -0800279 const char* minSdk8 = strdup(String8(minSdk16).string());
280 bundle->setManifestMinSdkVersion(minSdk8);
281 }
282 }
283 }
284 }
285
286 return NO_ERROR;
287}
288
289// ==========================================================================
290// ==========================================================================
291// ==========================================================================
292
293static status_t makeFileResources(Bundle* bundle, const sp<AaptAssets>& assets,
294 ResourceTable* table,
295 const sp<ResourceTypeSet>& set,
296 const char* resType)
297{
298 String8 type8(resType);
299 String16 type16(resType);
300
301 bool hasErrors = false;
302
303 ResourceDirIterator it(set, String8(resType));
304 ssize_t res;
305 while ((res=it.next()) == NO_ERROR) {
306 if (bundle->getVerbose()) {
307 printf(" (new resource id %s from %s)\n",
308 it.getBaseName().string(), it.getFile()->getPrintableSource().string());
309 }
310 String16 baseName(it.getBaseName());
311 const char16_t* str = baseName.string();
312 const char16_t* const end = str + baseName.size();
313 while (str < end) {
314 if (!((*str >= 'a' && *str <= 'z')
315 || (*str >= '0' && *str <= '9')
316 || *str == '_' || *str == '.')) {
317 fprintf(stderr, "%s: Invalid file name: must contain only [a-z0-9_.]\n",
318 it.getPath().string());
319 hasErrors = true;
320 }
321 str++;
322 }
323 String8 resPath = it.getPath();
324 resPath.convertToResPath();
Adam Lesinski526d73b2016-07-18 17:01:14 -0700325 status_t result = table->addEntry(SourcePos(it.getPath(), 0),
326 String16(assets->getPackage()),
Adam Lesinski282e1812014-01-23 18:17:42 -0800327 type16,
328 baseName,
329 String16(resPath),
330 NULL,
331 &it.getParams());
Adam Lesinski526d73b2016-07-18 17:01:14 -0700332 if (result != NO_ERROR) {
333 hasErrors = true;
334 } else {
335 assets->addResource(it.getLeafName(), resPath, it.getFile(), type8);
336 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800337 }
338
Andreas Gampe2412f842014-09-30 20:55:57 -0700339 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -0800340}
341
342class PreProcessImageWorkUnit : public WorkQueue::WorkUnit {
343public:
344 PreProcessImageWorkUnit(const Bundle* bundle, const sp<AaptAssets>& assets,
345 const sp<AaptFile>& file, volatile bool* hasErrors) :
346 mBundle(bundle), mAssets(assets), mFile(file), mHasErrors(hasErrors) {
347 }
348
349 virtual bool run() {
350 status_t status = preProcessImage(mBundle, mAssets, mFile, NULL);
351 if (status) {
352 *mHasErrors = true;
353 }
354 return true; // continue even if there are errors
355 }
356
357private:
358 const Bundle* mBundle;
359 sp<AaptAssets> mAssets;
360 sp<AaptFile> mFile;
361 volatile bool* mHasErrors;
362};
363
364static status_t preProcessImages(const Bundle* bundle, const sp<AaptAssets>& assets,
365 const sp<ResourceTypeSet>& set, const char* type)
366{
367 volatile bool hasErrors = false;
368 ssize_t res = NO_ERROR;
369 if (bundle->getUseCrunchCache() == false) {
370 WorkQueue wq(MAX_THREADS, false);
371 ResourceDirIterator it(set, String8(type));
372 while ((res=it.next()) == NO_ERROR) {
373 PreProcessImageWorkUnit* w = new PreProcessImageWorkUnit(
374 bundle, assets, it.getFile(), &hasErrors);
375 status_t status = wq.schedule(w);
376 if (status) {
377 fprintf(stderr, "preProcessImages failed: schedule() returned %d\n", status);
378 hasErrors = true;
379 delete w;
380 break;
381 }
382 }
383 status_t status = wq.finish();
384 if (status) {
385 fprintf(stderr, "preProcessImages failed: finish() returned %d\n", status);
386 hasErrors = true;
387 }
388 }
Andreas Gampe2412f842014-09-30 20:55:57 -0700389 return (hasErrors || (res < NO_ERROR)) ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -0800390}
391
Adam Lesinski282e1812014-01-23 18:17:42 -0800392static void collect_files(const sp<AaptDir>& dir,
393 KeyedVector<String8, sp<ResourceTypeSet> >* resources)
394{
395 const DefaultKeyedVector<String8, sp<AaptGroup> >& groups = dir->getFiles();
396 int N = groups.size();
397 for (int i=0; i<N; i++) {
Chih-Hung Hsieh8bd37ba2016-08-10 14:15:30 -0700398 const String8& leafName = groups.keyAt(i);
Adam Lesinski282e1812014-01-23 18:17:42 -0800399 const sp<AaptGroup>& group = groups.valueAt(i);
400
401 const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files
402 = group->getFiles();
403
404 if (files.size() == 0) {
405 continue;
406 }
407
408 String8 resType = files.valueAt(0)->getResourceType();
409
410 ssize_t index = resources->indexOfKey(resType);
411
412 if (index < 0) {
413 sp<ResourceTypeSet> set = new ResourceTypeSet();
Andreas Gampe2412f842014-09-30 20:55:57 -0700414 if (kIsDebug) {
415 printf("Creating new resource type set for leaf %s with group %s (%p)\n",
416 leafName.string(), group->getPath().string(), group.get());
417 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800418 set->add(leafName, group);
419 resources->add(resType, set);
420 } else {
Chih-Hung Hsieh8bd37ba2016-08-10 14:15:30 -0700421 const sp<ResourceTypeSet>& set = resources->valueAt(index);
Adam Lesinski282e1812014-01-23 18:17:42 -0800422 index = set->indexOfKey(leafName);
423 if (index < 0) {
Andreas Gampe2412f842014-09-30 20:55:57 -0700424 if (kIsDebug) {
425 printf("Adding to resource type set for leaf %s group %s (%p)\n",
426 leafName.string(), group->getPath().string(), group.get());
427 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800428 set->add(leafName, group);
429 } else {
430 sp<AaptGroup> existingGroup = set->valueAt(index);
Andreas Gampe2412f842014-09-30 20:55:57 -0700431 if (kIsDebug) {
432 printf("Extending to resource type set for leaf %s group %s (%p)\n",
433 leafName.string(), group->getPath().string(), group.get());
434 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800435 for (size_t j=0; j<files.size(); j++) {
Andreas Gampe2412f842014-09-30 20:55:57 -0700436 if (kIsDebug) {
437 printf("Adding file %s in group %s resType %s\n",
438 files.valueAt(j)->getSourceFile().string(),
439 files.keyAt(j).toDirName(String8()).string(),
440 resType.string());
441 }
442 existingGroup->addFile(files.valueAt(j));
Adam Lesinski282e1812014-01-23 18:17:42 -0800443 }
444 }
445 }
446 }
447}
448
449static void collect_files(const sp<AaptAssets>& ass,
450 KeyedVector<String8, sp<ResourceTypeSet> >* resources)
451{
452 const Vector<sp<AaptDir> >& dirs = ass->resDirs();
453 int N = dirs.size();
454
455 for (int i=0; i<N; i++) {
Chih-Hung Hsieh8bd37ba2016-08-10 14:15:30 -0700456 const sp<AaptDir>& d = dirs.itemAt(i);
Andreas Gampe2412f842014-09-30 20:55:57 -0700457 if (kIsDebug) {
458 printf("Collecting dir #%d %p: %s, leaf %s\n", i, d.get(), d->getPath().string(),
459 d->getLeaf().string());
460 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800461 collect_files(d, resources);
462
463 // don't try to include the res dir
Andreas Gampe2412f842014-09-30 20:55:57 -0700464 if (kIsDebug) {
465 printf("Removing dir leaf %s\n", d->getLeaf().string());
466 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800467 ass->removeDir(d->getLeaf());
468 }
469}
470
471enum {
472 ATTR_OKAY = -1,
473 ATTR_NOT_FOUND = -2,
474 ATTR_LEADING_SPACES = -3,
475 ATTR_TRAILING_SPACES = -4
476};
477static int validateAttr(const String8& path, const ResTable& table,
478 const ResXMLParser& parser,
479 const char* ns, const char* attr, const char* validChars, bool required)
480{
481 size_t len;
482
483 ssize_t index = parser.indexOfAttribute(ns, attr);
Dan Albertf348c152014-09-08 18:28:00 -0700484 const char16_t* str;
Adam Lesinski282e1812014-01-23 18:17:42 -0800485 Res_value value;
486 if (index >= 0 && parser.getAttributeValue(index, &value) >= 0) {
487 const ResStringPool* pool = &parser.getStrings();
488 if (value.dataType == Res_value::TYPE_REFERENCE) {
489 uint32_t specFlags = 0;
490 int strIdx;
491 if ((strIdx=table.resolveReference(&value, 0x10000000, NULL, &specFlags)) < 0) {
492 fprintf(stderr, "%s:%d: Tag <%s> attribute %s references unknown resid 0x%08x.\n",
493 path.string(), parser.getLineNumber(),
494 String8(parser.getElementName(&len)).string(), attr,
495 value.data);
496 return ATTR_NOT_FOUND;
497 }
498
499 pool = table.getTableStringBlock(strIdx);
500 #if 0
501 if (pool != NULL) {
502 str = pool->stringAt(value.data, &len);
503 }
504 printf("***** RES ATTR: %s specFlags=0x%x strIdx=%d: %s\n", attr,
505 specFlags, strIdx, str != NULL ? String8(str).string() : "???");
506 #endif
507 if ((specFlags&~ResTable_typeSpec::SPEC_PUBLIC) != 0 && false) {
508 fprintf(stderr, "%s:%d: Tag <%s> attribute %s varies by configurations 0x%x.\n",
509 path.string(), parser.getLineNumber(),
510 String8(parser.getElementName(&len)).string(), attr,
511 specFlags);
512 return ATTR_NOT_FOUND;
513 }
514 }
515 if (value.dataType == Res_value::TYPE_STRING) {
516 if (pool == NULL) {
517 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has no string block.\n",
518 path.string(), parser.getLineNumber(),
519 String8(parser.getElementName(&len)).string(), attr);
520 return ATTR_NOT_FOUND;
521 }
522 if ((str=pool->stringAt(value.data, &len)) == NULL) {
523 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has corrupt string value.\n",
524 path.string(), parser.getLineNumber(),
525 String8(parser.getElementName(&len)).string(), attr);
526 return ATTR_NOT_FOUND;
527 }
528 } else {
529 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has invalid type %d.\n",
530 path.string(), parser.getLineNumber(),
531 String8(parser.getElementName(&len)).string(), attr,
532 value.dataType);
533 return ATTR_NOT_FOUND;
534 }
535 if (validChars) {
536 for (size_t i=0; i<len; i++) {
Adam Lesinski4bf58102014-11-03 11:21:19 -0800537 char16_t c = str[i];
Adam Lesinski282e1812014-01-23 18:17:42 -0800538 const char* p = validChars;
539 bool okay = false;
540 while (*p) {
541 if (c == *p) {
542 okay = true;
543 break;
544 }
545 p++;
546 }
547 if (!okay) {
548 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has invalid character '%c'.\n",
549 path.string(), parser.getLineNumber(),
550 String8(parser.getElementName(&len)).string(), attr, (char)str[i]);
551 return (int)i;
552 }
553 }
554 }
555 if (*str == ' ') {
556 fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not start with a space.\n",
557 path.string(), parser.getLineNumber(),
558 String8(parser.getElementName(&len)).string(), attr);
559 return ATTR_LEADING_SPACES;
560 }
Dan Albertd395f792014-10-20 14:44:39 -0700561 if (len != 0 && str[len-1] == ' ') {
Adam Lesinski282e1812014-01-23 18:17:42 -0800562 fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not end with a space.\n",
563 path.string(), parser.getLineNumber(),
564 String8(parser.getElementName(&len)).string(), attr);
565 return ATTR_TRAILING_SPACES;
566 }
567 return ATTR_OKAY;
568 }
569 if (required) {
570 fprintf(stderr, "%s:%d: Tag <%s> missing required attribute %s.\n",
571 path.string(), parser.getLineNumber(),
572 String8(parser.getElementName(&len)).string(), attr);
573 return ATTR_NOT_FOUND;
574 }
575 return ATTR_OKAY;
576}
577
578static void checkForIds(const String8& path, ResXMLParser& parser)
579{
580 ResXMLTree::event_code_t code;
581 while ((code=parser.next()) != ResXMLTree::END_DOCUMENT
582 && code > ResXMLTree::BAD_DOCUMENT) {
583 if (code == ResXMLTree::START_TAG) {
584 ssize_t index = parser.indexOfAttribute(NULL, "id");
585 if (index >= 0) {
586 fprintf(stderr, "%s:%d: warning: found plain 'id' attribute; did you mean the new 'android:id' name?\n",
587 path.string(), parser.getLineNumber());
588 }
589 }
590 }
591}
592
593static bool applyFileOverlay(Bundle *bundle,
594 const sp<AaptAssets>& assets,
595 sp<ResourceTypeSet> *baseSet,
596 const char *resType)
597{
598 if (bundle->getVerbose()) {
599 printf("applyFileOverlay for %s\n", resType);
600 }
601
602 // Replace any base level files in this category with any found from the overlay
603 // Also add any found only in the overlay.
604 sp<AaptAssets> overlay = assets->getOverlay();
605 String8 resTypeString(resType);
606
607 // work through the linked list of overlays
608 while (overlay.get()) {
609 KeyedVector<String8, sp<ResourceTypeSet> >* overlayRes = overlay->getResources();
610
611 // get the overlay resources of the requested type
612 ssize_t index = overlayRes->indexOfKey(resTypeString);
613 if (index >= 0) {
Chih-Hung Hsieh8bd37ba2016-08-10 14:15:30 -0700614 const sp<ResourceTypeSet>& overlaySet = overlayRes->valueAt(index);
Adam Lesinski282e1812014-01-23 18:17:42 -0800615
616 // for each of the resources, check for a match in the previously built
617 // non-overlay "baseset".
618 size_t overlayCount = overlaySet->size();
619 for (size_t overlayIndex=0; overlayIndex<overlayCount; overlayIndex++) {
620 if (bundle->getVerbose()) {
621 printf("trying overlaySet Key=%s\n",overlaySet->keyAt(overlayIndex).string());
622 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700623 ssize_t baseIndex = -1;
Adam Lesinski282e1812014-01-23 18:17:42 -0800624 if (baseSet->get() != NULL) {
625 baseIndex = (*baseSet)->indexOfKey(overlaySet->keyAt(overlayIndex));
626 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700627 if (baseIndex >= 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800628 // look for same flavor. For a given file (strings.xml, for example)
629 // there may be a locale specific or other flavors - we want to match
630 // the same flavor.
631 sp<AaptGroup> overlayGroup = overlaySet->valueAt(overlayIndex);
632 sp<AaptGroup> baseGroup = (*baseSet)->valueAt(baseIndex);
633
634 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > overlayFiles =
635 overlayGroup->getFiles();
636 if (bundle->getVerbose()) {
637 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > baseFiles =
638 baseGroup->getFiles();
639 for (size_t i=0; i < baseFiles.size(); i++) {
640 printf("baseFile " ZD " has flavor %s\n", (ZD_TYPE) i,
641 baseFiles.keyAt(i).toString().string());
642 }
643 for (size_t i=0; i < overlayFiles.size(); i++) {
644 printf("overlayFile " ZD " has flavor %s\n", (ZD_TYPE) i,
645 overlayFiles.keyAt(i).toString().string());
646 }
647 }
648
649 size_t overlayGroupSize = overlayFiles.size();
650 for (size_t overlayGroupIndex = 0;
651 overlayGroupIndex<overlayGroupSize;
652 overlayGroupIndex++) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700653 ssize_t baseFileIndex =
Adam Lesinski282e1812014-01-23 18:17:42 -0800654 baseGroup->getFiles().indexOfKey(overlayFiles.
655 keyAt(overlayGroupIndex));
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700656 if (baseFileIndex >= 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800657 if (bundle->getVerbose()) {
658 printf("found a match (" ZD ") for overlay file %s, for flavor %s\n",
659 (ZD_TYPE) baseFileIndex,
660 overlayGroup->getLeaf().string(),
661 overlayFiles.keyAt(overlayGroupIndex).toString().string());
662 }
663 baseGroup->removeFile(baseFileIndex);
664 } else {
665 // didn't find a match fall through and add it..
666 if (true || bundle->getVerbose()) {
667 printf("nothing matches overlay file %s, for flavor %s\n",
668 overlayGroup->getLeaf().string(),
669 overlayFiles.keyAt(overlayGroupIndex).toString().string());
670 }
671 }
672 baseGroup->addFile(overlayFiles.valueAt(overlayGroupIndex));
673 assets->addGroupEntry(overlayFiles.keyAt(overlayGroupIndex));
674 }
675 } else {
676 if (baseSet->get() == NULL) {
677 *baseSet = new ResourceTypeSet();
678 assets->getResources()->add(String8(resType), *baseSet);
679 }
680 // this group doesn't exist (a file that's only in the overlay)
681 (*baseSet)->add(overlaySet->keyAt(overlayIndex),
682 overlaySet->valueAt(overlayIndex));
683 // make sure all flavors are defined in the resources.
684 sp<AaptGroup> overlayGroup = overlaySet->valueAt(overlayIndex);
685 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > overlayFiles =
686 overlayGroup->getFiles();
687 size_t overlayGroupSize = overlayFiles.size();
688 for (size_t overlayGroupIndex = 0;
689 overlayGroupIndex<overlayGroupSize;
690 overlayGroupIndex++) {
691 assets->addGroupEntry(overlayFiles.keyAt(overlayGroupIndex));
692 }
693 }
694 }
695 // this overlay didn't have resources for this type
696 }
697 // try next overlay
698 overlay = overlay->getOverlay();
699 }
700 return true;
701}
702
703/*
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800704 * Inserts an attribute in a given node.
Adam Lesinski282e1812014-01-23 18:17:42 -0800705 * If errorOnFailedInsert is true, and the attribute already exists, returns false.
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800706 * If replaceExisting is true, the attribute will be updated if it already exists.
707 * Returns true otherwise, even if the attribute already exists, and does not modify
708 * the existing attribute's value.
Adam Lesinski282e1812014-01-23 18:17:42 -0800709 */
710bool addTagAttribute(const sp<XMLNode>& node, const char* ns8,
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800711 const char* attr8, const char* value, bool errorOnFailedInsert,
712 bool replaceExisting)
Adam Lesinski282e1812014-01-23 18:17:42 -0800713{
714 if (value == NULL) {
715 return true;
716 }
717
718 const String16 ns(ns8);
719 const String16 attr(attr8);
720
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800721 XMLNode::attribute_entry* existingEntry = node->editAttribute(ns, attr);
722 if (existingEntry != NULL) {
723 if (replaceExisting) {
Andreas Gampe87332a72014-10-01 22:03:58 -0700724 if (kIsDebug) {
725 printf("Info: AndroidManifest.xml already defines %s (in %s);"
726 " overwriting existing value from manifest.\n",
727 String8(attr).string(), String8(ns).string());
728 }
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800729 existingEntry->string = String16(value);
730 return true;
731 }
732
Adam Lesinski282e1812014-01-23 18:17:42 -0800733 if (errorOnFailedInsert) {
734 fprintf(stderr, "Error: AndroidManifest.xml already defines %s (in %s);"
735 " cannot insert new value %s.\n",
736 String8(attr).string(), String8(ns).string(), value);
737 return false;
738 }
739
740 fprintf(stderr, "Warning: AndroidManifest.xml already defines %s (in %s);"
741 " using existing value in manifest.\n",
742 String8(attr).string(), String8(ns).string());
743
744 // don't stop the build.
745 return true;
746 }
747
748 node->addAttribute(ns, attr, String16(value));
749 return true;
750}
751
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800752/*
753 * Inserts an attribute in a given node, only if the attribute does not
754 * exist.
755 * If errorOnFailedInsert is true, and the attribute already exists, returns false.
756 * Returns true otherwise, even if the attribute already exists.
757 */
758bool addTagAttribute(const sp<XMLNode>& node, const char* ns8,
759 const char* attr8, const char* value, bool errorOnFailedInsert)
760{
761 return addTagAttribute(node, ns8, attr8, value, errorOnFailedInsert, false);
762}
763
Chih-Hung Hsieh8bd37ba2016-08-10 14:15:30 -0700764static void fullyQualifyClassName(const String8& package, const sp<XMLNode>& node,
Adam Lesinski282e1812014-01-23 18:17:42 -0800765 const String16& attrName) {
766 XMLNode::attribute_entry* attr = node->editAttribute(
767 String16("http://schemas.android.com/apk/res/android"), attrName);
768 if (attr != NULL) {
769 String8 name(attr->string);
770
771 // asdf --> package.asdf
772 // .asdf .a.b --> package.asdf package.a.b
773 // asdf.adsf --> asdf.asdf
774 String8 className;
775 const char* p = name.string();
776 const char* q = strchr(p, '.');
777 if (p == q) {
778 className += package;
779 className += name;
780 } else if (q == NULL) {
781 className += package;
782 className += ".";
783 className += name;
784 } else {
785 className += name;
786 }
Andreas Gampe2412f842014-09-30 20:55:57 -0700787 if (kIsDebug) {
788 printf("Qualifying class '%s' to '%s'", name.string(), className.string());
789 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800790 attr->string.setTo(String16(className));
791 }
792}
793
794status_t massageManifest(Bundle* bundle, sp<XMLNode> root)
795{
796 root = root->searchElement(String16(), String16("manifest"));
797 if (root == NULL) {
798 fprintf(stderr, "No <manifest> tag.\n");
799 return UNKNOWN_ERROR;
800 }
801
802 bool errorOnFailedInsert = bundle->getErrorOnFailedInsert();
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800803 bool replaceVersion = bundle->getReplaceVersion();
Adam Lesinski282e1812014-01-23 18:17:42 -0800804
805 if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionCode",
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800806 bundle->getVersionCode(), errorOnFailedInsert, replaceVersion)) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800807 return UNKNOWN_ERROR;
Adam Lesinski6a7d2752014-08-07 21:26:53 -0700808 } else {
809 const XMLNode::attribute_entry* attr = root->getAttribute(
810 String16(RESOURCES_ANDROID_NAMESPACE), String16("versionCode"));
811 if (attr != NULL) {
812 bundle->setVersionCode(strdup(String8(attr->string).string()));
813 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800814 }
Adam Lesinski6a7d2752014-08-07 21:26:53 -0700815
Adam Lesinski282e1812014-01-23 18:17:42 -0800816 if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionName",
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800817 bundle->getVersionName(), errorOnFailedInsert, replaceVersion)) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800818 return UNKNOWN_ERROR;
Adam Lesinski82a2dd82014-09-17 18:34:15 -0700819 } else {
820 const XMLNode::attribute_entry* attr = root->getAttribute(
821 String16(RESOURCES_ANDROID_NAMESPACE), String16("versionName"));
822 if (attr != NULL) {
823 bundle->setVersionName(strdup(String8(attr->string).string()));
824 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800825 }
826
Adam Lesinski82a2dd82014-09-17 18:34:15 -0700827 sp<XMLNode> vers = root->getChildElement(String16(), String16("uses-sdk"));
Adam Lesinski282e1812014-01-23 18:17:42 -0800828 if (bundle->getMinSdkVersion() != NULL
829 || bundle->getTargetSdkVersion() != NULL
830 || bundle->getMaxSdkVersion() != NULL) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800831 if (vers == NULL) {
832 vers = XMLNode::newElement(root->getFilename(), String16(), String16("uses-sdk"));
833 root->insertChildAt(vers, 0);
834 }
835
836 if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "minSdkVersion",
837 bundle->getMinSdkVersion(), errorOnFailedInsert)) {
838 return UNKNOWN_ERROR;
839 }
840 if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "targetSdkVersion",
841 bundle->getTargetSdkVersion(), errorOnFailedInsert)) {
842 return UNKNOWN_ERROR;
843 }
844 if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "maxSdkVersion",
845 bundle->getMaxSdkVersion(), errorOnFailedInsert)) {
846 return UNKNOWN_ERROR;
847 }
848 }
849
Adam Lesinski82a2dd82014-09-17 18:34:15 -0700850 if (vers != NULL) {
851 const XMLNode::attribute_entry* attr = vers->getAttribute(
852 String16(RESOURCES_ANDROID_NAMESPACE), String16("minSdkVersion"));
853 if (attr != NULL) {
854 bundle->setMinSdkVersion(strdup(String8(attr->string).string()));
855 }
856 }
857
Adam Lesinskiad2d07d2014-08-27 16:21:08 -0700858 if (bundle->getPlatformBuildVersionCode() != "") {
859 if (!addTagAttribute(root, "", "platformBuildVersionCode",
860 bundle->getPlatformBuildVersionCode(), errorOnFailedInsert, true)) {
861 return UNKNOWN_ERROR;
862 }
863 }
864
865 if (bundle->getPlatformBuildVersionName() != "") {
866 if (!addTagAttribute(root, "", "platformBuildVersionName",
867 bundle->getPlatformBuildVersionName(), errorOnFailedInsert, true)) {
868 return UNKNOWN_ERROR;
869 }
870 }
871
Adam Lesinski282e1812014-01-23 18:17:42 -0800872 if (bundle->getDebugMode()) {
873 sp<XMLNode> application = root->getChildElement(String16(), String16("application"));
874 if (application != NULL) {
875 if (!addTagAttribute(application, RESOURCES_ANDROID_NAMESPACE, "debuggable", "true",
876 errorOnFailedInsert)) {
877 return UNKNOWN_ERROR;
878 }
879 }
880 }
881
882 // Deal with manifest package name overrides
883 const char* manifestPackageNameOverride = bundle->getManifestPackageNameOverride();
884 if (manifestPackageNameOverride != NULL) {
885 // Update the actual package name
886 XMLNode::attribute_entry* attr = root->editAttribute(String16(), String16("package"));
887 if (attr == NULL) {
888 fprintf(stderr, "package name is required with --rename-manifest-package.\n");
889 return UNKNOWN_ERROR;
890 }
891 String8 origPackage(attr->string);
892 attr->string.setTo(String16(manifestPackageNameOverride));
Andreas Gampe2412f842014-09-30 20:55:57 -0700893 if (kIsDebug) {
894 printf("Overriding package '%s' to be '%s'\n", origPackage.string(),
895 manifestPackageNameOverride);
896 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800897
898 // Make class names fully qualified
899 sp<XMLNode> application = root->getChildElement(String16(), String16("application"));
900 if (application != NULL) {
901 fullyQualifyClassName(origPackage, application, String16("name"));
902 fullyQualifyClassName(origPackage, application, String16("backupAgent"));
903
904 Vector<sp<XMLNode> >& children = const_cast<Vector<sp<XMLNode> >&>(application->getChildren());
905 for (size_t i = 0; i < children.size(); i++) {
906 sp<XMLNode> child = children.editItemAt(i);
907 String8 tag(child->getElementName());
908 if (tag == "activity" || tag == "service" || tag == "receiver" || tag == "provider") {
909 fullyQualifyClassName(origPackage, child, String16("name"));
910 } else if (tag == "activity-alias") {
911 fullyQualifyClassName(origPackage, child, String16("name"));
912 fullyQualifyClassName(origPackage, child, String16("targetActivity"));
913 }
914 }
915 }
916 }
917
918 // Deal with manifest package name overrides
919 const char* instrumentationPackageNameOverride = bundle->getInstrumentationPackageNameOverride();
920 if (instrumentationPackageNameOverride != NULL) {
921 // Fix up instrumentation targets.
922 Vector<sp<XMLNode> >& children = const_cast<Vector<sp<XMLNode> >&>(root->getChildren());
923 for (size_t i = 0; i < children.size(); i++) {
924 sp<XMLNode> child = children.editItemAt(i);
925 String8 tag(child->getElementName());
926 if (tag == "instrumentation") {
927 XMLNode::attribute_entry* attr = child->editAttribute(
928 String16("http://schemas.android.com/apk/res/android"), String16("targetPackage"));
929 if (attr != NULL) {
930 attr->string.setTo(String16(instrumentationPackageNameOverride));
931 }
932 }
933 }
934 }
935
Adam Lesinski833f3cc2014-06-18 15:06:01 -0700936 // Generate split name if feature is present.
937 const XMLNode::attribute_entry* attr = root->getAttribute(String16(), String16("featureName"));
938 if (attr != NULL) {
939 String16 splitName("feature_");
940 splitName.append(attr->string);
941 status_t err = root->addAttribute(String16(), String16("split"), splitName);
942 if (err != NO_ERROR) {
943 ALOGE("Failed to insert split name into AndroidManifest.xml");
944 return err;
945 }
946 }
947
Adam Lesinski282e1812014-01-23 18:17:42 -0800948 return NO_ERROR;
949}
950
Adam Lesinskiad2d07d2014-08-27 16:21:08 -0700951static int32_t getPlatformAssetCookie(const AssetManager& assets) {
952 // Find the system package (0x01). AAPT always generates attributes
953 // with the type 0x01, so we're looking for the first attribute
954 // resource in the system package.
955 const ResTable& table = assets.getResources(true);
956 Res_value val;
957 ssize_t idx = table.getResource(0x01010000, &val, true);
958 if (idx != NO_ERROR) {
959 // Try as a bag.
960 const ResTable::bag_entry* entry;
961 ssize_t cnt = table.lockBag(0x01010000, &entry);
962 if (cnt >= 0) {
963 idx = entry->stringBlock;
964 }
965 table.unlockBag(entry);
966 }
967
968 if (idx < 0) {
969 return 0;
970 }
971 return table.getTableCookie(idx);
972}
973
974enum {
975 VERSION_CODE_ATTR = 0x0101021b,
976 VERSION_NAME_ATTR = 0x0101021c,
977};
978
979static ssize_t extractPlatformBuildVersion(ResXMLTree& tree, Bundle* bundle) {
980 size_t len;
981 ResXMLTree::event_code_t code;
982 while ((code = tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
983 if (code != ResXMLTree::START_TAG) {
984 continue;
985 }
986
987 const char16_t* ctag16 = tree.getElementName(&len);
988 if (ctag16 == NULL) {
989 fprintf(stderr, "ERROR: failed to get XML element name (bad string pool)\n");
990 return UNKNOWN_ERROR;
991 }
992
993 String8 tag(ctag16, len);
994 if (tag != "manifest") {
995 continue;
996 }
997
998 String8 error;
999 int32_t versionCode = AaptXml::getIntegerAttribute(tree, VERSION_CODE_ATTR, &error);
1000 if (error != "") {
1001 fprintf(stderr, "ERROR: failed to get platform version code\n");
1002 return UNKNOWN_ERROR;
1003 }
1004
1005 if (versionCode >= 0 && bundle->getPlatformBuildVersionCode() == "") {
1006 bundle->setPlatformBuildVersionCode(String8::format("%d", versionCode));
1007 }
1008
1009 String8 versionName = AaptXml::getAttribute(tree, VERSION_NAME_ATTR, &error);
1010 if (error != "") {
1011 fprintf(stderr, "ERROR: failed to get platform version name\n");
1012 return UNKNOWN_ERROR;
1013 }
1014
1015 if (versionName != "" && bundle->getPlatformBuildVersionName() == "") {
1016 bundle->setPlatformBuildVersionName(versionName);
1017 }
1018 return NO_ERROR;
1019 }
1020
1021 fprintf(stderr, "ERROR: no <manifest> tag found in platform AndroidManifest.xml\n");
1022 return UNKNOWN_ERROR;
1023}
1024
1025static ssize_t extractPlatformBuildVersion(AssetManager& assets, Bundle* bundle) {
1026 int32_t cookie = getPlatformAssetCookie(assets);
1027 if (cookie == 0) {
Adam Lesinski82a2dd82014-09-17 18:34:15 -07001028 // No platform was loaded.
1029 return NO_ERROR;
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001030 }
1031
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001032 Asset* asset = assets.openNonAsset(cookie, "AndroidManifest.xml", Asset::ACCESS_STREAMING);
1033 if (asset == NULL) {
1034 fprintf(stderr, "ERROR: Platform AndroidManifest.xml not found\n");
1035 return UNKNOWN_ERROR;
1036 }
1037
1038 ssize_t result = NO_ERROR;
Adam Lesinski193ed742016-08-15 14:19:46 -07001039
1040 // Create a new scope so that ResXMLTree is destroyed before we delete the memory over
1041 // which it iterates (asset).
1042 {
1043 ResXMLTree tree;
1044 if (tree.setTo(asset->getBuffer(true), asset->getLength()) != NO_ERROR) {
1045 fprintf(stderr, "ERROR: Platform AndroidManifest.xml is corrupt\n");
1046 result = UNKNOWN_ERROR;
1047 } else {
1048 result = extractPlatformBuildVersion(tree, bundle);
1049 }
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001050 }
1051
1052 delete asset;
1053 return result;
1054}
1055
Adam Lesinski282e1812014-01-23 18:17:42 -08001056#define ASSIGN_IT(n) \
1057 do { \
1058 ssize_t index = resources->indexOfKey(String8(#n)); \
1059 if (index >= 0) { \
1060 n ## s = resources->valueAt(index); \
1061 } \
1062 } while (0)
1063
1064status_t updatePreProcessedCache(Bundle* bundle)
1065{
1066 #if BENCHMARK
1067 fprintf(stdout, "BENCHMARK: Starting PNG PreProcessing \n");
1068 long startPNGTime = clock();
1069 #endif /* BENCHMARK */
1070
1071 String8 source(bundle->getResourceSourceDirs()[0]);
1072 String8 dest(bundle->getCrunchedOutputDir());
1073
1074 FileFinder* ff = new SystemFileFinder();
1075 CrunchCache cc(source,dest,ff);
1076
1077 CacheUpdater* cu = new SystemCacheUpdater(bundle);
1078 size_t numFiles = cc.crunch(cu);
1079
1080 if (bundle->getVerbose())
1081 fprintf(stdout, "Crunched %d PNG files to update cache\n", (int)numFiles);
1082
1083 delete ff;
1084 delete cu;
1085
1086 #if BENCHMARK
1087 fprintf(stdout, "BENCHMARK: End PNG PreProcessing. Time Elapsed: %f ms \n"
1088 ,(clock() - startPNGTime)/1000.0);
1089 #endif /* BENCHMARK */
1090 return 0;
1091}
1092
Jeff Sharkey2cfc8482014-07-09 16:10:16 -07001093status_t generateAndroidManifestForSplit(Bundle* bundle, const sp<AaptAssets>& assets,
1094 const sp<ApkSplit>& split, sp<AaptFile>& outFile, ResourceTable* table) {
Adam Lesinskifab50872014-04-16 14:40:42 -07001095 const String8 filename("AndroidManifest.xml");
1096 const String16 androidPrefix("android");
1097 const String16 androidNSUri("http://schemas.android.com/apk/res/android");
1098 sp<XMLNode> root = XMLNode::newNamespace(filename, androidPrefix, androidNSUri);
1099
1100 // Build the <manifest> tag
1101 sp<XMLNode> manifest = XMLNode::newElement(filename, String16(), String16("manifest"));
1102
Jeff Sharkey2cfc8482014-07-09 16:10:16 -07001103 // Add the 'package' attribute which is set to the package name.
1104 const char* packageName = assets->getPackage();
1105 const char* manifestPackageNameOverride = bundle->getManifestPackageNameOverride();
1106 if (manifestPackageNameOverride != NULL) {
1107 packageName = manifestPackageNameOverride;
1108 }
1109 manifest->addAttribute(String16(), String16("package"), String16(packageName));
1110
1111 // Add the 'versionCode' attribute which is set to the original version code.
1112 if (!addTagAttribute(manifest, RESOURCES_ANDROID_NAMESPACE, "versionCode",
1113 bundle->getVersionCode(), true, true)) {
1114 return UNKNOWN_ERROR;
1115 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001116
Adam Lesinski54de2982014-12-16 09:16:26 -08001117 // Add the 'revisionCode' attribute, which is set to the original revisionCode.
1118 if (bundle->getRevisionCode().size() > 0) {
1119 if (!addTagAttribute(manifest, RESOURCES_ANDROID_NAMESPACE, "revisionCode",
1120 bundle->getRevisionCode().string(), true, true)) {
1121 return UNKNOWN_ERROR;
1122 }
1123 }
1124
Adam Lesinskifab50872014-04-16 14:40:42 -07001125 // Add the 'split' attribute which describes the configurations included.
Adam Lesinski62408402014-08-07 21:26:53 -07001126 String8 splitName("config.");
1127 splitName.append(split->getPackageSafeName());
Adam Lesinskifab50872014-04-16 14:40:42 -07001128 manifest->addAttribute(String16(), String16("split"), String16(splitName));
1129
1130 // Build an empty <application> tag (required).
1131 sp<XMLNode> app = XMLNode::newElement(filename, String16(), String16("application"));
Jeff Sharkey78a13012014-07-15 20:18:34 -07001132
1133 // Add the 'hasCode' attribute which is never true for resource splits.
1134 if (!addTagAttribute(app, RESOURCES_ANDROID_NAMESPACE, "hasCode",
1135 "false", true, true)) {
1136 return UNKNOWN_ERROR;
1137 }
1138
Adam Lesinskifab50872014-04-16 14:40:42 -07001139 manifest->addChild(app);
1140 root->addChild(manifest);
1141
Adam Lesinskie572c012014-09-19 15:10:04 -07001142 int err = compileXmlFile(bundle, assets, String16(), root, outFile, table);
Jeff Sharkey2cfc8482014-07-09 16:10:16 -07001143 if (err < NO_ERROR) {
Adam Lesinskifab50872014-04-16 14:40:42 -07001144 return err;
1145 }
1146 outFile->setCompressionMethod(ZipEntry::kCompressDeflated);
1147 return NO_ERROR;
1148}
1149
1150status_t buildResources(Bundle* bundle, const sp<AaptAssets>& assets, sp<ApkBuilder>& builder)
Adam Lesinski282e1812014-01-23 18:17:42 -08001151{
1152 // First, look for a package file to parse. This is required to
1153 // be able to generate the resource information.
1154 sp<AaptGroup> androidManifestFile =
1155 assets->getFiles().valueFor(String8("AndroidManifest.xml"));
1156 if (androidManifestFile == NULL) {
1157 fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n");
1158 return UNKNOWN_ERROR;
1159 }
1160
1161 status_t err = parsePackage(bundle, assets, androidManifestFile);
1162 if (err != NO_ERROR) {
1163 return err;
1164 }
1165
Andreas Gampe2412f842014-09-30 20:55:57 -07001166 if (kIsDebug) {
1167 printf("Creating resources for package %s\n", assets->getPackage().string());
1168 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001169
Adam Lesinski78713992015-12-07 14:02:15 -08001170 // Set the private symbols package if it was declared.
1171 // This can also be declared in XML as <private-symbols name="package" />
1172 if (bundle->getPrivateSymbolsPackage().size() != 0) {
1173 assets->setSymbolsPrivatePackage(bundle->getPrivateSymbolsPackage());
1174 }
1175
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001176 ResourceTable::PackageType packageType = ResourceTable::App;
1177 if (bundle->getBuildSharedLibrary()) {
1178 packageType = ResourceTable::SharedLibrary;
1179 } else if (bundle->getExtending()) {
1180 packageType = ResourceTable::System;
1181 } else if (!bundle->getFeatureOfPackage().isEmpty()) {
1182 packageType = ResourceTable::AppFeature;
1183 }
1184
1185 ResourceTable table(bundle, String16(assets->getPackage()), packageType);
Adam Lesinski282e1812014-01-23 18:17:42 -08001186 err = table.addIncludedResources(bundle, assets);
1187 if (err != NO_ERROR) {
1188 return err;
1189 }
1190
Andreas Gampe2412f842014-09-30 20:55:57 -07001191 if (kIsDebug) {
1192 printf("Found %d included resource packages\n", (int)table.size());
1193 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001194
1195 // Standard flags for compiled XML and optional UTF-8 encoding
1196 int xmlFlags = XML_COMPILE_STANDARD_RESOURCE;
1197
1198 /* Only enable UTF-8 if the caller of aapt didn't specifically
1199 * request UTF-16 encoding and the parameters of this package
1200 * allow UTF-8 to be used.
1201 */
1202 if (!bundle->getUTF16StringsOption()) {
1203 xmlFlags |= XML_COMPILE_UTF8;
1204 }
1205
1206 // --------------------------------------------------------------
1207 // First, gather all resource information.
1208 // --------------------------------------------------------------
1209
1210 // resType -> leafName -> group
1211 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
1212 new KeyedVector<String8, sp<ResourceTypeSet> >;
1213 collect_files(assets, resources);
1214
1215 sp<ResourceTypeSet> drawables;
1216 sp<ResourceTypeSet> layouts;
1217 sp<ResourceTypeSet> anims;
1218 sp<ResourceTypeSet> animators;
1219 sp<ResourceTypeSet> interpolators;
1220 sp<ResourceTypeSet> transitions;
Adam Lesinski282e1812014-01-23 18:17:42 -08001221 sp<ResourceTypeSet> xmls;
1222 sp<ResourceTypeSet> raws;
1223 sp<ResourceTypeSet> colors;
1224 sp<ResourceTypeSet> menus;
1225 sp<ResourceTypeSet> mipmaps;
1226
1227 ASSIGN_IT(drawable);
1228 ASSIGN_IT(layout);
1229 ASSIGN_IT(anim);
1230 ASSIGN_IT(animator);
1231 ASSIGN_IT(interpolator);
1232 ASSIGN_IT(transition);
Adam Lesinski282e1812014-01-23 18:17:42 -08001233 ASSIGN_IT(xml);
1234 ASSIGN_IT(raw);
1235 ASSIGN_IT(color);
1236 ASSIGN_IT(menu);
1237 ASSIGN_IT(mipmap);
1238
1239 assets->setResources(resources);
1240 // now go through any resource overlays and collect their files
1241 sp<AaptAssets> current = assets->getOverlay();
1242 while(current.get()) {
1243 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
1244 new KeyedVector<String8, sp<ResourceTypeSet> >;
1245 current->setResources(resources);
1246 collect_files(current, resources);
1247 current = current->getOverlay();
1248 }
1249 // apply the overlay files to the base set
1250 if (!applyFileOverlay(bundle, assets, &drawables, "drawable") ||
1251 !applyFileOverlay(bundle, assets, &layouts, "layout") ||
1252 !applyFileOverlay(bundle, assets, &anims, "anim") ||
1253 !applyFileOverlay(bundle, assets, &animators, "animator") ||
1254 !applyFileOverlay(bundle, assets, &interpolators, "interpolator") ||
1255 !applyFileOverlay(bundle, assets, &transitions, "transition") ||
Adam Lesinski282e1812014-01-23 18:17:42 -08001256 !applyFileOverlay(bundle, assets, &xmls, "xml") ||
1257 !applyFileOverlay(bundle, assets, &raws, "raw") ||
1258 !applyFileOverlay(bundle, assets, &colors, "color") ||
1259 !applyFileOverlay(bundle, assets, &menus, "menu") ||
1260 !applyFileOverlay(bundle, assets, &mipmaps, "mipmap")) {
1261 return UNKNOWN_ERROR;
1262 }
1263
1264 bool hasErrors = false;
1265
1266 if (drawables != NULL) {
1267 if (bundle->getOutputAPKFile() != NULL) {
1268 err = preProcessImages(bundle, assets, drawables, "drawable");
1269 }
1270 if (err == NO_ERROR) {
1271 err = makeFileResources(bundle, assets, &table, drawables, "drawable");
1272 if (err != NO_ERROR) {
1273 hasErrors = true;
1274 }
1275 } else {
1276 hasErrors = true;
1277 }
1278 }
1279
1280 if (mipmaps != NULL) {
1281 if (bundle->getOutputAPKFile() != NULL) {
1282 err = preProcessImages(bundle, assets, mipmaps, "mipmap");
1283 }
1284 if (err == NO_ERROR) {
1285 err = makeFileResources(bundle, assets, &table, mipmaps, "mipmap");
1286 if (err != NO_ERROR) {
1287 hasErrors = true;
1288 }
1289 } else {
1290 hasErrors = true;
1291 }
1292 }
1293
1294 if (layouts != NULL) {
1295 err = makeFileResources(bundle, assets, &table, layouts, "layout");
1296 if (err != NO_ERROR) {
1297 hasErrors = true;
1298 }
1299 }
1300
1301 if (anims != NULL) {
1302 err = makeFileResources(bundle, assets, &table, anims, "anim");
1303 if (err != NO_ERROR) {
1304 hasErrors = true;
1305 }
1306 }
1307
1308 if (animators != NULL) {
1309 err = makeFileResources(bundle, assets, &table, animators, "animator");
1310 if (err != NO_ERROR) {
1311 hasErrors = true;
1312 }
1313 }
1314
1315 if (transitions != NULL) {
1316 err = makeFileResources(bundle, assets, &table, transitions, "transition");
1317 if (err != NO_ERROR) {
1318 hasErrors = true;
1319 }
1320 }
1321
Adam Lesinski282e1812014-01-23 18:17:42 -08001322 if (interpolators != NULL) {
1323 err = makeFileResources(bundle, assets, &table, interpolators, "interpolator");
1324 if (err != NO_ERROR) {
1325 hasErrors = true;
1326 }
1327 }
1328
1329 if (xmls != NULL) {
1330 err = makeFileResources(bundle, assets, &table, xmls, "xml");
1331 if (err != NO_ERROR) {
1332 hasErrors = true;
1333 }
1334 }
1335
1336 if (raws != NULL) {
1337 err = makeFileResources(bundle, assets, &table, raws, "raw");
1338 if (err != NO_ERROR) {
1339 hasErrors = true;
1340 }
1341 }
1342
1343 // compile resources
1344 current = assets;
1345 while(current.get()) {
1346 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
1347 current->getResources();
1348
1349 ssize_t index = resources->indexOfKey(String8("values"));
1350 if (index >= 0) {
1351 ResourceDirIterator it(resources->valueAt(index), String8("values"));
1352 ssize_t res;
1353 while ((res=it.next()) == NO_ERROR) {
Chih-Hung Hsieh8bd37ba2016-08-10 14:15:30 -07001354 const sp<AaptFile>& file = it.getFile();
Adam Lesinski282e1812014-01-23 18:17:42 -08001355 res = compileResourceFile(bundle, assets, file, it.getParams(),
1356 (current!=assets), &table);
1357 if (res != NO_ERROR) {
1358 hasErrors = true;
1359 }
1360 }
1361 }
1362 current = current->getOverlay();
1363 }
1364
1365 if (colors != NULL) {
1366 err = makeFileResources(bundle, assets, &table, colors, "color");
1367 if (err != NO_ERROR) {
1368 hasErrors = true;
1369 }
1370 }
1371
1372 if (menus != NULL) {
1373 err = makeFileResources(bundle, assets, &table, menus, "menu");
1374 if (err != NO_ERROR) {
1375 hasErrors = true;
1376 }
1377 }
1378
Adam Lesinski526d73b2016-07-18 17:01:14 -07001379 if (hasErrors) {
1380 return UNKNOWN_ERROR;
1381 }
1382
Adam Lesinski282e1812014-01-23 18:17:42 -08001383 // --------------------------------------------------------------------
1384 // Assignment of resource IDs and initial generation of resource table.
1385 // --------------------------------------------------------------------
1386
1387 if (table.hasResources()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001388 err = table.assignResourceIds();
1389 if (err < NO_ERROR) {
1390 return err;
1391 }
1392 }
1393
1394 // --------------------------------------------------------------
1395 // Finally, we can now we can compile XML files, which may reference
1396 // resources.
1397 // --------------------------------------------------------------
1398
1399 if (layouts != NULL) {
1400 ResourceDirIterator it(layouts, String8("layout"));
1401 while ((err=it.next()) == NO_ERROR) {
1402 String8 src = it.getFile()->getPrintableSource();
Adam Lesinskie572c012014-09-19 15:10:04 -07001403 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1404 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001405 if (err == NO_ERROR) {
1406 ResXMLTree block;
1407 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
1408 checkForIds(src, block);
1409 } else {
1410 hasErrors = true;
1411 }
1412 }
1413
1414 if (err < NO_ERROR) {
1415 hasErrors = true;
1416 }
1417 err = NO_ERROR;
1418 }
1419
1420 if (anims != NULL) {
1421 ResourceDirIterator it(anims, String8("anim"));
1422 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001423 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1424 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001425 if (err != NO_ERROR) {
1426 hasErrors = true;
1427 }
1428 }
1429
1430 if (err < NO_ERROR) {
1431 hasErrors = true;
1432 }
1433 err = NO_ERROR;
1434 }
1435
1436 if (animators != NULL) {
1437 ResourceDirIterator it(animators, String8("animator"));
1438 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001439 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1440 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001441 if (err != NO_ERROR) {
1442 hasErrors = true;
1443 }
1444 }
1445
1446 if (err < NO_ERROR) {
1447 hasErrors = true;
1448 }
1449 err = NO_ERROR;
1450 }
1451
1452 if (interpolators != NULL) {
1453 ResourceDirIterator it(interpolators, String8("interpolator"));
1454 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001455 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1456 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001457 if (err != NO_ERROR) {
1458 hasErrors = true;
1459 }
1460 }
1461
1462 if (err < NO_ERROR) {
1463 hasErrors = true;
1464 }
1465 err = NO_ERROR;
1466 }
1467
1468 if (transitions != NULL) {
1469 ResourceDirIterator it(transitions, String8("transition"));
1470 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001471 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1472 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001473 if (err != NO_ERROR) {
1474 hasErrors = true;
1475 }
1476 }
1477
1478 if (err < NO_ERROR) {
1479 hasErrors = true;
1480 }
1481 err = NO_ERROR;
1482 }
1483
Adam Lesinski282e1812014-01-23 18:17:42 -08001484 if (xmls != NULL) {
1485 ResourceDirIterator it(xmls, String8("xml"));
1486 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001487 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1488 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001489 if (err != NO_ERROR) {
1490 hasErrors = true;
1491 }
1492 }
1493
1494 if (err < NO_ERROR) {
1495 hasErrors = true;
1496 }
1497 err = NO_ERROR;
1498 }
1499
1500 if (drawables != NULL) {
Adam Lesinskifab50872014-04-16 14:40:42 -07001501 ResourceDirIterator it(drawables, String8("drawable"));
1502 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001503 err = postProcessImage(bundle, assets, &table, it.getFile());
Adam Lesinskifab50872014-04-16 14:40:42 -07001504 if (err != NO_ERROR) {
1505 hasErrors = true;
1506 }
1507 }
1508
1509 if (err < NO_ERROR) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001510 hasErrors = true;
1511 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001512 err = NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001513 }
1514
1515 if (colors != NULL) {
1516 ResourceDirIterator it(colors, String8("color"));
1517 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001518 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1519 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001520 if (err != NO_ERROR) {
1521 hasErrors = true;
1522 }
1523 }
1524
1525 if (err < NO_ERROR) {
1526 hasErrors = true;
1527 }
1528 err = NO_ERROR;
1529 }
1530
1531 if (menus != NULL) {
1532 ResourceDirIterator it(menus, String8("menu"));
1533 while ((err=it.next()) == NO_ERROR) {
1534 String8 src = it.getFile()->getPrintableSource();
Adam Lesinskie572c012014-09-19 15:10:04 -07001535 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1536 it.getFile(), &table, xmlFlags);
Adam Lesinskifab50872014-04-16 14:40:42 -07001537 if (err == NO_ERROR) {
1538 ResXMLTree block;
1539 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
1540 checkForIds(src, block);
1541 } else {
Adam Lesinski282e1812014-01-23 18:17:42 -08001542 hasErrors = true;
1543 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001544 }
1545
1546 if (err < NO_ERROR) {
1547 hasErrors = true;
1548 }
1549 err = NO_ERROR;
1550 }
1551
Adam Lesinskie572c012014-09-19 15:10:04 -07001552 // Now compile any generated resources.
1553 std::queue<CompileResourceWorkItem>& workQueue = table.getWorkQueue();
1554 while (!workQueue.empty()) {
1555 CompileResourceWorkItem& workItem = workQueue.front();
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07001556 int xmlCompilationFlags = xmlFlags | XML_COMPILE_PARSE_VALUES
1557 | XML_COMPILE_ASSIGN_ATTRIBUTE_IDS;
1558 if (!workItem.needsCompiling) {
1559 xmlCompilationFlags &= ~XML_COMPILE_ASSIGN_ATTRIBUTE_IDS;
1560 xmlCompilationFlags &= ~XML_COMPILE_PARSE_VALUES;
1561 }
1562 err = compileXmlFile(bundle, assets, workItem.resourceName, workItem.xmlRoot,
1563 workItem.file, &table, xmlCompilationFlags);
1564
Adam Lesinskie572c012014-09-19 15:10:04 -07001565 if (err == NO_ERROR) {
1566 assets->addResource(workItem.resPath.getPathLeaf(),
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07001567 workItem.resPath,
1568 workItem.file,
1569 workItem.file->getResourceType());
Adam Lesinskie572c012014-09-19 15:10:04 -07001570 } else {
1571 hasErrors = true;
1572 }
1573 workQueue.pop();
1574 }
1575
Adam Lesinski282e1812014-01-23 18:17:42 -08001576 if (table.validateLocalizations()) {
1577 hasErrors = true;
1578 }
1579
1580 if (hasErrors) {
1581 return UNKNOWN_ERROR;
1582 }
1583
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001584 // If we're not overriding the platform build versions,
1585 // extract them from the platform APK.
1586 if (packageType != ResourceTable::System &&
1587 (bundle->getPlatformBuildVersionCode() == "" ||
1588 bundle->getPlatformBuildVersionName() == "")) {
1589 err = extractPlatformBuildVersion(assets->getAssetManager(), bundle);
1590 if (err != NO_ERROR) {
1591 return UNKNOWN_ERROR;
1592 }
1593 }
1594
Adam Lesinski282e1812014-01-23 18:17:42 -08001595 const sp<AaptFile> manifestFile(androidManifestFile->getFiles().valueAt(0));
1596 String8 manifestPath(manifestFile->getPrintableSource());
1597
1598 // Generate final compiled manifest file.
1599 manifestFile->clearData();
1600 sp<XMLNode> manifestTree = XMLNode::parse(manifestFile);
1601 if (manifestTree == NULL) {
1602 return UNKNOWN_ERROR;
1603 }
1604 err = massageManifest(bundle, manifestTree);
1605 if (err < NO_ERROR) {
1606 return err;
1607 }
Adam Lesinskie572c012014-09-19 15:10:04 -07001608 err = compileXmlFile(bundle, assets, String16(), manifestTree, manifestFile, &table);
Adam Lesinski282e1812014-01-23 18:17:42 -08001609 if (err < NO_ERROR) {
1610 return err;
1611 }
1612
Adam Lesinski82a2dd82014-09-17 18:34:15 -07001613 if (table.modifyForCompat(bundle) != NO_ERROR) {
1614 return UNKNOWN_ERROR;
1615 }
1616
Adam Lesinski282e1812014-01-23 18:17:42 -08001617 //block.restart();
1618 //printXMLBlock(&block);
1619
1620 // --------------------------------------------------------------
1621 // Generate the final resource table.
1622 // Re-flatten because we may have added new resource IDs
1623 // --------------------------------------------------------------
1624
Adam Lesinskide7de472014-11-03 12:03:08 -08001625
Adam Lesinski282e1812014-01-23 18:17:42 -08001626 ResTable finalResTable;
1627 sp<AaptFile> resFile;
1628
1629 if (table.hasResources()) {
1630 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
Adrian Roos58922482015-06-01 17:59:41 -07001631 err = table.addSymbols(symbols, bundle->getSkipSymbolsWithoutDefaultLocalization());
Adam Lesinski282e1812014-01-23 18:17:42 -08001632 if (err < NO_ERROR) {
1633 return err;
1634 }
1635
Adam Lesinskide7de472014-11-03 12:03:08 -08001636 KeyedVector<Symbol, Vector<SymbolDefinition> > densityVaryingResources;
1637 if (builder->getSplits().size() > 1) {
1638 // Only look for density varying resources if we're generating
1639 // splits.
1640 table.getDensityVaryingResources(densityVaryingResources);
1641 }
1642
Adam Lesinskifab50872014-04-16 14:40:42 -07001643 Vector<sp<ApkSplit> >& splits = builder->getSplits();
1644 const size_t numSplits = splits.size();
1645 for (size_t i = 0; i < numSplits; i++) {
1646 sp<ApkSplit>& split = splits.editItemAt(i);
1647 sp<AaptFile> flattenedTable = new AaptFile(String8("resources.arsc"),
1648 AaptGroupEntry(), String8());
Adam Lesinski27f69f42014-08-21 13:19:12 -07001649 err = table.flatten(bundle, split->getResourceFilter(),
1650 flattenedTable, split->isBase());
Adam Lesinskifab50872014-04-16 14:40:42 -07001651 if (err != NO_ERROR) {
1652 fprintf(stderr, "Failed to generate resource table for split '%s'\n",
1653 split->getPrintableName().string());
1654 return err;
1655 }
1656 split->addEntry(String8("resources.arsc"), flattenedTable);
Adam Lesinski282e1812014-01-23 18:17:42 -08001657
Adam Lesinskifab50872014-04-16 14:40:42 -07001658 if (split->isBase()) {
1659 resFile = flattenedTable;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07001660 err = finalResTable.add(flattenedTable->getData(), flattenedTable->getSize());
1661 if (err != NO_ERROR) {
1662 fprintf(stderr, "Generated resource table is corrupt.\n");
1663 return err;
1664 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001665 } else {
Adam Lesinskide7de472014-11-03 12:03:08 -08001666 ResTable resTable;
1667 err = resTable.add(flattenedTable->getData(), flattenedTable->getSize());
1668 if (err != NO_ERROR) {
1669 fprintf(stderr, "Generated resource table for split '%s' is corrupt.\n",
1670 split->getPrintableName().string());
1671 return err;
1672 }
1673
1674 bool hasError = false;
1675 const std::set<ConfigDescription>& splitConfigs = split->getConfigs();
1676 for (std::set<ConfigDescription>::const_iterator iter = splitConfigs.begin();
1677 iter != splitConfigs.end();
1678 ++iter) {
1679 const ConfigDescription& config = *iter;
1680 if (AaptConfig::isDensityOnly(config)) {
1681 // Each density only split must contain all
1682 // density only resources.
1683 Res_value val;
1684 resTable.setParameters(&config);
1685 const size_t densityVaryingResourceCount = densityVaryingResources.size();
1686 for (size_t k = 0; k < densityVaryingResourceCount; k++) {
1687 const Symbol& symbol = densityVaryingResources.keyAt(k);
1688 ssize_t block = resTable.getResource(symbol.id, &val, true);
1689 if (block < 0) {
1690 // Maybe it's in the base?
1691 finalResTable.setParameters(&config);
1692 block = finalResTable.getResource(symbol.id, &val, true);
1693 }
1694
1695 if (block < 0) {
1696 hasError = true;
1697 SourcePos().error("%s has no definition for density split '%s'",
1698 symbol.toString().string(), config.toString().string());
1699
1700 if (bundle->getVerbose()) {
1701 const Vector<SymbolDefinition>& defs = densityVaryingResources[k];
1702 const size_t defCount = std::min(size_t(5), defs.size());
1703 for (size_t d = 0; d < defCount; d++) {
1704 const SymbolDefinition& def = defs[d];
1705 def.source.error("%s has definition for %s",
1706 symbol.toString().string(), def.config.toString().string());
1707 }
1708
1709 if (defCount < defs.size()) {
1710 SourcePos().error("and %d more ...", (int) (defs.size() - defCount));
1711 }
1712 }
1713 }
1714 }
1715 }
1716 }
1717
1718 if (hasError) {
1719 return UNKNOWN_ERROR;
1720 }
1721
1722 // Generate the AndroidManifest for this split.
Adam Lesinskifab50872014-04-16 14:40:42 -07001723 sp<AaptFile> generatedManifest = new AaptFile(String8("AndroidManifest.xml"),
1724 AaptGroupEntry(), String8());
Jeff Sharkey2cfc8482014-07-09 16:10:16 -07001725 err = generateAndroidManifestForSplit(bundle, assets, split,
1726 generatedManifest, &table);
Adam Lesinskifab50872014-04-16 14:40:42 -07001727 if (err != NO_ERROR) {
1728 fprintf(stderr, "Failed to generate AndroidManifest.xml for split '%s'\n",
1729 split->getPrintableName().string());
1730 return err;
1731 }
1732 split->addEntry(String8("AndroidManifest.xml"), generatedManifest);
1733 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001734 }
1735
1736 if (bundle->getPublicOutputFile()) {
1737 FILE* fp = fopen(bundle->getPublicOutputFile(), "w+");
1738 if (fp == NULL) {
1739 fprintf(stderr, "ERROR: Unable to open public definitions output file %s: %s\n",
1740 (const char*)bundle->getPublicOutputFile(), strerror(errno));
1741 return UNKNOWN_ERROR;
1742 }
1743 if (bundle->getVerbose()) {
1744 printf(" Writing public definitions to %s.\n", bundle->getPublicOutputFile());
1745 }
1746 table.writePublicDefinitions(String16(assets->getPackage()), fp);
1747 fclose(fp);
1748 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001749
1750 if (finalResTable.getTableCount() == 0 || resFile == NULL) {
1751 fprintf(stderr, "No resource table was generated.\n");
1752 return UNKNOWN_ERROR;
1753 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001754 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001755
Adam Lesinski282e1812014-01-23 18:17:42 -08001756 // Perform a basic validation of the manifest file. This time we
1757 // parse it with the comments intact, so that we can use them to
1758 // generate java docs... so we are not going to write this one
1759 // back out to the final manifest data.
1760 sp<AaptFile> outManifestFile = new AaptFile(manifestFile->getSourceFile(),
1761 manifestFile->getGroupEntry(),
1762 manifestFile->getResourceType());
Adam Lesinskie572c012014-09-19 15:10:04 -07001763 err = compileXmlFile(bundle, assets, String16(), manifestFile,
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07001764 outManifestFile, &table, XML_COMPILE_STANDARD_RESOURCE & ~XML_COMPILE_STRIP_COMMENTS);
Adam Lesinski282e1812014-01-23 18:17:42 -08001765 if (err < NO_ERROR) {
1766 return err;
1767 }
1768 ResXMLTree block;
1769 block.setTo(outManifestFile->getData(), outManifestFile->getSize(), true);
1770 String16 manifest16("manifest");
1771 String16 permission16("permission");
1772 String16 permission_group16("permission-group");
1773 String16 uses_permission16("uses-permission");
1774 String16 instrumentation16("instrumentation");
1775 String16 application16("application");
1776 String16 provider16("provider");
1777 String16 service16("service");
1778 String16 receiver16("receiver");
1779 String16 activity16("activity");
1780 String16 action16("action");
1781 String16 category16("category");
1782 String16 data16("scheme");
Adam Lesinskid3edfde2014-08-08 17:32:44 -07001783 String16 feature_group16("feature-group");
1784 String16 uses_feature16("uses-feature");
Adam Lesinski282e1812014-01-23 18:17:42 -08001785 const char* packageIdentChars = "abcdefghijklmnopqrstuvwxyz"
1786 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789";
1787 const char* packageIdentCharsWithTheStupid = "abcdefghijklmnopqrstuvwxyz"
1788 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
1789 const char* classIdentChars = "abcdefghijklmnopqrstuvwxyz"
1790 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789$";
1791 const char* processIdentChars = "abcdefghijklmnopqrstuvwxyz"
1792 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:";
1793 const char* authoritiesIdentChars = "abcdefghijklmnopqrstuvwxyz"
1794 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-:;";
1795 const char* typeIdentChars = "abcdefghijklmnopqrstuvwxyz"
1796 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:-/*+";
1797 const char* schemeIdentChars = "abcdefghijklmnopqrstuvwxyz"
1798 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
1799 ResXMLTree::event_code_t code;
1800 sp<AaptSymbols> permissionSymbols;
1801 sp<AaptSymbols> permissionGroupSymbols;
1802 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1803 && code > ResXMLTree::BAD_DOCUMENT) {
1804 if (code == ResXMLTree::START_TAG) {
1805 size_t len;
1806 if (block.getElementNamespace(&len) != NULL) {
1807 continue;
1808 }
1809 if (strcmp16(block.getElementName(&len), manifest16.string()) == 0) {
1810 if (validateAttr(manifestPath, finalResTable, block, NULL, "package",
1811 packageIdentChars, true) != ATTR_OKAY) {
1812 hasErrors = true;
1813 }
1814 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1815 "sharedUserId", packageIdentChars, false) != ATTR_OKAY) {
1816 hasErrors = true;
1817 }
1818 } else if (strcmp16(block.getElementName(&len), permission16.string()) == 0
1819 || strcmp16(block.getElementName(&len), permission_group16.string()) == 0) {
1820 const bool isGroup = strcmp16(block.getElementName(&len),
1821 permission_group16.string()) == 0;
1822 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1823 "name", isGroup ? packageIdentCharsWithTheStupid
1824 : packageIdentChars, true) != ATTR_OKAY) {
1825 hasErrors = true;
1826 }
1827 SourcePos srcPos(manifestPath, block.getLineNumber());
1828 sp<AaptSymbols> syms;
1829 if (!isGroup) {
1830 syms = permissionSymbols;
1831 if (syms == NULL) {
1832 sp<AaptSymbols> symbols =
1833 assets->getSymbolsFor(String8("Manifest"));
1834 syms = permissionSymbols = symbols->addNestedSymbol(
1835 String8("permission"), srcPos);
1836 }
1837 } else {
1838 syms = permissionGroupSymbols;
1839 if (syms == NULL) {
1840 sp<AaptSymbols> symbols =
1841 assets->getSymbolsFor(String8("Manifest"));
1842 syms = permissionGroupSymbols = symbols->addNestedSymbol(
1843 String8("permission_group"), srcPos);
1844 }
1845 }
1846 size_t len;
1847 ssize_t index = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "name");
Dan Albertf348c152014-09-08 18:28:00 -07001848 const char16_t* id = block.getAttributeStringValue(index, &len);
Adam Lesinski282e1812014-01-23 18:17:42 -08001849 if (id == NULL) {
1850 fprintf(stderr, "%s:%d: missing name attribute in element <%s>.\n",
1851 manifestPath.string(), block.getLineNumber(),
1852 String8(block.getElementName(&len)).string());
1853 hasErrors = true;
1854 break;
1855 }
1856 String8 idStr(id);
1857 char* p = idStr.lockBuffer(idStr.size());
1858 char* e = p + idStr.size();
1859 bool begins_with_digit = true; // init to true so an empty string fails
1860 while (e > p) {
1861 e--;
1862 if (*e >= '0' && *e <= '9') {
1863 begins_with_digit = true;
1864 continue;
1865 }
1866 if ((*e >= 'a' && *e <= 'z') ||
1867 (*e >= 'A' && *e <= 'Z') ||
1868 (*e == '_')) {
1869 begins_with_digit = false;
1870 continue;
1871 }
1872 if (isGroup && (*e == '-')) {
1873 *e = '_';
1874 begins_with_digit = false;
1875 continue;
1876 }
1877 e++;
1878 break;
1879 }
1880 idStr.unlockBuffer();
1881 // verify that we stopped because we hit a period or
1882 // the beginning of the string, and that the
1883 // identifier didn't begin with a digit.
1884 if (begins_with_digit || (e != p && *(e-1) != '.')) {
1885 fprintf(stderr,
1886 "%s:%d: Permission name <%s> is not a valid Java symbol\n",
1887 manifestPath.string(), block.getLineNumber(), idStr.string());
1888 hasErrors = true;
1889 }
1890 syms->addStringSymbol(String8(e), idStr, srcPos);
Dan Albertf348c152014-09-08 18:28:00 -07001891 const char16_t* cmt = block.getComment(&len);
Adam Lesinski282e1812014-01-23 18:17:42 -08001892 if (cmt != NULL && *cmt != 0) {
1893 //printf("Comment of %s: %s\n", String8(e).string(),
1894 // String8(cmt).string());
1895 syms->appendComment(String8(e), String16(cmt), srcPos);
Adam Lesinski282e1812014-01-23 18:17:42 -08001896 }
1897 syms->makeSymbolPublic(String8(e), srcPos);
1898 } else if (strcmp16(block.getElementName(&len), uses_permission16.string()) == 0) {
1899 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1900 "name", packageIdentChars, true) != ATTR_OKAY) {
1901 hasErrors = true;
1902 }
1903 } else if (strcmp16(block.getElementName(&len), instrumentation16.string()) == 0) {
1904 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1905 "name", classIdentChars, true) != ATTR_OKAY) {
1906 hasErrors = true;
1907 }
1908 if (validateAttr(manifestPath, finalResTable, block,
1909 RESOURCES_ANDROID_NAMESPACE, "targetPackage",
1910 packageIdentChars, true) != ATTR_OKAY) {
1911 hasErrors = true;
1912 }
1913 } else if (strcmp16(block.getElementName(&len), application16.string()) == 0) {
1914 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1915 "name", classIdentChars, false) != ATTR_OKAY) {
1916 hasErrors = true;
1917 }
1918 if (validateAttr(manifestPath, finalResTable, block,
1919 RESOURCES_ANDROID_NAMESPACE, "permission",
1920 packageIdentChars, false) != ATTR_OKAY) {
1921 hasErrors = true;
1922 }
1923 if (validateAttr(manifestPath, finalResTable, block,
1924 RESOURCES_ANDROID_NAMESPACE, "process",
1925 processIdentChars, false) != ATTR_OKAY) {
1926 hasErrors = true;
1927 }
1928 if (validateAttr(manifestPath, finalResTable, block,
1929 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
1930 processIdentChars, false) != ATTR_OKAY) {
1931 hasErrors = true;
1932 }
1933 } else if (strcmp16(block.getElementName(&len), provider16.string()) == 0) {
1934 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1935 "name", classIdentChars, true) != ATTR_OKAY) {
1936 hasErrors = true;
1937 }
1938 if (validateAttr(manifestPath, finalResTable, block,
1939 RESOURCES_ANDROID_NAMESPACE, "authorities",
1940 authoritiesIdentChars, true) != ATTR_OKAY) {
1941 hasErrors = true;
1942 }
1943 if (validateAttr(manifestPath, finalResTable, block,
1944 RESOURCES_ANDROID_NAMESPACE, "permission",
1945 packageIdentChars, false) != ATTR_OKAY) {
1946 hasErrors = true;
1947 }
1948 if (validateAttr(manifestPath, finalResTable, block,
1949 RESOURCES_ANDROID_NAMESPACE, "process",
1950 processIdentChars, false) != ATTR_OKAY) {
1951 hasErrors = true;
1952 }
1953 } else if (strcmp16(block.getElementName(&len), service16.string()) == 0
1954 || strcmp16(block.getElementName(&len), receiver16.string()) == 0
1955 || strcmp16(block.getElementName(&len), activity16.string()) == 0) {
1956 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1957 "name", classIdentChars, true) != ATTR_OKAY) {
1958 hasErrors = true;
1959 }
1960 if (validateAttr(manifestPath, finalResTable, block,
1961 RESOURCES_ANDROID_NAMESPACE, "permission",
1962 packageIdentChars, false) != ATTR_OKAY) {
1963 hasErrors = true;
1964 }
1965 if (validateAttr(manifestPath, finalResTable, block,
1966 RESOURCES_ANDROID_NAMESPACE, "process",
1967 processIdentChars, false) != ATTR_OKAY) {
1968 hasErrors = true;
1969 }
1970 if (validateAttr(manifestPath, finalResTable, block,
1971 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
1972 processIdentChars, false) != ATTR_OKAY) {
1973 hasErrors = true;
1974 }
1975 } else if (strcmp16(block.getElementName(&len), action16.string()) == 0
1976 || strcmp16(block.getElementName(&len), category16.string()) == 0) {
1977 if (validateAttr(manifestPath, finalResTable, block,
1978 RESOURCES_ANDROID_NAMESPACE, "name",
1979 packageIdentChars, true) != ATTR_OKAY) {
1980 hasErrors = true;
1981 }
1982 } else if (strcmp16(block.getElementName(&len), data16.string()) == 0) {
1983 if (validateAttr(manifestPath, finalResTable, block,
1984 RESOURCES_ANDROID_NAMESPACE, "mimeType",
1985 typeIdentChars, true) != ATTR_OKAY) {
1986 hasErrors = true;
1987 }
1988 if (validateAttr(manifestPath, finalResTable, block,
1989 RESOURCES_ANDROID_NAMESPACE, "scheme",
1990 schemeIdentChars, true) != ATTR_OKAY) {
1991 hasErrors = true;
1992 }
Adam Lesinskid3edfde2014-08-08 17:32:44 -07001993 } else if (strcmp16(block.getElementName(&len), feature_group16.string()) == 0) {
1994 int depth = 1;
1995 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1996 && code > ResXMLTree::BAD_DOCUMENT) {
1997 if (code == ResXMLTree::START_TAG) {
1998 depth++;
1999 if (strcmp16(block.getElementName(&len), uses_feature16.string()) == 0) {
2000 ssize_t idx = block.indexOfAttribute(
2001 RESOURCES_ANDROID_NAMESPACE, "required");
2002 if (idx < 0) {
2003 continue;
2004 }
2005
2006 int32_t data = block.getAttributeData(idx);
2007 if (data == 0) {
2008 fprintf(stderr, "%s:%d: Tag <uses-feature> can not have "
2009 "android:required=\"false\" when inside a "
2010 "<feature-group> tag.\n",
2011 manifestPath.string(), block.getLineNumber());
2012 hasErrors = true;
2013 }
2014 }
2015 } else if (code == ResXMLTree::END_TAG) {
2016 depth--;
2017 if (depth == 0) {
2018 break;
2019 }
2020 }
2021 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002022 }
2023 }
2024 }
2025
Adam Lesinskid3edfde2014-08-08 17:32:44 -07002026 if (hasErrors) {
2027 return UNKNOWN_ERROR;
2028 }
2029
Adam Lesinski282e1812014-01-23 18:17:42 -08002030 if (resFile != NULL) {
2031 // These resources are now considered to be a part of the included
2032 // resources, for others to reference.
2033 err = assets->addIncludedResources(resFile);
2034 if (err < NO_ERROR) {
2035 fprintf(stderr, "ERROR: Unable to parse generated resources, aborting.\n");
2036 return err;
2037 }
2038 }
2039
2040 return err;
2041}
2042
2043static const char* getIndentSpace(int indent)
2044{
2045static const char whitespace[] =
2046" ";
2047
2048 return whitespace + sizeof(whitespace) - 1 - indent*4;
2049}
2050
2051static String8 flattenSymbol(const String8& symbol) {
2052 String8 result(symbol);
2053 ssize_t first;
2054 if ((first = symbol.find(":", 0)) >= 0
2055 || (first = symbol.find(".", 0)) >= 0) {
2056 size_t size = symbol.size();
2057 char* buf = result.lockBuffer(size);
2058 for (size_t i = first; i < size; i++) {
2059 if (buf[i] == ':' || buf[i] == '.') {
2060 buf[i] = '_';
2061 }
2062 }
2063 result.unlockBuffer(size);
2064 }
2065 return result;
2066}
2067
2068static String8 getSymbolPackage(const String8& symbol, const sp<AaptAssets>& assets, bool pub) {
2069 ssize_t colon = symbol.find(":", 0);
2070 if (colon >= 0) {
2071 return String8(symbol.string(), colon);
2072 }
2073 return pub ? assets->getPackage() : assets->getSymbolsPrivatePackage();
2074}
2075
2076static String8 getSymbolName(const String8& symbol) {
2077 ssize_t colon = symbol.find(":", 0);
2078 if (colon >= 0) {
2079 return String8(symbol.string() + colon + 1);
2080 }
2081 return symbol;
2082}
2083
2084static String16 getAttributeComment(const sp<AaptAssets>& assets,
2085 const String8& name,
2086 String16* outTypeComment = NULL)
2087{
2088 sp<AaptSymbols> asym = assets->getSymbolsFor(String8("R"));
2089 if (asym != NULL) {
2090 //printf("Got R symbols!\n");
2091 asym = asym->getNestedSymbols().valueFor(String8("attr"));
2092 if (asym != NULL) {
2093 //printf("Got attrs symbols! comment %s=%s\n",
2094 // name.string(), String8(asym->getComment(name)).string());
2095 if (outTypeComment != NULL) {
2096 *outTypeComment = asym->getTypeComment(name);
2097 }
2098 return asym->getComment(name);
2099 }
2100 }
2101 return String16();
2102}
2103
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002104static status_t writeResourceLoadedCallbackForLayoutClasses(
2105 FILE* fp, const sp<AaptAssets>& assets,
Andreas Gampe87332a72014-10-01 22:03:58 -07002106 const sp<AaptSymbols>& symbols, int indent, bool /* includePrivate */)
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002107{
2108 String16 attr16("attr");
2109 String16 package16(assets->getPackage());
2110
2111 const char* indentStr = getIndentSpace(indent);
2112 bool hasErrors = false;
2113
2114 size_t i;
2115 size_t N = symbols->getNestedSymbols().size();
2116 for (i=0; i<N; i++) {
2117 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2118 String8 realClassName(symbols->getNestedSymbols().keyAt(i));
2119 String8 nclassName(flattenSymbol(realClassName));
2120
2121 fprintf(fp,
2122 "%sfor(int i = 0; i < styleable.%s.length; ++i) {\n"
2123 "%sstyleable.%s[i] = (styleable.%s[i] & 0x00ffffff) | (packageId << 24);\n"
2124 "%s}\n",
2125 indentStr, nclassName.string(),
2126 getIndentSpace(indent+1), nclassName.string(), nclassName.string(),
2127 indentStr);
Adam Lesinski1e4663852014-08-15 14:47:28 -07002128 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002129
Dan Alberted811ee2016-01-15 12:16:06 -08002130 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002131}
2132
2133static status_t writeResourceLoadedCallback(
2134 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2135 const sp<AaptSymbols>& symbols, const String8& className, int indent)
2136{
2137 size_t i;
2138 status_t err = NO_ERROR;
2139
2140 size_t N = symbols->getSymbols().size();
2141 for (i=0; i<N; i++) {
2142 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
Adam Lesinskieed58582015-09-10 18:43:34 -07002143 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002144 continue;
Adam Lesinski1e4663852014-08-15 14:47:28 -07002145 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002146 if (!assets->isJavaSymbol(sym, includePrivate)) {
2147 continue;
Adam Lesinski1e4663852014-08-15 14:47:28 -07002148 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002149 String8 flat_name(flattenSymbol(sym.name));
2150 fprintf(fp,
2151 "%s%s.%s = (%s.%s & 0x00ffffff) | (packageId << 24);\n",
2152 getIndentSpace(indent), className.string(), flat_name.string(),
2153 className.string(), flat_name.string());
Adam Lesinski1e4663852014-08-15 14:47:28 -07002154 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002155
2156 N = symbols->getNestedSymbols().size();
2157 for (i=0; i<N; i++) {
2158 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2159 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2160 if (nclassName == "styleable") {
2161 err = writeResourceLoadedCallbackForLayoutClasses(
2162 fp, assets, nsymbols, indent, includePrivate);
2163 } else {
2164 err = writeResourceLoadedCallback(fp, assets, includePrivate, nsymbols,
2165 nclassName, indent);
Adam Lesinski1e4663852014-08-15 14:47:28 -07002166 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002167 if (err != NO_ERROR) {
2168 return err;
2169 }
Adam Lesinski1e4663852014-08-15 14:47:28 -07002170 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002171
2172 return NO_ERROR;
Adam Lesinski1e4663852014-08-15 14:47:28 -07002173}
2174
Adam Lesinski282e1812014-01-23 18:17:42 -08002175static status_t writeLayoutClasses(
2176 FILE* fp, const sp<AaptAssets>& assets,
Adam Lesinskie8e91922014-08-06 17:41:08 -07002177 const sp<AaptSymbols>& symbols, int indent, bool includePrivate, bool nonConstantId)
Adam Lesinski282e1812014-01-23 18:17:42 -08002178{
2179 const char* indentStr = getIndentSpace(indent);
2180 if (!includePrivate) {
2181 fprintf(fp, "%s/** @doconly */\n", indentStr);
2182 }
2183 fprintf(fp, "%spublic static final class styleable {\n", indentStr);
2184 indent++;
2185
2186 String16 attr16("attr");
2187 String16 package16(assets->getPackage());
2188
2189 indentStr = getIndentSpace(indent);
2190 bool hasErrors = false;
2191
2192 size_t i;
2193 size_t N = symbols->getNestedSymbols().size();
2194 for (i=0; i<N; i++) {
2195 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2196 String8 realClassName(symbols->getNestedSymbols().keyAt(i));
2197 String8 nclassName(flattenSymbol(realClassName));
2198
2199 SortedVector<uint32_t> idents;
2200 Vector<uint32_t> origOrder;
2201 Vector<bool> publicFlags;
2202
2203 size_t a;
2204 size_t NA = nsymbols->getSymbols().size();
2205 for (a=0; a<NA; a++) {
2206 const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a));
2207 int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32
2208 ? sym.int32Val : 0;
2209 bool isPublic = true;
2210 if (code == 0) {
2211 String16 name16(sym.name);
2212 uint32_t typeSpecFlags;
2213 code = assets->getIncludedResources().identifierForName(
2214 name16.string(), name16.size(),
2215 attr16.string(), attr16.size(),
2216 package16.string(), package16.size(), &typeSpecFlags);
2217 if (code == 0) {
2218 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
2219 nclassName.string(), sym.name.string());
2220 hasErrors = true;
2221 }
2222 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
2223 }
2224 idents.add(code);
2225 origOrder.add(code);
2226 publicFlags.add(isPublic);
2227 }
2228
2229 NA = idents.size();
2230
Adam Lesinski282e1812014-01-23 18:17:42 -08002231 String16 comment = symbols->getComment(realClassName);
Jeff Browneb490d62014-06-06 19:43:42 -07002232 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002233 fprintf(fp, "%s/** ", indentStr);
2234 if (comment.size() > 0) {
2235 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002236 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002237 fprintf(fp, "%s\n", cmt.string());
Adam Lesinski282e1812014-01-23 18:17:42 -08002238 } else {
2239 fprintf(fp, "Attributes that can be used with a %s.\n", nclassName.string());
2240 }
2241 bool hasTable = false;
2242 for (a=0; a<NA; a++) {
2243 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2244 if (pos >= 0) {
2245 if (!hasTable) {
2246 hasTable = true;
2247 fprintf(fp,
2248 "%s <p>Includes the following attributes:</p>\n"
2249 "%s <table>\n"
2250 "%s <colgroup align=\"left\" />\n"
2251 "%s <colgroup align=\"left\" />\n"
2252 "%s <tr><th>Attribute</th><th>Description</th></tr>\n",
2253 indentStr,
2254 indentStr,
2255 indentStr,
2256 indentStr,
2257 indentStr);
2258 }
2259 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2260 if (!publicFlags.itemAt(a) && !includePrivate) {
2261 continue;
2262 }
2263 String8 name8(sym.name);
2264 String16 comment(sym.comment);
2265 if (comment.size() <= 0) {
2266 comment = getAttributeComment(assets, name8);
2267 }
Michael Wrightfeaf99f2016-05-06 17:16:06 +01002268 if (comment.contains(u"@removed")) {
2269 continue;
2270 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002271 if (comment.size() > 0) {
2272 const char16_t* p = comment.string();
2273 while (*p != 0 && *p != '.') {
2274 if (*p == '{') {
2275 while (*p != 0 && *p != '}') {
2276 p++;
2277 }
2278 } else {
2279 p++;
2280 }
2281 }
2282 if (*p == '.') {
2283 p++;
2284 }
2285 comment = String16(comment.string(), p-comment.string());
2286 }
2287 fprintf(fp, "%s <tr><td><code>{@link #%s_%s %s:%s}</code></td><td>%s</td></tr>\n",
2288 indentStr, nclassName.string(),
2289 flattenSymbol(name8).string(),
2290 getSymbolPackage(name8, assets, true).string(),
2291 getSymbolName(name8).string(),
2292 String8(comment).string());
2293 }
2294 }
2295 if (hasTable) {
2296 fprintf(fp, "%s </table>\n", indentStr);
2297 }
2298 for (a=0; a<NA; a++) {
2299 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2300 if (pos >= 0) {
2301 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2302 if (!publicFlags.itemAt(a) && !includePrivate) {
2303 continue;
2304 }
2305 fprintf(fp, "%s @see #%s_%s\n",
2306 indentStr, nclassName.string(),
2307 flattenSymbol(sym.name).string());
2308 }
2309 }
2310 fprintf(fp, "%s */\n", getIndentSpace(indent));
2311
Jeff Browneb490d62014-06-06 19:43:42 -07002312 ann.printAnnotations(fp, indentStr);
Adam Lesinski282e1812014-01-23 18:17:42 -08002313
2314 fprintf(fp,
2315 "%spublic static final int[] %s = {\n"
2316 "%s",
2317 indentStr, nclassName.string(),
2318 getIndentSpace(indent+1));
2319
2320 for (a=0; a<NA; a++) {
2321 if (a != 0) {
2322 if ((a&3) == 0) {
2323 fprintf(fp, ",\n%s", getIndentSpace(indent+1));
2324 } else {
2325 fprintf(fp, ", ");
2326 }
2327 }
2328 fprintf(fp, "0x%08x", idents[a]);
2329 }
2330
2331 fprintf(fp, "\n%s};\n", indentStr);
2332
2333 for (a=0; a<NA; a++) {
2334 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2335 if (pos >= 0) {
2336 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2337 if (!publicFlags.itemAt(a) && !includePrivate) {
2338 continue;
2339 }
2340 String8 name8(sym.name);
2341 String16 comment(sym.comment);
2342 String16 typeComment;
2343 if (comment.size() <= 0) {
2344 comment = getAttributeComment(assets, name8, &typeComment);
2345 } else {
2346 getAttributeComment(assets, name8, &typeComment);
2347 }
2348
2349 uint32_t typeSpecFlags = 0;
2350 String16 name16(sym.name);
2351 assets->getIncludedResources().identifierForName(
2352 name16.string(), name16.size(),
2353 attr16.string(), attr16.size(),
2354 package16.string(), package16.size(), &typeSpecFlags);
2355 //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
2356 // String8(attr16).string(), String8(name16).string(), typeSpecFlags);
2357 const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
Jeff Browneb490d62014-06-06 19:43:42 -07002358
2359 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002360 fprintf(fp, "%s/**\n", indentStr);
2361 if (comment.size() > 0) {
2362 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002363 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002364 fprintf(fp, "%s <p>\n%s @attr description\n", indentStr, indentStr);
2365 fprintf(fp, "%s %s\n", indentStr, cmt.string());
Adam Lesinski282e1812014-01-23 18:17:42 -08002366 } else {
2367 fprintf(fp,
2368 "%s <p>This symbol is the offset where the {@link %s.R.attr#%s}\n"
2369 "%s attribute's value can be found in the {@link #%s} array.\n",
2370 indentStr,
2371 getSymbolPackage(name8, assets, pub).string(),
2372 getSymbolName(name8).string(),
2373 indentStr, nclassName.string());
2374 }
2375 if (typeComment.size() > 0) {
2376 String8 cmt(typeComment);
Jeff Browneb490d62014-06-06 19:43:42 -07002377 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002378 fprintf(fp, "\n\n%s %s\n", indentStr, cmt.string());
Adam Lesinski282e1812014-01-23 18:17:42 -08002379 }
2380 if (comment.size() > 0) {
2381 if (pub) {
2382 fprintf(fp,
2383 "%s <p>This corresponds to the global attribute\n"
2384 "%s resource symbol {@link %s.R.attr#%s}.\n",
2385 indentStr, indentStr,
2386 getSymbolPackage(name8, assets, true).string(),
2387 getSymbolName(name8).string());
2388 } else {
2389 fprintf(fp,
2390 "%s <p>This is a private symbol.\n", indentStr);
2391 }
2392 }
2393 fprintf(fp, "%s @attr name %s:%s\n", indentStr,
2394 getSymbolPackage(name8, assets, pub).string(),
2395 getSymbolName(name8).string());
2396 fprintf(fp, "%s*/\n", indentStr);
Jeff Browneb490d62014-06-06 19:43:42 -07002397 ann.printAnnotations(fp, indentStr);
Adam Lesinskie8e91922014-08-06 17:41:08 -07002398
2399 const char * id_format = nonConstantId ?
2400 "%spublic static int %s_%s = %d;\n" :
2401 "%spublic static final int %s_%s = %d;\n";
2402
Adam Lesinski282e1812014-01-23 18:17:42 -08002403 fprintf(fp,
Adam Lesinskie8e91922014-08-06 17:41:08 -07002404 id_format,
Adam Lesinski282e1812014-01-23 18:17:42 -08002405 indentStr, nclassName.string(),
2406 flattenSymbol(name8).string(), (int)pos);
2407 }
2408 }
2409 }
2410
2411 indent--;
2412 fprintf(fp, "%s};\n", getIndentSpace(indent));
Andreas Gampe2412f842014-09-30 20:55:57 -07002413 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08002414}
2415
2416static status_t writeTextLayoutClasses(
2417 FILE* fp, const sp<AaptAssets>& assets,
2418 const sp<AaptSymbols>& symbols, bool includePrivate)
2419{
2420 String16 attr16("attr");
2421 String16 package16(assets->getPackage());
2422
2423 bool hasErrors = false;
2424
2425 size_t i;
2426 size_t N = symbols->getNestedSymbols().size();
2427 for (i=0; i<N; i++) {
2428 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2429 String8 realClassName(symbols->getNestedSymbols().keyAt(i));
2430 String8 nclassName(flattenSymbol(realClassName));
2431
2432 SortedVector<uint32_t> idents;
2433 Vector<uint32_t> origOrder;
2434 Vector<bool> publicFlags;
2435
2436 size_t a;
2437 size_t NA = nsymbols->getSymbols().size();
2438 for (a=0; a<NA; a++) {
2439 const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a));
2440 int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32
2441 ? sym.int32Val : 0;
2442 bool isPublic = true;
2443 if (code == 0) {
2444 String16 name16(sym.name);
2445 uint32_t typeSpecFlags;
2446 code = assets->getIncludedResources().identifierForName(
2447 name16.string(), name16.size(),
2448 attr16.string(), attr16.size(),
2449 package16.string(), package16.size(), &typeSpecFlags);
2450 if (code == 0) {
2451 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
2452 nclassName.string(), sym.name.string());
2453 hasErrors = true;
2454 }
2455 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
2456 }
2457 idents.add(code);
2458 origOrder.add(code);
2459 publicFlags.add(isPublic);
2460 }
2461
2462 NA = idents.size();
2463
2464 fprintf(fp, "int[] styleable %s {", nclassName.string());
2465
2466 for (a=0; a<NA; a++) {
2467 if (a != 0) {
2468 fprintf(fp, ",");
2469 }
2470 fprintf(fp, " 0x%08x", idents[a]);
2471 }
2472
2473 fprintf(fp, " }\n");
2474
2475 for (a=0; a<NA; a++) {
2476 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2477 if (pos >= 0) {
2478 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2479 if (!publicFlags.itemAt(a) && !includePrivate) {
2480 continue;
2481 }
2482 String8 name8(sym.name);
2483 String16 comment(sym.comment);
2484 String16 typeComment;
2485 if (comment.size() <= 0) {
2486 comment = getAttributeComment(assets, name8, &typeComment);
2487 } else {
2488 getAttributeComment(assets, name8, &typeComment);
2489 }
2490
2491 uint32_t typeSpecFlags = 0;
2492 String16 name16(sym.name);
2493 assets->getIncludedResources().identifierForName(
2494 name16.string(), name16.size(),
2495 attr16.string(), attr16.size(),
2496 package16.string(), package16.size(), &typeSpecFlags);
2497 //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
2498 // String8(attr16).string(), String8(name16).string(), typeSpecFlags);
Andreas Gampe2412f842014-09-30 20:55:57 -07002499 //const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08002500
2501 fprintf(fp,
2502 "int styleable %s_%s %d\n",
2503 nclassName.string(),
2504 flattenSymbol(name8).string(), (int)pos);
2505 }
2506 }
2507 }
2508
Andreas Gampe2412f842014-09-30 20:55:57 -07002509 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08002510}
2511
2512static status_t writeSymbolClass(
2513 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2514 const sp<AaptSymbols>& symbols, const String8& className, int indent,
Adam Lesinski1e4663852014-08-15 14:47:28 -07002515 bool nonConstantId, bool emitCallback)
Adam Lesinski282e1812014-01-23 18:17:42 -08002516{
2517 fprintf(fp, "%spublic %sfinal class %s {\n",
2518 getIndentSpace(indent),
2519 indent != 0 ? "static " : "", className.string());
2520 indent++;
2521
2522 size_t i;
2523 status_t err = NO_ERROR;
2524
2525 const char * id_format = nonConstantId ?
2526 "%spublic static int %s=0x%08x;\n" :
2527 "%spublic static final int %s=0x%08x;\n";
2528
2529 size_t N = symbols->getSymbols().size();
2530 for (i=0; i<N; i++) {
2531 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2532 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
2533 continue;
2534 }
2535 if (!assets->isJavaSymbol(sym, includePrivate)) {
2536 continue;
2537 }
2538 String8 name8(sym.name);
2539 String16 comment(sym.comment);
2540 bool haveComment = false;
Jeff Browneb490d62014-06-06 19:43:42 -07002541 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002542 if (comment.size() > 0) {
2543 haveComment = true;
2544 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002545 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002546 fprintf(fp,
2547 "%s/** %s\n",
2548 getIndentSpace(indent), cmt.string());
Adam Lesinski282e1812014-01-23 18:17:42 -08002549 }
2550 String16 typeComment(sym.typeComment);
2551 if (typeComment.size() > 0) {
2552 String8 cmt(typeComment);
Jeff Browneb490d62014-06-06 19:43:42 -07002553 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002554 if (!haveComment) {
2555 haveComment = true;
2556 fprintf(fp,
2557 "%s/** %s\n", getIndentSpace(indent), cmt.string());
2558 } else {
2559 fprintf(fp,
2560 "%s %s\n", getIndentSpace(indent), cmt.string());
2561 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002562 }
2563 if (haveComment) {
2564 fprintf(fp,"%s */\n", getIndentSpace(indent));
2565 }
Jeff Browneb490d62014-06-06 19:43:42 -07002566 ann.printAnnotations(fp, getIndentSpace(indent));
Adam Lesinski282e1812014-01-23 18:17:42 -08002567 fprintf(fp, id_format,
2568 getIndentSpace(indent),
2569 flattenSymbol(name8).string(), (int)sym.int32Val);
2570 }
2571
2572 for (i=0; i<N; i++) {
2573 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2574 if (sym.typeCode != AaptSymbolEntry::TYPE_STRING) {
2575 continue;
2576 }
2577 if (!assets->isJavaSymbol(sym, includePrivate)) {
2578 continue;
2579 }
2580 String8 name8(sym.name);
2581 String16 comment(sym.comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002582 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002583 if (comment.size() > 0) {
2584 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002585 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002586 fprintf(fp,
2587 "%s/** %s\n"
2588 "%s */\n",
2589 getIndentSpace(indent), cmt.string(),
2590 getIndentSpace(indent));
Adam Lesinski282e1812014-01-23 18:17:42 -08002591 }
Jeff Browneb490d62014-06-06 19:43:42 -07002592 ann.printAnnotations(fp, getIndentSpace(indent));
Adam Lesinski282e1812014-01-23 18:17:42 -08002593 fprintf(fp, "%spublic static final String %s=\"%s\";\n",
2594 getIndentSpace(indent),
2595 flattenSymbol(name8).string(), sym.stringVal.string());
2596 }
2597
2598 sp<AaptSymbols> styleableSymbols;
2599
2600 N = symbols->getNestedSymbols().size();
2601 for (i=0; i<N; i++) {
2602 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2603 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2604 if (nclassName == "styleable") {
2605 styleableSymbols = nsymbols;
2606 } else {
Adam Lesinski1e4663852014-08-15 14:47:28 -07002607 err = writeSymbolClass(fp, assets, includePrivate, nsymbols, nclassName,
2608 indent, nonConstantId, false);
Adam Lesinski282e1812014-01-23 18:17:42 -08002609 }
2610 if (err != NO_ERROR) {
2611 return err;
2612 }
2613 }
2614
2615 if (styleableSymbols != NULL) {
Adam Lesinskie8e91922014-08-06 17:41:08 -07002616 err = writeLayoutClasses(fp, assets, styleableSymbols, indent, includePrivate, nonConstantId);
Adam Lesinski282e1812014-01-23 18:17:42 -08002617 if (err != NO_ERROR) {
2618 return err;
2619 }
2620 }
2621
Adam Lesinski1e4663852014-08-15 14:47:28 -07002622 if (emitCallback) {
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002623 fprintf(fp, "%spublic static void onResourcesLoaded(int packageId) {\n",
2624 getIndentSpace(indent));
2625 writeResourceLoadedCallback(fp, assets, includePrivate, symbols, className, indent + 1);
2626 fprintf(fp, "%s}\n", getIndentSpace(indent));
Adam Lesinski1e4663852014-08-15 14:47:28 -07002627 }
2628
Adam Lesinski282e1812014-01-23 18:17:42 -08002629 indent--;
2630 fprintf(fp, "%s}\n", getIndentSpace(indent));
2631 return NO_ERROR;
2632}
2633
2634static status_t writeTextSymbolClass(
2635 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2636 const sp<AaptSymbols>& symbols, const String8& className)
2637{
2638 size_t i;
2639 status_t err = NO_ERROR;
2640
2641 size_t N = symbols->getSymbols().size();
2642 for (i=0; i<N; i++) {
2643 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2644 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
2645 continue;
2646 }
2647
2648 if (!assets->isJavaSymbol(sym, includePrivate)) {
2649 continue;
2650 }
2651
2652 String8 name8(sym.name);
2653 fprintf(fp, "int %s %s 0x%08x\n",
2654 className.string(),
2655 flattenSymbol(name8).string(), (int)sym.int32Val);
2656 }
2657
2658 N = symbols->getNestedSymbols().size();
2659 for (i=0; i<N; i++) {
2660 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2661 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2662 if (nclassName == "styleable") {
2663 err = writeTextLayoutClasses(fp, assets, nsymbols, includePrivate);
2664 } else {
2665 err = writeTextSymbolClass(fp, assets, includePrivate, nsymbols, nclassName);
2666 }
2667 if (err != NO_ERROR) {
2668 return err;
2669 }
2670 }
2671
2672 return NO_ERROR;
2673}
2674
2675status_t writeResourceSymbols(Bundle* bundle, const sp<AaptAssets>& assets,
Adam Lesinski1e4663852014-08-15 14:47:28 -07002676 const String8& package, bool includePrivate, bool emitCallback)
Adam Lesinski282e1812014-01-23 18:17:42 -08002677{
2678 if (!bundle->getRClassDir()) {
2679 return NO_ERROR;
2680 }
2681
2682 const char* textSymbolsDest = bundle->getOutputTextSymbols();
2683
2684 String8 R("R");
2685 const size_t N = assets->getSymbols().size();
2686 for (size_t i=0; i<N; i++) {
2687 sp<AaptSymbols> symbols = assets->getSymbols().valueAt(i);
2688 String8 className(assets->getSymbols().keyAt(i));
2689 String8 dest(bundle->getRClassDir());
2690
2691 if (bundle->getMakePackageDirs()) {
Chih-Hung Hsieh8bd37ba2016-08-10 14:15:30 -07002692 const String8& pkg(package);
Adam Lesinski282e1812014-01-23 18:17:42 -08002693 const char* last = pkg.string();
2694 const char* s = last-1;
2695 do {
2696 s++;
2697 if (s > last && (*s == '.' || *s == 0)) {
2698 String8 part(last, s-last);
2699 dest.appendPath(part);
Elliott Hughese17788c2015-08-17 12:41:46 -07002700#ifdef _WIN32
Adam Lesinski282e1812014-01-23 18:17:42 -08002701 _mkdir(dest.string());
2702#else
2703 mkdir(dest.string(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP);
2704#endif
2705 last = s+1;
2706 }
2707 } while (*s);
2708 }
2709 dest.appendPath(className);
2710 dest.append(".java");
2711 FILE* fp = fopen(dest.string(), "w+");
2712 if (fp == NULL) {
2713 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
2714 dest.string(), strerror(errno));
2715 return UNKNOWN_ERROR;
2716 }
2717 if (bundle->getVerbose()) {
2718 printf(" Writing symbols for class %s.\n", className.string());
2719 }
2720
2721 fprintf(fp,
2722 "/* AUTO-GENERATED FILE. DO NOT MODIFY.\n"
2723 " *\n"
2724 " * This class was automatically generated by the\n"
2725 " * aapt tool from the resource data it found. It\n"
2726 " * should not be modified by hand.\n"
2727 " */\n"
2728 "\n"
2729 "package %s;\n\n", package.string());
2730
2731 status_t err = writeSymbolClass(fp, assets, includePrivate, symbols,
Adam Lesinski1e4663852014-08-15 14:47:28 -07002732 className, 0, bundle->getNonConstantId(), emitCallback);
Elliott Hughesb30296b2013-10-29 15:25:52 -07002733 fclose(fp);
Adam Lesinski282e1812014-01-23 18:17:42 -08002734 if (err != NO_ERROR) {
2735 return err;
2736 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002737
2738 if (textSymbolsDest != NULL && R == className) {
2739 String8 textDest(textSymbolsDest);
2740 textDest.appendPath(className);
2741 textDest.append(".txt");
2742
2743 FILE* fp = fopen(textDest.string(), "w+");
2744 if (fp == NULL) {
2745 fprintf(stderr, "ERROR: Unable to open text symbol file %s: %s\n",
2746 textDest.string(), strerror(errno));
2747 return UNKNOWN_ERROR;
2748 }
2749 if (bundle->getVerbose()) {
2750 printf(" Writing text symbols for class %s.\n", className.string());
2751 }
2752
2753 status_t err = writeTextSymbolClass(fp, assets, includePrivate, symbols,
2754 className);
Elliott Hughesb30296b2013-10-29 15:25:52 -07002755 fclose(fp);
Adam Lesinski282e1812014-01-23 18:17:42 -08002756 if (err != NO_ERROR) {
2757 return err;
2758 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002759 }
2760
2761 // If we were asked to generate a dependency file, we'll go ahead and add this R.java
2762 // as a target in the dependency file right next to it.
2763 if (bundle->getGenDependencies() && R == className) {
2764 // Add this R.java to the dependency file
2765 String8 dependencyFile(bundle->getRClassDir());
2766 dependencyFile.appendPath("R.java.d");
2767
2768 FILE *fp = fopen(dependencyFile.string(), "a");
2769 fprintf(fp,"%s \\\n", dest.string());
2770 fclose(fp);
2771 }
2772 }
2773
2774 return NO_ERROR;
2775}
2776
2777
2778class ProguardKeepSet
2779{
2780public:
2781 // { rule --> { file locations } }
2782 KeyedVector<String8, SortedVector<String8> > rules;
2783
2784 void add(const String8& rule, const String8& where);
2785};
2786
2787void ProguardKeepSet::add(const String8& rule, const String8& where)
2788{
2789 ssize_t index = rules.indexOfKey(rule);
2790 if (index < 0) {
2791 index = rules.add(rule, SortedVector<String8>());
2792 }
2793 rules.editValueAt(index).add(where);
2794}
2795
2796void
2797addProguardKeepRule(ProguardKeepSet* keep, const String8& inClassName,
2798 const char* pkg, const String8& srcName, int line)
2799{
2800 String8 className(inClassName);
2801 if (pkg != NULL) {
2802 // asdf --> package.asdf
2803 // .asdf .a.b --> package.asdf package.a.b
2804 // asdf.adsf --> asdf.asdf
2805 const char* p = className.string();
2806 const char* q = strchr(p, '.');
2807 if (p == q) {
2808 className = pkg;
2809 className.append(inClassName);
2810 } else if (q == NULL) {
2811 className = pkg;
2812 className.append(".");
2813 className.append(inClassName);
2814 }
2815 }
2816
2817 String8 rule("-keep class ");
2818 rule += className;
2819 rule += " { <init>(...); }";
2820
2821 String8 location("view ");
2822 location += srcName;
2823 char lineno[20];
2824 sprintf(lineno, ":%d", line);
2825 location += lineno;
2826
2827 keep->add(rule, location);
2828}
2829
2830void
2831addProguardKeepMethodRule(ProguardKeepSet* keep, const String8& memberName,
Andreas Gampe2412f842014-09-30 20:55:57 -07002832 const char* /* pkg */, const String8& srcName, int line)
Adam Lesinski282e1812014-01-23 18:17:42 -08002833{
2834 String8 rule("-keepclassmembers class * { *** ");
2835 rule += memberName;
2836 rule += "(...); }";
2837
2838 String8 location("onClick ");
2839 location += srcName;
2840 char lineno[20];
2841 sprintf(lineno, ":%d", line);
2842 location += lineno;
2843
2844 keep->add(rule, location);
2845}
2846
2847status_t
Rohit Agrawal682583c2016-04-21 16:29:58 -07002848writeProguardForAndroidManifest(ProguardKeepSet* keep, const sp<AaptAssets>& assets, bool mainDex)
Adam Lesinski282e1812014-01-23 18:17:42 -08002849{
2850 status_t err;
2851 ResXMLTree tree;
2852 size_t len;
2853 ResXMLTree::event_code_t code;
2854 int depth = 0;
2855 bool inApplication = false;
2856 String8 error;
2857 sp<AaptGroup> assGroup;
2858 sp<AaptFile> assFile;
2859 String8 pkg;
Rohit Agrawal682583c2016-04-21 16:29:58 -07002860 String8 defaultProcess;
Adam Lesinski282e1812014-01-23 18:17:42 -08002861
2862 // First, look for a package file to parse. This is required to
2863 // be able to generate the resource information.
2864 assGroup = assets->getFiles().valueFor(String8("AndroidManifest.xml"));
2865 if (assGroup == NULL) {
2866 fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n");
2867 return -1;
2868 }
2869
2870 if (assGroup->getFiles().size() != 1) {
2871 fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
2872 assGroup->getFiles().valueAt(0)->getPrintableSource().string());
2873 }
2874
2875 assFile = assGroup->getFiles().valueAt(0);
2876
2877 err = parseXMLResource(assFile, &tree);
2878 if (err != NO_ERROR) {
2879 return err;
2880 }
2881
2882 tree.restart();
2883
2884 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
2885 if (code == ResXMLTree::END_TAG) {
2886 if (/* name == "Application" && */ depth == 2) {
2887 inApplication = false;
2888 }
2889 depth--;
2890 continue;
2891 }
2892 if (code != ResXMLTree::START_TAG) {
2893 continue;
2894 }
2895 depth++;
2896 String8 tag(tree.getElementName(&len));
2897 // printf("Depth %d tag %s\n", depth, tag.string());
2898 bool keepTag = false;
2899 if (depth == 1) {
2900 if (tag != "manifest") {
2901 fprintf(stderr, "ERROR: manifest does not start with <manifest> tag\n");
2902 return -1;
2903 }
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07002904 pkg = AaptXml::getAttribute(tree, NULL, "package");
Adam Lesinski282e1812014-01-23 18:17:42 -08002905 } else if (depth == 2) {
2906 if (tag == "application") {
2907 inApplication = true;
2908 keepTag = true;
2909
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07002910 String8 agent = AaptXml::getAttribute(tree,
2911 "http://schemas.android.com/apk/res/android",
Adam Lesinski282e1812014-01-23 18:17:42 -08002912 "backupAgent", &error);
2913 if (agent.length() > 0) {
2914 addProguardKeepRule(keep, agent, pkg.string(),
2915 assFile->getPrintableSource(), tree.getLineNumber());
2916 }
Rohit Agrawal682583c2016-04-21 16:29:58 -07002917
2918 if (mainDex) {
2919 defaultProcess = AaptXml::getAttribute(tree,
2920 "http://schemas.android.com/apk/res/android", "process", &error);
2921 if (error != "") {
2922 fprintf(stderr, "ERROR: %s\n", error.string());
2923 return -1;
2924 }
2925 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002926 } else if (tag == "instrumentation") {
2927 keepTag = true;
2928 }
2929 }
2930 if (!keepTag && inApplication && depth == 3) {
2931 if (tag == "activity" || tag == "service" || tag == "receiver" || tag == "provider") {
2932 keepTag = true;
2933 }
2934 }
2935 if (keepTag) {
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07002936 String8 name = AaptXml::getAttribute(tree,
2937 "http://schemas.android.com/apk/res/android", "name", &error);
Adam Lesinski282e1812014-01-23 18:17:42 -08002938 if (error != "") {
2939 fprintf(stderr, "ERROR: %s\n", error.string());
2940 return -1;
2941 }
Rohit Agrawal682583c2016-04-21 16:29:58 -07002942
2943 keepTag = name.length() > 0;
2944
2945 if (keepTag && mainDex) {
2946 String8 componentProcess = AaptXml::getAttribute(tree,
2947 "http://schemas.android.com/apk/res/android", "process", &error);
2948 if (error != "") {
2949 fprintf(stderr, "ERROR: %s\n", error.string());
2950 return -1;
2951 }
2952
2953 const String8& process =
2954 componentProcess.length() > 0 ? componentProcess : defaultProcess;
2955 keepTag = process.length() > 0 && process.find(":") != 0;
2956 }
2957
2958 if (keepTag) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002959 addProguardKeepRule(keep, name, pkg.string(),
2960 assFile->getPrintableSource(), tree.getLineNumber());
2961 }
2962 }
2963 }
2964
2965 return NO_ERROR;
2966}
2967
2968struct NamespaceAttributePair {
2969 const char* ns;
2970 const char* attr;
2971
2972 NamespaceAttributePair(const char* n, const char* a) : ns(n), attr(a) {}
2973 NamespaceAttributePair() : ns(NULL), attr(NULL) {}
2974};
2975
2976status_t
2977writeProguardForXml(ProguardKeepSet* keep, const sp<AaptFile>& layoutFile,
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07002978 const Vector<String8>& startTags, const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs)
Adam Lesinski282e1812014-01-23 18:17:42 -08002979{
2980 status_t err;
2981 ResXMLTree tree;
2982 size_t len;
2983 ResXMLTree::event_code_t code;
2984
2985 err = parseXMLResource(layoutFile, &tree);
2986 if (err != NO_ERROR) {
2987 return err;
2988 }
2989
2990 tree.restart();
2991
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07002992 if (!startTags.isEmpty()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002993 bool haveStart = false;
2994 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
2995 if (code != ResXMLTree::START_TAG) {
2996 continue;
2997 }
2998 String8 tag(tree.getElementName(&len));
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07002999 const size_t numStartTags = startTags.size();
3000 for (size_t i = 0; i < numStartTags; i++) {
3001 if (tag == startTags[i]) {
3002 haveStart = true;
3003 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003004 }
3005 break;
3006 }
3007 if (!haveStart) {
3008 return NO_ERROR;
3009 }
3010 }
3011
3012 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
3013 if (code != ResXMLTree::START_TAG) {
3014 continue;
3015 }
3016 String8 tag(tree.getElementName(&len));
3017
3018 // If there is no '.', we'll assume that it's one of the built in names.
3019 if (strchr(tag.string(), '.')) {
3020 addProguardKeepRule(keep, tag, NULL,
3021 layoutFile->getPrintableSource(), tree.getLineNumber());
3022 } else if (tagAttrPairs != NULL) {
3023 ssize_t tagIndex = tagAttrPairs->indexOfKey(tag);
3024 if (tagIndex >= 0) {
3025 const Vector<NamespaceAttributePair>& nsAttrVector = tagAttrPairs->valueAt(tagIndex);
3026 for (size_t i = 0; i < nsAttrVector.size(); i++) {
3027 const NamespaceAttributePair& nsAttr = nsAttrVector[i];
3028
3029 ssize_t attrIndex = tree.indexOfAttribute(nsAttr.ns, nsAttr.attr);
3030 if (attrIndex < 0) {
3031 // fprintf(stderr, "%s:%d: <%s> does not have attribute %s:%s.\n",
3032 // layoutFile->getPrintableSource().string(), tree.getLineNumber(),
3033 // tag.string(), nsAttr.ns, nsAttr.attr);
3034 } else {
3035 size_t len;
3036 addProguardKeepRule(keep,
3037 String8(tree.getAttributeStringValue(attrIndex, &len)), NULL,
3038 layoutFile->getPrintableSource(), tree.getLineNumber());
3039 }
3040 }
3041 }
3042 }
3043 ssize_t attrIndex = tree.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "onClick");
3044 if (attrIndex >= 0) {
3045 size_t len;
3046 addProguardKeepMethodRule(keep,
3047 String8(tree.getAttributeStringValue(attrIndex, &len)), NULL,
3048 layoutFile->getPrintableSource(), tree.getLineNumber());
3049 }
3050 }
3051
3052 return NO_ERROR;
3053}
3054
3055static void addTagAttrPair(KeyedVector<String8, Vector<NamespaceAttributePair> >* dest,
3056 const char* tag, const char* ns, const char* attr) {
3057 String8 tagStr(tag);
3058 ssize_t index = dest->indexOfKey(tagStr);
3059
3060 if (index < 0) {
3061 Vector<NamespaceAttributePair> vector;
3062 vector.add(NamespaceAttributePair(ns, attr));
3063 dest->add(tagStr, vector);
3064 } else {
3065 dest->editValueAt(index).add(NamespaceAttributePair(ns, attr));
3066 }
3067}
3068
3069status_t
3070writeProguardForLayouts(ProguardKeepSet* keep, const sp<AaptAssets>& assets)
3071{
3072 status_t err;
Adam Lesinski62c5df52014-12-02 16:19:05 -08003073 const char* kClass = "class";
3074 const char* kFragment = "fragment";
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003075 const String8 kTransition("transition");
3076 const String8 kTransitionPrefix("transition-");
Adam Lesinski282e1812014-01-23 18:17:42 -08003077
3078 // tag:attribute pairs that should be checked in layout files.
3079 KeyedVector<String8, Vector<NamespaceAttributePair> > kLayoutTagAttrPairs;
Adam Lesinski62c5df52014-12-02 16:19:05 -08003080 addTagAttrPair(&kLayoutTagAttrPairs, "view", NULL, kClass);
3081 addTagAttrPair(&kLayoutTagAttrPairs, kFragment, NULL, kClass);
3082 addTagAttrPair(&kLayoutTagAttrPairs, kFragment, RESOURCES_ANDROID_NAMESPACE, "name");
Adam Lesinski282e1812014-01-23 18:17:42 -08003083
3084 // tag:attribute pairs that should be checked in xml files.
3085 KeyedVector<String8, Vector<NamespaceAttributePair> > kXmlTagAttrPairs;
Adam Lesinski62c5df52014-12-02 16:19:05 -08003086 addTagAttrPair(&kXmlTagAttrPairs, "PreferenceScreen", RESOURCES_ANDROID_NAMESPACE, kFragment);
3087 addTagAttrPair(&kXmlTagAttrPairs, "header", RESOURCES_ANDROID_NAMESPACE, kFragment);
Adam Lesinski282e1812014-01-23 18:17:42 -08003088
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003089 // tag:attribute pairs that should be checked in transition files.
3090 KeyedVector<String8, Vector<NamespaceAttributePair> > kTransitionTagAttrPairs;
Adam Lesinski62c5df52014-12-02 16:19:05 -08003091 addTagAttrPair(&kTransitionTagAttrPairs, kTransition.string(), NULL, kClass);
3092 addTagAttrPair(&kTransitionTagAttrPairs, "pathMotion", NULL, kClass);
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003093
Adam Lesinski282e1812014-01-23 18:17:42 -08003094 const Vector<sp<AaptDir> >& dirs = assets->resDirs();
3095 const size_t K = dirs.size();
3096 for (size_t k=0; k<K; k++) {
3097 const sp<AaptDir>& d = dirs.itemAt(k);
3098 const String8& dirName = d->getLeaf();
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003099 Vector<String8> startTags;
Adam Lesinski282e1812014-01-23 18:17:42 -08003100 const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs = NULL;
3101 if ((dirName == String8("layout")) || (strncmp(dirName.string(), "layout-", 7) == 0)) {
3102 tagAttrPairs = &kLayoutTagAttrPairs;
3103 } else if ((dirName == String8("xml")) || (strncmp(dirName.string(), "xml-", 4) == 0)) {
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003104 startTags.add(String8("PreferenceScreen"));
3105 startTags.add(String8("preference-headers"));
Adam Lesinski282e1812014-01-23 18:17:42 -08003106 tagAttrPairs = &kXmlTagAttrPairs;
3107 } else if ((dirName == String8("menu")) || (strncmp(dirName.string(), "menu-", 5) == 0)) {
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003108 startTags.add(String8("menu"));
Adam Lesinski282e1812014-01-23 18:17:42 -08003109 tagAttrPairs = NULL;
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003110 } else if (dirName == kTransition || (strncmp(dirName.string(), kTransitionPrefix.string(),
3111 kTransitionPrefix.size()) == 0)) {
3112 tagAttrPairs = &kTransitionTagAttrPairs;
Adam Lesinski282e1812014-01-23 18:17:42 -08003113 } else {
3114 continue;
3115 }
3116
3117 const KeyedVector<String8,sp<AaptGroup> > groups = d->getFiles();
3118 const size_t N = groups.size();
3119 for (size_t i=0; i<N; i++) {
3120 const sp<AaptGroup>& group = groups.valueAt(i);
3121 const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files = group->getFiles();
3122 const size_t M = files.size();
3123 for (size_t j=0; j<M; j++) {
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003124 err = writeProguardForXml(keep, files.valueAt(j), startTags, tagAttrPairs);
Adam Lesinski282e1812014-01-23 18:17:42 -08003125 if (err < 0) {
3126 return err;
3127 }
3128 }
3129 }
3130 }
3131 // Handle the overlays
3132 sp<AaptAssets> overlay = assets->getOverlay();
3133 if (overlay.get()) {
3134 return writeProguardForLayouts(keep, overlay);
3135 }
3136
3137 return NO_ERROR;
3138}
3139
3140status_t
Rohit Agrawal682583c2016-04-21 16:29:58 -07003141writeProguardSpec(const char* filename, const ProguardKeepSet& keep, status_t err)
Adam Lesinski282e1812014-01-23 18:17:42 -08003142{
Rohit Agrawal682583c2016-04-21 16:29:58 -07003143 FILE* fp = fopen(filename, "w+");
Adam Lesinski282e1812014-01-23 18:17:42 -08003144 if (fp == NULL) {
3145 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
Rohit Agrawal682583c2016-04-21 16:29:58 -07003146 filename, strerror(errno));
Adam Lesinski282e1812014-01-23 18:17:42 -08003147 return UNKNOWN_ERROR;
3148 }
3149
3150 const KeyedVector<String8, SortedVector<String8> >& rules = keep.rules;
3151 const size_t N = rules.size();
3152 for (size_t i=0; i<N; i++) {
3153 const SortedVector<String8>& locations = rules.valueAt(i);
3154 const size_t M = locations.size();
3155 for (size_t j=0; j<M; j++) {
3156 fprintf(fp, "# %s\n", locations.itemAt(j).string());
3157 }
3158 fprintf(fp, "%s\n\n", rules.keyAt(i).string());
3159 }
3160 fclose(fp);
3161
3162 return err;
3163}
3164
Rohit Agrawal682583c2016-04-21 16:29:58 -07003165status_t
3166writeProguardFile(Bundle* bundle, const sp<AaptAssets>& assets)
3167{
3168 status_t err = -1;
3169
3170 if (!bundle->getProguardFile()) {
3171 return NO_ERROR;
3172 }
3173
3174 ProguardKeepSet keep;
3175
3176 err = writeProguardForAndroidManifest(&keep, assets, false);
3177 if (err < 0) {
3178 return err;
3179 }
3180
3181 err = writeProguardForLayouts(&keep, assets);
3182 if (err < 0) {
3183 return err;
3184 }
3185
3186 return writeProguardSpec(bundle->getProguardFile(), keep, err);
3187}
3188
3189status_t
3190writeMainDexProguardFile(Bundle* bundle, const sp<AaptAssets>& assets)
3191{
3192 status_t err = -1;
3193
3194 if (!bundle->getMainDexProguardFile()) {
3195 return NO_ERROR;
3196 }
3197
3198 ProguardKeepSet keep;
3199
3200 err = writeProguardForAndroidManifest(&keep, assets, true);
3201 if (err < 0) {
3202 return err;
3203 }
3204
3205 return writeProguardSpec(bundle->getMainDexProguardFile(), keep, err);
3206}
3207
Adam Lesinski282e1812014-01-23 18:17:42 -08003208// Loops through the string paths and writes them to the file pointer
3209// Each file path is written on its own line with a terminating backslash.
3210status_t writePathsToFile(const sp<FilePathStore>& files, FILE* fp)
3211{
3212 status_t deps = -1;
3213 for (size_t file_i = 0; file_i < files->size(); ++file_i) {
3214 // Add the full file path to the dependency file
3215 fprintf(fp, "%s \\\n", files->itemAt(file_i).string());
3216 deps++;
3217 }
3218 return deps;
3219}
3220
3221status_t
Andreas Gampe2412f842014-09-30 20:55:57 -07003222writeDependencyPreReqs(Bundle* /* bundle */, const sp<AaptAssets>& assets, FILE* fp, bool includeRaw)
Adam Lesinski282e1812014-01-23 18:17:42 -08003223{
3224 status_t deps = -1;
3225 deps += writePathsToFile(assets->getFullResPaths(), fp);
3226 if (includeRaw) {
3227 deps += writePathsToFile(assets->getFullAssetPaths(), fp);
3228 }
3229 return deps;
3230}