blob: 881ac8748083124dfb664b0468447bb642545c5d [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 Lesinski282e1812014-01-23 18:17:42 -08001406 if (err == NO_ERROR) {
1407 ResXMLTree block;
1408 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
1409 checkForIds(src, block);
1410 } else {
1411 hasErrors = true;
1412 }
1413 }
1414
1415 if (err < NO_ERROR) {
1416 hasErrors = true;
1417 }
1418 err = NO_ERROR;
1419 }
1420
1421 if (anims != NULL) {
1422 ResourceDirIterator it(anims, String8("anim"));
1423 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001424 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1425 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001426 if (err != NO_ERROR) {
1427 hasErrors = true;
1428 }
1429 }
1430
1431 if (err < NO_ERROR) {
1432 hasErrors = true;
1433 }
1434 err = NO_ERROR;
1435 }
1436
1437 if (animators != NULL) {
1438 ResourceDirIterator it(animators, String8("animator"));
1439 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001440 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1441 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001442 if (err != NO_ERROR) {
1443 hasErrors = true;
1444 }
1445 }
1446
1447 if (err < NO_ERROR) {
1448 hasErrors = true;
1449 }
1450 err = NO_ERROR;
1451 }
1452
1453 if (interpolators != NULL) {
1454 ResourceDirIterator it(interpolators, String8("interpolator"));
1455 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001456 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1457 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001458 if (err != NO_ERROR) {
1459 hasErrors = true;
1460 }
1461 }
1462
1463 if (err < NO_ERROR) {
1464 hasErrors = true;
1465 }
1466 err = NO_ERROR;
1467 }
1468
1469 if (transitions != NULL) {
1470 ResourceDirIterator it(transitions, String8("transition"));
1471 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001472 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1473 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001474 if (err != NO_ERROR) {
1475 hasErrors = true;
1476 }
1477 }
1478
1479 if (err < NO_ERROR) {
1480 hasErrors = true;
1481 }
1482 err = NO_ERROR;
1483 }
1484
Adam Lesinski282e1812014-01-23 18:17:42 -08001485 if (xmls != NULL) {
1486 ResourceDirIterator it(xmls, String8("xml"));
1487 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001488 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1489 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001490 if (err != NO_ERROR) {
1491 hasErrors = true;
1492 }
1493 }
1494
1495 if (err < NO_ERROR) {
1496 hasErrors = true;
1497 }
1498 err = NO_ERROR;
1499 }
1500
1501 if (drawables != NULL) {
Adam Lesinskifab50872014-04-16 14:40:42 -07001502 ResourceDirIterator it(drawables, String8("drawable"));
1503 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001504 err = postProcessImage(bundle, assets, &table, it.getFile());
Adam Lesinskifab50872014-04-16 14:40:42 -07001505 if (err != NO_ERROR) {
1506 hasErrors = true;
1507 }
1508 }
1509
1510 if (err < NO_ERROR) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001511 hasErrors = true;
1512 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001513 err = NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001514 }
1515
1516 if (colors != NULL) {
1517 ResourceDirIterator it(colors, String8("color"));
1518 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001519 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1520 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001521 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
1532 if (menus != NULL) {
1533 ResourceDirIterator it(menus, String8("menu"));
1534 while ((err=it.next()) == NO_ERROR) {
1535 String8 src = it.getFile()->getPrintableSource();
Adam Lesinskie572c012014-09-19 15:10:04 -07001536 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1537 it.getFile(), &table, xmlFlags);
Adam Lesinskifab50872014-04-16 14:40:42 -07001538 if (err == NO_ERROR) {
1539 ResXMLTree block;
1540 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
1541 checkForIds(src, block);
1542 } else {
Adam Lesinski282e1812014-01-23 18:17:42 -08001543 hasErrors = true;
1544 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001545 }
1546
1547 if (err < NO_ERROR) {
1548 hasErrors = true;
1549 }
1550 err = NO_ERROR;
1551 }
1552
Adam Lesinski9bbe7872017-01-24 13:52:04 -08001553 if (fonts != NULL) {
1554 ResourceDirIterator it(fonts, String8("font"));
1555 while ((err=it.next()) == NO_ERROR) {
1556 // fonts can be resources other than xml.
1557 if (it.getFile()->getPath().getPathExtension() == ".xml") {
1558 String8 src = it.getFile()->getPrintableSource();
1559 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1560 it.getFile(), &table, xmlFlags);
1561 if (err != NO_ERROR) {
1562 hasErrors = true;
1563 }
1564 }
1565 }
1566
1567 if (err < NO_ERROR) {
1568 hasErrors = true;
1569 }
1570 err = NO_ERROR;
1571 }
1572
Adam Lesinskie572c012014-09-19 15:10:04 -07001573 // Now compile any generated resources.
1574 std::queue<CompileResourceWorkItem>& workQueue = table.getWorkQueue();
1575 while (!workQueue.empty()) {
1576 CompileResourceWorkItem& workItem = workQueue.front();
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07001577 int xmlCompilationFlags = xmlFlags | XML_COMPILE_PARSE_VALUES
1578 | XML_COMPILE_ASSIGN_ATTRIBUTE_IDS;
1579 if (!workItem.needsCompiling) {
1580 xmlCompilationFlags &= ~XML_COMPILE_ASSIGN_ATTRIBUTE_IDS;
1581 xmlCompilationFlags &= ~XML_COMPILE_PARSE_VALUES;
1582 }
1583 err = compileXmlFile(bundle, assets, workItem.resourceName, workItem.xmlRoot,
1584 workItem.file, &table, xmlCompilationFlags);
1585
Adam Lesinskie572c012014-09-19 15:10:04 -07001586 if (err == NO_ERROR) {
1587 assets->addResource(workItem.resPath.getPathLeaf(),
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07001588 workItem.resPath,
1589 workItem.file,
1590 workItem.file->getResourceType());
Adam Lesinskie572c012014-09-19 15:10:04 -07001591 } else {
1592 hasErrors = true;
1593 }
1594 workQueue.pop();
1595 }
1596
Adam Lesinski282e1812014-01-23 18:17:42 -08001597 if (table.validateLocalizations()) {
1598 hasErrors = true;
1599 }
1600
1601 if (hasErrors) {
1602 return UNKNOWN_ERROR;
1603 }
1604
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001605 // If we're not overriding the platform build versions,
1606 // extract them from the platform APK.
1607 if (packageType != ResourceTable::System &&
1608 (bundle->getPlatformBuildVersionCode() == "" ||
1609 bundle->getPlatformBuildVersionName() == "")) {
1610 err = extractPlatformBuildVersion(assets->getAssetManager(), bundle);
1611 if (err != NO_ERROR) {
1612 return UNKNOWN_ERROR;
1613 }
1614 }
1615
Adam Lesinski282e1812014-01-23 18:17:42 -08001616 const sp<AaptFile> manifestFile(androidManifestFile->getFiles().valueAt(0));
1617 String8 manifestPath(manifestFile->getPrintableSource());
1618
1619 // Generate final compiled manifest file.
1620 manifestFile->clearData();
1621 sp<XMLNode> manifestTree = XMLNode::parse(manifestFile);
1622 if (manifestTree == NULL) {
1623 return UNKNOWN_ERROR;
1624 }
1625 err = massageManifest(bundle, manifestTree);
1626 if (err < NO_ERROR) {
1627 return err;
1628 }
Adam Lesinskie572c012014-09-19 15:10:04 -07001629 err = compileXmlFile(bundle, assets, String16(), manifestTree, manifestFile, &table);
Adam Lesinski282e1812014-01-23 18:17:42 -08001630 if (err < NO_ERROR) {
1631 return err;
1632 }
1633
Adam Lesinski82a2dd82014-09-17 18:34:15 -07001634 if (table.modifyForCompat(bundle) != NO_ERROR) {
1635 return UNKNOWN_ERROR;
1636 }
1637
Adam Lesinski282e1812014-01-23 18:17:42 -08001638 //block.restart();
1639 //printXMLBlock(&block);
1640
1641 // --------------------------------------------------------------
1642 // Generate the final resource table.
1643 // Re-flatten because we may have added new resource IDs
1644 // --------------------------------------------------------------
1645
Adam Lesinskide7de472014-11-03 12:03:08 -08001646
Adam Lesinski282e1812014-01-23 18:17:42 -08001647 ResTable finalResTable;
1648 sp<AaptFile> resFile;
1649
1650 if (table.hasResources()) {
1651 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
Adrian Roos58922482015-06-01 17:59:41 -07001652 err = table.addSymbols(symbols, bundle->getSkipSymbolsWithoutDefaultLocalization());
Adam Lesinski282e1812014-01-23 18:17:42 -08001653 if (err < NO_ERROR) {
1654 return err;
1655 }
1656
Adam Lesinskide7de472014-11-03 12:03:08 -08001657 KeyedVector<Symbol, Vector<SymbolDefinition> > densityVaryingResources;
1658 if (builder->getSplits().size() > 1) {
1659 // Only look for density varying resources if we're generating
1660 // splits.
1661 table.getDensityVaryingResources(densityVaryingResources);
1662 }
1663
Adam Lesinskifab50872014-04-16 14:40:42 -07001664 Vector<sp<ApkSplit> >& splits = builder->getSplits();
1665 const size_t numSplits = splits.size();
1666 for (size_t i = 0; i < numSplits; i++) {
1667 sp<ApkSplit>& split = splits.editItemAt(i);
1668 sp<AaptFile> flattenedTable = new AaptFile(String8("resources.arsc"),
1669 AaptGroupEntry(), String8());
Adam Lesinski27f69f42014-08-21 13:19:12 -07001670 err = table.flatten(bundle, split->getResourceFilter(),
1671 flattenedTable, split->isBase());
Adam Lesinskifab50872014-04-16 14:40:42 -07001672 if (err != NO_ERROR) {
1673 fprintf(stderr, "Failed to generate resource table for split '%s'\n",
1674 split->getPrintableName().string());
1675 return err;
1676 }
1677 split->addEntry(String8("resources.arsc"), flattenedTable);
Adam Lesinski282e1812014-01-23 18:17:42 -08001678
Adam Lesinskifab50872014-04-16 14:40:42 -07001679 if (split->isBase()) {
1680 resFile = flattenedTable;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07001681 err = finalResTable.add(flattenedTable->getData(), flattenedTable->getSize());
1682 if (err != NO_ERROR) {
1683 fprintf(stderr, "Generated resource table is corrupt.\n");
1684 return err;
1685 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001686 } else {
Adam Lesinskide7de472014-11-03 12:03:08 -08001687 ResTable resTable;
1688 err = resTable.add(flattenedTable->getData(), flattenedTable->getSize());
1689 if (err != NO_ERROR) {
1690 fprintf(stderr, "Generated resource table for split '%s' is corrupt.\n",
1691 split->getPrintableName().string());
1692 return err;
1693 }
1694
1695 bool hasError = false;
1696 const std::set<ConfigDescription>& splitConfigs = split->getConfigs();
1697 for (std::set<ConfigDescription>::const_iterator iter = splitConfigs.begin();
1698 iter != splitConfigs.end();
1699 ++iter) {
1700 const ConfigDescription& config = *iter;
1701 if (AaptConfig::isDensityOnly(config)) {
1702 // Each density only split must contain all
1703 // density only resources.
1704 Res_value val;
1705 resTable.setParameters(&config);
1706 const size_t densityVaryingResourceCount = densityVaryingResources.size();
1707 for (size_t k = 0; k < densityVaryingResourceCount; k++) {
1708 const Symbol& symbol = densityVaryingResources.keyAt(k);
1709 ssize_t block = resTable.getResource(symbol.id, &val, true);
1710 if (block < 0) {
1711 // Maybe it's in the base?
1712 finalResTable.setParameters(&config);
1713 block = finalResTable.getResource(symbol.id, &val, true);
1714 }
1715
1716 if (block < 0) {
1717 hasError = true;
1718 SourcePos().error("%s has no definition for density split '%s'",
1719 symbol.toString().string(), config.toString().string());
1720
1721 if (bundle->getVerbose()) {
1722 const Vector<SymbolDefinition>& defs = densityVaryingResources[k];
1723 const size_t defCount = std::min(size_t(5), defs.size());
1724 for (size_t d = 0; d < defCount; d++) {
1725 const SymbolDefinition& def = defs[d];
1726 def.source.error("%s has definition for %s",
1727 symbol.toString().string(), def.config.toString().string());
1728 }
1729
1730 if (defCount < defs.size()) {
1731 SourcePos().error("and %d more ...", (int) (defs.size() - defCount));
1732 }
1733 }
1734 }
1735 }
1736 }
1737 }
1738
1739 if (hasError) {
1740 return UNKNOWN_ERROR;
1741 }
1742
1743 // Generate the AndroidManifest for this split.
Adam Lesinskifab50872014-04-16 14:40:42 -07001744 sp<AaptFile> generatedManifest = new AaptFile(String8("AndroidManifest.xml"),
1745 AaptGroupEntry(), String8());
Jeff Sharkey2cfc8482014-07-09 16:10:16 -07001746 err = generateAndroidManifestForSplit(bundle, assets, split,
1747 generatedManifest, &table);
Adam Lesinskifab50872014-04-16 14:40:42 -07001748 if (err != NO_ERROR) {
1749 fprintf(stderr, "Failed to generate AndroidManifest.xml for split '%s'\n",
1750 split->getPrintableName().string());
1751 return err;
1752 }
1753 split->addEntry(String8("AndroidManifest.xml"), generatedManifest);
1754 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001755 }
1756
1757 if (bundle->getPublicOutputFile()) {
1758 FILE* fp = fopen(bundle->getPublicOutputFile(), "w+");
1759 if (fp == NULL) {
1760 fprintf(stderr, "ERROR: Unable to open public definitions output file %s: %s\n",
1761 (const char*)bundle->getPublicOutputFile(), strerror(errno));
1762 return UNKNOWN_ERROR;
1763 }
1764 if (bundle->getVerbose()) {
1765 printf(" Writing public definitions to %s.\n", bundle->getPublicOutputFile());
1766 }
1767 table.writePublicDefinitions(String16(assets->getPackage()), fp);
1768 fclose(fp);
1769 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001770
1771 if (finalResTable.getTableCount() == 0 || resFile == NULL) {
1772 fprintf(stderr, "No resource table was generated.\n");
1773 return UNKNOWN_ERROR;
1774 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001775 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001776
Adam Lesinski282e1812014-01-23 18:17:42 -08001777 // Perform a basic validation of the manifest file. This time we
1778 // parse it with the comments intact, so that we can use them to
1779 // generate java docs... so we are not going to write this one
1780 // back out to the final manifest data.
1781 sp<AaptFile> outManifestFile = new AaptFile(manifestFile->getSourceFile(),
1782 manifestFile->getGroupEntry(),
1783 manifestFile->getResourceType());
Adam Lesinskie572c012014-09-19 15:10:04 -07001784 err = compileXmlFile(bundle, assets, String16(), manifestFile,
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07001785 outManifestFile, &table, XML_COMPILE_STANDARD_RESOURCE & ~XML_COMPILE_STRIP_COMMENTS);
Adam Lesinski282e1812014-01-23 18:17:42 -08001786 if (err < NO_ERROR) {
1787 return err;
1788 }
1789 ResXMLTree block;
1790 block.setTo(outManifestFile->getData(), outManifestFile->getSize(), true);
1791 String16 manifest16("manifest");
1792 String16 permission16("permission");
1793 String16 permission_group16("permission-group");
1794 String16 uses_permission16("uses-permission");
1795 String16 instrumentation16("instrumentation");
1796 String16 application16("application");
1797 String16 provider16("provider");
1798 String16 service16("service");
1799 String16 receiver16("receiver");
1800 String16 activity16("activity");
1801 String16 action16("action");
1802 String16 category16("category");
1803 String16 data16("scheme");
Adam Lesinskid3edfde2014-08-08 17:32:44 -07001804 String16 feature_group16("feature-group");
1805 String16 uses_feature16("uses-feature");
Adam Lesinski282e1812014-01-23 18:17:42 -08001806 const char* packageIdentChars = "abcdefghijklmnopqrstuvwxyz"
1807 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789";
1808 const char* packageIdentCharsWithTheStupid = "abcdefghijklmnopqrstuvwxyz"
1809 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
1810 const char* classIdentChars = "abcdefghijklmnopqrstuvwxyz"
1811 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789$";
1812 const char* processIdentChars = "abcdefghijklmnopqrstuvwxyz"
1813 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:";
1814 const char* authoritiesIdentChars = "abcdefghijklmnopqrstuvwxyz"
1815 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-:;";
1816 const char* typeIdentChars = "abcdefghijklmnopqrstuvwxyz"
1817 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:-/*+";
1818 const char* schemeIdentChars = "abcdefghijklmnopqrstuvwxyz"
1819 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
1820 ResXMLTree::event_code_t code;
1821 sp<AaptSymbols> permissionSymbols;
1822 sp<AaptSymbols> permissionGroupSymbols;
1823 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1824 && code > ResXMLTree::BAD_DOCUMENT) {
1825 if (code == ResXMLTree::START_TAG) {
1826 size_t len;
1827 if (block.getElementNamespace(&len) != NULL) {
1828 continue;
1829 }
1830 if (strcmp16(block.getElementName(&len), manifest16.string()) == 0) {
1831 if (validateAttr(manifestPath, finalResTable, block, NULL, "package",
1832 packageIdentChars, true) != ATTR_OKAY) {
1833 hasErrors = true;
1834 }
1835 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1836 "sharedUserId", packageIdentChars, false) != ATTR_OKAY) {
1837 hasErrors = true;
1838 }
1839 } else if (strcmp16(block.getElementName(&len), permission16.string()) == 0
1840 || strcmp16(block.getElementName(&len), permission_group16.string()) == 0) {
1841 const bool isGroup = strcmp16(block.getElementName(&len),
1842 permission_group16.string()) == 0;
1843 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1844 "name", isGroup ? packageIdentCharsWithTheStupid
1845 : packageIdentChars, true) != ATTR_OKAY) {
1846 hasErrors = true;
1847 }
1848 SourcePos srcPos(manifestPath, block.getLineNumber());
1849 sp<AaptSymbols> syms;
1850 if (!isGroup) {
1851 syms = permissionSymbols;
1852 if (syms == NULL) {
1853 sp<AaptSymbols> symbols =
1854 assets->getSymbolsFor(String8("Manifest"));
1855 syms = permissionSymbols = symbols->addNestedSymbol(
1856 String8("permission"), srcPos);
1857 }
1858 } else {
1859 syms = permissionGroupSymbols;
1860 if (syms == NULL) {
1861 sp<AaptSymbols> symbols =
1862 assets->getSymbolsFor(String8("Manifest"));
1863 syms = permissionGroupSymbols = symbols->addNestedSymbol(
1864 String8("permission_group"), srcPos);
1865 }
1866 }
1867 size_t len;
1868 ssize_t index = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "name");
Dan Albertf348c152014-09-08 18:28:00 -07001869 const char16_t* id = block.getAttributeStringValue(index, &len);
Adam Lesinski282e1812014-01-23 18:17:42 -08001870 if (id == NULL) {
1871 fprintf(stderr, "%s:%d: missing name attribute in element <%s>.\n",
1872 manifestPath.string(), block.getLineNumber(),
1873 String8(block.getElementName(&len)).string());
1874 hasErrors = true;
1875 break;
1876 }
1877 String8 idStr(id);
1878 char* p = idStr.lockBuffer(idStr.size());
1879 char* e = p + idStr.size();
1880 bool begins_with_digit = true; // init to true so an empty string fails
1881 while (e > p) {
1882 e--;
1883 if (*e >= '0' && *e <= '9') {
1884 begins_with_digit = true;
1885 continue;
1886 }
1887 if ((*e >= 'a' && *e <= 'z') ||
1888 (*e >= 'A' && *e <= 'Z') ||
1889 (*e == '_')) {
1890 begins_with_digit = false;
1891 continue;
1892 }
1893 if (isGroup && (*e == '-')) {
1894 *e = '_';
1895 begins_with_digit = false;
1896 continue;
1897 }
1898 e++;
1899 break;
1900 }
1901 idStr.unlockBuffer();
1902 // verify that we stopped because we hit a period or
1903 // the beginning of the string, and that the
1904 // identifier didn't begin with a digit.
1905 if (begins_with_digit || (e != p && *(e-1) != '.')) {
1906 fprintf(stderr,
1907 "%s:%d: Permission name <%s> is not a valid Java symbol\n",
1908 manifestPath.string(), block.getLineNumber(), idStr.string());
1909 hasErrors = true;
1910 }
1911 syms->addStringSymbol(String8(e), idStr, srcPos);
Dan Albertf348c152014-09-08 18:28:00 -07001912 const char16_t* cmt = block.getComment(&len);
Adam Lesinski282e1812014-01-23 18:17:42 -08001913 if (cmt != NULL && *cmt != 0) {
1914 //printf("Comment of %s: %s\n", String8(e).string(),
1915 // String8(cmt).string());
1916 syms->appendComment(String8(e), String16(cmt), srcPos);
Adam Lesinski282e1812014-01-23 18:17:42 -08001917 }
1918 syms->makeSymbolPublic(String8(e), srcPos);
1919 } else if (strcmp16(block.getElementName(&len), uses_permission16.string()) == 0) {
1920 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1921 "name", packageIdentChars, true) != ATTR_OKAY) {
1922 hasErrors = true;
1923 }
1924 } else if (strcmp16(block.getElementName(&len), instrumentation16.string()) == 0) {
1925 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1926 "name", classIdentChars, true) != ATTR_OKAY) {
1927 hasErrors = true;
1928 }
1929 if (validateAttr(manifestPath, finalResTable, block,
1930 RESOURCES_ANDROID_NAMESPACE, "targetPackage",
1931 packageIdentChars, true) != ATTR_OKAY) {
1932 hasErrors = true;
1933 }
1934 } else if (strcmp16(block.getElementName(&len), application16.string()) == 0) {
1935 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1936 "name", classIdentChars, false) != ATTR_OKAY) {
1937 hasErrors = true;
1938 }
1939 if (validateAttr(manifestPath, finalResTable, block,
1940 RESOURCES_ANDROID_NAMESPACE, "permission",
1941 packageIdentChars, false) != ATTR_OKAY) {
1942 hasErrors = true;
1943 }
1944 if (validateAttr(manifestPath, finalResTable, block,
1945 RESOURCES_ANDROID_NAMESPACE, "process",
1946 processIdentChars, false) != ATTR_OKAY) {
1947 hasErrors = true;
1948 }
1949 if (validateAttr(manifestPath, finalResTable, block,
1950 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
1951 processIdentChars, false) != ATTR_OKAY) {
1952 hasErrors = true;
1953 }
1954 } else if (strcmp16(block.getElementName(&len), provider16.string()) == 0) {
1955 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1956 "name", classIdentChars, true) != ATTR_OKAY) {
1957 hasErrors = true;
1958 }
1959 if (validateAttr(manifestPath, finalResTable, block,
1960 RESOURCES_ANDROID_NAMESPACE, "authorities",
1961 authoritiesIdentChars, true) != ATTR_OKAY) {
1962 hasErrors = true;
1963 }
1964 if (validateAttr(manifestPath, finalResTable, block,
1965 RESOURCES_ANDROID_NAMESPACE, "permission",
1966 packageIdentChars, false) != ATTR_OKAY) {
1967 hasErrors = true;
1968 }
1969 if (validateAttr(manifestPath, finalResTable, block,
1970 RESOURCES_ANDROID_NAMESPACE, "process",
1971 processIdentChars, false) != ATTR_OKAY) {
1972 hasErrors = true;
1973 }
1974 } else if (strcmp16(block.getElementName(&len), service16.string()) == 0
1975 || strcmp16(block.getElementName(&len), receiver16.string()) == 0
1976 || strcmp16(block.getElementName(&len), activity16.string()) == 0) {
1977 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1978 "name", classIdentChars, true) != ATTR_OKAY) {
1979 hasErrors = true;
1980 }
1981 if (validateAttr(manifestPath, finalResTable, block,
1982 RESOURCES_ANDROID_NAMESPACE, "permission",
1983 packageIdentChars, false) != ATTR_OKAY) {
1984 hasErrors = true;
1985 }
1986 if (validateAttr(manifestPath, finalResTable, block,
1987 RESOURCES_ANDROID_NAMESPACE, "process",
1988 processIdentChars, false) != ATTR_OKAY) {
1989 hasErrors = true;
1990 }
1991 if (validateAttr(manifestPath, finalResTable, block,
1992 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
1993 processIdentChars, false) != ATTR_OKAY) {
1994 hasErrors = true;
1995 }
1996 } else if (strcmp16(block.getElementName(&len), action16.string()) == 0
1997 || strcmp16(block.getElementName(&len), category16.string()) == 0) {
1998 if (validateAttr(manifestPath, finalResTable, block,
1999 RESOURCES_ANDROID_NAMESPACE, "name",
2000 packageIdentChars, true) != ATTR_OKAY) {
2001 hasErrors = true;
2002 }
2003 } else if (strcmp16(block.getElementName(&len), data16.string()) == 0) {
2004 if (validateAttr(manifestPath, finalResTable, block,
2005 RESOURCES_ANDROID_NAMESPACE, "mimeType",
2006 typeIdentChars, true) != ATTR_OKAY) {
2007 hasErrors = true;
2008 }
2009 if (validateAttr(manifestPath, finalResTable, block,
2010 RESOURCES_ANDROID_NAMESPACE, "scheme",
2011 schemeIdentChars, true) != ATTR_OKAY) {
2012 hasErrors = true;
2013 }
Adam Lesinskid3edfde2014-08-08 17:32:44 -07002014 } else if (strcmp16(block.getElementName(&len), feature_group16.string()) == 0) {
2015 int depth = 1;
2016 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
2017 && code > ResXMLTree::BAD_DOCUMENT) {
2018 if (code == ResXMLTree::START_TAG) {
2019 depth++;
2020 if (strcmp16(block.getElementName(&len), uses_feature16.string()) == 0) {
2021 ssize_t idx = block.indexOfAttribute(
2022 RESOURCES_ANDROID_NAMESPACE, "required");
2023 if (idx < 0) {
2024 continue;
2025 }
2026
2027 int32_t data = block.getAttributeData(idx);
2028 if (data == 0) {
2029 fprintf(stderr, "%s:%d: Tag <uses-feature> can not have "
2030 "android:required=\"false\" when inside a "
2031 "<feature-group> tag.\n",
2032 manifestPath.string(), block.getLineNumber());
2033 hasErrors = true;
2034 }
2035 }
2036 } else if (code == ResXMLTree::END_TAG) {
2037 depth--;
2038 if (depth == 0) {
2039 break;
2040 }
2041 }
2042 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002043 }
2044 }
2045 }
2046
Adam Lesinskid3edfde2014-08-08 17:32:44 -07002047 if (hasErrors) {
2048 return UNKNOWN_ERROR;
2049 }
2050
Adam Lesinski282e1812014-01-23 18:17:42 -08002051 if (resFile != NULL) {
2052 // These resources are now considered to be a part of the included
2053 // resources, for others to reference.
2054 err = assets->addIncludedResources(resFile);
2055 if (err < NO_ERROR) {
2056 fprintf(stderr, "ERROR: Unable to parse generated resources, aborting.\n");
2057 return err;
2058 }
2059 }
2060
2061 return err;
2062}
2063
2064static const char* getIndentSpace(int indent)
2065{
2066static const char whitespace[] =
2067" ";
2068
2069 return whitespace + sizeof(whitespace) - 1 - indent*4;
2070}
2071
2072static String8 flattenSymbol(const String8& symbol) {
2073 String8 result(symbol);
2074 ssize_t first;
2075 if ((first = symbol.find(":", 0)) >= 0
2076 || (first = symbol.find(".", 0)) >= 0) {
2077 size_t size = symbol.size();
2078 char* buf = result.lockBuffer(size);
2079 for (size_t i = first; i < size; i++) {
2080 if (buf[i] == ':' || buf[i] == '.') {
2081 buf[i] = '_';
2082 }
2083 }
2084 result.unlockBuffer(size);
2085 }
2086 return result;
2087}
2088
2089static String8 getSymbolPackage(const String8& symbol, const sp<AaptAssets>& assets, bool pub) {
2090 ssize_t colon = symbol.find(":", 0);
2091 if (colon >= 0) {
2092 return String8(symbol.string(), colon);
2093 }
2094 return pub ? assets->getPackage() : assets->getSymbolsPrivatePackage();
2095}
2096
2097static String8 getSymbolName(const String8& symbol) {
2098 ssize_t colon = symbol.find(":", 0);
2099 if (colon >= 0) {
2100 return String8(symbol.string() + colon + 1);
2101 }
2102 return symbol;
2103}
2104
2105static String16 getAttributeComment(const sp<AaptAssets>& assets,
2106 const String8& name,
2107 String16* outTypeComment = NULL)
2108{
2109 sp<AaptSymbols> asym = assets->getSymbolsFor(String8("R"));
2110 if (asym != NULL) {
2111 //printf("Got R symbols!\n");
2112 asym = asym->getNestedSymbols().valueFor(String8("attr"));
2113 if (asym != NULL) {
2114 //printf("Got attrs symbols! comment %s=%s\n",
2115 // name.string(), String8(asym->getComment(name)).string());
2116 if (outTypeComment != NULL) {
2117 *outTypeComment = asym->getTypeComment(name);
2118 }
2119 return asym->getComment(name);
2120 }
2121 }
2122 return String16();
2123}
2124
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002125static status_t writeResourceLoadedCallbackForLayoutClasses(
2126 FILE* fp, const sp<AaptAssets>& assets,
Andreas Gampe87332a72014-10-01 22:03:58 -07002127 const sp<AaptSymbols>& symbols, int indent, bool /* includePrivate */)
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002128{
2129 String16 attr16("attr");
2130 String16 package16(assets->getPackage());
2131
2132 const char* indentStr = getIndentSpace(indent);
2133 bool hasErrors = false;
2134
2135 size_t i;
2136 size_t N = symbols->getNestedSymbols().size();
2137 for (i=0; i<N; i++) {
2138 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2139 String8 realClassName(symbols->getNestedSymbols().keyAt(i));
2140 String8 nclassName(flattenSymbol(realClassName));
2141
2142 fprintf(fp,
2143 "%sfor(int i = 0; i < styleable.%s.length; ++i) {\n"
2144 "%sstyleable.%s[i] = (styleable.%s[i] & 0x00ffffff) | (packageId << 24);\n"
2145 "%s}\n",
2146 indentStr, nclassName.string(),
2147 getIndentSpace(indent+1), nclassName.string(), nclassName.string(),
2148 indentStr);
Adam Lesinski1e4663852014-08-15 14:47:28 -07002149 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002150
Dan Alberted811ee2016-01-15 12:16:06 -08002151 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002152}
2153
2154static status_t writeResourceLoadedCallback(
2155 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2156 const sp<AaptSymbols>& symbols, const String8& className, int indent)
2157{
2158 size_t i;
2159 status_t err = NO_ERROR;
2160
2161 size_t N = symbols->getSymbols().size();
2162 for (i=0; i<N; i++) {
2163 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
Adam Lesinskieed58582015-09-10 18:43:34 -07002164 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002165 continue;
Adam Lesinski1e4663852014-08-15 14:47:28 -07002166 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002167 if (!assets->isJavaSymbol(sym, includePrivate)) {
2168 continue;
Adam Lesinski1e4663852014-08-15 14:47:28 -07002169 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002170 String8 flat_name(flattenSymbol(sym.name));
2171 fprintf(fp,
2172 "%s%s.%s = (%s.%s & 0x00ffffff) | (packageId << 24);\n",
2173 getIndentSpace(indent), className.string(), flat_name.string(),
2174 className.string(), flat_name.string());
Adam Lesinski1e4663852014-08-15 14:47:28 -07002175 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002176
2177 N = symbols->getNestedSymbols().size();
2178 for (i=0; i<N; i++) {
2179 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2180 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2181 if (nclassName == "styleable") {
2182 err = writeResourceLoadedCallbackForLayoutClasses(
2183 fp, assets, nsymbols, indent, includePrivate);
2184 } else {
2185 err = writeResourceLoadedCallback(fp, assets, includePrivate, nsymbols,
2186 nclassName, indent);
Adam Lesinski1e4663852014-08-15 14:47:28 -07002187 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002188 if (err != NO_ERROR) {
2189 return err;
2190 }
Adam Lesinski1e4663852014-08-15 14:47:28 -07002191 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002192
2193 return NO_ERROR;
Adam Lesinski1e4663852014-08-15 14:47:28 -07002194}
2195
Adam Lesinski282e1812014-01-23 18:17:42 -08002196static status_t writeLayoutClasses(
2197 FILE* fp, const sp<AaptAssets>& assets,
Adam Lesinskie8e91922014-08-06 17:41:08 -07002198 const sp<AaptSymbols>& symbols, int indent, bool includePrivate, bool nonConstantId)
Adam Lesinski282e1812014-01-23 18:17:42 -08002199{
2200 const char* indentStr = getIndentSpace(indent);
2201 if (!includePrivate) {
2202 fprintf(fp, "%s/** @doconly */\n", indentStr);
2203 }
2204 fprintf(fp, "%spublic static final class styleable {\n", indentStr);
2205 indent++;
2206
2207 String16 attr16("attr");
2208 String16 package16(assets->getPackage());
2209
2210 indentStr = getIndentSpace(indent);
2211 bool hasErrors = false;
2212
2213 size_t i;
2214 size_t N = symbols->getNestedSymbols().size();
2215 for (i=0; i<N; i++) {
2216 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2217 String8 realClassName(symbols->getNestedSymbols().keyAt(i));
2218 String8 nclassName(flattenSymbol(realClassName));
2219
2220 SortedVector<uint32_t> idents;
2221 Vector<uint32_t> origOrder;
2222 Vector<bool> publicFlags;
2223
2224 size_t a;
2225 size_t NA = nsymbols->getSymbols().size();
2226 for (a=0; a<NA; a++) {
2227 const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a));
2228 int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32
2229 ? sym.int32Val : 0;
2230 bool isPublic = true;
2231 if (code == 0) {
2232 String16 name16(sym.name);
2233 uint32_t typeSpecFlags;
2234 code = assets->getIncludedResources().identifierForName(
2235 name16.string(), name16.size(),
2236 attr16.string(), attr16.size(),
2237 package16.string(), package16.size(), &typeSpecFlags);
2238 if (code == 0) {
2239 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
2240 nclassName.string(), sym.name.string());
2241 hasErrors = true;
2242 }
2243 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
2244 }
2245 idents.add(code);
2246 origOrder.add(code);
2247 publicFlags.add(isPublic);
2248 }
2249
2250 NA = idents.size();
2251
Adam Lesinski282e1812014-01-23 18:17:42 -08002252 String16 comment = symbols->getComment(realClassName);
Jeff Browneb490d62014-06-06 19:43:42 -07002253 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002254 fprintf(fp, "%s/** ", indentStr);
2255 if (comment.size() > 0) {
2256 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002257 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002258 fprintf(fp, "%s\n", cmt.string());
Adam Lesinski282e1812014-01-23 18:17:42 -08002259 } else {
2260 fprintf(fp, "Attributes that can be used with a %s.\n", nclassName.string());
2261 }
2262 bool hasTable = false;
2263 for (a=0; a<NA; a++) {
2264 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2265 if (pos >= 0) {
2266 if (!hasTable) {
2267 hasTable = true;
2268 fprintf(fp,
2269 "%s <p>Includes the following attributes:</p>\n"
2270 "%s <table>\n"
2271 "%s <colgroup align=\"left\" />\n"
2272 "%s <colgroup align=\"left\" />\n"
2273 "%s <tr><th>Attribute</th><th>Description</th></tr>\n",
2274 indentStr,
2275 indentStr,
2276 indentStr,
2277 indentStr,
2278 indentStr);
2279 }
2280 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2281 if (!publicFlags.itemAt(a) && !includePrivate) {
2282 continue;
2283 }
2284 String8 name8(sym.name);
2285 String16 comment(sym.comment);
2286 if (comment.size() <= 0) {
2287 comment = getAttributeComment(assets, name8);
2288 }
Michael Wrightfeaf99f2016-05-06 17:16:06 +01002289 if (comment.contains(u"@removed")) {
2290 continue;
2291 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002292 if (comment.size() > 0) {
2293 const char16_t* p = comment.string();
2294 while (*p != 0 && *p != '.') {
2295 if (*p == '{') {
2296 while (*p != 0 && *p != '}') {
2297 p++;
2298 }
2299 } else {
2300 p++;
2301 }
2302 }
2303 if (*p == '.') {
2304 p++;
2305 }
2306 comment = String16(comment.string(), p-comment.string());
2307 }
2308 fprintf(fp, "%s <tr><td><code>{@link #%s_%s %s:%s}</code></td><td>%s</td></tr>\n",
2309 indentStr, nclassName.string(),
2310 flattenSymbol(name8).string(),
2311 getSymbolPackage(name8, assets, true).string(),
2312 getSymbolName(name8).string(),
2313 String8(comment).string());
2314 }
2315 }
2316 if (hasTable) {
2317 fprintf(fp, "%s </table>\n", indentStr);
2318 }
2319 for (a=0; a<NA; a++) {
2320 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2321 if (pos >= 0) {
2322 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2323 if (!publicFlags.itemAt(a) && !includePrivate) {
2324 continue;
2325 }
2326 fprintf(fp, "%s @see #%s_%s\n",
2327 indentStr, nclassName.string(),
2328 flattenSymbol(sym.name).string());
2329 }
2330 }
2331 fprintf(fp, "%s */\n", getIndentSpace(indent));
2332
Jeff Browneb490d62014-06-06 19:43:42 -07002333 ann.printAnnotations(fp, indentStr);
Adam Lesinski282e1812014-01-23 18:17:42 -08002334
2335 fprintf(fp,
2336 "%spublic static final int[] %s = {\n"
2337 "%s",
2338 indentStr, nclassName.string(),
2339 getIndentSpace(indent+1));
2340
2341 for (a=0; a<NA; a++) {
2342 if (a != 0) {
2343 if ((a&3) == 0) {
2344 fprintf(fp, ",\n%s", getIndentSpace(indent+1));
2345 } else {
2346 fprintf(fp, ", ");
2347 }
2348 }
2349 fprintf(fp, "0x%08x", idents[a]);
2350 }
2351
2352 fprintf(fp, "\n%s};\n", indentStr);
2353
2354 for (a=0; a<NA; a++) {
2355 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2356 if (pos >= 0) {
2357 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2358 if (!publicFlags.itemAt(a) && !includePrivate) {
2359 continue;
2360 }
2361 String8 name8(sym.name);
2362 String16 comment(sym.comment);
2363 String16 typeComment;
2364 if (comment.size() <= 0) {
2365 comment = getAttributeComment(assets, name8, &typeComment);
2366 } else {
2367 getAttributeComment(assets, name8, &typeComment);
2368 }
2369
2370 uint32_t typeSpecFlags = 0;
2371 String16 name16(sym.name);
2372 assets->getIncludedResources().identifierForName(
2373 name16.string(), name16.size(),
2374 attr16.string(), attr16.size(),
2375 package16.string(), package16.size(), &typeSpecFlags);
2376 //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
2377 // String8(attr16).string(), String8(name16).string(), typeSpecFlags);
2378 const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
Jeff Browneb490d62014-06-06 19:43:42 -07002379
2380 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002381 fprintf(fp, "%s/**\n", indentStr);
2382 if (comment.size() > 0) {
2383 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002384 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002385 fprintf(fp, "%s <p>\n%s @attr description\n", indentStr, indentStr);
2386 fprintf(fp, "%s %s\n", indentStr, cmt.string());
Adam Lesinski282e1812014-01-23 18:17:42 -08002387 } else {
2388 fprintf(fp,
2389 "%s <p>This symbol is the offset where the {@link %s.R.attr#%s}\n"
2390 "%s attribute's value can be found in the {@link #%s} array.\n",
2391 indentStr,
2392 getSymbolPackage(name8, assets, pub).string(),
2393 getSymbolName(name8).string(),
2394 indentStr, nclassName.string());
2395 }
2396 if (typeComment.size() > 0) {
2397 String8 cmt(typeComment);
Jeff Browneb490d62014-06-06 19:43:42 -07002398 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002399 fprintf(fp, "\n\n%s %s\n", indentStr, cmt.string());
Adam Lesinski282e1812014-01-23 18:17:42 -08002400 }
2401 if (comment.size() > 0) {
2402 if (pub) {
2403 fprintf(fp,
2404 "%s <p>This corresponds to the global attribute\n"
2405 "%s resource symbol {@link %s.R.attr#%s}.\n",
2406 indentStr, indentStr,
2407 getSymbolPackage(name8, assets, true).string(),
2408 getSymbolName(name8).string());
2409 } else {
2410 fprintf(fp,
2411 "%s <p>This is a private symbol.\n", indentStr);
2412 }
2413 }
2414 fprintf(fp, "%s @attr name %s:%s\n", indentStr,
2415 getSymbolPackage(name8, assets, pub).string(),
2416 getSymbolName(name8).string());
2417 fprintf(fp, "%s*/\n", indentStr);
Jeff Browneb490d62014-06-06 19:43:42 -07002418 ann.printAnnotations(fp, indentStr);
Adam Lesinskie8e91922014-08-06 17:41:08 -07002419
2420 const char * id_format = nonConstantId ?
2421 "%spublic static int %s_%s = %d;\n" :
2422 "%spublic static final int %s_%s = %d;\n";
2423
Adam Lesinski282e1812014-01-23 18:17:42 -08002424 fprintf(fp,
Adam Lesinskie8e91922014-08-06 17:41:08 -07002425 id_format,
Adam Lesinski282e1812014-01-23 18:17:42 -08002426 indentStr, nclassName.string(),
2427 flattenSymbol(name8).string(), (int)pos);
2428 }
2429 }
2430 }
2431
2432 indent--;
2433 fprintf(fp, "%s};\n", getIndentSpace(indent));
Andreas Gampe2412f842014-09-30 20:55:57 -07002434 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08002435}
2436
2437static status_t writeTextLayoutClasses(
2438 FILE* fp, const sp<AaptAssets>& assets,
2439 const sp<AaptSymbols>& symbols, bool includePrivate)
2440{
2441 String16 attr16("attr");
2442 String16 package16(assets->getPackage());
2443
2444 bool hasErrors = false;
2445
2446 size_t i;
2447 size_t N = symbols->getNestedSymbols().size();
2448 for (i=0; i<N; i++) {
2449 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2450 String8 realClassName(symbols->getNestedSymbols().keyAt(i));
2451 String8 nclassName(flattenSymbol(realClassName));
2452
2453 SortedVector<uint32_t> idents;
2454 Vector<uint32_t> origOrder;
2455 Vector<bool> publicFlags;
2456
2457 size_t a;
2458 size_t NA = nsymbols->getSymbols().size();
2459 for (a=0; a<NA; a++) {
2460 const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a));
2461 int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32
2462 ? sym.int32Val : 0;
2463 bool isPublic = true;
2464 if (code == 0) {
2465 String16 name16(sym.name);
2466 uint32_t typeSpecFlags;
2467 code = assets->getIncludedResources().identifierForName(
2468 name16.string(), name16.size(),
2469 attr16.string(), attr16.size(),
2470 package16.string(), package16.size(), &typeSpecFlags);
2471 if (code == 0) {
2472 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
2473 nclassName.string(), sym.name.string());
2474 hasErrors = true;
2475 }
2476 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
2477 }
2478 idents.add(code);
2479 origOrder.add(code);
2480 publicFlags.add(isPublic);
2481 }
2482
2483 NA = idents.size();
2484
2485 fprintf(fp, "int[] styleable %s {", nclassName.string());
2486
2487 for (a=0; a<NA; a++) {
2488 if (a != 0) {
2489 fprintf(fp, ",");
2490 }
2491 fprintf(fp, " 0x%08x", idents[a]);
2492 }
2493
2494 fprintf(fp, " }\n");
2495
2496 for (a=0; a<NA; a++) {
2497 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2498 if (pos >= 0) {
2499 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2500 if (!publicFlags.itemAt(a) && !includePrivate) {
2501 continue;
2502 }
2503 String8 name8(sym.name);
2504 String16 comment(sym.comment);
2505 String16 typeComment;
2506 if (comment.size() <= 0) {
2507 comment = getAttributeComment(assets, name8, &typeComment);
2508 } else {
2509 getAttributeComment(assets, name8, &typeComment);
2510 }
2511
2512 uint32_t typeSpecFlags = 0;
2513 String16 name16(sym.name);
2514 assets->getIncludedResources().identifierForName(
2515 name16.string(), name16.size(),
2516 attr16.string(), attr16.size(),
2517 package16.string(), package16.size(), &typeSpecFlags);
2518 //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
2519 // String8(attr16).string(), String8(name16).string(), typeSpecFlags);
Andreas Gampe2412f842014-09-30 20:55:57 -07002520 //const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08002521
2522 fprintf(fp,
2523 "int styleable %s_%s %d\n",
2524 nclassName.string(),
2525 flattenSymbol(name8).string(), (int)pos);
2526 }
2527 }
2528 }
2529
Andreas Gampe2412f842014-09-30 20:55:57 -07002530 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08002531}
2532
2533static status_t writeSymbolClass(
2534 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2535 const sp<AaptSymbols>& symbols, const String8& className, int indent,
Adam Lesinski1e4663852014-08-15 14:47:28 -07002536 bool nonConstantId, bool emitCallback)
Adam Lesinski282e1812014-01-23 18:17:42 -08002537{
2538 fprintf(fp, "%spublic %sfinal class %s {\n",
2539 getIndentSpace(indent),
2540 indent != 0 ? "static " : "", className.string());
2541 indent++;
2542
2543 size_t i;
2544 status_t err = NO_ERROR;
2545
2546 const char * id_format = nonConstantId ?
2547 "%spublic static int %s=0x%08x;\n" :
2548 "%spublic static final int %s=0x%08x;\n";
2549
2550 size_t N = symbols->getSymbols().size();
2551 for (i=0; i<N; i++) {
2552 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2553 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
2554 continue;
2555 }
2556 if (!assets->isJavaSymbol(sym, includePrivate)) {
2557 continue;
2558 }
2559 String8 name8(sym.name);
2560 String16 comment(sym.comment);
2561 bool haveComment = false;
Jeff Browneb490d62014-06-06 19:43:42 -07002562 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002563 if (comment.size() > 0) {
2564 haveComment = true;
2565 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002566 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002567 fprintf(fp,
2568 "%s/** %s\n",
2569 getIndentSpace(indent), cmt.string());
Adam Lesinski282e1812014-01-23 18:17:42 -08002570 }
2571 String16 typeComment(sym.typeComment);
2572 if (typeComment.size() > 0) {
2573 String8 cmt(typeComment);
Jeff Browneb490d62014-06-06 19:43:42 -07002574 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002575 if (!haveComment) {
2576 haveComment = true;
2577 fprintf(fp,
2578 "%s/** %s\n", getIndentSpace(indent), cmt.string());
2579 } else {
2580 fprintf(fp,
2581 "%s %s\n", getIndentSpace(indent), cmt.string());
2582 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002583 }
2584 if (haveComment) {
2585 fprintf(fp,"%s */\n", getIndentSpace(indent));
2586 }
Jeff Browneb490d62014-06-06 19:43:42 -07002587 ann.printAnnotations(fp, getIndentSpace(indent));
Adam Lesinski282e1812014-01-23 18:17:42 -08002588 fprintf(fp, id_format,
2589 getIndentSpace(indent),
2590 flattenSymbol(name8).string(), (int)sym.int32Val);
2591 }
2592
2593 for (i=0; i<N; i++) {
2594 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2595 if (sym.typeCode != AaptSymbolEntry::TYPE_STRING) {
2596 continue;
2597 }
2598 if (!assets->isJavaSymbol(sym, includePrivate)) {
2599 continue;
2600 }
2601 String8 name8(sym.name);
2602 String16 comment(sym.comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002603 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002604 if (comment.size() > 0) {
2605 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002606 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002607 fprintf(fp,
2608 "%s/** %s\n"
2609 "%s */\n",
2610 getIndentSpace(indent), cmt.string(),
2611 getIndentSpace(indent));
Adam Lesinski282e1812014-01-23 18:17:42 -08002612 }
Jeff Browneb490d62014-06-06 19:43:42 -07002613 ann.printAnnotations(fp, getIndentSpace(indent));
Adam Lesinski282e1812014-01-23 18:17:42 -08002614 fprintf(fp, "%spublic static final String %s=\"%s\";\n",
2615 getIndentSpace(indent),
2616 flattenSymbol(name8).string(), sym.stringVal.string());
2617 }
2618
2619 sp<AaptSymbols> styleableSymbols;
2620
2621 N = symbols->getNestedSymbols().size();
2622 for (i=0; i<N; i++) {
2623 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2624 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2625 if (nclassName == "styleable") {
2626 styleableSymbols = nsymbols;
2627 } else {
Adam Lesinski1e4663852014-08-15 14:47:28 -07002628 err = writeSymbolClass(fp, assets, includePrivate, nsymbols, nclassName,
2629 indent, nonConstantId, false);
Adam Lesinski282e1812014-01-23 18:17:42 -08002630 }
2631 if (err != NO_ERROR) {
2632 return err;
2633 }
2634 }
2635
2636 if (styleableSymbols != NULL) {
Adam Lesinskie8e91922014-08-06 17:41:08 -07002637 err = writeLayoutClasses(fp, assets, styleableSymbols, indent, includePrivate, nonConstantId);
Adam Lesinski282e1812014-01-23 18:17:42 -08002638 if (err != NO_ERROR) {
2639 return err;
2640 }
2641 }
2642
Adam Lesinski1e4663852014-08-15 14:47:28 -07002643 if (emitCallback) {
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002644 fprintf(fp, "%spublic static void onResourcesLoaded(int packageId) {\n",
2645 getIndentSpace(indent));
2646 writeResourceLoadedCallback(fp, assets, includePrivate, symbols, className, indent + 1);
2647 fprintf(fp, "%s}\n", getIndentSpace(indent));
Adam Lesinski1e4663852014-08-15 14:47:28 -07002648 }
2649
Adam Lesinski282e1812014-01-23 18:17:42 -08002650 indent--;
2651 fprintf(fp, "%s}\n", getIndentSpace(indent));
2652 return NO_ERROR;
2653}
2654
2655static status_t writeTextSymbolClass(
2656 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2657 const sp<AaptSymbols>& symbols, const String8& className)
2658{
2659 size_t i;
2660 status_t err = NO_ERROR;
2661
2662 size_t N = symbols->getSymbols().size();
2663 for (i=0; i<N; i++) {
2664 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2665 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
2666 continue;
2667 }
2668
2669 if (!assets->isJavaSymbol(sym, includePrivate)) {
2670 continue;
2671 }
2672
2673 String8 name8(sym.name);
2674 fprintf(fp, "int %s %s 0x%08x\n",
2675 className.string(),
2676 flattenSymbol(name8).string(), (int)sym.int32Val);
2677 }
2678
2679 N = symbols->getNestedSymbols().size();
2680 for (i=0; i<N; i++) {
2681 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2682 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2683 if (nclassName == "styleable") {
2684 err = writeTextLayoutClasses(fp, assets, nsymbols, includePrivate);
2685 } else {
2686 err = writeTextSymbolClass(fp, assets, includePrivate, nsymbols, nclassName);
2687 }
2688 if (err != NO_ERROR) {
2689 return err;
2690 }
2691 }
2692
2693 return NO_ERROR;
2694}
2695
2696status_t writeResourceSymbols(Bundle* bundle, const sp<AaptAssets>& assets,
Adam Lesinski1e4663852014-08-15 14:47:28 -07002697 const String8& package, bool includePrivate, bool emitCallback)
Adam Lesinski282e1812014-01-23 18:17:42 -08002698{
2699 if (!bundle->getRClassDir()) {
2700 return NO_ERROR;
2701 }
2702
2703 const char* textSymbolsDest = bundle->getOutputTextSymbols();
2704
2705 String8 R("R");
2706 const size_t N = assets->getSymbols().size();
2707 for (size_t i=0; i<N; i++) {
2708 sp<AaptSymbols> symbols = assets->getSymbols().valueAt(i);
2709 String8 className(assets->getSymbols().keyAt(i));
2710 String8 dest(bundle->getRClassDir());
2711
2712 if (bundle->getMakePackageDirs()) {
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -07002713 const String8& pkg(package);
Adam Lesinski282e1812014-01-23 18:17:42 -08002714 const char* last = pkg.string();
2715 const char* s = last-1;
2716 do {
2717 s++;
2718 if (s > last && (*s == '.' || *s == 0)) {
2719 String8 part(last, s-last);
2720 dest.appendPath(part);
Elliott Hughese17788c2015-08-17 12:41:46 -07002721#ifdef _WIN32
Adam Lesinski282e1812014-01-23 18:17:42 -08002722 _mkdir(dest.string());
2723#else
2724 mkdir(dest.string(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP);
2725#endif
2726 last = s+1;
2727 }
2728 } while (*s);
2729 }
2730 dest.appendPath(className);
2731 dest.append(".java");
2732 FILE* fp = fopen(dest.string(), "w+");
2733 if (fp == NULL) {
2734 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
2735 dest.string(), strerror(errno));
2736 return UNKNOWN_ERROR;
2737 }
2738 if (bundle->getVerbose()) {
2739 printf(" Writing symbols for class %s.\n", className.string());
2740 }
2741
2742 fprintf(fp,
2743 "/* AUTO-GENERATED FILE. DO NOT MODIFY.\n"
2744 " *\n"
2745 " * This class was automatically generated by the\n"
2746 " * aapt tool from the resource data it found. It\n"
2747 " * should not be modified by hand.\n"
2748 " */\n"
2749 "\n"
2750 "package %s;\n\n", package.string());
2751
2752 status_t err = writeSymbolClass(fp, assets, includePrivate, symbols,
Adam Lesinski1e4663852014-08-15 14:47:28 -07002753 className, 0, bundle->getNonConstantId(), emitCallback);
Elliott Hughesb30296b2013-10-29 15:25:52 -07002754 fclose(fp);
Adam Lesinski282e1812014-01-23 18:17:42 -08002755 if (err != NO_ERROR) {
2756 return err;
2757 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002758
2759 if (textSymbolsDest != NULL && R == className) {
2760 String8 textDest(textSymbolsDest);
2761 textDest.appendPath(className);
2762 textDest.append(".txt");
2763
2764 FILE* fp = fopen(textDest.string(), "w+");
2765 if (fp == NULL) {
2766 fprintf(stderr, "ERROR: Unable to open text symbol file %s: %s\n",
2767 textDest.string(), strerror(errno));
2768 return UNKNOWN_ERROR;
2769 }
2770 if (bundle->getVerbose()) {
2771 printf(" Writing text symbols for class %s.\n", className.string());
2772 }
2773
2774 status_t err = writeTextSymbolClass(fp, assets, includePrivate, symbols,
2775 className);
Elliott Hughesb30296b2013-10-29 15:25:52 -07002776 fclose(fp);
Adam Lesinski282e1812014-01-23 18:17:42 -08002777 if (err != NO_ERROR) {
2778 return err;
2779 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002780 }
2781
2782 // If we were asked to generate a dependency file, we'll go ahead and add this R.java
2783 // as a target in the dependency file right next to it.
2784 if (bundle->getGenDependencies() && R == className) {
2785 // Add this R.java to the dependency file
2786 String8 dependencyFile(bundle->getRClassDir());
2787 dependencyFile.appendPath("R.java.d");
2788
2789 FILE *fp = fopen(dependencyFile.string(), "a");
2790 fprintf(fp,"%s \\\n", dest.string());
2791 fclose(fp);
2792 }
2793 }
2794
2795 return NO_ERROR;
2796}
2797
2798
2799class ProguardKeepSet
2800{
2801public:
2802 // { rule --> { file locations } }
2803 KeyedVector<String8, SortedVector<String8> > rules;
2804
2805 void add(const String8& rule, const String8& where);
2806};
2807
2808void ProguardKeepSet::add(const String8& rule, const String8& where)
2809{
2810 ssize_t index = rules.indexOfKey(rule);
2811 if (index < 0) {
2812 index = rules.add(rule, SortedVector<String8>());
2813 }
2814 rules.editValueAt(index).add(where);
2815}
2816
2817void
2818addProguardKeepRule(ProguardKeepSet* keep, const String8& inClassName,
2819 const char* pkg, const String8& srcName, int line)
2820{
2821 String8 className(inClassName);
2822 if (pkg != NULL) {
2823 // asdf --> package.asdf
2824 // .asdf .a.b --> package.asdf package.a.b
2825 // asdf.adsf --> asdf.asdf
2826 const char* p = className.string();
2827 const char* q = strchr(p, '.');
2828 if (p == q) {
2829 className = pkg;
2830 className.append(inClassName);
2831 } else if (q == NULL) {
2832 className = pkg;
2833 className.append(".");
2834 className.append(inClassName);
2835 }
2836 }
2837
2838 String8 rule("-keep class ");
2839 rule += className;
2840 rule += " { <init>(...); }";
2841
2842 String8 location("view ");
2843 location += srcName;
2844 char lineno[20];
2845 sprintf(lineno, ":%d", line);
2846 location += lineno;
2847
2848 keep->add(rule, location);
2849}
2850
2851void
2852addProguardKeepMethodRule(ProguardKeepSet* keep, const String8& memberName,
Andreas Gampe2412f842014-09-30 20:55:57 -07002853 const char* /* pkg */, const String8& srcName, int line)
Adam Lesinski282e1812014-01-23 18:17:42 -08002854{
2855 String8 rule("-keepclassmembers class * { *** ");
2856 rule += memberName;
2857 rule += "(...); }";
2858
2859 String8 location("onClick ");
2860 location += srcName;
2861 char lineno[20];
2862 sprintf(lineno, ":%d", line);
2863 location += lineno;
2864
2865 keep->add(rule, location);
2866}
2867
2868status_t
Rohit Agrawal682583c2016-04-21 16:29:58 -07002869writeProguardForAndroidManifest(ProguardKeepSet* keep, const sp<AaptAssets>& assets, bool mainDex)
Adam Lesinski282e1812014-01-23 18:17:42 -08002870{
2871 status_t err;
2872 ResXMLTree tree;
2873 size_t len;
2874 ResXMLTree::event_code_t code;
2875 int depth = 0;
2876 bool inApplication = false;
2877 String8 error;
2878 sp<AaptGroup> assGroup;
2879 sp<AaptFile> assFile;
2880 String8 pkg;
Rohit Agrawal682583c2016-04-21 16:29:58 -07002881 String8 defaultProcess;
Adam Lesinski282e1812014-01-23 18:17:42 -08002882
2883 // First, look for a package file to parse. This is required to
2884 // be able to generate the resource information.
2885 assGroup = assets->getFiles().valueFor(String8("AndroidManifest.xml"));
2886 if (assGroup == NULL) {
2887 fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n");
2888 return -1;
2889 }
2890
2891 if (assGroup->getFiles().size() != 1) {
2892 fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
2893 assGroup->getFiles().valueAt(0)->getPrintableSource().string());
2894 }
2895
2896 assFile = assGroup->getFiles().valueAt(0);
2897
2898 err = parseXMLResource(assFile, &tree);
2899 if (err != NO_ERROR) {
2900 return err;
2901 }
2902
2903 tree.restart();
2904
2905 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
2906 if (code == ResXMLTree::END_TAG) {
2907 if (/* name == "Application" && */ depth == 2) {
2908 inApplication = false;
2909 }
2910 depth--;
2911 continue;
2912 }
2913 if (code != ResXMLTree::START_TAG) {
2914 continue;
2915 }
2916 depth++;
2917 String8 tag(tree.getElementName(&len));
2918 // printf("Depth %d tag %s\n", depth, tag.string());
2919 bool keepTag = false;
2920 if (depth == 1) {
2921 if (tag != "manifest") {
2922 fprintf(stderr, "ERROR: manifest does not start with <manifest> tag\n");
2923 return -1;
2924 }
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07002925 pkg = AaptXml::getAttribute(tree, NULL, "package");
Adam Lesinski282e1812014-01-23 18:17:42 -08002926 } else if (depth == 2) {
2927 if (tag == "application") {
2928 inApplication = true;
2929 keepTag = true;
2930
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07002931 String8 agent = AaptXml::getAttribute(tree,
2932 "http://schemas.android.com/apk/res/android",
Adam Lesinski282e1812014-01-23 18:17:42 -08002933 "backupAgent", &error);
2934 if (agent.length() > 0) {
2935 addProguardKeepRule(keep, agent, pkg.string(),
2936 assFile->getPrintableSource(), tree.getLineNumber());
2937 }
Rohit Agrawal682583c2016-04-21 16:29:58 -07002938
2939 if (mainDex) {
2940 defaultProcess = AaptXml::getAttribute(tree,
2941 "http://schemas.android.com/apk/res/android", "process", &error);
2942 if (error != "") {
2943 fprintf(stderr, "ERROR: %s\n", error.string());
2944 return -1;
2945 }
2946 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002947 } else if (tag == "instrumentation") {
2948 keepTag = true;
2949 }
2950 }
2951 if (!keepTag && inApplication && depth == 3) {
2952 if (tag == "activity" || tag == "service" || tag == "receiver" || tag == "provider") {
2953 keepTag = true;
Ivan Gavrilovicf580d912016-07-19 12:03:33 +01002954
2955 if (mainDex) {
2956 String8 componentProcess = 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
2963 const String8& process =
2964 componentProcess.length() > 0 ? componentProcess : defaultProcess;
2965 keepTag = process.length() > 0 && process.find(":") != 0;
2966 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002967 }
2968 }
2969 if (keepTag) {
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07002970 String8 name = AaptXml::getAttribute(tree,
2971 "http://schemas.android.com/apk/res/android", "name", &error);
Adam Lesinski282e1812014-01-23 18:17:42 -08002972 if (error != "") {
2973 fprintf(stderr, "ERROR: %s\n", error.string());
2974 return -1;
2975 }
Rohit Agrawal682583c2016-04-21 16:29:58 -07002976
2977 keepTag = name.length() > 0;
2978
Rohit Agrawal682583c2016-04-21 16:29:58 -07002979 if (keepTag) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002980 addProguardKeepRule(keep, name, pkg.string(),
2981 assFile->getPrintableSource(), tree.getLineNumber());
2982 }
2983 }
2984 }
2985
2986 return NO_ERROR;
2987}
2988
2989struct NamespaceAttributePair {
2990 const char* ns;
2991 const char* attr;
2992
2993 NamespaceAttributePair(const char* n, const char* a) : ns(n), attr(a) {}
2994 NamespaceAttributePair() : ns(NULL), attr(NULL) {}
2995};
2996
2997status_t
2998writeProguardForXml(ProguardKeepSet* keep, const sp<AaptFile>& layoutFile,
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07002999 const Vector<String8>& startTags, const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs)
Adam Lesinski282e1812014-01-23 18:17:42 -08003000{
3001 status_t err;
3002 ResXMLTree tree;
3003 size_t len;
3004 ResXMLTree::event_code_t code;
3005
3006 err = parseXMLResource(layoutFile, &tree);
3007 if (err != NO_ERROR) {
3008 return err;
3009 }
3010
3011 tree.restart();
3012
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003013 if (!startTags.isEmpty()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003014 bool haveStart = false;
3015 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
3016 if (code != ResXMLTree::START_TAG) {
3017 continue;
3018 }
3019 String8 tag(tree.getElementName(&len));
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003020 const size_t numStartTags = startTags.size();
3021 for (size_t i = 0; i < numStartTags; i++) {
3022 if (tag == startTags[i]) {
3023 haveStart = true;
3024 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003025 }
3026 break;
3027 }
3028 if (!haveStart) {
3029 return NO_ERROR;
3030 }
3031 }
3032
3033 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
3034 if (code != ResXMLTree::START_TAG) {
3035 continue;
3036 }
3037 String8 tag(tree.getElementName(&len));
3038
3039 // If there is no '.', we'll assume that it's one of the built in names.
3040 if (strchr(tag.string(), '.')) {
3041 addProguardKeepRule(keep, tag, NULL,
3042 layoutFile->getPrintableSource(), tree.getLineNumber());
3043 } else if (tagAttrPairs != NULL) {
3044 ssize_t tagIndex = tagAttrPairs->indexOfKey(tag);
3045 if (tagIndex >= 0) {
3046 const Vector<NamespaceAttributePair>& nsAttrVector = tagAttrPairs->valueAt(tagIndex);
3047 for (size_t i = 0; i < nsAttrVector.size(); i++) {
3048 const NamespaceAttributePair& nsAttr = nsAttrVector[i];
3049
3050 ssize_t attrIndex = tree.indexOfAttribute(nsAttr.ns, nsAttr.attr);
3051 if (attrIndex < 0) {
3052 // fprintf(stderr, "%s:%d: <%s> does not have attribute %s:%s.\n",
3053 // layoutFile->getPrintableSource().string(), tree.getLineNumber(),
3054 // tag.string(), nsAttr.ns, nsAttr.attr);
3055 } else {
3056 size_t len;
3057 addProguardKeepRule(keep,
3058 String8(tree.getAttributeStringValue(attrIndex, &len)), NULL,
3059 layoutFile->getPrintableSource(), tree.getLineNumber());
3060 }
3061 }
3062 }
3063 }
3064 ssize_t attrIndex = tree.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "onClick");
3065 if (attrIndex >= 0) {
3066 size_t len;
3067 addProguardKeepMethodRule(keep,
3068 String8(tree.getAttributeStringValue(attrIndex, &len)), NULL,
3069 layoutFile->getPrintableSource(), tree.getLineNumber());
3070 }
3071 }
3072
3073 return NO_ERROR;
3074}
3075
3076static void addTagAttrPair(KeyedVector<String8, Vector<NamespaceAttributePair> >* dest,
3077 const char* tag, const char* ns, const char* attr) {
3078 String8 tagStr(tag);
3079 ssize_t index = dest->indexOfKey(tagStr);
3080
3081 if (index < 0) {
3082 Vector<NamespaceAttributePair> vector;
3083 vector.add(NamespaceAttributePair(ns, attr));
3084 dest->add(tagStr, vector);
3085 } else {
3086 dest->editValueAt(index).add(NamespaceAttributePair(ns, attr));
3087 }
3088}
3089
3090status_t
3091writeProguardForLayouts(ProguardKeepSet* keep, const sp<AaptAssets>& assets)
3092{
3093 status_t err;
Adam Lesinski62c5df52014-12-02 16:19:05 -08003094 const char* kClass = "class";
3095 const char* kFragment = "fragment";
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003096 const String8 kTransition("transition");
3097 const String8 kTransitionPrefix("transition-");
Adam Lesinski282e1812014-01-23 18:17:42 -08003098
3099 // tag:attribute pairs that should be checked in layout files.
3100 KeyedVector<String8, Vector<NamespaceAttributePair> > kLayoutTagAttrPairs;
Adam Lesinski62c5df52014-12-02 16:19:05 -08003101 addTagAttrPair(&kLayoutTagAttrPairs, "view", NULL, kClass);
3102 addTagAttrPair(&kLayoutTagAttrPairs, kFragment, NULL, kClass);
3103 addTagAttrPair(&kLayoutTagAttrPairs, kFragment, RESOURCES_ANDROID_NAMESPACE, "name");
Adam Lesinski282e1812014-01-23 18:17:42 -08003104
3105 // tag:attribute pairs that should be checked in xml files.
3106 KeyedVector<String8, Vector<NamespaceAttributePair> > kXmlTagAttrPairs;
Adam Lesinski62c5df52014-12-02 16:19:05 -08003107 addTagAttrPair(&kXmlTagAttrPairs, "PreferenceScreen", RESOURCES_ANDROID_NAMESPACE, kFragment);
3108 addTagAttrPair(&kXmlTagAttrPairs, "header", RESOURCES_ANDROID_NAMESPACE, kFragment);
Adam Lesinski282e1812014-01-23 18:17:42 -08003109
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003110 // tag:attribute pairs that should be checked in transition files.
3111 KeyedVector<String8, Vector<NamespaceAttributePair> > kTransitionTagAttrPairs;
Adam Lesinski62c5df52014-12-02 16:19:05 -08003112 addTagAttrPair(&kTransitionTagAttrPairs, kTransition.string(), NULL, kClass);
3113 addTagAttrPair(&kTransitionTagAttrPairs, "pathMotion", NULL, kClass);
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003114
Adam Lesinski282e1812014-01-23 18:17:42 -08003115 const Vector<sp<AaptDir> >& dirs = assets->resDirs();
3116 const size_t K = dirs.size();
3117 for (size_t k=0; k<K; k++) {
3118 const sp<AaptDir>& d = dirs.itemAt(k);
3119 const String8& dirName = d->getLeaf();
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003120 Vector<String8> startTags;
Adam Lesinski282e1812014-01-23 18:17:42 -08003121 const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs = NULL;
3122 if ((dirName == String8("layout")) || (strncmp(dirName.string(), "layout-", 7) == 0)) {
3123 tagAttrPairs = &kLayoutTagAttrPairs;
3124 } else if ((dirName == String8("xml")) || (strncmp(dirName.string(), "xml-", 4) == 0)) {
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003125 startTags.add(String8("PreferenceScreen"));
3126 startTags.add(String8("preference-headers"));
Adam Lesinski282e1812014-01-23 18:17:42 -08003127 tagAttrPairs = &kXmlTagAttrPairs;
3128 } else if ((dirName == String8("menu")) || (strncmp(dirName.string(), "menu-", 5) == 0)) {
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003129 startTags.add(String8("menu"));
Adam Lesinski282e1812014-01-23 18:17:42 -08003130 tagAttrPairs = NULL;
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003131 } else if (dirName == kTransition || (strncmp(dirName.string(), kTransitionPrefix.string(),
3132 kTransitionPrefix.size()) == 0)) {
3133 tagAttrPairs = &kTransitionTagAttrPairs;
Adam Lesinski282e1812014-01-23 18:17:42 -08003134 } else {
3135 continue;
3136 }
3137
3138 const KeyedVector<String8,sp<AaptGroup> > groups = d->getFiles();
3139 const size_t N = groups.size();
3140 for (size_t i=0; i<N; i++) {
3141 const sp<AaptGroup>& group = groups.valueAt(i);
3142 const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files = group->getFiles();
3143 const size_t M = files.size();
3144 for (size_t j=0; j<M; j++) {
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003145 err = writeProguardForXml(keep, files.valueAt(j), startTags, tagAttrPairs);
Adam Lesinski282e1812014-01-23 18:17:42 -08003146 if (err < 0) {
3147 return err;
3148 }
3149 }
3150 }
3151 }
3152 // Handle the overlays
3153 sp<AaptAssets> overlay = assets->getOverlay();
3154 if (overlay.get()) {
3155 return writeProguardForLayouts(keep, overlay);
3156 }
3157
3158 return NO_ERROR;
3159}
3160
3161status_t
Rohit Agrawal682583c2016-04-21 16:29:58 -07003162writeProguardSpec(const char* filename, const ProguardKeepSet& keep, status_t err)
Adam Lesinski282e1812014-01-23 18:17:42 -08003163{
Rohit Agrawal682583c2016-04-21 16:29:58 -07003164 FILE* fp = fopen(filename, "w+");
Adam Lesinski282e1812014-01-23 18:17:42 -08003165 if (fp == NULL) {
3166 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
Rohit Agrawal682583c2016-04-21 16:29:58 -07003167 filename, strerror(errno));
Adam Lesinski282e1812014-01-23 18:17:42 -08003168 return UNKNOWN_ERROR;
3169 }
3170
3171 const KeyedVector<String8, SortedVector<String8> >& rules = keep.rules;
3172 const size_t N = rules.size();
3173 for (size_t i=0; i<N; i++) {
3174 const SortedVector<String8>& locations = rules.valueAt(i);
3175 const size_t M = locations.size();
3176 for (size_t j=0; j<M; j++) {
3177 fprintf(fp, "# %s\n", locations.itemAt(j).string());
3178 }
3179 fprintf(fp, "%s\n\n", rules.keyAt(i).string());
3180 }
3181 fclose(fp);
3182
3183 return err;
3184}
3185
Rohit Agrawal682583c2016-04-21 16:29:58 -07003186status_t
3187writeProguardFile(Bundle* bundle, const sp<AaptAssets>& assets)
3188{
3189 status_t err = -1;
3190
3191 if (!bundle->getProguardFile()) {
3192 return NO_ERROR;
3193 }
3194
3195 ProguardKeepSet keep;
3196
3197 err = writeProguardForAndroidManifest(&keep, assets, false);
3198 if (err < 0) {
3199 return err;
3200 }
3201
3202 err = writeProguardForLayouts(&keep, assets);
3203 if (err < 0) {
3204 return err;
3205 }
3206
3207 return writeProguardSpec(bundle->getProguardFile(), keep, err);
3208}
3209
3210status_t
3211writeMainDexProguardFile(Bundle* bundle, const sp<AaptAssets>& assets)
3212{
3213 status_t err = -1;
3214
3215 if (!bundle->getMainDexProguardFile()) {
3216 return NO_ERROR;
3217 }
3218
3219 ProguardKeepSet keep;
3220
3221 err = writeProguardForAndroidManifest(&keep, assets, true);
3222 if (err < 0) {
3223 return err;
3224 }
3225
3226 return writeProguardSpec(bundle->getMainDexProguardFile(), keep, err);
3227}
3228
Adam Lesinski282e1812014-01-23 18:17:42 -08003229// Loops through the string paths and writes them to the file pointer
3230// Each file path is written on its own line with a terminating backslash.
3231status_t writePathsToFile(const sp<FilePathStore>& files, FILE* fp)
3232{
3233 status_t deps = -1;
3234 for (size_t file_i = 0; file_i < files->size(); ++file_i) {
3235 // Add the full file path to the dependency file
3236 fprintf(fp, "%s \\\n", files->itemAt(file_i).string());
3237 deps++;
3238 }
3239 return deps;
3240}
3241
3242status_t
Andreas Gampe2412f842014-09-30 20:55:57 -07003243writeDependencyPreReqs(Bundle* /* bundle */, const sp<AaptAssets>& assets, FILE* fp, bool includeRaw)
Adam Lesinski282e1812014-01-23 18:17:42 -08003244{
3245 status_t deps = -1;
3246 deps += writePathsToFile(assets->getFullResPaths(), fp);
3247 if (includeRaw) {
3248 deps += writePathsToFile(assets->getFullAssetPaths(), fp);
3249 }
3250 return deps;
3251}