blob: 57d44f2a4ab0412752742315af9b28921e76dbb4 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001//
2// Copyright 2006 The Android Open Source Project
3//
4// Build resource files from raw assets.
5//
6#include "Main.h"
7#include "AaptAssets.h"
8#include "StringPool.h"
9#include "XMLNode.h"
10#include "ResourceTable.h"
11#include "Images.h"
12
Josiah Gaskin8a39da82011-06-06 17:00:35 -070013#include "CrunchCache.h"
14#include "FileFinder.h"
15#include "CacheUpdater.h"
16
Mathias Agopian1f5762e2013-05-06 20:20:34 -070017#include "WorkQueue.h"
Jeff Brownc0f73662012-03-16 22:17:41 -070018
Raphaelf51125d2011-10-27 17:01:31 -070019#if HAVE_PRINTF_ZD
20# define ZD "%zd"
21# define ZD_TYPE ssize_t
22#else
23# define ZD "%ld"
24# define ZD_TYPE long
25#endif
26
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027#define NOISY(x) // x
28
Jeff Brownc0f73662012-03-16 22:17:41 -070029// Number of threads to use for preprocessing images.
30static const size_t MAX_THREADS = 4;
31
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032// ==========================================================================
33// ==========================================================================
34// ==========================================================================
35
36class PackageInfo
37{
38public:
39 PackageInfo()
40 {
41 }
42 ~PackageInfo()
43 {
44 }
45
46 status_t parsePackage(const sp<AaptGroup>& grp);
47};
48
49// ==========================================================================
50// ==========================================================================
51// ==========================================================================
52
53static String8 parseResourceName(const String8& leaf)
54{
55 const char* firstDot = strchr(leaf.string(), '.');
56 const char* str = leaf.string();
57
58 if (firstDot) {
59 return String8(str, firstDot-str);
60 } else {
61 return String8(str);
62 }
63}
64
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065ResourceTypeSet::ResourceTypeSet()
66 :RefBase(),
67 KeyedVector<String8,sp<AaptGroup> >()
68{
69}
70
Josiah Gaskin9bf34ca2011-06-14 13:57:09 -070071FilePathStore::FilePathStore()
72 :RefBase(),
73 Vector<String8>()
74{
75}
76
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077class ResourceDirIterator
78{
79public:
80 ResourceDirIterator(const sp<ResourceTypeSet>& set, const String8& resType)
81 : mResType(resType), mSet(set), mSetPos(0), mGroupPos(0)
82 {
83 }
84
85 inline const sp<AaptGroup>& getGroup() const { return mGroup; }
86 inline const sp<AaptFile>& getFile() const { return mFile; }
87
88 inline const String8& getBaseName() const { return mBaseName; }
89 inline const String8& getLeafName() const { return mLeafName; }
90 inline String8 getPath() const { return mPath; }
91 inline const ResTable_config& getParams() const { return mParams; }
92
93 enum {
94 EOD = 1
95 };
96
97 ssize_t next()
98 {
99 while (true) {
100 sp<AaptGroup> group;
101 sp<AaptFile> file;
102
103 // Try to get next file in this current group.
104 if (mGroup != NULL && mGroupPos < mGroup->getFiles().size()) {
105 group = mGroup;
106 file = group->getFiles().valueAt(mGroupPos++);
107
108 // Try to get the next group/file in this directory
109 } else if (mSetPos < mSet->size()) {
110 mGroup = group = mSet->valueAt(mSetPos++);
111 if (group->getFiles().size() < 1) {
112 continue;
113 }
114 file = group->getFiles().valueAt(0);
115 mGroupPos = 1;
116
117 // All done!
118 } else {
119 return EOD;
120 }
121
122 mFile = file;
123
124 String8 leaf(group->getLeaf());
125 mLeafName = String8(leaf);
126 mParams = file->getGroupEntry().toParams();
Tobias Haamel27b28b32010-02-09 23:09:17 +0100127 NOISY(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",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 group->getPath().string(), mParams.mcc, mParams.mnc,
129 mParams.language[0] ? mParams.language[0] : '-',
130 mParams.language[1] ? mParams.language[1] : '-',
131 mParams.country[0] ? mParams.country[0] : '-',
132 mParams.country[1] ? mParams.country[1] : '-',
Tobias Haamel27b28b32010-02-09 23:09:17 +0100133 mParams.orientation, mParams.uiMode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134 mParams.density, mParams.touchscreen, mParams.keyboard,
135 mParams.inputFlags, mParams.navigation));
136 mPath = "res";
137 mPath.appendPath(file->getGroupEntry().toDirName(mResType));
138 mPath.appendPath(leaf);
139 mBaseName = parseResourceName(leaf);
140 if (mBaseName == "") {
141 fprintf(stderr, "Error: malformed resource filename %s\n",
142 file->getPrintableSource().string());
143 return UNKNOWN_ERROR;
144 }
145
146 NOISY(printf("file name=%s\n", mBaseName.string()));
147
148 return NO_ERROR;
149 }
150 }
151
152private:
153 String8 mResType;
154
155 const sp<ResourceTypeSet> mSet;
156 size_t mSetPos;
157
158 sp<AaptGroup> mGroup;
159 size_t mGroupPos;
160
161 sp<AaptFile> mFile;
162 String8 mBaseName;
163 String8 mLeafName;
164 String8 mPath;
165 ResTable_config mParams;
166};
167
168// ==========================================================================
169// ==========================================================================
170// ==========================================================================
171
172bool isValidResourceType(const String8& type)
173{
Dianne Hackbornf31161a2011-01-04 21:02:48 -0800174 return type == "anim" || type == "animator" || type == "interpolator"
Chet Haased82c8ac2013-08-26 14:20:16 -0700175 || type == "transition"
Dianne Hackbornf31161a2011-01-04 21:02:48 -0800176 || type == "drawable" || type == "layout"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 || type == "values" || type == "xml" || type == "raw"
Kenny Root7c710232010-11-22 22:28:37 -0800178 || type == "color" || type == "menu" || type == "mipmap";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179}
180
181static sp<AaptFile> getResourceFile(const sp<AaptAssets>& assets, bool makeIfNecessary=true)
182{
183 sp<AaptGroup> group = assets->getFiles().valueFor(String8("resources.arsc"));
184 sp<AaptFile> file;
185 if (group != NULL) {
186 file = group->getFiles().valueFor(AaptGroupEntry());
187 if (file != NULL) {
188 return file;
189 }
190 }
191
192 if (!makeIfNecessary) {
193 return NULL;
194 }
195 return assets->addFile(String8("resources.arsc"), AaptGroupEntry(), String8(),
196 NULL, String8());
197}
198
Kenny Rootb5ef7ee2009-12-10 13:52:53 -0800199static status_t parsePackage(Bundle* bundle, const sp<AaptAssets>& assets,
200 const sp<AaptGroup>& grp)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201{
202 if (grp->getFiles().size() != 1) {
Marco Nelissendd931862009-07-13 13:02:33 -0700203 fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 grp->getFiles().valueAt(0)->getPrintableSource().string());
205 }
206
207 sp<AaptFile> file = grp->getFiles().valueAt(0);
208
209 ResXMLTree block;
210 status_t err = parseXMLResource(file, &block);
211 if (err != NO_ERROR) {
212 return err;
213 }
214 //printXMLBlock(&block);
215
216 ResXMLTree::event_code_t code;
217 while ((code=block.next()) != ResXMLTree::START_TAG
218 && code != ResXMLTree::END_DOCUMENT
219 && code != ResXMLTree::BAD_DOCUMENT) {
220 }
221
222 size_t len;
223 if (code != ResXMLTree::START_TAG) {
224 fprintf(stderr, "%s:%d: No start tag found\n",
225 file->getPrintableSource().string(), block.getLineNumber());
226 return UNKNOWN_ERROR;
227 }
228 if (strcmp16(block.getElementName(&len), String16("manifest").string()) != 0) {
229 fprintf(stderr, "%s:%d: Invalid start tag %s, expected <manifest>\n",
230 file->getPrintableSource().string(), block.getLineNumber(),
231 String8(block.getElementName(&len)).string());
232 return UNKNOWN_ERROR;
233 }
234
235 ssize_t nameIndex = block.indexOfAttribute(NULL, "package");
236 if (nameIndex < 0) {
237 fprintf(stderr, "%s:%d: <manifest> does not have package attribute.\n",
238 file->getPrintableSource().string(), block.getLineNumber());
239 return UNKNOWN_ERROR;
240 }
241
242 assets->setPackage(String8(block.getAttributeStringValue(nameIndex, &len)));
243
Kenny Rootb5ef7ee2009-12-10 13:52:53 -0800244 String16 uses_sdk16("uses-sdk");
245 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
246 && code != ResXMLTree::BAD_DOCUMENT) {
247 if (code == ResXMLTree::START_TAG) {
248 if (strcmp16(block.getElementName(&len), uses_sdk16.string()) == 0) {
Kenny Root5a8ec762010-02-24 20:00:03 -0800249 ssize_t minSdkIndex = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE,
Kenny Rootb5ef7ee2009-12-10 13:52:53 -0800250 "minSdkVersion");
251 if (minSdkIndex >= 0) {
Kenny Root7ff20e32010-02-24 23:49:59 -0800252 const uint16_t* minSdk16 = block.getAttributeStringValue(minSdkIndex, &len);
253 const char* minSdk8 = strdup(String8(minSdk16).string());
Kenny Root1741cd42010-03-18 12:12:11 -0700254 bundle->setManifestMinSdkVersion(minSdk8);
Kenny Rootb5ef7ee2009-12-10 13:52:53 -0800255 }
256 }
257 }
258 }
259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 return NO_ERROR;
261}
262
263// ==========================================================================
264// ==========================================================================
265// ==========================================================================
266
267static status_t makeFileResources(Bundle* bundle, const sp<AaptAssets>& assets,
268 ResourceTable* table,
269 const sp<ResourceTypeSet>& set,
270 const char* resType)
271{
272 String8 type8(resType);
273 String16 type16(resType);
274
275 bool hasErrors = false;
276
277 ResourceDirIterator it(set, String8(resType));
278 ssize_t res;
279 while ((res=it.next()) == NO_ERROR) {
280 if (bundle->getVerbose()) {
281 printf(" (new resource id %s from %s)\n",
282 it.getBaseName().string(), it.getFile()->getPrintableSource().string());
283 }
284 String16 baseName(it.getBaseName());
285 const char16_t* str = baseName.string();
286 const char16_t* const end = str + baseName.size();
287 while (str < end) {
288 if (!((*str >= 'a' && *str <= 'z')
289 || (*str >= '0' && *str <= '9')
290 || *str == '_' || *str == '.')) {
291 fprintf(stderr, "%s: Invalid file name: must contain only [a-z0-9_.]\n",
292 it.getPath().string());
293 hasErrors = true;
294 }
295 str++;
296 }
297 String8 resPath = it.getPath();
298 resPath.convertToResPath();
299 table->addEntry(SourcePos(it.getPath(), 0), String16(assets->getPackage()),
300 type16,
301 baseName,
302 String16(resPath),
303 NULL,
304 &it.getParams());
305 assets->addResource(it.getLeafName(), resPath, it.getFile(), type8);
306 }
307
308 return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
309}
310
Jeff Brownc0f73662012-03-16 22:17:41 -0700311class PreProcessImageWorkUnit : public WorkQueue::WorkUnit {
312public:
313 PreProcessImageWorkUnit(const Bundle* bundle, const sp<AaptAssets>& assets,
314 const sp<AaptFile>& file, volatile bool* hasErrors) :
315 mBundle(bundle), mAssets(assets), mFile(file), mHasErrors(hasErrors) {
316 }
317
318 virtual bool run() {
319 status_t status = preProcessImage(mBundle, mAssets, mFile, NULL);
320 if (status) {
321 *mHasErrors = true;
322 }
323 return true; // continue even if there are errors
324 }
325
326private:
327 const Bundle* mBundle;
328 sp<AaptAssets> mAssets;
329 sp<AaptFile> mFile;
330 volatile bool* mHasErrors;
331};
332
333static status_t preProcessImages(const Bundle* bundle, const sp<AaptAssets>& assets,
Kenny Root7c710232010-11-22 22:28:37 -0800334 const sp<ResourceTypeSet>& set, const char* type)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335{
Jeff Brownc0f73662012-03-16 22:17:41 -0700336 volatile bool hasErrors = false;
Josiah Gaskin8a39da82011-06-06 17:00:35 -0700337 ssize_t res = NO_ERROR;
338 if (bundle->getUseCrunchCache() == false) {
Jeff Brownc0f73662012-03-16 22:17:41 -0700339 WorkQueue wq(MAX_THREADS, false);
Xavier Ducrohet84be06e2011-07-20 17:45:11 -0700340 ResourceDirIterator it(set, String8(type));
Josiah Gaskin8a39da82011-06-06 17:00:35 -0700341 while ((res=it.next()) == NO_ERROR) {
Jeff Brownc0f73662012-03-16 22:17:41 -0700342 PreProcessImageWorkUnit* w = new PreProcessImageWorkUnit(
343 bundle, assets, it.getFile(), &hasErrors);
344 status_t status = wq.schedule(w);
345 if (status) {
346 fprintf(stderr, "preProcessImages failed: schedule() returned %d\n", status);
Josiah Gaskin8a39da82011-06-06 17:00:35 -0700347 hasErrors = true;
Jeff Brownc0f73662012-03-16 22:17:41 -0700348 delete w;
349 break;
Josiah Gaskin8a39da82011-06-06 17:00:35 -0700350 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800351 }
Jeff Brownc0f73662012-03-16 22:17:41 -0700352 status_t status = wq.finish();
353 if (status) {
354 fprintf(stderr, "preProcessImages failed: finish() returned %d\n", status);
355 hasErrors = true;
356 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 }
Daniel Sandler3547f852009-08-14 13:47:30 -0700358 return (hasErrors || (res < NO_ERROR)) ? UNKNOWN_ERROR : NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800359}
360
361status_t postProcessImages(const sp<AaptAssets>& assets,
362 ResourceTable* table,
363 const sp<ResourceTypeSet>& set)
364{
365 ResourceDirIterator it(set, String8("drawable"));
Daniel Sandler3547f852009-08-14 13:47:30 -0700366 bool hasErrors = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367 ssize_t res;
368 while ((res=it.next()) == NO_ERROR) {
369 res = postProcessImage(assets, table, it.getFile());
Daniel Sandler3547f852009-08-14 13:47:30 -0700370 if (res < NO_ERROR) {
371 hasErrors = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800372 }
373 }
374
Daniel Sandler3547f852009-08-14 13:47:30 -0700375 return (hasErrors || (res < NO_ERROR)) ? UNKNOWN_ERROR : NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376}
377
378static void collect_files(const sp<AaptDir>& dir,
379 KeyedVector<String8, sp<ResourceTypeSet> >* resources)
380{
381 const DefaultKeyedVector<String8, sp<AaptGroup> >& groups = dir->getFiles();
382 int N = groups.size();
383 for (int i=0; i<N; i++) {
384 String8 leafName = groups.keyAt(i);
385 const sp<AaptGroup>& group = groups.valueAt(i);
386
387 const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files
388 = group->getFiles();
389
390 if (files.size() == 0) {
391 continue;
392 }
393
394 String8 resType = files.valueAt(0)->getResourceType();
395
396 ssize_t index = resources->indexOfKey(resType);
397
398 if (index < 0) {
399 sp<ResourceTypeSet> set = new ResourceTypeSet();
Dianne Hackborne6b68032011-10-13 16:26:02 -0700400 NOISY(printf("Creating new resource type set for leaf %s with group %s (%p)\n",
401 leafName.string(), group->getPath().string(), group.get()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800402 set->add(leafName, group);
403 resources->add(resType, set);
404 } else {
405 sp<ResourceTypeSet> set = resources->valueAt(index);
406 index = set->indexOfKey(leafName);
407 if (index < 0) {
Dianne Hackborne6b68032011-10-13 16:26:02 -0700408 NOISY(printf("Adding to resource type set for leaf %s group %s (%p)\n",
409 leafName.string(), group->getPath().string(), group.get()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800410 set->add(leafName, group);
411 } else {
412 sp<AaptGroup> existingGroup = set->valueAt(index);
Dianne Hackborne6b68032011-10-13 16:26:02 -0700413 NOISY(printf("Extending to resource type set for leaf %s group %s (%p)\n",
414 leafName.string(), group->getPath().string(), group.get()));
415 for (size_t j=0; j<files.size(); j++) {
416 NOISY(printf("Adding file %s in group %s resType %s\n",
417 files.valueAt(j)->getSourceFile().string(),
418 files.keyAt(j).toDirName(String8()).string(),
419 resType.string()));
420 status_t err = existingGroup->addFile(files.valueAt(j));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800421 }
422 }
423 }
424 }
425}
426
427static void collect_files(const sp<AaptAssets>& ass,
428 KeyedVector<String8, sp<ResourceTypeSet> >* resources)
429{
430 const Vector<sp<AaptDir> >& dirs = ass->resDirs();
431 int N = dirs.size();
432
433 for (int i=0; i<N; i++) {
434 sp<AaptDir> d = dirs.itemAt(i);
Dianne Hackborne6b68032011-10-13 16:26:02 -0700435 NOISY(printf("Collecting dir #%d %p: %s, leaf %s\n", i, d.get(), d->getPath().string(),
436 d->getLeaf().string()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437 collect_files(d, resources);
438
439 // don't try to include the res dir
Dianne Hackborne6b68032011-10-13 16:26:02 -0700440 NOISY(printf("Removing dir leaf %s\n", d->getLeaf().string()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800441 ass->removeDir(d->getLeaf());
442 }
443}
444
445enum {
446 ATTR_OKAY = -1,
447 ATTR_NOT_FOUND = -2,
448 ATTR_LEADING_SPACES = -3,
449 ATTR_TRAILING_SPACES = -4
450};
Dianne Hackborncf244ad2010-03-09 15:00:30 -0800451static int validateAttr(const String8& path, const ResTable& table,
452 const ResXMLParser& parser,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453 const char* ns, const char* attr, const char* validChars, bool required)
454{
455 size_t len;
456
457 ssize_t index = parser.indexOfAttribute(ns, attr);
458 const uint16_t* str;
Dianne Hackborncf244ad2010-03-09 15:00:30 -0800459 Res_value value;
460 if (index >= 0 && parser.getAttributeValue(index, &value) >= 0) {
461 const ResStringPool* pool = &parser.getStrings();
462 if (value.dataType == Res_value::TYPE_REFERENCE) {
463 uint32_t specFlags = 0;
464 int strIdx;
465 if ((strIdx=table.resolveReference(&value, 0x10000000, NULL, &specFlags)) < 0) {
466 fprintf(stderr, "%s:%d: Tag <%s> attribute %s references unknown resid 0x%08x.\n",
467 path.string(), parser.getLineNumber(),
468 String8(parser.getElementName(&len)).string(), attr,
469 value.data);
470 return ATTR_NOT_FOUND;
471 }
Elliott Hughesc367d482013-10-29 13:12:55 -0700472
Dianne Hackborncf244ad2010-03-09 15:00:30 -0800473 pool = table.getTableStringBlock(strIdx);
474 #if 0
475 if (pool != NULL) {
476 str = pool->stringAt(value.data, &len);
477 }
478 printf("***** RES ATTR: %s specFlags=0x%x strIdx=%d: %s\n", attr,
479 specFlags, strIdx, str != NULL ? String8(str).string() : "???");
480 #endif
481 if ((specFlags&~ResTable_typeSpec::SPEC_PUBLIC) != 0 && false) {
482 fprintf(stderr, "%s:%d: Tag <%s> attribute %s varies by configurations 0x%x.\n",
483 path.string(), parser.getLineNumber(),
484 String8(parser.getElementName(&len)).string(), attr,
485 specFlags);
486 return ATTR_NOT_FOUND;
487 }
488 }
489 if (value.dataType == Res_value::TYPE_STRING) {
490 if (pool == NULL) {
491 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has no string block.\n",
492 path.string(), parser.getLineNumber(),
493 String8(parser.getElementName(&len)).string(), attr);
494 return ATTR_NOT_FOUND;
495 }
496 if ((str=pool->stringAt(value.data, &len)) == NULL) {
497 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has corrupt string value.\n",
498 path.string(), parser.getLineNumber(),
499 String8(parser.getElementName(&len)).string(), attr);
500 return ATTR_NOT_FOUND;
501 }
502 } else {
503 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has invalid type %d.\n",
504 path.string(), parser.getLineNumber(),
505 String8(parser.getElementName(&len)).string(), attr,
506 value.dataType);
507 return ATTR_NOT_FOUND;
508 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800509 if (validChars) {
510 for (size_t i=0; i<len; i++) {
511 uint16_t c = str[i];
512 const char* p = validChars;
513 bool okay = false;
514 while (*p) {
515 if (c == *p) {
516 okay = true;
517 break;
518 }
519 p++;
520 }
521 if (!okay) {
522 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has invalid character '%c'.\n",
523 path.string(), parser.getLineNumber(),
524 String8(parser.getElementName(&len)).string(), attr, (char)str[i]);
525 return (int)i;
526 }
527 }
528 }
529 if (*str == ' ') {
530 fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not start with a space.\n",
531 path.string(), parser.getLineNumber(),
532 String8(parser.getElementName(&len)).string(), attr);
533 return ATTR_LEADING_SPACES;
534 }
535 if (str[len-1] == ' ') {
536 fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not end with a space.\n",
537 path.string(), parser.getLineNumber(),
538 String8(parser.getElementName(&len)).string(), attr);
539 return ATTR_TRAILING_SPACES;
540 }
541 return ATTR_OKAY;
542 }
543 if (required) {
544 fprintf(stderr, "%s:%d: Tag <%s> missing required attribute %s.\n",
545 path.string(), parser.getLineNumber(),
546 String8(parser.getElementName(&len)).string(), attr);
547 return ATTR_NOT_FOUND;
548 }
549 return ATTR_OKAY;
550}
551
552static void checkForIds(const String8& path, ResXMLParser& parser)
553{
554 ResXMLTree::event_code_t code;
555 while ((code=parser.next()) != ResXMLTree::END_DOCUMENT
556 && code > ResXMLTree::BAD_DOCUMENT) {
557 if (code == ResXMLTree::START_TAG) {
558 ssize_t index = parser.indexOfAttribute(NULL, "id");
559 if (index >= 0) {
Marco Nelissendd931862009-07-13 13:02:33 -0700560 fprintf(stderr, "%s:%d: warning: found plain 'id' attribute; did you mean the new 'android:id' name?\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800561 path.string(), parser.getLineNumber());
562 }
563 }
564 }
565}
566
Robert Greenwalt832528f2009-08-31 14:48:20 -0700567static bool applyFileOverlay(Bundle *bundle,
568 const sp<AaptAssets>& assets,
Xavier Ducrohet83f4c092010-03-04 15:21:59 -0800569 sp<ResourceTypeSet> *baseSet,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800570 const char *resType)
571{
Robert Greenwalt832528f2009-08-31 14:48:20 -0700572 if (bundle->getVerbose()) {
573 printf("applyFileOverlay for %s\n", resType);
574 }
575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 // Replace any base level files in this category with any found from the overlay
577 // Also add any found only in the overlay.
578 sp<AaptAssets> overlay = assets->getOverlay();
579 String8 resTypeString(resType);
Robert Greenwaltfa5c7e12009-06-05 18:53:26 -0700580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581 // work through the linked list of overlays
582 while (overlay.get()) {
583 KeyedVector<String8, sp<ResourceTypeSet> >* overlayRes = overlay->getResources();
584
585 // get the overlay resources of the requested type
586 ssize_t index = overlayRes->indexOfKey(resTypeString);
587 if (index >= 0) {
588 sp<ResourceTypeSet> overlaySet = overlayRes->valueAt(index);
589
590 // for each of the resources, check for a match in the previously built
591 // non-overlay "baseset".
592 size_t overlayCount = overlaySet->size();
593 for (size_t overlayIndex=0; overlayIndex<overlayCount; overlayIndex++) {
Robert Greenwalt832528f2009-08-31 14:48:20 -0700594 if (bundle->getVerbose()) {
595 printf("trying overlaySet Key=%s\n",overlaySet->keyAt(overlayIndex).string());
596 }
Xavier Ducrohet83f4c092010-03-04 15:21:59 -0800597 size_t baseIndex = UNKNOWN_ERROR;
598 if (baseSet->get() != NULL) {
599 baseIndex = (*baseSet)->indexOfKey(overlaySet->keyAt(overlayIndex));
600 }
Robert Greenwaltfa5c7e12009-06-05 18:53:26 -0700601 if (baseIndex < UNKNOWN_ERROR) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800602 // look for same flavor. For a given file (strings.xml, for example)
603 // there may be a locale specific or other flavors - we want to match
604 // the same flavor.
605 sp<AaptGroup> overlayGroup = overlaySet->valueAt(overlayIndex);
Xavier Ducrohet83f4c092010-03-04 15:21:59 -0800606 sp<AaptGroup> baseGroup = (*baseSet)->valueAt(baseIndex);
Robert Greenwalt832528f2009-08-31 14:48:20 -0700607
608 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > overlayFiles =
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800609 overlayGroup->getFiles();
Robert Greenwalt832528f2009-08-31 14:48:20 -0700610 if (bundle->getVerbose()) {
611 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > baseFiles =
612 baseGroup->getFiles();
613 for (size_t i=0; i < baseFiles.size(); i++) {
Raphaelf51125d2011-10-27 17:01:31 -0700614 printf("baseFile " ZD " has flavor %s\n", (ZD_TYPE) i,
Robert Greenwalt832528f2009-08-31 14:48:20 -0700615 baseFiles.keyAt(i).toString().string());
616 }
617 for (size_t i=0; i < overlayFiles.size(); i++) {
Raphaelf51125d2011-10-27 17:01:31 -0700618 printf("overlayFile " ZD " has flavor %s\n", (ZD_TYPE) i,
Robert Greenwalt832528f2009-08-31 14:48:20 -0700619 overlayFiles.keyAt(i).toString().string());
620 }
621 }
622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623 size_t overlayGroupSize = overlayFiles.size();
Robert Greenwalt832528f2009-08-31 14:48:20 -0700624 for (size_t overlayGroupIndex = 0;
625 overlayGroupIndex<overlayGroupSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 overlayGroupIndex++) {
Robert Greenwalt832528f2009-08-31 14:48:20 -0700627 size_t baseFileIndex =
628 baseGroup->getFiles().indexOfKey(overlayFiles.
629 keyAt(overlayGroupIndex));
Dianne Hackborne6b68032011-10-13 16:26:02 -0700630 if (baseFileIndex < UNKNOWN_ERROR) {
Robert Greenwalt832528f2009-08-31 14:48:20 -0700631 if (bundle->getVerbose()) {
Raphaelf51125d2011-10-27 17:01:31 -0700632 printf("found a match (" ZD ") for overlay file %s, for flavor %s\n",
633 (ZD_TYPE) baseFileIndex,
Robert Greenwalt832528f2009-08-31 14:48:20 -0700634 overlayGroup->getLeaf().string(),
635 overlayFiles.keyAt(overlayGroupIndex).toString().string());
636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800637 baseGroup->removeFile(baseFileIndex);
638 } else {
639 // didn't find a match fall through and add it..
Dianne Hackborne6b68032011-10-13 16:26:02 -0700640 if (true || bundle->getVerbose()) {
641 printf("nothing matches overlay file %s, for flavor %s\n",
642 overlayGroup->getLeaf().string(),
643 overlayFiles.keyAt(overlayGroupIndex).toString().string());
644 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 }
646 baseGroup->addFile(overlayFiles.valueAt(overlayGroupIndex));
Dianne Hackborn64551b22009-08-15 00:00:33 -0700647 assets->addGroupEntry(overlayFiles.keyAt(overlayGroupIndex));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 }
649 } else {
Xavier Ducrohet83f4c092010-03-04 15:21:59 -0800650 if (baseSet->get() == NULL) {
651 *baseSet = new ResourceTypeSet();
652 assets->getResources()->add(String8(resType), *baseSet);
653 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 // this group doesn't exist (a file that's only in the overlay)
Xavier Ducrohet83f4c092010-03-04 15:21:59 -0800655 (*baseSet)->add(overlaySet->keyAt(overlayIndex),
Dianne Hackborn58c27a02009-08-13 13:36:00 -0700656 overlaySet->valueAt(overlayIndex));
Dianne Hackborn64551b22009-08-15 00:00:33 -0700657 // make sure all flavors are defined in the resources.
658 sp<AaptGroup> overlayGroup = overlaySet->valueAt(overlayIndex);
Robert Greenwalt832528f2009-08-31 14:48:20 -0700659 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > overlayFiles =
Dianne Hackborn64551b22009-08-15 00:00:33 -0700660 overlayGroup->getFiles();
661 size_t overlayGroupSize = overlayFiles.size();
Robert Greenwalt832528f2009-08-31 14:48:20 -0700662 for (size_t overlayGroupIndex = 0;
663 overlayGroupIndex<overlayGroupSize;
Dianne Hackborn64551b22009-08-15 00:00:33 -0700664 overlayGroupIndex++) {
665 assets->addGroupEntry(overlayFiles.keyAt(overlayGroupIndex));
666 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 }
668 }
669 // this overlay didn't have resources for this type
670 }
671 // try next overlay
672 overlay = overlay->getOverlay();
673 }
Robert Greenwaltfa5c7e12009-06-05 18:53:26 -0700674 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675}
676
Xavier Ducrohet7714a242012-09-05 17:49:21 -0700677/*
678 * Inserts an attribute in a given node, only if the attribute does not
679 * exist.
680 * If errorOnFailedInsert is true, and the attribute already exists, returns false.
681 * Returns true otherwise, even if the attribute already exists.
682 */
683bool addTagAttribute(const sp<XMLNode>& node, const char* ns8,
684 const char* attr8, const char* value, bool errorOnFailedInsert)
Dianne Hackborn62da8462009-05-13 15:06:13 -0700685{
686 if (value == NULL) {
Xavier Ducrohet7714a242012-09-05 17:49:21 -0700687 return true;
Dianne Hackborn62da8462009-05-13 15:06:13 -0700688 }
Xavier Ducrohet7714a242012-09-05 17:49:21 -0700689
Dianne Hackborn62da8462009-05-13 15:06:13 -0700690 const String16 ns(ns8);
691 const String16 attr(attr8);
Xavier Ducrohet7714a242012-09-05 17:49:21 -0700692
Dianne Hackborn62da8462009-05-13 15:06:13 -0700693 if (node->getAttribute(ns, attr) != NULL) {
Xavier Ducrohet7714a242012-09-05 17:49:21 -0700694 if (errorOnFailedInsert) {
695 fprintf(stderr, "Error: AndroidManifest.xml already defines %s (in %s);"
696 " cannot insert new value %s.\n",
697 String8(attr).string(), String8(ns).string(), value);
698 return false;
699 }
700
Kenny Rooted983092010-03-18 14:14:49 -0700701 fprintf(stderr, "Warning: AndroidManifest.xml already defines %s (in %s);"
702 " using existing value in manifest.\n",
Dianne Hackborn62da8462009-05-13 15:06:13 -0700703 String8(attr).string(), String8(ns).string());
Xavier Ducrohet7714a242012-09-05 17:49:21 -0700704
705 // don't stop the build.
706 return true;
Dianne Hackborn62da8462009-05-13 15:06:13 -0700707 }
Elliott Hughesc367d482013-10-29 13:12:55 -0700708
Dianne Hackborn62da8462009-05-13 15:06:13 -0700709 node->addAttribute(ns, attr, String16(value));
Xavier Ducrohet7714a242012-09-05 17:49:21 -0700710 return true;
Dianne Hackborn62da8462009-05-13 15:06:13 -0700711}
712
Dianne Hackbornef05e072010-03-01 17:43:39 -0800713static void fullyQualifyClassName(const String8& package, sp<XMLNode> node,
714 const String16& attrName) {
Jeff Hamilton2fee0ed2010-01-06 15:46:38 -0600715 XMLNode::attribute_entry* attr = node->editAttribute(
Dianne Hackbornef05e072010-03-01 17:43:39 -0800716 String16("http://schemas.android.com/apk/res/android"), attrName);
Jeff Hamilton2fee0ed2010-01-06 15:46:38 -0600717 if (attr != NULL) {
718 String8 name(attr->string);
719
720 // asdf --> package.asdf
721 // .asdf .a.b --> package.asdf package.a.b
722 // asdf.adsf --> asdf.asdf
723 String8 className;
724 const char* p = name.string();
725 const char* q = strchr(p, '.');
726 if (p == q) {
727 className += package;
728 className += name;
729 } else if (q == NULL) {
730 className += package;
731 className += ".";
732 className += name;
733 } else {
734 className += name;
735 }
736 NOISY(printf("Qualifying class '%s' to '%s'", name.string(), className.string()));
737 attr->string.setTo(String16(className));
738 }
739}
740
Dianne Hackborn62da8462009-05-13 15:06:13 -0700741status_t massageManifest(Bundle* bundle, sp<XMLNode> root)
742{
743 root = root->searchElement(String16(), String16("manifest"));
744 if (root == NULL) {
745 fprintf(stderr, "No <manifest> tag.\n");
746 return UNKNOWN_ERROR;
747 }
Xavier Ducrohet7714a242012-09-05 17:49:21 -0700748
749 bool errorOnFailedInsert = bundle->getErrorOnFailedInsert();
750
751 if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionCode",
752 bundle->getVersionCode(), errorOnFailedInsert)) {
753 return UNKNOWN_ERROR;
754 }
755 if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionName",
756 bundle->getVersionName(), errorOnFailedInsert)) {
757 return UNKNOWN_ERROR;
758 }
Elliott Hughesc367d482013-10-29 13:12:55 -0700759
Dianne Hackborn62da8462009-05-13 15:06:13 -0700760 if (bundle->getMinSdkVersion() != NULL
761 || bundle->getTargetSdkVersion() != NULL
762 || bundle->getMaxSdkVersion() != NULL) {
763 sp<XMLNode> vers = root->getChildElement(String16(), String16("uses-sdk"));
764 if (vers == NULL) {
765 vers = XMLNode::newElement(root->getFilename(), String16(), String16("uses-sdk"));
766 root->insertChildAt(vers, 0);
767 }
Elliott Hughesc367d482013-10-29 13:12:55 -0700768
Xavier Ducrohet7714a242012-09-05 17:49:21 -0700769 if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "minSdkVersion",
770 bundle->getMinSdkVersion(), errorOnFailedInsert)) {
771 return UNKNOWN_ERROR;
772 }
773 if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "targetSdkVersion",
774 bundle->getTargetSdkVersion(), errorOnFailedInsert)) {
775 return UNKNOWN_ERROR;
776 }
777 if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "maxSdkVersion",
778 bundle->getMaxSdkVersion(), errorOnFailedInsert)) {
779 return UNKNOWN_ERROR;
780 }
Dianne Hackborn62da8462009-05-13 15:06:13 -0700781 }
Jeff Hamilton2fee0ed2010-01-06 15:46:38 -0600782
Xavier Ducrohet6487b092010-08-31 10:45:31 -0700783 if (bundle->getDebugMode()) {
784 sp<XMLNode> application = root->getChildElement(String16(), String16("application"));
785 if (application != NULL) {
Xavier Ducrohet7714a242012-09-05 17:49:21 -0700786 if (!addTagAttribute(application, RESOURCES_ANDROID_NAMESPACE, "debuggable", "true",
787 errorOnFailedInsert)) {
788 return UNKNOWN_ERROR;
789 }
Xavier Ducrohet6487b092010-08-31 10:45:31 -0700790 }
791 }
792
Jeff Hamilton2fee0ed2010-01-06 15:46:38 -0600793 // Deal with manifest package name overrides
794 const char* manifestPackageNameOverride = bundle->getManifestPackageNameOverride();
795 if (manifestPackageNameOverride != NULL) {
796 // Update the actual package name
797 XMLNode::attribute_entry* attr = root->editAttribute(String16(), String16("package"));
798 if (attr == NULL) {
799 fprintf(stderr, "package name is required with --rename-manifest-package.\n");
800 return UNKNOWN_ERROR;
801 }
802 String8 origPackage(attr->string);
803 attr->string.setTo(String16(manifestPackageNameOverride));
804 NOISY(printf("Overriding package '%s' to be '%s'\n", origPackage.string(), manifestPackageNameOverride));
805
806 // Make class names fully qualified
807 sp<XMLNode> application = root->getChildElement(String16(), String16("application"));
808 if (application != NULL) {
Dianne Hackbornef05e072010-03-01 17:43:39 -0800809 fullyQualifyClassName(origPackage, application, String16("name"));
Dianne Hackbornb0381ef2010-03-03 13:36:35 -0800810 fullyQualifyClassName(origPackage, application, String16("backupAgent"));
Jeff Hamilton2fee0ed2010-01-06 15:46:38 -0600811
812 Vector<sp<XMLNode> >& children = const_cast<Vector<sp<XMLNode> >&>(application->getChildren());
813 for (size_t i = 0; i < children.size(); i++) {
814 sp<XMLNode> child = children.editItemAt(i);
815 String8 tag(child->getElementName());
816 if (tag == "activity" || tag == "service" || tag == "receiver" || tag == "provider") {
Dianne Hackbornef05e072010-03-01 17:43:39 -0800817 fullyQualifyClassName(origPackage, child, String16("name"));
818 } else if (tag == "activity-alias") {
819 fullyQualifyClassName(origPackage, child, String16("name"));
820 fullyQualifyClassName(origPackage, child, String16("targetActivity"));
Jeff Hamilton2fee0ed2010-01-06 15:46:38 -0600821 }
822 }
823 }
824 }
825
Dianne Hackbornef05e072010-03-01 17:43:39 -0800826 // Deal with manifest package name overrides
827 const char* instrumentationPackageNameOverride = bundle->getInstrumentationPackageNameOverride();
828 if (instrumentationPackageNameOverride != NULL) {
829 // Fix up instrumentation targets.
830 Vector<sp<XMLNode> >& children = const_cast<Vector<sp<XMLNode> >&>(root->getChildren());
831 for (size_t i = 0; i < children.size(); i++) {
832 sp<XMLNode> child = children.editItemAt(i);
833 String8 tag(child->getElementName());
834 if (tag == "instrumentation") {
835 XMLNode::attribute_entry* attr = child->editAttribute(
836 String16("http://schemas.android.com/apk/res/android"), String16("targetPackage"));
837 if (attr != NULL) {
838 attr->string.setTo(String16(instrumentationPackageNameOverride));
839 }
840 }
841 }
842 }
Elliott Hughesc367d482013-10-29 13:12:55 -0700843
Dianne Hackborn62da8462009-05-13 15:06:13 -0700844 return NO_ERROR;
845}
846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847#define ASSIGN_IT(n) \
848 do { \
849 ssize_t index = resources->indexOfKey(String8(#n)); \
850 if (index >= 0) { \
851 n ## s = resources->valueAt(index); \
852 } \
853 } while (0)
854
Josiah Gaskin8a39da82011-06-06 17:00:35 -0700855status_t updatePreProcessedCache(Bundle* bundle)
856{
857 #if BENCHMARK
858 fprintf(stdout, "BENCHMARK: Starting PNG PreProcessing \n");
859 long startPNGTime = clock();
860 #endif /* BENCHMARK */
861
862 String8 source(bundle->getResourceSourceDirs()[0]);
863 String8 dest(bundle->getCrunchedOutputDir());
864
865 FileFinder* ff = new SystemFileFinder();
866 CrunchCache cc(source,dest,ff);
867
868 CacheUpdater* cu = new SystemCacheUpdater(bundle);
869 size_t numFiles = cc.crunch(cu);
870
871 if (bundle->getVerbose())
872 fprintf(stdout, "Crunched %d PNG files to update cache\n", (int)numFiles);
873
874 delete ff;
875 delete cu;
876
877 #if BENCHMARK
878 fprintf(stdout, "BENCHMARK: End PNG PreProcessing. Time Elapsed: %f ms \n"
879 ,(clock() - startPNGTime)/1000.0);
880 #endif /* BENCHMARK */
881 return 0;
882}
883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884status_t buildResources(Bundle* bundle, const sp<AaptAssets>& assets)
885{
886 // First, look for a package file to parse. This is required to
887 // be able to generate the resource information.
888 sp<AaptGroup> androidManifestFile =
889 assets->getFiles().valueFor(String8("AndroidManifest.xml"));
890 if (androidManifestFile == NULL) {
891 fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n");
892 return UNKNOWN_ERROR;
893 }
894
Kenny Rootb5ef7ee2009-12-10 13:52:53 -0800895 status_t err = parsePackage(bundle, assets, androidManifestFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 if (err != NO_ERROR) {
897 return err;
898 }
899
900 NOISY(printf("Creating resources for package %s\n",
901 assets->getPackage().string()));
902
903 ResourceTable table(bundle, String16(assets->getPackage()));
904 err = table.addIncludedResources(bundle, assets);
905 if (err != NO_ERROR) {
906 return err;
907 }
908
909 NOISY(printf("Found %d included resource packages\n", (int)table.size()));
910
Kenny Root19138462009-12-04 09:38:48 -0800911 // Standard flags for compiled XML and optional UTF-8 encoding
912 int xmlFlags = XML_COMPILE_STANDARD_RESOURCE;
Kenny Root1741cd42010-03-18 12:12:11 -0700913
914 /* Only enable UTF-8 if the caller of aapt didn't specifically
915 * request UTF-16 encoding and the parameters of this package
916 * allow UTF-8 to be used.
917 */
Dianne Hackborn6c997a92012-01-31 11:27:43 -0800918 if (!bundle->getUTF16StringsOption()) {
Kenny Root19138462009-12-04 09:38:48 -0800919 xmlFlags |= XML_COMPILE_UTF8;
920 }
921
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 // --------------------------------------------------------------
923 // First, gather all resource information.
924 // --------------------------------------------------------------
925
926 // resType -> leafName -> group
Elliott Hughesc367d482013-10-29 13:12:55 -0700927 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 new KeyedVector<String8, sp<ResourceTypeSet> >;
929 collect_files(assets, resources);
930
931 sp<ResourceTypeSet> drawables;
932 sp<ResourceTypeSet> layouts;
933 sp<ResourceTypeSet> anims;
Dianne Hackbornf31161a2011-01-04 21:02:48 -0800934 sp<ResourceTypeSet> animators;
935 sp<ResourceTypeSet> interpolators;
Chet Haasefaebd8f2012-05-18 14:17:57 -0700936 sp<ResourceTypeSet> transitions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 sp<ResourceTypeSet> xmls;
938 sp<ResourceTypeSet> raws;
939 sp<ResourceTypeSet> colors;
940 sp<ResourceTypeSet> menus;
Kenny Root7c710232010-11-22 22:28:37 -0800941 sp<ResourceTypeSet> mipmaps;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942
943 ASSIGN_IT(drawable);
944 ASSIGN_IT(layout);
945 ASSIGN_IT(anim);
Dianne Hackbornf31161a2011-01-04 21:02:48 -0800946 ASSIGN_IT(animator);
947 ASSIGN_IT(interpolator);
Chet Haasefaebd8f2012-05-18 14:17:57 -0700948 ASSIGN_IT(transition);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 ASSIGN_IT(xml);
950 ASSIGN_IT(raw);
951 ASSIGN_IT(color);
952 ASSIGN_IT(menu);
Kenny Root7c710232010-11-22 22:28:37 -0800953 ASSIGN_IT(mipmap);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954
955 assets->setResources(resources);
956 // now go through any resource overlays and collect their files
957 sp<AaptAssets> current = assets->getOverlay();
958 while(current.get()) {
Elliott Hughesc367d482013-10-29 13:12:55 -0700959 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 new KeyedVector<String8, sp<ResourceTypeSet> >;
961 current->setResources(resources);
962 collect_files(current, resources);
963 current = current->getOverlay();
964 }
965 // apply the overlay files to the base set
Xavier Ducrohet83f4c092010-03-04 15:21:59 -0800966 if (!applyFileOverlay(bundle, assets, &drawables, "drawable") ||
967 !applyFileOverlay(bundle, assets, &layouts, "layout") ||
968 !applyFileOverlay(bundle, assets, &anims, "anim") ||
Dianne Hackbornf31161a2011-01-04 21:02:48 -0800969 !applyFileOverlay(bundle, assets, &animators, "animator") ||
970 !applyFileOverlay(bundle, assets, &interpolators, "interpolator") ||
Chet Haasefaebd8f2012-05-18 14:17:57 -0700971 !applyFileOverlay(bundle, assets, &transitions, "transition") ||
Xavier Ducrohet83f4c092010-03-04 15:21:59 -0800972 !applyFileOverlay(bundle, assets, &xmls, "xml") ||
973 !applyFileOverlay(bundle, assets, &raws, "raw") ||
974 !applyFileOverlay(bundle, assets, &colors, "color") ||
Kenny Root7c710232010-11-22 22:28:37 -0800975 !applyFileOverlay(bundle, assets, &menus, "menu") ||
976 !applyFileOverlay(bundle, assets, &mipmaps, "mipmap")) {
Robert Greenwaltfa5c7e12009-06-05 18:53:26 -0700977 return UNKNOWN_ERROR;
978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979
980 bool hasErrors = false;
981
982 if (drawables != NULL) {
Anthony Newnam578a57f2010-09-01 12:06:04 -0500983 if (bundle->getOutputAPKFile() != NULL) {
Kenny Root7c710232010-11-22 22:28:37 -0800984 err = preProcessImages(bundle, assets, drawables, "drawable");
Anthony Newnam578a57f2010-09-01 12:06:04 -0500985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 if (err == NO_ERROR) {
987 err = makeFileResources(bundle, assets, &table, drawables, "drawable");
988 if (err != NO_ERROR) {
989 hasErrors = true;
990 }
991 } else {
992 hasErrors = true;
993 }
994 }
995
Kenny Root7c710232010-11-22 22:28:37 -0800996 if (mipmaps != NULL) {
997 if (bundle->getOutputAPKFile() != NULL) {
998 err = preProcessImages(bundle, assets, mipmaps, "mipmap");
999 }
1000 if (err == NO_ERROR) {
1001 err = makeFileResources(bundle, assets, &table, mipmaps, "mipmap");
1002 if (err != NO_ERROR) {
1003 hasErrors = true;
1004 }
1005 } else {
1006 hasErrors = true;
1007 }
1008 }
1009
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 if (layouts != NULL) {
1011 err = makeFileResources(bundle, assets, &table, layouts, "layout");
1012 if (err != NO_ERROR) {
1013 hasErrors = true;
1014 }
1015 }
1016
1017 if (anims != NULL) {
1018 err = makeFileResources(bundle, assets, &table, anims, "anim");
1019 if (err != NO_ERROR) {
1020 hasErrors = true;
1021 }
1022 }
1023
Dianne Hackbornf31161a2011-01-04 21:02:48 -08001024 if (animators != NULL) {
1025 err = makeFileResources(bundle, assets, &table, animators, "animator");
1026 if (err != NO_ERROR) {
1027 hasErrors = true;
1028 }
1029 }
1030
Chet Haasefaebd8f2012-05-18 14:17:57 -07001031 if (transitions != NULL) {
1032 err = makeFileResources(bundle, assets, &table, transitions, "transition");
1033 if (err != NO_ERROR) {
1034 hasErrors = true;
1035 }
1036 }
1037
Dianne Hackbornf31161a2011-01-04 21:02:48 -08001038 if (interpolators != NULL) {
1039 err = makeFileResources(bundle, assets, &table, interpolators, "interpolator");
1040 if (err != NO_ERROR) {
1041 hasErrors = true;
1042 }
1043 }
1044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 if (xmls != NULL) {
1046 err = makeFileResources(bundle, assets, &table, xmls, "xml");
1047 if (err != NO_ERROR) {
1048 hasErrors = true;
1049 }
1050 }
1051
1052 if (raws != NULL) {
1053 err = makeFileResources(bundle, assets, &table, raws, "raw");
1054 if (err != NO_ERROR) {
1055 hasErrors = true;
1056 }
1057 }
1058
1059 // compile resources
1060 current = assets;
1061 while(current.get()) {
Elliott Hughesc367d482013-10-29 13:12:55 -07001062 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 current->getResources();
1064
1065 ssize_t index = resources->indexOfKey(String8("values"));
1066 if (index >= 0) {
1067 ResourceDirIterator it(resources->valueAt(index), String8("values"));
1068 ssize_t res;
1069 while ((res=it.next()) == NO_ERROR) {
1070 sp<AaptFile> file = it.getFile();
Elliott Hughesc367d482013-10-29 13:12:55 -07001071 res = compileResourceFile(bundle, assets, file, it.getParams(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 (current!=assets), &table);
1073 if (res != NO_ERROR) {
1074 hasErrors = true;
1075 }
1076 }
1077 }
1078 current = current->getOverlay();
1079 }
1080
1081 if (colors != NULL) {
1082 err = makeFileResources(bundle, assets, &table, colors, "color");
1083 if (err != NO_ERROR) {
1084 hasErrors = true;
1085 }
1086 }
1087
1088 if (menus != NULL) {
1089 err = makeFileResources(bundle, assets, &table, menus, "menu");
1090 if (err != NO_ERROR) {
1091 hasErrors = true;
1092 }
1093 }
1094
1095 // --------------------------------------------------------------------
1096 // Assignment of resource IDs and initial generation of resource table.
1097 // --------------------------------------------------------------------
1098
1099 if (table.hasResources()) {
1100 sp<AaptFile> resFile(getResourceFile(assets));
1101 if (resFile == NULL) {
1102 fprintf(stderr, "Error: unable to generate entry for resource data\n");
1103 return UNKNOWN_ERROR;
1104 }
1105
1106 err = table.assignResourceIds();
1107 if (err < NO_ERROR) {
1108 return err;
1109 }
1110 }
1111
1112 // --------------------------------------------------------------
1113 // Finally, we can now we can compile XML files, which may reference
1114 // resources.
1115 // --------------------------------------------------------------
1116
1117 if (layouts != NULL) {
1118 ResourceDirIterator it(layouts, String8("layout"));
1119 while ((err=it.next()) == NO_ERROR) {
1120 String8 src = it.getFile()->getPrintableSource();
Kenny Root19138462009-12-04 09:38:48 -08001121 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 if (err == NO_ERROR) {
1123 ResXMLTree block;
1124 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
1125 checkForIds(src, block);
1126 } else {
1127 hasErrors = true;
1128 }
1129 }
1130
1131 if (err < NO_ERROR) {
1132 hasErrors = true;
1133 }
1134 err = NO_ERROR;
1135 }
1136
1137 if (anims != NULL) {
1138 ResourceDirIterator it(anims, String8("anim"));
1139 while ((err=it.next()) == NO_ERROR) {
Kenny Root19138462009-12-04 09:38:48 -08001140 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 if (err != NO_ERROR) {
1142 hasErrors = true;
1143 }
1144 }
1145
1146 if (err < NO_ERROR) {
1147 hasErrors = true;
1148 }
1149 err = NO_ERROR;
1150 }
1151
Dianne Hackbornf31161a2011-01-04 21:02:48 -08001152 if (animators != NULL) {
1153 ResourceDirIterator it(animators, String8("animator"));
1154 while ((err=it.next()) == NO_ERROR) {
1155 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
1156 if (err != NO_ERROR) {
1157 hasErrors = true;
1158 }
1159 }
1160
1161 if (err < NO_ERROR) {
1162 hasErrors = true;
1163 }
1164 err = NO_ERROR;
1165 }
1166
1167 if (interpolators != NULL) {
1168 ResourceDirIterator it(interpolators, String8("interpolator"));
1169 while ((err=it.next()) == NO_ERROR) {
1170 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
1171 if (err != NO_ERROR) {
1172 hasErrors = true;
1173 }
1174 }
1175
1176 if (err < NO_ERROR) {
1177 hasErrors = true;
1178 }
1179 err = NO_ERROR;
1180 }
1181
Chet Haasefaebd8f2012-05-18 14:17:57 -07001182 if (transitions != NULL) {
1183 ResourceDirIterator it(transitions, String8("transition"));
1184 while ((err=it.next()) == NO_ERROR) {
1185 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
1186 if (err != NO_ERROR) {
1187 hasErrors = true;
1188 }
1189 }
1190
1191 if (err < NO_ERROR) {
1192 hasErrors = true;
1193 }
1194 err = NO_ERROR;
1195 }
1196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 if (xmls != NULL) {
1198 ResourceDirIterator it(xmls, String8("xml"));
1199 while ((err=it.next()) == NO_ERROR) {
Kenny Root19138462009-12-04 09:38:48 -08001200 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001201 if (err != NO_ERROR) {
1202 hasErrors = true;
1203 }
1204 }
1205
1206 if (err < NO_ERROR) {
1207 hasErrors = true;
1208 }
1209 err = NO_ERROR;
1210 }
1211
1212 if (drawables != NULL) {
1213 err = postProcessImages(assets, &table, drawables);
1214 if (err != NO_ERROR) {
1215 hasErrors = true;
1216 }
1217 }
1218
1219 if (colors != NULL) {
1220 ResourceDirIterator it(colors, String8("color"));
1221 while ((err=it.next()) == NO_ERROR) {
Kenny Root19138462009-12-04 09:38:48 -08001222 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 if (err != NO_ERROR) {
1224 hasErrors = true;
1225 }
1226 }
1227
1228 if (err < NO_ERROR) {
1229 hasErrors = true;
1230 }
1231 err = NO_ERROR;
1232 }
1233
1234 if (menus != NULL) {
1235 ResourceDirIterator it(menus, String8("menu"));
1236 while ((err=it.next()) == NO_ERROR) {
1237 String8 src = it.getFile()->getPrintableSource();
Kenny Root19138462009-12-04 09:38:48 -08001238 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 if (err != NO_ERROR) {
1240 hasErrors = true;
1241 }
1242 ResXMLTree block;
1243 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
1244 checkForIds(src, block);
1245 }
1246
1247 if (err < NO_ERROR) {
1248 hasErrors = true;
1249 }
1250 err = NO_ERROR;
1251 }
1252
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001253 if (table.validateLocalizations()) {
1254 hasErrors = true;
1255 }
Elliott Hughesc367d482013-10-29 13:12:55 -07001256
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001257 if (hasErrors) {
1258 return UNKNOWN_ERROR;
1259 }
1260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 const sp<AaptFile> manifestFile(androidManifestFile->getFiles().valueAt(0));
1262 String8 manifestPath(manifestFile->getPrintableSource());
1263
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001264 // Generate final compiled manifest file.
1265 manifestFile->clearData();
1266 sp<XMLNode> manifestTree = XMLNode::parse(manifestFile);
1267 if (manifestTree == NULL) {
1268 return UNKNOWN_ERROR;
1269 }
1270 err = massageManifest(bundle, manifestTree);
1271 if (err < NO_ERROR) {
1272 return err;
1273 }
1274 err = compileXmlFile(assets, manifestTree, manifestFile, &table);
1275 if (err < NO_ERROR) {
1276 return err;
1277 }
1278
1279 //block.restart();
1280 //printXMLBlock(&block);
1281
1282 // --------------------------------------------------------------
1283 // Generate the final resource table.
1284 // Re-flatten because we may have added new resource IDs
1285 // --------------------------------------------------------------
1286
1287 ResTable finalResTable;
1288 sp<AaptFile> resFile;
Elliott Hughesc367d482013-10-29 13:12:55 -07001289
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001290 if (table.hasResources()) {
1291 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1292 err = table.addSymbols(symbols);
1293 if (err < NO_ERROR) {
1294 return err;
1295 }
1296
1297 resFile = getResourceFile(assets);
1298 if (resFile == NULL) {
1299 fprintf(stderr, "Error: unable to generate entry for resource data\n");
1300 return UNKNOWN_ERROR;
1301 }
1302
1303 err = table.flatten(bundle, resFile);
1304 if (err < NO_ERROR) {
1305 return err;
1306 }
1307
1308 if (bundle->getPublicOutputFile()) {
1309 FILE* fp = fopen(bundle->getPublicOutputFile(), "w+");
1310 if (fp == NULL) {
1311 fprintf(stderr, "ERROR: Unable to open public definitions output file %s: %s\n",
1312 (const char*)bundle->getPublicOutputFile(), strerror(errno));
1313 return UNKNOWN_ERROR;
1314 }
1315 if (bundle->getVerbose()) {
1316 printf(" Writing public definitions to %s.\n", bundle->getPublicOutputFile());
1317 }
1318 table.writePublicDefinitions(String16(assets->getPackage()), fp);
1319 fclose(fp);
1320 }
Elliott Hughesc367d482013-10-29 13:12:55 -07001321
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001322 // Read resources back in,
Narayan Kamath7c4887f2014-01-27 17:32:37 +00001323 finalResTable.add(resFile->getData(), resFile->getSize());
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001324#if 0
1325 NOISY(
1326 printf("Generated resources:\n");
1327 finalResTable.print();
1328 )
1329#endif
1330 }
Elliott Hughesc367d482013-10-29 13:12:55 -07001331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 // Perform a basic validation of the manifest file. This time we
1333 // parse it with the comments intact, so that we can use them to
1334 // generate java docs... so we are not going to write this one
1335 // back out to the final manifest data.
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001336 sp<AaptFile> outManifestFile = new AaptFile(manifestFile->getSourceFile(),
1337 manifestFile->getGroupEntry(),
1338 manifestFile->getResourceType());
1339 err = compileXmlFile(assets, manifestFile,
1340 outManifestFile, &table,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 XML_COMPILE_ASSIGN_ATTRIBUTE_IDS
1342 | XML_COMPILE_STRIP_WHITESPACE | XML_COMPILE_STRIP_RAW_VALUES);
1343 if (err < NO_ERROR) {
1344 return err;
1345 }
1346 ResXMLTree block;
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001347 block.setTo(outManifestFile->getData(), outManifestFile->getSize(), true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 String16 manifest16("manifest");
1349 String16 permission16("permission");
1350 String16 permission_group16("permission-group");
1351 String16 uses_permission16("uses-permission");
1352 String16 instrumentation16("instrumentation");
1353 String16 application16("application");
1354 String16 provider16("provider");
1355 String16 service16("service");
1356 String16 receiver16("receiver");
1357 String16 activity16("activity");
1358 String16 action16("action");
1359 String16 category16("category");
1360 String16 data16("scheme");
1361 const char* packageIdentChars = "abcdefghijklmnopqrstuvwxyz"
1362 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789";
1363 const char* packageIdentCharsWithTheStupid = "abcdefghijklmnopqrstuvwxyz"
1364 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
1365 const char* classIdentChars = "abcdefghijklmnopqrstuvwxyz"
1366 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789$";
1367 const char* processIdentChars = "abcdefghijklmnopqrstuvwxyz"
1368 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:";
1369 const char* authoritiesIdentChars = "abcdefghijklmnopqrstuvwxyz"
1370 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-:;";
1371 const char* typeIdentChars = "abcdefghijklmnopqrstuvwxyz"
1372 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:-/*+";
1373 const char* schemeIdentChars = "abcdefghijklmnopqrstuvwxyz"
1374 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
1375 ResXMLTree::event_code_t code;
1376 sp<AaptSymbols> permissionSymbols;
1377 sp<AaptSymbols> permissionGroupSymbols;
1378 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1379 && code > ResXMLTree::BAD_DOCUMENT) {
1380 if (code == ResXMLTree::START_TAG) {
1381 size_t len;
1382 if (block.getElementNamespace(&len) != NULL) {
1383 continue;
1384 }
1385 if (strcmp16(block.getElementName(&len), manifest16.string()) == 0) {
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001386 if (validateAttr(manifestPath, finalResTable, block, NULL, "package",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 packageIdentChars, true) != ATTR_OKAY) {
1388 hasErrors = true;
1389 }
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001390 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1391 "sharedUserId", packageIdentChars, false) != ATTR_OKAY) {
1392 hasErrors = true;
1393 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394 } else if (strcmp16(block.getElementName(&len), permission16.string()) == 0
1395 || strcmp16(block.getElementName(&len), permission_group16.string()) == 0) {
1396 const bool isGroup = strcmp16(block.getElementName(&len),
1397 permission_group16.string()) == 0;
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001398 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1399 "name", isGroup ? packageIdentCharsWithTheStupid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 : packageIdentChars, true) != ATTR_OKAY) {
1401 hasErrors = true;
1402 }
1403 SourcePos srcPos(manifestPath, block.getLineNumber());
1404 sp<AaptSymbols> syms;
1405 if (!isGroup) {
1406 syms = permissionSymbols;
1407 if (syms == NULL) {
1408 sp<AaptSymbols> symbols =
1409 assets->getSymbolsFor(String8("Manifest"));
1410 syms = permissionSymbols = symbols->addNestedSymbol(
1411 String8("permission"), srcPos);
1412 }
1413 } else {
1414 syms = permissionGroupSymbols;
1415 if (syms == NULL) {
1416 sp<AaptSymbols> symbols =
1417 assets->getSymbolsFor(String8("Manifest"));
1418 syms = permissionGroupSymbols = symbols->addNestedSymbol(
1419 String8("permission_group"), srcPos);
1420 }
1421 }
1422 size_t len;
1423 ssize_t index = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "name");
1424 const uint16_t* id = block.getAttributeStringValue(index, &len);
1425 if (id == NULL) {
Elliott Hughesc367d482013-10-29 13:12:55 -07001426 fprintf(stderr, "%s:%d: missing name attribute in element <%s>.\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 manifestPath.string(), block.getLineNumber(),
1428 String8(block.getElementName(&len)).string());
1429 hasErrors = true;
1430 break;
1431 }
1432 String8 idStr(id);
1433 char* p = idStr.lockBuffer(idStr.size());
1434 char* e = p + idStr.size();
1435 bool begins_with_digit = true; // init to true so an empty string fails
1436 while (e > p) {
1437 e--;
1438 if (*e >= '0' && *e <= '9') {
1439 begins_with_digit = true;
1440 continue;
1441 }
1442 if ((*e >= 'a' && *e <= 'z') ||
1443 (*e >= 'A' && *e <= 'Z') ||
1444 (*e == '_')) {
1445 begins_with_digit = false;
1446 continue;
1447 }
1448 if (isGroup && (*e == '-')) {
1449 *e = '_';
1450 begins_with_digit = false;
1451 continue;
1452 }
1453 e++;
1454 break;
1455 }
1456 idStr.unlockBuffer();
1457 // verify that we stopped because we hit a period or
1458 // the beginning of the string, and that the
1459 // identifier didn't begin with a digit.
1460 if (begins_with_digit || (e != p && *(e-1) != '.')) {
1461 fprintf(stderr,
1462 "%s:%d: Permission name <%s> is not a valid Java symbol\n",
1463 manifestPath.string(), block.getLineNumber(), idStr.string());
1464 hasErrors = true;
1465 }
1466 syms->addStringSymbol(String8(e), idStr, srcPos);
1467 const uint16_t* cmt = block.getComment(&len);
1468 if (cmt != NULL && *cmt != 0) {
1469 //printf("Comment of %s: %s\n", String8(e).string(),
1470 // String8(cmt).string());
1471 syms->appendComment(String8(e), String16(cmt), srcPos);
1472 } else {
1473 //printf("No comment for %s\n", String8(e).string());
1474 }
1475 syms->makeSymbolPublic(String8(e), srcPos);
1476 } else if (strcmp16(block.getElementName(&len), uses_permission16.string()) == 0) {
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001477 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1478 "name", packageIdentChars, true) != ATTR_OKAY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 hasErrors = true;
1480 }
1481 } else if (strcmp16(block.getElementName(&len), instrumentation16.string()) == 0) {
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001482 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1483 "name", classIdentChars, true) != ATTR_OKAY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 hasErrors = true;
1485 }
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001486 if (validateAttr(manifestPath, finalResTable, block,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 RESOURCES_ANDROID_NAMESPACE, "targetPackage",
1488 packageIdentChars, true) != ATTR_OKAY) {
1489 hasErrors = true;
1490 }
1491 } else if (strcmp16(block.getElementName(&len), application16.string()) == 0) {
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001492 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1493 "name", classIdentChars, false) != ATTR_OKAY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 hasErrors = true;
1495 }
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001496 if (validateAttr(manifestPath, finalResTable, block,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 RESOURCES_ANDROID_NAMESPACE, "permission",
1498 packageIdentChars, false) != ATTR_OKAY) {
1499 hasErrors = true;
1500 }
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001501 if (validateAttr(manifestPath, finalResTable, block,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 RESOURCES_ANDROID_NAMESPACE, "process",
1503 processIdentChars, false) != ATTR_OKAY) {
1504 hasErrors = true;
1505 }
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001506 if (validateAttr(manifestPath, finalResTable, block,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
1508 processIdentChars, false) != ATTR_OKAY) {
1509 hasErrors = true;
1510 }
1511 } else if (strcmp16(block.getElementName(&len), provider16.string()) == 0) {
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001512 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1513 "name", classIdentChars, true) != ATTR_OKAY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 hasErrors = true;
1515 }
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001516 if (validateAttr(manifestPath, finalResTable, block,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 RESOURCES_ANDROID_NAMESPACE, "authorities",
1518 authoritiesIdentChars, true) != ATTR_OKAY) {
1519 hasErrors = true;
1520 }
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001521 if (validateAttr(manifestPath, finalResTable, block,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 RESOURCES_ANDROID_NAMESPACE, "permission",
1523 packageIdentChars, false) != ATTR_OKAY) {
1524 hasErrors = true;
1525 }
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001526 if (validateAttr(manifestPath, finalResTable, block,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 RESOURCES_ANDROID_NAMESPACE, "process",
1528 processIdentChars, false) != ATTR_OKAY) {
1529 hasErrors = true;
1530 }
1531 } else if (strcmp16(block.getElementName(&len), service16.string()) == 0
1532 || strcmp16(block.getElementName(&len), receiver16.string()) == 0
1533 || strcmp16(block.getElementName(&len), activity16.string()) == 0) {
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001534 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1535 "name", classIdentChars, true) != ATTR_OKAY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 hasErrors = true;
1537 }
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001538 if (validateAttr(manifestPath, finalResTable, block,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 RESOURCES_ANDROID_NAMESPACE, "permission",
1540 packageIdentChars, false) != ATTR_OKAY) {
1541 hasErrors = true;
1542 }
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001543 if (validateAttr(manifestPath, finalResTable, block,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 RESOURCES_ANDROID_NAMESPACE, "process",
1545 processIdentChars, false) != ATTR_OKAY) {
1546 hasErrors = true;
1547 }
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001548 if (validateAttr(manifestPath, finalResTable, block,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
1550 processIdentChars, false) != ATTR_OKAY) {
1551 hasErrors = true;
1552 }
1553 } else if (strcmp16(block.getElementName(&len), action16.string()) == 0
1554 || strcmp16(block.getElementName(&len), category16.string()) == 0) {
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001555 if (validateAttr(manifestPath, finalResTable, block,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 RESOURCES_ANDROID_NAMESPACE, "name",
1557 packageIdentChars, true) != ATTR_OKAY) {
1558 hasErrors = true;
1559 }
1560 } else if (strcmp16(block.getElementName(&len), data16.string()) == 0) {
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001561 if (validateAttr(manifestPath, finalResTable, block,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 RESOURCES_ANDROID_NAMESPACE, "mimeType",
1563 typeIdentChars, true) != ATTR_OKAY) {
1564 hasErrors = true;
1565 }
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001566 if (validateAttr(manifestPath, finalResTable, block,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 RESOURCES_ANDROID_NAMESPACE, "scheme",
1568 schemeIdentChars, true) != ATTR_OKAY) {
1569 hasErrors = true;
1570 }
1571 }
1572 }
1573 }
1574
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001575 if (resFile != NULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 // These resources are now considered to be a part of the included
1577 // resources, for others to reference.
1578 err = assets->addIncludedResources(resFile);
1579 if (err < NO_ERROR) {
1580 fprintf(stderr, "ERROR: Unable to parse generated resources, aborting.\n");
1581 return err;
1582 }
1583 }
Elliott Hughesc367d482013-10-29 13:12:55 -07001584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 return err;
1586}
1587
1588static const char* getIndentSpace(int indent)
1589{
1590static const char whitespace[] =
1591" ";
1592
1593 return whitespace + sizeof(whitespace) - 1 - indent*4;
1594}
1595
Jeff Browncaf7b0a2013-04-25 21:24:44 -07001596static String8 flattenSymbol(const String8& symbol) {
1597 String8 result(symbol);
1598 ssize_t first;
1599 if ((first = symbol.find(":", 0)) >= 0
1600 || (first = symbol.find(".", 0)) >= 0) {
1601 size_t size = symbol.size();
1602 char* buf = result.lockBuffer(size);
1603 for (size_t i = first; i < size; i++) {
1604 if (buf[i] == ':' || buf[i] == '.') {
1605 buf[i] = '_';
1606 }
1607 }
1608 result.unlockBuffer(size);
1609 }
1610 return result;
1611}
1612
1613static String8 getSymbolPackage(const String8& symbol, const sp<AaptAssets>& assets, bool pub) {
1614 ssize_t colon = symbol.find(":", 0);
1615 if (colon >= 0) {
1616 return String8(symbol.string(), colon);
1617 }
1618 return pub ? assets->getPackage() : assets->getSymbolsPrivatePackage();
1619}
1620
1621static String8 getSymbolName(const String8& symbol) {
1622 ssize_t colon = symbol.find(":", 0);
1623 if (colon >= 0) {
1624 return String8(symbol.string() + colon + 1);
1625 }
1626 return symbol;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627}
1628
1629static String16 getAttributeComment(const sp<AaptAssets>& assets,
1630 const String8& name,
1631 String16* outTypeComment = NULL)
1632{
1633 sp<AaptSymbols> asym = assets->getSymbolsFor(String8("R"));
1634 if (asym != NULL) {
1635 //printf("Got R symbols!\n");
1636 asym = asym->getNestedSymbols().valueFor(String8("attr"));
1637 if (asym != NULL) {
1638 //printf("Got attrs symbols! comment %s=%s\n",
1639 // name.string(), String8(asym->getComment(name)).string());
1640 if (outTypeComment != NULL) {
1641 *outTypeComment = asym->getTypeComment(name);
1642 }
1643 return asym->getComment(name);
1644 }
1645 }
1646 return String16();
1647}
1648
1649static status_t writeLayoutClasses(
1650 FILE* fp, const sp<AaptAssets>& assets,
Xavier Ducroheta068eed2013-04-13 09:48:01 -07001651 const sp<AaptSymbols>& symbols, int indent, bool includePrivate)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652{
1653 const char* indentStr = getIndentSpace(indent);
1654 if (!includePrivate) {
1655 fprintf(fp, "%s/** @doconly */\n", indentStr);
1656 }
1657 fprintf(fp, "%spublic static final class styleable {\n", indentStr);
1658 indent++;
1659
1660 String16 attr16("attr");
1661 String16 package16(assets->getPackage());
1662
1663 indentStr = getIndentSpace(indent);
1664 bool hasErrors = false;
1665
1666 size_t i;
1667 size_t N = symbols->getNestedSymbols().size();
1668 for (i=0; i<N; i++) {
1669 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
Jeff Browncaf7b0a2013-04-25 21:24:44 -07001670 String8 realClassName(symbols->getNestedSymbols().keyAt(i));
1671 String8 nclassName(flattenSymbol(realClassName));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672
1673 SortedVector<uint32_t> idents;
1674 Vector<uint32_t> origOrder;
1675 Vector<bool> publicFlags;
1676
1677 size_t a;
1678 size_t NA = nsymbols->getSymbols().size();
1679 for (a=0; a<NA; a++) {
1680 const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a));
1681 int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32
1682 ? sym.int32Val : 0;
1683 bool isPublic = true;
1684 if (code == 0) {
1685 String16 name16(sym.name);
1686 uint32_t typeSpecFlags;
1687 code = assets->getIncludedResources().identifierForName(
1688 name16.string(), name16.size(),
1689 attr16.string(), attr16.size(),
1690 package16.string(), package16.size(), &typeSpecFlags);
1691 if (code == 0) {
1692 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
1693 nclassName.string(), sym.name.string());
1694 hasErrors = true;
1695 }
1696 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
1697 }
1698 idents.add(code);
1699 origOrder.add(code);
1700 publicFlags.add(isPublic);
1701 }
1702
1703 NA = idents.size();
1704
Dianne Hackborn4a51c202009-08-21 15:14:02 -07001705 bool deprecated = false;
Elliott Hughesc367d482013-10-29 13:12:55 -07001706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 String16 comment = symbols->getComment(realClassName);
1708 fprintf(fp, "%s/** ", indentStr);
1709 if (comment.size() > 0) {
Dianne Hackborn4a51c202009-08-21 15:14:02 -07001710 String8 cmt(comment);
1711 fprintf(fp, "%s\n", cmt.string());
1712 if (strstr(cmt.string(), "@deprecated") != NULL) {
1713 deprecated = true;
1714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 } else {
1716 fprintf(fp, "Attributes that can be used with a %s.\n", nclassName.string());
1717 }
1718 bool hasTable = false;
1719 for (a=0; a<NA; a++) {
1720 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1721 if (pos >= 0) {
1722 if (!hasTable) {
1723 hasTable = true;
1724 fprintf(fp,
1725 "%s <p>Includes the following attributes:</p>\n"
Dirk Dougherty59ad2752009-11-03 15:33:37 -08001726 "%s <table>\n"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 "%s <colgroup align=\"left\" />\n"
1728 "%s <colgroup align=\"left\" />\n"
Dirk Dougherty59ad2752009-11-03 15:33:37 -08001729 "%s <tr><th>Attribute</th><th>Description</th></tr>\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 indentStr,
1731 indentStr,
1732 indentStr,
1733 indentStr,
1734 indentStr);
1735 }
1736 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1737 if (!publicFlags.itemAt(a) && !includePrivate) {
1738 continue;
1739 }
1740 String8 name8(sym.name);
1741 String16 comment(sym.comment);
1742 if (comment.size() <= 0) {
1743 comment = getAttributeComment(assets, name8);
1744 }
1745 if (comment.size() > 0) {
1746 const char16_t* p = comment.string();
1747 while (*p != 0 && *p != '.') {
1748 if (*p == '{') {
1749 while (*p != 0 && *p != '}') {
1750 p++;
1751 }
1752 } else {
1753 p++;
1754 }
1755 }
1756 if (*p == '.') {
1757 p++;
1758 }
1759 comment = String16(comment.string(), p-comment.string());
1760 }
Dirk Dougherty59ad2752009-11-03 15:33:37 -08001761 fprintf(fp, "%s <tr><td><code>{@link #%s_%s %s:%s}</code></td><td>%s</td></tr>\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 indentStr, nclassName.string(),
Jeff Browncaf7b0a2013-04-25 21:24:44 -07001763 flattenSymbol(name8).string(),
1764 getSymbolPackage(name8, assets, true).string(),
1765 getSymbolName(name8).string(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 String8(comment).string());
1767 }
1768 }
1769 if (hasTable) {
1770 fprintf(fp, "%s </table>\n", indentStr);
1771 }
1772 for (a=0; a<NA; a++) {
1773 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1774 if (pos >= 0) {
1775 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1776 if (!publicFlags.itemAt(a) && !includePrivate) {
1777 continue;
1778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 fprintf(fp, "%s @see #%s_%s\n",
1780 indentStr, nclassName.string(),
Jeff Browncaf7b0a2013-04-25 21:24:44 -07001781 flattenSymbol(sym.name).string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 }
1783 }
1784 fprintf(fp, "%s */\n", getIndentSpace(indent));
1785
Dianne Hackborn4a51c202009-08-21 15:14:02 -07001786 if (deprecated) {
1787 fprintf(fp, "%s@Deprecated\n", indentStr);
1788 }
Elliott Hughesc367d482013-10-29 13:12:55 -07001789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 fprintf(fp,
Xavier Ducroheta068eed2013-04-13 09:48:01 -07001791 "%spublic static final int[] %s = {\n"
1792 "%s",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 indentStr, nclassName.string(),
1794 getIndentSpace(indent+1));
1795
1796 for (a=0; a<NA; a++) {
1797 if (a != 0) {
1798 if ((a&3) == 0) {
1799 fprintf(fp, ",\n%s", getIndentSpace(indent+1));
1800 } else {
1801 fprintf(fp, ", ");
1802 }
1803 }
1804 fprintf(fp, "0x%08x", idents[a]);
1805 }
1806
1807 fprintf(fp, "\n%s};\n", indentStr);
1808
1809 for (a=0; a<NA; a++) {
1810 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1811 if (pos >= 0) {
1812 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1813 if (!publicFlags.itemAt(a) && !includePrivate) {
1814 continue;
1815 }
1816 String8 name8(sym.name);
1817 String16 comment(sym.comment);
1818 String16 typeComment;
1819 if (comment.size() <= 0) {
1820 comment = getAttributeComment(assets, name8, &typeComment);
1821 } else {
1822 getAttributeComment(assets, name8, &typeComment);
1823 }
Jeff Browncaf7b0a2013-04-25 21:24:44 -07001824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 uint32_t typeSpecFlags = 0;
1826 String16 name16(sym.name);
1827 assets->getIncludedResources().identifierForName(
1828 name16.string(), name16.size(),
1829 attr16.string(), attr16.size(),
1830 package16.string(), package16.size(), &typeSpecFlags);
1831 //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
1832 // String8(attr16).string(), String8(name16).string(), typeSpecFlags);
1833 const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
Elliott Hughesc367d482013-10-29 13:12:55 -07001834
Dianne Hackborn4a51c202009-08-21 15:14:02 -07001835 bool deprecated = false;
Elliott Hughesc367d482013-10-29 13:12:55 -07001836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 fprintf(fp, "%s/**\n", indentStr);
1838 if (comment.size() > 0) {
Dianne Hackborn4a51c202009-08-21 15:14:02 -07001839 String8 cmt(comment);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 fprintf(fp, "%s <p>\n%s @attr description\n", indentStr, indentStr);
Dianne Hackborn4a51c202009-08-21 15:14:02 -07001841 fprintf(fp, "%s %s\n", indentStr, cmt.string());
1842 if (strstr(cmt.string(), "@deprecated") != NULL) {
1843 deprecated = true;
1844 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 } else {
1846 fprintf(fp,
1847 "%s <p>This symbol is the offset where the {@link %s.R.attr#%s}\n"
1848 "%s attribute's value can be found in the {@link #%s} array.\n",
1849 indentStr,
Jeff Browncaf7b0a2013-04-25 21:24:44 -07001850 getSymbolPackage(name8, assets, pub).string(),
1851 getSymbolName(name8).string(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 indentStr, nclassName.string());
1853 }
1854 if (typeComment.size() > 0) {
Dianne Hackborn4a51c202009-08-21 15:14:02 -07001855 String8 cmt(typeComment);
1856 fprintf(fp, "\n\n%s %s\n", indentStr, cmt.string());
1857 if (strstr(cmt.string(), "@deprecated") != NULL) {
1858 deprecated = true;
1859 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 }
1861 if (comment.size() > 0) {
1862 if (pub) {
1863 fprintf(fp,
Jeff Browncaf7b0a2013-04-25 21:24:44 -07001864 "%s <p>This corresponds to the global attribute\n"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 "%s resource symbol {@link %s.R.attr#%s}.\n",
1866 indentStr, indentStr,
Jeff Browncaf7b0a2013-04-25 21:24:44 -07001867 getSymbolPackage(name8, assets, true).string(),
1868 getSymbolName(name8).string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 } else {
1870 fprintf(fp,
1871 "%s <p>This is a private symbol.\n", indentStr);
1872 }
1873 }
1874 fprintf(fp, "%s @attr name %s:%s\n", indentStr,
Jeff Browncaf7b0a2013-04-25 21:24:44 -07001875 getSymbolPackage(name8, assets, pub).string(),
1876 getSymbolName(name8).string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 fprintf(fp, "%s*/\n", indentStr);
Dianne Hackborn4a51c202009-08-21 15:14:02 -07001878 if (deprecated) {
1879 fprintf(fp, "%s@Deprecated\n", indentStr);
1880 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 fprintf(fp,
Xavier Ducroheta068eed2013-04-13 09:48:01 -07001882 "%spublic static final int %s_%s = %d;\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 indentStr, nclassName.string(),
Jeff Browncaf7b0a2013-04-25 21:24:44 -07001884 flattenSymbol(name8).string(), (int)pos);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 }
1886 }
1887 }
1888
1889 indent--;
1890 fprintf(fp, "%s};\n", getIndentSpace(indent));
1891 return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
1892}
1893
Xavier Ducrohetf5de6502012-09-11 14:45:22 -07001894static status_t writeTextLayoutClasses(
1895 FILE* fp, const sp<AaptAssets>& assets,
1896 const sp<AaptSymbols>& symbols, bool includePrivate)
1897{
1898 String16 attr16("attr");
1899 String16 package16(assets->getPackage());
1900
1901 bool hasErrors = false;
1902
1903 size_t i;
1904 size_t N = symbols->getNestedSymbols().size();
1905 for (i=0; i<N; i++) {
1906 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
Jeff Browncaf7b0a2013-04-25 21:24:44 -07001907 String8 realClassName(symbols->getNestedSymbols().keyAt(i));
1908 String8 nclassName(flattenSymbol(realClassName));
Xavier Ducrohetf5de6502012-09-11 14:45:22 -07001909
1910 SortedVector<uint32_t> idents;
1911 Vector<uint32_t> origOrder;
1912 Vector<bool> publicFlags;
1913
1914 size_t a;
1915 size_t NA = nsymbols->getSymbols().size();
1916 for (a=0; a<NA; a++) {
1917 const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a));
1918 int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32
1919 ? sym.int32Val : 0;
1920 bool isPublic = true;
1921 if (code == 0) {
1922 String16 name16(sym.name);
1923 uint32_t typeSpecFlags;
1924 code = assets->getIncludedResources().identifierForName(
1925 name16.string(), name16.size(),
1926 attr16.string(), attr16.size(),
1927 package16.string(), package16.size(), &typeSpecFlags);
1928 if (code == 0) {
1929 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
1930 nclassName.string(), sym.name.string());
1931 hasErrors = true;
1932 }
1933 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
1934 }
1935 idents.add(code);
1936 origOrder.add(code);
1937 publicFlags.add(isPublic);
1938 }
1939
1940 NA = idents.size();
1941
1942 fprintf(fp, "int[] styleable %s {", nclassName.string());
1943
1944 for (a=0; a<NA; a++) {
1945 if (a != 0) {
1946 fprintf(fp, ",");
1947 }
1948 fprintf(fp, " 0x%08x", idents[a]);
1949 }
1950
1951 fprintf(fp, " }\n");
1952
1953 for (a=0; a<NA; a++) {
1954 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1955 if (pos >= 0) {
1956 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1957 if (!publicFlags.itemAt(a) && !includePrivate) {
1958 continue;
1959 }
1960 String8 name8(sym.name);
1961 String16 comment(sym.comment);
1962 String16 typeComment;
1963 if (comment.size() <= 0) {
1964 comment = getAttributeComment(assets, name8, &typeComment);
1965 } else {
1966 getAttributeComment(assets, name8, &typeComment);
1967 }
Xavier Ducrohetf5de6502012-09-11 14:45:22 -07001968
1969 uint32_t typeSpecFlags = 0;
1970 String16 name16(sym.name);
1971 assets->getIncludedResources().identifierForName(
1972 name16.string(), name16.size(),
1973 attr16.string(), attr16.size(),
1974 package16.string(), package16.size(), &typeSpecFlags);
1975 //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
1976 // String8(attr16).string(), String8(name16).string(), typeSpecFlags);
1977 const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
1978
1979 fprintf(fp,
Xavier Ducrohetd1604742012-09-26 10:11:54 -07001980 "int styleable %s_%s %d\n",
Xavier Ducrohetf5de6502012-09-11 14:45:22 -07001981 nclassName.string(),
Jeff Browncaf7b0a2013-04-25 21:24:44 -07001982 flattenSymbol(name8).string(), (int)pos);
Xavier Ducrohetf5de6502012-09-11 14:45:22 -07001983 }
1984 }
1985 }
1986
1987 return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
1988}
1989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990static status_t writeSymbolClass(
1991 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
Xavier Ducrohetd06c1af2011-02-14 16:58:00 -08001992 const sp<AaptSymbols>& symbols, const String8& className, int indent,
1993 bool nonConstantId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994{
1995 fprintf(fp, "%spublic %sfinal class %s {\n",
1996 getIndentSpace(indent),
1997 indent != 0 ? "static " : "", className.string());
1998 indent++;
1999
2000 size_t i;
2001 status_t err = NO_ERROR;
2002
Xavier Ducrohetd06c1af2011-02-14 16:58:00 -08002003 const char * id_format = nonConstantId ?
2004 "%spublic static int %s=0x%08x;\n" :
2005 "%spublic static final int %s=0x%08x;\n";
2006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 size_t N = symbols->getSymbols().size();
2008 for (i=0; i<N; i++) {
2009 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2010 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
2011 continue;
2012 }
Dianne Hackborn1644c6d72012-02-06 15:33:21 -08002013 if (!assets->isJavaSymbol(sym, includePrivate)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002014 continue;
2015 }
Jeff Browncaf7b0a2013-04-25 21:24:44 -07002016 String8 name8(sym.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 String16 comment(sym.comment);
2018 bool haveComment = false;
Dianne Hackborn4a51c202009-08-21 15:14:02 -07002019 bool deprecated = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 if (comment.size() > 0) {
2021 haveComment = true;
Dianne Hackborn4a51c202009-08-21 15:14:02 -07002022 String8 cmt(comment);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 fprintf(fp,
2024 "%s/** %s\n",
Dianne Hackborn4a51c202009-08-21 15:14:02 -07002025 getIndentSpace(indent), cmt.string());
2026 if (strstr(cmt.string(), "@deprecated") != NULL) {
2027 deprecated = true;
2028 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002029 } else if (sym.isPublic && !includePrivate) {
2030 sym.sourcePos.warning("No comment for public symbol %s:%s/%s",
2031 assets->getPackage().string(), className.string(),
2032 String8(sym.name).string());
2033 }
2034 String16 typeComment(sym.typeComment);
2035 if (typeComment.size() > 0) {
Dianne Hackborn4a51c202009-08-21 15:14:02 -07002036 String8 cmt(typeComment);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002037 if (!haveComment) {
2038 haveComment = true;
2039 fprintf(fp,
Dianne Hackborn4a51c202009-08-21 15:14:02 -07002040 "%s/** %s\n", getIndentSpace(indent), cmt.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 } else {
2042 fprintf(fp,
Dianne Hackborn4a51c202009-08-21 15:14:02 -07002043 "%s %s\n", getIndentSpace(indent), cmt.string());
2044 }
2045 if (strstr(cmt.string(), "@deprecated") != NULL) {
2046 deprecated = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 }
2048 }
2049 if (haveComment) {
2050 fprintf(fp,"%s */\n", getIndentSpace(indent));
2051 }
Dianne Hackborn4a51c202009-08-21 15:14:02 -07002052 if (deprecated) {
2053 fprintf(fp, "%s@Deprecated\n", getIndentSpace(indent));
2054 }
Xavier Ducrohetd06c1af2011-02-14 16:58:00 -08002055 fprintf(fp, id_format,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 getIndentSpace(indent),
Jeff Browncaf7b0a2013-04-25 21:24:44 -07002057 flattenSymbol(name8).string(), (int)sym.int32Val);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 }
2059
2060 for (i=0; i<N; i++) {
2061 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2062 if (sym.typeCode != AaptSymbolEntry::TYPE_STRING) {
2063 continue;
2064 }
Dianne Hackborn1644c6d72012-02-06 15:33:21 -08002065 if (!assets->isJavaSymbol(sym, includePrivate)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 continue;
2067 }
Jeff Browncaf7b0a2013-04-25 21:24:44 -07002068 String8 name8(sym.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002069 String16 comment(sym.comment);
Dianne Hackborn4a51c202009-08-21 15:14:02 -07002070 bool deprecated = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 if (comment.size() > 0) {
Dianne Hackborn4a51c202009-08-21 15:14:02 -07002072 String8 cmt(comment);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002073 fprintf(fp,
2074 "%s/** %s\n"
2075 "%s */\n",
Dianne Hackborn4a51c202009-08-21 15:14:02 -07002076 getIndentSpace(indent), cmt.string(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 getIndentSpace(indent));
Dianne Hackborn4a51c202009-08-21 15:14:02 -07002078 if (strstr(cmt.string(), "@deprecated") != NULL) {
2079 deprecated = true;
2080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 } else if (sym.isPublic && !includePrivate) {
2082 sym.sourcePos.warning("No comment for public symbol %s:%s/%s",
2083 assets->getPackage().string(), className.string(),
2084 String8(sym.name).string());
2085 }
Dianne Hackborn4a51c202009-08-21 15:14:02 -07002086 if (deprecated) {
2087 fprintf(fp, "%s@Deprecated\n", getIndentSpace(indent));
2088 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 fprintf(fp, "%spublic static final String %s=\"%s\";\n",
2090 getIndentSpace(indent),
Jeff Browncaf7b0a2013-04-25 21:24:44 -07002091 flattenSymbol(name8).string(), sym.stringVal.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002092 }
2093
2094 sp<AaptSymbols> styleableSymbols;
2095
2096 N = symbols->getNestedSymbols().size();
2097 for (i=0; i<N; i++) {
2098 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2099 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2100 if (nclassName == "styleable") {
2101 styleableSymbols = nsymbols;
2102 } else {
Xavier Ducrohetd06c1af2011-02-14 16:58:00 -08002103 err = writeSymbolClass(fp, assets, includePrivate, nsymbols, nclassName, indent, nonConstantId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002104 }
2105 if (err != NO_ERROR) {
2106 return err;
2107 }
2108 }
2109
2110 if (styleableSymbols != NULL) {
Xavier Ducroheta068eed2013-04-13 09:48:01 -07002111 err = writeLayoutClasses(fp, assets, styleableSymbols, indent, includePrivate);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002112 if (err != NO_ERROR) {
2113 return err;
2114 }
2115 }
2116
2117 indent--;
2118 fprintf(fp, "%s}\n", getIndentSpace(indent));
2119 return NO_ERROR;
2120}
2121
Xavier Ducrohetf5de6502012-09-11 14:45:22 -07002122static status_t writeTextSymbolClass(
2123 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2124 const sp<AaptSymbols>& symbols, const String8& className)
2125{
2126 size_t i;
2127 status_t err = NO_ERROR;
2128
2129 size_t N = symbols->getSymbols().size();
2130 for (i=0; i<N; i++) {
2131 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2132 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
2133 continue;
2134 }
2135
2136 if (!assets->isJavaSymbol(sym, includePrivate)) {
2137 continue;
2138 }
2139
Jeff Browncaf7b0a2013-04-25 21:24:44 -07002140 String8 name8(sym.name);
Xavier Ducrohetf5de6502012-09-11 14:45:22 -07002141 fprintf(fp, "int %s %s 0x%08x\n",
2142 className.string(),
Jeff Browncaf7b0a2013-04-25 21:24:44 -07002143 flattenSymbol(name8).string(), (int)sym.int32Val);
Xavier Ducrohetf5de6502012-09-11 14:45:22 -07002144 }
2145
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 = writeTextLayoutClasses(fp, assets, nsymbols, includePrivate);
2152 } else {
2153 err = writeTextSymbolClass(fp, assets, includePrivate, nsymbols, nclassName);
2154 }
2155 if (err != NO_ERROR) {
2156 return err;
2157 }
2158 }
2159
2160 return NO_ERROR;
2161}
2162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002163status_t writeResourceSymbols(Bundle* bundle, const sp<AaptAssets>& assets,
2164 const String8& package, bool includePrivate)
2165{
2166 if (!bundle->getRClassDir()) {
2167 return NO_ERROR;
2168 }
2169
Xavier Ducrohetf5de6502012-09-11 14:45:22 -07002170 const char* textSymbolsDest = bundle->getOutputTextSymbols();
2171
2172 String8 R("R");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002173 const size_t N = assets->getSymbols().size();
2174 for (size_t i=0; i<N; i++) {
2175 sp<AaptSymbols> symbols = assets->getSymbols().valueAt(i);
2176 String8 className(assets->getSymbols().keyAt(i));
2177 String8 dest(bundle->getRClassDir());
Xavier Ducrohetf5de6502012-09-11 14:45:22 -07002178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002179 if (bundle->getMakePackageDirs()) {
2180 String8 pkg(package);
2181 const char* last = pkg.string();
2182 const char* s = last-1;
2183 do {
2184 s++;
2185 if (s > last && (*s == '.' || *s == 0)) {
2186 String8 part(last, s-last);
2187 dest.appendPath(part);
2188#ifdef HAVE_MS_C_RUNTIME
2189 _mkdir(dest.string());
2190#else
2191 mkdir(dest.string(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP);
2192#endif
2193 last = s+1;
2194 }
2195 } while (*s);
2196 }
2197 dest.appendPath(className);
2198 dest.append(".java");
2199 FILE* fp = fopen(dest.string(), "w+");
2200 if (fp == NULL) {
2201 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
2202 dest.string(), strerror(errno));
2203 return UNKNOWN_ERROR;
2204 }
2205 if (bundle->getVerbose()) {
2206 printf(" Writing symbols for class %s.\n", className.string());
2207 }
2208
2209 fprintf(fp,
Xavier Ducrohetf5de6502012-09-11 14:45:22 -07002210 "/* AUTO-GENERATED FILE. DO NOT MODIFY.\n"
2211 " *\n"
2212 " * This class was automatically generated by the\n"
2213 " * aapt tool from the resource data it found. It\n"
2214 " * should not be modified by hand.\n"
2215 " */\n"
2216 "\n"
2217 "package %s;\n\n", package.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218
Dianne Hackborn1644c6d72012-02-06 15:33:21 -08002219 status_t err = writeSymbolClass(fp, assets, includePrivate, symbols,
2220 className, 0, bundle->getNonConstantId());
Elliott Hughesc367d482013-10-29 13:12:55 -07002221 fclose(fp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002222 if (err != NO_ERROR) {
2223 return err;
2224 }
Josiah Gaskin9bf34ca2011-06-14 13:57:09 -07002225
Xavier Ducrohetf5de6502012-09-11 14:45:22 -07002226 if (textSymbolsDest != NULL && R == className) {
2227 String8 textDest(textSymbolsDest);
2228 textDest.appendPath(className);
2229 textDest.append(".txt");
2230
2231 FILE* fp = fopen(textDest.string(), "w+");
2232 if (fp == NULL) {
2233 fprintf(stderr, "ERROR: Unable to open text symbol file %s: %s\n",
2234 textDest.string(), strerror(errno));
2235 return UNKNOWN_ERROR;
2236 }
2237 if (bundle->getVerbose()) {
2238 printf(" Writing text symbols for class %s.\n", className.string());
2239 }
2240
2241 status_t err = writeTextSymbolClass(fp, assets, includePrivate, symbols,
2242 className);
Elliott Hughesc367d482013-10-29 13:12:55 -07002243 fclose(fp);
Xavier Ducrohetf5de6502012-09-11 14:45:22 -07002244 if (err != NO_ERROR) {
2245 return err;
2246 }
Xavier Ducrohetf5de6502012-09-11 14:45:22 -07002247 }
2248
Josiah Gaskinb711f3f2011-08-15 18:33:44 -07002249 // If we were asked to generate a dependency file, we'll go ahead and add this R.java
2250 // as a target in the dependency file right next to it.
Xavier Ducrohetf5de6502012-09-11 14:45:22 -07002251 if (bundle->getGenDependencies() && R == className) {
Josiah Gaskin9bf34ca2011-06-14 13:57:09 -07002252 // Add this R.java to the dependency file
2253 String8 dependencyFile(bundle->getRClassDir());
Josiah Gaskinb711f3f2011-08-15 18:33:44 -07002254 dependencyFile.appendPath("R.java.d");
Josiah Gaskin9bf34ca2011-06-14 13:57:09 -07002255
Xavier Ducrohetf5de6502012-09-11 14:45:22 -07002256 FILE *fp = fopen(dependencyFile.string(), "a");
Josiah Gaskin9bf34ca2011-06-14 13:57:09 -07002257 fprintf(fp,"%s \\\n", dest.string());
2258 fclose(fp);
2259 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002260 }
2261
2262 return NO_ERROR;
2263}
Joe Onorato1553c822009-08-30 13:36:22 -07002264
2265
Joe Onorato1553c822009-08-30 13:36:22 -07002266class ProguardKeepSet
2267{
2268public:
2269 // { rule --> { file locations } }
2270 KeyedVector<String8, SortedVector<String8> > rules;
2271
2272 void add(const String8& rule, const String8& where);
2273};
2274
2275void ProguardKeepSet::add(const String8& rule, const String8& where)
2276{
2277 ssize_t index = rules.indexOfKey(rule);
2278 if (index < 0) {
2279 index = rules.add(rule, SortedVector<String8>());
2280 }
2281 rules.editValueAt(index).add(where);
2282}
2283
Dianne Hackbornb0381ef2010-03-03 13:36:35 -08002284void
2285addProguardKeepRule(ProguardKeepSet* keep, const String8& inClassName,
2286 const char* pkg, const String8& srcName, int line)
2287{
2288 String8 className(inClassName);
2289 if (pkg != NULL) {
2290 // asdf --> package.asdf
2291 // .asdf .a.b --> package.asdf package.a.b
2292 // asdf.adsf --> asdf.asdf
2293 const char* p = className.string();
2294 const char* q = strchr(p, '.');
2295 if (p == q) {
2296 className = pkg;
2297 className.append(inClassName);
2298 } else if (q == NULL) {
2299 className = pkg;
2300 className.append(".");
2301 className.append(inClassName);
2302 }
2303 }
Ying Wang561a9182010-08-13 13:56:07 -07002304
Dianne Hackbornb0381ef2010-03-03 13:36:35 -08002305 String8 rule("-keep class ");
2306 rule += className;
2307 rule += " { <init>(...); }";
2308
2309 String8 location("view ");
2310 location += srcName;
2311 char lineno[20];
2312 sprintf(lineno, ":%d", line);
2313 location += lineno;
2314
2315 keep->add(rule, location);
2316}
2317
Dianne Hackborn92751972012-05-18 19:22:14 -07002318void
2319addProguardKeepMethodRule(ProguardKeepSet* keep, const String8& memberName,
2320 const char* pkg, const String8& srcName, int line)
2321{
2322 String8 rule("-keepclassmembers class * { *** ");
2323 rule += memberName;
2324 rule += "(...); }";
2325
2326 String8 location("onClick ");
2327 location += srcName;
2328 char lineno[20];
2329 sprintf(lineno, ":%d", line);
2330 location += lineno;
2331
2332 keep->add(rule, location);
2333}
2334
Joe Onorato1553c822009-08-30 13:36:22 -07002335status_t
2336writeProguardForAndroidManifest(ProguardKeepSet* keep, const sp<AaptAssets>& assets)
2337{
2338 status_t err;
2339 ResXMLTree tree;
2340 size_t len;
2341 ResXMLTree::event_code_t code;
2342 int depth = 0;
2343 bool inApplication = false;
2344 String8 error;
2345 sp<AaptGroup> assGroup;
2346 sp<AaptFile> assFile;
2347 String8 pkg;
2348
2349 // First, look for a package file to parse. This is required to
2350 // be able to generate the resource information.
2351 assGroup = assets->getFiles().valueFor(String8("AndroidManifest.xml"));
2352 if (assGroup == NULL) {
2353 fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n");
2354 return -1;
2355 }
2356
2357 if (assGroup->getFiles().size() != 1) {
2358 fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
2359 assGroup->getFiles().valueAt(0)->getPrintableSource().string());
2360 }
2361
2362 assFile = assGroup->getFiles().valueAt(0);
2363
2364 err = parseXMLResource(assFile, &tree);
2365 if (err != NO_ERROR) {
2366 return err;
2367 }
2368
2369 tree.restart();
2370
2371 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
2372 if (code == ResXMLTree::END_TAG) {
2373 if (/* name == "Application" && */ depth == 2) {
2374 inApplication = false;
2375 }
2376 depth--;
2377 continue;
2378 }
2379 if (code != ResXMLTree::START_TAG) {
2380 continue;
2381 }
2382 depth++;
2383 String8 tag(tree.getElementName(&len));
2384 // printf("Depth %d tag %s\n", depth, tag.string());
Ying Wang46f4b982010-01-13 14:18:11 -08002385 bool keepTag = false;
Joe Onorato1553c822009-08-30 13:36:22 -07002386 if (depth == 1) {
2387 if (tag != "manifest") {
2388 fprintf(stderr, "ERROR: manifest does not start with <manifest> tag\n");
2389 return -1;
2390 }
2391 pkg = getAttribute(tree, NULL, "package", NULL);
Ying Wang46f4b982010-01-13 14:18:11 -08002392 } else if (depth == 2) {
2393 if (tag == "application") {
2394 inApplication = true;
2395 keepTag = true;
Ying Wang561a9182010-08-13 13:56:07 -07002396
Dianne Hackbornb0381ef2010-03-03 13:36:35 -08002397 String8 agent = getAttribute(tree, "http://schemas.android.com/apk/res/android",
2398 "backupAgent", &error);
2399 if (agent.length() > 0) {
2400 addProguardKeepRule(keep, agent, pkg.string(),
2401 assFile->getPrintableSource(), tree.getLineNumber());
2402 }
Ying Wang46f4b982010-01-13 14:18:11 -08002403 } else if (tag == "instrumentation") {
2404 keepTag = true;
2405 }
Joe Onorato1553c822009-08-30 13:36:22 -07002406 }
Ying Wang46f4b982010-01-13 14:18:11 -08002407 if (!keepTag && inApplication && depth == 3) {
2408 if (tag == "activity" || tag == "service" || tag == "receiver" || tag == "provider") {
2409 keepTag = true;
2410 }
2411 }
2412 if (keepTag) {
2413 String8 name = getAttribute(tree, "http://schemas.android.com/apk/res/android",
2414 "name", &error);
2415 if (error != "") {
2416 fprintf(stderr, "ERROR: %s\n", error.string());
2417 return -1;
2418 }
2419 if (name.length() > 0) {
Dianne Hackbornb0381ef2010-03-03 13:36:35 -08002420 addProguardKeepRule(keep, name, pkg.string(),
2421 assFile->getPrintableSource(), tree.getLineNumber());
Joe Onorato1553c822009-08-30 13:36:22 -07002422 }
2423 }
2424 }
2425
2426 return NO_ERROR;
2427}
2428
Ying Wang561a9182010-08-13 13:56:07 -07002429struct NamespaceAttributePair {
2430 const char* ns;
2431 const char* attr;
2432
2433 NamespaceAttributePair(const char* n, const char* a) : ns(n), attr(a) {}
2434 NamespaceAttributePair() : ns(NULL), attr(NULL) {}
2435};
2436
Joe Onorato1553c822009-08-30 13:36:22 -07002437status_t
Dianne Hackbornabd03652010-03-02 14:56:51 -08002438writeProguardForXml(ProguardKeepSet* keep, const sp<AaptFile>& layoutFile,
Xavier Ducrohet095cd2e2012-07-18 18:06:09 -07002439 const char* startTag, const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs)
Joe Onorato1553c822009-08-30 13:36:22 -07002440{
2441 status_t err;
2442 ResXMLTree tree;
2443 size_t len;
2444 ResXMLTree::event_code_t code;
2445
2446 err = parseXMLResource(layoutFile, &tree);
2447 if (err != NO_ERROR) {
2448 return err;
2449 }
2450
2451 tree.restart();
2452
Dianne Hackbornabd03652010-03-02 14:56:51 -08002453 if (startTag != NULL) {
2454 bool haveStart = false;
2455 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
2456 if (code != ResXMLTree::START_TAG) {
2457 continue;
2458 }
2459 String8 tag(tree.getElementName(&len));
2460 if (tag == startTag) {
2461 haveStart = true;
2462 }
2463 break;
2464 }
2465 if (!haveStart) {
2466 return NO_ERROR;
2467 }
2468 }
Ying Wang561a9182010-08-13 13:56:07 -07002469
Joe Onorato1553c822009-08-30 13:36:22 -07002470 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
2471 if (code != ResXMLTree::START_TAG) {
2472 continue;
2473 }
2474 String8 tag(tree.getElementName(&len));
2475
2476 // If there is no '.', we'll assume that it's one of the built in names.
2477 if (strchr(tag.string(), '.')) {
Dianne Hackbornb0381ef2010-03-03 13:36:35 -08002478 addProguardKeepRule(keep, tag, NULL,
Dianne Hackbornabd03652010-03-02 14:56:51 -08002479 layoutFile->getPrintableSource(), tree.getLineNumber());
Ying Wang561a9182010-08-13 13:56:07 -07002480 } else if (tagAttrPairs != NULL) {
2481 ssize_t tagIndex = tagAttrPairs->indexOfKey(tag);
2482 if (tagIndex >= 0) {
Xavier Ducrohet095cd2e2012-07-18 18:06:09 -07002483 const Vector<NamespaceAttributePair>& nsAttrVector = tagAttrPairs->valueAt(tagIndex);
2484 for (size_t i = 0; i < nsAttrVector.size(); i++) {
2485 const NamespaceAttributePair& nsAttr = nsAttrVector[i];
2486
2487 ssize_t attrIndex = tree.indexOfAttribute(nsAttr.ns, nsAttr.attr);
2488 if (attrIndex < 0) {
2489 // fprintf(stderr, "%s:%d: <%s> does not have attribute %s:%s.\n",
2490 // layoutFile->getPrintableSource().string(), tree.getLineNumber(),
2491 // tag.string(), nsAttr.ns, nsAttr.attr);
2492 } else {
2493 size_t len;
2494 addProguardKeepRule(keep,
2495 String8(tree.getAttributeStringValue(attrIndex, &len)), NULL,
2496 layoutFile->getPrintableSource(), tree.getLineNumber());
2497 }
Ying Wang561a9182010-08-13 13:56:07 -07002498 }
Dianne Hackbornabd03652010-03-02 14:56:51 -08002499 }
Joe Onorato1553c822009-08-30 13:36:22 -07002500 }
Dianne Hackborn92751972012-05-18 19:22:14 -07002501 ssize_t attrIndex = tree.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "onClick");
2502 if (attrIndex >= 0) {
2503 size_t len;
2504 addProguardKeepMethodRule(keep,
2505 String8(tree.getAttributeStringValue(attrIndex, &len)), NULL,
2506 layoutFile->getPrintableSource(), tree.getLineNumber());
2507 }
Joe Onorato1553c822009-08-30 13:36:22 -07002508 }
2509
2510 return NO_ERROR;
2511}
2512
Xavier Ducrohet095cd2e2012-07-18 18:06:09 -07002513static void addTagAttrPair(KeyedVector<String8, Vector<NamespaceAttributePair> >* dest,
Ying Wang561a9182010-08-13 13:56:07 -07002514 const char* tag, const char* ns, const char* attr) {
Xavier Ducrohet095cd2e2012-07-18 18:06:09 -07002515 String8 tagStr(tag);
2516 ssize_t index = dest->indexOfKey(tagStr);
2517
2518 if (index < 0) {
2519 Vector<NamespaceAttributePair> vector;
2520 vector.add(NamespaceAttributePair(ns, attr));
2521 dest->add(tagStr, vector);
2522 } else {
2523 dest->editValueAt(index).add(NamespaceAttributePair(ns, attr));
2524 }
Ying Wang561a9182010-08-13 13:56:07 -07002525}
2526
Joe Onorato1553c822009-08-30 13:36:22 -07002527status_t
2528writeProguardForLayouts(ProguardKeepSet* keep, const sp<AaptAssets>& assets)
2529{
2530 status_t err;
Ying Wang561a9182010-08-13 13:56:07 -07002531
2532 // tag:attribute pairs that should be checked in layout files.
Xavier Ducrohet095cd2e2012-07-18 18:06:09 -07002533 KeyedVector<String8, Vector<NamespaceAttributePair> > kLayoutTagAttrPairs;
Ying Wang561a9182010-08-13 13:56:07 -07002534 addTagAttrPair(&kLayoutTagAttrPairs, "view", NULL, "class");
Dianne Hackborn8a44bb22010-08-19 12:56:10 -07002535 addTagAttrPair(&kLayoutTagAttrPairs, "fragment", NULL, "class");
Ying Wang561a9182010-08-13 13:56:07 -07002536 addTagAttrPair(&kLayoutTagAttrPairs, "fragment", RESOURCES_ANDROID_NAMESPACE, "name");
2537
2538 // tag:attribute pairs that should be checked in xml files.
Xavier Ducrohet095cd2e2012-07-18 18:06:09 -07002539 KeyedVector<String8, Vector<NamespaceAttributePair> > kXmlTagAttrPairs;
Ying Wang561a9182010-08-13 13:56:07 -07002540 addTagAttrPair(&kXmlTagAttrPairs, "PreferenceScreen", RESOURCES_ANDROID_NAMESPACE, "fragment");
Dianne Hackborn8a44bb22010-08-19 12:56:10 -07002541 addTagAttrPair(&kXmlTagAttrPairs, "header", RESOURCES_ANDROID_NAMESPACE, "fragment");
Ying Wang561a9182010-08-13 13:56:07 -07002542
Ying Wangc1112962010-01-20 22:12:46 -08002543 const Vector<sp<AaptDir> >& dirs = assets->resDirs();
2544 const size_t K = dirs.size();
2545 for (size_t k=0; k<K; k++) {
2546 const sp<AaptDir>& d = dirs.itemAt(k);
2547 const String8& dirName = d->getLeaf();
Dianne Hackbornabd03652010-03-02 14:56:51 -08002548 const char* startTag = NULL;
Xavier Ducrohet095cd2e2012-07-18 18:06:09 -07002549 const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs = NULL;
Dianne Hackbornabd03652010-03-02 14:56:51 -08002550 if ((dirName == String8("layout")) || (strncmp(dirName.string(), "layout-", 7) == 0)) {
Ying Wang561a9182010-08-13 13:56:07 -07002551 tagAttrPairs = &kLayoutTagAttrPairs;
Dianne Hackbornabd03652010-03-02 14:56:51 -08002552 } else if ((dirName == String8("xml")) || (strncmp(dirName.string(), "xml-", 4) == 0)) {
2553 startTag = "PreferenceScreen";
Ying Wang561a9182010-08-13 13:56:07 -07002554 tagAttrPairs = &kXmlTagAttrPairs;
Dianne Hackborn92751972012-05-18 19:22:14 -07002555 } else if ((dirName == String8("menu")) || (strncmp(dirName.string(), "menu-", 5) == 0)) {
2556 startTag = "menu";
2557 tagAttrPairs = NULL;
Dianne Hackbornabd03652010-03-02 14:56:51 -08002558 } else {
Ying Wangc1112962010-01-20 22:12:46 -08002559 continue;
2560 }
Ying Wang561a9182010-08-13 13:56:07 -07002561
Ying Wangc1112962010-01-20 22:12:46 -08002562 const KeyedVector<String8,sp<AaptGroup> > groups = d->getFiles();
Joe Onorato1553c822009-08-30 13:36:22 -07002563 const size_t N = groups.size();
2564 for (size_t i=0; i<N; i++) {
2565 const sp<AaptGroup>& group = groups.valueAt(i);
2566 const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files = group->getFiles();
2567 const size_t M = files.size();
2568 for (size_t j=0; j<M; j++) {
Ying Wang561a9182010-08-13 13:56:07 -07002569 err = writeProguardForXml(keep, files.valueAt(j), startTag, tagAttrPairs);
Joe Onorato1553c822009-08-30 13:36:22 -07002570 if (err < 0) {
2571 return err;
2572 }
2573 }
2574 }
2575 }
Ying Wang45ccfa52011-06-20 15:41:08 -07002576 // Handle the overlays
2577 sp<AaptAssets> overlay = assets->getOverlay();
2578 if (overlay.get()) {
2579 return writeProguardForLayouts(keep, overlay);
2580 }
Xavier Ducrohet095cd2e2012-07-18 18:06:09 -07002581
Joe Onorato1553c822009-08-30 13:36:22 -07002582 return NO_ERROR;
2583}
2584
2585status_t
2586writeProguardFile(Bundle* bundle, const sp<AaptAssets>& assets)
2587{
2588 status_t err = -1;
2589
2590 if (!bundle->getProguardFile()) {
2591 return NO_ERROR;
2592 }
2593
2594 ProguardKeepSet keep;
2595
2596 err = writeProguardForAndroidManifest(&keep, assets);
2597 if (err < 0) {
2598 return err;
2599 }
2600
2601 err = writeProguardForLayouts(&keep, assets);
2602 if (err < 0) {
2603 return err;
2604 }
2605
2606 FILE* fp = fopen(bundle->getProguardFile(), "w+");
2607 if (fp == NULL) {
2608 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
2609 bundle->getProguardFile(), strerror(errno));
2610 return UNKNOWN_ERROR;
2611 }
2612
2613 const KeyedVector<String8, SortedVector<String8> >& rules = keep.rules;
2614 const size_t N = rules.size();
2615 for (size_t i=0; i<N; i++) {
2616 const SortedVector<String8>& locations = rules.valueAt(i);
2617 const size_t M = locations.size();
2618 for (size_t j=0; j<M; j++) {
2619 fprintf(fp, "# %s\n", locations.itemAt(j).string());
2620 }
2621 fprintf(fp, "%s\n\n", rules.keyAt(i).string());
2622 }
2623 fclose(fp);
2624
2625 return err;
2626}
Josiah Gaskin9bf34ca2011-06-14 13:57:09 -07002627
Josiah Gaskin03589cc2011-06-27 16:26:02 -07002628// Loops through the string paths and writes them to the file pointer
2629// Each file path is written on its own line with a terminating backslash.
2630status_t writePathsToFile(const sp<FilePathStore>& files, FILE* fp)
Josiah Gaskin9bf34ca2011-06-14 13:57:09 -07002631{
2632 status_t deps = -1;
Josiah Gaskin9bf34ca2011-06-14 13:57:09 -07002633 for (size_t file_i = 0; file_i < files->size(); ++file_i) {
2634 // Add the full file path to the dependency file
2635 fprintf(fp, "%s \\\n", files->itemAt(file_i).string());
2636 deps++;
2637 }
2638 return deps;
Xavier Ducrohet91398682011-07-19 10:18:28 -07002639}
Josiah Gaskin03589cc2011-06-27 16:26:02 -07002640
2641status_t
2642writeDependencyPreReqs(Bundle* bundle, const sp<AaptAssets>& assets, FILE* fp, bool includeRaw)
2643{
2644 status_t deps = -1;
2645 deps += writePathsToFile(assets->getFullResPaths(), fp);
2646 if (includeRaw) {
2647 deps += writePathsToFile(assets->getFullAssetPaths(), fp);
2648 }
2649 return deps;
2650}