blob: 2bf52066b618faebc1570652d9778a1fd693cf64 [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) {
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800724 existingEntry->string = String16(value);
725 return true;
726 }
727
Adam Lesinski282e1812014-01-23 18:17:42 -0800728 if (errorOnFailedInsert) {
729 fprintf(stderr, "Error: AndroidManifest.xml already defines %s (in %s);"
730 " cannot insert new value %s.\n",
731 String8(attr).string(), String8(ns).string(), value);
732 return false;
733 }
734
Adam Lesinski282e1812014-01-23 18:17:42 -0800735 // don't stop the build.
736 return true;
737 }
738
739 node->addAttribute(ns, attr, String16(value));
740 return true;
741}
742
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800743/*
744 * Inserts an attribute in a given node, only if the attribute does not
745 * exist.
746 * If errorOnFailedInsert is true, and the attribute already exists, returns false.
747 * Returns true otherwise, even if the attribute already exists.
748 */
749bool addTagAttribute(const sp<XMLNode>& node, const char* ns8,
750 const char* attr8, const char* value, bool errorOnFailedInsert)
751{
752 return addTagAttribute(node, ns8, attr8, value, errorOnFailedInsert, false);
753}
754
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -0700755static void fullyQualifyClassName(const String8& package, const sp<XMLNode>& node,
Adam Lesinski282e1812014-01-23 18:17:42 -0800756 const String16& attrName) {
757 XMLNode::attribute_entry* attr = node->editAttribute(
758 String16("http://schemas.android.com/apk/res/android"), attrName);
759 if (attr != NULL) {
760 String8 name(attr->string);
761
762 // asdf --> package.asdf
763 // .asdf .a.b --> package.asdf package.a.b
764 // asdf.adsf --> asdf.asdf
765 String8 className;
766 const char* p = name.string();
767 const char* q = strchr(p, '.');
768 if (p == q) {
769 className += package;
770 className += name;
771 } else if (q == NULL) {
772 className += package;
773 className += ".";
774 className += name;
775 } else {
776 className += name;
777 }
Andreas Gampe2412f842014-09-30 20:55:57 -0700778 if (kIsDebug) {
779 printf("Qualifying class '%s' to '%s'", name.string(), className.string());
780 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800781 attr->string.setTo(String16(className));
782 }
783}
784
785status_t massageManifest(Bundle* bundle, sp<XMLNode> root)
786{
787 root = root->searchElement(String16(), String16("manifest"));
788 if (root == NULL) {
789 fprintf(stderr, "No <manifest> tag.\n");
790 return UNKNOWN_ERROR;
791 }
792
793 bool errorOnFailedInsert = bundle->getErrorOnFailedInsert();
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800794 bool replaceVersion = bundle->getReplaceVersion();
Adam Lesinski282e1812014-01-23 18:17:42 -0800795
796 if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionCode",
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800797 bundle->getVersionCode(), errorOnFailedInsert, replaceVersion)) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800798 return UNKNOWN_ERROR;
Adam Lesinski6a7d2752014-08-07 21:26:53 -0700799 } else {
800 const XMLNode::attribute_entry* attr = root->getAttribute(
801 String16(RESOURCES_ANDROID_NAMESPACE), String16("versionCode"));
802 if (attr != NULL) {
803 bundle->setVersionCode(strdup(String8(attr->string).string()));
804 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800805 }
Adam Lesinski6a7d2752014-08-07 21:26:53 -0700806
Adam Lesinski282e1812014-01-23 18:17:42 -0800807 if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionName",
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800808 bundle->getVersionName(), errorOnFailedInsert, replaceVersion)) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800809 return UNKNOWN_ERROR;
Adam Lesinski82a2dd82014-09-17 18:34:15 -0700810 } else {
811 const XMLNode::attribute_entry* attr = root->getAttribute(
812 String16(RESOURCES_ANDROID_NAMESPACE), String16("versionName"));
813 if (attr != NULL) {
814 bundle->setVersionName(strdup(String8(attr->string).string()));
815 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800816 }
817
Adam Lesinski82a2dd82014-09-17 18:34:15 -0700818 sp<XMLNode> vers = root->getChildElement(String16(), String16("uses-sdk"));
Adam Lesinski282e1812014-01-23 18:17:42 -0800819 if (bundle->getMinSdkVersion() != NULL
820 || bundle->getTargetSdkVersion() != NULL
821 || bundle->getMaxSdkVersion() != NULL) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800822 if (vers == NULL) {
823 vers = XMLNode::newElement(root->getFilename(), String16(), String16("uses-sdk"));
824 root->insertChildAt(vers, 0);
825 }
826
827 if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "minSdkVersion",
828 bundle->getMinSdkVersion(), errorOnFailedInsert)) {
829 return UNKNOWN_ERROR;
830 }
831 if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "targetSdkVersion",
832 bundle->getTargetSdkVersion(), errorOnFailedInsert)) {
833 return UNKNOWN_ERROR;
834 }
835 if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "maxSdkVersion",
836 bundle->getMaxSdkVersion(), errorOnFailedInsert)) {
837 return UNKNOWN_ERROR;
838 }
839 }
840
Adam Lesinski82a2dd82014-09-17 18:34:15 -0700841 if (vers != NULL) {
842 const XMLNode::attribute_entry* attr = vers->getAttribute(
843 String16(RESOURCES_ANDROID_NAMESPACE), String16("minSdkVersion"));
844 if (attr != NULL) {
845 bundle->setMinSdkVersion(strdup(String8(attr->string).string()));
846 }
847 }
848
Adam Lesinskiad2d07d2014-08-27 16:21:08 -0700849 if (bundle->getPlatformBuildVersionCode() != "") {
850 if (!addTagAttribute(root, "", "platformBuildVersionCode",
851 bundle->getPlatformBuildVersionCode(), errorOnFailedInsert, true)) {
852 return UNKNOWN_ERROR;
853 }
854 }
855
856 if (bundle->getPlatformBuildVersionName() != "") {
857 if (!addTagAttribute(root, "", "platformBuildVersionName",
858 bundle->getPlatformBuildVersionName(), errorOnFailedInsert, true)) {
859 return UNKNOWN_ERROR;
860 }
861 }
862
Adam Lesinski282e1812014-01-23 18:17:42 -0800863 if (bundle->getDebugMode()) {
864 sp<XMLNode> application = root->getChildElement(String16(), String16("application"));
865 if (application != NULL) {
866 if (!addTagAttribute(application, RESOURCES_ANDROID_NAMESPACE, "debuggable", "true",
867 errorOnFailedInsert)) {
868 return UNKNOWN_ERROR;
869 }
870 }
871 }
872
873 // Deal with manifest package name overrides
874 const char* manifestPackageNameOverride = bundle->getManifestPackageNameOverride();
875 if (manifestPackageNameOverride != NULL) {
876 // Update the actual package name
877 XMLNode::attribute_entry* attr = root->editAttribute(String16(), String16("package"));
878 if (attr == NULL) {
879 fprintf(stderr, "package name is required with --rename-manifest-package.\n");
880 return UNKNOWN_ERROR;
881 }
882 String8 origPackage(attr->string);
883 attr->string.setTo(String16(manifestPackageNameOverride));
Andreas Gampe2412f842014-09-30 20:55:57 -0700884 if (kIsDebug) {
885 printf("Overriding package '%s' to be '%s'\n", origPackage.string(),
886 manifestPackageNameOverride);
887 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800888
889 // Make class names fully qualified
890 sp<XMLNode> application = root->getChildElement(String16(), String16("application"));
891 if (application != NULL) {
892 fullyQualifyClassName(origPackage, application, String16("name"));
893 fullyQualifyClassName(origPackage, application, String16("backupAgent"));
894
895 Vector<sp<XMLNode> >& children = const_cast<Vector<sp<XMLNode> >&>(application->getChildren());
896 for (size_t i = 0; i < children.size(); i++) {
897 sp<XMLNode> child = children.editItemAt(i);
898 String8 tag(child->getElementName());
899 if (tag == "activity" || tag == "service" || tag == "receiver" || tag == "provider") {
900 fullyQualifyClassName(origPackage, child, String16("name"));
901 } else if (tag == "activity-alias") {
902 fullyQualifyClassName(origPackage, child, String16("name"));
903 fullyQualifyClassName(origPackage, child, String16("targetActivity"));
904 }
905 }
906 }
907 }
908
909 // Deal with manifest package name overrides
910 const char* instrumentationPackageNameOverride = bundle->getInstrumentationPackageNameOverride();
911 if (instrumentationPackageNameOverride != NULL) {
912 // Fix up instrumentation targets.
913 Vector<sp<XMLNode> >& children = const_cast<Vector<sp<XMLNode> >&>(root->getChildren());
914 for (size_t i = 0; i < children.size(); i++) {
915 sp<XMLNode> child = children.editItemAt(i);
916 String8 tag(child->getElementName());
917 if (tag == "instrumentation") {
918 XMLNode::attribute_entry* attr = child->editAttribute(
919 String16("http://schemas.android.com/apk/res/android"), String16("targetPackage"));
920 if (attr != NULL) {
921 attr->string.setTo(String16(instrumentationPackageNameOverride));
922 }
923 }
924 }
925 }
926
Adam Lesinski833f3cc2014-06-18 15:06:01 -0700927 // Generate split name if feature is present.
928 const XMLNode::attribute_entry* attr = root->getAttribute(String16(), String16("featureName"));
929 if (attr != NULL) {
930 String16 splitName("feature_");
931 splitName.append(attr->string);
932 status_t err = root->addAttribute(String16(), String16("split"), splitName);
933 if (err != NO_ERROR) {
934 ALOGE("Failed to insert split name into AndroidManifest.xml");
935 return err;
936 }
937 }
938
Adam Lesinski282e1812014-01-23 18:17:42 -0800939 return NO_ERROR;
940}
941
Adam Lesinskiad2d07d2014-08-27 16:21:08 -0700942static int32_t getPlatformAssetCookie(const AssetManager& assets) {
943 // Find the system package (0x01). AAPT always generates attributes
944 // with the type 0x01, so we're looking for the first attribute
945 // resource in the system package.
946 const ResTable& table = assets.getResources(true);
947 Res_value val;
948 ssize_t idx = table.getResource(0x01010000, &val, true);
949 if (idx != NO_ERROR) {
950 // Try as a bag.
951 const ResTable::bag_entry* entry;
952 ssize_t cnt = table.lockBag(0x01010000, &entry);
953 if (cnt >= 0) {
954 idx = entry->stringBlock;
955 }
956 table.unlockBag(entry);
957 }
958
959 if (idx < 0) {
960 return 0;
961 }
962 return table.getTableCookie(idx);
963}
964
965enum {
966 VERSION_CODE_ATTR = 0x0101021b,
967 VERSION_NAME_ATTR = 0x0101021c,
968};
969
970static ssize_t extractPlatformBuildVersion(ResXMLTree& tree, Bundle* bundle) {
971 size_t len;
972 ResXMLTree::event_code_t code;
973 while ((code = tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
974 if (code != ResXMLTree::START_TAG) {
975 continue;
976 }
977
978 const char16_t* ctag16 = tree.getElementName(&len);
979 if (ctag16 == NULL) {
980 fprintf(stderr, "ERROR: failed to get XML element name (bad string pool)\n");
981 return UNKNOWN_ERROR;
982 }
983
984 String8 tag(ctag16, len);
985 if (tag != "manifest") {
986 continue;
987 }
988
989 String8 error;
990 int32_t versionCode = AaptXml::getIntegerAttribute(tree, VERSION_CODE_ATTR, &error);
991 if (error != "") {
992 fprintf(stderr, "ERROR: failed to get platform version code\n");
993 return UNKNOWN_ERROR;
994 }
995
996 if (versionCode >= 0 && bundle->getPlatformBuildVersionCode() == "") {
997 bundle->setPlatformBuildVersionCode(String8::format("%d", versionCode));
998 }
999
1000 String8 versionName = AaptXml::getAttribute(tree, VERSION_NAME_ATTR, &error);
1001 if (error != "") {
1002 fprintf(stderr, "ERROR: failed to get platform version name\n");
1003 return UNKNOWN_ERROR;
1004 }
1005
1006 if (versionName != "" && bundle->getPlatformBuildVersionName() == "") {
1007 bundle->setPlatformBuildVersionName(versionName);
1008 }
1009 return NO_ERROR;
1010 }
1011
1012 fprintf(stderr, "ERROR: no <manifest> tag found in platform AndroidManifest.xml\n");
1013 return UNKNOWN_ERROR;
1014}
1015
1016static ssize_t extractPlatformBuildVersion(AssetManager& assets, Bundle* bundle) {
1017 int32_t cookie = getPlatformAssetCookie(assets);
1018 if (cookie == 0) {
Adam Lesinski82a2dd82014-09-17 18:34:15 -07001019 // No platform was loaded.
1020 return NO_ERROR;
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001021 }
1022
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001023 Asset* asset = assets.openNonAsset(cookie, "AndroidManifest.xml", Asset::ACCESS_STREAMING);
1024 if (asset == NULL) {
1025 fprintf(stderr, "ERROR: Platform AndroidManifest.xml not found\n");
1026 return UNKNOWN_ERROR;
1027 }
1028
1029 ssize_t result = NO_ERROR;
Adam Lesinski193ed742016-08-15 14:19:46 -07001030
1031 // Create a new scope so that ResXMLTree is destroyed before we delete the memory over
1032 // which it iterates (asset).
1033 {
1034 ResXMLTree tree;
1035 if (tree.setTo(asset->getBuffer(true), asset->getLength()) != NO_ERROR) {
1036 fprintf(stderr, "ERROR: Platform AndroidManifest.xml is corrupt\n");
1037 result = UNKNOWN_ERROR;
1038 } else {
1039 result = extractPlatformBuildVersion(tree, bundle);
1040 }
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001041 }
1042
1043 delete asset;
1044 return result;
1045}
1046
Adam Lesinski282e1812014-01-23 18:17:42 -08001047#define ASSIGN_IT(n) \
1048 do { \
1049 ssize_t index = resources->indexOfKey(String8(#n)); \
1050 if (index >= 0) { \
1051 n ## s = resources->valueAt(index); \
1052 } \
1053 } while (0)
1054
1055status_t updatePreProcessedCache(Bundle* bundle)
1056{
1057 #if BENCHMARK
1058 fprintf(stdout, "BENCHMARK: Starting PNG PreProcessing \n");
1059 long startPNGTime = clock();
1060 #endif /* BENCHMARK */
1061
1062 String8 source(bundle->getResourceSourceDirs()[0]);
1063 String8 dest(bundle->getCrunchedOutputDir());
1064
1065 FileFinder* ff = new SystemFileFinder();
1066 CrunchCache cc(source,dest,ff);
1067
1068 CacheUpdater* cu = new SystemCacheUpdater(bundle);
1069 size_t numFiles = cc.crunch(cu);
1070
1071 if (bundle->getVerbose())
1072 fprintf(stdout, "Crunched %d PNG files to update cache\n", (int)numFiles);
1073
1074 delete ff;
1075 delete cu;
1076
1077 #if BENCHMARK
1078 fprintf(stdout, "BENCHMARK: End PNG PreProcessing. Time Elapsed: %f ms \n"
1079 ,(clock() - startPNGTime)/1000.0);
1080 #endif /* BENCHMARK */
1081 return 0;
1082}
1083
Jeff Sharkey2cfc8482014-07-09 16:10:16 -07001084status_t generateAndroidManifestForSplit(Bundle* bundle, const sp<AaptAssets>& assets,
1085 const sp<ApkSplit>& split, sp<AaptFile>& outFile, ResourceTable* table) {
Adam Lesinskifab50872014-04-16 14:40:42 -07001086 const String8 filename("AndroidManifest.xml");
1087 const String16 androidPrefix("android");
1088 const String16 androidNSUri("http://schemas.android.com/apk/res/android");
1089 sp<XMLNode> root = XMLNode::newNamespace(filename, androidPrefix, androidNSUri);
1090
1091 // Build the <manifest> tag
1092 sp<XMLNode> manifest = XMLNode::newElement(filename, String16(), String16("manifest"));
1093
Jeff Sharkey2cfc8482014-07-09 16:10:16 -07001094 // Add the 'package' attribute which is set to the package name.
1095 const char* packageName = assets->getPackage();
1096 const char* manifestPackageNameOverride = bundle->getManifestPackageNameOverride();
1097 if (manifestPackageNameOverride != NULL) {
1098 packageName = manifestPackageNameOverride;
1099 }
1100 manifest->addAttribute(String16(), String16("package"), String16(packageName));
1101
1102 // Add the 'versionCode' attribute which is set to the original version code.
1103 if (!addTagAttribute(manifest, RESOURCES_ANDROID_NAMESPACE, "versionCode",
1104 bundle->getVersionCode(), true, true)) {
1105 return UNKNOWN_ERROR;
1106 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001107
Adam Lesinski54de2982014-12-16 09:16:26 -08001108 // Add the 'revisionCode' attribute, which is set to the original revisionCode.
1109 if (bundle->getRevisionCode().size() > 0) {
1110 if (!addTagAttribute(manifest, RESOURCES_ANDROID_NAMESPACE, "revisionCode",
1111 bundle->getRevisionCode().string(), true, true)) {
1112 return UNKNOWN_ERROR;
1113 }
1114 }
1115
Adam Lesinskifab50872014-04-16 14:40:42 -07001116 // Add the 'split' attribute which describes the configurations included.
Adam Lesinski62408402014-08-07 21:26:53 -07001117 String8 splitName("config.");
1118 splitName.append(split->getPackageSafeName());
Adam Lesinskifab50872014-04-16 14:40:42 -07001119 manifest->addAttribute(String16(), String16("split"), String16(splitName));
1120
1121 // Build an empty <application> tag (required).
1122 sp<XMLNode> app = XMLNode::newElement(filename, String16(), String16("application"));
Jeff Sharkey78a13012014-07-15 20:18:34 -07001123
1124 // Add the 'hasCode' attribute which is never true for resource splits.
1125 if (!addTagAttribute(app, RESOURCES_ANDROID_NAMESPACE, "hasCode",
1126 "false", true, true)) {
1127 return UNKNOWN_ERROR;
1128 }
1129
Adam Lesinskifab50872014-04-16 14:40:42 -07001130 manifest->addChild(app);
1131 root->addChild(manifest);
1132
Adam Lesinskie572c012014-09-19 15:10:04 -07001133 int err = compileXmlFile(bundle, assets, String16(), root, outFile, table);
Jeff Sharkey2cfc8482014-07-09 16:10:16 -07001134 if (err < NO_ERROR) {
Adam Lesinskifab50872014-04-16 14:40:42 -07001135 return err;
1136 }
1137 outFile->setCompressionMethod(ZipEntry::kCompressDeflated);
1138 return NO_ERROR;
1139}
1140
1141status_t buildResources(Bundle* bundle, const sp<AaptAssets>& assets, sp<ApkBuilder>& builder)
Adam Lesinski282e1812014-01-23 18:17:42 -08001142{
1143 // First, look for a package file to parse. This is required to
1144 // be able to generate the resource information.
1145 sp<AaptGroup> androidManifestFile =
1146 assets->getFiles().valueFor(String8("AndroidManifest.xml"));
1147 if (androidManifestFile == NULL) {
1148 fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n");
1149 return UNKNOWN_ERROR;
1150 }
1151
1152 status_t err = parsePackage(bundle, assets, androidManifestFile);
1153 if (err != NO_ERROR) {
1154 return err;
1155 }
1156
Andreas Gampe2412f842014-09-30 20:55:57 -07001157 if (kIsDebug) {
1158 printf("Creating resources for package %s\n", assets->getPackage().string());
1159 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001160
Adam Lesinski78713992015-12-07 14:02:15 -08001161 // Set the private symbols package if it was declared.
1162 // This can also be declared in XML as <private-symbols name="package" />
1163 if (bundle->getPrivateSymbolsPackage().size() != 0) {
1164 assets->setSymbolsPrivatePackage(bundle->getPrivateSymbolsPackage());
1165 }
1166
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001167 ResourceTable::PackageType packageType = ResourceTable::App;
1168 if (bundle->getBuildSharedLibrary()) {
1169 packageType = ResourceTable::SharedLibrary;
1170 } else if (bundle->getExtending()) {
1171 packageType = ResourceTable::System;
1172 } else if (!bundle->getFeatureOfPackage().isEmpty()) {
1173 packageType = ResourceTable::AppFeature;
1174 }
1175
1176 ResourceTable table(bundle, String16(assets->getPackage()), packageType);
Adam Lesinski282e1812014-01-23 18:17:42 -08001177 err = table.addIncludedResources(bundle, assets);
1178 if (err != NO_ERROR) {
1179 return err;
1180 }
1181
Andreas Gampe2412f842014-09-30 20:55:57 -07001182 if (kIsDebug) {
1183 printf("Found %d included resource packages\n", (int)table.size());
1184 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001185
1186 // Standard flags for compiled XML and optional UTF-8 encoding
1187 int xmlFlags = XML_COMPILE_STANDARD_RESOURCE;
1188
1189 /* Only enable UTF-8 if the caller of aapt didn't specifically
1190 * request UTF-16 encoding and the parameters of this package
1191 * allow UTF-8 to be used.
1192 */
1193 if (!bundle->getUTF16StringsOption()) {
1194 xmlFlags |= XML_COMPILE_UTF8;
1195 }
1196
1197 // --------------------------------------------------------------
1198 // First, gather all resource information.
1199 // --------------------------------------------------------------
1200
1201 // resType -> leafName -> group
1202 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
1203 new KeyedVector<String8, sp<ResourceTypeSet> >;
1204 collect_files(assets, resources);
1205
1206 sp<ResourceTypeSet> drawables;
1207 sp<ResourceTypeSet> layouts;
1208 sp<ResourceTypeSet> anims;
1209 sp<ResourceTypeSet> animators;
1210 sp<ResourceTypeSet> interpolators;
1211 sp<ResourceTypeSet> transitions;
Adam Lesinski282e1812014-01-23 18:17:42 -08001212 sp<ResourceTypeSet> xmls;
1213 sp<ResourceTypeSet> raws;
1214 sp<ResourceTypeSet> colors;
1215 sp<ResourceTypeSet> menus;
1216 sp<ResourceTypeSet> mipmaps;
Adam Lesinski9bbe7872017-01-24 13:52:04 -08001217 sp<ResourceTypeSet> fonts;
Adam Lesinski282e1812014-01-23 18:17:42 -08001218
1219 ASSIGN_IT(drawable);
1220 ASSIGN_IT(layout);
1221 ASSIGN_IT(anim);
1222 ASSIGN_IT(animator);
1223 ASSIGN_IT(interpolator);
1224 ASSIGN_IT(transition);
Adam Lesinski282e1812014-01-23 18:17:42 -08001225 ASSIGN_IT(xml);
1226 ASSIGN_IT(raw);
1227 ASSIGN_IT(color);
1228 ASSIGN_IT(menu);
1229 ASSIGN_IT(mipmap);
Adam Lesinski9bbe7872017-01-24 13:52:04 -08001230 ASSIGN_IT(font);
Adam Lesinski282e1812014-01-23 18:17:42 -08001231
1232 assets->setResources(resources);
1233 // now go through any resource overlays and collect their files
1234 sp<AaptAssets> current = assets->getOverlay();
1235 while(current.get()) {
1236 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
1237 new KeyedVector<String8, sp<ResourceTypeSet> >;
1238 current->setResources(resources);
1239 collect_files(current, resources);
1240 current = current->getOverlay();
1241 }
1242 // apply the overlay files to the base set
1243 if (!applyFileOverlay(bundle, assets, &drawables, "drawable") ||
1244 !applyFileOverlay(bundle, assets, &layouts, "layout") ||
1245 !applyFileOverlay(bundle, assets, &anims, "anim") ||
1246 !applyFileOverlay(bundle, assets, &animators, "animator") ||
1247 !applyFileOverlay(bundle, assets, &interpolators, "interpolator") ||
1248 !applyFileOverlay(bundle, assets, &transitions, "transition") ||
Adam Lesinski282e1812014-01-23 18:17:42 -08001249 !applyFileOverlay(bundle, assets, &xmls, "xml") ||
1250 !applyFileOverlay(bundle, assets, &raws, "raw") ||
1251 !applyFileOverlay(bundle, assets, &colors, "color") ||
1252 !applyFileOverlay(bundle, assets, &menus, "menu") ||
Adam Lesinski9bbe7872017-01-24 13:52:04 -08001253 !applyFileOverlay(bundle, assets, &fonts, "font") ||
Adam Lesinski282e1812014-01-23 18:17:42 -08001254 !applyFileOverlay(bundle, assets, &mipmaps, "mipmap")) {
1255 return UNKNOWN_ERROR;
1256 }
1257
1258 bool hasErrors = false;
1259
1260 if (drawables != NULL) {
1261 if (bundle->getOutputAPKFile() != NULL) {
1262 err = preProcessImages(bundle, assets, drawables, "drawable");
1263 }
1264 if (err == NO_ERROR) {
1265 err = makeFileResources(bundle, assets, &table, drawables, "drawable");
1266 if (err != NO_ERROR) {
1267 hasErrors = true;
1268 }
1269 } else {
1270 hasErrors = true;
1271 }
1272 }
1273
1274 if (mipmaps != NULL) {
1275 if (bundle->getOutputAPKFile() != NULL) {
1276 err = preProcessImages(bundle, assets, mipmaps, "mipmap");
1277 }
1278 if (err == NO_ERROR) {
1279 err = makeFileResources(bundle, assets, &table, mipmaps, "mipmap");
1280 if (err != NO_ERROR) {
1281 hasErrors = true;
1282 }
1283 } else {
1284 hasErrors = true;
1285 }
1286 }
1287
Adam Lesinski9bbe7872017-01-24 13:52:04 -08001288 if (fonts != NULL) {
1289 err = makeFileResources(bundle, assets, &table, fonts, "font");
1290 if (err != NO_ERROR) {
1291 hasErrors = true;
1292 }
1293 }
1294
Adam Lesinski282e1812014-01-23 18:17:42 -08001295 if (layouts != NULL) {
1296 err = makeFileResources(bundle, assets, &table, layouts, "layout");
1297 if (err != NO_ERROR) {
1298 hasErrors = true;
1299 }
1300 }
1301
1302 if (anims != NULL) {
1303 err = makeFileResources(bundle, assets, &table, anims, "anim");
1304 if (err != NO_ERROR) {
1305 hasErrors = true;
1306 }
1307 }
1308
1309 if (animators != NULL) {
1310 err = makeFileResources(bundle, assets, &table, animators, "animator");
1311 if (err != NO_ERROR) {
1312 hasErrors = true;
1313 }
1314 }
1315
1316 if (transitions != NULL) {
1317 err = makeFileResources(bundle, assets, &table, transitions, "transition");
1318 if (err != NO_ERROR) {
1319 hasErrors = true;
1320 }
1321 }
1322
Adam Lesinski282e1812014-01-23 18:17:42 -08001323 if (interpolators != NULL) {
1324 err = makeFileResources(bundle, assets, &table, interpolators, "interpolator");
1325 if (err != NO_ERROR) {
1326 hasErrors = true;
1327 }
1328 }
1329
1330 if (xmls != NULL) {
1331 err = makeFileResources(bundle, assets, &table, xmls, "xml");
1332 if (err != NO_ERROR) {
1333 hasErrors = true;
1334 }
1335 }
1336
1337 if (raws != NULL) {
1338 err = makeFileResources(bundle, assets, &table, raws, "raw");
1339 if (err != NO_ERROR) {
1340 hasErrors = true;
1341 }
1342 }
1343
1344 // compile resources
1345 current = assets;
1346 while(current.get()) {
1347 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
1348 current->getResources();
1349
1350 ssize_t index = resources->indexOfKey(String8("values"));
1351 if (index >= 0) {
1352 ResourceDirIterator it(resources->valueAt(index), String8("values"));
1353 ssize_t res;
1354 while ((res=it.next()) == NO_ERROR) {
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -07001355 const sp<AaptFile>& file = it.getFile();
Adam Lesinski282e1812014-01-23 18:17:42 -08001356 res = compileResourceFile(bundle, assets, file, it.getParams(),
1357 (current!=assets), &table);
1358 if (res != NO_ERROR) {
1359 hasErrors = true;
1360 }
1361 }
1362 }
1363 current = current->getOverlay();
1364 }
1365
1366 if (colors != NULL) {
1367 err = makeFileResources(bundle, assets, &table, colors, "color");
1368 if (err != NO_ERROR) {
1369 hasErrors = true;
1370 }
1371 }
1372
1373 if (menus != NULL) {
1374 err = makeFileResources(bundle, assets, &table, menus, "menu");
1375 if (err != NO_ERROR) {
1376 hasErrors = true;
1377 }
1378 }
1379
Adam Lesinski526d73b2016-07-18 17:01:14 -07001380 if (hasErrors) {
1381 return UNKNOWN_ERROR;
1382 }
1383
Adam Lesinski282e1812014-01-23 18:17:42 -08001384 // --------------------------------------------------------------------
1385 // Assignment of resource IDs and initial generation of resource table.
1386 // --------------------------------------------------------------------
1387
1388 if (table.hasResources()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001389 err = table.assignResourceIds();
1390 if (err < NO_ERROR) {
1391 return err;
1392 }
1393 }
1394
1395 // --------------------------------------------------------------
1396 // Finally, we can now we can compile XML files, which may reference
1397 // resources.
1398 // --------------------------------------------------------------
1399
1400 if (layouts != NULL) {
1401 ResourceDirIterator it(layouts, String8("layout"));
1402 while ((err=it.next()) == NO_ERROR) {
1403 String8 src = it.getFile()->getPrintableSource();
Adam Lesinskie572c012014-09-19 15:10:04 -07001404 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1405 it.getFile(), &table, xmlFlags);
Adam Lesinskic7614e52017-03-16 16:54:23 -07001406 // Only verify IDs if there was no error and the file is non-empty.
1407 if (err == NO_ERROR && it.getFile()->hasData()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001408 ResXMLTree block;
1409 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
1410 checkForIds(src, block);
1411 } else {
1412 hasErrors = true;
1413 }
1414 }
1415
1416 if (err < NO_ERROR) {
1417 hasErrors = true;
1418 }
1419 err = NO_ERROR;
1420 }
1421
1422 if (anims != NULL) {
1423 ResourceDirIterator it(anims, String8("anim"));
1424 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001425 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1426 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001427 if (err != NO_ERROR) {
1428 hasErrors = true;
1429 }
1430 }
1431
1432 if (err < NO_ERROR) {
1433 hasErrors = true;
1434 }
1435 err = NO_ERROR;
1436 }
1437
1438 if (animators != NULL) {
1439 ResourceDirIterator it(animators, String8("animator"));
1440 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001441 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1442 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001443 if (err != NO_ERROR) {
1444 hasErrors = true;
1445 }
1446 }
1447
1448 if (err < NO_ERROR) {
1449 hasErrors = true;
1450 }
1451 err = NO_ERROR;
1452 }
1453
1454 if (interpolators != NULL) {
1455 ResourceDirIterator it(interpolators, String8("interpolator"));
1456 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001457 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1458 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001459 if (err != NO_ERROR) {
1460 hasErrors = true;
1461 }
1462 }
1463
1464 if (err < NO_ERROR) {
1465 hasErrors = true;
1466 }
1467 err = NO_ERROR;
1468 }
1469
1470 if (transitions != NULL) {
1471 ResourceDirIterator it(transitions, String8("transition"));
1472 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001473 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1474 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001475 if (err != NO_ERROR) {
1476 hasErrors = true;
1477 }
1478 }
1479
1480 if (err < NO_ERROR) {
1481 hasErrors = true;
1482 }
1483 err = NO_ERROR;
1484 }
1485
Adam Lesinski282e1812014-01-23 18:17:42 -08001486 if (xmls != NULL) {
1487 ResourceDirIterator it(xmls, String8("xml"));
1488 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001489 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1490 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001491 if (err != NO_ERROR) {
1492 hasErrors = true;
1493 }
1494 }
1495
1496 if (err < NO_ERROR) {
1497 hasErrors = true;
1498 }
1499 err = NO_ERROR;
1500 }
1501
1502 if (drawables != NULL) {
Adam Lesinskifab50872014-04-16 14:40:42 -07001503 ResourceDirIterator it(drawables, String8("drawable"));
1504 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001505 err = postProcessImage(bundle, assets, &table, it.getFile());
Adam Lesinskifab50872014-04-16 14:40:42 -07001506 if (err != NO_ERROR) {
1507 hasErrors = true;
1508 }
1509 }
1510
1511 if (err < NO_ERROR) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001512 hasErrors = true;
1513 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001514 err = NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001515 }
1516
Adam Lesinski2d6fa032017-03-10 18:42:32 -08001517 if (mipmaps != NULL) {
1518 ResourceDirIterator it(mipmaps, String8("mipmap"));
1519 while ((err=it.next()) == NO_ERROR) {
1520 err = postProcessImage(bundle, assets, &table, it.getFile());
1521 if (err != NO_ERROR) {
1522 hasErrors = true;
1523 }
1524 }
1525
1526 if (err < NO_ERROR) {
1527 hasErrors = true;
1528 }
1529 err = NO_ERROR;
1530 }
1531
Adam Lesinski282e1812014-01-23 18:17:42 -08001532 if (colors != NULL) {
1533 ResourceDirIterator it(colors, String8("color"));
1534 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001535 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1536 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001537 if (err != NO_ERROR) {
1538 hasErrors = true;
1539 }
1540 }
1541
1542 if (err < NO_ERROR) {
1543 hasErrors = true;
1544 }
1545 err = NO_ERROR;
1546 }
1547
1548 if (menus != NULL) {
1549 ResourceDirIterator it(menus, String8("menu"));
1550 while ((err=it.next()) == NO_ERROR) {
1551 String8 src = it.getFile()->getPrintableSource();
Adam Lesinskie572c012014-09-19 15:10:04 -07001552 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1553 it.getFile(), &table, xmlFlags);
Adam Lesinskic7614e52017-03-16 16:54:23 -07001554 if (err == NO_ERROR && it.getFile()->hasData()) {
Adam Lesinskifab50872014-04-16 14:40:42 -07001555 ResXMLTree block;
1556 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
1557 checkForIds(src, block);
1558 } else {
Adam Lesinski282e1812014-01-23 18:17:42 -08001559 hasErrors = true;
1560 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001561 }
1562
1563 if (err < NO_ERROR) {
1564 hasErrors = true;
1565 }
1566 err = NO_ERROR;
1567 }
1568
Adam Lesinski9bbe7872017-01-24 13:52:04 -08001569 if (fonts != NULL) {
1570 ResourceDirIterator it(fonts, String8("font"));
1571 while ((err=it.next()) == NO_ERROR) {
1572 // fonts can be resources other than xml.
1573 if (it.getFile()->getPath().getPathExtension() == ".xml") {
1574 String8 src = it.getFile()->getPrintableSource();
1575 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1576 it.getFile(), &table, xmlFlags);
1577 if (err != NO_ERROR) {
1578 hasErrors = true;
1579 }
1580 }
1581 }
1582
1583 if (err < NO_ERROR) {
1584 hasErrors = true;
1585 }
1586 err = NO_ERROR;
1587 }
1588
Adam Lesinskie572c012014-09-19 15:10:04 -07001589 // Now compile any generated resources.
1590 std::queue<CompileResourceWorkItem>& workQueue = table.getWorkQueue();
1591 while (!workQueue.empty()) {
1592 CompileResourceWorkItem& workItem = workQueue.front();
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07001593 int xmlCompilationFlags = xmlFlags | XML_COMPILE_PARSE_VALUES
1594 | XML_COMPILE_ASSIGN_ATTRIBUTE_IDS;
1595 if (!workItem.needsCompiling) {
1596 xmlCompilationFlags &= ~XML_COMPILE_ASSIGN_ATTRIBUTE_IDS;
1597 xmlCompilationFlags &= ~XML_COMPILE_PARSE_VALUES;
1598 }
1599 err = compileXmlFile(bundle, assets, workItem.resourceName, workItem.xmlRoot,
1600 workItem.file, &table, xmlCompilationFlags);
1601
Adam Lesinskic7614e52017-03-16 16:54:23 -07001602 if (err == NO_ERROR && workItem.file->hasData()) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001603 assets->addResource(workItem.resPath.getPathLeaf(),
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07001604 workItem.resPath,
1605 workItem.file,
1606 workItem.file->getResourceType());
Adam Lesinskie572c012014-09-19 15:10:04 -07001607 } else {
1608 hasErrors = true;
1609 }
1610 workQueue.pop();
1611 }
1612
Adam Lesinski282e1812014-01-23 18:17:42 -08001613 if (table.validateLocalizations()) {
1614 hasErrors = true;
1615 }
1616
1617 if (hasErrors) {
1618 return UNKNOWN_ERROR;
1619 }
1620
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001621 // If we're not overriding the platform build versions,
1622 // extract them from the platform APK.
1623 if (packageType != ResourceTable::System &&
1624 (bundle->getPlatformBuildVersionCode() == "" ||
1625 bundle->getPlatformBuildVersionName() == "")) {
1626 err = extractPlatformBuildVersion(assets->getAssetManager(), bundle);
1627 if (err != NO_ERROR) {
1628 return UNKNOWN_ERROR;
1629 }
1630 }
1631
Adam Lesinski282e1812014-01-23 18:17:42 -08001632 const sp<AaptFile> manifestFile(androidManifestFile->getFiles().valueAt(0));
1633 String8 manifestPath(manifestFile->getPrintableSource());
1634
1635 // Generate final compiled manifest file.
1636 manifestFile->clearData();
1637 sp<XMLNode> manifestTree = XMLNode::parse(manifestFile);
1638 if (manifestTree == NULL) {
1639 return UNKNOWN_ERROR;
1640 }
1641 err = massageManifest(bundle, manifestTree);
1642 if (err < NO_ERROR) {
1643 return err;
1644 }
Adam Lesinskie572c012014-09-19 15:10:04 -07001645 err = compileXmlFile(bundle, assets, String16(), manifestTree, manifestFile, &table);
Adam Lesinski282e1812014-01-23 18:17:42 -08001646 if (err < NO_ERROR) {
1647 return err;
1648 }
1649
Adam Lesinski82a2dd82014-09-17 18:34:15 -07001650 if (table.modifyForCompat(bundle) != NO_ERROR) {
1651 return UNKNOWN_ERROR;
1652 }
1653
Adam Lesinski282e1812014-01-23 18:17:42 -08001654 //block.restart();
1655 //printXMLBlock(&block);
1656
1657 // --------------------------------------------------------------
1658 // Generate the final resource table.
1659 // Re-flatten because we may have added new resource IDs
1660 // --------------------------------------------------------------
1661
Adam Lesinskide7de472014-11-03 12:03:08 -08001662
Adam Lesinski282e1812014-01-23 18:17:42 -08001663 ResTable finalResTable;
1664 sp<AaptFile> resFile;
1665
1666 if (table.hasResources()) {
1667 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
Adrian Roos58922482015-06-01 17:59:41 -07001668 err = table.addSymbols(symbols, bundle->getSkipSymbolsWithoutDefaultLocalization());
Adam Lesinski282e1812014-01-23 18:17:42 -08001669 if (err < NO_ERROR) {
1670 return err;
1671 }
1672
Adam Lesinskide7de472014-11-03 12:03:08 -08001673 KeyedVector<Symbol, Vector<SymbolDefinition> > densityVaryingResources;
1674 if (builder->getSplits().size() > 1) {
1675 // Only look for density varying resources if we're generating
1676 // splits.
1677 table.getDensityVaryingResources(densityVaryingResources);
1678 }
1679
Adam Lesinskifab50872014-04-16 14:40:42 -07001680 Vector<sp<ApkSplit> >& splits = builder->getSplits();
1681 const size_t numSplits = splits.size();
1682 for (size_t i = 0; i < numSplits; i++) {
1683 sp<ApkSplit>& split = splits.editItemAt(i);
1684 sp<AaptFile> flattenedTable = new AaptFile(String8("resources.arsc"),
1685 AaptGroupEntry(), String8());
Adam Lesinski27f69f42014-08-21 13:19:12 -07001686 err = table.flatten(bundle, split->getResourceFilter(),
1687 flattenedTable, split->isBase());
Adam Lesinskifab50872014-04-16 14:40:42 -07001688 if (err != NO_ERROR) {
1689 fprintf(stderr, "Failed to generate resource table for split '%s'\n",
1690 split->getPrintableName().string());
1691 return err;
1692 }
1693 split->addEntry(String8("resources.arsc"), flattenedTable);
Adam Lesinski282e1812014-01-23 18:17:42 -08001694
Adam Lesinskifab50872014-04-16 14:40:42 -07001695 if (split->isBase()) {
1696 resFile = flattenedTable;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07001697 err = finalResTable.add(flattenedTable->getData(), flattenedTable->getSize());
1698 if (err != NO_ERROR) {
1699 fprintf(stderr, "Generated resource table is corrupt.\n");
1700 return err;
1701 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001702 } else {
Adam Lesinskide7de472014-11-03 12:03:08 -08001703 ResTable resTable;
1704 err = resTable.add(flattenedTable->getData(), flattenedTable->getSize());
1705 if (err != NO_ERROR) {
1706 fprintf(stderr, "Generated resource table for split '%s' is corrupt.\n",
1707 split->getPrintableName().string());
1708 return err;
1709 }
1710
1711 bool hasError = false;
1712 const std::set<ConfigDescription>& splitConfigs = split->getConfigs();
1713 for (std::set<ConfigDescription>::const_iterator iter = splitConfigs.begin();
1714 iter != splitConfigs.end();
1715 ++iter) {
1716 const ConfigDescription& config = *iter;
1717 if (AaptConfig::isDensityOnly(config)) {
1718 // Each density only split must contain all
1719 // density only resources.
1720 Res_value val;
1721 resTable.setParameters(&config);
1722 const size_t densityVaryingResourceCount = densityVaryingResources.size();
1723 for (size_t k = 0; k < densityVaryingResourceCount; k++) {
1724 const Symbol& symbol = densityVaryingResources.keyAt(k);
1725 ssize_t block = resTable.getResource(symbol.id, &val, true);
1726 if (block < 0) {
1727 // Maybe it's in the base?
1728 finalResTable.setParameters(&config);
1729 block = finalResTable.getResource(symbol.id, &val, true);
1730 }
1731
1732 if (block < 0) {
1733 hasError = true;
1734 SourcePos().error("%s has no definition for density split '%s'",
1735 symbol.toString().string(), config.toString().string());
1736
1737 if (bundle->getVerbose()) {
1738 const Vector<SymbolDefinition>& defs = densityVaryingResources[k];
1739 const size_t defCount = std::min(size_t(5), defs.size());
1740 for (size_t d = 0; d < defCount; d++) {
1741 const SymbolDefinition& def = defs[d];
1742 def.source.error("%s has definition for %s",
1743 symbol.toString().string(), def.config.toString().string());
1744 }
1745
1746 if (defCount < defs.size()) {
1747 SourcePos().error("and %d more ...", (int) (defs.size() - defCount));
1748 }
1749 }
1750 }
1751 }
1752 }
1753 }
1754
1755 if (hasError) {
1756 return UNKNOWN_ERROR;
1757 }
1758
1759 // Generate the AndroidManifest for this split.
Adam Lesinskifab50872014-04-16 14:40:42 -07001760 sp<AaptFile> generatedManifest = new AaptFile(String8("AndroidManifest.xml"),
1761 AaptGroupEntry(), String8());
Jeff Sharkey2cfc8482014-07-09 16:10:16 -07001762 err = generateAndroidManifestForSplit(bundle, assets, split,
1763 generatedManifest, &table);
Adam Lesinskifab50872014-04-16 14:40:42 -07001764 if (err != NO_ERROR) {
1765 fprintf(stderr, "Failed to generate AndroidManifest.xml for split '%s'\n",
1766 split->getPrintableName().string());
1767 return err;
1768 }
1769 split->addEntry(String8("AndroidManifest.xml"), generatedManifest);
1770 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001771 }
1772
1773 if (bundle->getPublicOutputFile()) {
1774 FILE* fp = fopen(bundle->getPublicOutputFile(), "w+");
1775 if (fp == NULL) {
1776 fprintf(stderr, "ERROR: Unable to open public definitions output file %s: %s\n",
1777 (const char*)bundle->getPublicOutputFile(), strerror(errno));
1778 return UNKNOWN_ERROR;
1779 }
1780 if (bundle->getVerbose()) {
1781 printf(" Writing public definitions to %s.\n", bundle->getPublicOutputFile());
1782 }
1783 table.writePublicDefinitions(String16(assets->getPackage()), fp);
1784 fclose(fp);
1785 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001786
1787 if (finalResTable.getTableCount() == 0 || resFile == NULL) {
1788 fprintf(stderr, "No resource table was generated.\n");
1789 return UNKNOWN_ERROR;
1790 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001791 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001792
Adam Lesinski282e1812014-01-23 18:17:42 -08001793 // Perform a basic validation of the manifest file. This time we
1794 // parse it with the comments intact, so that we can use them to
1795 // generate java docs... so we are not going to write this one
1796 // back out to the final manifest data.
1797 sp<AaptFile> outManifestFile = new AaptFile(manifestFile->getSourceFile(),
1798 manifestFile->getGroupEntry(),
1799 manifestFile->getResourceType());
Adam Lesinskie572c012014-09-19 15:10:04 -07001800 err = compileXmlFile(bundle, assets, String16(), manifestFile,
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07001801 outManifestFile, &table, XML_COMPILE_STANDARD_RESOURCE & ~XML_COMPILE_STRIP_COMMENTS);
Adam Lesinski282e1812014-01-23 18:17:42 -08001802 if (err < NO_ERROR) {
1803 return err;
1804 }
1805 ResXMLTree block;
1806 block.setTo(outManifestFile->getData(), outManifestFile->getSize(), true);
1807 String16 manifest16("manifest");
1808 String16 permission16("permission");
1809 String16 permission_group16("permission-group");
1810 String16 uses_permission16("uses-permission");
1811 String16 instrumentation16("instrumentation");
1812 String16 application16("application");
1813 String16 provider16("provider");
1814 String16 service16("service");
1815 String16 receiver16("receiver");
1816 String16 activity16("activity");
1817 String16 action16("action");
1818 String16 category16("category");
1819 String16 data16("scheme");
Adam Lesinskid3edfde2014-08-08 17:32:44 -07001820 String16 feature_group16("feature-group");
1821 String16 uses_feature16("uses-feature");
Adam Lesinski282e1812014-01-23 18:17:42 -08001822 const char* packageIdentChars = "abcdefghijklmnopqrstuvwxyz"
1823 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789";
1824 const char* packageIdentCharsWithTheStupid = "abcdefghijklmnopqrstuvwxyz"
1825 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
1826 const char* classIdentChars = "abcdefghijklmnopqrstuvwxyz"
1827 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789$";
1828 const char* processIdentChars = "abcdefghijklmnopqrstuvwxyz"
1829 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:";
1830 const char* authoritiesIdentChars = "abcdefghijklmnopqrstuvwxyz"
1831 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-:;";
1832 const char* typeIdentChars = "abcdefghijklmnopqrstuvwxyz"
1833 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:-/*+";
1834 const char* schemeIdentChars = "abcdefghijklmnopqrstuvwxyz"
1835 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
1836 ResXMLTree::event_code_t code;
1837 sp<AaptSymbols> permissionSymbols;
1838 sp<AaptSymbols> permissionGroupSymbols;
1839 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1840 && code > ResXMLTree::BAD_DOCUMENT) {
1841 if (code == ResXMLTree::START_TAG) {
1842 size_t len;
1843 if (block.getElementNamespace(&len) != NULL) {
1844 continue;
1845 }
1846 if (strcmp16(block.getElementName(&len), manifest16.string()) == 0) {
1847 if (validateAttr(manifestPath, finalResTable, block, NULL, "package",
1848 packageIdentChars, true) != ATTR_OKAY) {
1849 hasErrors = true;
1850 }
1851 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1852 "sharedUserId", packageIdentChars, false) != ATTR_OKAY) {
1853 hasErrors = true;
1854 }
1855 } else if (strcmp16(block.getElementName(&len), permission16.string()) == 0
1856 || strcmp16(block.getElementName(&len), permission_group16.string()) == 0) {
1857 const bool isGroup = strcmp16(block.getElementName(&len),
1858 permission_group16.string()) == 0;
1859 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1860 "name", isGroup ? packageIdentCharsWithTheStupid
1861 : packageIdentChars, true) != ATTR_OKAY) {
1862 hasErrors = true;
1863 }
1864 SourcePos srcPos(manifestPath, block.getLineNumber());
1865 sp<AaptSymbols> syms;
1866 if (!isGroup) {
1867 syms = permissionSymbols;
1868 if (syms == NULL) {
1869 sp<AaptSymbols> symbols =
1870 assets->getSymbolsFor(String8("Manifest"));
1871 syms = permissionSymbols = symbols->addNestedSymbol(
1872 String8("permission"), srcPos);
1873 }
1874 } else {
1875 syms = permissionGroupSymbols;
1876 if (syms == NULL) {
1877 sp<AaptSymbols> symbols =
1878 assets->getSymbolsFor(String8("Manifest"));
1879 syms = permissionGroupSymbols = symbols->addNestedSymbol(
1880 String8("permission_group"), srcPos);
1881 }
1882 }
1883 size_t len;
1884 ssize_t index = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "name");
Dan Albertf348c152014-09-08 18:28:00 -07001885 const char16_t* id = block.getAttributeStringValue(index, &len);
Adam Lesinski282e1812014-01-23 18:17:42 -08001886 if (id == NULL) {
1887 fprintf(stderr, "%s:%d: missing name attribute in element <%s>.\n",
1888 manifestPath.string(), block.getLineNumber(),
1889 String8(block.getElementName(&len)).string());
1890 hasErrors = true;
1891 break;
1892 }
1893 String8 idStr(id);
1894 char* p = idStr.lockBuffer(idStr.size());
1895 char* e = p + idStr.size();
1896 bool begins_with_digit = true; // init to true so an empty string fails
1897 while (e > p) {
1898 e--;
1899 if (*e >= '0' && *e <= '9') {
1900 begins_with_digit = true;
1901 continue;
1902 }
1903 if ((*e >= 'a' && *e <= 'z') ||
1904 (*e >= 'A' && *e <= 'Z') ||
1905 (*e == '_')) {
1906 begins_with_digit = false;
1907 continue;
1908 }
1909 if (isGroup && (*e == '-')) {
1910 *e = '_';
1911 begins_with_digit = false;
1912 continue;
1913 }
1914 e++;
1915 break;
1916 }
1917 idStr.unlockBuffer();
1918 // verify that we stopped because we hit a period or
1919 // the beginning of the string, and that the
1920 // identifier didn't begin with a digit.
1921 if (begins_with_digit || (e != p && *(e-1) != '.')) {
1922 fprintf(stderr,
1923 "%s:%d: Permission name <%s> is not a valid Java symbol\n",
1924 manifestPath.string(), block.getLineNumber(), idStr.string());
1925 hasErrors = true;
1926 }
1927 syms->addStringSymbol(String8(e), idStr, srcPos);
Dan Albertf348c152014-09-08 18:28:00 -07001928 const char16_t* cmt = block.getComment(&len);
Adam Lesinski282e1812014-01-23 18:17:42 -08001929 if (cmt != NULL && *cmt != 0) {
1930 //printf("Comment of %s: %s\n", String8(e).string(),
1931 // String8(cmt).string());
1932 syms->appendComment(String8(e), String16(cmt), srcPos);
Adam Lesinski282e1812014-01-23 18:17:42 -08001933 }
1934 syms->makeSymbolPublic(String8(e), srcPos);
1935 } else if (strcmp16(block.getElementName(&len), uses_permission16.string()) == 0) {
1936 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1937 "name", packageIdentChars, true) != ATTR_OKAY) {
1938 hasErrors = true;
1939 }
1940 } else if (strcmp16(block.getElementName(&len), instrumentation16.string()) == 0) {
1941 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1942 "name", classIdentChars, true) != ATTR_OKAY) {
1943 hasErrors = true;
1944 }
1945 if (validateAttr(manifestPath, finalResTable, block,
1946 RESOURCES_ANDROID_NAMESPACE, "targetPackage",
1947 packageIdentChars, true) != ATTR_OKAY) {
1948 hasErrors = true;
1949 }
1950 } else if (strcmp16(block.getElementName(&len), application16.string()) == 0) {
1951 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1952 "name", classIdentChars, false) != ATTR_OKAY) {
1953 hasErrors = true;
1954 }
1955 if (validateAttr(manifestPath, finalResTable, block,
1956 RESOURCES_ANDROID_NAMESPACE, "permission",
1957 packageIdentChars, false) != ATTR_OKAY) {
1958 hasErrors = true;
1959 }
1960 if (validateAttr(manifestPath, finalResTable, block,
1961 RESOURCES_ANDROID_NAMESPACE, "process",
1962 processIdentChars, false) != ATTR_OKAY) {
1963 hasErrors = true;
1964 }
1965 if (validateAttr(manifestPath, finalResTable, block,
1966 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
1967 processIdentChars, false) != ATTR_OKAY) {
1968 hasErrors = true;
1969 }
1970 } else if (strcmp16(block.getElementName(&len), provider16.string()) == 0) {
1971 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1972 "name", classIdentChars, true) != ATTR_OKAY) {
1973 hasErrors = true;
1974 }
1975 if (validateAttr(manifestPath, finalResTable, block,
1976 RESOURCES_ANDROID_NAMESPACE, "authorities",
1977 authoritiesIdentChars, true) != ATTR_OKAY) {
1978 hasErrors = true;
1979 }
1980 if (validateAttr(manifestPath, finalResTable, block,
1981 RESOURCES_ANDROID_NAMESPACE, "permission",
1982 packageIdentChars, false) != ATTR_OKAY) {
1983 hasErrors = true;
1984 }
1985 if (validateAttr(manifestPath, finalResTable, block,
1986 RESOURCES_ANDROID_NAMESPACE, "process",
1987 processIdentChars, false) != ATTR_OKAY) {
1988 hasErrors = true;
1989 }
1990 } else if (strcmp16(block.getElementName(&len), service16.string()) == 0
1991 || strcmp16(block.getElementName(&len), receiver16.string()) == 0
1992 || strcmp16(block.getElementName(&len), activity16.string()) == 0) {
1993 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1994 "name", classIdentChars, true) != ATTR_OKAY) {
1995 hasErrors = true;
1996 }
1997 if (validateAttr(manifestPath, finalResTable, block,
1998 RESOURCES_ANDROID_NAMESPACE, "permission",
1999 packageIdentChars, false) != ATTR_OKAY) {
2000 hasErrors = true;
2001 }
2002 if (validateAttr(manifestPath, finalResTable, block,
2003 RESOURCES_ANDROID_NAMESPACE, "process",
2004 processIdentChars, false) != ATTR_OKAY) {
2005 hasErrors = true;
2006 }
2007 if (validateAttr(manifestPath, finalResTable, block,
2008 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
2009 processIdentChars, false) != ATTR_OKAY) {
2010 hasErrors = true;
2011 }
2012 } else if (strcmp16(block.getElementName(&len), action16.string()) == 0
2013 || strcmp16(block.getElementName(&len), category16.string()) == 0) {
2014 if (validateAttr(manifestPath, finalResTable, block,
2015 RESOURCES_ANDROID_NAMESPACE, "name",
2016 packageIdentChars, true) != ATTR_OKAY) {
2017 hasErrors = true;
2018 }
2019 } else if (strcmp16(block.getElementName(&len), data16.string()) == 0) {
2020 if (validateAttr(manifestPath, finalResTable, block,
2021 RESOURCES_ANDROID_NAMESPACE, "mimeType",
2022 typeIdentChars, true) != ATTR_OKAY) {
2023 hasErrors = true;
2024 }
2025 if (validateAttr(manifestPath, finalResTable, block,
2026 RESOURCES_ANDROID_NAMESPACE, "scheme",
2027 schemeIdentChars, true) != ATTR_OKAY) {
2028 hasErrors = true;
2029 }
Adam Lesinskid3edfde2014-08-08 17:32:44 -07002030 } else if (strcmp16(block.getElementName(&len), feature_group16.string()) == 0) {
2031 int depth = 1;
2032 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
2033 && code > ResXMLTree::BAD_DOCUMENT) {
2034 if (code == ResXMLTree::START_TAG) {
2035 depth++;
2036 if (strcmp16(block.getElementName(&len), uses_feature16.string()) == 0) {
2037 ssize_t idx = block.indexOfAttribute(
2038 RESOURCES_ANDROID_NAMESPACE, "required");
2039 if (idx < 0) {
2040 continue;
2041 }
2042
2043 int32_t data = block.getAttributeData(idx);
2044 if (data == 0) {
2045 fprintf(stderr, "%s:%d: Tag <uses-feature> can not have "
2046 "android:required=\"false\" when inside a "
2047 "<feature-group> tag.\n",
2048 manifestPath.string(), block.getLineNumber());
2049 hasErrors = true;
2050 }
2051 }
2052 } else if (code == ResXMLTree::END_TAG) {
2053 depth--;
2054 if (depth == 0) {
2055 break;
2056 }
2057 }
2058 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002059 }
2060 }
2061 }
2062
Adam Lesinskid3edfde2014-08-08 17:32:44 -07002063 if (hasErrors) {
2064 return UNKNOWN_ERROR;
2065 }
2066
Adam Lesinski282e1812014-01-23 18:17:42 -08002067 if (resFile != NULL) {
2068 // These resources are now considered to be a part of the included
2069 // resources, for others to reference.
2070 err = assets->addIncludedResources(resFile);
2071 if (err < NO_ERROR) {
2072 fprintf(stderr, "ERROR: Unable to parse generated resources, aborting.\n");
2073 return err;
2074 }
2075 }
2076
2077 return err;
2078}
2079
2080static const char* getIndentSpace(int indent)
2081{
2082static const char whitespace[] =
2083" ";
2084
2085 return whitespace + sizeof(whitespace) - 1 - indent*4;
2086}
2087
2088static String8 flattenSymbol(const String8& symbol) {
2089 String8 result(symbol);
2090 ssize_t first;
2091 if ((first = symbol.find(":", 0)) >= 0
2092 || (first = symbol.find(".", 0)) >= 0) {
2093 size_t size = symbol.size();
2094 char* buf = result.lockBuffer(size);
2095 for (size_t i = first; i < size; i++) {
2096 if (buf[i] == ':' || buf[i] == '.') {
2097 buf[i] = '_';
2098 }
2099 }
2100 result.unlockBuffer(size);
2101 }
2102 return result;
2103}
2104
2105static String8 getSymbolPackage(const String8& symbol, const sp<AaptAssets>& assets, bool pub) {
2106 ssize_t colon = symbol.find(":", 0);
2107 if (colon >= 0) {
2108 return String8(symbol.string(), colon);
2109 }
2110 return pub ? assets->getPackage() : assets->getSymbolsPrivatePackage();
2111}
2112
2113static String8 getSymbolName(const String8& symbol) {
2114 ssize_t colon = symbol.find(":", 0);
2115 if (colon >= 0) {
2116 return String8(symbol.string() + colon + 1);
2117 }
2118 return symbol;
2119}
2120
2121static String16 getAttributeComment(const sp<AaptAssets>& assets,
2122 const String8& name,
2123 String16* outTypeComment = NULL)
2124{
2125 sp<AaptSymbols> asym = assets->getSymbolsFor(String8("R"));
2126 if (asym != NULL) {
2127 //printf("Got R symbols!\n");
2128 asym = asym->getNestedSymbols().valueFor(String8("attr"));
2129 if (asym != NULL) {
2130 //printf("Got attrs symbols! comment %s=%s\n",
2131 // name.string(), String8(asym->getComment(name)).string());
2132 if (outTypeComment != NULL) {
2133 *outTypeComment = asym->getTypeComment(name);
2134 }
2135 return asym->getComment(name);
2136 }
2137 }
2138 return String16();
2139}
2140
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002141static status_t writeResourceLoadedCallbackForLayoutClasses(
2142 FILE* fp, const sp<AaptAssets>& assets,
Andreas Gampe87332a72014-10-01 22:03:58 -07002143 const sp<AaptSymbols>& symbols, int indent, bool /* includePrivate */)
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002144{
2145 String16 attr16("attr");
2146 String16 package16(assets->getPackage());
2147
2148 const char* indentStr = getIndentSpace(indent);
2149 bool hasErrors = false;
2150
2151 size_t i;
2152 size_t N = symbols->getNestedSymbols().size();
2153 for (i=0; i<N; i++) {
2154 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2155 String8 realClassName(symbols->getNestedSymbols().keyAt(i));
2156 String8 nclassName(flattenSymbol(realClassName));
2157
2158 fprintf(fp,
2159 "%sfor(int i = 0; i < styleable.%s.length; ++i) {\n"
2160 "%sstyleable.%s[i] = (styleable.%s[i] & 0x00ffffff) | (packageId << 24);\n"
2161 "%s}\n",
2162 indentStr, nclassName.string(),
2163 getIndentSpace(indent+1), nclassName.string(), nclassName.string(),
2164 indentStr);
Adam Lesinski1e4663852014-08-15 14:47:28 -07002165 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002166
Dan Alberted811ee2016-01-15 12:16:06 -08002167 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002168}
2169
2170static status_t writeResourceLoadedCallback(
2171 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2172 const sp<AaptSymbols>& symbols, const String8& className, int indent)
2173{
2174 size_t i;
2175 status_t err = NO_ERROR;
2176
2177 size_t N = symbols->getSymbols().size();
2178 for (i=0; i<N; i++) {
2179 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
Adam Lesinskieed58582015-09-10 18:43:34 -07002180 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002181 continue;
Adam Lesinski1e4663852014-08-15 14:47:28 -07002182 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002183 if (!assets->isJavaSymbol(sym, includePrivate)) {
2184 continue;
Adam Lesinski1e4663852014-08-15 14:47:28 -07002185 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002186 String8 flat_name(flattenSymbol(sym.name));
2187 fprintf(fp,
2188 "%s%s.%s = (%s.%s & 0x00ffffff) | (packageId << 24);\n",
2189 getIndentSpace(indent), className.string(), flat_name.string(),
2190 className.string(), flat_name.string());
Adam Lesinski1e4663852014-08-15 14:47:28 -07002191 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002192
2193 N = symbols->getNestedSymbols().size();
2194 for (i=0; i<N; i++) {
2195 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2196 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2197 if (nclassName == "styleable") {
2198 err = writeResourceLoadedCallbackForLayoutClasses(
2199 fp, assets, nsymbols, indent, includePrivate);
2200 } else {
2201 err = writeResourceLoadedCallback(fp, assets, includePrivate, nsymbols,
2202 nclassName, indent);
Adam Lesinski1e4663852014-08-15 14:47:28 -07002203 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002204 if (err != NO_ERROR) {
2205 return err;
2206 }
Adam Lesinski1e4663852014-08-15 14:47:28 -07002207 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002208
2209 return NO_ERROR;
Adam Lesinski1e4663852014-08-15 14:47:28 -07002210}
2211
Adam Lesinski282e1812014-01-23 18:17:42 -08002212static status_t writeLayoutClasses(
2213 FILE* fp, const sp<AaptAssets>& assets,
Adam Lesinskie8e91922014-08-06 17:41:08 -07002214 const sp<AaptSymbols>& symbols, int indent, bool includePrivate, bool nonConstantId)
Adam Lesinski282e1812014-01-23 18:17:42 -08002215{
2216 const char* indentStr = getIndentSpace(indent);
2217 if (!includePrivate) {
2218 fprintf(fp, "%s/** @doconly */\n", indentStr);
2219 }
2220 fprintf(fp, "%spublic static final class styleable {\n", indentStr);
2221 indent++;
2222
2223 String16 attr16("attr");
2224 String16 package16(assets->getPackage());
2225
2226 indentStr = getIndentSpace(indent);
2227 bool hasErrors = false;
2228
2229 size_t i;
2230 size_t N = symbols->getNestedSymbols().size();
2231 for (i=0; i<N; i++) {
2232 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2233 String8 realClassName(symbols->getNestedSymbols().keyAt(i));
2234 String8 nclassName(flattenSymbol(realClassName));
2235
2236 SortedVector<uint32_t> idents;
2237 Vector<uint32_t> origOrder;
2238 Vector<bool> publicFlags;
2239
2240 size_t a;
2241 size_t NA = nsymbols->getSymbols().size();
2242 for (a=0; a<NA; a++) {
2243 const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a));
2244 int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32
2245 ? sym.int32Val : 0;
2246 bool isPublic = true;
2247 if (code == 0) {
2248 String16 name16(sym.name);
2249 uint32_t typeSpecFlags;
2250 code = assets->getIncludedResources().identifierForName(
2251 name16.string(), name16.size(),
2252 attr16.string(), attr16.size(),
2253 package16.string(), package16.size(), &typeSpecFlags);
2254 if (code == 0) {
2255 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
2256 nclassName.string(), sym.name.string());
2257 hasErrors = true;
2258 }
2259 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
2260 }
2261 idents.add(code);
2262 origOrder.add(code);
2263 publicFlags.add(isPublic);
2264 }
2265
2266 NA = idents.size();
2267
Adam Lesinski282e1812014-01-23 18:17:42 -08002268 String16 comment = symbols->getComment(realClassName);
Jeff Browneb490d62014-06-06 19:43:42 -07002269 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002270 fprintf(fp, "%s/** ", indentStr);
2271 if (comment.size() > 0) {
2272 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002273 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002274 fprintf(fp, "%s\n", cmt.string());
Adam Lesinski282e1812014-01-23 18:17:42 -08002275 } else {
2276 fprintf(fp, "Attributes that can be used with a %s.\n", nclassName.string());
2277 }
2278 bool hasTable = false;
2279 for (a=0; a<NA; a++) {
2280 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2281 if (pos >= 0) {
2282 if (!hasTable) {
2283 hasTable = true;
2284 fprintf(fp,
2285 "%s <p>Includes the following attributes:</p>\n"
2286 "%s <table>\n"
2287 "%s <colgroup align=\"left\" />\n"
2288 "%s <colgroup align=\"left\" />\n"
2289 "%s <tr><th>Attribute</th><th>Description</th></tr>\n",
2290 indentStr,
2291 indentStr,
2292 indentStr,
2293 indentStr,
2294 indentStr);
2295 }
2296 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2297 if (!publicFlags.itemAt(a) && !includePrivate) {
2298 continue;
2299 }
2300 String8 name8(sym.name);
2301 String16 comment(sym.comment);
2302 if (comment.size() <= 0) {
2303 comment = getAttributeComment(assets, name8);
2304 }
Michael Wrightfeaf99f2016-05-06 17:16:06 +01002305 if (comment.contains(u"@removed")) {
2306 continue;
2307 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002308 if (comment.size() > 0) {
2309 const char16_t* p = comment.string();
2310 while (*p != 0 && *p != '.') {
2311 if (*p == '{') {
2312 while (*p != 0 && *p != '}') {
2313 p++;
2314 }
2315 } else {
2316 p++;
2317 }
2318 }
2319 if (*p == '.') {
2320 p++;
2321 }
2322 comment = String16(comment.string(), p-comment.string());
2323 }
2324 fprintf(fp, "%s <tr><td><code>{@link #%s_%s %s:%s}</code></td><td>%s</td></tr>\n",
2325 indentStr, nclassName.string(),
2326 flattenSymbol(name8).string(),
2327 getSymbolPackage(name8, assets, true).string(),
2328 getSymbolName(name8).string(),
2329 String8(comment).string());
2330 }
2331 }
2332 if (hasTable) {
2333 fprintf(fp, "%s </table>\n", indentStr);
2334 }
2335 for (a=0; a<NA; a++) {
2336 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2337 if (pos >= 0) {
2338 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2339 if (!publicFlags.itemAt(a) && !includePrivate) {
2340 continue;
2341 }
2342 fprintf(fp, "%s @see #%s_%s\n",
2343 indentStr, nclassName.string(),
2344 flattenSymbol(sym.name).string());
2345 }
2346 }
2347 fprintf(fp, "%s */\n", getIndentSpace(indent));
2348
Jeff Browneb490d62014-06-06 19:43:42 -07002349 ann.printAnnotations(fp, indentStr);
Adam Lesinski282e1812014-01-23 18:17:42 -08002350
2351 fprintf(fp,
2352 "%spublic static final int[] %s = {\n"
2353 "%s",
2354 indentStr, nclassName.string(),
2355 getIndentSpace(indent+1));
2356
2357 for (a=0; a<NA; a++) {
2358 if (a != 0) {
2359 if ((a&3) == 0) {
2360 fprintf(fp, ",\n%s", getIndentSpace(indent+1));
2361 } else {
2362 fprintf(fp, ", ");
2363 }
2364 }
2365 fprintf(fp, "0x%08x", idents[a]);
2366 }
2367
2368 fprintf(fp, "\n%s};\n", indentStr);
2369
2370 for (a=0; a<NA; a++) {
2371 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2372 if (pos >= 0) {
2373 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2374 if (!publicFlags.itemAt(a) && !includePrivate) {
2375 continue;
2376 }
2377 String8 name8(sym.name);
2378 String16 comment(sym.comment);
2379 String16 typeComment;
2380 if (comment.size() <= 0) {
2381 comment = getAttributeComment(assets, name8, &typeComment);
2382 } else {
2383 getAttributeComment(assets, name8, &typeComment);
2384 }
2385
2386 uint32_t typeSpecFlags = 0;
2387 String16 name16(sym.name);
2388 assets->getIncludedResources().identifierForName(
2389 name16.string(), name16.size(),
2390 attr16.string(), attr16.size(),
2391 package16.string(), package16.size(), &typeSpecFlags);
2392 //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
2393 // String8(attr16).string(), String8(name16).string(), typeSpecFlags);
2394 const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
Jeff Browneb490d62014-06-06 19:43:42 -07002395
2396 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002397 fprintf(fp, "%s/**\n", indentStr);
2398 if (comment.size() > 0) {
2399 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002400 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002401 fprintf(fp, "%s <p>\n%s @attr description\n", indentStr, indentStr);
2402 fprintf(fp, "%s %s\n", indentStr, cmt.string());
Adam Lesinski282e1812014-01-23 18:17:42 -08002403 } else {
2404 fprintf(fp,
2405 "%s <p>This symbol is the offset where the {@link %s.R.attr#%s}\n"
2406 "%s attribute's value can be found in the {@link #%s} array.\n",
2407 indentStr,
2408 getSymbolPackage(name8, assets, pub).string(),
2409 getSymbolName(name8).string(),
2410 indentStr, nclassName.string());
2411 }
2412 if (typeComment.size() > 0) {
2413 String8 cmt(typeComment);
Jeff Browneb490d62014-06-06 19:43:42 -07002414 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002415 fprintf(fp, "\n\n%s %s\n", indentStr, cmt.string());
Adam Lesinski282e1812014-01-23 18:17:42 -08002416 }
2417 if (comment.size() > 0) {
2418 if (pub) {
2419 fprintf(fp,
2420 "%s <p>This corresponds to the global attribute\n"
2421 "%s resource symbol {@link %s.R.attr#%s}.\n",
2422 indentStr, indentStr,
2423 getSymbolPackage(name8, assets, true).string(),
2424 getSymbolName(name8).string());
2425 } else {
2426 fprintf(fp,
2427 "%s <p>This is a private symbol.\n", indentStr);
2428 }
2429 }
2430 fprintf(fp, "%s @attr name %s:%s\n", indentStr,
2431 getSymbolPackage(name8, assets, pub).string(),
2432 getSymbolName(name8).string());
2433 fprintf(fp, "%s*/\n", indentStr);
Jeff Browneb490d62014-06-06 19:43:42 -07002434 ann.printAnnotations(fp, indentStr);
Adam Lesinskie8e91922014-08-06 17:41:08 -07002435
2436 const char * id_format = nonConstantId ?
2437 "%spublic static int %s_%s = %d;\n" :
2438 "%spublic static final int %s_%s = %d;\n";
2439
Adam Lesinski282e1812014-01-23 18:17:42 -08002440 fprintf(fp,
Adam Lesinskie8e91922014-08-06 17:41:08 -07002441 id_format,
Adam Lesinski282e1812014-01-23 18:17:42 -08002442 indentStr, nclassName.string(),
2443 flattenSymbol(name8).string(), (int)pos);
2444 }
2445 }
2446 }
2447
2448 indent--;
2449 fprintf(fp, "%s};\n", getIndentSpace(indent));
Andreas Gampe2412f842014-09-30 20:55:57 -07002450 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08002451}
2452
2453static status_t writeTextLayoutClasses(
2454 FILE* fp, const sp<AaptAssets>& assets,
2455 const sp<AaptSymbols>& symbols, bool includePrivate)
2456{
2457 String16 attr16("attr");
2458 String16 package16(assets->getPackage());
2459
2460 bool hasErrors = false;
2461
2462 size_t i;
2463 size_t N = symbols->getNestedSymbols().size();
2464 for (i=0; i<N; i++) {
2465 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2466 String8 realClassName(symbols->getNestedSymbols().keyAt(i));
2467 String8 nclassName(flattenSymbol(realClassName));
2468
2469 SortedVector<uint32_t> idents;
2470 Vector<uint32_t> origOrder;
2471 Vector<bool> publicFlags;
2472
2473 size_t a;
2474 size_t NA = nsymbols->getSymbols().size();
2475 for (a=0; a<NA; a++) {
2476 const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a));
2477 int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32
2478 ? sym.int32Val : 0;
2479 bool isPublic = true;
2480 if (code == 0) {
2481 String16 name16(sym.name);
2482 uint32_t typeSpecFlags;
2483 code = assets->getIncludedResources().identifierForName(
2484 name16.string(), name16.size(),
2485 attr16.string(), attr16.size(),
2486 package16.string(), package16.size(), &typeSpecFlags);
2487 if (code == 0) {
2488 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
2489 nclassName.string(), sym.name.string());
2490 hasErrors = true;
2491 }
2492 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
2493 }
2494 idents.add(code);
2495 origOrder.add(code);
2496 publicFlags.add(isPublic);
2497 }
2498
2499 NA = idents.size();
2500
2501 fprintf(fp, "int[] styleable %s {", nclassName.string());
2502
2503 for (a=0; a<NA; a++) {
2504 if (a != 0) {
2505 fprintf(fp, ",");
2506 }
2507 fprintf(fp, " 0x%08x", idents[a]);
2508 }
2509
2510 fprintf(fp, " }\n");
2511
2512 for (a=0; a<NA; a++) {
2513 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2514 if (pos >= 0) {
2515 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2516 if (!publicFlags.itemAt(a) && !includePrivate) {
2517 continue;
2518 }
2519 String8 name8(sym.name);
2520 String16 comment(sym.comment);
2521 String16 typeComment;
2522 if (comment.size() <= 0) {
2523 comment = getAttributeComment(assets, name8, &typeComment);
2524 } else {
2525 getAttributeComment(assets, name8, &typeComment);
2526 }
2527
2528 uint32_t typeSpecFlags = 0;
2529 String16 name16(sym.name);
2530 assets->getIncludedResources().identifierForName(
2531 name16.string(), name16.size(),
2532 attr16.string(), attr16.size(),
2533 package16.string(), package16.size(), &typeSpecFlags);
2534 //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
2535 // String8(attr16).string(), String8(name16).string(), typeSpecFlags);
Andreas Gampe2412f842014-09-30 20:55:57 -07002536 //const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08002537
2538 fprintf(fp,
2539 "int styleable %s_%s %d\n",
2540 nclassName.string(),
2541 flattenSymbol(name8).string(), (int)pos);
2542 }
2543 }
2544 }
2545
Andreas Gampe2412f842014-09-30 20:55:57 -07002546 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08002547}
2548
2549static status_t writeSymbolClass(
2550 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2551 const sp<AaptSymbols>& symbols, const String8& className, int indent,
Adam Lesinski1e4663852014-08-15 14:47:28 -07002552 bool nonConstantId, bool emitCallback)
Adam Lesinski282e1812014-01-23 18:17:42 -08002553{
2554 fprintf(fp, "%spublic %sfinal class %s {\n",
2555 getIndentSpace(indent),
2556 indent != 0 ? "static " : "", className.string());
2557 indent++;
2558
2559 size_t i;
2560 status_t err = NO_ERROR;
2561
2562 const char * id_format = nonConstantId ?
2563 "%spublic static int %s=0x%08x;\n" :
2564 "%spublic static final int %s=0x%08x;\n";
2565
2566 size_t N = symbols->getSymbols().size();
2567 for (i=0; i<N; i++) {
2568 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2569 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
2570 continue;
2571 }
2572 if (!assets->isJavaSymbol(sym, includePrivate)) {
2573 continue;
2574 }
2575 String8 name8(sym.name);
2576 String16 comment(sym.comment);
2577 bool haveComment = false;
Jeff Browneb490d62014-06-06 19:43:42 -07002578 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002579 if (comment.size() > 0) {
2580 haveComment = true;
2581 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002582 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002583 fprintf(fp,
2584 "%s/** %s\n",
2585 getIndentSpace(indent), cmt.string());
Adam Lesinski282e1812014-01-23 18:17:42 -08002586 }
2587 String16 typeComment(sym.typeComment);
2588 if (typeComment.size() > 0) {
2589 String8 cmt(typeComment);
Jeff Browneb490d62014-06-06 19:43:42 -07002590 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002591 if (!haveComment) {
2592 haveComment = true;
2593 fprintf(fp,
2594 "%s/** %s\n", getIndentSpace(indent), cmt.string());
2595 } else {
2596 fprintf(fp,
2597 "%s %s\n", getIndentSpace(indent), cmt.string());
2598 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002599 }
2600 if (haveComment) {
2601 fprintf(fp,"%s */\n", getIndentSpace(indent));
2602 }
Jeff Browneb490d62014-06-06 19:43:42 -07002603 ann.printAnnotations(fp, getIndentSpace(indent));
Adam Lesinski282e1812014-01-23 18:17:42 -08002604 fprintf(fp, id_format,
2605 getIndentSpace(indent),
2606 flattenSymbol(name8).string(), (int)sym.int32Val);
2607 }
2608
2609 for (i=0; i<N; i++) {
2610 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2611 if (sym.typeCode != AaptSymbolEntry::TYPE_STRING) {
2612 continue;
2613 }
2614 if (!assets->isJavaSymbol(sym, includePrivate)) {
2615 continue;
2616 }
2617 String8 name8(sym.name);
2618 String16 comment(sym.comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002619 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002620 if (comment.size() > 0) {
2621 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002622 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002623 fprintf(fp,
2624 "%s/** %s\n"
2625 "%s */\n",
2626 getIndentSpace(indent), cmt.string(),
2627 getIndentSpace(indent));
Adam Lesinski282e1812014-01-23 18:17:42 -08002628 }
Jeff Browneb490d62014-06-06 19:43:42 -07002629 ann.printAnnotations(fp, getIndentSpace(indent));
Adam Lesinski282e1812014-01-23 18:17:42 -08002630 fprintf(fp, "%spublic static final String %s=\"%s\";\n",
2631 getIndentSpace(indent),
2632 flattenSymbol(name8).string(), sym.stringVal.string());
2633 }
2634
2635 sp<AaptSymbols> styleableSymbols;
2636
2637 N = symbols->getNestedSymbols().size();
2638 for (i=0; i<N; i++) {
2639 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2640 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2641 if (nclassName == "styleable") {
2642 styleableSymbols = nsymbols;
2643 } else {
Adam Lesinski1e4663852014-08-15 14:47:28 -07002644 err = writeSymbolClass(fp, assets, includePrivate, nsymbols, nclassName,
2645 indent, nonConstantId, false);
Adam Lesinski282e1812014-01-23 18:17:42 -08002646 }
2647 if (err != NO_ERROR) {
2648 return err;
2649 }
2650 }
2651
2652 if (styleableSymbols != NULL) {
Adam Lesinskie8e91922014-08-06 17:41:08 -07002653 err = writeLayoutClasses(fp, assets, styleableSymbols, indent, includePrivate, nonConstantId);
Adam Lesinski282e1812014-01-23 18:17:42 -08002654 if (err != NO_ERROR) {
2655 return err;
2656 }
2657 }
2658
Adam Lesinski1e4663852014-08-15 14:47:28 -07002659 if (emitCallback) {
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002660 fprintf(fp, "%spublic static void onResourcesLoaded(int packageId) {\n",
2661 getIndentSpace(indent));
2662 writeResourceLoadedCallback(fp, assets, includePrivate, symbols, className, indent + 1);
2663 fprintf(fp, "%s}\n", getIndentSpace(indent));
Adam Lesinski1e4663852014-08-15 14:47:28 -07002664 }
2665
Adam Lesinski282e1812014-01-23 18:17:42 -08002666 indent--;
2667 fprintf(fp, "%s}\n", getIndentSpace(indent));
2668 return NO_ERROR;
2669}
2670
2671static status_t writeTextSymbolClass(
2672 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2673 const sp<AaptSymbols>& symbols, const String8& className)
2674{
2675 size_t i;
2676 status_t err = NO_ERROR;
2677
2678 size_t N = symbols->getSymbols().size();
2679 for (i=0; i<N; i++) {
2680 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2681 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
2682 continue;
2683 }
2684
2685 if (!assets->isJavaSymbol(sym, includePrivate)) {
2686 continue;
2687 }
2688
2689 String8 name8(sym.name);
2690 fprintf(fp, "int %s %s 0x%08x\n",
2691 className.string(),
2692 flattenSymbol(name8).string(), (int)sym.int32Val);
2693 }
2694
2695 N = symbols->getNestedSymbols().size();
2696 for (i=0; i<N; i++) {
2697 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2698 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2699 if (nclassName == "styleable") {
2700 err = writeTextLayoutClasses(fp, assets, nsymbols, includePrivate);
2701 } else {
2702 err = writeTextSymbolClass(fp, assets, includePrivate, nsymbols, nclassName);
2703 }
2704 if (err != NO_ERROR) {
2705 return err;
2706 }
2707 }
2708
2709 return NO_ERROR;
2710}
2711
2712status_t writeResourceSymbols(Bundle* bundle, const sp<AaptAssets>& assets,
Adam Lesinski1e4663852014-08-15 14:47:28 -07002713 const String8& package, bool includePrivate, bool emitCallback)
Adam Lesinski282e1812014-01-23 18:17:42 -08002714{
2715 if (!bundle->getRClassDir()) {
2716 return NO_ERROR;
2717 }
2718
2719 const char* textSymbolsDest = bundle->getOutputTextSymbols();
2720
2721 String8 R("R");
2722 const size_t N = assets->getSymbols().size();
2723 for (size_t i=0; i<N; i++) {
2724 sp<AaptSymbols> symbols = assets->getSymbols().valueAt(i);
2725 String8 className(assets->getSymbols().keyAt(i));
2726 String8 dest(bundle->getRClassDir());
2727
2728 if (bundle->getMakePackageDirs()) {
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -07002729 const String8& pkg(package);
Adam Lesinski282e1812014-01-23 18:17:42 -08002730 const char* last = pkg.string();
2731 const char* s = last-1;
2732 do {
2733 s++;
2734 if (s > last && (*s == '.' || *s == 0)) {
2735 String8 part(last, s-last);
2736 dest.appendPath(part);
Elliott Hughese17788c2015-08-17 12:41:46 -07002737#ifdef _WIN32
Adam Lesinski282e1812014-01-23 18:17:42 -08002738 _mkdir(dest.string());
2739#else
2740 mkdir(dest.string(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP);
2741#endif
2742 last = s+1;
2743 }
2744 } while (*s);
2745 }
2746 dest.appendPath(className);
2747 dest.append(".java");
2748 FILE* fp = fopen(dest.string(), "w+");
2749 if (fp == NULL) {
2750 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
2751 dest.string(), strerror(errno));
2752 return UNKNOWN_ERROR;
2753 }
2754 if (bundle->getVerbose()) {
2755 printf(" Writing symbols for class %s.\n", className.string());
2756 }
2757
2758 fprintf(fp,
2759 "/* AUTO-GENERATED FILE. DO NOT MODIFY.\n"
2760 " *\n"
2761 " * This class was automatically generated by the\n"
2762 " * aapt tool from the resource data it found. It\n"
2763 " * should not be modified by hand.\n"
2764 " */\n"
2765 "\n"
2766 "package %s;\n\n", package.string());
2767
2768 status_t err = writeSymbolClass(fp, assets, includePrivate, symbols,
Adam Lesinski1e4663852014-08-15 14:47:28 -07002769 className, 0, bundle->getNonConstantId(), emitCallback);
Elliott Hughesb30296b2013-10-29 15:25:52 -07002770 fclose(fp);
Adam Lesinski282e1812014-01-23 18:17:42 -08002771 if (err != NO_ERROR) {
2772 return err;
2773 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002774
2775 if (textSymbolsDest != NULL && R == className) {
2776 String8 textDest(textSymbolsDest);
2777 textDest.appendPath(className);
2778 textDest.append(".txt");
2779
2780 FILE* fp = fopen(textDest.string(), "w+");
2781 if (fp == NULL) {
2782 fprintf(stderr, "ERROR: Unable to open text symbol file %s: %s\n",
2783 textDest.string(), strerror(errno));
2784 return UNKNOWN_ERROR;
2785 }
2786 if (bundle->getVerbose()) {
2787 printf(" Writing text symbols for class %s.\n", className.string());
2788 }
2789
2790 status_t err = writeTextSymbolClass(fp, assets, includePrivate, symbols,
2791 className);
Elliott Hughesb30296b2013-10-29 15:25:52 -07002792 fclose(fp);
Adam Lesinski282e1812014-01-23 18:17:42 -08002793 if (err != NO_ERROR) {
2794 return err;
2795 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002796 }
2797
2798 // If we were asked to generate a dependency file, we'll go ahead and add this R.java
2799 // as a target in the dependency file right next to it.
2800 if (bundle->getGenDependencies() && R == className) {
2801 // Add this R.java to the dependency file
2802 String8 dependencyFile(bundle->getRClassDir());
2803 dependencyFile.appendPath("R.java.d");
2804
2805 FILE *fp = fopen(dependencyFile.string(), "a");
2806 fprintf(fp,"%s \\\n", dest.string());
2807 fclose(fp);
2808 }
2809 }
2810
2811 return NO_ERROR;
2812}
2813
2814
2815class ProguardKeepSet
2816{
2817public:
2818 // { rule --> { file locations } }
2819 KeyedVector<String8, SortedVector<String8> > rules;
2820
2821 void add(const String8& rule, const String8& where);
2822};
2823
2824void ProguardKeepSet::add(const String8& rule, const String8& where)
2825{
2826 ssize_t index = rules.indexOfKey(rule);
2827 if (index < 0) {
2828 index = rules.add(rule, SortedVector<String8>());
2829 }
2830 rules.editValueAt(index).add(where);
2831}
2832
2833void
2834addProguardKeepRule(ProguardKeepSet* keep, const String8& inClassName,
2835 const char* pkg, const String8& srcName, int line)
2836{
2837 String8 className(inClassName);
2838 if (pkg != NULL) {
2839 // asdf --> package.asdf
2840 // .asdf .a.b --> package.asdf package.a.b
2841 // asdf.adsf --> asdf.asdf
2842 const char* p = className.string();
2843 const char* q = strchr(p, '.');
2844 if (p == q) {
2845 className = pkg;
2846 className.append(inClassName);
2847 } else if (q == NULL) {
2848 className = pkg;
2849 className.append(".");
2850 className.append(inClassName);
2851 }
2852 }
2853
2854 String8 rule("-keep class ");
2855 rule += className;
2856 rule += " { <init>(...); }";
2857
2858 String8 location("view ");
2859 location += srcName;
2860 char lineno[20];
2861 sprintf(lineno, ":%d", line);
2862 location += lineno;
2863
2864 keep->add(rule, location);
2865}
2866
2867void
2868addProguardKeepMethodRule(ProguardKeepSet* keep, const String8& memberName,
Andreas Gampe2412f842014-09-30 20:55:57 -07002869 const char* /* pkg */, const String8& srcName, int line)
Adam Lesinski282e1812014-01-23 18:17:42 -08002870{
2871 String8 rule("-keepclassmembers class * { *** ");
2872 rule += memberName;
2873 rule += "(...); }";
2874
2875 String8 location("onClick ");
2876 location += srcName;
2877 char lineno[20];
2878 sprintf(lineno, ":%d", line);
2879 location += lineno;
2880
2881 keep->add(rule, location);
2882}
2883
2884status_t
Rohit Agrawal682583c2016-04-21 16:29:58 -07002885writeProguardForAndroidManifest(ProguardKeepSet* keep, const sp<AaptAssets>& assets, bool mainDex)
Adam Lesinski282e1812014-01-23 18:17:42 -08002886{
2887 status_t err;
2888 ResXMLTree tree;
2889 size_t len;
2890 ResXMLTree::event_code_t code;
2891 int depth = 0;
2892 bool inApplication = false;
2893 String8 error;
2894 sp<AaptGroup> assGroup;
2895 sp<AaptFile> assFile;
2896 String8 pkg;
Rohit Agrawal682583c2016-04-21 16:29:58 -07002897 String8 defaultProcess;
Adam Lesinski282e1812014-01-23 18:17:42 -08002898
2899 // First, look for a package file to parse. This is required to
2900 // be able to generate the resource information.
2901 assGroup = assets->getFiles().valueFor(String8("AndroidManifest.xml"));
2902 if (assGroup == NULL) {
2903 fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n");
2904 return -1;
2905 }
2906
2907 if (assGroup->getFiles().size() != 1) {
2908 fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
2909 assGroup->getFiles().valueAt(0)->getPrintableSource().string());
2910 }
2911
2912 assFile = assGroup->getFiles().valueAt(0);
2913
2914 err = parseXMLResource(assFile, &tree);
2915 if (err != NO_ERROR) {
2916 return err;
2917 }
2918
2919 tree.restart();
2920
2921 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
2922 if (code == ResXMLTree::END_TAG) {
2923 if (/* name == "Application" && */ depth == 2) {
2924 inApplication = false;
2925 }
2926 depth--;
2927 continue;
2928 }
2929 if (code != ResXMLTree::START_TAG) {
2930 continue;
2931 }
2932 depth++;
2933 String8 tag(tree.getElementName(&len));
2934 // printf("Depth %d tag %s\n", depth, tag.string());
2935 bool keepTag = false;
2936 if (depth == 1) {
2937 if (tag != "manifest") {
2938 fprintf(stderr, "ERROR: manifest does not start with <manifest> tag\n");
2939 return -1;
2940 }
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07002941 pkg = AaptXml::getAttribute(tree, NULL, "package");
Adam Lesinski282e1812014-01-23 18:17:42 -08002942 } else if (depth == 2) {
2943 if (tag == "application") {
2944 inApplication = true;
2945 keepTag = true;
2946
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07002947 String8 agent = AaptXml::getAttribute(tree,
2948 "http://schemas.android.com/apk/res/android",
Adam Lesinski282e1812014-01-23 18:17:42 -08002949 "backupAgent", &error);
2950 if (agent.length() > 0) {
2951 addProguardKeepRule(keep, agent, pkg.string(),
2952 assFile->getPrintableSource(), tree.getLineNumber());
2953 }
Rohit Agrawal682583c2016-04-21 16:29:58 -07002954
2955 if (mainDex) {
2956 defaultProcess = AaptXml::getAttribute(tree,
2957 "http://schemas.android.com/apk/res/android", "process", &error);
2958 if (error != "") {
2959 fprintf(stderr, "ERROR: %s\n", error.string());
2960 return -1;
2961 }
2962 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002963 } else if (tag == "instrumentation") {
2964 keepTag = true;
2965 }
2966 }
2967 if (!keepTag && inApplication && depth == 3) {
2968 if (tag == "activity" || tag == "service" || tag == "receiver" || tag == "provider") {
2969 keepTag = true;
Ivan Gavrilovicf580d912016-07-19 12:03:33 +01002970
2971 if (mainDex) {
2972 String8 componentProcess = AaptXml::getAttribute(tree,
2973 "http://schemas.android.com/apk/res/android", "process", &error);
2974 if (error != "") {
2975 fprintf(stderr, "ERROR: %s\n", error.string());
2976 return -1;
2977 }
2978
2979 const String8& process =
2980 componentProcess.length() > 0 ? componentProcess : defaultProcess;
2981 keepTag = process.length() > 0 && process.find(":") != 0;
2982 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002983 }
2984 }
2985 if (keepTag) {
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07002986 String8 name = AaptXml::getAttribute(tree,
2987 "http://schemas.android.com/apk/res/android", "name", &error);
Adam Lesinski282e1812014-01-23 18:17:42 -08002988 if (error != "") {
2989 fprintf(stderr, "ERROR: %s\n", error.string());
2990 return -1;
2991 }
Rohit Agrawal682583c2016-04-21 16:29:58 -07002992
2993 keepTag = name.length() > 0;
2994
Rohit Agrawal682583c2016-04-21 16:29:58 -07002995 if (keepTag) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002996 addProguardKeepRule(keep, name, pkg.string(),
2997 assFile->getPrintableSource(), tree.getLineNumber());
2998 }
2999 }
3000 }
3001
3002 return NO_ERROR;
3003}
3004
3005struct NamespaceAttributePair {
3006 const char* ns;
3007 const char* attr;
3008
3009 NamespaceAttributePair(const char* n, const char* a) : ns(n), attr(a) {}
3010 NamespaceAttributePair() : ns(NULL), attr(NULL) {}
3011};
3012
3013status_t
3014writeProguardForXml(ProguardKeepSet* keep, const sp<AaptFile>& layoutFile,
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003015 const Vector<String8>& startTags, const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs)
Adam Lesinski282e1812014-01-23 18:17:42 -08003016{
3017 status_t err;
3018 ResXMLTree tree;
3019 size_t len;
3020 ResXMLTree::event_code_t code;
3021
3022 err = parseXMLResource(layoutFile, &tree);
3023 if (err != NO_ERROR) {
3024 return err;
3025 }
3026
3027 tree.restart();
3028
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003029 if (!startTags.isEmpty()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003030 bool haveStart = false;
3031 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
3032 if (code != ResXMLTree::START_TAG) {
3033 continue;
3034 }
3035 String8 tag(tree.getElementName(&len));
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003036 const size_t numStartTags = startTags.size();
3037 for (size_t i = 0; i < numStartTags; i++) {
3038 if (tag == startTags[i]) {
3039 haveStart = true;
3040 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003041 }
3042 break;
3043 }
3044 if (!haveStart) {
3045 return NO_ERROR;
3046 }
3047 }
3048
3049 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
3050 if (code != ResXMLTree::START_TAG) {
3051 continue;
3052 }
3053 String8 tag(tree.getElementName(&len));
3054
3055 // If there is no '.', we'll assume that it's one of the built in names.
3056 if (strchr(tag.string(), '.')) {
3057 addProguardKeepRule(keep, tag, NULL,
3058 layoutFile->getPrintableSource(), tree.getLineNumber());
3059 } else if (tagAttrPairs != NULL) {
3060 ssize_t tagIndex = tagAttrPairs->indexOfKey(tag);
3061 if (tagIndex >= 0) {
3062 const Vector<NamespaceAttributePair>& nsAttrVector = tagAttrPairs->valueAt(tagIndex);
3063 for (size_t i = 0; i < nsAttrVector.size(); i++) {
3064 const NamespaceAttributePair& nsAttr = nsAttrVector[i];
3065
3066 ssize_t attrIndex = tree.indexOfAttribute(nsAttr.ns, nsAttr.attr);
3067 if (attrIndex < 0) {
3068 // fprintf(stderr, "%s:%d: <%s> does not have attribute %s:%s.\n",
3069 // layoutFile->getPrintableSource().string(), tree.getLineNumber(),
3070 // tag.string(), nsAttr.ns, nsAttr.attr);
3071 } else {
3072 size_t len;
3073 addProguardKeepRule(keep,
3074 String8(tree.getAttributeStringValue(attrIndex, &len)), NULL,
3075 layoutFile->getPrintableSource(), tree.getLineNumber());
3076 }
3077 }
3078 }
3079 }
3080 ssize_t attrIndex = tree.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "onClick");
3081 if (attrIndex >= 0) {
3082 size_t len;
3083 addProguardKeepMethodRule(keep,
3084 String8(tree.getAttributeStringValue(attrIndex, &len)), NULL,
3085 layoutFile->getPrintableSource(), tree.getLineNumber());
3086 }
3087 }
3088
3089 return NO_ERROR;
3090}
3091
3092static void addTagAttrPair(KeyedVector<String8, Vector<NamespaceAttributePair> >* dest,
3093 const char* tag, const char* ns, const char* attr) {
3094 String8 tagStr(tag);
3095 ssize_t index = dest->indexOfKey(tagStr);
3096
3097 if (index < 0) {
3098 Vector<NamespaceAttributePair> vector;
3099 vector.add(NamespaceAttributePair(ns, attr));
3100 dest->add(tagStr, vector);
3101 } else {
3102 dest->editValueAt(index).add(NamespaceAttributePair(ns, attr));
3103 }
3104}
3105
3106status_t
3107writeProguardForLayouts(ProguardKeepSet* keep, const sp<AaptAssets>& assets)
3108{
3109 status_t err;
Adam Lesinski62c5df52014-12-02 16:19:05 -08003110 const char* kClass = "class";
3111 const char* kFragment = "fragment";
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003112 const String8 kTransition("transition");
3113 const String8 kTransitionPrefix("transition-");
Adam Lesinski282e1812014-01-23 18:17:42 -08003114
3115 // tag:attribute pairs that should be checked in layout files.
3116 KeyedVector<String8, Vector<NamespaceAttributePair> > kLayoutTagAttrPairs;
Adam Lesinski62c5df52014-12-02 16:19:05 -08003117 addTagAttrPair(&kLayoutTagAttrPairs, "view", NULL, kClass);
3118 addTagAttrPair(&kLayoutTagAttrPairs, kFragment, NULL, kClass);
3119 addTagAttrPair(&kLayoutTagAttrPairs, kFragment, RESOURCES_ANDROID_NAMESPACE, "name");
Adam Lesinski282e1812014-01-23 18:17:42 -08003120
3121 // tag:attribute pairs that should be checked in xml files.
3122 KeyedVector<String8, Vector<NamespaceAttributePair> > kXmlTagAttrPairs;
Adam Lesinski62c5df52014-12-02 16:19:05 -08003123 addTagAttrPair(&kXmlTagAttrPairs, "PreferenceScreen", RESOURCES_ANDROID_NAMESPACE, kFragment);
3124 addTagAttrPair(&kXmlTagAttrPairs, "header", RESOURCES_ANDROID_NAMESPACE, kFragment);
Adam Lesinski282e1812014-01-23 18:17:42 -08003125
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003126 // tag:attribute pairs that should be checked in transition files.
3127 KeyedVector<String8, Vector<NamespaceAttributePair> > kTransitionTagAttrPairs;
Adam Lesinski62c5df52014-12-02 16:19:05 -08003128 addTagAttrPair(&kTransitionTagAttrPairs, kTransition.string(), NULL, kClass);
3129 addTagAttrPair(&kTransitionTagAttrPairs, "pathMotion", NULL, kClass);
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003130
Adam Lesinski282e1812014-01-23 18:17:42 -08003131 const Vector<sp<AaptDir> >& dirs = assets->resDirs();
3132 const size_t K = dirs.size();
3133 for (size_t k=0; k<K; k++) {
3134 const sp<AaptDir>& d = dirs.itemAt(k);
3135 const String8& dirName = d->getLeaf();
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003136 Vector<String8> startTags;
Adam Lesinski282e1812014-01-23 18:17:42 -08003137 const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs = NULL;
3138 if ((dirName == String8("layout")) || (strncmp(dirName.string(), "layout-", 7) == 0)) {
3139 tagAttrPairs = &kLayoutTagAttrPairs;
3140 } else if ((dirName == String8("xml")) || (strncmp(dirName.string(), "xml-", 4) == 0)) {
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003141 startTags.add(String8("PreferenceScreen"));
3142 startTags.add(String8("preference-headers"));
Adam Lesinski282e1812014-01-23 18:17:42 -08003143 tagAttrPairs = &kXmlTagAttrPairs;
3144 } else if ((dirName == String8("menu")) || (strncmp(dirName.string(), "menu-", 5) == 0)) {
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003145 startTags.add(String8("menu"));
Adam Lesinski282e1812014-01-23 18:17:42 -08003146 tagAttrPairs = NULL;
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003147 } else if (dirName == kTransition || (strncmp(dirName.string(), kTransitionPrefix.string(),
3148 kTransitionPrefix.size()) == 0)) {
3149 tagAttrPairs = &kTransitionTagAttrPairs;
Adam Lesinski282e1812014-01-23 18:17:42 -08003150 } else {
3151 continue;
3152 }
3153
3154 const KeyedVector<String8,sp<AaptGroup> > groups = d->getFiles();
3155 const size_t N = groups.size();
3156 for (size_t i=0; i<N; i++) {
3157 const sp<AaptGroup>& group = groups.valueAt(i);
3158 const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files = group->getFiles();
3159 const size_t M = files.size();
3160 for (size_t j=0; j<M; j++) {
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003161 err = writeProguardForXml(keep, files.valueAt(j), startTags, tagAttrPairs);
Adam Lesinski282e1812014-01-23 18:17:42 -08003162 if (err < 0) {
3163 return err;
3164 }
3165 }
3166 }
3167 }
3168 // Handle the overlays
3169 sp<AaptAssets> overlay = assets->getOverlay();
3170 if (overlay.get()) {
3171 return writeProguardForLayouts(keep, overlay);
3172 }
3173
3174 return NO_ERROR;
3175}
3176
3177status_t
Rohit Agrawal682583c2016-04-21 16:29:58 -07003178writeProguardSpec(const char* filename, const ProguardKeepSet& keep, status_t err)
Adam Lesinski282e1812014-01-23 18:17:42 -08003179{
Rohit Agrawal682583c2016-04-21 16:29:58 -07003180 FILE* fp = fopen(filename, "w+");
Adam Lesinski282e1812014-01-23 18:17:42 -08003181 if (fp == NULL) {
3182 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
Rohit Agrawal682583c2016-04-21 16:29:58 -07003183 filename, strerror(errno));
Adam Lesinski282e1812014-01-23 18:17:42 -08003184 return UNKNOWN_ERROR;
3185 }
3186
3187 const KeyedVector<String8, SortedVector<String8> >& rules = keep.rules;
3188 const size_t N = rules.size();
3189 for (size_t i=0; i<N; i++) {
3190 const SortedVector<String8>& locations = rules.valueAt(i);
3191 const size_t M = locations.size();
3192 for (size_t j=0; j<M; j++) {
3193 fprintf(fp, "# %s\n", locations.itemAt(j).string());
3194 }
3195 fprintf(fp, "%s\n\n", rules.keyAt(i).string());
3196 }
3197 fclose(fp);
3198
3199 return err;
3200}
3201
Rohit Agrawal682583c2016-04-21 16:29:58 -07003202status_t
3203writeProguardFile(Bundle* bundle, const sp<AaptAssets>& assets)
3204{
3205 status_t err = -1;
3206
3207 if (!bundle->getProguardFile()) {
3208 return NO_ERROR;
3209 }
3210
3211 ProguardKeepSet keep;
3212
3213 err = writeProguardForAndroidManifest(&keep, assets, false);
3214 if (err < 0) {
3215 return err;
3216 }
3217
3218 err = writeProguardForLayouts(&keep, assets);
3219 if (err < 0) {
3220 return err;
3221 }
3222
3223 return writeProguardSpec(bundle->getProguardFile(), keep, err);
3224}
3225
3226status_t
3227writeMainDexProguardFile(Bundle* bundle, const sp<AaptAssets>& assets)
3228{
3229 status_t err = -1;
3230
3231 if (!bundle->getMainDexProguardFile()) {
3232 return NO_ERROR;
3233 }
3234
3235 ProguardKeepSet keep;
3236
3237 err = writeProguardForAndroidManifest(&keep, assets, true);
3238 if (err < 0) {
3239 return err;
3240 }
3241
3242 return writeProguardSpec(bundle->getMainDexProguardFile(), keep, err);
3243}
3244
Adam Lesinski282e1812014-01-23 18:17:42 -08003245// Loops through the string paths and writes them to the file pointer
3246// Each file path is written on its own line with a terminating backslash.
3247status_t writePathsToFile(const sp<FilePathStore>& files, FILE* fp)
3248{
3249 status_t deps = -1;
3250 for (size_t file_i = 0; file_i < files->size(); ++file_i) {
3251 // Add the full file path to the dependency file
3252 fprintf(fp, "%s \\\n", files->itemAt(file_i).string());
3253 deps++;
3254 }
3255 return deps;
3256}
3257
3258status_t
Andreas Gampe2412f842014-09-30 20:55:57 -07003259writeDependencyPreReqs(Bundle* /* bundle */, const sp<AaptAssets>& assets, FILE* fp, bool includeRaw)
Adam Lesinski282e1812014-01-23 18:17:42 -08003260{
3261 status_t deps = -1;
3262 deps += writePathsToFile(assets->getFullResPaths(), fp);
3263 if (includeRaw) {
3264 deps += writePathsToFile(assets->getFullAssetPaths(), fp);
3265 }
3266 return deps;
3267}