1 //
2 // Copyright 2006 The Android Open Source Project
3 //
4 // Build resource files from raw assets.
5 //
6 #include "AaptAssets.h"
7 #include "AaptUtil.h"
8 #include "AaptXml.h"
9 #include "CacheUpdater.h"
10 #include "CrunchCache.h"
11 #include "FileFinder.h"
12 #include "Images.h"
13 #include "IndentPrinter.h"
14 #include "Main.h"
15 #include "ResourceTable.h"
16 #include "StringPool.h"
17 #include "Symbol.h"
18 #include "Utils.h"
19 #include "WorkQueue.h"
20 #include "XMLNode.h"
21
22 #include <androidfw/PathUtils.h>
23
24 #include <algorithm>
25
26 // STATUST: mingw does seem to redefine UNKNOWN_ERROR from our enum value, so a cast is necessary.
27
28 #if !defined(_WIN32)
29 # define STATUST(x) x
30 #else
31 # define STATUST(x) (status_t)x
32 #endif
33
34 // Set to true for noisy debug output.
35 static const bool kIsDebug = false;
36
37 // Number of threads to use for preprocessing images.
38 static const size_t MAX_THREADS = 4;
39
40 // ==========================================================================
41 // ==========================================================================
42 // ==========================================================================
43
44 class PackageInfo
45 {
46 public:
PackageInfo()47 PackageInfo()
48 {
49 }
~PackageInfo()50 ~PackageInfo()
51 {
52 }
53
54 status_t parsePackage(const sp<AaptGroup>& grp);
55 };
56
57 // ==========================================================================
58 // ==========================================================================
59 // ==========================================================================
60
parseResourceName(const String8 & leaf)61 String8 parseResourceName(const String8& leaf)
62 {
63 const char* firstDot = strchr(leaf.c_str(), '.');
64 const char* str = leaf.c_str();
65
66 if (firstDot) {
67 return String8(str, firstDot-str);
68 } else {
69 return String8(str);
70 }
71 }
72
ResourceTypeSet()73 ResourceTypeSet::ResourceTypeSet()
74 :RefBase(),
75 KeyedVector<String8,sp<AaptGroup> >()
76 {
77 }
78
FilePathStore()79 FilePathStore::FilePathStore()
80 :RefBase(),
81 Vector<String8>()
82 {
83 }
84
85 class ResourceDirIterator
86 {
87 public:
ResourceDirIterator(const sp<ResourceTypeSet> & set,const String8 & resType)88 ResourceDirIterator(const sp<ResourceTypeSet>& set, const String8& resType)
89 : mResType(resType), mSet(set), mSetPos(0), mGroupPos(0)
90 {
91 memset(&mParams, 0, sizeof(ResTable_config));
92 }
93
getGroup() const94 inline const sp<AaptGroup>& getGroup() const { return mGroup; }
getFile() const95 inline const sp<AaptFile>& getFile() const { return mFile; }
96
getBaseName() const97 inline const String8& getBaseName() const { return mBaseName; }
getLeafName() const98 inline const String8& getLeafName() const { return mLeafName; }
getPath() const99 inline String8 getPath() const { return mPath; }
getParams() const100 inline const ResTable_config& getParams() const { return mParams; }
101
102 enum {
103 EOD = 1
104 };
105
next()106 ssize_t next()
107 {
108 while (true) {
109 sp<AaptGroup> group;
110 sp<AaptFile> file;
111
112 // Try to get next file in this current group.
113 if (mGroup != NULL && mGroupPos < mGroup->getFiles().size()) {
114 group = mGroup;
115 file = group->getFiles().valueAt(mGroupPos++);
116
117 // Try to get the next group/file in this directory
118 } else if (mSetPos < mSet->size()) {
119 mGroup = group = mSet->valueAt(mSetPos++);
120 if (group->getFiles().size() < 1) {
121 continue;
122 }
123 file = group->getFiles().valueAt(0);
124 mGroupPos = 1;
125
126 // All done!
127 } else {
128 return EOD;
129 }
130
131 mFile = file;
132
133 String8 leaf(group->getLeaf());
134 mLeafName = String8(leaf);
135 mParams = file->getGroupEntry().toParams();
136 if (kIsDebug) {
137 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",
138 group->getPath().c_str(), mParams.mcc, mParams.mnc,
139 mParams.language[0] ? mParams.language[0] : '-',
140 mParams.language[1] ? mParams.language[1] : '-',
141 mParams.country[0] ? mParams.country[0] : '-',
142 mParams.country[1] ? mParams.country[1] : '-',
143 mParams.orientation, mParams.uiMode,
144 mParams.density, mParams.touchscreen, mParams.keyboard,
145 mParams.inputFlags, mParams.navigation);
146 }
147 mPath = "res";
148 appendPath(mPath, file->getGroupEntry().toDirName(mResType));
149 appendPath(mPath, leaf);
150 mBaseName = parseResourceName(leaf);
151 if (mBaseName == "") {
152 fprintf(stderr, "Error: malformed resource filename %s\n",
153 file->getPrintableSource().c_str());
154 return UNKNOWN_ERROR;
155 }
156
157 if (kIsDebug) {
158 printf("file name=%s\n", mBaseName.c_str());
159 }
160
161 return NO_ERROR;
162 }
163 }
164
165 private:
166 String8 mResType;
167
168 const sp<ResourceTypeSet> mSet;
169 size_t mSetPos;
170
171 sp<AaptGroup> mGroup;
172 size_t mGroupPos;
173
174 sp<AaptFile> mFile;
175 String8 mBaseName;
176 String8 mLeafName;
177 String8 mPath;
178 ResTable_config mParams;
179 };
180
181 class AnnotationProcessor {
182 public:
AnnotationProcessor()183 AnnotationProcessor() : mDeprecated(false), mSystemApi(false) { }
184
preprocessComment(String8 & comment)185 void preprocessComment(String8& comment) {
186 if (comment.size() > 0) {
187 if (comment.contains("@deprecated")) {
188 mDeprecated = true;
189 }
190 if (comment.removeAll("@SystemApi")) {
191 mSystemApi = true;
192 }
193 }
194 }
195
printAnnotations(FILE * fp,const char * indentStr)196 void printAnnotations(FILE* fp, const char* indentStr) {
197 if (mDeprecated) {
198 fprintf(fp, "%s@Deprecated\n", indentStr);
199 }
200 if (mSystemApi) {
201 fprintf(fp, "%s@android.annotation.SystemApi\n", indentStr);
202 }
203 }
204
205 private:
206 bool mDeprecated;
207 bool mSystemApi;
208 };
209
210 // ==========================================================================
211 // ==========================================================================
212 // ==========================================================================
213
isValidResourceType(const String8 & type)214 bool isValidResourceType(const String8& type)
215 {
216 return type == "anim" || type == "animator" || type == "interpolator"
217 || type == "transition" || type == "font"
218 || type == "drawable" || type == "layout"
219 || type == "values" || type == "xml" || type == "raw"
220 || type == "color" || type == "menu" || type == "mipmap";
221 }
222
parsePackage(Bundle * bundle,const sp<AaptAssets> & assets,const sp<AaptGroup> & grp)223 static status_t parsePackage(Bundle* bundle, const sp<AaptAssets>& assets,
224 const sp<AaptGroup>& grp)
225 {
226 if (grp->getFiles().size() != 1) {
227 fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
228 grp->getFiles().valueAt(0)->getPrintableSource().c_str());
229 }
230
231 sp<AaptFile> file = grp->getFiles().valueAt(0);
232
233 ResXMLTree block;
234 status_t err = parseXMLResource(file, &block);
235 if (err != NO_ERROR) {
236 return err;
237 }
238 //printXMLBlock(&block);
239
240 ResXMLTree::event_code_t code;
241 while ((code=block.next()) != ResXMLTree::START_TAG
242 && code != ResXMLTree::END_DOCUMENT
243 && code != ResXMLTree::BAD_DOCUMENT) {
244 }
245
246 size_t len;
247 if (code != ResXMLTree::START_TAG) {
248 fprintf(stderr, "%s:%d: No start tag found\n",
249 file->getPrintableSource().c_str(), block.getLineNumber());
250 return UNKNOWN_ERROR;
251 }
252 if (strcmp16(block.getElementName(&len), String16("manifest").c_str()) != 0) {
253 fprintf(stderr, "%s:%d: Invalid start tag %s, expected <manifest>\n",
254 file->getPrintableSource().c_str(), block.getLineNumber(),
255 String8(block.getElementName(&len)).c_str());
256 return UNKNOWN_ERROR;
257 }
258
259 ssize_t nameIndex = block.indexOfAttribute(NULL, "package");
260 if (nameIndex < 0) {
261 fprintf(stderr, "%s:%d: <manifest> does not have package attribute.\n",
262 file->getPrintableSource().c_str(), block.getLineNumber());
263 return UNKNOWN_ERROR;
264 }
265
266 assets->setPackage(String8(block.getAttributeStringValue(nameIndex, &len)));
267
268 ssize_t revisionCodeIndex = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "revisionCode");
269 if (revisionCodeIndex >= 0) {
270 bundle->setRevisionCode(String8(block.getAttributeStringValue(revisionCodeIndex, &len)).c_str());
271 }
272
273 String16 uses_sdk16("uses-sdk");
274 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
275 && code != ResXMLTree::BAD_DOCUMENT) {
276 if (code == ResXMLTree::START_TAG) {
277 if (strcmp16(block.getElementName(&len), uses_sdk16.c_str()) == 0) {
278 ssize_t minSdkIndex = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE,
279 "minSdkVersion");
280 if (minSdkIndex >= 0) {
281 const char16_t* minSdk16 = block.getAttributeStringValue(minSdkIndex, &len);
282 const char* minSdk8 = strdup(String8(minSdk16).c_str());
283 bundle->setManifestMinSdkVersion(minSdk8);
284 }
285 }
286 }
287 }
288
289 return NO_ERROR;
290 }
291
292 // ==========================================================================
293 // ==========================================================================
294 // ==========================================================================
295
makeFileResources(Bundle * bundle,const sp<AaptAssets> & assets,ResourceTable * table,const sp<ResourceTypeSet> & set,const char * resType)296 static status_t makeFileResources(Bundle* bundle, const sp<AaptAssets>& assets,
297 ResourceTable* table,
298 const sp<ResourceTypeSet>& set,
299 const char* resType)
300 {
301 String8 type8(resType);
302 String16 type16(resType);
303
304 bool hasErrors = false;
305
306 ResourceDirIterator it(set, String8(resType));
307 ssize_t res;
308 while ((res=it.next()) == NO_ERROR) {
309 if (bundle->getVerbose()) {
310 printf(" (new resource id %s from %s)\n",
311 it.getBaseName().c_str(), it.getFile()->getPrintableSource().c_str());
312 }
313 String16 baseName(it.getBaseName());
314 const char16_t* str = baseName.c_str();
315 const char16_t* const end = str + baseName.size();
316 while (str < end) {
317 if (!((*str >= 'a' && *str <= 'z')
318 || (*str >= '0' && *str <= '9')
319 || *str == '_' || *str == '.')) {
320 fprintf(stderr, "%s: Invalid file name: must contain only [a-z0-9_.]\n",
321 it.getPath().c_str());
322 hasErrors = true;
323 }
324 str++;
325 }
326 String8 resPath = it.getPath();
327 convertToResPath(resPath);
328 status_t result = table->addEntry(SourcePos(it.getPath(), 0),
329 String16(assets->getPackage()),
330 type16,
331 baseName,
332 String16(resPath),
333 NULL,
334 &it.getParams());
335 if (result != NO_ERROR) {
336 hasErrors = true;
337 } else {
338 assets->addResource(it.getLeafName(), resPath, it.getFile(), type8);
339 }
340 }
341
342 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
343 }
344
345 class PreProcessImageWorkUnit : public WorkQueue::WorkUnit {
346 public:
PreProcessImageWorkUnit(const Bundle * bundle,const sp<AaptAssets> & assets,const sp<AaptFile> & file,volatile bool * hasErrors)347 PreProcessImageWorkUnit(const Bundle* bundle, const sp<AaptAssets>& assets,
348 const sp<AaptFile>& file, volatile bool* hasErrors) :
349 mBundle(bundle), mAssets(assets), mFile(file), mHasErrors(hasErrors) {
350 }
351
run()352 virtual bool run() {
353 status_t status = preProcessImage(mBundle, mAssets, mFile, NULL);
354 if (status) {
355 *mHasErrors = true;
356 }
357 return true; // continue even if there are errors
358 }
359
360 private:
361 const Bundle* mBundle;
362 sp<AaptAssets> mAssets;
363 sp<AaptFile> mFile;
364 volatile bool* mHasErrors;
365 };
366
preProcessImages(const Bundle * bundle,const sp<AaptAssets> & assets,const sp<ResourceTypeSet> & set,const char * type)367 static status_t preProcessImages(const Bundle* bundle, const sp<AaptAssets>& assets,
368 const sp<ResourceTypeSet>& set, const char* type)
369 {
370 volatile bool hasErrors = false;
371 ssize_t res = NO_ERROR;
372 if (bundle->getUseCrunchCache() == false) {
373 WorkQueue wq(MAX_THREADS, false);
374 ResourceDirIterator it(set, String8(type));
375 while ((res=it.next()) == NO_ERROR) {
376 PreProcessImageWorkUnit* w = new PreProcessImageWorkUnit(
377 bundle, assets, it.getFile(), &hasErrors);
378 status_t status = wq.schedule(w);
379 if (status) {
380 fprintf(stderr, "preProcessImages failed: schedule() returned %d\n", status);
381 hasErrors = true;
382 delete w;
383 break;
384 }
385 }
386 status_t status = wq.finish();
387 if (status) {
388 fprintf(stderr, "preProcessImages failed: finish() returned %d\n", status);
389 hasErrors = true;
390 }
391 }
392 return (hasErrors || (res < NO_ERROR)) ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
393 }
394
collect_files(const sp<AaptDir> & dir,KeyedVector<String8,sp<ResourceTypeSet>> * resources)395 static void collect_files(const sp<AaptDir>& dir,
396 KeyedVector<String8, sp<ResourceTypeSet> >* resources)
397 {
398 const DefaultKeyedVector<String8, sp<AaptGroup> >& groups = dir->getFiles();
399 int N = groups.size();
400 for (int i=0; i<N; i++) {
401 const String8& leafName = groups.keyAt(i);
402 const sp<AaptGroup>& group = groups.valueAt(i);
403
404 const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files
405 = group->getFiles();
406
407 if (files.size() == 0) {
408 continue;
409 }
410
411 String8 resType = files.valueAt(0)->getResourceType();
412
413 ssize_t index = resources->indexOfKey(resType);
414
415 if (index < 0) {
416 sp<ResourceTypeSet> set = new ResourceTypeSet();
417 if (kIsDebug) {
418 printf("Creating new resource type set for leaf %s with group %s (%p)\n",
419 leafName.c_str(), group->getPath().c_str(), group.get());
420 }
421 set->add(leafName, group);
422 resources->add(resType, set);
423 } else {
424 const sp<ResourceTypeSet>& set = resources->valueAt(index);
425 index = set->indexOfKey(leafName);
426 if (index < 0) {
427 if (kIsDebug) {
428 printf("Adding to resource type set for leaf %s group %s (%p)\n",
429 leafName.c_str(), group->getPath().c_str(), group.get());
430 }
431 set->add(leafName, group);
432 } else {
433 sp<AaptGroup> existingGroup = set->valueAt(index);
434 if (kIsDebug) {
435 printf("Extending to resource type set for leaf %s group %s (%p)\n",
436 leafName.c_str(), group->getPath().c_str(), group.get());
437 }
438 for (size_t j=0; j<files.size(); j++) {
439 if (kIsDebug) {
440 printf("Adding file %s in group %s resType %s\n",
441 files.valueAt(j)->getSourceFile().c_str(),
442 files.keyAt(j).toDirName(String8()).c_str(),
443 resType.c_str());
444 }
445 existingGroup->addFile(files.valueAt(j));
446 }
447 }
448 }
449 }
450 }
451
collect_files(const sp<AaptAssets> & ass,KeyedVector<String8,sp<ResourceTypeSet>> * resources)452 static void collect_files(const sp<AaptAssets>& ass,
453 KeyedVector<String8, sp<ResourceTypeSet> >* resources)
454 {
455 const Vector<sp<AaptDir> >& dirs = ass->resDirs();
456 int N = dirs.size();
457
458 for (int i=0; i<N; i++) {
459 const sp<AaptDir>& d = dirs.itemAt(i);
460 if (kIsDebug) {
461 printf("Collecting dir #%d %p: %s, leaf %s\n", i, d.get(), d->getPath().c_str(),
462 d->getLeaf().c_str());
463 }
464 collect_files(d, resources);
465
466 // don't try to include the res dir
467 if (kIsDebug) {
468 printf("Removing dir leaf %s\n", d->getLeaf().c_str());
469 }
470 ass->removeDir(d->getLeaf());
471 }
472 }
473
474 enum {
475 ATTR_OKAY = -1,
476 ATTR_NOT_FOUND = -2,
477 ATTR_LEADING_SPACES = -3,
478 ATTR_TRAILING_SPACES = -4
479 };
validateAttr(const String8 & path,const ResTable & table,const ResXMLParser & parser,const char * ns,const char * attr,const char * validChars,bool required)480 static int validateAttr(const String8& path, const ResTable& table,
481 const ResXMLParser& parser,
482 const char* ns, const char* attr, const char* validChars, bool required)
483 {
484 size_t len;
485
486 ssize_t index = parser.indexOfAttribute(ns, attr);
487 const char16_t* str;
488 Res_value value;
489 if (index >= 0 && parser.getAttributeValue(index, &value) >= 0) {
490 const ResStringPool* pool = &parser.getStrings();
491 if (value.dataType == Res_value::TYPE_REFERENCE) {
492 uint32_t specFlags = 0;
493 int strIdx;
494 if ((strIdx=table.resolveReference(&value, 0x10000000, NULL, &specFlags)) < 0) {
495 fprintf(stderr, "%s:%d: Tag <%s> attribute %s references unknown resid 0x%08x.\n",
496 path.c_str(), parser.getLineNumber(),
497 String8(parser.getElementName(&len)).c_str(), attr,
498 value.data);
499 return ATTR_NOT_FOUND;
500 }
501
502 pool = table.getTableStringBlock(strIdx);
503 #if 0
504 if (pool != NULL) {
505 str = pool->stringAt(value.data, &len);
506 }
507 printf("***** RES ATTR: %s specFlags=0x%x strIdx=%d: %s\n", attr,
508 specFlags, strIdx, str != NULL ? String8(str).c_str() : "???");
509 #endif
510 if ((specFlags&~ResTable_typeSpec::SPEC_PUBLIC) != 0 && false) {
511 fprintf(stderr, "%s:%d: Tag <%s> attribute %s varies by configurations 0x%x.\n",
512 path.c_str(), parser.getLineNumber(),
513 String8(parser.getElementName(&len)).c_str(), attr,
514 specFlags);
515 return ATTR_NOT_FOUND;
516 }
517 }
518 if (value.dataType == Res_value::TYPE_STRING) {
519 if (pool == NULL) {
520 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has no string block.\n",
521 path.c_str(), parser.getLineNumber(),
522 String8(parser.getElementName(&len)).c_str(), attr);
523 return ATTR_NOT_FOUND;
524 }
525 if ((str = UnpackOptionalString(pool->stringAt(value.data), &len)) == NULL) {
526 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has corrupt string value.\n",
527 path.c_str(), parser.getLineNumber(),
528 String8(parser.getElementName(&len)).c_str(), attr);
529 return ATTR_NOT_FOUND;
530 }
531 } else {
532 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has invalid type %d.\n",
533 path.c_str(), parser.getLineNumber(),
534 String8(parser.getElementName(&len)).c_str(), attr,
535 value.dataType);
536 return ATTR_NOT_FOUND;
537 }
538 if (validChars) {
539 for (size_t i=0; i<len; i++) {
540 char16_t c = str[i];
541 const char* p = validChars;
542 bool okay = false;
543 while (*p) {
544 if (c == *p) {
545 okay = true;
546 break;
547 }
548 p++;
549 }
550 if (!okay) {
551 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has invalid character '%c'.\n",
552 path.c_str(), parser.getLineNumber(),
553 String8(parser.getElementName(&len)).c_str(), attr, (char)str[i]);
554 return (int)i;
555 }
556 }
557 }
558 if (*str == ' ') {
559 fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not start with a space.\n",
560 path.c_str(), parser.getLineNumber(),
561 String8(parser.getElementName(&len)).c_str(), attr);
562 return ATTR_LEADING_SPACES;
563 }
564 if (len != 0 && str[len-1] == ' ') {
565 fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not end with a space.\n",
566 path.c_str(), parser.getLineNumber(),
567 String8(parser.getElementName(&len)).c_str(), attr);
568 return ATTR_TRAILING_SPACES;
569 }
570 return ATTR_OKAY;
571 }
572 if (required) {
573 fprintf(stderr, "%s:%d: Tag <%s> missing required attribute %s.\n",
574 path.c_str(), parser.getLineNumber(),
575 String8(parser.getElementName(&len)).c_str(), attr);
576 return ATTR_NOT_FOUND;
577 }
578 return ATTR_OKAY;
579 }
580
checkForIds(const String8 & path,ResXMLParser & parser)581 static void checkForIds(const String8& path, ResXMLParser& parser)
582 {
583 ResXMLTree::event_code_t code;
584 while ((code=parser.next()) != ResXMLTree::END_DOCUMENT
585 && code > ResXMLTree::BAD_DOCUMENT) {
586 if (code == ResXMLTree::START_TAG) {
587 ssize_t index = parser.indexOfAttribute(NULL, "id");
588 if (index >= 0) {
589 fprintf(stderr, "%s:%d: warning: found plain 'id' attribute; did you mean the new 'android:id' name?\n",
590 path.c_str(), parser.getLineNumber());
591 }
592 }
593 }
594 }
595
applyFileOverlay(Bundle * bundle,const sp<AaptAssets> & assets,sp<ResourceTypeSet> * baseSet,const char * resType)596 static bool applyFileOverlay(Bundle *bundle,
597 const sp<AaptAssets>& assets,
598 sp<ResourceTypeSet> *baseSet,
599 const char *resType)
600 {
601 if (bundle->getVerbose()) {
602 printf("applyFileOverlay for %s\n", resType);
603 }
604
605 // Replace any base level files in this category with any found from the overlay
606 // Also add any found only in the overlay.
607 sp<AaptAssets> overlay = assets->getOverlay();
608 String8 resTypeString(resType);
609
610 // work through the linked list of overlays
611 while (overlay.get()) {
612 KeyedVector<String8, sp<ResourceTypeSet> >* overlayRes = overlay->getResources();
613
614 // get the overlay resources of the requested type
615 ssize_t index = overlayRes->indexOfKey(resTypeString);
616 if (index >= 0) {
617 const sp<ResourceTypeSet>& overlaySet = overlayRes->valueAt(index);
618
619 // for each of the resources, check for a match in the previously built
620 // non-overlay "baseset".
621 size_t overlayCount = overlaySet->size();
622 for (size_t overlayIndex=0; overlayIndex<overlayCount; overlayIndex++) {
623 if (bundle->getVerbose()) {
624 printf("trying overlaySet Key=%s\n",overlaySet->keyAt(overlayIndex).c_str());
625 }
626 ssize_t baseIndex = -1;
627 if (baseSet->get() != NULL) {
628 baseIndex = (*baseSet)->indexOfKey(overlaySet->keyAt(overlayIndex));
629 }
630 if (baseIndex >= 0) {
631 // look for same flavor. For a given file (strings.xml, for example)
632 // there may be a locale specific or other flavors - we want to match
633 // the same flavor.
634 sp<AaptGroup> overlayGroup = overlaySet->valueAt(overlayIndex);
635 sp<AaptGroup> baseGroup = (*baseSet)->valueAt(baseIndex);
636
637 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > overlayFiles =
638 overlayGroup->getFiles();
639 if (bundle->getVerbose()) {
640 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > baseFiles =
641 baseGroup->getFiles();
642 for (size_t i=0; i < baseFiles.size(); i++) {
643 printf("baseFile " ZD " has flavor %s\n", (ZD_TYPE) i,
644 baseFiles.keyAt(i).toString().c_str());
645 }
646 for (size_t i=0; i < overlayFiles.size(); i++) {
647 printf("overlayFile " ZD " has flavor %s\n", (ZD_TYPE) i,
648 overlayFiles.keyAt(i).toString().c_str());
649 }
650 }
651
652 size_t overlayGroupSize = overlayFiles.size();
653 for (size_t overlayGroupIndex = 0;
654 overlayGroupIndex<overlayGroupSize;
655 overlayGroupIndex++) {
656 ssize_t baseFileIndex =
657 baseGroup->getFiles().indexOfKey(overlayFiles.
658 keyAt(overlayGroupIndex));
659 if (baseFileIndex >= 0) {
660 if (bundle->getVerbose()) {
661 printf("found a match (" ZD ") for overlay file %s, for flavor %s\n",
662 (ZD_TYPE) baseFileIndex,
663 overlayGroup->getLeaf().c_str(),
664 overlayFiles.keyAt(overlayGroupIndex).toString().c_str());
665 }
666 baseGroup->removeFile(baseFileIndex);
667 } else {
668 // didn't find a match fall through and add it..
669 if (true || bundle->getVerbose()) {
670 printf("nothing matches overlay file %s, for flavor %s\n",
671 overlayGroup->getLeaf().c_str(),
672 overlayFiles.keyAt(overlayGroupIndex).toString().c_str());
673 }
674 }
675 baseGroup->addFile(overlayFiles.valueAt(overlayGroupIndex));
676 assets->addGroupEntry(overlayFiles.keyAt(overlayGroupIndex));
677 }
678 } else {
679 if (baseSet->get() == NULL) {
680 *baseSet = new ResourceTypeSet();
681 assets->getResources()->add(String8(resType), *baseSet);
682 }
683 // this group doesn't exist (a file that's only in the overlay)
684 (*baseSet)->add(overlaySet->keyAt(overlayIndex),
685 overlaySet->valueAt(overlayIndex));
686 // make sure all flavors are defined in the resources.
687 sp<AaptGroup> overlayGroup = overlaySet->valueAt(overlayIndex);
688 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > overlayFiles =
689 overlayGroup->getFiles();
690 size_t overlayGroupSize = overlayFiles.size();
691 for (size_t overlayGroupIndex = 0;
692 overlayGroupIndex<overlayGroupSize;
693 overlayGroupIndex++) {
694 assets->addGroupEntry(overlayFiles.keyAt(overlayGroupIndex));
695 }
696 }
697 }
698 // this overlay didn't have resources for this type
699 }
700 // try next overlay
701 overlay = overlay->getOverlay();
702 }
703 return true;
704 }
705
706 /*
707 * Inserts an attribute in a given node.
708 * If errorOnFailedInsert is true, and the attribute already exists, returns false.
709 * If replaceExisting is true, the attribute will be updated if it already exists.
710 * Returns true otherwise, even if the attribute already exists, and does not modify
711 * the existing attribute's value.
712 */
addTagAttribute(const sp<XMLNode> & node,const char * ns8,const char * attr8,const char * value,bool errorOnFailedInsert,bool replaceExisting)713 bool addTagAttribute(const sp<XMLNode>& node, const char* ns8,
714 const char* attr8, const char* value, bool errorOnFailedInsert,
715 bool replaceExisting)
716 {
717 if (value == NULL) {
718 return true;
719 }
720
721 const String16 ns(ns8);
722 const String16 attr(attr8);
723
724 XMLNode::attribute_entry* existingEntry = node->editAttribute(ns, attr);
725 if (existingEntry != NULL) {
726 if (replaceExisting) {
727 existingEntry->string = String16(value);
728 return true;
729 }
730
731 if (errorOnFailedInsert) {
732 fprintf(stderr, "Error: AndroidManifest.xml already defines %s (in %s);"
733 " cannot insert new value %s.\n",
734 String8(attr).c_str(), String8(ns).c_str(), value);
735 return false;
736 }
737
738 // don't stop the build.
739 return true;
740 }
741
742 node->addAttribute(ns, attr, String16(value));
743 return true;
744 }
745
746 /*
747 * Inserts an attribute in a given node, only if the attribute does not
748 * exist.
749 * If errorOnFailedInsert is true, and the attribute already exists, returns false.
750 * Returns true otherwise, even if the attribute already exists.
751 */
addTagAttribute(const sp<XMLNode> & node,const char * ns8,const char * attr8,const char * value,bool errorOnFailedInsert)752 bool addTagAttribute(const sp<XMLNode>& node, const char* ns8,
753 const char* attr8, const char* value, bool errorOnFailedInsert)
754 {
755 return addTagAttribute(node, ns8, attr8, value, errorOnFailedInsert, false);
756 }
757
fullyQualifyClassName(const String8 & package,const sp<XMLNode> & node,const String16 & attrName)758 static void fullyQualifyClassName(const String8& package, const sp<XMLNode>& node,
759 const String16& attrName) {
760 XMLNode::attribute_entry* attr = node->editAttribute(
761 String16("http://schemas.android.com/apk/res/android"), attrName);
762 if (attr != NULL) {
763 String8 name(attr->string);
764
765 // asdf --> package.asdf
766 // .asdf .a.b --> package.asdf package.a.b
767 // asdf.adsf --> asdf.asdf
768 String8 className;
769 const char* p = name.c_str();
770 const char* q = strchr(p, '.');
771 if (p == q) {
772 className += package;
773 className += name;
774 } else if (q == NULL) {
775 className += package;
776 className += ".";
777 className += name;
778 } else {
779 className += name;
780 }
781 if (kIsDebug) {
782 printf("Qualifying class '%s' to '%s'", name.c_str(), className.c_str());
783 }
784 attr->string = String16(className);
785 }
786 }
787
findEntry(const String16 & packageStr,const String16 & typeStr,const String16 & nameStr,ResourceTable * table)788 static sp<ResourceTable::ConfigList> findEntry(const String16& packageStr, const String16& typeStr,
789 const String16& nameStr, ResourceTable* table) {
790 sp<ResourceTable::Package> pkg = table->getPackage(packageStr);
791 if (pkg != NULL) {
792 sp<ResourceTable::Type> type = pkg->getTypes().valueFor(typeStr);
793 if (type != NULL) {
794 return type->getConfigs().valueFor(nameStr);
795 }
796 }
797 return NULL;
798 }
799
getMaxSdkVersion(const sp<ResourceTable::ConfigList> & configList)800 static uint16_t getMaxSdkVersion(const sp<ResourceTable::ConfigList>& configList) {
801 const DefaultKeyedVector<ConfigDescription, sp<ResourceTable::Entry>>& entries =
802 configList->getEntries();
803 uint16_t maxSdkVersion = 0u;
804 for (size_t i = 0; i < entries.size(); i++) {
805 maxSdkVersion = std::max(maxSdkVersion, entries.keyAt(i).sdkVersion);
806 }
807 return maxSdkVersion;
808 }
809
massageRoundIconSupport(const String16 & iconRef,const String16 & roundIconRef,ResourceTable * table)810 static void massageRoundIconSupport(const String16& iconRef, const String16& roundIconRef,
811 ResourceTable* table) {
812 bool publicOnly = false;
813 const char* err;
814
815 String16 iconPackage, iconType, iconName;
816 if (!ResTable::expandResourceRef(iconRef.c_str(), iconRef.size(), &iconPackage, &iconType,
817 &iconName, NULL, &table->getAssetsPackage(), &err,
818 &publicOnly)) {
819 // Errors will be raised in later XML compilation.
820 return;
821 }
822
823 sp<ResourceTable::ConfigList> iconEntry = findEntry(iconPackage, iconType, iconName, table);
824 if (iconEntry == NULL || getMaxSdkVersion(iconEntry) < SDK_O) {
825 // The icon is not adaptive, so nothing to massage.
826 return;
827 }
828
829 String16 roundIconPackage, roundIconType, roundIconName;
830 if (!ResTable::expandResourceRef(roundIconRef.c_str(), roundIconRef.size(), &roundIconPackage,
831 &roundIconType, &roundIconName, NULL, &table->getAssetsPackage(),
832 &err, &publicOnly)) {
833 // Errors will be raised in later XML compilation.
834 return;
835 }
836
837 sp<ResourceTable::ConfigList> roundIconEntry = findEntry(roundIconPackage, roundIconType,
838 roundIconName, table);
839 if (roundIconEntry == NULL || getMaxSdkVersion(roundIconEntry) >= SDK_O) {
840 // The developer explicitly used a v26 compatible drawable as the roundIcon, meaning we should
841 // not generate an alias to the icon drawable.
842 return;
843 }
844
845 String16 aliasValue = String16(String8::format("@%s:%s/%s", String8(iconPackage).c_str(),
846 String8(iconType).c_str(),
847 String8(iconName).c_str()));
848
849 // Add an equivalent v26 entry to the roundIcon for each v26 variant of the regular icon.
850 const DefaultKeyedVector<ConfigDescription, sp<ResourceTable::Entry>>& configList =
851 iconEntry->getEntries();
852 for (size_t i = 0; i < configList.size(); i++) {
853 if (configList.keyAt(i).sdkVersion >= SDK_O) {
854 table->addEntry(SourcePos(), roundIconPackage, roundIconType, roundIconName, aliasValue,
855 NULL, &configList.keyAt(i));
856 }
857 }
858 }
859
massageManifest(Bundle * bundle,ResourceTable * table,sp<XMLNode> root)860 status_t massageManifest(Bundle* bundle, ResourceTable* table, sp<XMLNode> root)
861 {
862 root = root->searchElement(String16(), String16("manifest"));
863 if (root == NULL) {
864 fprintf(stderr, "No <manifest> tag.\n");
865 return UNKNOWN_ERROR;
866 }
867
868 bool errorOnFailedInsert = bundle->getErrorOnFailedInsert();
869 bool replaceVersion = bundle->getReplaceVersion();
870
871 if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionCode",
872 bundle->getVersionCode(), errorOnFailedInsert, replaceVersion)) {
873 return UNKNOWN_ERROR;
874 } else {
875 const XMLNode::attribute_entry* attr = root->getAttribute(
876 String16(RESOURCES_ANDROID_NAMESPACE), String16("versionCode"));
877 if (attr != NULL) {
878 bundle->setVersionCode(strdup(String8(attr->string).c_str()));
879 }
880 }
881
882 if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionName",
883 bundle->getVersionName(), errorOnFailedInsert, replaceVersion)) {
884 return UNKNOWN_ERROR;
885 } else {
886 const XMLNode::attribute_entry* attr = root->getAttribute(
887 String16(RESOURCES_ANDROID_NAMESPACE), String16("versionName"));
888 if (attr != NULL) {
889 bundle->setVersionName(strdup(String8(attr->string).c_str()));
890 }
891 }
892
893 sp<XMLNode> vers = root->getChildElement(String16(), String16("uses-sdk"));
894 if (bundle->getMinSdkVersion() != NULL
895 || bundle->getTargetSdkVersion() != NULL
896 || bundle->getMaxSdkVersion() != NULL) {
897 if (vers == NULL) {
898 vers = XMLNode::newElement(root->getFilename(), String16(), String16("uses-sdk"));
899 root->insertChildAt(vers, 0);
900 }
901
902 if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "minSdkVersion",
903 bundle->getMinSdkVersion(), errorOnFailedInsert)) {
904 return UNKNOWN_ERROR;
905 }
906 if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "targetSdkVersion",
907 bundle->getTargetSdkVersion(), errorOnFailedInsert)) {
908 return UNKNOWN_ERROR;
909 }
910 if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "maxSdkVersion",
911 bundle->getMaxSdkVersion(), errorOnFailedInsert)) {
912 return UNKNOWN_ERROR;
913 }
914 }
915
916 if (vers != NULL) {
917 const XMLNode::attribute_entry* attr = vers->getAttribute(
918 String16(RESOURCES_ANDROID_NAMESPACE), String16("minSdkVersion"));
919 if (attr != NULL) {
920 bundle->setMinSdkVersion(strdup(String8(attr->string).c_str()));
921 }
922 }
923
924
925 if (bundle->getCompileSdkVersion() != 0) {
926 if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "compileSdkVersion",
927 String8::format("%d", bundle->getCompileSdkVersion()).c_str(),
928 errorOnFailedInsert, true)) {
929 return UNKNOWN_ERROR;
930 }
931 }
932
933 if (bundle->getCompileSdkVersionCodename() != "") {
934 if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "compileSdkVersionCodename",
935 bundle->getCompileSdkVersionCodename().c_str(), errorOnFailedInsert, true)) {
936 return UNKNOWN_ERROR;
937 }
938 }
939
940 if (bundle->getPlatformBuildVersionCode() != "") {
941 if (!addTagAttribute(root, "", "platformBuildVersionCode",
942 bundle->getPlatformBuildVersionCode().c_str(), errorOnFailedInsert, true)) {
943 return UNKNOWN_ERROR;
944 }
945 }
946
947 if (bundle->getPlatformBuildVersionName() != "") {
948 if (!addTagAttribute(root, "", "platformBuildVersionName",
949 bundle->getPlatformBuildVersionName().c_str(), errorOnFailedInsert, true)) {
950 return UNKNOWN_ERROR;
951 }
952 }
953
954 if (bundle->getDebugMode()) {
955 sp<XMLNode> application = root->getChildElement(String16(), String16("application"));
956 if (application != NULL) {
957 if (!addTagAttribute(application, RESOURCES_ANDROID_NAMESPACE, "debuggable", "true",
958 errorOnFailedInsert)) {
959 return UNKNOWN_ERROR;
960 }
961 }
962 }
963
964 // Deal with manifest package name overrides
965 const char* manifestPackageNameOverride = bundle->getManifestPackageNameOverride();
966 if (manifestPackageNameOverride != NULL) {
967 // Update the actual package name
968 XMLNode::attribute_entry* attr = root->editAttribute(String16(), String16("package"));
969 if (attr == NULL) {
970 fprintf(stderr, "package name is required with --rename-manifest-package.\n");
971 return UNKNOWN_ERROR;
972 }
973 String8 origPackage(attr->string);
974 attr->string = String16(manifestPackageNameOverride);
975 if (kIsDebug) {
976 printf("Overriding package '%s' to be '%s'\n", origPackage.c_str(),
977 manifestPackageNameOverride);
978 }
979
980 // Make class names fully qualified
981 sp<XMLNode> application = root->getChildElement(String16(), String16("application"));
982 if (application != NULL) {
983 fullyQualifyClassName(origPackage, application, String16("name"));
984 fullyQualifyClassName(origPackage, application, String16("backupAgent"));
985
986 Vector<sp<XMLNode> >& children = const_cast<Vector<sp<XMLNode> >&>(application->getChildren());
987 for (size_t i = 0; i < children.size(); i++) {
988 sp<XMLNode> child = children.editItemAt(i);
989 String8 tag(child->getElementName());
990 if (tag == "activity" || tag == "service" || tag == "receiver" || tag == "provider") {
991 fullyQualifyClassName(origPackage, child, String16("name"));
992 } else if (tag == "activity-alias") {
993 fullyQualifyClassName(origPackage, child, String16("name"));
994 fullyQualifyClassName(origPackage, child, String16("targetActivity"));
995 }
996 }
997 }
998 }
999
1000 // Deal with manifest package name overrides
1001 const char* instrumentationPackageNameOverride = bundle->getInstrumentationPackageNameOverride();
1002 if (instrumentationPackageNameOverride != NULL) {
1003 // Fix up instrumentation targets.
1004 Vector<sp<XMLNode> >& children = const_cast<Vector<sp<XMLNode> >&>(root->getChildren());
1005 for (size_t i = 0; i < children.size(); i++) {
1006 sp<XMLNode> child = children.editItemAt(i);
1007 String8 tag(child->getElementName());
1008 if (tag == "instrumentation") {
1009 XMLNode::attribute_entry* attr = child->editAttribute(
1010 String16(RESOURCES_ANDROID_NAMESPACE), String16("targetPackage"));
1011 if (attr != NULL) {
1012 attr->string = String16(instrumentationPackageNameOverride);
1013 }
1014 }
1015 }
1016 }
1017
1018 sp<XMLNode> application = root->getChildElement(String16(), String16("application"));
1019 if (application != NULL) {
1020 XMLNode::attribute_entry* icon_attr = application->editAttribute(
1021 String16(RESOURCES_ANDROID_NAMESPACE), String16("icon"));
1022 if (icon_attr != NULL) {
1023 XMLNode::attribute_entry* round_icon_attr = application->editAttribute(
1024 String16(RESOURCES_ANDROID_NAMESPACE), String16("roundIcon"));
1025 if (round_icon_attr != NULL) {
1026 massageRoundIconSupport(icon_attr->string, round_icon_attr->string, table);
1027 }
1028 }
1029 }
1030
1031 // Generate split name if feature is present.
1032 const XMLNode::attribute_entry* attr = root->getAttribute(String16(), String16("featureName"));
1033 if (attr != NULL) {
1034 String16 splitName("feature_");
1035 splitName.append(attr->string);
1036 status_t err = root->addAttribute(String16(), String16("split"), splitName);
1037 if (err != NO_ERROR) {
1038 ALOGE("Failed to insert split name into AndroidManifest.xml");
1039 return err;
1040 }
1041 }
1042
1043 return NO_ERROR;
1044 }
1045
getPlatformAssetCookie(const AssetManager & assets)1046 static int32_t getPlatformAssetCookie(const AssetManager& assets) {
1047 // Find the system package (0x01). AAPT always generates attributes
1048 // with the type 0x01, so we're looking for the first attribute
1049 // resource in the system package.
1050 const ResTable& table = assets.getResources(true);
1051 Res_value val;
1052 ssize_t idx = table.getResource(0x01010000, &val, true);
1053 if (idx != NO_ERROR) {
1054 // Try as a bag.
1055 const ResTable::bag_entry* entry;
1056 ssize_t cnt = table.lockBag(0x01010000, &entry);
1057 if (cnt >= 0) {
1058 idx = entry->stringBlock;
1059 }
1060 table.unlockBag(entry);
1061 }
1062
1063 if (idx < 0) {
1064 return 0;
1065 }
1066 return table.getTableCookie(idx);
1067 }
1068
1069 enum {
1070 VERSION_CODE_ATTR = 0x0101021b,
1071 VERSION_NAME_ATTR = 0x0101021c,
1072 };
1073
extractPlatformBuildVersion(const ResTable & table,ResXMLTree & tree,Bundle * bundle)1074 static ssize_t extractPlatformBuildVersion(const ResTable& table, ResXMLTree& tree, Bundle* bundle) {
1075 // First check if we should be recording the compileSdkVersion* attributes.
1076 static const String16 compileSdkVersionName("android:attr/compileSdkVersion");
1077 const bool useCompileSdkVersion = table.identifierForName(compileSdkVersionName.c_str(),
1078 compileSdkVersionName.size()) != 0u;
1079
1080 size_t len;
1081 ResXMLTree::event_code_t code;
1082 while ((code = tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1083 if (code != ResXMLTree::START_TAG) {
1084 continue;
1085 }
1086
1087 const char16_t* ctag16 = tree.getElementName(&len);
1088 if (ctag16 == NULL) {
1089 fprintf(stderr, "ERROR: failed to get XML element name (bad string pool)\n");
1090 return UNKNOWN_ERROR;
1091 }
1092
1093 String8 tag(ctag16, len);
1094 if (tag != "manifest") {
1095 continue;
1096 }
1097
1098 String8 error;
1099 int32_t versionCode = AaptXml::getIntegerAttribute(tree, VERSION_CODE_ATTR, &error);
1100 if (error != "") {
1101 fprintf(stderr, "ERROR: failed to get platform version code\n");
1102 return UNKNOWN_ERROR;
1103 }
1104
1105 if (versionCode >= 0 && bundle->getPlatformBuildVersionCode() == "") {
1106 bundle->setPlatformBuildVersionCode(String8::format("%d", versionCode));
1107 }
1108
1109 if (useCompileSdkVersion && versionCode >= 0 && bundle->getCompileSdkVersion() == 0) {
1110 bundle->setCompileSdkVersion(versionCode);
1111 }
1112
1113 String8 versionName = AaptXml::getAttribute(tree, VERSION_NAME_ATTR, &error);
1114 if (error != "") {
1115 fprintf(stderr, "ERROR: failed to get platform version name\n");
1116 return UNKNOWN_ERROR;
1117 }
1118
1119 if (versionName != "" && bundle->getPlatformBuildVersionName() == "") {
1120 bundle->setPlatformBuildVersionName(versionName);
1121 }
1122
1123 if (useCompileSdkVersion && versionName != ""
1124 && bundle->getCompileSdkVersionCodename() == "") {
1125 bundle->setCompileSdkVersionCodename(versionName);
1126 }
1127 return NO_ERROR;
1128 }
1129
1130 fprintf(stderr, "ERROR: no <manifest> tag found in platform AndroidManifest.xml\n");
1131 return UNKNOWN_ERROR;
1132 }
1133
extractPlatformBuildVersion(AssetManager & assets,Bundle * bundle)1134 static ssize_t extractPlatformBuildVersion(AssetManager& assets, Bundle* bundle) {
1135 int32_t cookie = getPlatformAssetCookie(assets);
1136 if (cookie == 0) {
1137 // No platform was loaded.
1138 return NO_ERROR;
1139 }
1140
1141 Asset* asset = assets.openNonAsset(cookie, "AndroidManifest.xml", Asset::ACCESS_STREAMING);
1142 if (asset == NULL) {
1143 fprintf(stderr, "ERROR: Platform AndroidManifest.xml not found\n");
1144 return UNKNOWN_ERROR;
1145 }
1146
1147 ssize_t result = NO_ERROR;
1148
1149 // Create a new scope so that ResXMLTree is destroyed before we delete the memory over
1150 // which it iterates (asset).
1151 {
1152 ResXMLTree tree;
1153 if (tree.setTo(asset->getBuffer(true), asset->getLength()) != NO_ERROR) {
1154 fprintf(stderr, "ERROR: Platform AndroidManifest.xml is corrupt\n");
1155 result = UNKNOWN_ERROR;
1156 } else {
1157 result = extractPlatformBuildVersion(assets.getResources(true), tree, bundle);
1158 }
1159 }
1160
1161 delete asset;
1162 return result;
1163 }
1164
1165 #define ASSIGN_IT(n) \
1166 do { \
1167 ssize_t index = resources->indexOfKey(String8(#n)); \
1168 if (index >= 0) { \
1169 n ## s = resources->valueAt(index); \
1170 } \
1171 } while (0)
1172
updatePreProcessedCache(Bundle * bundle)1173 status_t updatePreProcessedCache(Bundle* bundle)
1174 {
1175 #if BENCHMARK
1176 fprintf(stdout, "BENCHMARK: Starting PNG PreProcessing \n");
1177 long startPNGTime = clock();
1178 #endif /* BENCHMARK */
1179
1180 String8 source(bundle->getResourceSourceDirs()[0]);
1181 String8 dest(bundle->getCrunchedOutputDir());
1182
1183 FileFinder* ff = new SystemFileFinder();
1184 CrunchCache cc(source,dest,ff);
1185
1186 CacheUpdater* cu = new SystemCacheUpdater(bundle);
1187 size_t numFiles = cc.crunch(cu);
1188
1189 if (bundle->getVerbose())
1190 fprintf(stdout, "Crunched %d PNG files to update cache\n", (int)numFiles);
1191
1192 delete ff;
1193 delete cu;
1194
1195 #if BENCHMARK
1196 fprintf(stdout, "BENCHMARK: End PNG PreProcessing. Time Elapsed: %f ms \n"
1197 ,(clock() - startPNGTime)/1000.0);
1198 #endif /* BENCHMARK */
1199 return 0;
1200 }
1201
generateAndroidManifestForSplit(Bundle * bundle,const sp<AaptAssets> & assets,const sp<ApkSplit> & split,sp<AaptFile> & outFile,ResourceTable * table)1202 status_t generateAndroidManifestForSplit(Bundle* bundle, const sp<AaptAssets>& assets,
1203 const sp<ApkSplit>& split, sp<AaptFile>& outFile, ResourceTable* table) {
1204 const String8 filename("AndroidManifest.xml");
1205 const String16 androidPrefix("android");
1206 const String16 androidNSUri("http://schemas.android.com/apk/res/android");
1207 sp<XMLNode> root = XMLNode::newNamespace(filename, androidPrefix, androidNSUri);
1208
1209 // Build the <manifest> tag
1210 sp<XMLNode> manifest = XMLNode::newElement(filename, String16(), String16("manifest"));
1211
1212 // Add the 'package' attribute which is set to the package name.
1213 const char* packageName = assets->getPackage().c_str();
1214 const char* manifestPackageNameOverride = bundle->getManifestPackageNameOverride();
1215 if (manifestPackageNameOverride != NULL) {
1216 packageName = manifestPackageNameOverride;
1217 }
1218 manifest->addAttribute(String16(), String16("package"), String16(packageName));
1219
1220 // Add the 'versionCode' attribute which is set to the original version code.
1221 if (!addTagAttribute(manifest, RESOURCES_ANDROID_NAMESPACE, "versionCode",
1222 bundle->getVersionCode(), true, true)) {
1223 return UNKNOWN_ERROR;
1224 }
1225
1226 // Add the 'revisionCode' attribute, which is set to the original revisionCode.
1227 if (bundle->getRevisionCode().size() > 0) {
1228 if (!addTagAttribute(manifest, RESOURCES_ANDROID_NAMESPACE, "revisionCode",
1229 bundle->getRevisionCode().c_str(), true, true)) {
1230 return UNKNOWN_ERROR;
1231 }
1232 }
1233
1234 // Add the 'split' attribute which describes the configurations included.
1235 String8 splitName("config.");
1236 splitName.append(split->getPackageSafeName());
1237 manifest->addAttribute(String16(), String16("split"), String16(splitName));
1238
1239 // Build an empty <application> tag (required).
1240 sp<XMLNode> app = XMLNode::newElement(filename, String16(), String16("application"));
1241
1242 // Add the 'hasCode' attribute which is never true for resource splits.
1243 if (!addTagAttribute(app, RESOURCES_ANDROID_NAMESPACE, "hasCode",
1244 "false", true, true)) {
1245 return UNKNOWN_ERROR;
1246 }
1247
1248 manifest->addChild(app);
1249 root->addChild(manifest);
1250
1251 int err = compileXmlFile(bundle, assets, String16(), root, outFile, table);
1252 if (err < NO_ERROR) {
1253 return err;
1254 }
1255 outFile->setCompressionMethod(ZipEntry::kCompressDeflated);
1256 return NO_ERROR;
1257 }
1258
buildResources(Bundle * bundle,const sp<AaptAssets> & assets,sp<ApkBuilder> & builder)1259 status_t buildResources(Bundle* bundle, const sp<AaptAssets>& assets, sp<ApkBuilder>& builder)
1260 {
1261 // First, look for a package file to parse. This is required to
1262 // be able to generate the resource information.
1263 sp<AaptGroup> androidManifestFile =
1264 assets->getFiles().valueFor(String8("AndroidManifest.xml"));
1265 if (androidManifestFile == NULL) {
1266 fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n");
1267 return UNKNOWN_ERROR;
1268 }
1269
1270 status_t err = parsePackage(bundle, assets, androidManifestFile);
1271 if (err != NO_ERROR) {
1272 return err;
1273 }
1274
1275 if (kIsDebug) {
1276 printf("Creating resources for package %s\n", assets->getPackage().c_str());
1277 }
1278
1279 // Set the private symbols package if it was declared.
1280 // This can also be declared in XML as <private-symbols name="package" />
1281 if (bundle->getPrivateSymbolsPackage().size() != 0) {
1282 assets->setSymbolsPrivatePackage(bundle->getPrivateSymbolsPackage());
1283 }
1284
1285 ResourceTable::PackageType packageType = ResourceTable::App;
1286 if (bundle->getBuildSharedLibrary()) {
1287 packageType = ResourceTable::SharedLibrary;
1288 } else if (bundle->getExtending()) {
1289 packageType = ResourceTable::System;
1290 } else if (!bundle->getFeatureOfPackage().empty()) {
1291 packageType = ResourceTable::AppFeature;
1292 }
1293
1294 ResourceTable table(bundle, String16(assets->getPackage()), packageType);
1295 err = table.addIncludedResources(bundle, assets);
1296 if (err != NO_ERROR) {
1297 return err;
1298 }
1299
1300 if (kIsDebug) {
1301 printf("Found %d included resource packages\n", (int)table.size());
1302 }
1303
1304 // Standard flags for compiled XML and optional UTF-8 encoding
1305 int xmlFlags = XML_COMPILE_STANDARD_RESOURCE;
1306
1307 /* Only enable UTF-8 if the caller of aapt didn't specifically
1308 * request UTF-16 encoding and the parameters of this package
1309 * allow UTF-8 to be used.
1310 */
1311 if (!bundle->getUTF16StringsOption()) {
1312 xmlFlags |= XML_COMPILE_UTF8;
1313 }
1314
1315 // --------------------------------------------------------------
1316 // First, gather all resource information.
1317 // --------------------------------------------------------------
1318
1319 // resType -> leafName -> group
1320 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
1321 new KeyedVector<String8, sp<ResourceTypeSet> >;
1322 collect_files(assets, resources);
1323
1324 sp<ResourceTypeSet> drawables;
1325 sp<ResourceTypeSet> layouts;
1326 sp<ResourceTypeSet> anims;
1327 sp<ResourceTypeSet> animators;
1328 sp<ResourceTypeSet> interpolators;
1329 sp<ResourceTypeSet> transitions;
1330 sp<ResourceTypeSet> xmls;
1331 sp<ResourceTypeSet> raws;
1332 sp<ResourceTypeSet> colors;
1333 sp<ResourceTypeSet> menus;
1334 sp<ResourceTypeSet> mipmaps;
1335 sp<ResourceTypeSet> fonts;
1336
1337 ASSIGN_IT(drawable);
1338 ASSIGN_IT(layout);
1339 ASSIGN_IT(anim);
1340 ASSIGN_IT(animator);
1341 ASSIGN_IT(interpolator);
1342 ASSIGN_IT(transition);
1343 ASSIGN_IT(xml);
1344 ASSIGN_IT(raw);
1345 ASSIGN_IT(color);
1346 ASSIGN_IT(menu);
1347 ASSIGN_IT(mipmap);
1348 ASSIGN_IT(font);
1349
1350 assets->setResources(resources);
1351 // now go through any resource overlays and collect their files
1352 sp<AaptAssets> current = assets->getOverlay();
1353 while(current.get()) {
1354 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
1355 new KeyedVector<String8, sp<ResourceTypeSet> >;
1356 current->setResources(resources);
1357 collect_files(current, resources);
1358 current = current->getOverlay();
1359 }
1360 // apply the overlay files to the base set
1361 if (!applyFileOverlay(bundle, assets, &drawables, "drawable") ||
1362 !applyFileOverlay(bundle, assets, &layouts, "layout") ||
1363 !applyFileOverlay(bundle, assets, &anims, "anim") ||
1364 !applyFileOverlay(bundle, assets, &animators, "animator") ||
1365 !applyFileOverlay(bundle, assets, &interpolators, "interpolator") ||
1366 !applyFileOverlay(bundle, assets, &transitions, "transition") ||
1367 !applyFileOverlay(bundle, assets, &xmls, "xml") ||
1368 !applyFileOverlay(bundle, assets, &raws, "raw") ||
1369 !applyFileOverlay(bundle, assets, &colors, "color") ||
1370 !applyFileOverlay(bundle, assets, &menus, "menu") ||
1371 !applyFileOverlay(bundle, assets, &fonts, "font") ||
1372 !applyFileOverlay(bundle, assets, &mipmaps, "mipmap")) {
1373 return UNKNOWN_ERROR;
1374 }
1375
1376 bool hasErrors = false;
1377
1378 if (drawables != NULL) {
1379 if (bundle->getOutputAPKFile() != NULL) {
1380 err = preProcessImages(bundle, assets, drawables, "drawable");
1381 }
1382 if (err == NO_ERROR) {
1383 err = makeFileResources(bundle, assets, &table, drawables, "drawable");
1384 if (err != NO_ERROR) {
1385 hasErrors = true;
1386 }
1387 } else {
1388 hasErrors = true;
1389 }
1390 }
1391
1392 if (mipmaps != NULL) {
1393 if (bundle->getOutputAPKFile() != NULL) {
1394 err = preProcessImages(bundle, assets, mipmaps, "mipmap");
1395 }
1396 if (err == NO_ERROR) {
1397 err = makeFileResources(bundle, assets, &table, mipmaps, "mipmap");
1398 if (err != NO_ERROR) {
1399 hasErrors = true;
1400 }
1401 } else {
1402 hasErrors = true;
1403 }
1404 }
1405
1406 if (fonts != NULL) {
1407 err = makeFileResources(bundle, assets, &table, fonts, "font");
1408 if (err != NO_ERROR) {
1409 hasErrors = true;
1410 }
1411 }
1412
1413 if (layouts != NULL) {
1414 err = makeFileResources(bundle, assets, &table, layouts, "layout");
1415 if (err != NO_ERROR) {
1416 hasErrors = true;
1417 }
1418 }
1419
1420 if (anims != NULL) {
1421 err = makeFileResources(bundle, assets, &table, anims, "anim");
1422 if (err != NO_ERROR) {
1423 hasErrors = true;
1424 }
1425 }
1426
1427 if (animators != NULL) {
1428 err = makeFileResources(bundle, assets, &table, animators, "animator");
1429 if (err != NO_ERROR) {
1430 hasErrors = true;
1431 }
1432 }
1433
1434 if (transitions != NULL) {
1435 err = makeFileResources(bundle, assets, &table, transitions, "transition");
1436 if (err != NO_ERROR) {
1437 hasErrors = true;
1438 }
1439 }
1440
1441 if (interpolators != NULL) {
1442 err = makeFileResources(bundle, assets, &table, interpolators, "interpolator");
1443 if (err != NO_ERROR) {
1444 hasErrors = true;
1445 }
1446 }
1447
1448 if (xmls != NULL) {
1449 err = makeFileResources(bundle, assets, &table, xmls, "xml");
1450 if (err != NO_ERROR) {
1451 hasErrors = true;
1452 }
1453 }
1454
1455 if (raws != NULL) {
1456 err = makeFileResources(bundle, assets, &table, raws, "raw");
1457 if (err != NO_ERROR) {
1458 hasErrors = true;
1459 }
1460 }
1461
1462 // compile resources
1463 current = assets;
1464 while(current.get()) {
1465 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
1466 current->getResources();
1467
1468 ssize_t index = resources->indexOfKey(String8("values"));
1469 if (index >= 0) {
1470 ResourceDirIterator it(resources->valueAt(index), String8("values"));
1471 ssize_t res;
1472 while ((res=it.next()) == NO_ERROR) {
1473 const sp<AaptFile>& file = it.getFile();
1474 res = compileResourceFile(bundle, assets, file, it.getParams(),
1475 (current!=assets), &table);
1476 if (res != NO_ERROR) {
1477 hasErrors = true;
1478 }
1479 }
1480 }
1481 current = current->getOverlay();
1482 }
1483
1484 if (colors != NULL) {
1485 err = makeFileResources(bundle, assets, &table, colors, "color");
1486 if (err != NO_ERROR) {
1487 hasErrors = true;
1488 }
1489 }
1490
1491 if (menus != NULL) {
1492 err = makeFileResources(bundle, assets, &table, menus, "menu");
1493 if (err != NO_ERROR) {
1494 hasErrors = true;
1495 }
1496 }
1497
1498 if (hasErrors) {
1499 return UNKNOWN_ERROR;
1500 }
1501
1502 // --------------------------------------------------------------------
1503 // Assignment of resource IDs and initial generation of resource table.
1504 // --------------------------------------------------------------------
1505
1506 if (table.hasResources()) {
1507 err = table.assignResourceIds();
1508 if (err < NO_ERROR) {
1509 return err;
1510 }
1511 }
1512
1513 // --------------------------------------------------------------
1514 // Finally, we can now we can compile XML files, which may reference
1515 // resources.
1516 // --------------------------------------------------------------
1517
1518 if (layouts != NULL) {
1519 ResourceDirIterator it(layouts, String8("layout"));
1520 while ((err=it.next()) == NO_ERROR) {
1521 String8 src = it.getFile()->getPrintableSource();
1522 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1523 it.getFile(), &table, xmlFlags);
1524 // Only verify IDs if there was no error and the file is non-empty.
1525 if (err == NO_ERROR && it.getFile()->hasData()) {
1526 ResXMLTree block;
1527 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
1528 checkForIds(src, block);
1529 } else {
1530 hasErrors = true;
1531 }
1532 }
1533
1534 if (err < NO_ERROR) {
1535 hasErrors = true;
1536 }
1537 err = NO_ERROR;
1538 }
1539
1540 if (anims != NULL) {
1541 ResourceDirIterator it(anims, String8("anim"));
1542 while ((err=it.next()) == NO_ERROR) {
1543 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1544 it.getFile(), &table, xmlFlags);
1545 if (err != NO_ERROR) {
1546 hasErrors = true;
1547 }
1548 }
1549
1550 if (err < NO_ERROR) {
1551 hasErrors = true;
1552 }
1553 err = NO_ERROR;
1554 }
1555
1556 if (animators != NULL) {
1557 ResourceDirIterator it(animators, String8("animator"));
1558 while ((err=it.next()) == NO_ERROR) {
1559 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1560 it.getFile(), &table, xmlFlags);
1561 if (err != NO_ERROR) {
1562 hasErrors = true;
1563 }
1564 }
1565
1566 if (err < NO_ERROR) {
1567 hasErrors = true;
1568 }
1569 err = NO_ERROR;
1570 }
1571
1572 if (interpolators != NULL) {
1573 ResourceDirIterator it(interpolators, String8("interpolator"));
1574 while ((err=it.next()) == NO_ERROR) {
1575 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1576 it.getFile(), &table, xmlFlags);
1577 if (err != NO_ERROR) {
1578 hasErrors = true;
1579 }
1580 }
1581
1582 if (err < NO_ERROR) {
1583 hasErrors = true;
1584 }
1585 err = NO_ERROR;
1586 }
1587
1588 if (transitions != NULL) {
1589 ResourceDirIterator it(transitions, String8("transition"));
1590 while ((err=it.next()) == NO_ERROR) {
1591 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1592 it.getFile(), &table, xmlFlags);
1593 if (err != NO_ERROR) {
1594 hasErrors = true;
1595 }
1596 }
1597
1598 if (err < NO_ERROR) {
1599 hasErrors = true;
1600 }
1601 err = NO_ERROR;
1602 }
1603
1604 if (xmls != NULL) {
1605 ResourceDirIterator it(xmls, String8("xml"));
1606 while ((err=it.next()) == NO_ERROR) {
1607 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1608 it.getFile(), &table, xmlFlags);
1609 if (err != NO_ERROR) {
1610 hasErrors = true;
1611 }
1612 }
1613
1614 if (err < NO_ERROR) {
1615 hasErrors = true;
1616 }
1617 err = NO_ERROR;
1618 }
1619
1620 if (drawables != NULL) {
1621 ResourceDirIterator it(drawables, String8("drawable"));
1622 while ((err=it.next()) == NO_ERROR) {
1623 err = postProcessImage(bundle, assets, &table, it.getFile());
1624 if (err != NO_ERROR) {
1625 hasErrors = true;
1626 }
1627 }
1628
1629 if (err < NO_ERROR) {
1630 hasErrors = true;
1631 }
1632 err = NO_ERROR;
1633 }
1634
1635 if (mipmaps != NULL) {
1636 ResourceDirIterator it(mipmaps, String8("mipmap"));
1637 while ((err=it.next()) == NO_ERROR) {
1638 err = postProcessImage(bundle, assets, &table, it.getFile());
1639 if (err != NO_ERROR) {
1640 hasErrors = true;
1641 }
1642 }
1643
1644 if (err < NO_ERROR) {
1645 hasErrors = true;
1646 }
1647 err = NO_ERROR;
1648 }
1649
1650 if (colors != NULL) {
1651 ResourceDirIterator it(colors, String8("color"));
1652 while ((err=it.next()) == NO_ERROR) {
1653 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1654 it.getFile(), &table, xmlFlags);
1655 if (err != NO_ERROR) {
1656 hasErrors = true;
1657 }
1658 }
1659
1660 if (err < NO_ERROR) {
1661 hasErrors = true;
1662 }
1663 err = NO_ERROR;
1664 }
1665
1666 if (menus != NULL) {
1667 ResourceDirIterator it(menus, String8("menu"));
1668 while ((err=it.next()) == NO_ERROR) {
1669 String8 src = it.getFile()->getPrintableSource();
1670 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1671 it.getFile(), &table, xmlFlags);
1672 if (err == NO_ERROR && it.getFile()->hasData()) {
1673 ResXMLTree block;
1674 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
1675 checkForIds(src, block);
1676 } else {
1677 hasErrors = true;
1678 }
1679 }
1680
1681 if (err < NO_ERROR) {
1682 hasErrors = true;
1683 }
1684 err = NO_ERROR;
1685 }
1686
1687 if (fonts != NULL) {
1688 ResourceDirIterator it(fonts, String8("font"));
1689 while ((err=it.next()) == NO_ERROR) {
1690 // fonts can be resources other than xml.
1691 if (getPathExtension(it.getFile()->getPath()) == ".xml") {
1692 String8 src = it.getFile()->getPrintableSource();
1693 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1694 it.getFile(), &table, xmlFlags);
1695 if (err != NO_ERROR) {
1696 hasErrors = true;
1697 }
1698 }
1699 }
1700
1701 if (err < NO_ERROR) {
1702 hasErrors = true;
1703 }
1704 err = NO_ERROR;
1705 }
1706
1707 // Now compile any generated resources.
1708 std::queue<CompileResourceWorkItem>& workQueue = table.getWorkQueue();
1709 while (!workQueue.empty()) {
1710 CompileResourceWorkItem& workItem = workQueue.front();
1711 int xmlCompilationFlags = xmlFlags | XML_COMPILE_PARSE_VALUES
1712 | XML_COMPILE_ASSIGN_ATTRIBUTE_IDS;
1713 if (!workItem.needsCompiling) {
1714 xmlCompilationFlags &= ~XML_COMPILE_ASSIGN_ATTRIBUTE_IDS;
1715 xmlCompilationFlags &= ~XML_COMPILE_PARSE_VALUES;
1716 }
1717 err = compileXmlFile(bundle, assets, workItem.resourceName, workItem.xmlRoot,
1718 workItem.file, &table, xmlCompilationFlags);
1719
1720 if (err == NO_ERROR && workItem.file->hasData()) {
1721 assets->addResource(getPathLeaf(workItem.resPath),
1722 workItem.resPath,
1723 workItem.file,
1724 workItem.file->getResourceType());
1725 } else {
1726 hasErrors = true;
1727 }
1728 workQueue.pop();
1729 }
1730
1731 if (table.validateLocalizations()) {
1732 hasErrors = true;
1733 }
1734
1735 if (hasErrors) {
1736 return UNKNOWN_ERROR;
1737 }
1738
1739 // If we're not overriding the platform build versions,
1740 // extract them from the platform APK.
1741 if (packageType != ResourceTable::System &&
1742 (bundle->getPlatformBuildVersionCode() == "" ||
1743 bundle->getPlatformBuildVersionName() == "" ||
1744 bundle->getCompileSdkVersion() == 0 ||
1745 bundle->getCompileSdkVersionCodename() == "")) {
1746 err = extractPlatformBuildVersion(assets->getAssetManager(), bundle);
1747 if (err != NO_ERROR) {
1748 return UNKNOWN_ERROR;
1749 }
1750 }
1751
1752 const sp<AaptFile> manifestFile(androidManifestFile->getFiles().valueAt(0));
1753 String8 manifestPath(manifestFile->getPrintableSource());
1754
1755 // Generate final compiled manifest file.
1756 manifestFile->clearData();
1757 sp<XMLNode> manifestTree = XMLNode::parse(manifestFile);
1758 if (manifestTree == NULL) {
1759 return UNKNOWN_ERROR;
1760 }
1761 err = massageManifest(bundle, &table, manifestTree);
1762 if (err < NO_ERROR) {
1763 return err;
1764 }
1765 err = compileXmlFile(bundle, assets, String16(), manifestTree, manifestFile, &table);
1766 if (err < NO_ERROR) {
1767 return err;
1768 }
1769
1770 if (table.modifyForCompat(bundle) != NO_ERROR) {
1771 return UNKNOWN_ERROR;
1772 }
1773
1774 //block.restart();
1775 //printXMLBlock(&block);
1776
1777 // --------------------------------------------------------------
1778 // Generate the final resource table.
1779 // Re-flatten because we may have added new resource IDs
1780 // --------------------------------------------------------------
1781
1782
1783 ResTable finalResTable;
1784 sp<AaptFile> resFile;
1785
1786 if (table.hasResources()) {
1787 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1788 err = table.addSymbols(symbols, bundle->getSkipSymbolsWithoutDefaultLocalization());
1789 if (err < NO_ERROR) {
1790 return err;
1791 }
1792
1793 KeyedVector<Symbol, Vector<SymbolDefinition> > densityVaryingResources;
1794 if (builder->getSplits().size() > 1) {
1795 // Only look for density varying resources if we're generating
1796 // splits.
1797 table.getDensityVaryingResources(densityVaryingResources);
1798 }
1799
1800 Vector<sp<ApkSplit> >& splits = builder->getSplits();
1801 const size_t numSplits = splits.size();
1802 for (size_t i = 0; i < numSplits; i++) {
1803 sp<ApkSplit>& split = splits.editItemAt(i);
1804 sp<AaptFile> flattenedTable = new AaptFile(String8("resources.arsc"),
1805 AaptGroupEntry(), String8());
1806 err = table.flatten(bundle, split->getResourceFilter(),
1807 flattenedTable, split->isBase());
1808 if (err != NO_ERROR) {
1809 fprintf(stderr, "Failed to generate resource table for split '%s'\n",
1810 split->getPrintableName().c_str());
1811 return err;
1812 }
1813 split->addEntry(String8("resources.arsc"), flattenedTable);
1814
1815 if (split->isBase()) {
1816 resFile = flattenedTable;
1817 err = finalResTable.add(flattenedTable->getData(), flattenedTable->getSize());
1818 if (err != NO_ERROR) {
1819 fprintf(stderr, "Generated resource table is corrupt.\n");
1820 return err;
1821 }
1822 } else {
1823 ResTable resTable;
1824 err = resTable.add(flattenedTable->getData(), flattenedTable->getSize());
1825 if (err != NO_ERROR) {
1826 fprintf(stderr, "Generated resource table for split '%s' is corrupt.\n",
1827 split->getPrintableName().c_str());
1828 return err;
1829 }
1830
1831 bool hasError = false;
1832 const std::set<ConfigDescription>& splitConfigs = split->getConfigs();
1833 for (std::set<ConfigDescription>::const_iterator iter = splitConfigs.begin();
1834 iter != splitConfigs.end();
1835 ++iter) {
1836 const ConfigDescription& config = *iter;
1837 if (AaptConfig::isDensityOnly(config)) {
1838 // Each density only split must contain all
1839 // density only resources.
1840 Res_value val;
1841 resTable.setParameters(&config);
1842 const size_t densityVaryingResourceCount = densityVaryingResources.size();
1843 for (size_t k = 0; k < densityVaryingResourceCount; k++) {
1844 const Symbol& symbol = densityVaryingResources.keyAt(k);
1845 ssize_t block = resTable.getResource(symbol.id, &val, true);
1846 if (block < 0) {
1847 // Maybe it's in the base?
1848 finalResTable.setParameters(&config);
1849 block = finalResTable.getResource(symbol.id, &val, true);
1850 }
1851
1852 if (block < 0) {
1853 hasError = true;
1854 SourcePos().error("%s has no definition for density split '%s'",
1855 symbol.toString().c_str(), config.toString().c_str());
1856
1857 if (bundle->getVerbose()) {
1858 const Vector<SymbolDefinition>& defs = densityVaryingResources[k];
1859 const size_t defCount = std::min(size_t(5), defs.size());
1860 for (size_t d = 0; d < defCount; d++) {
1861 const SymbolDefinition& def = defs[d];
1862 def.source.error("%s has definition for %s",
1863 symbol.toString().c_str(), def.config.toString().c_str());
1864 }
1865
1866 if (defCount < defs.size()) {
1867 SourcePos().error("and %d more ...", (int) (defs.size() - defCount));
1868 }
1869 }
1870 }
1871 }
1872 }
1873 }
1874
1875 if (hasError) {
1876 return UNKNOWN_ERROR;
1877 }
1878
1879 // Generate the AndroidManifest for this split.
1880 sp<AaptFile> generatedManifest = new AaptFile(String8("AndroidManifest.xml"),
1881 AaptGroupEntry(), String8());
1882 err = generateAndroidManifestForSplit(bundle, assets, split,
1883 generatedManifest, &table);
1884 if (err != NO_ERROR) {
1885 fprintf(stderr, "Failed to generate AndroidManifest.xml for split '%s'\n",
1886 split->getPrintableName().c_str());
1887 return err;
1888 }
1889 split->addEntry(String8("AndroidManifest.xml"), generatedManifest);
1890 }
1891 }
1892
1893 if (bundle->getPublicOutputFile()) {
1894 FILE* fp = fopen(bundle->getPublicOutputFile(), "w+");
1895 if (fp == NULL) {
1896 fprintf(stderr, "ERROR: Unable to open public definitions output file %s: %s\n",
1897 (const char*)bundle->getPublicOutputFile(), strerror(errno));
1898 return UNKNOWN_ERROR;
1899 }
1900 if (bundle->getVerbose()) {
1901 printf(" Writing public definitions to %s.\n", bundle->getPublicOutputFile());
1902 }
1903 table.writePublicDefinitions(String16(assets->getPackage()), fp);
1904 fclose(fp);
1905 }
1906
1907 if (finalResTable.getTableCount() == 0 || resFile == NULL) {
1908 fprintf(stderr, "No resource table was generated.\n");
1909 return UNKNOWN_ERROR;
1910 }
1911 }
1912
1913 // Perform a basic validation of the manifest file. This time we
1914 // parse it with the comments intact, so that we can use them to
1915 // generate java docs... so we are not going to write this one
1916 // back out to the final manifest data.
1917 sp<AaptFile> outManifestFile = new AaptFile(manifestFile->getSourceFile(),
1918 manifestFile->getGroupEntry(),
1919 manifestFile->getResourceType());
1920 err = compileXmlFile(bundle, assets, String16(), manifestFile,
1921 outManifestFile, &table, XML_COMPILE_STANDARD_RESOURCE & ~XML_COMPILE_STRIP_COMMENTS);
1922 if (err < NO_ERROR) {
1923 return err;
1924 }
1925 ResXMLTree block;
1926 block.setTo(outManifestFile->getData(), outManifestFile->getSize(), true);
1927 String16 manifest16("manifest");
1928 String16 permission16("permission");
1929 String16 permission_group16("permission-group");
1930 String16 uses_permission16("uses-permission");
1931 String16 instrumentation16("instrumentation");
1932 String16 application16("application");
1933 String16 provider16("provider");
1934 String16 service16("service");
1935 String16 receiver16("receiver");
1936 String16 activity16("activity");
1937 String16 action16("action");
1938 String16 category16("category");
1939 String16 data16("scheme");
1940 String16 feature_group16("feature-group");
1941 String16 uses_feature16("uses-feature");
1942 const char* packageIdentChars = "abcdefghijklmnopqrstuvwxyz"
1943 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789";
1944 const char* packageIdentCharsWithTheStupid = "abcdefghijklmnopqrstuvwxyz"
1945 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
1946 const char* classIdentChars = "abcdefghijklmnopqrstuvwxyz"
1947 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789$";
1948 const char* processIdentChars = "abcdefghijklmnopqrstuvwxyz"
1949 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:";
1950 const char* authoritiesIdentChars = "abcdefghijklmnopqrstuvwxyz"
1951 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-:;";
1952 const char* typeIdentChars = "abcdefghijklmnopqrstuvwxyz"
1953 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:-/*+";
1954 const char* schemeIdentChars = "abcdefghijklmnopqrstuvwxyz"
1955 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
1956 ResXMLTree::event_code_t code;
1957 sp<AaptSymbols> permissionSymbols;
1958 sp<AaptSymbols> permissionGroupSymbols;
1959 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1960 && code > ResXMLTree::BAD_DOCUMENT) {
1961 if (code == ResXMLTree::START_TAG) {
1962 size_t len;
1963 if (block.getElementNamespace(&len) != NULL) {
1964 continue;
1965 }
1966 if (strcmp16(block.getElementName(&len), manifest16.c_str()) == 0) {
1967 if (validateAttr(manifestPath, finalResTable, block, NULL, "package",
1968 packageIdentChars, true) != ATTR_OKAY) {
1969 hasErrors = true;
1970 }
1971 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1972 "sharedUserId", packageIdentChars, false) != ATTR_OKAY) {
1973 hasErrors = true;
1974 }
1975 } else if (strcmp16(block.getElementName(&len), permission16.c_str()) == 0
1976 || strcmp16(block.getElementName(&len), permission_group16.c_str()) == 0) {
1977 const bool isGroup = strcmp16(block.getElementName(&len),
1978 permission_group16.c_str()) == 0;
1979 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1980 "name", isGroup ? packageIdentCharsWithTheStupid
1981 : packageIdentChars, true) != ATTR_OKAY) {
1982 hasErrors = true;
1983 }
1984 SourcePos srcPos(manifestPath, block.getLineNumber());
1985 sp<AaptSymbols> syms;
1986 if (!isGroup) {
1987 syms = permissionSymbols;
1988 if (syms == NULL) {
1989 sp<AaptSymbols> symbols =
1990 assets->getSymbolsFor(String8("Manifest"));
1991 syms = permissionSymbols = symbols->addNestedSymbol(
1992 String8("permission"), srcPos);
1993 }
1994 } else {
1995 syms = permissionGroupSymbols;
1996 if (syms == NULL) {
1997 sp<AaptSymbols> symbols =
1998 assets->getSymbolsFor(String8("Manifest"));
1999 syms = permissionGroupSymbols = symbols->addNestedSymbol(
2000 String8("permission_group"), srcPos);
2001 }
2002 }
2003 size_t len;
2004 ssize_t index = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "name");
2005 const char16_t* id = block.getAttributeStringValue(index, &len);
2006 if (id == NULL) {
2007 fprintf(stderr, "%s:%d: missing name attribute in element <%s>.\n",
2008 manifestPath.c_str(), block.getLineNumber(),
2009 String8(block.getElementName(&len)).c_str());
2010 hasErrors = true;
2011 break;
2012 }
2013 String8 idStr(id);
2014 char* p = idStr.lockBuffer(idStr.size());
2015 char* e = p + idStr.size();
2016 bool begins_with_digit = true; // init to true so an empty string fails
2017 while (e > p) {
2018 e--;
2019 if (*e >= '0' && *e <= '9') {
2020 begins_with_digit = true;
2021 continue;
2022 }
2023 if ((*e >= 'a' && *e <= 'z') ||
2024 (*e >= 'A' && *e <= 'Z') ||
2025 (*e == '_')) {
2026 begins_with_digit = false;
2027 continue;
2028 }
2029 if (isGroup && (*e == '-')) {
2030 *e = '_';
2031 begins_with_digit = false;
2032 continue;
2033 }
2034 e++;
2035 break;
2036 }
2037 idStr.unlockBuffer();
2038 // verify that we stopped because we hit a period or
2039 // the beginning of the string, and that the
2040 // identifier didn't begin with a digit.
2041 if (begins_with_digit || (e != p && *(e-1) != '.')) {
2042 fprintf(stderr,
2043 "%s:%d: Permission name <%s> is not a valid Java symbol\n",
2044 manifestPath.c_str(), block.getLineNumber(), idStr.c_str());
2045 hasErrors = true;
2046 }
2047 syms->addStringSymbol(String8(e), idStr, srcPos);
2048 const char16_t* cmt = block.getComment(&len);
2049 if (cmt != NULL && *cmt != 0) {
2050 //printf("Comment of %s: %s\n", String8(e).c_str(),
2051 // String8(cmt).c_str());
2052 syms->appendComment(String8(e), String16(cmt), srcPos);
2053 }
2054 syms->makeSymbolPublic(String8(e), srcPos);
2055 } else if (strcmp16(block.getElementName(&len), uses_permission16.c_str()) == 0) {
2056 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
2057 "name", packageIdentChars, true) != ATTR_OKAY) {
2058 hasErrors = true;
2059 }
2060 } else if (strcmp16(block.getElementName(&len), instrumentation16.c_str()) == 0) {
2061 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
2062 "name", classIdentChars, true) != ATTR_OKAY) {
2063 hasErrors = true;
2064 }
2065 if (validateAttr(manifestPath, finalResTable, block,
2066 RESOURCES_ANDROID_NAMESPACE, "targetPackage",
2067 packageIdentChars, true) != ATTR_OKAY) {
2068 hasErrors = true;
2069 }
2070 } else if (strcmp16(block.getElementName(&len), application16.c_str()) == 0) {
2071 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
2072 "name", classIdentChars, false) != ATTR_OKAY) {
2073 hasErrors = true;
2074 }
2075 if (validateAttr(manifestPath, finalResTable, block,
2076 RESOURCES_ANDROID_NAMESPACE, "permission",
2077 packageIdentChars, false) != ATTR_OKAY) {
2078 hasErrors = true;
2079 }
2080 if (validateAttr(manifestPath, finalResTable, block,
2081 RESOURCES_ANDROID_NAMESPACE, "process",
2082 processIdentChars, false) != ATTR_OKAY) {
2083 hasErrors = true;
2084 }
2085 if (validateAttr(manifestPath, finalResTable, block,
2086 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
2087 processIdentChars, false) != ATTR_OKAY) {
2088 hasErrors = true;
2089 }
2090 } else if (strcmp16(block.getElementName(&len), provider16.c_str()) == 0) {
2091 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
2092 "name", classIdentChars, true) != ATTR_OKAY) {
2093 hasErrors = true;
2094 }
2095 if (validateAttr(manifestPath, finalResTable, block,
2096 RESOURCES_ANDROID_NAMESPACE, "authorities",
2097 authoritiesIdentChars, true) != ATTR_OKAY) {
2098 hasErrors = true;
2099 }
2100 if (validateAttr(manifestPath, finalResTable, block,
2101 RESOURCES_ANDROID_NAMESPACE, "permission",
2102 packageIdentChars, false) != ATTR_OKAY) {
2103 hasErrors = true;
2104 }
2105 if (validateAttr(manifestPath, finalResTable, block,
2106 RESOURCES_ANDROID_NAMESPACE, "process",
2107 processIdentChars, false) != ATTR_OKAY) {
2108 hasErrors = true;
2109 }
2110 } else if (strcmp16(block.getElementName(&len), service16.c_str()) == 0
2111 || strcmp16(block.getElementName(&len), receiver16.c_str()) == 0
2112 || strcmp16(block.getElementName(&len), activity16.c_str()) == 0) {
2113 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
2114 "name", classIdentChars, true) != ATTR_OKAY) {
2115 hasErrors = true;
2116 }
2117 if (validateAttr(manifestPath, finalResTable, block,
2118 RESOURCES_ANDROID_NAMESPACE, "permission",
2119 packageIdentChars, false) != ATTR_OKAY) {
2120 hasErrors = true;
2121 }
2122 if (validateAttr(manifestPath, finalResTable, block,
2123 RESOURCES_ANDROID_NAMESPACE, "process",
2124 processIdentChars, false) != ATTR_OKAY) {
2125 hasErrors = true;
2126 }
2127 if (validateAttr(manifestPath, finalResTable, block,
2128 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
2129 processIdentChars, false) != ATTR_OKAY) {
2130 hasErrors = true;
2131 }
2132 } else if (strcmp16(block.getElementName(&len), action16.c_str()) == 0
2133 || strcmp16(block.getElementName(&len), category16.c_str()) == 0) {
2134 if (validateAttr(manifestPath, finalResTable, block,
2135 RESOURCES_ANDROID_NAMESPACE, "name",
2136 packageIdentChars, true) != ATTR_OKAY) {
2137 hasErrors = true;
2138 }
2139 } else if (strcmp16(block.getElementName(&len), data16.c_str()) == 0) {
2140 if (validateAttr(manifestPath, finalResTable, block,
2141 RESOURCES_ANDROID_NAMESPACE, "mimeType",
2142 typeIdentChars, true) != ATTR_OKAY) {
2143 hasErrors = true;
2144 }
2145 if (validateAttr(manifestPath, finalResTable, block,
2146 RESOURCES_ANDROID_NAMESPACE, "scheme",
2147 schemeIdentChars, true) != ATTR_OKAY) {
2148 hasErrors = true;
2149 }
2150 } else if (strcmp16(block.getElementName(&len), feature_group16.c_str()) == 0) {
2151 int depth = 1;
2152 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
2153 && code > ResXMLTree::BAD_DOCUMENT) {
2154 if (code == ResXMLTree::START_TAG) {
2155 depth++;
2156 if (strcmp16(block.getElementName(&len), uses_feature16.c_str()) == 0) {
2157 ssize_t idx = block.indexOfAttribute(
2158 RESOURCES_ANDROID_NAMESPACE, "required");
2159 if (idx < 0) {
2160 continue;
2161 }
2162
2163 int32_t data = block.getAttributeData(idx);
2164 if (data == 0) {
2165 fprintf(stderr, "%s:%d: Tag <uses-feature> can not have "
2166 "android:required=\"false\" when inside a "
2167 "<feature-group> tag.\n",
2168 manifestPath.c_str(), block.getLineNumber());
2169 hasErrors = true;
2170 }
2171 }
2172 } else if (code == ResXMLTree::END_TAG) {
2173 depth--;
2174 if (depth == 0) {
2175 break;
2176 }
2177 }
2178 }
2179 }
2180 }
2181 }
2182
2183 if (hasErrors) {
2184 return UNKNOWN_ERROR;
2185 }
2186
2187 if (resFile != NULL) {
2188 // These resources are now considered to be a part of the included
2189 // resources, for others to reference.
2190 err = assets->addIncludedResources(resFile);
2191 if (err < NO_ERROR) {
2192 fprintf(stderr, "ERROR: Unable to parse generated resources, aborting.\n");
2193 return err;
2194 }
2195 }
2196
2197 return err;
2198 }
2199
getIndentSpace(int indent)2200 static const char* getIndentSpace(int indent)
2201 {
2202 static const char whitespace[] =
2203 " ";
2204
2205 return whitespace + sizeof(whitespace) - 1 - indent*4;
2206 }
2207
flattenSymbol(const String8 & symbol)2208 static String8 flattenSymbol(const String8& symbol) {
2209 String8 result(symbol);
2210 ssize_t first;
2211 if ((first = symbol.find(":", 0)) >= 0
2212 || (first = symbol.find(".", 0)) >= 0) {
2213 size_t size = symbol.size();
2214 char* buf = result.lockBuffer(size);
2215 for (size_t i = first; i < size; i++) {
2216 if (buf[i] == ':' || buf[i] == '.') {
2217 buf[i] = '_';
2218 }
2219 }
2220 result.unlockBuffer(size);
2221 }
2222 return result;
2223 }
2224
getSymbolPackage(const String8 & symbol,const sp<AaptAssets> & assets,bool pub)2225 static String8 getSymbolPackage(const String8& symbol, const sp<AaptAssets>& assets, bool pub) {
2226 ssize_t colon = symbol.find(":", 0);
2227 if (colon >= 0) {
2228 return String8(symbol.c_str(), colon);
2229 }
2230 return pub ? assets->getPackage() : assets->getSymbolsPrivatePackage();
2231 }
2232
getSymbolName(const String8 & symbol)2233 static String8 getSymbolName(const String8& symbol) {
2234 ssize_t colon = symbol.find(":", 0);
2235 if (colon >= 0) {
2236 return String8(symbol.c_str() + colon + 1);
2237 }
2238 return symbol;
2239 }
2240
getAttributeComment(const sp<AaptAssets> & assets,const String8 & name,String16 * outTypeComment=NULL)2241 static String16 getAttributeComment(const sp<AaptAssets>& assets,
2242 const String8& name,
2243 String16* outTypeComment = NULL)
2244 {
2245 sp<AaptSymbols> asym = assets->getSymbolsFor(String8("R"));
2246 if (asym != NULL) {
2247 //printf("Got R symbols!\n");
2248 asym = asym->getNestedSymbols().valueFor(String8("attr"));
2249 if (asym != NULL) {
2250 //printf("Got attrs symbols! comment %s=%s\n",
2251 // name.c_str(), String8(asym->getComment(name)).c_str());
2252 if (outTypeComment != NULL) {
2253 *outTypeComment = asym->getTypeComment(name);
2254 }
2255 return asym->getComment(name);
2256 }
2257 }
2258 return String16();
2259 }
2260
writeResourceLoadedCallbackForLayoutClasses(FILE * fp,const sp<AaptAssets> & assets,const sp<AaptSymbols> & symbols,int indent,bool)2261 static status_t writeResourceLoadedCallbackForLayoutClasses(
2262 FILE* fp, const sp<AaptAssets>& assets,
2263 const sp<AaptSymbols>& symbols, int indent, bool /* includePrivate */)
2264 {
2265 String16 attr16("attr");
2266 String16 package16(assets->getPackage());
2267
2268 const char* indentStr = getIndentSpace(indent);
2269 bool hasErrors = false;
2270
2271 size_t i;
2272 size_t N = symbols->getNestedSymbols().size();
2273 for (i=0; i<N; i++) {
2274 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2275 String8 realClassName(symbols->getNestedSymbols().keyAt(i));
2276 String8 nclassName(flattenSymbol(realClassName));
2277
2278 fprintf(fp,
2279 "%sfor(int i = 0; i < styleable.%s.length; ++i) {\n"
2280 "%sstyleable.%s[i] = (styleable.%s[i] & 0x00ffffff) | (packageId << 24);\n"
2281 "%s}\n",
2282 indentStr, nclassName.c_str(),
2283 getIndentSpace(indent+1), nclassName.c_str(), nclassName.c_str(),
2284 indentStr);
2285 }
2286
2287 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
2288 }
2289
writeResourceLoadedCallback(FILE * fp,const sp<AaptAssets> & assets,bool includePrivate,const sp<AaptSymbols> & symbols,const String8 & className,int indent)2290 static status_t writeResourceLoadedCallback(
2291 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2292 const sp<AaptSymbols>& symbols, const String8& className, int indent)
2293 {
2294 size_t i;
2295 status_t err = NO_ERROR;
2296
2297 size_t N = symbols->getSymbols().size();
2298 for (i=0; i<N; i++) {
2299 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2300 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
2301 continue;
2302 }
2303 if (!assets->isJavaSymbol(sym, includePrivate)) {
2304 continue;
2305 }
2306 String8 flat_name(flattenSymbol(sym.name));
2307 fprintf(fp,
2308 "%s%s.%s = (%s.%s & 0x00ffffff) | (packageId << 24);\n",
2309 getIndentSpace(indent), className.c_str(), flat_name.c_str(),
2310 className.c_str(), flat_name.c_str());
2311 }
2312
2313 N = symbols->getNestedSymbols().size();
2314 for (i=0; i<N; i++) {
2315 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2316 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2317 if (nclassName == "styleable") {
2318 err = writeResourceLoadedCallbackForLayoutClasses(
2319 fp, assets, nsymbols, indent, includePrivate);
2320 } else {
2321 err = writeResourceLoadedCallback(fp, assets, includePrivate, nsymbols,
2322 nclassName, indent);
2323 }
2324 if (err != NO_ERROR) {
2325 return err;
2326 }
2327 }
2328
2329 return NO_ERROR;
2330 }
2331
writeLayoutClasses(FILE * fp,const sp<AaptAssets> & assets,const sp<AaptSymbols> & symbols,int indent,bool includePrivate,bool nonConstantId)2332 static status_t writeLayoutClasses(
2333 FILE* fp, const sp<AaptAssets>& assets,
2334 const sp<AaptSymbols>& symbols, int indent, bool includePrivate, bool nonConstantId)
2335 {
2336 const char* indentStr = getIndentSpace(indent);
2337 if (!includePrivate) {
2338 fprintf(fp, "%s/** @doconly */\n", indentStr);
2339 }
2340 fprintf(fp, "%spublic static final class styleable {\n", indentStr);
2341 indent++;
2342
2343 String16 attr16("attr");
2344 String16 package16(assets->getPackage());
2345
2346 indentStr = getIndentSpace(indent);
2347 bool hasErrors = false;
2348
2349 size_t i;
2350 size_t N = symbols->getNestedSymbols().size();
2351 for (i=0; i<N; i++) {
2352 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2353 String8 realClassName(symbols->getNestedSymbols().keyAt(i));
2354 String8 nclassName(flattenSymbol(realClassName));
2355
2356 SortedVector<uint32_t> idents;
2357 Vector<uint32_t> origOrder;
2358 Vector<bool> publicFlags;
2359
2360 size_t a;
2361 size_t NA = nsymbols->getSymbols().size();
2362 for (a=0; a<NA; a++) {
2363 const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a));
2364 int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32
2365 ? sym.int32Val : 0;
2366 bool isPublic = true;
2367 if (code == 0) {
2368 String16 name16(sym.name);
2369 uint32_t typeSpecFlags;
2370 code = assets->getIncludedResources().identifierForName(
2371 name16.c_str(), name16.size(),
2372 attr16.c_str(), attr16.size(),
2373 package16.c_str(), package16.size(), &typeSpecFlags);
2374 if (code == 0) {
2375 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
2376 nclassName.c_str(), sym.name.c_str());
2377 hasErrors = true;
2378 }
2379 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
2380 }
2381 idents.add(code);
2382 origOrder.add(code);
2383 publicFlags.add(isPublic);
2384 }
2385
2386 NA = idents.size();
2387
2388 String16 comment = symbols->getComment(realClassName);
2389 AnnotationProcessor ann;
2390 fprintf(fp, "%s/** ", indentStr);
2391 if (comment.size() > 0) {
2392 String8 cmt(comment);
2393 ann.preprocessComment(cmt);
2394 fprintf(fp, "%s\n", cmt.c_str());
2395 } else {
2396 fprintf(fp, "Attributes that can be used with a %s.\n", nclassName.c_str());
2397 }
2398 bool hasTable = false;
2399 for (a=0; a<NA; a++) {
2400 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2401 if (pos >= 0) {
2402 if (!hasTable) {
2403 hasTable = true;
2404 fprintf(fp,
2405 "%s <p>Includes the following attributes:</p>\n"
2406 "%s <table>\n"
2407 "%s <colgroup align=\"left\" />\n"
2408 "%s <colgroup align=\"left\" />\n"
2409 "%s <tr><th>Attribute</th><th>Description</th></tr>\n",
2410 indentStr,
2411 indentStr,
2412 indentStr,
2413 indentStr,
2414 indentStr);
2415 }
2416 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2417 if (!publicFlags.itemAt(a) && !includePrivate) {
2418 continue;
2419 }
2420 String8 name8(sym.name);
2421 String16 comment(sym.comment);
2422 if (comment.size() <= 0) {
2423 comment = getAttributeComment(assets, name8);
2424 }
2425 if (comment.contains(u"@removed")) {
2426 continue;
2427 }
2428 if (comment.size() > 0) {
2429 const char16_t* p = comment.c_str();
2430 while (*p != 0 && *p != '.') {
2431 if (*p == '{') {
2432 while (*p != 0 && *p != '}') {
2433 p++;
2434 }
2435 } else {
2436 p++;
2437 }
2438 }
2439 if (*p == '.') {
2440 p++;
2441 }
2442 comment = String16(comment.c_str(), p-comment.c_str());
2443 }
2444 fprintf(fp, "%s <tr><td><code>{@link #%s_%s %s:%s}</code></td><td>%s</td></tr>\n",
2445 indentStr, nclassName.c_str(),
2446 flattenSymbol(name8).c_str(),
2447 getSymbolPackage(name8, assets, true).c_str(),
2448 getSymbolName(name8).c_str(),
2449 String8(comment).c_str());
2450 }
2451 }
2452 if (hasTable) {
2453 fprintf(fp, "%s </table>\n", indentStr);
2454 }
2455 for (a=0; a<NA; a++) {
2456 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2457 if (pos >= 0) {
2458 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2459 if (!publicFlags.itemAt(a) && !includePrivate) {
2460 continue;
2461 }
2462 fprintf(fp, "%s @see #%s_%s\n",
2463 indentStr, nclassName.c_str(),
2464 flattenSymbol(sym.name).c_str());
2465 }
2466 }
2467 fprintf(fp, "%s */\n", getIndentSpace(indent));
2468
2469 ann.printAnnotations(fp, indentStr);
2470
2471 fprintf(fp,
2472 "%spublic static final int[] %s = {\n"
2473 "%s",
2474 indentStr, nclassName.c_str(),
2475 getIndentSpace(indent+1));
2476
2477 for (a=0; a<NA; a++) {
2478 if (a != 0) {
2479 if ((a&3) == 0) {
2480 fprintf(fp, ",\n%s", getIndentSpace(indent+1));
2481 } else {
2482 fprintf(fp, ", ");
2483 }
2484 }
2485 fprintf(fp, "0x%08x", idents[a]);
2486 }
2487
2488 fprintf(fp, "\n%s};\n", indentStr);
2489
2490 for (a=0; a<NA; a++) {
2491 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2492 if (pos >= 0) {
2493 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2494 if (!publicFlags.itemAt(a) && !includePrivate) {
2495 continue;
2496 }
2497 String8 name8(sym.name);
2498 String16 comment(sym.comment);
2499 String16 typeComment;
2500 if (comment.size() <= 0) {
2501 comment = getAttributeComment(assets, name8, &typeComment);
2502 } else {
2503 getAttributeComment(assets, name8, &typeComment);
2504 }
2505
2506 uint32_t typeSpecFlags = 0;
2507 String16 name16(sym.name);
2508 assets->getIncludedResources().identifierForName(
2509 name16.c_str(), name16.size(),
2510 attr16.c_str(), attr16.size(),
2511 package16.c_str(), package16.size(), &typeSpecFlags);
2512 //printf("%s:%s/%s: 0x%08x\n", String8(package16).c_str(),
2513 // String8(attr16).c_str(), String8(name16).c_str(), typeSpecFlags);
2514 const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
2515
2516 AnnotationProcessor ann;
2517 fprintf(fp, "%s/**\n", indentStr);
2518 if (comment.size() > 0) {
2519 String8 cmt(comment);
2520 ann.preprocessComment(cmt);
2521 fprintf(fp, "%s <p>\n%s @attr description\n", indentStr, indentStr);
2522 fprintf(fp, "%s %s\n", indentStr, cmt.c_str());
2523 } else {
2524 fprintf(fp,
2525 "%s <p>This symbol is the offset where the {@link %s.R.attr#%s}\n"
2526 "%s attribute's value can be found in the {@link #%s} array.\n",
2527 indentStr,
2528 getSymbolPackage(name8, assets, pub).c_str(),
2529 getSymbolName(name8).c_str(),
2530 indentStr, nclassName.c_str());
2531 }
2532 if (typeComment.size() > 0) {
2533 String8 cmt(typeComment);
2534 ann.preprocessComment(cmt);
2535 fprintf(fp, "\n\n%s %s\n", indentStr, cmt.c_str());
2536 }
2537 if (comment.size() > 0) {
2538 if (pub) {
2539 fprintf(fp,
2540 "%s <p>This corresponds to the global attribute\n"
2541 "%s resource symbol {@link %s.R.attr#%s}.\n",
2542 indentStr, indentStr,
2543 getSymbolPackage(name8, assets, true).c_str(),
2544 getSymbolName(name8).c_str());
2545 } else {
2546 fprintf(fp,
2547 "%s <p>This is a private symbol.\n", indentStr);
2548 }
2549 }
2550 fprintf(fp, "%s @attr name %s:%s\n", indentStr,
2551 getSymbolPackage(name8, assets, pub).c_str(),
2552 getSymbolName(name8).c_str());
2553 fprintf(fp, "%s*/\n", indentStr);
2554 ann.printAnnotations(fp, indentStr);
2555
2556 const char * id_format = nonConstantId ?
2557 "%spublic static int %s_%s = %d;\n" :
2558 "%spublic static final int %s_%s = %d;\n";
2559
2560 fprintf(fp,
2561 id_format,
2562 indentStr, nclassName.c_str(),
2563 flattenSymbol(name8).c_str(), (int)pos);
2564 }
2565 }
2566 }
2567
2568 indent--;
2569 fprintf(fp, "%s};\n", getIndentSpace(indent));
2570 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
2571 }
2572
writeTextLayoutClasses(FILE * fp,const sp<AaptAssets> & assets,const sp<AaptSymbols> & symbols,bool includePrivate)2573 static status_t writeTextLayoutClasses(
2574 FILE* fp, const sp<AaptAssets>& assets,
2575 const sp<AaptSymbols>& symbols, bool includePrivate)
2576 {
2577 String16 attr16("attr");
2578 String16 package16(assets->getPackage());
2579
2580 bool hasErrors = false;
2581
2582 size_t i;
2583 size_t N = symbols->getNestedSymbols().size();
2584 for (i=0; i<N; i++) {
2585 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2586 String8 realClassName(symbols->getNestedSymbols().keyAt(i));
2587 String8 nclassName(flattenSymbol(realClassName));
2588
2589 SortedVector<uint32_t> idents;
2590 Vector<uint32_t> origOrder;
2591 Vector<bool> publicFlags;
2592
2593 size_t a;
2594 size_t NA = nsymbols->getSymbols().size();
2595 for (a=0; a<NA; a++) {
2596 const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a));
2597 int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32
2598 ? sym.int32Val : 0;
2599 bool isPublic = true;
2600 if (code == 0) {
2601 String16 name16(sym.name);
2602 uint32_t typeSpecFlags;
2603 code = assets->getIncludedResources().identifierForName(
2604 name16.c_str(), name16.size(),
2605 attr16.c_str(), attr16.size(),
2606 package16.c_str(), package16.size(), &typeSpecFlags);
2607 if (code == 0) {
2608 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
2609 nclassName.c_str(), sym.name.c_str());
2610 hasErrors = true;
2611 }
2612 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
2613 }
2614 idents.add(code);
2615 origOrder.add(code);
2616 publicFlags.add(isPublic);
2617 }
2618
2619 NA = idents.size();
2620
2621 fprintf(fp, "int[] styleable %s {", nclassName.c_str());
2622
2623 for (a=0; a<NA; a++) {
2624 if (a != 0) {
2625 fprintf(fp, ",");
2626 }
2627 fprintf(fp, " 0x%08x", idents[a]);
2628 }
2629
2630 fprintf(fp, " }\n");
2631
2632 for (a=0; a<NA; a++) {
2633 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2634 if (pos >= 0) {
2635 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2636 if (!publicFlags.itemAt(a) && !includePrivate) {
2637 continue;
2638 }
2639 String8 name8(sym.name);
2640 String16 comment(sym.comment);
2641 String16 typeComment;
2642 if (comment.size() <= 0) {
2643 comment = getAttributeComment(assets, name8, &typeComment);
2644 } else {
2645 getAttributeComment(assets, name8, &typeComment);
2646 }
2647
2648 uint32_t typeSpecFlags = 0;
2649 String16 name16(sym.name);
2650 assets->getIncludedResources().identifierForName(
2651 name16.c_str(), name16.size(),
2652 attr16.c_str(), attr16.size(),
2653 package16.c_str(), package16.size(), &typeSpecFlags);
2654 //printf("%s:%s/%s: 0x%08x\n", String8(package16).c_str(),
2655 // String8(attr16).c_str(), String8(name16).c_str(), typeSpecFlags);
2656 //const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
2657
2658 fprintf(fp,
2659 "int styleable %s_%s %d\n",
2660 nclassName.c_str(),
2661 flattenSymbol(name8).c_str(), (int)pos);
2662 }
2663 }
2664 }
2665
2666 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
2667 }
2668
writeSymbolClass(FILE * fp,const sp<AaptAssets> & assets,bool includePrivate,const sp<AaptSymbols> & symbols,const String8 & className,int indent,bool nonConstantId,bool emitCallback)2669 static status_t writeSymbolClass(
2670 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2671 const sp<AaptSymbols>& symbols, const String8& className, int indent,
2672 bool nonConstantId, bool emitCallback)
2673 {
2674 fprintf(fp, "%spublic %sfinal class %s {\n",
2675 getIndentSpace(indent),
2676 indent != 0 ? "static " : "", className.c_str());
2677 indent++;
2678
2679 size_t i;
2680 status_t err = NO_ERROR;
2681
2682 const char * id_format = nonConstantId ?
2683 "%spublic static int %s=0x%08x;\n" :
2684 "%spublic static final int %s=0x%08x;\n";
2685
2686 size_t N = symbols->getSymbols().size();
2687 for (i=0; i<N; i++) {
2688 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2689 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
2690 continue;
2691 }
2692 if (!assets->isJavaSymbol(sym, includePrivate)) {
2693 continue;
2694 }
2695 String8 name8(sym.name);
2696 String16 comment(sym.comment);
2697 bool haveComment = false;
2698 AnnotationProcessor ann;
2699 if (comment.size() > 0) {
2700 haveComment = true;
2701 String8 cmt(comment);
2702 ann.preprocessComment(cmt);
2703 fprintf(fp,
2704 "%s/** %s\n",
2705 getIndentSpace(indent), cmt.c_str());
2706 }
2707 String16 typeComment(sym.typeComment);
2708 if (typeComment.size() > 0) {
2709 String8 cmt(typeComment);
2710 ann.preprocessComment(cmt);
2711 if (!haveComment) {
2712 haveComment = true;
2713 fprintf(fp,
2714 "%s/** %s\n", getIndentSpace(indent), cmt.c_str());
2715 } else {
2716 fprintf(fp,
2717 "%s %s\n", getIndentSpace(indent), cmt.c_str());
2718 }
2719 }
2720 if (haveComment) {
2721 fprintf(fp,"%s */\n", getIndentSpace(indent));
2722 }
2723 ann.printAnnotations(fp, getIndentSpace(indent));
2724 fprintf(fp, id_format,
2725 getIndentSpace(indent),
2726 flattenSymbol(name8).c_str(), (int)sym.int32Val);
2727 }
2728
2729 for (i=0; i<N; i++) {
2730 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2731 if (sym.typeCode != AaptSymbolEntry::TYPE_STRING) {
2732 continue;
2733 }
2734 if (!assets->isJavaSymbol(sym, includePrivate)) {
2735 continue;
2736 }
2737 String8 name8(sym.name);
2738 String16 comment(sym.comment);
2739 AnnotationProcessor ann;
2740 if (comment.size() > 0) {
2741 String8 cmt(comment);
2742 ann.preprocessComment(cmt);
2743 fprintf(fp,
2744 "%s/** %s\n"
2745 "%s */\n",
2746 getIndentSpace(indent), cmt.c_str(),
2747 getIndentSpace(indent));
2748 }
2749 ann.printAnnotations(fp, getIndentSpace(indent));
2750 fprintf(fp, "%spublic static final String %s=\"%s\";\n",
2751 getIndentSpace(indent),
2752 flattenSymbol(name8).c_str(), sym.stringVal.c_str());
2753 }
2754
2755 sp<AaptSymbols> styleableSymbols;
2756
2757 N = symbols->getNestedSymbols().size();
2758 for (i=0; i<N; i++) {
2759 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2760 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2761 if (nclassName == "styleable") {
2762 styleableSymbols = nsymbols;
2763 } else {
2764 err = writeSymbolClass(fp, assets, includePrivate, nsymbols, nclassName,
2765 indent, nonConstantId, false);
2766 }
2767 if (err != NO_ERROR) {
2768 return err;
2769 }
2770 }
2771
2772 if (styleableSymbols != NULL) {
2773 err = writeLayoutClasses(fp, assets, styleableSymbols, indent, includePrivate, nonConstantId);
2774 if (err != NO_ERROR) {
2775 return err;
2776 }
2777 }
2778
2779 if (emitCallback) {
2780 fprintf(fp, "%spublic static void onResourcesLoaded(int packageId) {\n",
2781 getIndentSpace(indent));
2782 writeResourceLoadedCallback(fp, assets, includePrivate, symbols, className, indent + 1);
2783 fprintf(fp, "%s}\n", getIndentSpace(indent));
2784 }
2785
2786 indent--;
2787 fprintf(fp, "%s}\n", getIndentSpace(indent));
2788 return NO_ERROR;
2789 }
2790
writeTextSymbolClass(FILE * fp,const sp<AaptAssets> & assets,bool includePrivate,const sp<AaptSymbols> & symbols,const String8 & className)2791 static status_t writeTextSymbolClass(
2792 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2793 const sp<AaptSymbols>& symbols, const String8& className)
2794 {
2795 size_t i;
2796 status_t err = NO_ERROR;
2797
2798 size_t N = symbols->getSymbols().size();
2799 for (i=0; i<N; i++) {
2800 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2801 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
2802 continue;
2803 }
2804
2805 if (!assets->isJavaSymbol(sym, includePrivate)) {
2806 continue;
2807 }
2808
2809 String8 name8(sym.name);
2810 fprintf(fp, "int %s %s 0x%08x\n",
2811 className.c_str(),
2812 flattenSymbol(name8).c_str(), (int)sym.int32Val);
2813 }
2814
2815 N = symbols->getNestedSymbols().size();
2816 for (i=0; i<N; i++) {
2817 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2818 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2819 if (nclassName == "styleable") {
2820 err = writeTextLayoutClasses(fp, assets, nsymbols, includePrivate);
2821 } else {
2822 err = writeTextSymbolClass(fp, assets, includePrivate, nsymbols, nclassName);
2823 }
2824 if (err != NO_ERROR) {
2825 return err;
2826 }
2827 }
2828
2829 return NO_ERROR;
2830 }
2831
writeResourceSymbols(Bundle * bundle,const sp<AaptAssets> & assets,const String8 & package,bool includePrivate,bool emitCallback)2832 status_t writeResourceSymbols(Bundle* bundle, const sp<AaptAssets>& assets,
2833 const String8& package, bool includePrivate, bool emitCallback)
2834 {
2835 if (!bundle->getRClassDir()) {
2836 return NO_ERROR;
2837 }
2838
2839 const char* textSymbolsDest = bundle->getOutputTextSymbols();
2840
2841 String8 R("R");
2842 const size_t N = assets->getSymbols().size();
2843 for (size_t i=0; i<N; i++) {
2844 sp<AaptSymbols> symbols = assets->getSymbols().valueAt(i);
2845 String8 className(assets->getSymbols().keyAt(i));
2846 String8 dest(bundle->getRClassDir());
2847
2848 if (bundle->getMakePackageDirs()) {
2849 const String8& pkg(package);
2850 const char* last = pkg.c_str();
2851 const char* s = last-1;
2852 do {
2853 s++;
2854 if (s > last && (*s == '.' || *s == 0)) {
2855 String8 part(last, s-last);
2856 appendPath(dest, part);
2857 #ifdef _WIN32
2858 _mkdir(dest.c_str());
2859 #else
2860 mkdir(dest.c_str(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP);
2861 #endif
2862 last = s+1;
2863 }
2864 } while (*s);
2865 }
2866 appendPath(dest, className);
2867 dest.append(".java");
2868 FILE* fp = fopen(dest.c_str(), "w+");
2869 if (fp == NULL) {
2870 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
2871 dest.c_str(), strerror(errno));
2872 return UNKNOWN_ERROR;
2873 }
2874 if (bundle->getVerbose()) {
2875 printf(" Writing symbols for class %s.\n", className.c_str());
2876 }
2877
2878 fprintf(fp,
2879 "/* AUTO-GENERATED FILE. DO NOT MODIFY.\n"
2880 " *\n"
2881 " * This class was automatically generated by the\n"
2882 " * aapt tool from the resource data it found. It\n"
2883 " * should not be modified by hand.\n"
2884 " */\n"
2885 "\n"
2886 "package %s;\n\n", package.c_str());
2887
2888 status_t err = writeSymbolClass(fp, assets, includePrivate, symbols,
2889 className, 0, bundle->getNonConstantId(), emitCallback);
2890 fclose(fp);
2891 if (err != NO_ERROR) {
2892 return err;
2893 }
2894
2895 if (textSymbolsDest != NULL && R == className) {
2896 String8 textDest(textSymbolsDest);
2897 appendPath(textDest, className);
2898 textDest.append(".txt");
2899
2900 FILE* fp = fopen(textDest.c_str(), "w+");
2901 if (fp == NULL) {
2902 fprintf(stderr, "ERROR: Unable to open text symbol file %s: %s\n",
2903 textDest.c_str(), strerror(errno));
2904 return UNKNOWN_ERROR;
2905 }
2906 if (bundle->getVerbose()) {
2907 printf(" Writing text symbols for class %s.\n", className.c_str());
2908 }
2909
2910 status_t err = writeTextSymbolClass(fp, assets, includePrivate, symbols,
2911 className);
2912 fclose(fp);
2913 if (err != NO_ERROR) {
2914 return err;
2915 }
2916 }
2917
2918 // If we were asked to generate a dependency file, we'll go ahead and add this R.java
2919 // as a target in the dependency file right next to it.
2920 if (bundle->getGenDependencies() && R == className) {
2921 // Add this R.java to the dependency file
2922 String8 dependencyFile(bundle->getRClassDir());
2923 appendPath(dependencyFile, "R.java.d");
2924
2925 FILE *fp = fopen(dependencyFile.c_str(), "a");
2926 fprintf(fp,"%s \\\n", dest.c_str());
2927 fclose(fp);
2928 }
2929 }
2930
2931 return NO_ERROR;
2932 }
2933
2934
2935 class ProguardKeepSet
2936 {
2937 public:
2938 // { rule --> { file locations } }
2939 KeyedVector<String8, SortedVector<String8> > rules;
2940
2941 void add(const String8& rule, const String8& where);
2942 };
2943
add(const String8 & rule,const String8 & where)2944 void ProguardKeepSet::add(const String8& rule, const String8& where)
2945 {
2946 ssize_t index = rules.indexOfKey(rule);
2947 if (index < 0) {
2948 index = rules.add(rule, SortedVector<String8>());
2949 }
2950 rules.editValueAt(index).add(where);
2951 }
2952
2953 void
addProguardKeepRule(ProguardKeepSet * keep,const String8 & inClassName,const char * pkg,const String8 & srcName,int line)2954 addProguardKeepRule(ProguardKeepSet* keep, const String8& inClassName,
2955 const char* pkg, const String8& srcName, int line)
2956 {
2957 String8 className(inClassName);
2958 if (pkg != NULL) {
2959 // asdf --> package.asdf
2960 // .asdf .a.b --> package.asdf package.a.b
2961 // asdf.adsf --> asdf.asdf
2962 const char* p = className.c_str();
2963 const char* q = strchr(p, '.');
2964 if (p == q) {
2965 className = pkg;
2966 className.append(inClassName);
2967 } else if (q == NULL) {
2968 className = pkg;
2969 className.append(".");
2970 className.append(inClassName);
2971 }
2972 }
2973
2974 String8 rule("-keep class ");
2975 rule += className;
2976 rule += " { <init>(...); }";
2977
2978 String8 location("view ");
2979 location += srcName;
2980 char lineno[20];
2981 sprintf(lineno, ":%d", line);
2982 location += lineno;
2983
2984 keep->add(rule, location);
2985 }
2986
2987 void
addProguardKeepMethodRule(ProguardKeepSet * keep,const String8 & memberName,const char *,const String8 & srcName,int line)2988 addProguardKeepMethodRule(ProguardKeepSet* keep, const String8& memberName,
2989 const char* /* pkg */, const String8& srcName, int line)
2990 {
2991 String8 rule("-keepclassmembers class * { *** ");
2992 rule += memberName;
2993 rule += "(...); }";
2994
2995 String8 location("onClick ");
2996 location += srcName;
2997 char lineno[20];
2998 sprintf(lineno, ":%d", line);
2999 location += lineno;
3000
3001 keep->add(rule, location);
3002 }
3003
3004 status_t
writeProguardForAndroidManifest(ProguardKeepSet * keep,const sp<AaptAssets> & assets,bool mainDex)3005 writeProguardForAndroidManifest(ProguardKeepSet* keep, const sp<AaptAssets>& assets, bool mainDex)
3006 {
3007 status_t err;
3008 ResXMLTree tree;
3009 size_t len;
3010 ResXMLTree::event_code_t code;
3011 int depth = 0;
3012 bool inApplication = false;
3013 String8 error;
3014 sp<AaptGroup> assGroup;
3015 sp<AaptFile> assFile;
3016 String8 pkg;
3017 String8 defaultProcess;
3018
3019 // First, look for a package file to parse. This is required to
3020 // be able to generate the resource information.
3021 assGroup = assets->getFiles().valueFor(String8("AndroidManifest.xml"));
3022 if (assGroup == NULL) {
3023 fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n");
3024 return -1;
3025 }
3026
3027 if (assGroup->getFiles().size() != 1) {
3028 fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
3029 assGroup->getFiles().valueAt(0)->getPrintableSource().c_str());
3030 }
3031
3032 assFile = assGroup->getFiles().valueAt(0);
3033
3034 err = parseXMLResource(assFile, &tree);
3035 if (err != NO_ERROR) {
3036 return err;
3037 }
3038
3039 tree.restart();
3040
3041 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
3042 if (code == ResXMLTree::END_TAG) {
3043 if (/* name == "Application" && */ depth == 2) {
3044 inApplication = false;
3045 }
3046 depth--;
3047 continue;
3048 }
3049 if (code != ResXMLTree::START_TAG) {
3050 continue;
3051 }
3052 depth++;
3053 String8 tag(tree.getElementName(&len));
3054 // printf("Depth %d tag %s\n", depth, tag.c_str());
3055 bool keepTag = false;
3056 if (depth == 1) {
3057 if (tag != "manifest") {
3058 fprintf(stderr, "ERROR: manifest does not start with <manifest> tag\n");
3059 return -1;
3060 }
3061 pkg = AaptXml::getAttribute(tree, NULL, "package");
3062 } else if (depth == 2) {
3063 if (tag == "application") {
3064 inApplication = true;
3065 keepTag = true;
3066
3067 String8 agent = AaptXml::getAttribute(tree,
3068 "http://schemas.android.com/apk/res/android",
3069 "backupAgent", &error);
3070 if (agent.length() > 0) {
3071 addProguardKeepRule(keep, agent, pkg.c_str(),
3072 assFile->getPrintableSource(), tree.getLineNumber());
3073 }
3074
3075 if (mainDex) {
3076 defaultProcess = AaptXml::getAttribute(tree,
3077 "http://schemas.android.com/apk/res/android", "process", &error);
3078 if (error != "") {
3079 fprintf(stderr, "ERROR: %s\n", error.c_str());
3080 return -1;
3081 }
3082 }
3083 } else if (tag == "instrumentation") {
3084 keepTag = true;
3085 }
3086 }
3087 if (!keepTag && inApplication && depth == 3) {
3088 if (tag == "activity" || tag == "service" || tag == "receiver" || tag == "provider") {
3089 keepTag = true;
3090
3091 if (mainDex) {
3092 String8 componentProcess = AaptXml::getAttribute(tree,
3093 "http://schemas.android.com/apk/res/android", "process", &error);
3094 if (error != "") {
3095 fprintf(stderr, "ERROR: %s\n", error.c_str());
3096 return -1;
3097 }
3098
3099 const String8& process =
3100 componentProcess.length() > 0 ? componentProcess : defaultProcess;
3101 keepTag = process.length() > 0 && process.find(":") != 0;
3102 }
3103 }
3104 }
3105 if (keepTag) {
3106 String8 name = AaptXml::getAttribute(tree,
3107 "http://schemas.android.com/apk/res/android", "name", &error);
3108 if (error != "") {
3109 fprintf(stderr, "ERROR: %s\n", error.c_str());
3110 return -1;
3111 }
3112
3113 keepTag = name.length() > 0;
3114
3115 if (keepTag) {
3116 addProguardKeepRule(keep, name, pkg.c_str(),
3117 assFile->getPrintableSource(), tree.getLineNumber());
3118 }
3119 }
3120 }
3121
3122 return NO_ERROR;
3123 }
3124
3125 struct NamespaceAttributePair {
3126 const char* ns;
3127 const char* attr;
3128
NamespaceAttributePairNamespaceAttributePair3129 NamespaceAttributePair(const char* n, const char* a) : ns(n), attr(a) {}
NamespaceAttributePairNamespaceAttributePair3130 NamespaceAttributePair() : ns(NULL), attr(NULL) {}
3131 };
3132
3133 status_t
writeProguardForXml(ProguardKeepSet * keep,const sp<AaptFile> & layoutFile,const Vector<String8> & startTags,const KeyedVector<String8,Vector<NamespaceAttributePair>> * tagAttrPairs)3134 writeProguardForXml(ProguardKeepSet* keep, const sp<AaptFile>& layoutFile,
3135 const Vector<String8>& startTags, const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs)
3136 {
3137 status_t err;
3138 ResXMLTree tree;
3139 size_t len;
3140 ResXMLTree::event_code_t code;
3141
3142 err = parseXMLResource(layoutFile, &tree);
3143 if (err != NO_ERROR) {
3144 return err;
3145 }
3146
3147 tree.restart();
3148
3149 if (!startTags.empty()) {
3150 bool haveStart = false;
3151 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
3152 if (code != ResXMLTree::START_TAG) {
3153 continue;
3154 }
3155 String8 tag(tree.getElementName(&len));
3156 const size_t numStartTags = startTags.size();
3157 for (size_t i = 0; i < numStartTags; i++) {
3158 if (tag == startTags[i]) {
3159 haveStart = true;
3160 }
3161 }
3162 break;
3163 }
3164 if (!haveStart) {
3165 return NO_ERROR;
3166 }
3167 }
3168
3169 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
3170 if (code != ResXMLTree::START_TAG) {
3171 continue;
3172 }
3173 String8 tag(tree.getElementName(&len));
3174
3175 // If there is no '.', we'll assume that it's one of the built in names.
3176 if (strchr(tag.c_str(), '.')) {
3177 addProguardKeepRule(keep, tag, NULL,
3178 layoutFile->getPrintableSource(), tree.getLineNumber());
3179 } else if (tagAttrPairs != NULL) {
3180 ssize_t tagIndex = tagAttrPairs->indexOfKey(tag);
3181 if (tagIndex >= 0) {
3182 const Vector<NamespaceAttributePair>& nsAttrVector = tagAttrPairs->valueAt(tagIndex);
3183 for (size_t i = 0; i < nsAttrVector.size(); i++) {
3184 const NamespaceAttributePair& nsAttr = nsAttrVector[i];
3185
3186 ssize_t attrIndex = tree.indexOfAttribute(nsAttr.ns, nsAttr.attr);
3187 if (attrIndex < 0) {
3188 // fprintf(stderr, "%s:%d: <%s> does not have attribute %s:%s.\n",
3189 // layoutFile->getPrintableSource().c_str(), tree.getLineNumber(),
3190 // tag.c_str(), nsAttr.ns, nsAttr.attr);
3191 } else {
3192 size_t len;
3193 addProguardKeepRule(keep,
3194 String8(tree.getAttributeStringValue(attrIndex, &len)), NULL,
3195 layoutFile->getPrintableSource(), tree.getLineNumber());
3196 }
3197 }
3198 }
3199 }
3200 ssize_t attrIndex = tree.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "onClick");
3201 if (attrIndex >= 0) {
3202 size_t len;
3203 addProguardKeepMethodRule(keep,
3204 String8(tree.getAttributeStringValue(attrIndex, &len)), NULL,
3205 layoutFile->getPrintableSource(), tree.getLineNumber());
3206 }
3207 }
3208
3209 return NO_ERROR;
3210 }
3211
addTagAttrPair(KeyedVector<String8,Vector<NamespaceAttributePair>> * dest,const char * tag,const char * ns,const char * attr)3212 static void addTagAttrPair(KeyedVector<String8, Vector<NamespaceAttributePair> >* dest,
3213 const char* tag, const char* ns, const char* attr) {
3214 String8 tagStr(tag);
3215 ssize_t index = dest->indexOfKey(tagStr);
3216
3217 if (index < 0) {
3218 Vector<NamespaceAttributePair> vector;
3219 vector.add(NamespaceAttributePair(ns, attr));
3220 dest->add(tagStr, vector);
3221 } else {
3222 dest->editValueAt(index).add(NamespaceAttributePair(ns, attr));
3223 }
3224 }
3225
3226 status_t
writeProguardForLayouts(ProguardKeepSet * keep,const sp<AaptAssets> & assets)3227 writeProguardForLayouts(ProguardKeepSet* keep, const sp<AaptAssets>& assets)
3228 {
3229 status_t err;
3230 const char* kClass = "class";
3231 const char* kFragment = "fragment";
3232 const String8 kTransition("transition");
3233 const String8 kTransitionPrefix("transition-");
3234
3235 // tag:attribute pairs that should be checked in layout files.
3236 KeyedVector<String8, Vector<NamespaceAttributePair> > kLayoutTagAttrPairs;
3237 addTagAttrPair(&kLayoutTagAttrPairs, "view", NULL, kClass);
3238 addTagAttrPair(&kLayoutTagAttrPairs, kFragment, NULL, kClass);
3239 addTagAttrPair(&kLayoutTagAttrPairs, kFragment, RESOURCES_ANDROID_NAMESPACE, "name");
3240
3241 // tag:attribute pairs that should be checked in xml files.
3242 KeyedVector<String8, Vector<NamespaceAttributePair> > kXmlTagAttrPairs;
3243 addTagAttrPair(&kXmlTagAttrPairs, "PreferenceScreen", RESOURCES_ANDROID_NAMESPACE, kFragment);
3244 addTagAttrPair(&kXmlTagAttrPairs, "header", RESOURCES_ANDROID_NAMESPACE, kFragment);
3245
3246 // tag:attribute pairs that should be checked in transition files.
3247 KeyedVector<String8, Vector<NamespaceAttributePair> > kTransitionTagAttrPairs;
3248 addTagAttrPair(&kTransitionTagAttrPairs, kTransition.c_str(), NULL, kClass);
3249 addTagAttrPair(&kTransitionTagAttrPairs, "pathMotion", NULL, kClass);
3250
3251 const Vector<sp<AaptDir> >& dirs = assets->resDirs();
3252 const size_t K = dirs.size();
3253 for (size_t k=0; k<K; k++) {
3254 const sp<AaptDir>& d = dirs.itemAt(k);
3255 const String8& dirName = d->getLeaf();
3256 Vector<String8> startTags;
3257 const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs = NULL;
3258 if ((dirName == String8("layout")) || (strncmp(dirName.c_str(), "layout-", 7) == 0)) {
3259 tagAttrPairs = &kLayoutTagAttrPairs;
3260 } else if ((dirName == String8("xml")) || (strncmp(dirName.c_str(), "xml-", 4) == 0)) {
3261 startTags.add(String8("PreferenceScreen"));
3262 startTags.add(String8("preference-headers"));
3263 tagAttrPairs = &kXmlTagAttrPairs;
3264 } else if ((dirName == String8("menu")) || (strncmp(dirName.c_str(), "menu-", 5) == 0)) {
3265 startTags.add(String8("menu"));
3266 tagAttrPairs = NULL;
3267 } else if (dirName == kTransition || (strncmp(dirName.c_str(), kTransitionPrefix.c_str(),
3268 kTransitionPrefix.size()) == 0)) {
3269 tagAttrPairs = &kTransitionTagAttrPairs;
3270 } else {
3271 continue;
3272 }
3273
3274 const KeyedVector<String8,sp<AaptGroup> > groups = d->getFiles();
3275 const size_t N = groups.size();
3276 for (size_t i=0; i<N; i++) {
3277 const sp<AaptGroup>& group = groups.valueAt(i);
3278 const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files = group->getFiles();
3279 const size_t M = files.size();
3280 for (size_t j=0; j<M; j++) {
3281 err = writeProguardForXml(keep, files.valueAt(j), startTags, tagAttrPairs);
3282 if (err < 0) {
3283 return err;
3284 }
3285 }
3286 }
3287 }
3288 // Handle the overlays
3289 sp<AaptAssets> overlay = assets->getOverlay();
3290 if (overlay.get()) {
3291 return writeProguardForLayouts(keep, overlay);
3292 }
3293
3294 return NO_ERROR;
3295 }
3296
3297 status_t
writeProguardSpec(const char * filename,const ProguardKeepSet & keep,status_t err)3298 writeProguardSpec(const char* filename, const ProguardKeepSet& keep, status_t err)
3299 {
3300 FILE* fp = fopen(filename, "w+");
3301 if (fp == NULL) {
3302 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
3303 filename, strerror(errno));
3304 return UNKNOWN_ERROR;
3305 }
3306
3307 const KeyedVector<String8, SortedVector<String8> >& rules = keep.rules;
3308 const size_t N = rules.size();
3309 for (size_t i=0; i<N; i++) {
3310 const SortedVector<String8>& locations = rules.valueAt(i);
3311 const size_t M = locations.size();
3312 for (size_t j=0; j<M; j++) {
3313 fprintf(fp, "# %s\n", locations.itemAt(j).c_str());
3314 }
3315 fprintf(fp, "%s\n\n", rules.keyAt(i).c_str());
3316 }
3317 fclose(fp);
3318
3319 return err;
3320 }
3321
3322 status_t
writeProguardFile(Bundle * bundle,const sp<AaptAssets> & assets)3323 writeProguardFile(Bundle* bundle, const sp<AaptAssets>& assets)
3324 {
3325 status_t err = -1;
3326
3327 if (!bundle->getProguardFile()) {
3328 return NO_ERROR;
3329 }
3330
3331 ProguardKeepSet keep;
3332
3333 err = writeProguardForAndroidManifest(&keep, assets, false);
3334 if (err < 0) {
3335 return err;
3336 }
3337
3338 err = writeProguardForLayouts(&keep, assets);
3339 if (err < 0) {
3340 return err;
3341 }
3342
3343 return writeProguardSpec(bundle->getProguardFile(), keep, err);
3344 }
3345
3346 status_t
writeMainDexProguardFile(Bundle * bundle,const sp<AaptAssets> & assets)3347 writeMainDexProguardFile(Bundle* bundle, const sp<AaptAssets>& assets)
3348 {
3349 status_t err = -1;
3350
3351 if (!bundle->getMainDexProguardFile()) {
3352 return NO_ERROR;
3353 }
3354
3355 ProguardKeepSet keep;
3356
3357 err = writeProguardForAndroidManifest(&keep, assets, true);
3358 if (err < 0) {
3359 return err;
3360 }
3361
3362 return writeProguardSpec(bundle->getMainDexProguardFile(), keep, err);
3363 }
3364
3365 // Loops through the string paths and writes them to the file pointer
3366 // Each file path is written on its own line with a terminating backslash.
writePathsToFile(const sp<FilePathStore> & files,FILE * fp)3367 status_t writePathsToFile(const sp<FilePathStore>& files, FILE* fp)
3368 {
3369 status_t deps = -1;
3370 for (size_t file_i = 0; file_i < files->size(); ++file_i) {
3371 // Add the full file path to the dependency file
3372 fprintf(fp, "%s \\\n", files->itemAt(file_i).c_str());
3373 deps++;
3374 }
3375 return deps;
3376 }
3377
3378 status_t
writeDependencyPreReqs(Bundle *,const sp<AaptAssets> & assets,FILE * fp,bool includeRaw)3379 writeDependencyPreReqs(Bundle* /* bundle */, const sp<AaptAssets>& assets, FILE* fp, bool includeRaw)
3380 {
3381 status_t deps = -1;
3382 deps += writePathsToFile(assets->getFullResPaths(), fp);
3383 if (includeRaw) {
3384 deps += writePathsToFile(assets->getFullAssetPaths(), fp);
3385 }
3386 return deps;
3387 }
3388