blob: cf5badc821179cc5293c5ce01d5965b286b06d6e [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"
Adam Lesinski83b4f7d2017-01-20 13:19:27 -0800214 || type == "transition" || type == "font"
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 Hsieh9b8528f2016-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 Hsieh9b8528f2016-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 Hsieh9b8528f2016-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 Hsieh9b8528f2016-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 Hsieh9b8528f2016-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;
Adam Lesinski9bbe7872017-01-24 13:52:04 -08001226 sp<ResourceTypeSet> fonts;
Adam Lesinski282e1812014-01-23 18:17:42 -08001227
1228 ASSIGN_IT(drawable);
1229 ASSIGN_IT(layout);
1230 ASSIGN_IT(anim);
1231 ASSIGN_IT(animator);
1232 ASSIGN_IT(interpolator);
1233 ASSIGN_IT(transition);
Adam Lesinski282e1812014-01-23 18:17:42 -08001234 ASSIGN_IT(xml);
1235 ASSIGN_IT(raw);
1236 ASSIGN_IT(color);
1237 ASSIGN_IT(menu);
1238 ASSIGN_IT(mipmap);
Adam Lesinski9bbe7872017-01-24 13:52:04 -08001239 ASSIGN_IT(font);
Adam Lesinski282e1812014-01-23 18:17:42 -08001240
1241 assets->setResources(resources);
1242 // now go through any resource overlays and collect their files
1243 sp<AaptAssets> current = assets->getOverlay();
1244 while(current.get()) {
1245 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
1246 new KeyedVector<String8, sp<ResourceTypeSet> >;
1247 current->setResources(resources);
1248 collect_files(current, resources);
1249 current = current->getOverlay();
1250 }
1251 // apply the overlay files to the base set
1252 if (!applyFileOverlay(bundle, assets, &drawables, "drawable") ||
1253 !applyFileOverlay(bundle, assets, &layouts, "layout") ||
1254 !applyFileOverlay(bundle, assets, &anims, "anim") ||
1255 !applyFileOverlay(bundle, assets, &animators, "animator") ||
1256 !applyFileOverlay(bundle, assets, &interpolators, "interpolator") ||
1257 !applyFileOverlay(bundle, assets, &transitions, "transition") ||
Adam Lesinski282e1812014-01-23 18:17:42 -08001258 !applyFileOverlay(bundle, assets, &xmls, "xml") ||
1259 !applyFileOverlay(bundle, assets, &raws, "raw") ||
1260 !applyFileOverlay(bundle, assets, &colors, "color") ||
1261 !applyFileOverlay(bundle, assets, &menus, "menu") ||
Adam Lesinski9bbe7872017-01-24 13:52:04 -08001262 !applyFileOverlay(bundle, assets, &fonts, "font") ||
Adam Lesinski282e1812014-01-23 18:17:42 -08001263 !applyFileOverlay(bundle, assets, &mipmaps, "mipmap")) {
1264 return UNKNOWN_ERROR;
1265 }
1266
1267 bool hasErrors = false;
1268
1269 if (drawables != NULL) {
1270 if (bundle->getOutputAPKFile() != NULL) {
1271 err = preProcessImages(bundle, assets, drawables, "drawable");
1272 }
1273 if (err == NO_ERROR) {
1274 err = makeFileResources(bundle, assets, &table, drawables, "drawable");
1275 if (err != NO_ERROR) {
1276 hasErrors = true;
1277 }
1278 } else {
1279 hasErrors = true;
1280 }
1281 }
1282
1283 if (mipmaps != NULL) {
1284 if (bundle->getOutputAPKFile() != NULL) {
1285 err = preProcessImages(bundle, assets, mipmaps, "mipmap");
1286 }
1287 if (err == NO_ERROR) {
1288 err = makeFileResources(bundle, assets, &table, mipmaps, "mipmap");
1289 if (err != NO_ERROR) {
1290 hasErrors = true;
1291 }
1292 } else {
1293 hasErrors = true;
1294 }
1295 }
1296
Adam Lesinski9bbe7872017-01-24 13:52:04 -08001297 if (fonts != NULL) {
1298 err = makeFileResources(bundle, assets, &table, fonts, "font");
1299 if (err != NO_ERROR) {
1300 hasErrors = true;
1301 }
1302 }
1303
Adam Lesinski282e1812014-01-23 18:17:42 -08001304 if (layouts != NULL) {
1305 err = makeFileResources(bundle, assets, &table, layouts, "layout");
1306 if (err != NO_ERROR) {
1307 hasErrors = true;
1308 }
1309 }
1310
1311 if (anims != NULL) {
1312 err = makeFileResources(bundle, assets, &table, anims, "anim");
1313 if (err != NO_ERROR) {
1314 hasErrors = true;
1315 }
1316 }
1317
1318 if (animators != NULL) {
1319 err = makeFileResources(bundle, assets, &table, animators, "animator");
1320 if (err != NO_ERROR) {
1321 hasErrors = true;
1322 }
1323 }
1324
1325 if (transitions != NULL) {
1326 err = makeFileResources(bundle, assets, &table, transitions, "transition");
1327 if (err != NO_ERROR) {
1328 hasErrors = true;
1329 }
1330 }
1331
Adam Lesinski282e1812014-01-23 18:17:42 -08001332 if (interpolators != NULL) {
1333 err = makeFileResources(bundle, assets, &table, interpolators, "interpolator");
1334 if (err != NO_ERROR) {
1335 hasErrors = true;
1336 }
1337 }
1338
1339 if (xmls != NULL) {
1340 err = makeFileResources(bundle, assets, &table, xmls, "xml");
1341 if (err != NO_ERROR) {
1342 hasErrors = true;
1343 }
1344 }
1345
1346 if (raws != NULL) {
1347 err = makeFileResources(bundle, assets, &table, raws, "raw");
1348 if (err != NO_ERROR) {
1349 hasErrors = true;
1350 }
1351 }
1352
1353 // compile resources
1354 current = assets;
1355 while(current.get()) {
1356 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
1357 current->getResources();
1358
1359 ssize_t index = resources->indexOfKey(String8("values"));
1360 if (index >= 0) {
1361 ResourceDirIterator it(resources->valueAt(index), String8("values"));
1362 ssize_t res;
1363 while ((res=it.next()) == NO_ERROR) {
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -07001364 const sp<AaptFile>& file = it.getFile();
Adam Lesinski282e1812014-01-23 18:17:42 -08001365 res = compileResourceFile(bundle, assets, file, it.getParams(),
1366 (current!=assets), &table);
1367 if (res != NO_ERROR) {
1368 hasErrors = true;
1369 }
1370 }
1371 }
1372 current = current->getOverlay();
1373 }
1374
1375 if (colors != NULL) {
1376 err = makeFileResources(bundle, assets, &table, colors, "color");
1377 if (err != NO_ERROR) {
1378 hasErrors = true;
1379 }
1380 }
1381
1382 if (menus != NULL) {
1383 err = makeFileResources(bundle, assets, &table, menus, "menu");
1384 if (err != NO_ERROR) {
1385 hasErrors = true;
1386 }
1387 }
1388
Adam Lesinski526d73b2016-07-18 17:01:14 -07001389 if (hasErrors) {
1390 return UNKNOWN_ERROR;
1391 }
1392
Adam Lesinski282e1812014-01-23 18:17:42 -08001393 // --------------------------------------------------------------------
1394 // Assignment of resource IDs and initial generation of resource table.
1395 // --------------------------------------------------------------------
1396
1397 if (table.hasResources()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001398 err = table.assignResourceIds();
1399 if (err < NO_ERROR) {
1400 return err;
1401 }
1402 }
1403
1404 // --------------------------------------------------------------
1405 // Finally, we can now we can compile XML files, which may reference
1406 // resources.
1407 // --------------------------------------------------------------
1408
1409 if (layouts != NULL) {
1410 ResourceDirIterator it(layouts, String8("layout"));
1411 while ((err=it.next()) == NO_ERROR) {
1412 String8 src = it.getFile()->getPrintableSource();
Adam Lesinskie572c012014-09-19 15:10:04 -07001413 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1414 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001415 if (err == NO_ERROR) {
1416 ResXMLTree block;
1417 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
1418 checkForIds(src, block);
1419 } else {
1420 hasErrors = true;
1421 }
1422 }
1423
1424 if (err < NO_ERROR) {
1425 hasErrors = true;
1426 }
1427 err = NO_ERROR;
1428 }
1429
1430 if (anims != NULL) {
1431 ResourceDirIterator it(anims, String8("anim"));
1432 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001433 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1434 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001435 if (err != NO_ERROR) {
1436 hasErrors = true;
1437 }
1438 }
1439
1440 if (err < NO_ERROR) {
1441 hasErrors = true;
1442 }
1443 err = NO_ERROR;
1444 }
1445
1446 if (animators != NULL) {
1447 ResourceDirIterator it(animators, String8("animator"));
1448 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001449 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1450 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001451 if (err != NO_ERROR) {
1452 hasErrors = true;
1453 }
1454 }
1455
1456 if (err < NO_ERROR) {
1457 hasErrors = true;
1458 }
1459 err = NO_ERROR;
1460 }
1461
1462 if (interpolators != NULL) {
1463 ResourceDirIterator it(interpolators, String8("interpolator"));
1464 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001465 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1466 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001467 if (err != NO_ERROR) {
1468 hasErrors = true;
1469 }
1470 }
1471
1472 if (err < NO_ERROR) {
1473 hasErrors = true;
1474 }
1475 err = NO_ERROR;
1476 }
1477
1478 if (transitions != NULL) {
1479 ResourceDirIterator it(transitions, String8("transition"));
1480 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001481 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1482 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001483 if (err != NO_ERROR) {
1484 hasErrors = true;
1485 }
1486 }
1487
1488 if (err < NO_ERROR) {
1489 hasErrors = true;
1490 }
1491 err = NO_ERROR;
1492 }
1493
Adam Lesinski282e1812014-01-23 18:17:42 -08001494 if (xmls != NULL) {
1495 ResourceDirIterator it(xmls, String8("xml"));
1496 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001497 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1498 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001499 if (err != NO_ERROR) {
1500 hasErrors = true;
1501 }
1502 }
1503
1504 if (err < NO_ERROR) {
1505 hasErrors = true;
1506 }
1507 err = NO_ERROR;
1508 }
1509
1510 if (drawables != NULL) {
Adam Lesinskifab50872014-04-16 14:40:42 -07001511 ResourceDirIterator it(drawables, String8("drawable"));
1512 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001513 err = postProcessImage(bundle, assets, &table, it.getFile());
Adam Lesinskifab50872014-04-16 14:40:42 -07001514 if (err != NO_ERROR) {
1515 hasErrors = true;
1516 }
1517 }
1518
1519 if (err < NO_ERROR) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001520 hasErrors = true;
1521 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001522 err = NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001523 }
1524
1525 if (colors != NULL) {
1526 ResourceDirIterator it(colors, String8("color"));
1527 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001528 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1529 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001530 if (err != NO_ERROR) {
1531 hasErrors = true;
1532 }
1533 }
1534
1535 if (err < NO_ERROR) {
1536 hasErrors = true;
1537 }
1538 err = NO_ERROR;
1539 }
1540
1541 if (menus != NULL) {
1542 ResourceDirIterator it(menus, String8("menu"));
1543 while ((err=it.next()) == NO_ERROR) {
1544 String8 src = it.getFile()->getPrintableSource();
Adam Lesinskie572c012014-09-19 15:10:04 -07001545 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1546 it.getFile(), &table, xmlFlags);
Adam Lesinskifab50872014-04-16 14:40:42 -07001547 if (err == NO_ERROR) {
1548 ResXMLTree block;
1549 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
1550 checkForIds(src, block);
1551 } else {
Adam Lesinski282e1812014-01-23 18:17:42 -08001552 hasErrors = true;
1553 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001554 }
1555
1556 if (err < NO_ERROR) {
1557 hasErrors = true;
1558 }
1559 err = NO_ERROR;
1560 }
1561
Adam Lesinski9bbe7872017-01-24 13:52:04 -08001562 if (fonts != NULL) {
1563 ResourceDirIterator it(fonts, String8("font"));
1564 while ((err=it.next()) == NO_ERROR) {
1565 // fonts can be resources other than xml.
1566 if (it.getFile()->getPath().getPathExtension() == ".xml") {
1567 String8 src = it.getFile()->getPrintableSource();
1568 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1569 it.getFile(), &table, xmlFlags);
1570 if (err != NO_ERROR) {
1571 hasErrors = true;
1572 }
1573 }
1574 }
1575
1576 if (err < NO_ERROR) {
1577 hasErrors = true;
1578 }
1579 err = NO_ERROR;
1580 }
1581
Adam Lesinskie572c012014-09-19 15:10:04 -07001582 // Now compile any generated resources.
1583 std::queue<CompileResourceWorkItem>& workQueue = table.getWorkQueue();
1584 while (!workQueue.empty()) {
1585 CompileResourceWorkItem& workItem = workQueue.front();
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07001586 int xmlCompilationFlags = xmlFlags | XML_COMPILE_PARSE_VALUES
1587 | XML_COMPILE_ASSIGN_ATTRIBUTE_IDS;
1588 if (!workItem.needsCompiling) {
1589 xmlCompilationFlags &= ~XML_COMPILE_ASSIGN_ATTRIBUTE_IDS;
1590 xmlCompilationFlags &= ~XML_COMPILE_PARSE_VALUES;
1591 }
1592 err = compileXmlFile(bundle, assets, workItem.resourceName, workItem.xmlRoot,
1593 workItem.file, &table, xmlCompilationFlags);
1594
Adam Lesinskie572c012014-09-19 15:10:04 -07001595 if (err == NO_ERROR) {
1596 assets->addResource(workItem.resPath.getPathLeaf(),
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07001597 workItem.resPath,
1598 workItem.file,
1599 workItem.file->getResourceType());
Adam Lesinskie572c012014-09-19 15:10:04 -07001600 } else {
1601 hasErrors = true;
1602 }
1603 workQueue.pop();
1604 }
1605
Adam Lesinski282e1812014-01-23 18:17:42 -08001606 if (table.validateLocalizations()) {
1607 hasErrors = true;
1608 }
1609
1610 if (hasErrors) {
1611 return UNKNOWN_ERROR;
1612 }
1613
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001614 // If we're not overriding the platform build versions,
1615 // extract them from the platform APK.
1616 if (packageType != ResourceTable::System &&
1617 (bundle->getPlatformBuildVersionCode() == "" ||
1618 bundle->getPlatformBuildVersionName() == "")) {
1619 err = extractPlatformBuildVersion(assets->getAssetManager(), bundle);
1620 if (err != NO_ERROR) {
1621 return UNKNOWN_ERROR;
1622 }
1623 }
1624
Adam Lesinski282e1812014-01-23 18:17:42 -08001625 const sp<AaptFile> manifestFile(androidManifestFile->getFiles().valueAt(0));
1626 String8 manifestPath(manifestFile->getPrintableSource());
1627
1628 // Generate final compiled manifest file.
1629 manifestFile->clearData();
1630 sp<XMLNode> manifestTree = XMLNode::parse(manifestFile);
1631 if (manifestTree == NULL) {
1632 return UNKNOWN_ERROR;
1633 }
1634 err = massageManifest(bundle, manifestTree);
1635 if (err < NO_ERROR) {
1636 return err;
1637 }
Adam Lesinskie572c012014-09-19 15:10:04 -07001638 err = compileXmlFile(bundle, assets, String16(), manifestTree, manifestFile, &table);
Adam Lesinski282e1812014-01-23 18:17:42 -08001639 if (err < NO_ERROR) {
1640 return err;
1641 }
1642
Adam Lesinski82a2dd82014-09-17 18:34:15 -07001643 if (table.modifyForCompat(bundle) != NO_ERROR) {
1644 return UNKNOWN_ERROR;
1645 }
1646
Adam Lesinski282e1812014-01-23 18:17:42 -08001647 //block.restart();
1648 //printXMLBlock(&block);
1649
1650 // --------------------------------------------------------------
1651 // Generate the final resource table.
1652 // Re-flatten because we may have added new resource IDs
1653 // --------------------------------------------------------------
1654
Adam Lesinskide7de472014-11-03 12:03:08 -08001655
Adam Lesinski282e1812014-01-23 18:17:42 -08001656 ResTable finalResTable;
1657 sp<AaptFile> resFile;
1658
1659 if (table.hasResources()) {
1660 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
Adrian Roos58922482015-06-01 17:59:41 -07001661 err = table.addSymbols(symbols, bundle->getSkipSymbolsWithoutDefaultLocalization());
Adam Lesinski282e1812014-01-23 18:17:42 -08001662 if (err < NO_ERROR) {
1663 return err;
1664 }
1665
Adam Lesinskide7de472014-11-03 12:03:08 -08001666 KeyedVector<Symbol, Vector<SymbolDefinition> > densityVaryingResources;
1667 if (builder->getSplits().size() > 1) {
1668 // Only look for density varying resources if we're generating
1669 // splits.
1670 table.getDensityVaryingResources(densityVaryingResources);
1671 }
1672
Adam Lesinskifab50872014-04-16 14:40:42 -07001673 Vector<sp<ApkSplit> >& splits = builder->getSplits();
1674 const size_t numSplits = splits.size();
1675 for (size_t i = 0; i < numSplits; i++) {
1676 sp<ApkSplit>& split = splits.editItemAt(i);
1677 sp<AaptFile> flattenedTable = new AaptFile(String8("resources.arsc"),
1678 AaptGroupEntry(), String8());
Adam Lesinski27f69f42014-08-21 13:19:12 -07001679 err = table.flatten(bundle, split->getResourceFilter(),
1680 flattenedTable, split->isBase());
Adam Lesinskifab50872014-04-16 14:40:42 -07001681 if (err != NO_ERROR) {
1682 fprintf(stderr, "Failed to generate resource table for split '%s'\n",
1683 split->getPrintableName().string());
1684 return err;
1685 }
1686 split->addEntry(String8("resources.arsc"), flattenedTable);
Adam Lesinski282e1812014-01-23 18:17:42 -08001687
Adam Lesinskifab50872014-04-16 14:40:42 -07001688 if (split->isBase()) {
1689 resFile = flattenedTable;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07001690 err = finalResTable.add(flattenedTable->getData(), flattenedTable->getSize());
1691 if (err != NO_ERROR) {
1692 fprintf(stderr, "Generated resource table is corrupt.\n");
1693 return err;
1694 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001695 } else {
Adam Lesinskide7de472014-11-03 12:03:08 -08001696 ResTable resTable;
1697 err = resTable.add(flattenedTable->getData(), flattenedTable->getSize());
1698 if (err != NO_ERROR) {
1699 fprintf(stderr, "Generated resource table for split '%s' is corrupt.\n",
1700 split->getPrintableName().string());
1701 return err;
1702 }
1703
1704 bool hasError = false;
1705 const std::set<ConfigDescription>& splitConfigs = split->getConfigs();
1706 for (std::set<ConfigDescription>::const_iterator iter = splitConfigs.begin();
1707 iter != splitConfigs.end();
1708 ++iter) {
1709 const ConfigDescription& config = *iter;
1710 if (AaptConfig::isDensityOnly(config)) {
1711 // Each density only split must contain all
1712 // density only resources.
1713 Res_value val;
1714 resTable.setParameters(&config);
1715 const size_t densityVaryingResourceCount = densityVaryingResources.size();
1716 for (size_t k = 0; k < densityVaryingResourceCount; k++) {
1717 const Symbol& symbol = densityVaryingResources.keyAt(k);
1718 ssize_t block = resTable.getResource(symbol.id, &val, true);
1719 if (block < 0) {
1720 // Maybe it's in the base?
1721 finalResTable.setParameters(&config);
1722 block = finalResTable.getResource(symbol.id, &val, true);
1723 }
1724
1725 if (block < 0) {
1726 hasError = true;
1727 SourcePos().error("%s has no definition for density split '%s'",
1728 symbol.toString().string(), config.toString().string());
1729
1730 if (bundle->getVerbose()) {
1731 const Vector<SymbolDefinition>& defs = densityVaryingResources[k];
1732 const size_t defCount = std::min(size_t(5), defs.size());
1733 for (size_t d = 0; d < defCount; d++) {
1734 const SymbolDefinition& def = defs[d];
1735 def.source.error("%s has definition for %s",
1736 symbol.toString().string(), def.config.toString().string());
1737 }
1738
1739 if (defCount < defs.size()) {
1740 SourcePos().error("and %d more ...", (int) (defs.size() - defCount));
1741 }
1742 }
1743 }
1744 }
1745 }
1746 }
1747
1748 if (hasError) {
1749 return UNKNOWN_ERROR;
1750 }
1751
1752 // Generate the AndroidManifest for this split.
Adam Lesinskifab50872014-04-16 14:40:42 -07001753 sp<AaptFile> generatedManifest = new AaptFile(String8("AndroidManifest.xml"),
1754 AaptGroupEntry(), String8());
Jeff Sharkey2cfc8482014-07-09 16:10:16 -07001755 err = generateAndroidManifestForSplit(bundle, assets, split,
1756 generatedManifest, &table);
Adam Lesinskifab50872014-04-16 14:40:42 -07001757 if (err != NO_ERROR) {
1758 fprintf(stderr, "Failed to generate AndroidManifest.xml for split '%s'\n",
1759 split->getPrintableName().string());
1760 return err;
1761 }
1762 split->addEntry(String8("AndroidManifest.xml"), generatedManifest);
1763 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001764 }
1765
1766 if (bundle->getPublicOutputFile()) {
1767 FILE* fp = fopen(bundle->getPublicOutputFile(), "w+");
1768 if (fp == NULL) {
1769 fprintf(stderr, "ERROR: Unable to open public definitions output file %s: %s\n",
1770 (const char*)bundle->getPublicOutputFile(), strerror(errno));
1771 return UNKNOWN_ERROR;
1772 }
1773 if (bundle->getVerbose()) {
1774 printf(" Writing public definitions to %s.\n", bundle->getPublicOutputFile());
1775 }
1776 table.writePublicDefinitions(String16(assets->getPackage()), fp);
1777 fclose(fp);
1778 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001779
1780 if (finalResTable.getTableCount() == 0 || resFile == NULL) {
1781 fprintf(stderr, "No resource table was generated.\n");
1782 return UNKNOWN_ERROR;
1783 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001784 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001785
Adam Lesinski282e1812014-01-23 18:17:42 -08001786 // Perform a basic validation of the manifest file. This time we
1787 // parse it with the comments intact, so that we can use them to
1788 // generate java docs... so we are not going to write this one
1789 // back out to the final manifest data.
1790 sp<AaptFile> outManifestFile = new AaptFile(manifestFile->getSourceFile(),
1791 manifestFile->getGroupEntry(),
1792 manifestFile->getResourceType());
Adam Lesinskie572c012014-09-19 15:10:04 -07001793 err = compileXmlFile(bundle, assets, String16(), manifestFile,
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07001794 outManifestFile, &table, XML_COMPILE_STANDARD_RESOURCE & ~XML_COMPILE_STRIP_COMMENTS);
Adam Lesinski282e1812014-01-23 18:17:42 -08001795 if (err < NO_ERROR) {
1796 return err;
1797 }
1798 ResXMLTree block;
1799 block.setTo(outManifestFile->getData(), outManifestFile->getSize(), true);
1800 String16 manifest16("manifest");
1801 String16 permission16("permission");
1802 String16 permission_group16("permission-group");
1803 String16 uses_permission16("uses-permission");
1804 String16 instrumentation16("instrumentation");
1805 String16 application16("application");
1806 String16 provider16("provider");
1807 String16 service16("service");
1808 String16 receiver16("receiver");
1809 String16 activity16("activity");
1810 String16 action16("action");
1811 String16 category16("category");
1812 String16 data16("scheme");
Adam Lesinskid3edfde2014-08-08 17:32:44 -07001813 String16 feature_group16("feature-group");
1814 String16 uses_feature16("uses-feature");
Adam Lesinski282e1812014-01-23 18:17:42 -08001815 const char* packageIdentChars = "abcdefghijklmnopqrstuvwxyz"
1816 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789";
1817 const char* packageIdentCharsWithTheStupid = "abcdefghijklmnopqrstuvwxyz"
1818 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
1819 const char* classIdentChars = "abcdefghijklmnopqrstuvwxyz"
1820 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789$";
1821 const char* processIdentChars = "abcdefghijklmnopqrstuvwxyz"
1822 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:";
1823 const char* authoritiesIdentChars = "abcdefghijklmnopqrstuvwxyz"
1824 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-:;";
1825 const char* typeIdentChars = "abcdefghijklmnopqrstuvwxyz"
1826 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:-/*+";
1827 const char* schemeIdentChars = "abcdefghijklmnopqrstuvwxyz"
1828 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
1829 ResXMLTree::event_code_t code;
1830 sp<AaptSymbols> permissionSymbols;
1831 sp<AaptSymbols> permissionGroupSymbols;
1832 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1833 && code > ResXMLTree::BAD_DOCUMENT) {
1834 if (code == ResXMLTree::START_TAG) {
1835 size_t len;
1836 if (block.getElementNamespace(&len) != NULL) {
1837 continue;
1838 }
1839 if (strcmp16(block.getElementName(&len), manifest16.string()) == 0) {
1840 if (validateAttr(manifestPath, finalResTable, block, NULL, "package",
1841 packageIdentChars, true) != ATTR_OKAY) {
1842 hasErrors = true;
1843 }
1844 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1845 "sharedUserId", packageIdentChars, false) != ATTR_OKAY) {
1846 hasErrors = true;
1847 }
1848 } else if (strcmp16(block.getElementName(&len), permission16.string()) == 0
1849 || strcmp16(block.getElementName(&len), permission_group16.string()) == 0) {
1850 const bool isGroup = strcmp16(block.getElementName(&len),
1851 permission_group16.string()) == 0;
1852 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1853 "name", isGroup ? packageIdentCharsWithTheStupid
1854 : packageIdentChars, true) != ATTR_OKAY) {
1855 hasErrors = true;
1856 }
1857 SourcePos srcPos(manifestPath, block.getLineNumber());
1858 sp<AaptSymbols> syms;
1859 if (!isGroup) {
1860 syms = permissionSymbols;
1861 if (syms == NULL) {
1862 sp<AaptSymbols> symbols =
1863 assets->getSymbolsFor(String8("Manifest"));
1864 syms = permissionSymbols = symbols->addNestedSymbol(
1865 String8("permission"), srcPos);
1866 }
1867 } else {
1868 syms = permissionGroupSymbols;
1869 if (syms == NULL) {
1870 sp<AaptSymbols> symbols =
1871 assets->getSymbolsFor(String8("Manifest"));
1872 syms = permissionGroupSymbols = symbols->addNestedSymbol(
1873 String8("permission_group"), srcPos);
1874 }
1875 }
1876 size_t len;
1877 ssize_t index = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "name");
Dan Albertf348c152014-09-08 18:28:00 -07001878 const char16_t* id = block.getAttributeStringValue(index, &len);
Adam Lesinski282e1812014-01-23 18:17:42 -08001879 if (id == NULL) {
1880 fprintf(stderr, "%s:%d: missing name attribute in element <%s>.\n",
1881 manifestPath.string(), block.getLineNumber(),
1882 String8(block.getElementName(&len)).string());
1883 hasErrors = true;
1884 break;
1885 }
1886 String8 idStr(id);
1887 char* p = idStr.lockBuffer(idStr.size());
1888 char* e = p + idStr.size();
1889 bool begins_with_digit = true; // init to true so an empty string fails
1890 while (e > p) {
1891 e--;
1892 if (*e >= '0' && *e <= '9') {
1893 begins_with_digit = true;
1894 continue;
1895 }
1896 if ((*e >= 'a' && *e <= 'z') ||
1897 (*e >= 'A' && *e <= 'Z') ||
1898 (*e == '_')) {
1899 begins_with_digit = false;
1900 continue;
1901 }
1902 if (isGroup && (*e == '-')) {
1903 *e = '_';
1904 begins_with_digit = false;
1905 continue;
1906 }
1907 e++;
1908 break;
1909 }
1910 idStr.unlockBuffer();
1911 // verify that we stopped because we hit a period or
1912 // the beginning of the string, and that the
1913 // identifier didn't begin with a digit.
1914 if (begins_with_digit || (e != p && *(e-1) != '.')) {
1915 fprintf(stderr,
1916 "%s:%d: Permission name <%s> is not a valid Java symbol\n",
1917 manifestPath.string(), block.getLineNumber(), idStr.string());
1918 hasErrors = true;
1919 }
1920 syms->addStringSymbol(String8(e), idStr, srcPos);
Dan Albertf348c152014-09-08 18:28:00 -07001921 const char16_t* cmt = block.getComment(&len);
Adam Lesinski282e1812014-01-23 18:17:42 -08001922 if (cmt != NULL && *cmt != 0) {
1923 //printf("Comment of %s: %s\n", String8(e).string(),
1924 // String8(cmt).string());
1925 syms->appendComment(String8(e), String16(cmt), srcPos);
Adam Lesinski282e1812014-01-23 18:17:42 -08001926 }
1927 syms->makeSymbolPublic(String8(e), srcPos);
1928 } else if (strcmp16(block.getElementName(&len), uses_permission16.string()) == 0) {
1929 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1930 "name", packageIdentChars, true) != ATTR_OKAY) {
1931 hasErrors = true;
1932 }
1933 } else if (strcmp16(block.getElementName(&len), instrumentation16.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, "targetPackage",
1940 packageIdentChars, true) != ATTR_OKAY) {
1941 hasErrors = true;
1942 }
1943 } else if (strcmp16(block.getElementName(&len), application16.string()) == 0) {
1944 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1945 "name", classIdentChars, false) != ATTR_OKAY) {
1946 hasErrors = true;
1947 }
1948 if (validateAttr(manifestPath, finalResTable, block,
1949 RESOURCES_ANDROID_NAMESPACE, "permission",
1950 packageIdentChars, false) != ATTR_OKAY) {
1951 hasErrors = true;
1952 }
1953 if (validateAttr(manifestPath, finalResTable, block,
1954 RESOURCES_ANDROID_NAMESPACE, "process",
1955 processIdentChars, false) != ATTR_OKAY) {
1956 hasErrors = true;
1957 }
1958 if (validateAttr(manifestPath, finalResTable, block,
1959 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
1960 processIdentChars, false) != ATTR_OKAY) {
1961 hasErrors = true;
1962 }
1963 } else if (strcmp16(block.getElementName(&len), provider16.string()) == 0) {
1964 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1965 "name", classIdentChars, true) != ATTR_OKAY) {
1966 hasErrors = true;
1967 }
1968 if (validateAttr(manifestPath, finalResTable, block,
1969 RESOURCES_ANDROID_NAMESPACE, "authorities",
1970 authoritiesIdentChars, true) != ATTR_OKAY) {
1971 hasErrors = true;
1972 }
1973 if (validateAttr(manifestPath, finalResTable, block,
1974 RESOURCES_ANDROID_NAMESPACE, "permission",
1975 packageIdentChars, false) != ATTR_OKAY) {
1976 hasErrors = true;
1977 }
1978 if (validateAttr(manifestPath, finalResTable, block,
1979 RESOURCES_ANDROID_NAMESPACE, "process",
1980 processIdentChars, false) != ATTR_OKAY) {
1981 hasErrors = true;
1982 }
1983 } else if (strcmp16(block.getElementName(&len), service16.string()) == 0
1984 || strcmp16(block.getElementName(&len), receiver16.string()) == 0
1985 || strcmp16(block.getElementName(&len), activity16.string()) == 0) {
1986 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1987 "name", classIdentChars, true) != ATTR_OKAY) {
1988 hasErrors = true;
1989 }
1990 if (validateAttr(manifestPath, finalResTable, block,
1991 RESOURCES_ANDROID_NAMESPACE, "permission",
1992 packageIdentChars, false) != ATTR_OKAY) {
1993 hasErrors = true;
1994 }
1995 if (validateAttr(manifestPath, finalResTable, block,
1996 RESOURCES_ANDROID_NAMESPACE, "process",
1997 processIdentChars, false) != ATTR_OKAY) {
1998 hasErrors = true;
1999 }
2000 if (validateAttr(manifestPath, finalResTable, block,
2001 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
2002 processIdentChars, false) != ATTR_OKAY) {
2003 hasErrors = true;
2004 }
2005 } else if (strcmp16(block.getElementName(&len), action16.string()) == 0
2006 || strcmp16(block.getElementName(&len), category16.string()) == 0) {
2007 if (validateAttr(manifestPath, finalResTable, block,
2008 RESOURCES_ANDROID_NAMESPACE, "name",
2009 packageIdentChars, true) != ATTR_OKAY) {
2010 hasErrors = true;
2011 }
2012 } else if (strcmp16(block.getElementName(&len), data16.string()) == 0) {
2013 if (validateAttr(manifestPath, finalResTable, block,
2014 RESOURCES_ANDROID_NAMESPACE, "mimeType",
2015 typeIdentChars, true) != ATTR_OKAY) {
2016 hasErrors = true;
2017 }
2018 if (validateAttr(manifestPath, finalResTable, block,
2019 RESOURCES_ANDROID_NAMESPACE, "scheme",
2020 schemeIdentChars, true) != ATTR_OKAY) {
2021 hasErrors = true;
2022 }
Adam Lesinskid3edfde2014-08-08 17:32:44 -07002023 } else if (strcmp16(block.getElementName(&len), feature_group16.string()) == 0) {
2024 int depth = 1;
2025 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
2026 && code > ResXMLTree::BAD_DOCUMENT) {
2027 if (code == ResXMLTree::START_TAG) {
2028 depth++;
2029 if (strcmp16(block.getElementName(&len), uses_feature16.string()) == 0) {
2030 ssize_t idx = block.indexOfAttribute(
2031 RESOURCES_ANDROID_NAMESPACE, "required");
2032 if (idx < 0) {
2033 continue;
2034 }
2035
2036 int32_t data = block.getAttributeData(idx);
2037 if (data == 0) {
2038 fprintf(stderr, "%s:%d: Tag <uses-feature> can not have "
2039 "android:required=\"false\" when inside a "
2040 "<feature-group> tag.\n",
2041 manifestPath.string(), block.getLineNumber());
2042 hasErrors = true;
2043 }
2044 }
2045 } else if (code == ResXMLTree::END_TAG) {
2046 depth--;
2047 if (depth == 0) {
2048 break;
2049 }
2050 }
2051 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002052 }
2053 }
2054 }
2055
Adam Lesinskid3edfde2014-08-08 17:32:44 -07002056 if (hasErrors) {
2057 return UNKNOWN_ERROR;
2058 }
2059
Adam Lesinski282e1812014-01-23 18:17:42 -08002060 if (resFile != NULL) {
2061 // These resources are now considered to be a part of the included
2062 // resources, for others to reference.
2063 err = assets->addIncludedResources(resFile);
2064 if (err < NO_ERROR) {
2065 fprintf(stderr, "ERROR: Unable to parse generated resources, aborting.\n");
2066 return err;
2067 }
2068 }
2069
2070 return err;
2071}
2072
2073static const char* getIndentSpace(int indent)
2074{
2075static const char whitespace[] =
2076" ";
2077
2078 return whitespace + sizeof(whitespace) - 1 - indent*4;
2079}
2080
2081static String8 flattenSymbol(const String8& symbol) {
2082 String8 result(symbol);
2083 ssize_t first;
2084 if ((first = symbol.find(":", 0)) >= 0
2085 || (first = symbol.find(".", 0)) >= 0) {
2086 size_t size = symbol.size();
2087 char* buf = result.lockBuffer(size);
2088 for (size_t i = first; i < size; i++) {
2089 if (buf[i] == ':' || buf[i] == '.') {
2090 buf[i] = '_';
2091 }
2092 }
2093 result.unlockBuffer(size);
2094 }
2095 return result;
2096}
2097
2098static String8 getSymbolPackage(const String8& symbol, const sp<AaptAssets>& assets, bool pub) {
2099 ssize_t colon = symbol.find(":", 0);
2100 if (colon >= 0) {
2101 return String8(symbol.string(), colon);
2102 }
2103 return pub ? assets->getPackage() : assets->getSymbolsPrivatePackage();
2104}
2105
2106static String8 getSymbolName(const String8& symbol) {
2107 ssize_t colon = symbol.find(":", 0);
2108 if (colon >= 0) {
2109 return String8(symbol.string() + colon + 1);
2110 }
2111 return symbol;
2112}
2113
2114static String16 getAttributeComment(const sp<AaptAssets>& assets,
2115 const String8& name,
2116 String16* outTypeComment = NULL)
2117{
2118 sp<AaptSymbols> asym = assets->getSymbolsFor(String8("R"));
2119 if (asym != NULL) {
2120 //printf("Got R symbols!\n");
2121 asym = asym->getNestedSymbols().valueFor(String8("attr"));
2122 if (asym != NULL) {
2123 //printf("Got attrs symbols! comment %s=%s\n",
2124 // name.string(), String8(asym->getComment(name)).string());
2125 if (outTypeComment != NULL) {
2126 *outTypeComment = asym->getTypeComment(name);
2127 }
2128 return asym->getComment(name);
2129 }
2130 }
2131 return String16();
2132}
2133
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002134static status_t writeResourceLoadedCallbackForLayoutClasses(
2135 FILE* fp, const sp<AaptAssets>& assets,
Andreas Gampe87332a72014-10-01 22:03:58 -07002136 const sp<AaptSymbols>& symbols, int indent, bool /* includePrivate */)
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002137{
2138 String16 attr16("attr");
2139 String16 package16(assets->getPackage());
2140
2141 const char* indentStr = getIndentSpace(indent);
2142 bool hasErrors = false;
2143
2144 size_t i;
2145 size_t N = symbols->getNestedSymbols().size();
2146 for (i=0; i<N; i++) {
2147 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2148 String8 realClassName(symbols->getNestedSymbols().keyAt(i));
2149 String8 nclassName(flattenSymbol(realClassName));
2150
2151 fprintf(fp,
2152 "%sfor(int i = 0; i < styleable.%s.length; ++i) {\n"
2153 "%sstyleable.%s[i] = (styleable.%s[i] & 0x00ffffff) | (packageId << 24);\n"
2154 "%s}\n",
2155 indentStr, nclassName.string(),
2156 getIndentSpace(indent+1), nclassName.string(), nclassName.string(),
2157 indentStr);
Adam Lesinski1e4663852014-08-15 14:47:28 -07002158 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002159
Dan Alberted811ee2016-01-15 12:16:06 -08002160 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002161}
2162
2163static status_t writeResourceLoadedCallback(
2164 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2165 const sp<AaptSymbols>& symbols, const String8& className, int indent)
2166{
2167 size_t i;
2168 status_t err = NO_ERROR;
2169
2170 size_t N = symbols->getSymbols().size();
2171 for (i=0; i<N; i++) {
2172 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
Adam Lesinskieed58582015-09-10 18:43:34 -07002173 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002174 continue;
Adam Lesinski1e4663852014-08-15 14:47:28 -07002175 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002176 if (!assets->isJavaSymbol(sym, includePrivate)) {
2177 continue;
Adam Lesinski1e4663852014-08-15 14:47:28 -07002178 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002179 String8 flat_name(flattenSymbol(sym.name));
2180 fprintf(fp,
2181 "%s%s.%s = (%s.%s & 0x00ffffff) | (packageId << 24);\n",
2182 getIndentSpace(indent), className.string(), flat_name.string(),
2183 className.string(), flat_name.string());
Adam Lesinski1e4663852014-08-15 14:47:28 -07002184 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002185
2186 N = symbols->getNestedSymbols().size();
2187 for (i=0; i<N; i++) {
2188 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2189 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2190 if (nclassName == "styleable") {
2191 err = writeResourceLoadedCallbackForLayoutClasses(
2192 fp, assets, nsymbols, indent, includePrivate);
2193 } else {
2194 err = writeResourceLoadedCallback(fp, assets, includePrivate, nsymbols,
2195 nclassName, indent);
Adam Lesinski1e4663852014-08-15 14:47:28 -07002196 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002197 if (err != NO_ERROR) {
2198 return err;
2199 }
Adam Lesinski1e4663852014-08-15 14:47:28 -07002200 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002201
2202 return NO_ERROR;
Adam Lesinski1e4663852014-08-15 14:47:28 -07002203}
2204
Adam Lesinski282e1812014-01-23 18:17:42 -08002205static status_t writeLayoutClasses(
2206 FILE* fp, const sp<AaptAssets>& assets,
Adam Lesinskie8e91922014-08-06 17:41:08 -07002207 const sp<AaptSymbols>& symbols, int indent, bool includePrivate, bool nonConstantId)
Adam Lesinski282e1812014-01-23 18:17:42 -08002208{
2209 const char* indentStr = getIndentSpace(indent);
2210 if (!includePrivate) {
2211 fprintf(fp, "%s/** @doconly */\n", indentStr);
2212 }
2213 fprintf(fp, "%spublic static final class styleable {\n", indentStr);
2214 indent++;
2215
2216 String16 attr16("attr");
2217 String16 package16(assets->getPackage());
2218
2219 indentStr = getIndentSpace(indent);
2220 bool hasErrors = false;
2221
2222 size_t i;
2223 size_t N = symbols->getNestedSymbols().size();
2224 for (i=0; i<N; i++) {
2225 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2226 String8 realClassName(symbols->getNestedSymbols().keyAt(i));
2227 String8 nclassName(flattenSymbol(realClassName));
2228
2229 SortedVector<uint32_t> idents;
2230 Vector<uint32_t> origOrder;
2231 Vector<bool> publicFlags;
2232
2233 size_t a;
2234 size_t NA = nsymbols->getSymbols().size();
2235 for (a=0; a<NA; a++) {
2236 const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a));
2237 int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32
2238 ? sym.int32Val : 0;
2239 bool isPublic = true;
2240 if (code == 0) {
2241 String16 name16(sym.name);
2242 uint32_t typeSpecFlags;
2243 code = assets->getIncludedResources().identifierForName(
2244 name16.string(), name16.size(),
2245 attr16.string(), attr16.size(),
2246 package16.string(), package16.size(), &typeSpecFlags);
2247 if (code == 0) {
2248 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
2249 nclassName.string(), sym.name.string());
2250 hasErrors = true;
2251 }
2252 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
2253 }
2254 idents.add(code);
2255 origOrder.add(code);
2256 publicFlags.add(isPublic);
2257 }
2258
2259 NA = idents.size();
2260
Adam Lesinski282e1812014-01-23 18:17:42 -08002261 String16 comment = symbols->getComment(realClassName);
Jeff Browneb490d62014-06-06 19:43:42 -07002262 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002263 fprintf(fp, "%s/** ", indentStr);
2264 if (comment.size() > 0) {
2265 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002266 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002267 fprintf(fp, "%s\n", cmt.string());
Adam Lesinski282e1812014-01-23 18:17:42 -08002268 } else {
2269 fprintf(fp, "Attributes that can be used with a %s.\n", nclassName.string());
2270 }
2271 bool hasTable = false;
2272 for (a=0; a<NA; a++) {
2273 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2274 if (pos >= 0) {
2275 if (!hasTable) {
2276 hasTable = true;
2277 fprintf(fp,
2278 "%s <p>Includes the following attributes:</p>\n"
2279 "%s <table>\n"
2280 "%s <colgroup align=\"left\" />\n"
2281 "%s <colgroup align=\"left\" />\n"
2282 "%s <tr><th>Attribute</th><th>Description</th></tr>\n",
2283 indentStr,
2284 indentStr,
2285 indentStr,
2286 indentStr,
2287 indentStr);
2288 }
2289 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2290 if (!publicFlags.itemAt(a) && !includePrivate) {
2291 continue;
2292 }
2293 String8 name8(sym.name);
2294 String16 comment(sym.comment);
2295 if (comment.size() <= 0) {
2296 comment = getAttributeComment(assets, name8);
2297 }
Michael Wrightfeaf99f2016-05-06 17:16:06 +01002298 if (comment.contains(u"@removed")) {
2299 continue;
2300 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002301 if (comment.size() > 0) {
2302 const char16_t* p = comment.string();
2303 while (*p != 0 && *p != '.') {
2304 if (*p == '{') {
2305 while (*p != 0 && *p != '}') {
2306 p++;
2307 }
2308 } else {
2309 p++;
2310 }
2311 }
2312 if (*p == '.') {
2313 p++;
2314 }
2315 comment = String16(comment.string(), p-comment.string());
2316 }
2317 fprintf(fp, "%s <tr><td><code>{@link #%s_%s %s:%s}</code></td><td>%s</td></tr>\n",
2318 indentStr, nclassName.string(),
2319 flattenSymbol(name8).string(),
2320 getSymbolPackage(name8, assets, true).string(),
2321 getSymbolName(name8).string(),
2322 String8(comment).string());
2323 }
2324 }
2325 if (hasTable) {
2326 fprintf(fp, "%s </table>\n", indentStr);
2327 }
2328 for (a=0; a<NA; a++) {
2329 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2330 if (pos >= 0) {
2331 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2332 if (!publicFlags.itemAt(a) && !includePrivate) {
2333 continue;
2334 }
2335 fprintf(fp, "%s @see #%s_%s\n",
2336 indentStr, nclassName.string(),
2337 flattenSymbol(sym.name).string());
2338 }
2339 }
2340 fprintf(fp, "%s */\n", getIndentSpace(indent));
2341
Jeff Browneb490d62014-06-06 19:43:42 -07002342 ann.printAnnotations(fp, indentStr);
Adam Lesinski282e1812014-01-23 18:17:42 -08002343
2344 fprintf(fp,
2345 "%spublic static final int[] %s = {\n"
2346 "%s",
2347 indentStr, nclassName.string(),
2348 getIndentSpace(indent+1));
2349
2350 for (a=0; a<NA; a++) {
2351 if (a != 0) {
2352 if ((a&3) == 0) {
2353 fprintf(fp, ",\n%s", getIndentSpace(indent+1));
2354 } else {
2355 fprintf(fp, ", ");
2356 }
2357 }
2358 fprintf(fp, "0x%08x", idents[a]);
2359 }
2360
2361 fprintf(fp, "\n%s};\n", indentStr);
2362
2363 for (a=0; a<NA; a++) {
2364 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2365 if (pos >= 0) {
2366 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2367 if (!publicFlags.itemAt(a) && !includePrivate) {
2368 continue;
2369 }
2370 String8 name8(sym.name);
2371 String16 comment(sym.comment);
2372 String16 typeComment;
2373 if (comment.size() <= 0) {
2374 comment = getAttributeComment(assets, name8, &typeComment);
2375 } else {
2376 getAttributeComment(assets, name8, &typeComment);
2377 }
2378
2379 uint32_t typeSpecFlags = 0;
2380 String16 name16(sym.name);
2381 assets->getIncludedResources().identifierForName(
2382 name16.string(), name16.size(),
2383 attr16.string(), attr16.size(),
2384 package16.string(), package16.size(), &typeSpecFlags);
2385 //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
2386 // String8(attr16).string(), String8(name16).string(), typeSpecFlags);
2387 const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
Jeff Browneb490d62014-06-06 19:43:42 -07002388
2389 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002390 fprintf(fp, "%s/**\n", indentStr);
2391 if (comment.size() > 0) {
2392 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002393 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002394 fprintf(fp, "%s <p>\n%s @attr description\n", indentStr, indentStr);
2395 fprintf(fp, "%s %s\n", indentStr, cmt.string());
Adam Lesinski282e1812014-01-23 18:17:42 -08002396 } else {
2397 fprintf(fp,
2398 "%s <p>This symbol is the offset where the {@link %s.R.attr#%s}\n"
2399 "%s attribute's value can be found in the {@link #%s} array.\n",
2400 indentStr,
2401 getSymbolPackage(name8, assets, pub).string(),
2402 getSymbolName(name8).string(),
2403 indentStr, nclassName.string());
2404 }
2405 if (typeComment.size() > 0) {
2406 String8 cmt(typeComment);
Jeff Browneb490d62014-06-06 19:43:42 -07002407 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002408 fprintf(fp, "\n\n%s %s\n", indentStr, cmt.string());
Adam Lesinski282e1812014-01-23 18:17:42 -08002409 }
2410 if (comment.size() > 0) {
2411 if (pub) {
2412 fprintf(fp,
2413 "%s <p>This corresponds to the global attribute\n"
2414 "%s resource symbol {@link %s.R.attr#%s}.\n",
2415 indentStr, indentStr,
2416 getSymbolPackage(name8, assets, true).string(),
2417 getSymbolName(name8).string());
2418 } else {
2419 fprintf(fp,
2420 "%s <p>This is a private symbol.\n", indentStr);
2421 }
2422 }
2423 fprintf(fp, "%s @attr name %s:%s\n", indentStr,
2424 getSymbolPackage(name8, assets, pub).string(),
2425 getSymbolName(name8).string());
2426 fprintf(fp, "%s*/\n", indentStr);
Jeff Browneb490d62014-06-06 19:43:42 -07002427 ann.printAnnotations(fp, indentStr);
Adam Lesinskie8e91922014-08-06 17:41:08 -07002428
2429 const char * id_format = nonConstantId ?
2430 "%spublic static int %s_%s = %d;\n" :
2431 "%spublic static final int %s_%s = %d;\n";
2432
Adam Lesinski282e1812014-01-23 18:17:42 -08002433 fprintf(fp,
Adam Lesinskie8e91922014-08-06 17:41:08 -07002434 id_format,
Adam Lesinski282e1812014-01-23 18:17:42 -08002435 indentStr, nclassName.string(),
2436 flattenSymbol(name8).string(), (int)pos);
2437 }
2438 }
2439 }
2440
2441 indent--;
2442 fprintf(fp, "%s};\n", getIndentSpace(indent));
Andreas Gampe2412f842014-09-30 20:55:57 -07002443 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08002444}
2445
2446static status_t writeTextLayoutClasses(
2447 FILE* fp, const sp<AaptAssets>& assets,
2448 const sp<AaptSymbols>& symbols, bool includePrivate)
2449{
2450 String16 attr16("attr");
2451 String16 package16(assets->getPackage());
2452
2453 bool hasErrors = false;
2454
2455 size_t i;
2456 size_t N = symbols->getNestedSymbols().size();
2457 for (i=0; i<N; i++) {
2458 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2459 String8 realClassName(symbols->getNestedSymbols().keyAt(i));
2460 String8 nclassName(flattenSymbol(realClassName));
2461
2462 SortedVector<uint32_t> idents;
2463 Vector<uint32_t> origOrder;
2464 Vector<bool> publicFlags;
2465
2466 size_t a;
2467 size_t NA = nsymbols->getSymbols().size();
2468 for (a=0; a<NA; a++) {
2469 const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a));
2470 int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32
2471 ? sym.int32Val : 0;
2472 bool isPublic = true;
2473 if (code == 0) {
2474 String16 name16(sym.name);
2475 uint32_t typeSpecFlags;
2476 code = assets->getIncludedResources().identifierForName(
2477 name16.string(), name16.size(),
2478 attr16.string(), attr16.size(),
2479 package16.string(), package16.size(), &typeSpecFlags);
2480 if (code == 0) {
2481 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
2482 nclassName.string(), sym.name.string());
2483 hasErrors = true;
2484 }
2485 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
2486 }
2487 idents.add(code);
2488 origOrder.add(code);
2489 publicFlags.add(isPublic);
2490 }
2491
2492 NA = idents.size();
2493
2494 fprintf(fp, "int[] styleable %s {", nclassName.string());
2495
2496 for (a=0; a<NA; a++) {
2497 if (a != 0) {
2498 fprintf(fp, ",");
2499 }
2500 fprintf(fp, " 0x%08x", idents[a]);
2501 }
2502
2503 fprintf(fp, " }\n");
2504
2505 for (a=0; a<NA; a++) {
2506 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2507 if (pos >= 0) {
2508 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2509 if (!publicFlags.itemAt(a) && !includePrivate) {
2510 continue;
2511 }
2512 String8 name8(sym.name);
2513 String16 comment(sym.comment);
2514 String16 typeComment;
2515 if (comment.size() <= 0) {
2516 comment = getAttributeComment(assets, name8, &typeComment);
2517 } else {
2518 getAttributeComment(assets, name8, &typeComment);
2519 }
2520
2521 uint32_t typeSpecFlags = 0;
2522 String16 name16(sym.name);
2523 assets->getIncludedResources().identifierForName(
2524 name16.string(), name16.size(),
2525 attr16.string(), attr16.size(),
2526 package16.string(), package16.size(), &typeSpecFlags);
2527 //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
2528 // String8(attr16).string(), String8(name16).string(), typeSpecFlags);
Andreas Gampe2412f842014-09-30 20:55:57 -07002529 //const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08002530
2531 fprintf(fp,
2532 "int styleable %s_%s %d\n",
2533 nclassName.string(),
2534 flattenSymbol(name8).string(), (int)pos);
2535 }
2536 }
2537 }
2538
Andreas Gampe2412f842014-09-30 20:55:57 -07002539 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08002540}
2541
2542static status_t writeSymbolClass(
2543 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2544 const sp<AaptSymbols>& symbols, const String8& className, int indent,
Adam Lesinski1e4663852014-08-15 14:47:28 -07002545 bool nonConstantId, bool emitCallback)
Adam Lesinski282e1812014-01-23 18:17:42 -08002546{
2547 fprintf(fp, "%spublic %sfinal class %s {\n",
2548 getIndentSpace(indent),
2549 indent != 0 ? "static " : "", className.string());
2550 indent++;
2551
2552 size_t i;
2553 status_t err = NO_ERROR;
2554
2555 const char * id_format = nonConstantId ?
2556 "%spublic static int %s=0x%08x;\n" :
2557 "%spublic static final int %s=0x%08x;\n";
2558
2559 size_t N = symbols->getSymbols().size();
2560 for (i=0; i<N; i++) {
2561 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2562 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
2563 continue;
2564 }
2565 if (!assets->isJavaSymbol(sym, includePrivate)) {
2566 continue;
2567 }
2568 String8 name8(sym.name);
2569 String16 comment(sym.comment);
2570 bool haveComment = false;
Jeff Browneb490d62014-06-06 19:43:42 -07002571 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002572 if (comment.size() > 0) {
2573 haveComment = true;
2574 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002575 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002576 fprintf(fp,
2577 "%s/** %s\n",
2578 getIndentSpace(indent), cmt.string());
Adam Lesinski282e1812014-01-23 18:17:42 -08002579 }
2580 String16 typeComment(sym.typeComment);
2581 if (typeComment.size() > 0) {
2582 String8 cmt(typeComment);
Jeff Browneb490d62014-06-06 19:43:42 -07002583 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002584 if (!haveComment) {
2585 haveComment = true;
2586 fprintf(fp,
2587 "%s/** %s\n", getIndentSpace(indent), cmt.string());
2588 } else {
2589 fprintf(fp,
2590 "%s %s\n", getIndentSpace(indent), cmt.string());
2591 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002592 }
2593 if (haveComment) {
2594 fprintf(fp,"%s */\n", getIndentSpace(indent));
2595 }
Jeff Browneb490d62014-06-06 19:43:42 -07002596 ann.printAnnotations(fp, getIndentSpace(indent));
Adam Lesinski282e1812014-01-23 18:17:42 -08002597 fprintf(fp, id_format,
2598 getIndentSpace(indent),
2599 flattenSymbol(name8).string(), (int)sym.int32Val);
2600 }
2601
2602 for (i=0; i<N; i++) {
2603 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2604 if (sym.typeCode != AaptSymbolEntry::TYPE_STRING) {
2605 continue;
2606 }
2607 if (!assets->isJavaSymbol(sym, includePrivate)) {
2608 continue;
2609 }
2610 String8 name8(sym.name);
2611 String16 comment(sym.comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002612 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002613 if (comment.size() > 0) {
2614 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002615 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002616 fprintf(fp,
2617 "%s/** %s\n"
2618 "%s */\n",
2619 getIndentSpace(indent), cmt.string(),
2620 getIndentSpace(indent));
Adam Lesinski282e1812014-01-23 18:17:42 -08002621 }
Jeff Browneb490d62014-06-06 19:43:42 -07002622 ann.printAnnotations(fp, getIndentSpace(indent));
Adam Lesinski282e1812014-01-23 18:17:42 -08002623 fprintf(fp, "%spublic static final String %s=\"%s\";\n",
2624 getIndentSpace(indent),
2625 flattenSymbol(name8).string(), sym.stringVal.string());
2626 }
2627
2628 sp<AaptSymbols> styleableSymbols;
2629
2630 N = symbols->getNestedSymbols().size();
2631 for (i=0; i<N; i++) {
2632 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2633 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2634 if (nclassName == "styleable") {
2635 styleableSymbols = nsymbols;
2636 } else {
Adam Lesinski1e4663852014-08-15 14:47:28 -07002637 err = writeSymbolClass(fp, assets, includePrivate, nsymbols, nclassName,
2638 indent, nonConstantId, false);
Adam Lesinski282e1812014-01-23 18:17:42 -08002639 }
2640 if (err != NO_ERROR) {
2641 return err;
2642 }
2643 }
2644
2645 if (styleableSymbols != NULL) {
Adam Lesinskie8e91922014-08-06 17:41:08 -07002646 err = writeLayoutClasses(fp, assets, styleableSymbols, indent, includePrivate, nonConstantId);
Adam Lesinski282e1812014-01-23 18:17:42 -08002647 if (err != NO_ERROR) {
2648 return err;
2649 }
2650 }
2651
Adam Lesinski1e4663852014-08-15 14:47:28 -07002652 if (emitCallback) {
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002653 fprintf(fp, "%spublic static void onResourcesLoaded(int packageId) {\n",
2654 getIndentSpace(indent));
2655 writeResourceLoadedCallback(fp, assets, includePrivate, symbols, className, indent + 1);
2656 fprintf(fp, "%s}\n", getIndentSpace(indent));
Adam Lesinski1e4663852014-08-15 14:47:28 -07002657 }
2658
Adam Lesinski282e1812014-01-23 18:17:42 -08002659 indent--;
2660 fprintf(fp, "%s}\n", getIndentSpace(indent));
2661 return NO_ERROR;
2662}
2663
2664static status_t writeTextSymbolClass(
2665 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2666 const sp<AaptSymbols>& symbols, const String8& className)
2667{
2668 size_t i;
2669 status_t err = NO_ERROR;
2670
2671 size_t N = symbols->getSymbols().size();
2672 for (i=0; i<N; i++) {
2673 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2674 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
2675 continue;
2676 }
2677
2678 if (!assets->isJavaSymbol(sym, includePrivate)) {
2679 continue;
2680 }
2681
2682 String8 name8(sym.name);
2683 fprintf(fp, "int %s %s 0x%08x\n",
2684 className.string(),
2685 flattenSymbol(name8).string(), (int)sym.int32Val);
2686 }
2687
2688 N = symbols->getNestedSymbols().size();
2689 for (i=0; i<N; i++) {
2690 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2691 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2692 if (nclassName == "styleable") {
2693 err = writeTextLayoutClasses(fp, assets, nsymbols, includePrivate);
2694 } else {
2695 err = writeTextSymbolClass(fp, assets, includePrivate, nsymbols, nclassName);
2696 }
2697 if (err != NO_ERROR) {
2698 return err;
2699 }
2700 }
2701
2702 return NO_ERROR;
2703}
2704
2705status_t writeResourceSymbols(Bundle* bundle, const sp<AaptAssets>& assets,
Adam Lesinski1e4663852014-08-15 14:47:28 -07002706 const String8& package, bool includePrivate, bool emitCallback)
Adam Lesinski282e1812014-01-23 18:17:42 -08002707{
2708 if (!bundle->getRClassDir()) {
2709 return NO_ERROR;
2710 }
2711
2712 const char* textSymbolsDest = bundle->getOutputTextSymbols();
2713
2714 String8 R("R");
2715 const size_t N = assets->getSymbols().size();
2716 for (size_t i=0; i<N; i++) {
2717 sp<AaptSymbols> symbols = assets->getSymbols().valueAt(i);
2718 String8 className(assets->getSymbols().keyAt(i));
2719 String8 dest(bundle->getRClassDir());
2720
2721 if (bundle->getMakePackageDirs()) {
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -07002722 const String8& pkg(package);
Adam Lesinski282e1812014-01-23 18:17:42 -08002723 const char* last = pkg.string();
2724 const char* s = last-1;
2725 do {
2726 s++;
2727 if (s > last && (*s == '.' || *s == 0)) {
2728 String8 part(last, s-last);
2729 dest.appendPath(part);
Elliott Hughese17788c2015-08-17 12:41:46 -07002730#ifdef _WIN32
Adam Lesinski282e1812014-01-23 18:17:42 -08002731 _mkdir(dest.string());
2732#else
2733 mkdir(dest.string(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP);
2734#endif
2735 last = s+1;
2736 }
2737 } while (*s);
2738 }
2739 dest.appendPath(className);
2740 dest.append(".java");
2741 FILE* fp = fopen(dest.string(), "w+");
2742 if (fp == NULL) {
2743 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
2744 dest.string(), strerror(errno));
2745 return UNKNOWN_ERROR;
2746 }
2747 if (bundle->getVerbose()) {
2748 printf(" Writing symbols for class %s.\n", className.string());
2749 }
2750
2751 fprintf(fp,
2752 "/* AUTO-GENERATED FILE. DO NOT MODIFY.\n"
2753 " *\n"
2754 " * This class was automatically generated by the\n"
2755 " * aapt tool from the resource data it found. It\n"
2756 " * should not be modified by hand.\n"
2757 " */\n"
2758 "\n"
2759 "package %s;\n\n", package.string());
2760
2761 status_t err = writeSymbolClass(fp, assets, includePrivate, symbols,
Adam Lesinski1e4663852014-08-15 14:47:28 -07002762 className, 0, bundle->getNonConstantId(), emitCallback);
Elliott Hughesb30296b2013-10-29 15:25:52 -07002763 fclose(fp);
Adam Lesinski282e1812014-01-23 18:17:42 -08002764 if (err != NO_ERROR) {
2765 return err;
2766 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002767
2768 if (textSymbolsDest != NULL && R == className) {
2769 String8 textDest(textSymbolsDest);
2770 textDest.appendPath(className);
2771 textDest.append(".txt");
2772
2773 FILE* fp = fopen(textDest.string(), "w+");
2774 if (fp == NULL) {
2775 fprintf(stderr, "ERROR: Unable to open text symbol file %s: %s\n",
2776 textDest.string(), strerror(errno));
2777 return UNKNOWN_ERROR;
2778 }
2779 if (bundle->getVerbose()) {
2780 printf(" Writing text symbols for class %s.\n", className.string());
2781 }
2782
2783 status_t err = writeTextSymbolClass(fp, assets, includePrivate, symbols,
2784 className);
Elliott Hughesb30296b2013-10-29 15:25:52 -07002785 fclose(fp);
Adam Lesinski282e1812014-01-23 18:17:42 -08002786 if (err != NO_ERROR) {
2787 return err;
2788 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002789 }
2790
2791 // If we were asked to generate a dependency file, we'll go ahead and add this R.java
2792 // as a target in the dependency file right next to it.
2793 if (bundle->getGenDependencies() && R == className) {
2794 // Add this R.java to the dependency file
2795 String8 dependencyFile(bundle->getRClassDir());
2796 dependencyFile.appendPath("R.java.d");
2797
2798 FILE *fp = fopen(dependencyFile.string(), "a");
2799 fprintf(fp,"%s \\\n", dest.string());
2800 fclose(fp);
2801 }
2802 }
2803
2804 return NO_ERROR;
2805}
2806
2807
2808class ProguardKeepSet
2809{
2810public:
2811 // { rule --> { file locations } }
2812 KeyedVector<String8, SortedVector<String8> > rules;
2813
2814 void add(const String8& rule, const String8& where);
2815};
2816
2817void ProguardKeepSet::add(const String8& rule, const String8& where)
2818{
2819 ssize_t index = rules.indexOfKey(rule);
2820 if (index < 0) {
2821 index = rules.add(rule, SortedVector<String8>());
2822 }
2823 rules.editValueAt(index).add(where);
2824}
2825
2826void
2827addProguardKeepRule(ProguardKeepSet* keep, const String8& inClassName,
2828 const char* pkg, const String8& srcName, int line)
2829{
2830 String8 className(inClassName);
2831 if (pkg != NULL) {
2832 // asdf --> package.asdf
2833 // .asdf .a.b --> package.asdf package.a.b
2834 // asdf.adsf --> asdf.asdf
2835 const char* p = className.string();
2836 const char* q = strchr(p, '.');
2837 if (p == q) {
2838 className = pkg;
2839 className.append(inClassName);
2840 } else if (q == NULL) {
2841 className = pkg;
2842 className.append(".");
2843 className.append(inClassName);
2844 }
2845 }
2846
2847 String8 rule("-keep class ");
2848 rule += className;
2849 rule += " { <init>(...); }";
2850
2851 String8 location("view ");
2852 location += srcName;
2853 char lineno[20];
2854 sprintf(lineno, ":%d", line);
2855 location += lineno;
2856
2857 keep->add(rule, location);
2858}
2859
2860void
2861addProguardKeepMethodRule(ProguardKeepSet* keep, const String8& memberName,
Andreas Gampe2412f842014-09-30 20:55:57 -07002862 const char* /* pkg */, const String8& srcName, int line)
Adam Lesinski282e1812014-01-23 18:17:42 -08002863{
2864 String8 rule("-keepclassmembers class * { *** ");
2865 rule += memberName;
2866 rule += "(...); }";
2867
2868 String8 location("onClick ");
2869 location += srcName;
2870 char lineno[20];
2871 sprintf(lineno, ":%d", line);
2872 location += lineno;
2873
2874 keep->add(rule, location);
2875}
2876
2877status_t
Rohit Agrawal682583c2016-04-21 16:29:58 -07002878writeProguardForAndroidManifest(ProguardKeepSet* keep, const sp<AaptAssets>& assets, bool mainDex)
Adam Lesinski282e1812014-01-23 18:17:42 -08002879{
2880 status_t err;
2881 ResXMLTree tree;
2882 size_t len;
2883 ResXMLTree::event_code_t code;
2884 int depth = 0;
2885 bool inApplication = false;
2886 String8 error;
2887 sp<AaptGroup> assGroup;
2888 sp<AaptFile> assFile;
2889 String8 pkg;
Rohit Agrawal682583c2016-04-21 16:29:58 -07002890 String8 defaultProcess;
Adam Lesinski282e1812014-01-23 18:17:42 -08002891
2892 // First, look for a package file to parse. This is required to
2893 // be able to generate the resource information.
2894 assGroup = assets->getFiles().valueFor(String8("AndroidManifest.xml"));
2895 if (assGroup == NULL) {
2896 fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n");
2897 return -1;
2898 }
2899
2900 if (assGroup->getFiles().size() != 1) {
2901 fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
2902 assGroup->getFiles().valueAt(0)->getPrintableSource().string());
2903 }
2904
2905 assFile = assGroup->getFiles().valueAt(0);
2906
2907 err = parseXMLResource(assFile, &tree);
2908 if (err != NO_ERROR) {
2909 return err;
2910 }
2911
2912 tree.restart();
2913
2914 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
2915 if (code == ResXMLTree::END_TAG) {
2916 if (/* name == "Application" && */ depth == 2) {
2917 inApplication = false;
2918 }
2919 depth--;
2920 continue;
2921 }
2922 if (code != ResXMLTree::START_TAG) {
2923 continue;
2924 }
2925 depth++;
2926 String8 tag(tree.getElementName(&len));
2927 // printf("Depth %d tag %s\n", depth, tag.string());
2928 bool keepTag = false;
2929 if (depth == 1) {
2930 if (tag != "manifest") {
2931 fprintf(stderr, "ERROR: manifest does not start with <manifest> tag\n");
2932 return -1;
2933 }
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07002934 pkg = AaptXml::getAttribute(tree, NULL, "package");
Adam Lesinski282e1812014-01-23 18:17:42 -08002935 } else if (depth == 2) {
2936 if (tag == "application") {
2937 inApplication = true;
2938 keepTag = true;
2939
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07002940 String8 agent = AaptXml::getAttribute(tree,
2941 "http://schemas.android.com/apk/res/android",
Adam Lesinski282e1812014-01-23 18:17:42 -08002942 "backupAgent", &error);
2943 if (agent.length() > 0) {
2944 addProguardKeepRule(keep, agent, pkg.string(),
2945 assFile->getPrintableSource(), tree.getLineNumber());
2946 }
Rohit Agrawal682583c2016-04-21 16:29:58 -07002947
2948 if (mainDex) {
2949 defaultProcess = AaptXml::getAttribute(tree,
2950 "http://schemas.android.com/apk/res/android", "process", &error);
2951 if (error != "") {
2952 fprintf(stderr, "ERROR: %s\n", error.string());
2953 return -1;
2954 }
2955 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002956 } else if (tag == "instrumentation") {
2957 keepTag = true;
2958 }
2959 }
2960 if (!keepTag && inApplication && depth == 3) {
2961 if (tag == "activity" || tag == "service" || tag == "receiver" || tag == "provider") {
2962 keepTag = true;
Ivan Gavrilovicf580d912016-07-19 12:03:33 +01002963
2964 if (mainDex) {
2965 String8 componentProcess = AaptXml::getAttribute(tree,
2966 "http://schemas.android.com/apk/res/android", "process", &error);
2967 if (error != "") {
2968 fprintf(stderr, "ERROR: %s\n", error.string());
2969 return -1;
2970 }
2971
2972 const String8& process =
2973 componentProcess.length() > 0 ? componentProcess : defaultProcess;
2974 keepTag = process.length() > 0 && process.find(":") != 0;
2975 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002976 }
2977 }
2978 if (keepTag) {
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07002979 String8 name = AaptXml::getAttribute(tree,
2980 "http://schemas.android.com/apk/res/android", "name", &error);
Adam Lesinski282e1812014-01-23 18:17:42 -08002981 if (error != "") {
2982 fprintf(stderr, "ERROR: %s\n", error.string());
2983 return -1;
2984 }
Rohit Agrawal682583c2016-04-21 16:29:58 -07002985
2986 keepTag = name.length() > 0;
2987
Rohit Agrawal682583c2016-04-21 16:29:58 -07002988 if (keepTag) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002989 addProguardKeepRule(keep, name, pkg.string(),
2990 assFile->getPrintableSource(), tree.getLineNumber());
2991 }
2992 }
2993 }
2994
2995 return NO_ERROR;
2996}
2997
2998struct NamespaceAttributePair {
2999 const char* ns;
3000 const char* attr;
3001
3002 NamespaceAttributePair(const char* n, const char* a) : ns(n), attr(a) {}
3003 NamespaceAttributePair() : ns(NULL), attr(NULL) {}
3004};
3005
3006status_t
3007writeProguardForXml(ProguardKeepSet* keep, const sp<AaptFile>& layoutFile,
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003008 const Vector<String8>& startTags, const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs)
Adam Lesinski282e1812014-01-23 18:17:42 -08003009{
3010 status_t err;
3011 ResXMLTree tree;
3012 size_t len;
3013 ResXMLTree::event_code_t code;
3014
3015 err = parseXMLResource(layoutFile, &tree);
3016 if (err != NO_ERROR) {
3017 return err;
3018 }
3019
3020 tree.restart();
3021
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003022 if (!startTags.isEmpty()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003023 bool haveStart = false;
3024 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
3025 if (code != ResXMLTree::START_TAG) {
3026 continue;
3027 }
3028 String8 tag(tree.getElementName(&len));
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003029 const size_t numStartTags = startTags.size();
3030 for (size_t i = 0; i < numStartTags; i++) {
3031 if (tag == startTags[i]) {
3032 haveStart = true;
3033 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003034 }
3035 break;
3036 }
3037 if (!haveStart) {
3038 return NO_ERROR;
3039 }
3040 }
3041
3042 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
3043 if (code != ResXMLTree::START_TAG) {
3044 continue;
3045 }
3046 String8 tag(tree.getElementName(&len));
3047
3048 // If there is no '.', we'll assume that it's one of the built in names.
3049 if (strchr(tag.string(), '.')) {
3050 addProguardKeepRule(keep, tag, NULL,
3051 layoutFile->getPrintableSource(), tree.getLineNumber());
3052 } else if (tagAttrPairs != NULL) {
3053 ssize_t tagIndex = tagAttrPairs->indexOfKey(tag);
3054 if (tagIndex >= 0) {
3055 const Vector<NamespaceAttributePair>& nsAttrVector = tagAttrPairs->valueAt(tagIndex);
3056 for (size_t i = 0; i < nsAttrVector.size(); i++) {
3057 const NamespaceAttributePair& nsAttr = nsAttrVector[i];
3058
3059 ssize_t attrIndex = tree.indexOfAttribute(nsAttr.ns, nsAttr.attr);
3060 if (attrIndex < 0) {
3061 // fprintf(stderr, "%s:%d: <%s> does not have attribute %s:%s.\n",
3062 // layoutFile->getPrintableSource().string(), tree.getLineNumber(),
3063 // tag.string(), nsAttr.ns, nsAttr.attr);
3064 } else {
3065 size_t len;
3066 addProguardKeepRule(keep,
3067 String8(tree.getAttributeStringValue(attrIndex, &len)), NULL,
3068 layoutFile->getPrintableSource(), tree.getLineNumber());
3069 }
3070 }
3071 }
3072 }
3073 ssize_t attrIndex = tree.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "onClick");
3074 if (attrIndex >= 0) {
3075 size_t len;
3076 addProguardKeepMethodRule(keep,
3077 String8(tree.getAttributeStringValue(attrIndex, &len)), NULL,
3078 layoutFile->getPrintableSource(), tree.getLineNumber());
3079 }
3080 }
3081
3082 return NO_ERROR;
3083}
3084
3085static void addTagAttrPair(KeyedVector<String8, Vector<NamespaceAttributePair> >* dest,
3086 const char* tag, const char* ns, const char* attr) {
3087 String8 tagStr(tag);
3088 ssize_t index = dest->indexOfKey(tagStr);
3089
3090 if (index < 0) {
3091 Vector<NamespaceAttributePair> vector;
3092 vector.add(NamespaceAttributePair(ns, attr));
3093 dest->add(tagStr, vector);
3094 } else {
3095 dest->editValueAt(index).add(NamespaceAttributePair(ns, attr));
3096 }
3097}
3098
3099status_t
3100writeProguardForLayouts(ProguardKeepSet* keep, const sp<AaptAssets>& assets)
3101{
3102 status_t err;
Adam Lesinski62c5df52014-12-02 16:19:05 -08003103 const char* kClass = "class";
3104 const char* kFragment = "fragment";
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003105 const String8 kTransition("transition");
3106 const String8 kTransitionPrefix("transition-");
Adam Lesinski282e1812014-01-23 18:17:42 -08003107
3108 // tag:attribute pairs that should be checked in layout files.
3109 KeyedVector<String8, Vector<NamespaceAttributePair> > kLayoutTagAttrPairs;
Adam Lesinski62c5df52014-12-02 16:19:05 -08003110 addTagAttrPair(&kLayoutTagAttrPairs, "view", NULL, kClass);
3111 addTagAttrPair(&kLayoutTagAttrPairs, kFragment, NULL, kClass);
3112 addTagAttrPair(&kLayoutTagAttrPairs, kFragment, RESOURCES_ANDROID_NAMESPACE, "name");
Adam Lesinski282e1812014-01-23 18:17:42 -08003113
3114 // tag:attribute pairs that should be checked in xml files.
3115 KeyedVector<String8, Vector<NamespaceAttributePair> > kXmlTagAttrPairs;
Adam Lesinski62c5df52014-12-02 16:19:05 -08003116 addTagAttrPair(&kXmlTagAttrPairs, "PreferenceScreen", RESOURCES_ANDROID_NAMESPACE, kFragment);
3117 addTagAttrPair(&kXmlTagAttrPairs, "header", RESOURCES_ANDROID_NAMESPACE, kFragment);
Adam Lesinski282e1812014-01-23 18:17:42 -08003118
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003119 // tag:attribute pairs that should be checked in transition files.
3120 KeyedVector<String8, Vector<NamespaceAttributePair> > kTransitionTagAttrPairs;
Adam Lesinski62c5df52014-12-02 16:19:05 -08003121 addTagAttrPair(&kTransitionTagAttrPairs, kTransition.string(), NULL, kClass);
3122 addTagAttrPair(&kTransitionTagAttrPairs, "pathMotion", NULL, kClass);
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003123
Adam Lesinski282e1812014-01-23 18:17:42 -08003124 const Vector<sp<AaptDir> >& dirs = assets->resDirs();
3125 const size_t K = dirs.size();
3126 for (size_t k=0; k<K; k++) {
3127 const sp<AaptDir>& d = dirs.itemAt(k);
3128 const String8& dirName = d->getLeaf();
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003129 Vector<String8> startTags;
Adam Lesinski282e1812014-01-23 18:17:42 -08003130 const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs = NULL;
3131 if ((dirName == String8("layout")) || (strncmp(dirName.string(), "layout-", 7) == 0)) {
3132 tagAttrPairs = &kLayoutTagAttrPairs;
3133 } else if ((dirName == String8("xml")) || (strncmp(dirName.string(), "xml-", 4) == 0)) {
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003134 startTags.add(String8("PreferenceScreen"));
3135 startTags.add(String8("preference-headers"));
Adam Lesinski282e1812014-01-23 18:17:42 -08003136 tagAttrPairs = &kXmlTagAttrPairs;
3137 } else if ((dirName == String8("menu")) || (strncmp(dirName.string(), "menu-", 5) == 0)) {
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003138 startTags.add(String8("menu"));
Adam Lesinski282e1812014-01-23 18:17:42 -08003139 tagAttrPairs = NULL;
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003140 } else if (dirName == kTransition || (strncmp(dirName.string(), kTransitionPrefix.string(),
3141 kTransitionPrefix.size()) == 0)) {
3142 tagAttrPairs = &kTransitionTagAttrPairs;
Adam Lesinski282e1812014-01-23 18:17:42 -08003143 } else {
3144 continue;
3145 }
3146
3147 const KeyedVector<String8,sp<AaptGroup> > groups = d->getFiles();
3148 const size_t N = groups.size();
3149 for (size_t i=0; i<N; i++) {
3150 const sp<AaptGroup>& group = groups.valueAt(i);
3151 const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files = group->getFiles();
3152 const size_t M = files.size();
3153 for (size_t j=0; j<M; j++) {
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003154 err = writeProguardForXml(keep, files.valueAt(j), startTags, tagAttrPairs);
Adam Lesinski282e1812014-01-23 18:17:42 -08003155 if (err < 0) {
3156 return err;
3157 }
3158 }
3159 }
3160 }
3161 // Handle the overlays
3162 sp<AaptAssets> overlay = assets->getOverlay();
3163 if (overlay.get()) {
3164 return writeProguardForLayouts(keep, overlay);
3165 }
3166
3167 return NO_ERROR;
3168}
3169
3170status_t
Rohit Agrawal682583c2016-04-21 16:29:58 -07003171writeProguardSpec(const char* filename, const ProguardKeepSet& keep, status_t err)
Adam Lesinski282e1812014-01-23 18:17:42 -08003172{
Rohit Agrawal682583c2016-04-21 16:29:58 -07003173 FILE* fp = fopen(filename, "w+");
Adam Lesinski282e1812014-01-23 18:17:42 -08003174 if (fp == NULL) {
3175 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
Rohit Agrawal682583c2016-04-21 16:29:58 -07003176 filename, strerror(errno));
Adam Lesinski282e1812014-01-23 18:17:42 -08003177 return UNKNOWN_ERROR;
3178 }
3179
3180 const KeyedVector<String8, SortedVector<String8> >& rules = keep.rules;
3181 const size_t N = rules.size();
3182 for (size_t i=0; i<N; i++) {
3183 const SortedVector<String8>& locations = rules.valueAt(i);
3184 const size_t M = locations.size();
3185 for (size_t j=0; j<M; j++) {
3186 fprintf(fp, "# %s\n", locations.itemAt(j).string());
3187 }
3188 fprintf(fp, "%s\n\n", rules.keyAt(i).string());
3189 }
3190 fclose(fp);
3191
3192 return err;
3193}
3194
Rohit Agrawal682583c2016-04-21 16:29:58 -07003195status_t
3196writeProguardFile(Bundle* bundle, const sp<AaptAssets>& assets)
3197{
3198 status_t err = -1;
3199
3200 if (!bundle->getProguardFile()) {
3201 return NO_ERROR;
3202 }
3203
3204 ProguardKeepSet keep;
3205
3206 err = writeProguardForAndroidManifest(&keep, assets, false);
3207 if (err < 0) {
3208 return err;
3209 }
3210
3211 err = writeProguardForLayouts(&keep, assets);
3212 if (err < 0) {
3213 return err;
3214 }
3215
3216 return writeProguardSpec(bundle->getProguardFile(), keep, err);
3217}
3218
3219status_t
3220writeMainDexProguardFile(Bundle* bundle, const sp<AaptAssets>& assets)
3221{
3222 status_t err = -1;
3223
3224 if (!bundle->getMainDexProguardFile()) {
3225 return NO_ERROR;
3226 }
3227
3228 ProguardKeepSet keep;
3229
3230 err = writeProguardForAndroidManifest(&keep, assets, true);
3231 if (err < 0) {
3232 return err;
3233 }
3234
3235 return writeProguardSpec(bundle->getMainDexProguardFile(), keep, err);
3236}
3237
Adam Lesinski282e1812014-01-23 18:17:42 -08003238// Loops through the string paths and writes them to the file pointer
3239// Each file path is written on its own line with a terminating backslash.
3240status_t writePathsToFile(const sp<FilePathStore>& files, FILE* fp)
3241{
3242 status_t deps = -1;
3243 for (size_t file_i = 0; file_i < files->size(); ++file_i) {
3244 // Add the full file path to the dependency file
3245 fprintf(fp, "%s \\\n", files->itemAt(file_i).string());
3246 deps++;
3247 }
3248 return deps;
3249}
3250
3251status_t
Andreas Gampe2412f842014-09-30 20:55:57 -07003252writeDependencyPreReqs(Bundle* /* bundle */, const sp<AaptAssets>& assets, FILE* fp, bool includeRaw)
Adam Lesinski282e1812014-01-23 18:17:42 -08003253{
3254 status_t deps = -1;
3255 deps += writePathsToFile(assets->getFullResPaths(), fp);
3256 if (includeRaw) {
3257 deps += writePathsToFile(assets->getFullAssetPaths(), fp);
3258 }
3259 return deps;
3260}