blob: 18a194326de77b8ab6f3bdf7b6a1e4d2470c528c [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)
Adam Lesinski282e1812014-01-23 18:17:42 -080026# define ZD "%zd"
27# define ZD_TYPE ssize_t
Andreas Gampe2412f842014-09-30 20:55:57 -070028# define STATUST(x) x
Adam Lesinski282e1812014-01-23 18:17:42 -080029#else
30# define ZD "%ld"
31# define ZD_TYPE long
Andreas Gampe2412f842014-09-30 20:55:57 -070032# define STATUST(x) (status_t)x
Adam Lesinski282e1812014-01-23 18:17:42 -080033#endif
34
Andreas Gampe2412f842014-09-30 20:55:57 -070035// Set to true for noisy debug output.
36static const bool kIsDebug = false;
Adam Lesinski282e1812014-01-23 18:17:42 -080037
38// Number of threads to use for preprocessing images.
39static const size_t MAX_THREADS = 4;
40
41// ==========================================================================
42// ==========================================================================
43// ==========================================================================
44
45class PackageInfo
46{
47public:
48 PackageInfo()
49 {
50 }
51 ~PackageInfo()
52 {
53 }
54
55 status_t parsePackage(const sp<AaptGroup>& grp);
56};
57
58// ==========================================================================
59// ==========================================================================
60// ==========================================================================
61
Adam Lesinskie572c012014-09-19 15:10:04 -070062String8 parseResourceName(const String8& leaf)
Adam Lesinski282e1812014-01-23 18:17:42 -080063{
64 const char* firstDot = strchr(leaf.string(), '.');
65 const char* str = leaf.string();
66
67 if (firstDot) {
68 return String8(str, firstDot-str);
69 } else {
70 return String8(str);
71 }
72}
73
74ResourceTypeSet::ResourceTypeSet()
75 :RefBase(),
76 KeyedVector<String8,sp<AaptGroup> >()
77{
78}
79
80FilePathStore::FilePathStore()
81 :RefBase(),
82 Vector<String8>()
83{
84}
85
86class ResourceDirIterator
87{
88public:
89 ResourceDirIterator(const sp<ResourceTypeSet>& set, const String8& resType)
90 : mResType(resType), mSet(set), mSetPos(0), mGroupPos(0)
91 {
Narayan Kamath91447d82014-01-21 15:32:36 +000092 memset(&mParams, 0, sizeof(ResTable_config));
Adam Lesinski282e1812014-01-23 18:17:42 -080093 }
94
95 inline const sp<AaptGroup>& getGroup() const { return mGroup; }
96 inline const sp<AaptFile>& getFile() const { return mFile; }
97
98 inline const String8& getBaseName() const { return mBaseName; }
99 inline const String8& getLeafName() const { return mLeafName; }
100 inline String8 getPath() const { return mPath; }
101 inline const ResTable_config& getParams() const { return mParams; }
102
103 enum {
104 EOD = 1
105 };
106
107 ssize_t next()
108 {
109 while (true) {
110 sp<AaptGroup> group;
111 sp<AaptFile> file;
112
113 // Try to get next file in this current group.
114 if (mGroup != NULL && mGroupPos < mGroup->getFiles().size()) {
115 group = mGroup;
116 file = group->getFiles().valueAt(mGroupPos++);
117
118 // Try to get the next group/file in this directory
119 } else if (mSetPos < mSet->size()) {
120 mGroup = group = mSet->valueAt(mSetPos++);
121 if (group->getFiles().size() < 1) {
122 continue;
123 }
124 file = group->getFiles().valueAt(0);
125 mGroupPos = 1;
126
127 // All done!
128 } else {
129 return EOD;
130 }
131
132 mFile = file;
133
134 String8 leaf(group->getLeaf());
135 mLeafName = String8(leaf);
136 mParams = file->getGroupEntry().toParams();
Andreas Gampe2412f842014-09-30 20:55:57 -0700137 if (kIsDebug) {
138 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",
139 group->getPath().string(), mParams.mcc, mParams.mnc,
140 mParams.language[0] ? mParams.language[0] : '-',
141 mParams.language[1] ? mParams.language[1] : '-',
142 mParams.country[0] ? mParams.country[0] : '-',
143 mParams.country[1] ? mParams.country[1] : '-',
144 mParams.orientation, mParams.uiMode,
145 mParams.density, mParams.touchscreen, mParams.keyboard,
146 mParams.inputFlags, mParams.navigation);
147 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800148 mPath = "res";
149 mPath.appendPath(file->getGroupEntry().toDirName(mResType));
150 mPath.appendPath(leaf);
151 mBaseName = parseResourceName(leaf);
152 if (mBaseName == "") {
153 fprintf(stderr, "Error: malformed resource filename %s\n",
154 file->getPrintableSource().string());
155 return UNKNOWN_ERROR;
156 }
157
Andreas Gampe2412f842014-09-30 20:55:57 -0700158 if (kIsDebug) {
159 printf("file name=%s\n", mBaseName.string());
160 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800161
162 return NO_ERROR;
163 }
164 }
165
166private:
167 String8 mResType;
168
169 const sp<ResourceTypeSet> mSet;
170 size_t mSetPos;
171
172 sp<AaptGroup> mGroup;
173 size_t mGroupPos;
174
175 sp<AaptFile> mFile;
176 String8 mBaseName;
177 String8 mLeafName;
178 String8 mPath;
179 ResTable_config mParams;
180};
181
Jeff Browneb490d62014-06-06 19:43:42 -0700182class AnnotationProcessor {
183public:
184 AnnotationProcessor() : mDeprecated(false), mSystemApi(false) { }
185
186 void preprocessComment(String8& comment) {
187 if (comment.size() > 0) {
188 if (comment.contains("@deprecated")) {
189 mDeprecated = true;
190 }
191 if (comment.removeAll("@SystemApi")) {
192 mSystemApi = true;
193 }
194 }
195 }
196
197 void printAnnotations(FILE* fp, const char* indentStr) {
198 if (mDeprecated) {
199 fprintf(fp, "%s@Deprecated\n", indentStr);
200 }
201 if (mSystemApi) {
202 fprintf(fp, "%s@android.annotation.SystemApi\n", indentStr);
203 }
204 }
205
206private:
207 bool mDeprecated;
208 bool mSystemApi;
209};
210
Adam Lesinski282e1812014-01-23 18:17:42 -0800211// ==========================================================================
212// ==========================================================================
213// ==========================================================================
214
215bool isValidResourceType(const String8& type)
216{
217 return type == "anim" || type == "animator" || type == "interpolator"
Chet Haase7cce7bb2013-09-04 17:41:11 -0700218 || type == "transition"
Adam Lesinski282e1812014-01-23 18:17:42 -0800219 || type == "drawable" || type == "layout"
220 || type == "values" || type == "xml" || type == "raw"
221 || type == "color" || type == "menu" || type == "mipmap";
222}
223
Adam Lesinski282e1812014-01-23 18:17:42 -0800224static status_t parsePackage(Bundle* bundle, const sp<AaptAssets>& assets,
225 const sp<AaptGroup>& grp)
226{
227 if (grp->getFiles().size() != 1) {
228 fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
229 grp->getFiles().valueAt(0)->getPrintableSource().string());
230 }
231
232 sp<AaptFile> file = grp->getFiles().valueAt(0);
233
234 ResXMLTree block;
235 status_t err = parseXMLResource(file, &block);
236 if (err != NO_ERROR) {
237 return err;
238 }
239 //printXMLBlock(&block);
240
241 ResXMLTree::event_code_t code;
242 while ((code=block.next()) != ResXMLTree::START_TAG
243 && code != ResXMLTree::END_DOCUMENT
244 && code != ResXMLTree::BAD_DOCUMENT) {
245 }
246
247 size_t len;
248 if (code != ResXMLTree::START_TAG) {
249 fprintf(stderr, "%s:%d: No start tag found\n",
250 file->getPrintableSource().string(), block.getLineNumber());
251 return UNKNOWN_ERROR;
252 }
253 if (strcmp16(block.getElementName(&len), String16("manifest").string()) != 0) {
254 fprintf(stderr, "%s:%d: Invalid start tag %s, expected <manifest>\n",
255 file->getPrintableSource().string(), block.getLineNumber(),
256 String8(block.getElementName(&len)).string());
257 return UNKNOWN_ERROR;
258 }
259
260 ssize_t nameIndex = block.indexOfAttribute(NULL, "package");
261 if (nameIndex < 0) {
262 fprintf(stderr, "%s:%d: <manifest> does not have package attribute.\n",
263 file->getPrintableSource().string(), block.getLineNumber());
264 return UNKNOWN_ERROR;
265 }
266
267 assets->setPackage(String8(block.getAttributeStringValue(nameIndex, &len)));
268
Adam Lesinski54de2982014-12-16 09:16:26 -0800269 ssize_t revisionCodeIndex = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "revisionCode");
270 if (revisionCodeIndex >= 0) {
271 bundle->setRevisionCode(String8(block.getAttributeStringValue(revisionCodeIndex, &len)).string());
272 }
273
Adam Lesinski282e1812014-01-23 18:17:42 -0800274 String16 uses_sdk16("uses-sdk");
275 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
276 && code != ResXMLTree::BAD_DOCUMENT) {
277 if (code == ResXMLTree::START_TAG) {
278 if (strcmp16(block.getElementName(&len), uses_sdk16.string()) == 0) {
279 ssize_t minSdkIndex = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE,
280 "minSdkVersion");
281 if (minSdkIndex >= 0) {
Dan Albertf348c152014-09-08 18:28:00 -0700282 const char16_t* minSdk16 = block.getAttributeStringValue(minSdkIndex, &len);
Adam Lesinski282e1812014-01-23 18:17:42 -0800283 const char* minSdk8 = strdup(String8(minSdk16).string());
284 bundle->setManifestMinSdkVersion(minSdk8);
285 }
286 }
287 }
288 }
289
290 return NO_ERROR;
291}
292
293// ==========================================================================
294// ==========================================================================
295// ==========================================================================
296
297static status_t makeFileResources(Bundle* bundle, const sp<AaptAssets>& assets,
298 ResourceTable* table,
299 const sp<ResourceTypeSet>& set,
300 const char* resType)
301{
302 String8 type8(resType);
303 String16 type16(resType);
304
305 bool hasErrors = false;
306
307 ResourceDirIterator it(set, String8(resType));
308 ssize_t res;
309 while ((res=it.next()) == NO_ERROR) {
310 if (bundle->getVerbose()) {
311 printf(" (new resource id %s from %s)\n",
312 it.getBaseName().string(), it.getFile()->getPrintableSource().string());
313 }
314 String16 baseName(it.getBaseName());
315 const char16_t* str = baseName.string();
316 const char16_t* const end = str + baseName.size();
317 while (str < end) {
318 if (!((*str >= 'a' && *str <= 'z')
319 || (*str >= '0' && *str <= '9')
320 || *str == '_' || *str == '.')) {
321 fprintf(stderr, "%s: Invalid file name: must contain only [a-z0-9_.]\n",
322 it.getPath().string());
323 hasErrors = true;
324 }
325 str++;
326 }
327 String8 resPath = it.getPath();
328 resPath.convertToResPath();
329 table->addEntry(SourcePos(it.getPath(), 0), String16(assets->getPackage()),
330 type16,
331 baseName,
332 String16(resPath),
333 NULL,
334 &it.getParams());
335 assets->addResource(it.getLeafName(), resPath, it.getFile(), type8);
336 }
337
Andreas Gampe2412f842014-09-30 20:55:57 -0700338 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -0800339}
340
341class PreProcessImageWorkUnit : public WorkQueue::WorkUnit {
342public:
343 PreProcessImageWorkUnit(const Bundle* bundle, const sp<AaptAssets>& assets,
344 const sp<AaptFile>& file, volatile bool* hasErrors) :
345 mBundle(bundle), mAssets(assets), mFile(file), mHasErrors(hasErrors) {
346 }
347
348 virtual bool run() {
349 status_t status = preProcessImage(mBundle, mAssets, mFile, NULL);
350 if (status) {
351 *mHasErrors = true;
352 }
353 return true; // continue even if there are errors
354 }
355
356private:
357 const Bundle* mBundle;
358 sp<AaptAssets> mAssets;
359 sp<AaptFile> mFile;
360 volatile bool* mHasErrors;
361};
362
363static status_t preProcessImages(const Bundle* bundle, const sp<AaptAssets>& assets,
364 const sp<ResourceTypeSet>& set, const char* type)
365{
366 volatile bool hasErrors = false;
367 ssize_t res = NO_ERROR;
368 if (bundle->getUseCrunchCache() == false) {
369 WorkQueue wq(MAX_THREADS, false);
370 ResourceDirIterator it(set, String8(type));
371 while ((res=it.next()) == NO_ERROR) {
372 PreProcessImageWorkUnit* w = new PreProcessImageWorkUnit(
373 bundle, assets, it.getFile(), &hasErrors);
374 status_t status = wq.schedule(w);
375 if (status) {
376 fprintf(stderr, "preProcessImages failed: schedule() returned %d\n", status);
377 hasErrors = true;
378 delete w;
379 break;
380 }
381 }
382 status_t status = wq.finish();
383 if (status) {
384 fprintf(stderr, "preProcessImages failed: finish() returned %d\n", status);
385 hasErrors = true;
386 }
387 }
Andreas Gampe2412f842014-09-30 20:55:57 -0700388 return (hasErrors || (res < NO_ERROR)) ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -0800389}
390
Adam Lesinski282e1812014-01-23 18:17:42 -0800391static void collect_files(const sp<AaptDir>& dir,
392 KeyedVector<String8, sp<ResourceTypeSet> >* resources)
393{
394 const DefaultKeyedVector<String8, sp<AaptGroup> >& groups = dir->getFiles();
395 int N = groups.size();
396 for (int i=0; i<N; i++) {
397 String8 leafName = groups.keyAt(i);
398 const sp<AaptGroup>& group = groups.valueAt(i);
399
400 const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files
401 = group->getFiles();
402
403 if (files.size() == 0) {
404 continue;
405 }
406
407 String8 resType = files.valueAt(0)->getResourceType();
408
409 ssize_t index = resources->indexOfKey(resType);
410
411 if (index < 0) {
412 sp<ResourceTypeSet> set = new ResourceTypeSet();
Andreas Gampe2412f842014-09-30 20:55:57 -0700413 if (kIsDebug) {
414 printf("Creating new resource type set for leaf %s with group %s (%p)\n",
415 leafName.string(), group->getPath().string(), group.get());
416 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800417 set->add(leafName, group);
418 resources->add(resType, set);
419 } else {
420 sp<ResourceTypeSet> set = resources->valueAt(index);
421 index = set->indexOfKey(leafName);
422 if (index < 0) {
Andreas Gampe2412f842014-09-30 20:55:57 -0700423 if (kIsDebug) {
424 printf("Adding to resource type set for leaf %s group %s (%p)\n",
425 leafName.string(), group->getPath().string(), group.get());
426 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800427 set->add(leafName, group);
428 } else {
429 sp<AaptGroup> existingGroup = set->valueAt(index);
Andreas Gampe2412f842014-09-30 20:55:57 -0700430 if (kIsDebug) {
431 printf("Extending to resource type set for leaf %s group %s (%p)\n",
432 leafName.string(), group->getPath().string(), group.get());
433 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800434 for (size_t j=0; j<files.size(); j++) {
Andreas Gampe2412f842014-09-30 20:55:57 -0700435 if (kIsDebug) {
436 printf("Adding file %s in group %s resType %s\n",
437 files.valueAt(j)->getSourceFile().string(),
438 files.keyAt(j).toDirName(String8()).string(),
439 resType.string());
440 }
441 existingGroup->addFile(files.valueAt(j));
Adam Lesinski282e1812014-01-23 18:17:42 -0800442 }
443 }
444 }
445 }
446}
447
448static void collect_files(const sp<AaptAssets>& ass,
449 KeyedVector<String8, sp<ResourceTypeSet> >* resources)
450{
451 const Vector<sp<AaptDir> >& dirs = ass->resDirs();
452 int N = dirs.size();
453
454 for (int i=0; i<N; i++) {
455 sp<AaptDir> d = dirs.itemAt(i);
Andreas Gampe2412f842014-09-30 20:55:57 -0700456 if (kIsDebug) {
457 printf("Collecting dir #%d %p: %s, leaf %s\n", i, d.get(), d->getPath().string(),
458 d->getLeaf().string());
459 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800460 collect_files(d, resources);
461
462 // don't try to include the res dir
Andreas Gampe2412f842014-09-30 20:55:57 -0700463 if (kIsDebug) {
464 printf("Removing dir leaf %s\n", d->getLeaf().string());
465 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800466 ass->removeDir(d->getLeaf());
467 }
468}
469
470enum {
471 ATTR_OKAY = -1,
472 ATTR_NOT_FOUND = -2,
473 ATTR_LEADING_SPACES = -3,
474 ATTR_TRAILING_SPACES = -4
475};
476static int validateAttr(const String8& path, const ResTable& table,
477 const ResXMLParser& parser,
478 const char* ns, const char* attr, const char* validChars, bool required)
479{
480 size_t len;
481
482 ssize_t index = parser.indexOfAttribute(ns, attr);
Dan Albertf348c152014-09-08 18:28:00 -0700483 const char16_t* str;
Adam Lesinski282e1812014-01-23 18:17:42 -0800484 Res_value value;
485 if (index >= 0 && parser.getAttributeValue(index, &value) >= 0) {
486 const ResStringPool* pool = &parser.getStrings();
487 if (value.dataType == Res_value::TYPE_REFERENCE) {
488 uint32_t specFlags = 0;
489 int strIdx;
490 if ((strIdx=table.resolveReference(&value, 0x10000000, NULL, &specFlags)) < 0) {
491 fprintf(stderr, "%s:%d: Tag <%s> attribute %s references unknown resid 0x%08x.\n",
492 path.string(), parser.getLineNumber(),
493 String8(parser.getElementName(&len)).string(), attr,
494 value.data);
495 return ATTR_NOT_FOUND;
496 }
497
498 pool = table.getTableStringBlock(strIdx);
499 #if 0
500 if (pool != NULL) {
501 str = pool->stringAt(value.data, &len);
502 }
503 printf("***** RES ATTR: %s specFlags=0x%x strIdx=%d: %s\n", attr,
504 specFlags, strIdx, str != NULL ? String8(str).string() : "???");
505 #endif
506 if ((specFlags&~ResTable_typeSpec::SPEC_PUBLIC) != 0 && false) {
507 fprintf(stderr, "%s:%d: Tag <%s> attribute %s varies by configurations 0x%x.\n",
508 path.string(), parser.getLineNumber(),
509 String8(parser.getElementName(&len)).string(), attr,
510 specFlags);
511 return ATTR_NOT_FOUND;
512 }
513 }
514 if (value.dataType == Res_value::TYPE_STRING) {
515 if (pool == NULL) {
516 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has no string block.\n",
517 path.string(), parser.getLineNumber(),
518 String8(parser.getElementName(&len)).string(), attr);
519 return ATTR_NOT_FOUND;
520 }
521 if ((str=pool->stringAt(value.data, &len)) == NULL) {
522 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has corrupt string value.\n",
523 path.string(), parser.getLineNumber(),
524 String8(parser.getElementName(&len)).string(), attr);
525 return ATTR_NOT_FOUND;
526 }
527 } else {
528 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has invalid type %d.\n",
529 path.string(), parser.getLineNumber(),
530 String8(parser.getElementName(&len)).string(), attr,
531 value.dataType);
532 return ATTR_NOT_FOUND;
533 }
534 if (validChars) {
535 for (size_t i=0; i<len; i++) {
Adam Lesinski4bf58102014-11-03 11:21:19 -0800536 char16_t c = str[i];
Adam Lesinski282e1812014-01-23 18:17:42 -0800537 const char* p = validChars;
538 bool okay = false;
539 while (*p) {
540 if (c == *p) {
541 okay = true;
542 break;
543 }
544 p++;
545 }
546 if (!okay) {
547 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has invalid character '%c'.\n",
548 path.string(), parser.getLineNumber(),
549 String8(parser.getElementName(&len)).string(), attr, (char)str[i]);
550 return (int)i;
551 }
552 }
553 }
554 if (*str == ' ') {
555 fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not start with a space.\n",
556 path.string(), parser.getLineNumber(),
557 String8(parser.getElementName(&len)).string(), attr);
558 return ATTR_LEADING_SPACES;
559 }
Dan Albertd395f792014-10-20 14:44:39 -0700560 if (len != 0 && str[len-1] == ' ') {
Adam Lesinski282e1812014-01-23 18:17:42 -0800561 fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not end with a space.\n",
562 path.string(), parser.getLineNumber(),
563 String8(parser.getElementName(&len)).string(), attr);
564 return ATTR_TRAILING_SPACES;
565 }
566 return ATTR_OKAY;
567 }
568 if (required) {
569 fprintf(stderr, "%s:%d: Tag <%s> missing required attribute %s.\n",
570 path.string(), parser.getLineNumber(),
571 String8(parser.getElementName(&len)).string(), attr);
572 return ATTR_NOT_FOUND;
573 }
574 return ATTR_OKAY;
575}
576
577static void checkForIds(const String8& path, ResXMLParser& parser)
578{
579 ResXMLTree::event_code_t code;
580 while ((code=parser.next()) != ResXMLTree::END_DOCUMENT
581 && code > ResXMLTree::BAD_DOCUMENT) {
582 if (code == ResXMLTree::START_TAG) {
583 ssize_t index = parser.indexOfAttribute(NULL, "id");
584 if (index >= 0) {
585 fprintf(stderr, "%s:%d: warning: found plain 'id' attribute; did you mean the new 'android:id' name?\n",
586 path.string(), parser.getLineNumber());
587 }
588 }
589 }
590}
591
592static bool applyFileOverlay(Bundle *bundle,
593 const sp<AaptAssets>& assets,
594 sp<ResourceTypeSet> *baseSet,
595 const char *resType)
596{
597 if (bundle->getVerbose()) {
598 printf("applyFileOverlay for %s\n", resType);
599 }
600
601 // Replace any base level files in this category with any found from the overlay
602 // Also add any found only in the overlay.
603 sp<AaptAssets> overlay = assets->getOverlay();
604 String8 resTypeString(resType);
605
606 // work through the linked list of overlays
607 while (overlay.get()) {
608 KeyedVector<String8, sp<ResourceTypeSet> >* overlayRes = overlay->getResources();
609
610 // get the overlay resources of the requested type
611 ssize_t index = overlayRes->indexOfKey(resTypeString);
612 if (index >= 0) {
613 sp<ResourceTypeSet> overlaySet = overlayRes->valueAt(index);
614
615 // for each of the resources, check for a match in the previously built
616 // non-overlay "baseset".
617 size_t overlayCount = overlaySet->size();
618 for (size_t overlayIndex=0; overlayIndex<overlayCount; overlayIndex++) {
619 if (bundle->getVerbose()) {
620 printf("trying overlaySet Key=%s\n",overlaySet->keyAt(overlayIndex).string());
621 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700622 ssize_t baseIndex = -1;
Adam Lesinski282e1812014-01-23 18:17:42 -0800623 if (baseSet->get() != NULL) {
624 baseIndex = (*baseSet)->indexOfKey(overlaySet->keyAt(overlayIndex));
625 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700626 if (baseIndex >= 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800627 // look for same flavor. For a given file (strings.xml, for example)
628 // there may be a locale specific or other flavors - we want to match
629 // the same flavor.
630 sp<AaptGroup> overlayGroup = overlaySet->valueAt(overlayIndex);
631 sp<AaptGroup> baseGroup = (*baseSet)->valueAt(baseIndex);
632
633 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > overlayFiles =
634 overlayGroup->getFiles();
635 if (bundle->getVerbose()) {
636 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > baseFiles =
637 baseGroup->getFiles();
638 for (size_t i=0; i < baseFiles.size(); i++) {
639 printf("baseFile " ZD " has flavor %s\n", (ZD_TYPE) i,
640 baseFiles.keyAt(i).toString().string());
641 }
642 for (size_t i=0; i < overlayFiles.size(); i++) {
643 printf("overlayFile " ZD " has flavor %s\n", (ZD_TYPE) i,
644 overlayFiles.keyAt(i).toString().string());
645 }
646 }
647
648 size_t overlayGroupSize = overlayFiles.size();
649 for (size_t overlayGroupIndex = 0;
650 overlayGroupIndex<overlayGroupSize;
651 overlayGroupIndex++) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700652 ssize_t baseFileIndex =
Adam Lesinski282e1812014-01-23 18:17:42 -0800653 baseGroup->getFiles().indexOfKey(overlayFiles.
654 keyAt(overlayGroupIndex));
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700655 if (baseFileIndex >= 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800656 if (bundle->getVerbose()) {
657 printf("found a match (" ZD ") for overlay file %s, for flavor %s\n",
658 (ZD_TYPE) baseFileIndex,
659 overlayGroup->getLeaf().string(),
660 overlayFiles.keyAt(overlayGroupIndex).toString().string());
661 }
662 baseGroup->removeFile(baseFileIndex);
663 } else {
664 // didn't find a match fall through and add it..
665 if (true || bundle->getVerbose()) {
666 printf("nothing matches overlay file %s, for flavor %s\n",
667 overlayGroup->getLeaf().string(),
668 overlayFiles.keyAt(overlayGroupIndex).toString().string());
669 }
670 }
671 baseGroup->addFile(overlayFiles.valueAt(overlayGroupIndex));
672 assets->addGroupEntry(overlayFiles.keyAt(overlayGroupIndex));
673 }
674 } else {
675 if (baseSet->get() == NULL) {
676 *baseSet = new ResourceTypeSet();
677 assets->getResources()->add(String8(resType), *baseSet);
678 }
679 // this group doesn't exist (a file that's only in the overlay)
680 (*baseSet)->add(overlaySet->keyAt(overlayIndex),
681 overlaySet->valueAt(overlayIndex));
682 // make sure all flavors are defined in the resources.
683 sp<AaptGroup> overlayGroup = overlaySet->valueAt(overlayIndex);
684 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > overlayFiles =
685 overlayGroup->getFiles();
686 size_t overlayGroupSize = overlayFiles.size();
687 for (size_t overlayGroupIndex = 0;
688 overlayGroupIndex<overlayGroupSize;
689 overlayGroupIndex++) {
690 assets->addGroupEntry(overlayFiles.keyAt(overlayGroupIndex));
691 }
692 }
693 }
694 // this overlay didn't have resources for this type
695 }
696 // try next overlay
697 overlay = overlay->getOverlay();
698 }
699 return true;
700}
701
702/*
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800703 * Inserts an attribute in a given node.
Adam Lesinski282e1812014-01-23 18:17:42 -0800704 * If errorOnFailedInsert is true, and the attribute already exists, returns false.
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800705 * If replaceExisting is true, the attribute will be updated if it already exists.
706 * Returns true otherwise, even if the attribute already exists, and does not modify
707 * the existing attribute's value.
Adam Lesinski282e1812014-01-23 18:17:42 -0800708 */
709bool addTagAttribute(const sp<XMLNode>& node, const char* ns8,
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800710 const char* attr8, const char* value, bool errorOnFailedInsert,
711 bool replaceExisting)
Adam Lesinski282e1812014-01-23 18:17:42 -0800712{
713 if (value == NULL) {
714 return true;
715 }
716
717 const String16 ns(ns8);
718 const String16 attr(attr8);
719
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800720 XMLNode::attribute_entry* existingEntry = node->editAttribute(ns, attr);
721 if (existingEntry != NULL) {
722 if (replaceExisting) {
Andreas Gampe87332a72014-10-01 22:03:58 -0700723 if (kIsDebug) {
724 printf("Info: AndroidManifest.xml already defines %s (in %s);"
725 " overwriting existing value from manifest.\n",
726 String8(attr).string(), String8(ns).string());
727 }
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800728 existingEntry->string = String16(value);
729 return true;
730 }
731
Adam Lesinski282e1812014-01-23 18:17:42 -0800732 if (errorOnFailedInsert) {
733 fprintf(stderr, "Error: AndroidManifest.xml already defines %s (in %s);"
734 " cannot insert new value %s.\n",
735 String8(attr).string(), String8(ns).string(), value);
736 return false;
737 }
738
739 fprintf(stderr, "Warning: AndroidManifest.xml already defines %s (in %s);"
740 " using existing value in manifest.\n",
741 String8(attr).string(), String8(ns).string());
742
743 // don't stop the build.
744 return true;
745 }
746
747 node->addAttribute(ns, attr, String16(value));
748 return true;
749}
750
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800751/*
752 * Inserts an attribute in a given node, only if the attribute does not
753 * exist.
754 * If errorOnFailedInsert is true, and the attribute already exists, returns false.
755 * Returns true otherwise, even if the attribute already exists.
756 */
757bool addTagAttribute(const sp<XMLNode>& node, const char* ns8,
758 const char* attr8, const char* value, bool errorOnFailedInsert)
759{
760 return addTagAttribute(node, ns8, attr8, value, errorOnFailedInsert, false);
761}
762
Adam Lesinski282e1812014-01-23 18:17:42 -0800763static void fullyQualifyClassName(const String8& package, sp<XMLNode> node,
764 const String16& attrName) {
765 XMLNode::attribute_entry* attr = node->editAttribute(
766 String16("http://schemas.android.com/apk/res/android"), attrName);
767 if (attr != NULL) {
768 String8 name(attr->string);
769
770 // asdf --> package.asdf
771 // .asdf .a.b --> package.asdf package.a.b
772 // asdf.adsf --> asdf.asdf
773 String8 className;
774 const char* p = name.string();
775 const char* q = strchr(p, '.');
776 if (p == q) {
777 className += package;
778 className += name;
779 } else if (q == NULL) {
780 className += package;
781 className += ".";
782 className += name;
783 } else {
784 className += name;
785 }
Andreas Gampe2412f842014-09-30 20:55:57 -0700786 if (kIsDebug) {
787 printf("Qualifying class '%s' to '%s'", name.string(), className.string());
788 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800789 attr->string.setTo(String16(className));
790 }
791}
792
793status_t massageManifest(Bundle* bundle, sp<XMLNode> root)
794{
795 root = root->searchElement(String16(), String16("manifest"));
796 if (root == NULL) {
797 fprintf(stderr, "No <manifest> tag.\n");
798 return UNKNOWN_ERROR;
799 }
800
801 bool errorOnFailedInsert = bundle->getErrorOnFailedInsert();
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800802 bool replaceVersion = bundle->getReplaceVersion();
Adam Lesinski282e1812014-01-23 18:17:42 -0800803
804 if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionCode",
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800805 bundle->getVersionCode(), errorOnFailedInsert, replaceVersion)) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800806 return UNKNOWN_ERROR;
Adam Lesinski6a7d2752014-08-07 21:26:53 -0700807 } else {
808 const XMLNode::attribute_entry* attr = root->getAttribute(
809 String16(RESOURCES_ANDROID_NAMESPACE), String16("versionCode"));
810 if (attr != NULL) {
811 bundle->setVersionCode(strdup(String8(attr->string).string()));
812 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800813 }
Adam Lesinski6a7d2752014-08-07 21:26:53 -0700814
Adam Lesinski282e1812014-01-23 18:17:42 -0800815 if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionName",
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800816 bundle->getVersionName(), errorOnFailedInsert, replaceVersion)) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800817 return UNKNOWN_ERROR;
Adam Lesinski82a2dd82014-09-17 18:34:15 -0700818 } else {
819 const XMLNode::attribute_entry* attr = root->getAttribute(
820 String16(RESOURCES_ANDROID_NAMESPACE), String16("versionName"));
821 if (attr != NULL) {
822 bundle->setVersionName(strdup(String8(attr->string).string()));
823 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800824 }
825
Adam Lesinski82a2dd82014-09-17 18:34:15 -0700826 sp<XMLNode> vers = root->getChildElement(String16(), String16("uses-sdk"));
Adam Lesinski282e1812014-01-23 18:17:42 -0800827 if (bundle->getMinSdkVersion() != NULL
828 || bundle->getTargetSdkVersion() != NULL
829 || bundle->getMaxSdkVersion() != NULL) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800830 if (vers == NULL) {
831 vers = XMLNode::newElement(root->getFilename(), String16(), String16("uses-sdk"));
832 root->insertChildAt(vers, 0);
833 }
834
835 if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "minSdkVersion",
836 bundle->getMinSdkVersion(), errorOnFailedInsert)) {
837 return UNKNOWN_ERROR;
838 }
839 if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "targetSdkVersion",
840 bundle->getTargetSdkVersion(), errorOnFailedInsert)) {
841 return UNKNOWN_ERROR;
842 }
843 if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "maxSdkVersion",
844 bundle->getMaxSdkVersion(), errorOnFailedInsert)) {
845 return UNKNOWN_ERROR;
846 }
847 }
848
Adam Lesinski82a2dd82014-09-17 18:34:15 -0700849 if (vers != NULL) {
850 const XMLNode::attribute_entry* attr = vers->getAttribute(
851 String16(RESOURCES_ANDROID_NAMESPACE), String16("minSdkVersion"));
852 if (attr != NULL) {
853 bundle->setMinSdkVersion(strdup(String8(attr->string).string()));
854 }
855 }
856
Adam Lesinskiad2d07d2014-08-27 16:21:08 -0700857 if (bundle->getPlatformBuildVersionCode() != "") {
858 if (!addTagAttribute(root, "", "platformBuildVersionCode",
859 bundle->getPlatformBuildVersionCode(), errorOnFailedInsert, true)) {
860 return UNKNOWN_ERROR;
861 }
862 }
863
864 if (bundle->getPlatformBuildVersionName() != "") {
865 if (!addTagAttribute(root, "", "platformBuildVersionName",
866 bundle->getPlatformBuildVersionName(), errorOnFailedInsert, true)) {
867 return UNKNOWN_ERROR;
868 }
869 }
870
Adam Lesinski282e1812014-01-23 18:17:42 -0800871 if (bundle->getDebugMode()) {
872 sp<XMLNode> application = root->getChildElement(String16(), String16("application"));
873 if (application != NULL) {
874 if (!addTagAttribute(application, RESOURCES_ANDROID_NAMESPACE, "debuggable", "true",
875 errorOnFailedInsert)) {
876 return UNKNOWN_ERROR;
877 }
878 }
879 }
880
881 // Deal with manifest package name overrides
882 const char* manifestPackageNameOverride = bundle->getManifestPackageNameOverride();
883 if (manifestPackageNameOverride != NULL) {
884 // Update the actual package name
885 XMLNode::attribute_entry* attr = root->editAttribute(String16(), String16("package"));
886 if (attr == NULL) {
887 fprintf(stderr, "package name is required with --rename-manifest-package.\n");
888 return UNKNOWN_ERROR;
889 }
890 String8 origPackage(attr->string);
891 attr->string.setTo(String16(manifestPackageNameOverride));
Andreas Gampe2412f842014-09-30 20:55:57 -0700892 if (kIsDebug) {
893 printf("Overriding package '%s' to be '%s'\n", origPackage.string(),
894 manifestPackageNameOverride);
895 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800896
897 // Make class names fully qualified
898 sp<XMLNode> application = root->getChildElement(String16(), String16("application"));
899 if (application != NULL) {
900 fullyQualifyClassName(origPackage, application, String16("name"));
901 fullyQualifyClassName(origPackage, application, String16("backupAgent"));
902
903 Vector<sp<XMLNode> >& children = const_cast<Vector<sp<XMLNode> >&>(application->getChildren());
904 for (size_t i = 0; i < children.size(); i++) {
905 sp<XMLNode> child = children.editItemAt(i);
906 String8 tag(child->getElementName());
907 if (tag == "activity" || tag == "service" || tag == "receiver" || tag == "provider") {
908 fullyQualifyClassName(origPackage, child, String16("name"));
909 } else if (tag == "activity-alias") {
910 fullyQualifyClassName(origPackage, child, String16("name"));
911 fullyQualifyClassName(origPackage, child, String16("targetActivity"));
912 }
913 }
914 }
915 }
916
917 // Deal with manifest package name overrides
918 const char* instrumentationPackageNameOverride = bundle->getInstrumentationPackageNameOverride();
919 if (instrumentationPackageNameOverride != NULL) {
920 // Fix up instrumentation targets.
921 Vector<sp<XMLNode> >& children = const_cast<Vector<sp<XMLNode> >&>(root->getChildren());
922 for (size_t i = 0; i < children.size(); i++) {
923 sp<XMLNode> child = children.editItemAt(i);
924 String8 tag(child->getElementName());
925 if (tag == "instrumentation") {
926 XMLNode::attribute_entry* attr = child->editAttribute(
927 String16("http://schemas.android.com/apk/res/android"), String16("targetPackage"));
928 if (attr != NULL) {
929 attr->string.setTo(String16(instrumentationPackageNameOverride));
930 }
931 }
932 }
933 }
934
Adam Lesinski833f3cc2014-06-18 15:06:01 -0700935 // Generate split name if feature is present.
936 const XMLNode::attribute_entry* attr = root->getAttribute(String16(), String16("featureName"));
937 if (attr != NULL) {
938 String16 splitName("feature_");
939 splitName.append(attr->string);
940 status_t err = root->addAttribute(String16(), String16("split"), splitName);
941 if (err != NO_ERROR) {
942 ALOGE("Failed to insert split name into AndroidManifest.xml");
943 return err;
944 }
945 }
946
Adam Lesinski282e1812014-01-23 18:17:42 -0800947 return NO_ERROR;
948}
949
Adam Lesinskiad2d07d2014-08-27 16:21:08 -0700950static int32_t getPlatformAssetCookie(const AssetManager& assets) {
951 // Find the system package (0x01). AAPT always generates attributes
952 // with the type 0x01, so we're looking for the first attribute
953 // resource in the system package.
954 const ResTable& table = assets.getResources(true);
955 Res_value val;
956 ssize_t idx = table.getResource(0x01010000, &val, true);
957 if (idx != NO_ERROR) {
958 // Try as a bag.
959 const ResTable::bag_entry* entry;
960 ssize_t cnt = table.lockBag(0x01010000, &entry);
961 if (cnt >= 0) {
962 idx = entry->stringBlock;
963 }
964 table.unlockBag(entry);
965 }
966
967 if (idx < 0) {
968 return 0;
969 }
970 return table.getTableCookie(idx);
971}
972
973enum {
974 VERSION_CODE_ATTR = 0x0101021b,
975 VERSION_NAME_ATTR = 0x0101021c,
976};
977
978static ssize_t extractPlatformBuildVersion(ResXMLTree& tree, Bundle* bundle) {
979 size_t len;
980 ResXMLTree::event_code_t code;
981 while ((code = tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
982 if (code != ResXMLTree::START_TAG) {
983 continue;
984 }
985
986 const char16_t* ctag16 = tree.getElementName(&len);
987 if (ctag16 == NULL) {
988 fprintf(stderr, "ERROR: failed to get XML element name (bad string pool)\n");
989 return UNKNOWN_ERROR;
990 }
991
992 String8 tag(ctag16, len);
993 if (tag != "manifest") {
994 continue;
995 }
996
997 String8 error;
998 int32_t versionCode = AaptXml::getIntegerAttribute(tree, VERSION_CODE_ATTR, &error);
999 if (error != "") {
1000 fprintf(stderr, "ERROR: failed to get platform version code\n");
1001 return UNKNOWN_ERROR;
1002 }
1003
1004 if (versionCode >= 0 && bundle->getPlatformBuildVersionCode() == "") {
1005 bundle->setPlatformBuildVersionCode(String8::format("%d", versionCode));
1006 }
1007
1008 String8 versionName = AaptXml::getAttribute(tree, VERSION_NAME_ATTR, &error);
1009 if (error != "") {
1010 fprintf(stderr, "ERROR: failed to get platform version name\n");
1011 return UNKNOWN_ERROR;
1012 }
1013
1014 if (versionName != "" && bundle->getPlatformBuildVersionName() == "") {
1015 bundle->setPlatformBuildVersionName(versionName);
1016 }
1017 return NO_ERROR;
1018 }
1019
1020 fprintf(stderr, "ERROR: no <manifest> tag found in platform AndroidManifest.xml\n");
1021 return UNKNOWN_ERROR;
1022}
1023
1024static ssize_t extractPlatformBuildVersion(AssetManager& assets, Bundle* bundle) {
1025 int32_t cookie = getPlatformAssetCookie(assets);
1026 if (cookie == 0) {
Adam Lesinski82a2dd82014-09-17 18:34:15 -07001027 // No platform was loaded.
1028 return NO_ERROR;
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001029 }
1030
1031 ResXMLTree tree;
1032 Asset* asset = assets.openNonAsset(cookie, "AndroidManifest.xml", Asset::ACCESS_STREAMING);
1033 if (asset == NULL) {
1034 fprintf(stderr, "ERROR: Platform AndroidManifest.xml not found\n");
1035 return UNKNOWN_ERROR;
1036 }
1037
1038 ssize_t result = NO_ERROR;
1039 if (tree.setTo(asset->getBuffer(true), asset->getLength()) != NO_ERROR) {
1040 fprintf(stderr, "ERROR: Platform AndroidManifest.xml is corrupt\n");
1041 result = UNKNOWN_ERROR;
1042 } else {
1043 result = extractPlatformBuildVersion(tree, bundle);
1044 }
1045
1046 delete asset;
1047 return result;
1048}
1049
Adam Lesinski282e1812014-01-23 18:17:42 -08001050#define ASSIGN_IT(n) \
1051 do { \
1052 ssize_t index = resources->indexOfKey(String8(#n)); \
1053 if (index >= 0) { \
1054 n ## s = resources->valueAt(index); \
1055 } \
1056 } while (0)
1057
1058status_t updatePreProcessedCache(Bundle* bundle)
1059{
1060 #if BENCHMARK
1061 fprintf(stdout, "BENCHMARK: Starting PNG PreProcessing \n");
1062 long startPNGTime = clock();
1063 #endif /* BENCHMARK */
1064
1065 String8 source(bundle->getResourceSourceDirs()[0]);
1066 String8 dest(bundle->getCrunchedOutputDir());
1067
1068 FileFinder* ff = new SystemFileFinder();
1069 CrunchCache cc(source,dest,ff);
1070
1071 CacheUpdater* cu = new SystemCacheUpdater(bundle);
1072 size_t numFiles = cc.crunch(cu);
1073
1074 if (bundle->getVerbose())
1075 fprintf(stdout, "Crunched %d PNG files to update cache\n", (int)numFiles);
1076
1077 delete ff;
1078 delete cu;
1079
1080 #if BENCHMARK
1081 fprintf(stdout, "BENCHMARK: End PNG PreProcessing. Time Elapsed: %f ms \n"
1082 ,(clock() - startPNGTime)/1000.0);
1083 #endif /* BENCHMARK */
1084 return 0;
1085}
1086
Jeff Sharkey2cfc8482014-07-09 16:10:16 -07001087status_t generateAndroidManifestForSplit(Bundle* bundle, const sp<AaptAssets>& assets,
1088 const sp<ApkSplit>& split, sp<AaptFile>& outFile, ResourceTable* table) {
Adam Lesinskifab50872014-04-16 14:40:42 -07001089 const String8 filename("AndroidManifest.xml");
1090 const String16 androidPrefix("android");
1091 const String16 androidNSUri("http://schemas.android.com/apk/res/android");
1092 sp<XMLNode> root = XMLNode::newNamespace(filename, androidPrefix, androidNSUri);
1093
1094 // Build the <manifest> tag
1095 sp<XMLNode> manifest = XMLNode::newElement(filename, String16(), String16("manifest"));
1096
Jeff Sharkey2cfc8482014-07-09 16:10:16 -07001097 // Add the 'package' attribute which is set to the package name.
1098 const char* packageName = assets->getPackage();
1099 const char* manifestPackageNameOverride = bundle->getManifestPackageNameOverride();
1100 if (manifestPackageNameOverride != NULL) {
1101 packageName = manifestPackageNameOverride;
1102 }
1103 manifest->addAttribute(String16(), String16("package"), String16(packageName));
1104
1105 // Add the 'versionCode' attribute which is set to the original version code.
1106 if (!addTagAttribute(manifest, RESOURCES_ANDROID_NAMESPACE, "versionCode",
1107 bundle->getVersionCode(), true, true)) {
1108 return UNKNOWN_ERROR;
1109 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001110
Adam Lesinski54de2982014-12-16 09:16:26 -08001111 // Add the 'revisionCode' attribute, which is set to the original revisionCode.
1112 if (bundle->getRevisionCode().size() > 0) {
1113 if (!addTagAttribute(manifest, RESOURCES_ANDROID_NAMESPACE, "revisionCode",
1114 bundle->getRevisionCode().string(), true, true)) {
1115 return UNKNOWN_ERROR;
1116 }
1117 }
1118
Adam Lesinskifab50872014-04-16 14:40:42 -07001119 // Add the 'split' attribute which describes the configurations included.
Adam Lesinski62408402014-08-07 21:26:53 -07001120 String8 splitName("config.");
1121 splitName.append(split->getPackageSafeName());
Adam Lesinskifab50872014-04-16 14:40:42 -07001122 manifest->addAttribute(String16(), String16("split"), String16(splitName));
1123
1124 // Build an empty <application> tag (required).
1125 sp<XMLNode> app = XMLNode::newElement(filename, String16(), String16("application"));
Jeff Sharkey78a13012014-07-15 20:18:34 -07001126
1127 // Add the 'hasCode' attribute which is never true for resource splits.
1128 if (!addTagAttribute(app, RESOURCES_ANDROID_NAMESPACE, "hasCode",
1129 "false", true, true)) {
1130 return UNKNOWN_ERROR;
1131 }
1132
Adam Lesinskifab50872014-04-16 14:40:42 -07001133 manifest->addChild(app);
1134 root->addChild(manifest);
1135
Adam Lesinskie572c012014-09-19 15:10:04 -07001136 int err = compileXmlFile(bundle, assets, String16(), root, outFile, table);
Jeff Sharkey2cfc8482014-07-09 16:10:16 -07001137 if (err < NO_ERROR) {
Adam Lesinskifab50872014-04-16 14:40:42 -07001138 return err;
1139 }
1140 outFile->setCompressionMethod(ZipEntry::kCompressDeflated);
1141 return NO_ERROR;
1142}
1143
1144status_t buildResources(Bundle* bundle, const sp<AaptAssets>& assets, sp<ApkBuilder>& builder)
Adam Lesinski282e1812014-01-23 18:17:42 -08001145{
1146 // First, look for a package file to parse. This is required to
1147 // be able to generate the resource information.
1148 sp<AaptGroup> androidManifestFile =
1149 assets->getFiles().valueFor(String8("AndroidManifest.xml"));
1150 if (androidManifestFile == NULL) {
1151 fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n");
1152 return UNKNOWN_ERROR;
1153 }
1154
1155 status_t err = parsePackage(bundle, assets, androidManifestFile);
1156 if (err != NO_ERROR) {
1157 return err;
1158 }
1159
Andreas Gampe2412f842014-09-30 20:55:57 -07001160 if (kIsDebug) {
1161 printf("Creating resources for package %s\n", assets->getPackage().string());
1162 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001163
Adam Lesinski78713992015-12-07 14:02:15 -08001164 // Set the private symbols package if it was declared.
1165 // This can also be declared in XML as <private-symbols name="package" />
1166 if (bundle->getPrivateSymbolsPackage().size() != 0) {
1167 assets->setSymbolsPrivatePackage(bundle->getPrivateSymbolsPackage());
1168 }
1169
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001170 ResourceTable::PackageType packageType = ResourceTable::App;
1171 if (bundle->getBuildSharedLibrary()) {
1172 packageType = ResourceTable::SharedLibrary;
1173 } else if (bundle->getExtending()) {
1174 packageType = ResourceTable::System;
1175 } else if (!bundle->getFeatureOfPackage().isEmpty()) {
1176 packageType = ResourceTable::AppFeature;
1177 }
1178
1179 ResourceTable table(bundle, String16(assets->getPackage()), packageType);
Adam Lesinski282e1812014-01-23 18:17:42 -08001180 err = table.addIncludedResources(bundle, assets);
1181 if (err != NO_ERROR) {
1182 return err;
1183 }
1184
Andreas Gampe2412f842014-09-30 20:55:57 -07001185 if (kIsDebug) {
1186 printf("Found %d included resource packages\n", (int)table.size());
1187 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001188
1189 // Standard flags for compiled XML and optional UTF-8 encoding
1190 int xmlFlags = XML_COMPILE_STANDARD_RESOURCE;
1191
1192 /* Only enable UTF-8 if the caller of aapt didn't specifically
1193 * request UTF-16 encoding and the parameters of this package
1194 * allow UTF-8 to be used.
1195 */
1196 if (!bundle->getUTF16StringsOption()) {
1197 xmlFlags |= XML_COMPILE_UTF8;
1198 }
1199
1200 // --------------------------------------------------------------
1201 // First, gather all resource information.
1202 // --------------------------------------------------------------
1203
1204 // resType -> leafName -> group
1205 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
1206 new KeyedVector<String8, sp<ResourceTypeSet> >;
1207 collect_files(assets, resources);
1208
1209 sp<ResourceTypeSet> drawables;
1210 sp<ResourceTypeSet> layouts;
1211 sp<ResourceTypeSet> anims;
1212 sp<ResourceTypeSet> animators;
1213 sp<ResourceTypeSet> interpolators;
1214 sp<ResourceTypeSet> transitions;
Adam Lesinski282e1812014-01-23 18:17:42 -08001215 sp<ResourceTypeSet> xmls;
1216 sp<ResourceTypeSet> raws;
1217 sp<ResourceTypeSet> colors;
1218 sp<ResourceTypeSet> menus;
1219 sp<ResourceTypeSet> mipmaps;
1220
1221 ASSIGN_IT(drawable);
1222 ASSIGN_IT(layout);
1223 ASSIGN_IT(anim);
1224 ASSIGN_IT(animator);
1225 ASSIGN_IT(interpolator);
1226 ASSIGN_IT(transition);
Adam Lesinski282e1812014-01-23 18:17:42 -08001227 ASSIGN_IT(xml);
1228 ASSIGN_IT(raw);
1229 ASSIGN_IT(color);
1230 ASSIGN_IT(menu);
1231 ASSIGN_IT(mipmap);
1232
1233 assets->setResources(resources);
1234 // now go through any resource overlays and collect their files
1235 sp<AaptAssets> current = assets->getOverlay();
1236 while(current.get()) {
1237 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
1238 new KeyedVector<String8, sp<ResourceTypeSet> >;
1239 current->setResources(resources);
1240 collect_files(current, resources);
1241 current = current->getOverlay();
1242 }
1243 // apply the overlay files to the base set
1244 if (!applyFileOverlay(bundle, assets, &drawables, "drawable") ||
1245 !applyFileOverlay(bundle, assets, &layouts, "layout") ||
1246 !applyFileOverlay(bundle, assets, &anims, "anim") ||
1247 !applyFileOverlay(bundle, assets, &animators, "animator") ||
1248 !applyFileOverlay(bundle, assets, &interpolators, "interpolator") ||
1249 !applyFileOverlay(bundle, assets, &transitions, "transition") ||
Adam Lesinski282e1812014-01-23 18:17:42 -08001250 !applyFileOverlay(bundle, assets, &xmls, "xml") ||
1251 !applyFileOverlay(bundle, assets, &raws, "raw") ||
1252 !applyFileOverlay(bundle, assets, &colors, "color") ||
1253 !applyFileOverlay(bundle, assets, &menus, "menu") ||
1254 !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
1288 if (layouts != NULL) {
1289 err = makeFileResources(bundle, assets, &table, layouts, "layout");
1290 if (err != NO_ERROR) {
1291 hasErrors = true;
1292 }
1293 }
1294
1295 if (anims != NULL) {
1296 err = makeFileResources(bundle, assets, &table, anims, "anim");
1297 if (err != NO_ERROR) {
1298 hasErrors = true;
1299 }
1300 }
1301
1302 if (animators != NULL) {
1303 err = makeFileResources(bundle, assets, &table, animators, "animator");
1304 if (err != NO_ERROR) {
1305 hasErrors = true;
1306 }
1307 }
1308
1309 if (transitions != NULL) {
1310 err = makeFileResources(bundle, assets, &table, transitions, "transition");
1311 if (err != NO_ERROR) {
1312 hasErrors = true;
1313 }
1314 }
1315
Adam Lesinski282e1812014-01-23 18:17:42 -08001316 if (interpolators != NULL) {
1317 err = makeFileResources(bundle, assets, &table, interpolators, "interpolator");
1318 if (err != NO_ERROR) {
1319 hasErrors = true;
1320 }
1321 }
1322
1323 if (xmls != NULL) {
1324 err = makeFileResources(bundle, assets, &table, xmls, "xml");
1325 if (err != NO_ERROR) {
1326 hasErrors = true;
1327 }
1328 }
1329
1330 if (raws != NULL) {
1331 err = makeFileResources(bundle, assets, &table, raws, "raw");
1332 if (err != NO_ERROR) {
1333 hasErrors = true;
1334 }
1335 }
1336
1337 // compile resources
1338 current = assets;
1339 while(current.get()) {
1340 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
1341 current->getResources();
1342
1343 ssize_t index = resources->indexOfKey(String8("values"));
1344 if (index >= 0) {
1345 ResourceDirIterator it(resources->valueAt(index), String8("values"));
1346 ssize_t res;
1347 while ((res=it.next()) == NO_ERROR) {
1348 sp<AaptFile> file = it.getFile();
1349 res = compileResourceFile(bundle, assets, file, it.getParams(),
1350 (current!=assets), &table);
1351 if (res != NO_ERROR) {
1352 hasErrors = true;
1353 }
1354 }
1355 }
1356 current = current->getOverlay();
1357 }
1358
1359 if (colors != NULL) {
1360 err = makeFileResources(bundle, assets, &table, colors, "color");
1361 if (err != NO_ERROR) {
1362 hasErrors = true;
1363 }
1364 }
1365
1366 if (menus != NULL) {
1367 err = makeFileResources(bundle, assets, &table, menus, "menu");
1368 if (err != NO_ERROR) {
1369 hasErrors = true;
1370 }
1371 }
1372
1373 // --------------------------------------------------------------------
1374 // Assignment of resource IDs and initial generation of resource table.
1375 // --------------------------------------------------------------------
1376
1377 if (table.hasResources()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001378 err = table.assignResourceIds();
1379 if (err < NO_ERROR) {
1380 return err;
1381 }
1382 }
1383
1384 // --------------------------------------------------------------
1385 // Finally, we can now we can compile XML files, which may reference
1386 // resources.
1387 // --------------------------------------------------------------
1388
1389 if (layouts != NULL) {
1390 ResourceDirIterator it(layouts, String8("layout"));
1391 while ((err=it.next()) == NO_ERROR) {
1392 String8 src = it.getFile()->getPrintableSource();
Adam Lesinskie572c012014-09-19 15:10:04 -07001393 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1394 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001395 if (err == NO_ERROR) {
1396 ResXMLTree block;
1397 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
1398 checkForIds(src, block);
1399 } else {
1400 hasErrors = true;
1401 }
1402 }
1403
1404 if (err < NO_ERROR) {
1405 hasErrors = true;
1406 }
1407 err = NO_ERROR;
1408 }
1409
1410 if (anims != NULL) {
1411 ResourceDirIterator it(anims, String8("anim"));
1412 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001413 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1414 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001415 if (err != NO_ERROR) {
1416 hasErrors = true;
1417 }
1418 }
1419
1420 if (err < NO_ERROR) {
1421 hasErrors = true;
1422 }
1423 err = NO_ERROR;
1424 }
1425
1426 if (animators != NULL) {
1427 ResourceDirIterator it(animators, String8("animator"));
1428 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001429 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1430 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001431 if (err != NO_ERROR) {
1432 hasErrors = true;
1433 }
1434 }
1435
1436 if (err < NO_ERROR) {
1437 hasErrors = true;
1438 }
1439 err = NO_ERROR;
1440 }
1441
1442 if (interpolators != NULL) {
1443 ResourceDirIterator it(interpolators, String8("interpolator"));
1444 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001445 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1446 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001447 if (err != NO_ERROR) {
1448 hasErrors = true;
1449 }
1450 }
1451
1452 if (err < NO_ERROR) {
1453 hasErrors = true;
1454 }
1455 err = NO_ERROR;
1456 }
1457
1458 if (transitions != NULL) {
1459 ResourceDirIterator it(transitions, String8("transition"));
1460 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001461 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1462 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001463 if (err != NO_ERROR) {
1464 hasErrors = true;
1465 }
1466 }
1467
1468 if (err < NO_ERROR) {
1469 hasErrors = true;
1470 }
1471 err = NO_ERROR;
1472 }
1473
Adam Lesinski282e1812014-01-23 18:17:42 -08001474 if (xmls != NULL) {
1475 ResourceDirIterator it(xmls, String8("xml"));
1476 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001477 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1478 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001479 if (err != NO_ERROR) {
1480 hasErrors = true;
1481 }
1482 }
1483
1484 if (err < NO_ERROR) {
1485 hasErrors = true;
1486 }
1487 err = NO_ERROR;
1488 }
1489
1490 if (drawables != NULL) {
Adam Lesinskifab50872014-04-16 14:40:42 -07001491 ResourceDirIterator it(drawables, String8("drawable"));
1492 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001493 err = postProcessImage(bundle, assets, &table, it.getFile());
Adam Lesinskifab50872014-04-16 14:40:42 -07001494 if (err != NO_ERROR) {
1495 hasErrors = true;
1496 }
1497 }
1498
1499 if (err < NO_ERROR) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001500 hasErrors = true;
1501 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001502 err = NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001503 }
1504
1505 if (colors != NULL) {
1506 ResourceDirIterator it(colors, String8("color"));
1507 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001508 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1509 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001510 if (err != NO_ERROR) {
1511 hasErrors = true;
1512 }
1513 }
1514
1515 if (err < NO_ERROR) {
1516 hasErrors = true;
1517 }
1518 err = NO_ERROR;
1519 }
1520
1521 if (menus != NULL) {
1522 ResourceDirIterator it(menus, String8("menu"));
1523 while ((err=it.next()) == NO_ERROR) {
1524 String8 src = it.getFile()->getPrintableSource();
Adam Lesinskie572c012014-09-19 15:10:04 -07001525 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1526 it.getFile(), &table, xmlFlags);
Adam Lesinskifab50872014-04-16 14:40:42 -07001527 if (err == NO_ERROR) {
1528 ResXMLTree block;
1529 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
1530 checkForIds(src, block);
1531 } else {
Adam Lesinski282e1812014-01-23 18:17:42 -08001532 hasErrors = true;
1533 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001534 }
1535
1536 if (err < NO_ERROR) {
1537 hasErrors = true;
1538 }
1539 err = NO_ERROR;
1540 }
1541
Adam Lesinskie572c012014-09-19 15:10:04 -07001542 // Now compile any generated resources.
1543 std::queue<CompileResourceWorkItem>& workQueue = table.getWorkQueue();
1544 while (!workQueue.empty()) {
1545 CompileResourceWorkItem& workItem = workQueue.front();
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07001546 int xmlCompilationFlags = xmlFlags | XML_COMPILE_PARSE_VALUES
1547 | XML_COMPILE_ASSIGN_ATTRIBUTE_IDS;
1548 if (!workItem.needsCompiling) {
1549 xmlCompilationFlags &= ~XML_COMPILE_ASSIGN_ATTRIBUTE_IDS;
1550 xmlCompilationFlags &= ~XML_COMPILE_PARSE_VALUES;
1551 }
1552 err = compileXmlFile(bundle, assets, workItem.resourceName, workItem.xmlRoot,
1553 workItem.file, &table, xmlCompilationFlags);
1554
Adam Lesinskie572c012014-09-19 15:10:04 -07001555 if (err == NO_ERROR) {
1556 assets->addResource(workItem.resPath.getPathLeaf(),
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07001557 workItem.resPath,
1558 workItem.file,
1559 workItem.file->getResourceType());
Adam Lesinskie572c012014-09-19 15:10:04 -07001560 } else {
1561 hasErrors = true;
1562 }
1563 workQueue.pop();
1564 }
1565
Adam Lesinski282e1812014-01-23 18:17:42 -08001566 if (table.validateLocalizations()) {
1567 hasErrors = true;
1568 }
1569
1570 if (hasErrors) {
1571 return UNKNOWN_ERROR;
1572 }
1573
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001574 // If we're not overriding the platform build versions,
1575 // extract them from the platform APK.
1576 if (packageType != ResourceTable::System &&
1577 (bundle->getPlatformBuildVersionCode() == "" ||
1578 bundle->getPlatformBuildVersionName() == "")) {
1579 err = extractPlatformBuildVersion(assets->getAssetManager(), bundle);
1580 if (err != NO_ERROR) {
1581 return UNKNOWN_ERROR;
1582 }
1583 }
1584
Adam Lesinski282e1812014-01-23 18:17:42 -08001585 const sp<AaptFile> manifestFile(androidManifestFile->getFiles().valueAt(0));
1586 String8 manifestPath(manifestFile->getPrintableSource());
1587
1588 // Generate final compiled manifest file.
1589 manifestFile->clearData();
1590 sp<XMLNode> manifestTree = XMLNode::parse(manifestFile);
1591 if (manifestTree == NULL) {
1592 return UNKNOWN_ERROR;
1593 }
1594 err = massageManifest(bundle, manifestTree);
1595 if (err < NO_ERROR) {
1596 return err;
1597 }
Adam Lesinskie572c012014-09-19 15:10:04 -07001598 err = compileXmlFile(bundle, assets, String16(), manifestTree, manifestFile, &table);
Adam Lesinski282e1812014-01-23 18:17:42 -08001599 if (err < NO_ERROR) {
1600 return err;
1601 }
1602
Adam Lesinski82a2dd82014-09-17 18:34:15 -07001603 if (table.modifyForCompat(bundle) != NO_ERROR) {
1604 return UNKNOWN_ERROR;
1605 }
1606
Adam Lesinski282e1812014-01-23 18:17:42 -08001607 //block.restart();
1608 //printXMLBlock(&block);
1609
1610 // --------------------------------------------------------------
1611 // Generate the final resource table.
1612 // Re-flatten because we may have added new resource IDs
1613 // --------------------------------------------------------------
1614
Adam Lesinskide7de472014-11-03 12:03:08 -08001615
Adam Lesinski282e1812014-01-23 18:17:42 -08001616 ResTable finalResTable;
1617 sp<AaptFile> resFile;
1618
1619 if (table.hasResources()) {
1620 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
Adrian Roos58922482015-06-01 17:59:41 -07001621 err = table.addSymbols(symbols, bundle->getSkipSymbolsWithoutDefaultLocalization());
Adam Lesinski282e1812014-01-23 18:17:42 -08001622 if (err < NO_ERROR) {
1623 return err;
1624 }
1625
Adam Lesinskide7de472014-11-03 12:03:08 -08001626 KeyedVector<Symbol, Vector<SymbolDefinition> > densityVaryingResources;
1627 if (builder->getSplits().size() > 1) {
1628 // Only look for density varying resources if we're generating
1629 // splits.
1630 table.getDensityVaryingResources(densityVaryingResources);
1631 }
1632
Adam Lesinskifab50872014-04-16 14:40:42 -07001633 Vector<sp<ApkSplit> >& splits = builder->getSplits();
1634 const size_t numSplits = splits.size();
1635 for (size_t i = 0; i < numSplits; i++) {
1636 sp<ApkSplit>& split = splits.editItemAt(i);
1637 sp<AaptFile> flattenedTable = new AaptFile(String8("resources.arsc"),
1638 AaptGroupEntry(), String8());
Adam Lesinski27f69f42014-08-21 13:19:12 -07001639 err = table.flatten(bundle, split->getResourceFilter(),
1640 flattenedTable, split->isBase());
Adam Lesinskifab50872014-04-16 14:40:42 -07001641 if (err != NO_ERROR) {
1642 fprintf(stderr, "Failed to generate resource table for split '%s'\n",
1643 split->getPrintableName().string());
1644 return err;
1645 }
1646 split->addEntry(String8("resources.arsc"), flattenedTable);
Adam Lesinski282e1812014-01-23 18:17:42 -08001647
Adam Lesinskifab50872014-04-16 14:40:42 -07001648 if (split->isBase()) {
1649 resFile = flattenedTable;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07001650 err = finalResTable.add(flattenedTable->getData(), flattenedTable->getSize());
1651 if (err != NO_ERROR) {
1652 fprintf(stderr, "Generated resource table is corrupt.\n");
1653 return err;
1654 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001655 } else {
Adam Lesinskide7de472014-11-03 12:03:08 -08001656 ResTable resTable;
1657 err = resTable.add(flattenedTable->getData(), flattenedTable->getSize());
1658 if (err != NO_ERROR) {
1659 fprintf(stderr, "Generated resource table for split '%s' is corrupt.\n",
1660 split->getPrintableName().string());
1661 return err;
1662 }
1663
1664 bool hasError = false;
1665 const std::set<ConfigDescription>& splitConfigs = split->getConfigs();
1666 for (std::set<ConfigDescription>::const_iterator iter = splitConfigs.begin();
1667 iter != splitConfigs.end();
1668 ++iter) {
1669 const ConfigDescription& config = *iter;
1670 if (AaptConfig::isDensityOnly(config)) {
1671 // Each density only split must contain all
1672 // density only resources.
1673 Res_value val;
1674 resTable.setParameters(&config);
1675 const size_t densityVaryingResourceCount = densityVaryingResources.size();
1676 for (size_t k = 0; k < densityVaryingResourceCount; k++) {
1677 const Symbol& symbol = densityVaryingResources.keyAt(k);
1678 ssize_t block = resTable.getResource(symbol.id, &val, true);
1679 if (block < 0) {
1680 // Maybe it's in the base?
1681 finalResTable.setParameters(&config);
1682 block = finalResTable.getResource(symbol.id, &val, true);
1683 }
1684
1685 if (block < 0) {
1686 hasError = true;
1687 SourcePos().error("%s has no definition for density split '%s'",
1688 symbol.toString().string(), config.toString().string());
1689
1690 if (bundle->getVerbose()) {
1691 const Vector<SymbolDefinition>& defs = densityVaryingResources[k];
1692 const size_t defCount = std::min(size_t(5), defs.size());
1693 for (size_t d = 0; d < defCount; d++) {
1694 const SymbolDefinition& def = defs[d];
1695 def.source.error("%s has definition for %s",
1696 symbol.toString().string(), def.config.toString().string());
1697 }
1698
1699 if (defCount < defs.size()) {
1700 SourcePos().error("and %d more ...", (int) (defs.size() - defCount));
1701 }
1702 }
1703 }
1704 }
1705 }
1706 }
1707
1708 if (hasError) {
1709 return UNKNOWN_ERROR;
1710 }
1711
1712 // Generate the AndroidManifest for this split.
Adam Lesinskifab50872014-04-16 14:40:42 -07001713 sp<AaptFile> generatedManifest = new AaptFile(String8("AndroidManifest.xml"),
1714 AaptGroupEntry(), String8());
Jeff Sharkey2cfc8482014-07-09 16:10:16 -07001715 err = generateAndroidManifestForSplit(bundle, assets, split,
1716 generatedManifest, &table);
Adam Lesinskifab50872014-04-16 14:40:42 -07001717 if (err != NO_ERROR) {
1718 fprintf(stderr, "Failed to generate AndroidManifest.xml for split '%s'\n",
1719 split->getPrintableName().string());
1720 return err;
1721 }
1722 split->addEntry(String8("AndroidManifest.xml"), generatedManifest);
1723 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001724 }
1725
1726 if (bundle->getPublicOutputFile()) {
1727 FILE* fp = fopen(bundle->getPublicOutputFile(), "w+");
1728 if (fp == NULL) {
1729 fprintf(stderr, "ERROR: Unable to open public definitions output file %s: %s\n",
1730 (const char*)bundle->getPublicOutputFile(), strerror(errno));
1731 return UNKNOWN_ERROR;
1732 }
1733 if (bundle->getVerbose()) {
1734 printf(" Writing public definitions to %s.\n", bundle->getPublicOutputFile());
1735 }
1736 table.writePublicDefinitions(String16(assets->getPackage()), fp);
1737 fclose(fp);
1738 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001739
1740 if (finalResTable.getTableCount() == 0 || resFile == NULL) {
1741 fprintf(stderr, "No resource table was generated.\n");
1742 return UNKNOWN_ERROR;
1743 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001744 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001745
Adam Lesinski282e1812014-01-23 18:17:42 -08001746 // Perform a basic validation of the manifest file. This time we
1747 // parse it with the comments intact, so that we can use them to
1748 // generate java docs... so we are not going to write this one
1749 // back out to the final manifest data.
1750 sp<AaptFile> outManifestFile = new AaptFile(manifestFile->getSourceFile(),
1751 manifestFile->getGroupEntry(),
1752 manifestFile->getResourceType());
Adam Lesinskie572c012014-09-19 15:10:04 -07001753 err = compileXmlFile(bundle, assets, String16(), manifestFile,
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07001754 outManifestFile, &table, XML_COMPILE_STANDARD_RESOURCE & ~XML_COMPILE_STRIP_COMMENTS);
Adam Lesinski282e1812014-01-23 18:17:42 -08001755 if (err < NO_ERROR) {
1756 return err;
1757 }
1758 ResXMLTree block;
1759 block.setTo(outManifestFile->getData(), outManifestFile->getSize(), true);
1760 String16 manifest16("manifest");
1761 String16 permission16("permission");
1762 String16 permission_group16("permission-group");
1763 String16 uses_permission16("uses-permission");
1764 String16 instrumentation16("instrumentation");
1765 String16 application16("application");
1766 String16 provider16("provider");
1767 String16 service16("service");
1768 String16 receiver16("receiver");
1769 String16 activity16("activity");
1770 String16 action16("action");
1771 String16 category16("category");
1772 String16 data16("scheme");
Adam Lesinskid3edfde2014-08-08 17:32:44 -07001773 String16 feature_group16("feature-group");
1774 String16 uses_feature16("uses-feature");
Adam Lesinski282e1812014-01-23 18:17:42 -08001775 const char* packageIdentChars = "abcdefghijklmnopqrstuvwxyz"
1776 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789";
1777 const char* packageIdentCharsWithTheStupid = "abcdefghijklmnopqrstuvwxyz"
1778 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
1779 const char* classIdentChars = "abcdefghijklmnopqrstuvwxyz"
1780 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789$";
1781 const char* processIdentChars = "abcdefghijklmnopqrstuvwxyz"
1782 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:";
1783 const char* authoritiesIdentChars = "abcdefghijklmnopqrstuvwxyz"
1784 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-:;";
1785 const char* typeIdentChars = "abcdefghijklmnopqrstuvwxyz"
1786 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:-/*+";
1787 const char* schemeIdentChars = "abcdefghijklmnopqrstuvwxyz"
1788 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
1789 ResXMLTree::event_code_t code;
1790 sp<AaptSymbols> permissionSymbols;
1791 sp<AaptSymbols> permissionGroupSymbols;
1792 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1793 && code > ResXMLTree::BAD_DOCUMENT) {
1794 if (code == ResXMLTree::START_TAG) {
1795 size_t len;
1796 if (block.getElementNamespace(&len) != NULL) {
1797 continue;
1798 }
1799 if (strcmp16(block.getElementName(&len), manifest16.string()) == 0) {
1800 if (validateAttr(manifestPath, finalResTable, block, NULL, "package",
1801 packageIdentChars, true) != ATTR_OKAY) {
1802 hasErrors = true;
1803 }
1804 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1805 "sharedUserId", packageIdentChars, false) != ATTR_OKAY) {
1806 hasErrors = true;
1807 }
1808 } else if (strcmp16(block.getElementName(&len), permission16.string()) == 0
1809 || strcmp16(block.getElementName(&len), permission_group16.string()) == 0) {
1810 const bool isGroup = strcmp16(block.getElementName(&len),
1811 permission_group16.string()) == 0;
1812 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1813 "name", isGroup ? packageIdentCharsWithTheStupid
1814 : packageIdentChars, true) != ATTR_OKAY) {
1815 hasErrors = true;
1816 }
1817 SourcePos srcPos(manifestPath, block.getLineNumber());
1818 sp<AaptSymbols> syms;
1819 if (!isGroup) {
1820 syms = permissionSymbols;
1821 if (syms == NULL) {
1822 sp<AaptSymbols> symbols =
1823 assets->getSymbolsFor(String8("Manifest"));
1824 syms = permissionSymbols = symbols->addNestedSymbol(
1825 String8("permission"), srcPos);
1826 }
1827 } else {
1828 syms = permissionGroupSymbols;
1829 if (syms == NULL) {
1830 sp<AaptSymbols> symbols =
1831 assets->getSymbolsFor(String8("Manifest"));
1832 syms = permissionGroupSymbols = symbols->addNestedSymbol(
1833 String8("permission_group"), srcPos);
1834 }
1835 }
1836 size_t len;
1837 ssize_t index = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "name");
Dan Albertf348c152014-09-08 18:28:00 -07001838 const char16_t* id = block.getAttributeStringValue(index, &len);
Adam Lesinski282e1812014-01-23 18:17:42 -08001839 if (id == NULL) {
1840 fprintf(stderr, "%s:%d: missing name attribute in element <%s>.\n",
1841 manifestPath.string(), block.getLineNumber(),
1842 String8(block.getElementName(&len)).string());
1843 hasErrors = true;
1844 break;
1845 }
1846 String8 idStr(id);
1847 char* p = idStr.lockBuffer(idStr.size());
1848 char* e = p + idStr.size();
1849 bool begins_with_digit = true; // init to true so an empty string fails
1850 while (e > p) {
1851 e--;
1852 if (*e >= '0' && *e <= '9') {
1853 begins_with_digit = true;
1854 continue;
1855 }
1856 if ((*e >= 'a' && *e <= 'z') ||
1857 (*e >= 'A' && *e <= 'Z') ||
1858 (*e == '_')) {
1859 begins_with_digit = false;
1860 continue;
1861 }
1862 if (isGroup && (*e == '-')) {
1863 *e = '_';
1864 begins_with_digit = false;
1865 continue;
1866 }
1867 e++;
1868 break;
1869 }
1870 idStr.unlockBuffer();
1871 // verify that we stopped because we hit a period or
1872 // the beginning of the string, and that the
1873 // identifier didn't begin with a digit.
1874 if (begins_with_digit || (e != p && *(e-1) != '.')) {
1875 fprintf(stderr,
1876 "%s:%d: Permission name <%s> is not a valid Java symbol\n",
1877 manifestPath.string(), block.getLineNumber(), idStr.string());
1878 hasErrors = true;
1879 }
1880 syms->addStringSymbol(String8(e), idStr, srcPos);
Dan Albertf348c152014-09-08 18:28:00 -07001881 const char16_t* cmt = block.getComment(&len);
Adam Lesinski282e1812014-01-23 18:17:42 -08001882 if (cmt != NULL && *cmt != 0) {
1883 //printf("Comment of %s: %s\n", String8(e).string(),
1884 // String8(cmt).string());
1885 syms->appendComment(String8(e), String16(cmt), srcPos);
Adam Lesinski282e1812014-01-23 18:17:42 -08001886 }
1887 syms->makeSymbolPublic(String8(e), srcPos);
1888 } else if (strcmp16(block.getElementName(&len), uses_permission16.string()) == 0) {
1889 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1890 "name", packageIdentChars, true) != ATTR_OKAY) {
1891 hasErrors = true;
1892 }
1893 } else if (strcmp16(block.getElementName(&len), instrumentation16.string()) == 0) {
1894 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1895 "name", classIdentChars, true) != ATTR_OKAY) {
1896 hasErrors = true;
1897 }
1898 if (validateAttr(manifestPath, finalResTable, block,
1899 RESOURCES_ANDROID_NAMESPACE, "targetPackage",
1900 packageIdentChars, true) != ATTR_OKAY) {
1901 hasErrors = true;
1902 }
1903 } else if (strcmp16(block.getElementName(&len), application16.string()) == 0) {
1904 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1905 "name", classIdentChars, false) != ATTR_OKAY) {
1906 hasErrors = true;
1907 }
1908 if (validateAttr(manifestPath, finalResTable, block,
1909 RESOURCES_ANDROID_NAMESPACE, "permission",
1910 packageIdentChars, false) != ATTR_OKAY) {
1911 hasErrors = true;
1912 }
1913 if (validateAttr(manifestPath, finalResTable, block,
1914 RESOURCES_ANDROID_NAMESPACE, "process",
1915 processIdentChars, false) != ATTR_OKAY) {
1916 hasErrors = true;
1917 }
1918 if (validateAttr(manifestPath, finalResTable, block,
1919 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
1920 processIdentChars, false) != ATTR_OKAY) {
1921 hasErrors = true;
1922 }
1923 } else if (strcmp16(block.getElementName(&len), provider16.string()) == 0) {
1924 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1925 "name", classIdentChars, true) != ATTR_OKAY) {
1926 hasErrors = true;
1927 }
1928 if (validateAttr(manifestPath, finalResTable, block,
1929 RESOURCES_ANDROID_NAMESPACE, "authorities",
1930 authoritiesIdentChars, true) != ATTR_OKAY) {
1931 hasErrors = true;
1932 }
1933 if (validateAttr(manifestPath, finalResTable, block,
1934 RESOURCES_ANDROID_NAMESPACE, "permission",
1935 packageIdentChars, false) != ATTR_OKAY) {
1936 hasErrors = true;
1937 }
1938 if (validateAttr(manifestPath, finalResTable, block,
1939 RESOURCES_ANDROID_NAMESPACE, "process",
1940 processIdentChars, false) != ATTR_OKAY) {
1941 hasErrors = true;
1942 }
1943 } else if (strcmp16(block.getElementName(&len), service16.string()) == 0
1944 || strcmp16(block.getElementName(&len), receiver16.string()) == 0
1945 || strcmp16(block.getElementName(&len), activity16.string()) == 0) {
1946 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1947 "name", classIdentChars, true) != ATTR_OKAY) {
1948 hasErrors = true;
1949 }
1950 if (validateAttr(manifestPath, finalResTable, block,
1951 RESOURCES_ANDROID_NAMESPACE, "permission",
1952 packageIdentChars, false) != ATTR_OKAY) {
1953 hasErrors = true;
1954 }
1955 if (validateAttr(manifestPath, finalResTable, block,
1956 RESOURCES_ANDROID_NAMESPACE, "process",
1957 processIdentChars, false) != ATTR_OKAY) {
1958 hasErrors = true;
1959 }
1960 if (validateAttr(manifestPath, finalResTable, block,
1961 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
1962 processIdentChars, false) != ATTR_OKAY) {
1963 hasErrors = true;
1964 }
1965 } else if (strcmp16(block.getElementName(&len), action16.string()) == 0
1966 || strcmp16(block.getElementName(&len), category16.string()) == 0) {
1967 if (validateAttr(manifestPath, finalResTable, block,
1968 RESOURCES_ANDROID_NAMESPACE, "name",
1969 packageIdentChars, true) != ATTR_OKAY) {
1970 hasErrors = true;
1971 }
1972 } else if (strcmp16(block.getElementName(&len), data16.string()) == 0) {
1973 if (validateAttr(manifestPath, finalResTable, block,
1974 RESOURCES_ANDROID_NAMESPACE, "mimeType",
1975 typeIdentChars, true) != ATTR_OKAY) {
1976 hasErrors = true;
1977 }
1978 if (validateAttr(manifestPath, finalResTable, block,
1979 RESOURCES_ANDROID_NAMESPACE, "scheme",
1980 schemeIdentChars, true) != ATTR_OKAY) {
1981 hasErrors = true;
1982 }
Adam Lesinskid3edfde2014-08-08 17:32:44 -07001983 } else if (strcmp16(block.getElementName(&len), feature_group16.string()) == 0) {
1984 int depth = 1;
1985 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1986 && code > ResXMLTree::BAD_DOCUMENT) {
1987 if (code == ResXMLTree::START_TAG) {
1988 depth++;
1989 if (strcmp16(block.getElementName(&len), uses_feature16.string()) == 0) {
1990 ssize_t idx = block.indexOfAttribute(
1991 RESOURCES_ANDROID_NAMESPACE, "required");
1992 if (idx < 0) {
1993 continue;
1994 }
1995
1996 int32_t data = block.getAttributeData(idx);
1997 if (data == 0) {
1998 fprintf(stderr, "%s:%d: Tag <uses-feature> can not have "
1999 "android:required=\"false\" when inside a "
2000 "<feature-group> tag.\n",
2001 manifestPath.string(), block.getLineNumber());
2002 hasErrors = true;
2003 }
2004 }
2005 } else if (code == ResXMLTree::END_TAG) {
2006 depth--;
2007 if (depth == 0) {
2008 break;
2009 }
2010 }
2011 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002012 }
2013 }
2014 }
2015
Adam Lesinskid3edfde2014-08-08 17:32:44 -07002016 if (hasErrors) {
2017 return UNKNOWN_ERROR;
2018 }
2019
Adam Lesinski282e1812014-01-23 18:17:42 -08002020 if (resFile != NULL) {
2021 // These resources are now considered to be a part of the included
2022 // resources, for others to reference.
2023 err = assets->addIncludedResources(resFile);
2024 if (err < NO_ERROR) {
2025 fprintf(stderr, "ERROR: Unable to parse generated resources, aborting.\n");
2026 return err;
2027 }
2028 }
2029
2030 return err;
2031}
2032
2033static const char* getIndentSpace(int indent)
2034{
2035static const char whitespace[] =
2036" ";
2037
2038 return whitespace + sizeof(whitespace) - 1 - indent*4;
2039}
2040
2041static String8 flattenSymbol(const String8& symbol) {
2042 String8 result(symbol);
2043 ssize_t first;
2044 if ((first = symbol.find(":", 0)) >= 0
2045 || (first = symbol.find(".", 0)) >= 0) {
2046 size_t size = symbol.size();
2047 char* buf = result.lockBuffer(size);
2048 for (size_t i = first; i < size; i++) {
2049 if (buf[i] == ':' || buf[i] == '.') {
2050 buf[i] = '_';
2051 }
2052 }
2053 result.unlockBuffer(size);
2054 }
2055 return result;
2056}
2057
2058static String8 getSymbolPackage(const String8& symbol, const sp<AaptAssets>& assets, bool pub) {
2059 ssize_t colon = symbol.find(":", 0);
2060 if (colon >= 0) {
2061 return String8(symbol.string(), colon);
2062 }
2063 return pub ? assets->getPackage() : assets->getSymbolsPrivatePackage();
2064}
2065
2066static String8 getSymbolName(const String8& symbol) {
2067 ssize_t colon = symbol.find(":", 0);
2068 if (colon >= 0) {
2069 return String8(symbol.string() + colon + 1);
2070 }
2071 return symbol;
2072}
2073
2074static String16 getAttributeComment(const sp<AaptAssets>& assets,
2075 const String8& name,
2076 String16* outTypeComment = NULL)
2077{
2078 sp<AaptSymbols> asym = assets->getSymbolsFor(String8("R"));
2079 if (asym != NULL) {
2080 //printf("Got R symbols!\n");
2081 asym = asym->getNestedSymbols().valueFor(String8("attr"));
2082 if (asym != NULL) {
2083 //printf("Got attrs symbols! comment %s=%s\n",
2084 // name.string(), String8(asym->getComment(name)).string());
2085 if (outTypeComment != NULL) {
2086 *outTypeComment = asym->getTypeComment(name);
2087 }
2088 return asym->getComment(name);
2089 }
2090 }
2091 return String16();
2092}
2093
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002094static status_t writeResourceLoadedCallbackForLayoutClasses(
2095 FILE* fp, const sp<AaptAssets>& assets,
Andreas Gampe87332a72014-10-01 22:03:58 -07002096 const sp<AaptSymbols>& symbols, int indent, bool /* includePrivate */)
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002097{
2098 String16 attr16("attr");
2099 String16 package16(assets->getPackage());
2100
2101 const char* indentStr = getIndentSpace(indent);
2102 bool hasErrors = false;
2103
2104 size_t i;
2105 size_t N = symbols->getNestedSymbols().size();
2106 for (i=0; i<N; i++) {
2107 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2108 String8 realClassName(symbols->getNestedSymbols().keyAt(i));
2109 String8 nclassName(flattenSymbol(realClassName));
2110
2111 fprintf(fp,
2112 "%sfor(int i = 0; i < styleable.%s.length; ++i) {\n"
2113 "%sstyleable.%s[i] = (styleable.%s[i] & 0x00ffffff) | (packageId << 24);\n"
2114 "%s}\n",
2115 indentStr, nclassName.string(),
2116 getIndentSpace(indent+1), nclassName.string(), nclassName.string(),
2117 indentStr);
Adam Lesinski1e4663852014-08-15 14:47:28 -07002118 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002119
Dan Alberted811ee2016-01-15 12:16:06 -08002120 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002121}
2122
2123static status_t writeResourceLoadedCallback(
2124 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2125 const sp<AaptSymbols>& symbols, const String8& className, int indent)
2126{
2127 size_t i;
2128 status_t err = NO_ERROR;
2129
2130 size_t N = symbols->getSymbols().size();
2131 for (i=0; i<N; i++) {
2132 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
Adam Lesinskieed58582015-09-10 18:43:34 -07002133 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002134 continue;
Adam Lesinski1e4663852014-08-15 14:47:28 -07002135 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002136 if (!assets->isJavaSymbol(sym, includePrivate)) {
2137 continue;
Adam Lesinski1e4663852014-08-15 14:47:28 -07002138 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002139 String8 flat_name(flattenSymbol(sym.name));
2140 fprintf(fp,
2141 "%s%s.%s = (%s.%s & 0x00ffffff) | (packageId << 24);\n",
2142 getIndentSpace(indent), className.string(), flat_name.string(),
2143 className.string(), flat_name.string());
Adam Lesinski1e4663852014-08-15 14:47:28 -07002144 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002145
2146 N = symbols->getNestedSymbols().size();
2147 for (i=0; i<N; i++) {
2148 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2149 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2150 if (nclassName == "styleable") {
2151 err = writeResourceLoadedCallbackForLayoutClasses(
2152 fp, assets, nsymbols, indent, includePrivate);
2153 } else {
2154 err = writeResourceLoadedCallback(fp, assets, includePrivate, nsymbols,
2155 nclassName, indent);
Adam Lesinski1e4663852014-08-15 14:47:28 -07002156 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002157 if (err != NO_ERROR) {
2158 return err;
2159 }
Adam Lesinski1e4663852014-08-15 14:47:28 -07002160 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002161
2162 return NO_ERROR;
Adam Lesinski1e4663852014-08-15 14:47:28 -07002163}
2164
Adam Lesinski282e1812014-01-23 18:17:42 -08002165static status_t writeLayoutClasses(
2166 FILE* fp, const sp<AaptAssets>& assets,
Adam Lesinskie8e91922014-08-06 17:41:08 -07002167 const sp<AaptSymbols>& symbols, int indent, bool includePrivate, bool nonConstantId)
Adam Lesinski282e1812014-01-23 18:17:42 -08002168{
2169 const char* indentStr = getIndentSpace(indent);
2170 if (!includePrivate) {
2171 fprintf(fp, "%s/** @doconly */\n", indentStr);
2172 }
2173 fprintf(fp, "%spublic static final class styleable {\n", indentStr);
2174 indent++;
2175
2176 String16 attr16("attr");
2177 String16 package16(assets->getPackage());
2178
2179 indentStr = getIndentSpace(indent);
2180 bool hasErrors = false;
2181
2182 size_t i;
2183 size_t N = symbols->getNestedSymbols().size();
2184 for (i=0; i<N; i++) {
2185 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2186 String8 realClassName(symbols->getNestedSymbols().keyAt(i));
2187 String8 nclassName(flattenSymbol(realClassName));
2188
2189 SortedVector<uint32_t> idents;
2190 Vector<uint32_t> origOrder;
2191 Vector<bool> publicFlags;
2192
2193 size_t a;
2194 size_t NA = nsymbols->getSymbols().size();
2195 for (a=0; a<NA; a++) {
2196 const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a));
2197 int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32
2198 ? sym.int32Val : 0;
2199 bool isPublic = true;
2200 if (code == 0) {
2201 String16 name16(sym.name);
2202 uint32_t typeSpecFlags;
2203 code = assets->getIncludedResources().identifierForName(
2204 name16.string(), name16.size(),
2205 attr16.string(), attr16.size(),
2206 package16.string(), package16.size(), &typeSpecFlags);
2207 if (code == 0) {
2208 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
2209 nclassName.string(), sym.name.string());
2210 hasErrors = true;
2211 }
2212 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
2213 }
2214 idents.add(code);
2215 origOrder.add(code);
2216 publicFlags.add(isPublic);
2217 }
2218
2219 NA = idents.size();
2220
Adam Lesinski282e1812014-01-23 18:17:42 -08002221 String16 comment = symbols->getComment(realClassName);
Jeff Browneb490d62014-06-06 19:43:42 -07002222 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002223 fprintf(fp, "%s/** ", indentStr);
2224 if (comment.size() > 0) {
2225 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002226 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002227 fprintf(fp, "%s\n", cmt.string());
Adam Lesinski282e1812014-01-23 18:17:42 -08002228 } else {
2229 fprintf(fp, "Attributes that can be used with a %s.\n", nclassName.string());
2230 }
2231 bool hasTable = false;
2232 for (a=0; a<NA; a++) {
2233 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2234 if (pos >= 0) {
2235 if (!hasTable) {
2236 hasTable = true;
2237 fprintf(fp,
2238 "%s <p>Includes the following attributes:</p>\n"
2239 "%s <table>\n"
2240 "%s <colgroup align=\"left\" />\n"
2241 "%s <colgroup align=\"left\" />\n"
2242 "%s <tr><th>Attribute</th><th>Description</th></tr>\n",
2243 indentStr,
2244 indentStr,
2245 indentStr,
2246 indentStr,
2247 indentStr);
2248 }
2249 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2250 if (!publicFlags.itemAt(a) && !includePrivate) {
2251 continue;
2252 }
2253 String8 name8(sym.name);
2254 String16 comment(sym.comment);
2255 if (comment.size() <= 0) {
2256 comment = getAttributeComment(assets, name8);
2257 }
2258 if (comment.size() > 0) {
2259 const char16_t* p = comment.string();
2260 while (*p != 0 && *p != '.') {
2261 if (*p == '{') {
2262 while (*p != 0 && *p != '}') {
2263 p++;
2264 }
2265 } else {
2266 p++;
2267 }
2268 }
2269 if (*p == '.') {
2270 p++;
2271 }
2272 comment = String16(comment.string(), p-comment.string());
2273 }
2274 fprintf(fp, "%s <tr><td><code>{@link #%s_%s %s:%s}</code></td><td>%s</td></tr>\n",
2275 indentStr, nclassName.string(),
2276 flattenSymbol(name8).string(),
2277 getSymbolPackage(name8, assets, true).string(),
2278 getSymbolName(name8).string(),
2279 String8(comment).string());
2280 }
2281 }
2282 if (hasTable) {
2283 fprintf(fp, "%s </table>\n", indentStr);
2284 }
2285 for (a=0; a<NA; a++) {
2286 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2287 if (pos >= 0) {
2288 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2289 if (!publicFlags.itemAt(a) && !includePrivate) {
2290 continue;
2291 }
2292 fprintf(fp, "%s @see #%s_%s\n",
2293 indentStr, nclassName.string(),
2294 flattenSymbol(sym.name).string());
2295 }
2296 }
2297 fprintf(fp, "%s */\n", getIndentSpace(indent));
2298
Jeff Browneb490d62014-06-06 19:43:42 -07002299 ann.printAnnotations(fp, indentStr);
Adam Lesinski282e1812014-01-23 18:17:42 -08002300
2301 fprintf(fp,
2302 "%spublic static final int[] %s = {\n"
2303 "%s",
2304 indentStr, nclassName.string(),
2305 getIndentSpace(indent+1));
2306
2307 for (a=0; a<NA; a++) {
2308 if (a != 0) {
2309 if ((a&3) == 0) {
2310 fprintf(fp, ",\n%s", getIndentSpace(indent+1));
2311 } else {
2312 fprintf(fp, ", ");
2313 }
2314 }
2315 fprintf(fp, "0x%08x", idents[a]);
2316 }
2317
2318 fprintf(fp, "\n%s};\n", indentStr);
2319
2320 for (a=0; a<NA; a++) {
2321 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2322 if (pos >= 0) {
2323 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2324 if (!publicFlags.itemAt(a) && !includePrivate) {
2325 continue;
2326 }
2327 String8 name8(sym.name);
2328 String16 comment(sym.comment);
2329 String16 typeComment;
2330 if (comment.size() <= 0) {
2331 comment = getAttributeComment(assets, name8, &typeComment);
2332 } else {
2333 getAttributeComment(assets, name8, &typeComment);
2334 }
2335
2336 uint32_t typeSpecFlags = 0;
2337 String16 name16(sym.name);
2338 assets->getIncludedResources().identifierForName(
2339 name16.string(), name16.size(),
2340 attr16.string(), attr16.size(),
2341 package16.string(), package16.size(), &typeSpecFlags);
2342 //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
2343 // String8(attr16).string(), String8(name16).string(), typeSpecFlags);
2344 const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
Jeff Browneb490d62014-06-06 19:43:42 -07002345
2346 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002347 fprintf(fp, "%s/**\n", indentStr);
2348 if (comment.size() > 0) {
2349 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002350 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002351 fprintf(fp, "%s <p>\n%s @attr description\n", indentStr, indentStr);
2352 fprintf(fp, "%s %s\n", indentStr, cmt.string());
Adam Lesinski282e1812014-01-23 18:17:42 -08002353 } else {
2354 fprintf(fp,
2355 "%s <p>This symbol is the offset where the {@link %s.R.attr#%s}\n"
2356 "%s attribute's value can be found in the {@link #%s} array.\n",
2357 indentStr,
2358 getSymbolPackage(name8, assets, pub).string(),
2359 getSymbolName(name8).string(),
2360 indentStr, nclassName.string());
2361 }
2362 if (typeComment.size() > 0) {
2363 String8 cmt(typeComment);
Jeff Browneb490d62014-06-06 19:43:42 -07002364 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002365 fprintf(fp, "\n\n%s %s\n", indentStr, cmt.string());
Adam Lesinski282e1812014-01-23 18:17:42 -08002366 }
2367 if (comment.size() > 0) {
2368 if (pub) {
2369 fprintf(fp,
2370 "%s <p>This corresponds to the global attribute\n"
2371 "%s resource symbol {@link %s.R.attr#%s}.\n",
2372 indentStr, indentStr,
2373 getSymbolPackage(name8, assets, true).string(),
2374 getSymbolName(name8).string());
2375 } else {
2376 fprintf(fp,
2377 "%s <p>This is a private symbol.\n", indentStr);
2378 }
2379 }
2380 fprintf(fp, "%s @attr name %s:%s\n", indentStr,
2381 getSymbolPackage(name8, assets, pub).string(),
2382 getSymbolName(name8).string());
2383 fprintf(fp, "%s*/\n", indentStr);
Jeff Browneb490d62014-06-06 19:43:42 -07002384 ann.printAnnotations(fp, indentStr);
Adam Lesinskie8e91922014-08-06 17:41:08 -07002385
2386 const char * id_format = nonConstantId ?
2387 "%spublic static int %s_%s = %d;\n" :
2388 "%spublic static final int %s_%s = %d;\n";
2389
Adam Lesinski282e1812014-01-23 18:17:42 -08002390 fprintf(fp,
Adam Lesinskie8e91922014-08-06 17:41:08 -07002391 id_format,
Adam Lesinski282e1812014-01-23 18:17:42 -08002392 indentStr, nclassName.string(),
2393 flattenSymbol(name8).string(), (int)pos);
2394 }
2395 }
2396 }
2397
2398 indent--;
2399 fprintf(fp, "%s};\n", getIndentSpace(indent));
Andreas Gampe2412f842014-09-30 20:55:57 -07002400 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08002401}
2402
2403static status_t writeTextLayoutClasses(
2404 FILE* fp, const sp<AaptAssets>& assets,
2405 const sp<AaptSymbols>& symbols, bool includePrivate)
2406{
2407 String16 attr16("attr");
2408 String16 package16(assets->getPackage());
2409
2410 bool hasErrors = false;
2411
2412 size_t i;
2413 size_t N = symbols->getNestedSymbols().size();
2414 for (i=0; i<N; i++) {
2415 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2416 String8 realClassName(symbols->getNestedSymbols().keyAt(i));
2417 String8 nclassName(flattenSymbol(realClassName));
2418
2419 SortedVector<uint32_t> idents;
2420 Vector<uint32_t> origOrder;
2421 Vector<bool> publicFlags;
2422
2423 size_t a;
2424 size_t NA = nsymbols->getSymbols().size();
2425 for (a=0; a<NA; a++) {
2426 const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a));
2427 int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32
2428 ? sym.int32Val : 0;
2429 bool isPublic = true;
2430 if (code == 0) {
2431 String16 name16(sym.name);
2432 uint32_t typeSpecFlags;
2433 code = assets->getIncludedResources().identifierForName(
2434 name16.string(), name16.size(),
2435 attr16.string(), attr16.size(),
2436 package16.string(), package16.size(), &typeSpecFlags);
2437 if (code == 0) {
2438 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
2439 nclassName.string(), sym.name.string());
2440 hasErrors = true;
2441 }
2442 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
2443 }
2444 idents.add(code);
2445 origOrder.add(code);
2446 publicFlags.add(isPublic);
2447 }
2448
2449 NA = idents.size();
2450
2451 fprintf(fp, "int[] styleable %s {", nclassName.string());
2452
2453 for (a=0; a<NA; a++) {
2454 if (a != 0) {
2455 fprintf(fp, ",");
2456 }
2457 fprintf(fp, " 0x%08x", idents[a]);
2458 }
2459
2460 fprintf(fp, " }\n");
2461
2462 for (a=0; a<NA; a++) {
2463 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2464 if (pos >= 0) {
2465 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2466 if (!publicFlags.itemAt(a) && !includePrivate) {
2467 continue;
2468 }
2469 String8 name8(sym.name);
2470 String16 comment(sym.comment);
2471 String16 typeComment;
2472 if (comment.size() <= 0) {
2473 comment = getAttributeComment(assets, name8, &typeComment);
2474 } else {
2475 getAttributeComment(assets, name8, &typeComment);
2476 }
2477
2478 uint32_t typeSpecFlags = 0;
2479 String16 name16(sym.name);
2480 assets->getIncludedResources().identifierForName(
2481 name16.string(), name16.size(),
2482 attr16.string(), attr16.size(),
2483 package16.string(), package16.size(), &typeSpecFlags);
2484 //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
2485 // String8(attr16).string(), String8(name16).string(), typeSpecFlags);
Andreas Gampe2412f842014-09-30 20:55:57 -07002486 //const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08002487
2488 fprintf(fp,
2489 "int styleable %s_%s %d\n",
2490 nclassName.string(),
2491 flattenSymbol(name8).string(), (int)pos);
2492 }
2493 }
2494 }
2495
Andreas Gampe2412f842014-09-30 20:55:57 -07002496 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08002497}
2498
2499static status_t writeSymbolClass(
2500 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2501 const sp<AaptSymbols>& symbols, const String8& className, int indent,
Adam Lesinski1e4663852014-08-15 14:47:28 -07002502 bool nonConstantId, bool emitCallback)
Adam Lesinski282e1812014-01-23 18:17:42 -08002503{
2504 fprintf(fp, "%spublic %sfinal class %s {\n",
2505 getIndentSpace(indent),
2506 indent != 0 ? "static " : "", className.string());
2507 indent++;
2508
2509 size_t i;
2510 status_t err = NO_ERROR;
2511
2512 const char * id_format = nonConstantId ?
2513 "%spublic static int %s=0x%08x;\n" :
2514 "%spublic static final int %s=0x%08x;\n";
2515
2516 size_t N = symbols->getSymbols().size();
2517 for (i=0; i<N; i++) {
2518 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2519 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
2520 continue;
2521 }
2522 if (!assets->isJavaSymbol(sym, includePrivate)) {
2523 continue;
2524 }
2525 String8 name8(sym.name);
2526 String16 comment(sym.comment);
2527 bool haveComment = false;
Jeff Browneb490d62014-06-06 19:43:42 -07002528 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002529 if (comment.size() > 0) {
2530 haveComment = true;
2531 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002532 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002533 fprintf(fp,
2534 "%s/** %s\n",
2535 getIndentSpace(indent), cmt.string());
Adam Lesinski282e1812014-01-23 18:17:42 -08002536 }
2537 String16 typeComment(sym.typeComment);
2538 if (typeComment.size() > 0) {
2539 String8 cmt(typeComment);
Jeff Browneb490d62014-06-06 19:43:42 -07002540 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002541 if (!haveComment) {
2542 haveComment = true;
2543 fprintf(fp,
2544 "%s/** %s\n", getIndentSpace(indent), cmt.string());
2545 } else {
2546 fprintf(fp,
2547 "%s %s\n", getIndentSpace(indent), cmt.string());
2548 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002549 }
2550 if (haveComment) {
2551 fprintf(fp,"%s */\n", getIndentSpace(indent));
2552 }
Jeff Browneb490d62014-06-06 19:43:42 -07002553 ann.printAnnotations(fp, getIndentSpace(indent));
Adam Lesinski282e1812014-01-23 18:17:42 -08002554 fprintf(fp, id_format,
2555 getIndentSpace(indent),
2556 flattenSymbol(name8).string(), (int)sym.int32Val);
2557 }
2558
2559 for (i=0; i<N; i++) {
2560 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2561 if (sym.typeCode != AaptSymbolEntry::TYPE_STRING) {
2562 continue;
2563 }
2564 if (!assets->isJavaSymbol(sym, includePrivate)) {
2565 continue;
2566 }
2567 String8 name8(sym.name);
2568 String16 comment(sym.comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002569 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002570 if (comment.size() > 0) {
2571 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002572 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002573 fprintf(fp,
2574 "%s/** %s\n"
2575 "%s */\n",
2576 getIndentSpace(indent), cmt.string(),
2577 getIndentSpace(indent));
Adam Lesinski282e1812014-01-23 18:17:42 -08002578 }
Jeff Browneb490d62014-06-06 19:43:42 -07002579 ann.printAnnotations(fp, getIndentSpace(indent));
Adam Lesinski282e1812014-01-23 18:17:42 -08002580 fprintf(fp, "%spublic static final String %s=\"%s\";\n",
2581 getIndentSpace(indent),
2582 flattenSymbol(name8).string(), sym.stringVal.string());
2583 }
2584
2585 sp<AaptSymbols> styleableSymbols;
2586
2587 N = symbols->getNestedSymbols().size();
2588 for (i=0; i<N; i++) {
2589 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2590 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2591 if (nclassName == "styleable") {
2592 styleableSymbols = nsymbols;
2593 } else {
Adam Lesinski1e4663852014-08-15 14:47:28 -07002594 err = writeSymbolClass(fp, assets, includePrivate, nsymbols, nclassName,
2595 indent, nonConstantId, false);
Adam Lesinski282e1812014-01-23 18:17:42 -08002596 }
2597 if (err != NO_ERROR) {
2598 return err;
2599 }
2600 }
2601
2602 if (styleableSymbols != NULL) {
Adam Lesinskie8e91922014-08-06 17:41:08 -07002603 err = writeLayoutClasses(fp, assets, styleableSymbols, indent, includePrivate, nonConstantId);
Adam Lesinski282e1812014-01-23 18:17:42 -08002604 if (err != NO_ERROR) {
2605 return err;
2606 }
2607 }
2608
Adam Lesinski1e4663852014-08-15 14:47:28 -07002609 if (emitCallback) {
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002610 fprintf(fp, "%spublic static void onResourcesLoaded(int packageId) {\n",
2611 getIndentSpace(indent));
2612 writeResourceLoadedCallback(fp, assets, includePrivate, symbols, className, indent + 1);
2613 fprintf(fp, "%s}\n", getIndentSpace(indent));
Adam Lesinski1e4663852014-08-15 14:47:28 -07002614 }
2615
Adam Lesinski282e1812014-01-23 18:17:42 -08002616 indent--;
2617 fprintf(fp, "%s}\n", getIndentSpace(indent));
2618 return NO_ERROR;
2619}
2620
2621static status_t writeTextSymbolClass(
2622 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2623 const sp<AaptSymbols>& symbols, const String8& className)
2624{
2625 size_t i;
2626 status_t err = NO_ERROR;
2627
2628 size_t N = symbols->getSymbols().size();
2629 for (i=0; i<N; i++) {
2630 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2631 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
2632 continue;
2633 }
2634
2635 if (!assets->isJavaSymbol(sym, includePrivate)) {
2636 continue;
2637 }
2638
2639 String8 name8(sym.name);
2640 fprintf(fp, "int %s %s 0x%08x\n",
2641 className.string(),
2642 flattenSymbol(name8).string(), (int)sym.int32Val);
2643 }
2644
2645 N = symbols->getNestedSymbols().size();
2646 for (i=0; i<N; i++) {
2647 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2648 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2649 if (nclassName == "styleable") {
2650 err = writeTextLayoutClasses(fp, assets, nsymbols, includePrivate);
2651 } else {
2652 err = writeTextSymbolClass(fp, assets, includePrivate, nsymbols, nclassName);
2653 }
2654 if (err != NO_ERROR) {
2655 return err;
2656 }
2657 }
2658
2659 return NO_ERROR;
2660}
2661
2662status_t writeResourceSymbols(Bundle* bundle, const sp<AaptAssets>& assets,
Adam Lesinski1e4663852014-08-15 14:47:28 -07002663 const String8& package, bool includePrivate, bool emitCallback)
Adam Lesinski282e1812014-01-23 18:17:42 -08002664{
2665 if (!bundle->getRClassDir()) {
2666 return NO_ERROR;
2667 }
2668
2669 const char* textSymbolsDest = bundle->getOutputTextSymbols();
2670
2671 String8 R("R");
2672 const size_t N = assets->getSymbols().size();
2673 for (size_t i=0; i<N; i++) {
2674 sp<AaptSymbols> symbols = assets->getSymbols().valueAt(i);
2675 String8 className(assets->getSymbols().keyAt(i));
2676 String8 dest(bundle->getRClassDir());
2677
2678 if (bundle->getMakePackageDirs()) {
2679 String8 pkg(package);
2680 const char* last = pkg.string();
2681 const char* s = last-1;
2682 do {
2683 s++;
2684 if (s > last && (*s == '.' || *s == 0)) {
2685 String8 part(last, s-last);
2686 dest.appendPath(part);
Elliott Hughese17788c2015-08-17 12:41:46 -07002687#ifdef _WIN32
Adam Lesinski282e1812014-01-23 18:17:42 -08002688 _mkdir(dest.string());
2689#else
2690 mkdir(dest.string(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP);
2691#endif
2692 last = s+1;
2693 }
2694 } while (*s);
2695 }
2696 dest.appendPath(className);
2697 dest.append(".java");
2698 FILE* fp = fopen(dest.string(), "w+");
2699 if (fp == NULL) {
2700 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
2701 dest.string(), strerror(errno));
2702 return UNKNOWN_ERROR;
2703 }
2704 if (bundle->getVerbose()) {
2705 printf(" Writing symbols for class %s.\n", className.string());
2706 }
2707
2708 fprintf(fp,
2709 "/* AUTO-GENERATED FILE. DO NOT MODIFY.\n"
2710 " *\n"
2711 " * This class was automatically generated by the\n"
2712 " * aapt tool from the resource data it found. It\n"
2713 " * should not be modified by hand.\n"
2714 " */\n"
2715 "\n"
2716 "package %s;\n\n", package.string());
2717
2718 status_t err = writeSymbolClass(fp, assets, includePrivate, symbols,
Adam Lesinski1e4663852014-08-15 14:47:28 -07002719 className, 0, bundle->getNonConstantId(), emitCallback);
Elliott Hughesb30296b2013-10-29 15:25:52 -07002720 fclose(fp);
Adam Lesinski282e1812014-01-23 18:17:42 -08002721 if (err != NO_ERROR) {
2722 return err;
2723 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002724
2725 if (textSymbolsDest != NULL && R == className) {
2726 String8 textDest(textSymbolsDest);
2727 textDest.appendPath(className);
2728 textDest.append(".txt");
2729
2730 FILE* fp = fopen(textDest.string(), "w+");
2731 if (fp == NULL) {
2732 fprintf(stderr, "ERROR: Unable to open text symbol file %s: %s\n",
2733 textDest.string(), strerror(errno));
2734 return UNKNOWN_ERROR;
2735 }
2736 if (bundle->getVerbose()) {
2737 printf(" Writing text symbols for class %s.\n", className.string());
2738 }
2739
2740 status_t err = writeTextSymbolClass(fp, assets, includePrivate, symbols,
2741 className);
Elliott Hughesb30296b2013-10-29 15:25:52 -07002742 fclose(fp);
Adam Lesinski282e1812014-01-23 18:17:42 -08002743 if (err != NO_ERROR) {
2744 return err;
2745 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002746 }
2747
2748 // If we were asked to generate a dependency file, we'll go ahead and add this R.java
2749 // as a target in the dependency file right next to it.
2750 if (bundle->getGenDependencies() && R == className) {
2751 // Add this R.java to the dependency file
2752 String8 dependencyFile(bundle->getRClassDir());
2753 dependencyFile.appendPath("R.java.d");
2754
2755 FILE *fp = fopen(dependencyFile.string(), "a");
2756 fprintf(fp,"%s \\\n", dest.string());
2757 fclose(fp);
2758 }
2759 }
2760
2761 return NO_ERROR;
2762}
2763
2764
2765class ProguardKeepSet
2766{
2767public:
2768 // { rule --> { file locations } }
2769 KeyedVector<String8, SortedVector<String8> > rules;
2770
2771 void add(const String8& rule, const String8& where);
2772};
2773
2774void ProguardKeepSet::add(const String8& rule, const String8& where)
2775{
2776 ssize_t index = rules.indexOfKey(rule);
2777 if (index < 0) {
2778 index = rules.add(rule, SortedVector<String8>());
2779 }
2780 rules.editValueAt(index).add(where);
2781}
2782
2783void
2784addProguardKeepRule(ProguardKeepSet* keep, const String8& inClassName,
2785 const char* pkg, const String8& srcName, int line)
2786{
2787 String8 className(inClassName);
2788 if (pkg != NULL) {
2789 // asdf --> package.asdf
2790 // .asdf .a.b --> package.asdf package.a.b
2791 // asdf.adsf --> asdf.asdf
2792 const char* p = className.string();
2793 const char* q = strchr(p, '.');
2794 if (p == q) {
2795 className = pkg;
2796 className.append(inClassName);
2797 } else if (q == NULL) {
2798 className = pkg;
2799 className.append(".");
2800 className.append(inClassName);
2801 }
2802 }
2803
2804 String8 rule("-keep class ");
2805 rule += className;
2806 rule += " { <init>(...); }";
2807
2808 String8 location("view ");
2809 location += srcName;
2810 char lineno[20];
2811 sprintf(lineno, ":%d", line);
2812 location += lineno;
2813
2814 keep->add(rule, location);
2815}
2816
2817void
2818addProguardKeepMethodRule(ProguardKeepSet* keep, const String8& memberName,
Andreas Gampe2412f842014-09-30 20:55:57 -07002819 const char* /* pkg */, const String8& srcName, int line)
Adam Lesinski282e1812014-01-23 18:17:42 -08002820{
2821 String8 rule("-keepclassmembers class * { *** ");
2822 rule += memberName;
2823 rule += "(...); }";
2824
2825 String8 location("onClick ");
2826 location += srcName;
2827 char lineno[20];
2828 sprintf(lineno, ":%d", line);
2829 location += lineno;
2830
2831 keep->add(rule, location);
2832}
2833
2834status_t
2835writeProguardForAndroidManifest(ProguardKeepSet* keep, const sp<AaptAssets>& assets)
2836{
2837 status_t err;
2838 ResXMLTree tree;
2839 size_t len;
2840 ResXMLTree::event_code_t code;
2841 int depth = 0;
2842 bool inApplication = false;
2843 String8 error;
2844 sp<AaptGroup> assGroup;
2845 sp<AaptFile> assFile;
2846 String8 pkg;
2847
2848 // First, look for a package file to parse. This is required to
2849 // be able to generate the resource information.
2850 assGroup = assets->getFiles().valueFor(String8("AndroidManifest.xml"));
2851 if (assGroup == NULL) {
2852 fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n");
2853 return -1;
2854 }
2855
2856 if (assGroup->getFiles().size() != 1) {
2857 fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
2858 assGroup->getFiles().valueAt(0)->getPrintableSource().string());
2859 }
2860
2861 assFile = assGroup->getFiles().valueAt(0);
2862
2863 err = parseXMLResource(assFile, &tree);
2864 if (err != NO_ERROR) {
2865 return err;
2866 }
2867
2868 tree.restart();
2869
2870 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
2871 if (code == ResXMLTree::END_TAG) {
2872 if (/* name == "Application" && */ depth == 2) {
2873 inApplication = false;
2874 }
2875 depth--;
2876 continue;
2877 }
2878 if (code != ResXMLTree::START_TAG) {
2879 continue;
2880 }
2881 depth++;
2882 String8 tag(tree.getElementName(&len));
2883 // printf("Depth %d tag %s\n", depth, tag.string());
2884 bool keepTag = false;
2885 if (depth == 1) {
2886 if (tag != "manifest") {
2887 fprintf(stderr, "ERROR: manifest does not start with <manifest> tag\n");
2888 return -1;
2889 }
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07002890 pkg = AaptXml::getAttribute(tree, NULL, "package");
Adam Lesinski282e1812014-01-23 18:17:42 -08002891 } else if (depth == 2) {
2892 if (tag == "application") {
2893 inApplication = true;
2894 keepTag = true;
2895
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07002896 String8 agent = AaptXml::getAttribute(tree,
2897 "http://schemas.android.com/apk/res/android",
Adam Lesinski282e1812014-01-23 18:17:42 -08002898 "backupAgent", &error);
2899 if (agent.length() > 0) {
2900 addProguardKeepRule(keep, agent, pkg.string(),
2901 assFile->getPrintableSource(), tree.getLineNumber());
2902 }
2903 } else if (tag == "instrumentation") {
2904 keepTag = true;
2905 }
2906 }
2907 if (!keepTag && inApplication && depth == 3) {
2908 if (tag == "activity" || tag == "service" || tag == "receiver" || tag == "provider") {
2909 keepTag = true;
2910 }
2911 }
2912 if (keepTag) {
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07002913 String8 name = AaptXml::getAttribute(tree,
2914 "http://schemas.android.com/apk/res/android", "name", &error);
Adam Lesinski282e1812014-01-23 18:17:42 -08002915 if (error != "") {
2916 fprintf(stderr, "ERROR: %s\n", error.string());
2917 return -1;
2918 }
2919 if (name.length() > 0) {
2920 addProguardKeepRule(keep, name, pkg.string(),
2921 assFile->getPrintableSource(), tree.getLineNumber());
2922 }
2923 }
2924 }
2925
2926 return NO_ERROR;
2927}
2928
2929struct NamespaceAttributePair {
2930 const char* ns;
2931 const char* attr;
2932
2933 NamespaceAttributePair(const char* n, const char* a) : ns(n), attr(a) {}
2934 NamespaceAttributePair() : ns(NULL), attr(NULL) {}
2935};
2936
2937status_t
2938writeProguardForXml(ProguardKeepSet* keep, const sp<AaptFile>& layoutFile,
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07002939 const Vector<String8>& startTags, const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs)
Adam Lesinski282e1812014-01-23 18:17:42 -08002940{
2941 status_t err;
2942 ResXMLTree tree;
2943 size_t len;
2944 ResXMLTree::event_code_t code;
2945
2946 err = parseXMLResource(layoutFile, &tree);
2947 if (err != NO_ERROR) {
2948 return err;
2949 }
2950
2951 tree.restart();
2952
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07002953 if (!startTags.isEmpty()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002954 bool haveStart = false;
2955 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
2956 if (code != ResXMLTree::START_TAG) {
2957 continue;
2958 }
2959 String8 tag(tree.getElementName(&len));
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07002960 const size_t numStartTags = startTags.size();
2961 for (size_t i = 0; i < numStartTags; i++) {
2962 if (tag == startTags[i]) {
2963 haveStart = true;
2964 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002965 }
2966 break;
2967 }
2968 if (!haveStart) {
2969 return NO_ERROR;
2970 }
2971 }
2972
2973 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
2974 if (code != ResXMLTree::START_TAG) {
2975 continue;
2976 }
2977 String8 tag(tree.getElementName(&len));
2978
2979 // If there is no '.', we'll assume that it's one of the built in names.
2980 if (strchr(tag.string(), '.')) {
2981 addProguardKeepRule(keep, tag, NULL,
2982 layoutFile->getPrintableSource(), tree.getLineNumber());
2983 } else if (tagAttrPairs != NULL) {
2984 ssize_t tagIndex = tagAttrPairs->indexOfKey(tag);
2985 if (tagIndex >= 0) {
2986 const Vector<NamespaceAttributePair>& nsAttrVector = tagAttrPairs->valueAt(tagIndex);
2987 for (size_t i = 0; i < nsAttrVector.size(); i++) {
2988 const NamespaceAttributePair& nsAttr = nsAttrVector[i];
2989
2990 ssize_t attrIndex = tree.indexOfAttribute(nsAttr.ns, nsAttr.attr);
2991 if (attrIndex < 0) {
2992 // fprintf(stderr, "%s:%d: <%s> does not have attribute %s:%s.\n",
2993 // layoutFile->getPrintableSource().string(), tree.getLineNumber(),
2994 // tag.string(), nsAttr.ns, nsAttr.attr);
2995 } else {
2996 size_t len;
2997 addProguardKeepRule(keep,
2998 String8(tree.getAttributeStringValue(attrIndex, &len)), NULL,
2999 layoutFile->getPrintableSource(), tree.getLineNumber());
3000 }
3001 }
3002 }
3003 }
3004 ssize_t attrIndex = tree.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "onClick");
3005 if (attrIndex >= 0) {
3006 size_t len;
3007 addProguardKeepMethodRule(keep,
3008 String8(tree.getAttributeStringValue(attrIndex, &len)), NULL,
3009 layoutFile->getPrintableSource(), tree.getLineNumber());
3010 }
3011 }
3012
3013 return NO_ERROR;
3014}
3015
3016static void addTagAttrPair(KeyedVector<String8, Vector<NamespaceAttributePair> >* dest,
3017 const char* tag, const char* ns, const char* attr) {
3018 String8 tagStr(tag);
3019 ssize_t index = dest->indexOfKey(tagStr);
3020
3021 if (index < 0) {
3022 Vector<NamespaceAttributePair> vector;
3023 vector.add(NamespaceAttributePair(ns, attr));
3024 dest->add(tagStr, vector);
3025 } else {
3026 dest->editValueAt(index).add(NamespaceAttributePair(ns, attr));
3027 }
3028}
3029
3030status_t
3031writeProguardForLayouts(ProguardKeepSet* keep, const sp<AaptAssets>& assets)
3032{
3033 status_t err;
Adam Lesinski62c5df52014-12-02 16:19:05 -08003034 const char* kClass = "class";
3035 const char* kFragment = "fragment";
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003036 const String8 kTransition("transition");
3037 const String8 kTransitionPrefix("transition-");
Adam Lesinski282e1812014-01-23 18:17:42 -08003038
3039 // tag:attribute pairs that should be checked in layout files.
3040 KeyedVector<String8, Vector<NamespaceAttributePair> > kLayoutTagAttrPairs;
Adam Lesinski62c5df52014-12-02 16:19:05 -08003041 addTagAttrPair(&kLayoutTagAttrPairs, "view", NULL, kClass);
3042 addTagAttrPair(&kLayoutTagAttrPairs, kFragment, NULL, kClass);
3043 addTagAttrPair(&kLayoutTagAttrPairs, kFragment, RESOURCES_ANDROID_NAMESPACE, "name");
Adam Lesinski282e1812014-01-23 18:17:42 -08003044
3045 // tag:attribute pairs that should be checked in xml files.
3046 KeyedVector<String8, Vector<NamespaceAttributePair> > kXmlTagAttrPairs;
Adam Lesinski62c5df52014-12-02 16:19:05 -08003047 addTagAttrPair(&kXmlTagAttrPairs, "PreferenceScreen", RESOURCES_ANDROID_NAMESPACE, kFragment);
3048 addTagAttrPair(&kXmlTagAttrPairs, "header", RESOURCES_ANDROID_NAMESPACE, kFragment);
Adam Lesinski282e1812014-01-23 18:17:42 -08003049
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003050 // tag:attribute pairs that should be checked in transition files.
3051 KeyedVector<String8, Vector<NamespaceAttributePair> > kTransitionTagAttrPairs;
Adam Lesinski62c5df52014-12-02 16:19:05 -08003052 addTagAttrPair(&kTransitionTagAttrPairs, kTransition.string(), NULL, kClass);
3053 addTagAttrPair(&kTransitionTagAttrPairs, "pathMotion", NULL, kClass);
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003054
Adam Lesinski282e1812014-01-23 18:17:42 -08003055 const Vector<sp<AaptDir> >& dirs = assets->resDirs();
3056 const size_t K = dirs.size();
3057 for (size_t k=0; k<K; k++) {
3058 const sp<AaptDir>& d = dirs.itemAt(k);
3059 const String8& dirName = d->getLeaf();
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003060 Vector<String8> startTags;
Adam Lesinski282e1812014-01-23 18:17:42 -08003061 const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs = NULL;
3062 if ((dirName == String8("layout")) || (strncmp(dirName.string(), "layout-", 7) == 0)) {
3063 tagAttrPairs = &kLayoutTagAttrPairs;
3064 } else if ((dirName == String8("xml")) || (strncmp(dirName.string(), "xml-", 4) == 0)) {
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003065 startTags.add(String8("PreferenceScreen"));
3066 startTags.add(String8("preference-headers"));
Adam Lesinski282e1812014-01-23 18:17:42 -08003067 tagAttrPairs = &kXmlTagAttrPairs;
3068 } else if ((dirName == String8("menu")) || (strncmp(dirName.string(), "menu-", 5) == 0)) {
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003069 startTags.add(String8("menu"));
Adam Lesinski282e1812014-01-23 18:17:42 -08003070 tagAttrPairs = NULL;
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003071 } else if (dirName == kTransition || (strncmp(dirName.string(), kTransitionPrefix.string(),
3072 kTransitionPrefix.size()) == 0)) {
3073 tagAttrPairs = &kTransitionTagAttrPairs;
Adam Lesinski282e1812014-01-23 18:17:42 -08003074 } else {
3075 continue;
3076 }
3077
3078 const KeyedVector<String8,sp<AaptGroup> > groups = d->getFiles();
3079 const size_t N = groups.size();
3080 for (size_t i=0; i<N; i++) {
3081 const sp<AaptGroup>& group = groups.valueAt(i);
3082 const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files = group->getFiles();
3083 const size_t M = files.size();
3084 for (size_t j=0; j<M; j++) {
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003085 err = writeProguardForXml(keep, files.valueAt(j), startTags, tagAttrPairs);
Adam Lesinski282e1812014-01-23 18:17:42 -08003086 if (err < 0) {
3087 return err;
3088 }
3089 }
3090 }
3091 }
3092 // Handle the overlays
3093 sp<AaptAssets> overlay = assets->getOverlay();
3094 if (overlay.get()) {
3095 return writeProguardForLayouts(keep, overlay);
3096 }
3097
3098 return NO_ERROR;
3099}
3100
3101status_t
3102writeProguardFile(Bundle* bundle, const sp<AaptAssets>& assets)
3103{
3104 status_t err = -1;
3105
3106 if (!bundle->getProguardFile()) {
3107 return NO_ERROR;
3108 }
3109
3110 ProguardKeepSet keep;
3111
3112 err = writeProguardForAndroidManifest(&keep, assets);
3113 if (err < 0) {
3114 return err;
3115 }
3116
3117 err = writeProguardForLayouts(&keep, assets);
3118 if (err < 0) {
3119 return err;
3120 }
3121
3122 FILE* fp = fopen(bundle->getProguardFile(), "w+");
3123 if (fp == NULL) {
3124 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
3125 bundle->getProguardFile(), strerror(errno));
3126 return UNKNOWN_ERROR;
3127 }
3128
3129 const KeyedVector<String8, SortedVector<String8> >& rules = keep.rules;
3130 const size_t N = rules.size();
3131 for (size_t i=0; i<N; i++) {
3132 const SortedVector<String8>& locations = rules.valueAt(i);
3133 const size_t M = locations.size();
3134 for (size_t j=0; j<M; j++) {
3135 fprintf(fp, "# %s\n", locations.itemAt(j).string());
3136 }
3137 fprintf(fp, "%s\n\n", rules.keyAt(i).string());
3138 }
3139 fclose(fp);
3140
3141 return err;
3142}
3143
3144// Loops through the string paths and writes them to the file pointer
3145// Each file path is written on its own line with a terminating backslash.
3146status_t writePathsToFile(const sp<FilePathStore>& files, FILE* fp)
3147{
3148 status_t deps = -1;
3149 for (size_t file_i = 0; file_i < files->size(); ++file_i) {
3150 // Add the full file path to the dependency file
3151 fprintf(fp, "%s \\\n", files->itemAt(file_i).string());
3152 deps++;
3153 }
3154 return deps;
3155}
3156
3157status_t
Andreas Gampe2412f842014-09-30 20:55:57 -07003158writeDependencyPreReqs(Bundle* /* bundle */, const sp<AaptAssets>& assets, FILE* fp, bool includeRaw)
Adam Lesinski282e1812014-01-23 18:17:42 -08003159{
3160 status_t deps = -1;
3161 deps += writePathsToFile(assets->getFullResPaths(), fp);
3162 if (includeRaw) {
3163 deps += writePathsToFile(assets->getFullAssetPaths(), fp);
3164 }
3165 return deps;
3166}