blob: 7e4e186ec320a3250301e34290d571e1bd333f6d [file] [log] [blame]
Adam Lesinski282e1812014-01-23 18:17:42 -08001//
2// Copyright 2006 The Android Open Source Project
3//
4// Build resource files from raw assets.
5//
Adam Lesinski282e1812014-01-23 18:17:42 -08006#include "AaptAssets.h"
Adam Lesinskide7de472014-11-03 12:03:08 -08007#include "AaptUtil.h"
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07008#include "AaptXml.h"
Adam Lesinski1e4663852014-08-15 14:47:28 -07009#include "CacheUpdater.h"
Adam Lesinski282e1812014-01-23 18:17:42 -080010#include "CrunchCache.h"
11#include "FileFinder.h"
Adam Lesinski1e4663852014-08-15 14:47:28 -070012#include "Images.h"
13#include "IndentPrinter.h"
14#include "Main.h"
15#include "ResourceTable.h"
16#include "StringPool.h"
Adam Lesinskide7de472014-11-03 12:03:08 -080017#include "Symbol.h"
Elliott Hughes338698e2021-07-13 17:15:19 -070018#include "Utils.h"
Adam Lesinski282e1812014-01-23 18:17:42 -080019#include "WorkQueue.h"
Adam Lesinski1e4663852014-08-15 14:47:28 -070020#include "XMLNode.h"
Adam Lesinski282e1812014-01-23 18:17:42 -080021
Tomasz Wasilczyk804e8192023-08-23 02:22:53 +000022#include <androidfw/PathUtils.h>
23
Adam Lesinskide7de472014-11-03 12:03:08 -080024#include <algorithm>
25
Andreas Gampe2412f842014-09-30 20:55:57 -070026// STATUST: mingw does seem to redefine UNKNOWN_ERROR from our enum value, so a cast is necessary.
Adam Lesinski685d3632014-11-05 12:30:25 -080027
Elliott Hughesb12f2412015-04-03 12:56:45 -070028#if !defined(_WIN32)
Andreas Gampe2412f842014-09-30 20:55:57 -070029# define STATUST(x) x
Adam Lesinski282e1812014-01-23 18:17:42 -080030#else
Andreas Gampe2412f842014-09-30 20:55:57 -070031# define STATUST(x) (status_t)x
Adam Lesinski282e1812014-01-23 18:17:42 -080032#endif
33
Andreas Gampe2412f842014-09-30 20:55:57 -070034// Set to true for noisy debug output.
35static const bool kIsDebug = false;
Adam Lesinski282e1812014-01-23 18:17:42 -080036
37// Number of threads to use for preprocessing images.
38static const size_t MAX_THREADS = 4;
39
40// ==========================================================================
41// ==========================================================================
42// ==========================================================================
43
44class PackageInfo
45{
46public:
47 PackageInfo()
48 {
49 }
50 ~PackageInfo()
51 {
52 }
53
54 status_t parsePackage(const sp<AaptGroup>& grp);
55};
56
57// ==========================================================================
58// ==========================================================================
59// ==========================================================================
60
Adam Lesinskie572c012014-09-19 15:10:04 -070061String8 parseResourceName(const String8& leaf)
Adam Lesinski282e1812014-01-23 18:17:42 -080062{
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +000063 const char* firstDot = strchr(leaf.c_str(), '.');
64 const char* str = leaf.c_str();
Adam Lesinski282e1812014-01-23 18:17:42 -080065
66 if (firstDot) {
67 return String8(str, firstDot-str);
68 } else {
69 return String8(str);
70 }
71}
72
73ResourceTypeSet::ResourceTypeSet()
74 :RefBase(),
75 KeyedVector<String8,sp<AaptGroup> >()
76{
77}
78
79FilePathStore::FilePathStore()
80 :RefBase(),
81 Vector<String8>()
82{
83}
84
85class ResourceDirIterator
86{
87public:
88 ResourceDirIterator(const sp<ResourceTypeSet>& set, const String8& resType)
89 : mResType(resType), mSet(set), mSetPos(0), mGroupPos(0)
90 {
Narayan Kamath91447d82014-01-21 15:32:36 +000091 memset(&mParams, 0, sizeof(ResTable_config));
Adam Lesinski282e1812014-01-23 18:17:42 -080092 }
93
94 inline const sp<AaptGroup>& getGroup() const { return mGroup; }
95 inline const sp<AaptFile>& getFile() const { return mFile; }
96
97 inline const String8& getBaseName() const { return mBaseName; }
98 inline const String8& getLeafName() const { return mLeafName; }
99 inline String8 getPath() const { return mPath; }
100 inline const ResTable_config& getParams() const { return mParams; }
101
102 enum {
103 EOD = 1
104 };
105
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();
Andreas Gampe2412f842014-09-30 20:55:57 -0700136 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",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000138 group->getPath().c_str(), mParams.mcc, mParams.mnc,
Andreas Gampe2412f842014-09-30 20:55:57 -0700139 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 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800147 mPath = "res";
Tomasz Wasilczyk804e8192023-08-23 02:22:53 +0000148 appendPath(mPath, file->getGroupEntry().toDirName(mResType));
149 appendPath(mPath, leaf);
Adam Lesinski282e1812014-01-23 18:17:42 -0800150 mBaseName = parseResourceName(leaf);
151 if (mBaseName == "") {
152 fprintf(stderr, "Error: malformed resource filename %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000153 file->getPrintableSource().c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800154 return UNKNOWN_ERROR;
155 }
156
Andreas Gampe2412f842014-09-30 20:55:57 -0700157 if (kIsDebug) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000158 printf("file name=%s\n", mBaseName.c_str());
Andreas Gampe2412f842014-09-30 20:55:57 -0700159 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800160
161 return NO_ERROR;
162 }
163 }
164
165private:
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
Jeff Browneb490d62014-06-06 19:43:42 -0700181class AnnotationProcessor {
182public:
183 AnnotationProcessor() : mDeprecated(false), mSystemApi(false) { }
184
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
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
205private:
206 bool mDeprecated;
207 bool mSystemApi;
208};
209
Adam Lesinski282e1812014-01-23 18:17:42 -0800210// ==========================================================================
211// ==========================================================================
212// ==========================================================================
213
214bool isValidResourceType(const String8& type)
215{
216 return type == "anim" || type == "animator" || type == "interpolator"
Adam Lesinski83b4f7d2017-01-20 13:19:27 -0800217 || type == "transition" || type == "font"
Adam Lesinski282e1812014-01-23 18:17:42 -0800218 || type == "drawable" || type == "layout"
219 || type == "values" || type == "xml" || type == "raw"
220 || type == "color" || type == "menu" || type == "mipmap";
221}
222
Adam Lesinski282e1812014-01-23 18:17:42 -0800223static 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",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000228 grp->getFiles().valueAt(0)->getPrintableSource().c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800229 }
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",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000249 file->getPrintableSource().c_str(), block.getLineNumber());
Adam Lesinski282e1812014-01-23 18:17:42 -0800250 return UNKNOWN_ERROR;
251 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000252 if (strcmp16(block.getElementName(&len), String16("manifest").c_str()) != 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800253 fprintf(stderr, "%s:%d: Invalid start tag %s, expected <manifest>\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000254 file->getPrintableSource().c_str(), block.getLineNumber(),
255 String8(block.getElementName(&len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800256 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",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000262 file->getPrintableSource().c_str(), block.getLineNumber());
Adam Lesinski282e1812014-01-23 18:17:42 -0800263 return UNKNOWN_ERROR;
264 }
265
266 assets->setPackage(String8(block.getAttributeStringValue(nameIndex, &len)));
267
Adam Lesinski54de2982014-12-16 09:16:26 -0800268 ssize_t revisionCodeIndex = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "revisionCode");
269 if (revisionCodeIndex >= 0) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000270 bundle->setRevisionCode(String8(block.getAttributeStringValue(revisionCodeIndex, &len)).c_str());
Adam Lesinski54de2982014-12-16 09:16:26 -0800271 }
272
Adam Lesinski282e1812014-01-23 18:17:42 -0800273 String16 uses_sdk16("uses-sdk");
274 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
275 && code != ResXMLTree::BAD_DOCUMENT) {
276 if (code == ResXMLTree::START_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000277 if (strcmp16(block.getElementName(&len), uses_sdk16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800278 ssize_t minSdkIndex = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE,
279 "minSdkVersion");
280 if (minSdkIndex >= 0) {
Dan Albertf348c152014-09-08 18:28:00 -0700281 const char16_t* minSdk16 = block.getAttributeStringValue(minSdkIndex, &len);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000282 const char* minSdk8 = strdup(String8(minSdk16).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800283 bundle->setManifestMinSdkVersion(minSdk8);
284 }
285 }
286 }
287 }
288
289 return NO_ERROR;
290}
291
292// ==========================================================================
293// ==========================================================================
294// ==========================================================================
295
296static 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",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000311 it.getBaseName().c_str(), it.getFile()->getPrintableSource().c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800312 }
313 String16 baseName(it.getBaseName());
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000314 const char16_t* str = baseName.c_str();
Adam Lesinski282e1812014-01-23 18:17:42 -0800315 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",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000321 it.getPath().c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800322 hasErrors = true;
323 }
324 str++;
325 }
326 String8 resPath = it.getPath();
Elliott Hughes338698e2021-07-13 17:15:19 -0700327 convertToResPath(resPath);
Adam Lesinski526d73b2016-07-18 17:01:14 -0700328 status_t result = table->addEntry(SourcePos(it.getPath(), 0),
329 String16(assets->getPackage()),
Adam Lesinski282e1812014-01-23 18:17:42 -0800330 type16,
331 baseName,
332 String16(resPath),
333 NULL,
334 &it.getParams());
Adam Lesinski526d73b2016-07-18 17:01:14 -0700335 if (result != NO_ERROR) {
336 hasErrors = true;
337 } else {
338 assets->addResource(it.getLeafName(), resPath, it.getFile(), type8);
339 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800340 }
341
Andreas Gampe2412f842014-09-30 20:55:57 -0700342 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -0800343}
344
345class PreProcessImageWorkUnit : public WorkQueue::WorkUnit {
346public:
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
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
360private:
361 const Bundle* mBundle;
362 sp<AaptAssets> mAssets;
363 sp<AaptFile> mFile;
364 volatile bool* mHasErrors;
365};
366
367static 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 }
Andreas Gampe2412f842014-09-30 20:55:57 -0700392 return (hasErrors || (res < NO_ERROR)) ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -0800393}
394
Adam Lesinski282e1812014-01-23 18:17:42 -0800395static 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++) {
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -0700401 const String8& leafName = groups.keyAt(i);
Adam Lesinski282e1812014-01-23 18:17:42 -0800402 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();
Andreas Gampe2412f842014-09-30 20:55:57 -0700417 if (kIsDebug) {
418 printf("Creating new resource type set for leaf %s with group %s (%p)\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000419 leafName.c_str(), group->getPath().c_str(), group.get());
Andreas Gampe2412f842014-09-30 20:55:57 -0700420 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800421 set->add(leafName, group);
422 resources->add(resType, set);
423 } else {
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -0700424 const sp<ResourceTypeSet>& set = resources->valueAt(index);
Adam Lesinski282e1812014-01-23 18:17:42 -0800425 index = set->indexOfKey(leafName);
426 if (index < 0) {
Andreas Gampe2412f842014-09-30 20:55:57 -0700427 if (kIsDebug) {
428 printf("Adding to resource type set for leaf %s group %s (%p)\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000429 leafName.c_str(), group->getPath().c_str(), group.get());
Andreas Gampe2412f842014-09-30 20:55:57 -0700430 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800431 set->add(leafName, group);
432 } else {
433 sp<AaptGroup> existingGroup = set->valueAt(index);
Andreas Gampe2412f842014-09-30 20:55:57 -0700434 if (kIsDebug) {
435 printf("Extending to resource type set for leaf %s group %s (%p)\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000436 leafName.c_str(), group->getPath().c_str(), group.get());
Andreas Gampe2412f842014-09-30 20:55:57 -0700437 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800438 for (size_t j=0; j<files.size(); j++) {
Andreas Gampe2412f842014-09-30 20:55:57 -0700439 if (kIsDebug) {
440 printf("Adding file %s in group %s resType %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000441 files.valueAt(j)->getSourceFile().c_str(),
442 files.keyAt(j).toDirName(String8()).c_str(),
443 resType.c_str());
Andreas Gampe2412f842014-09-30 20:55:57 -0700444 }
445 existingGroup->addFile(files.valueAt(j));
Adam Lesinski282e1812014-01-23 18:17:42 -0800446 }
447 }
448 }
449 }
450}
451
452static 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++) {
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -0700459 const sp<AaptDir>& d = dirs.itemAt(i);
Andreas Gampe2412f842014-09-30 20:55:57 -0700460 if (kIsDebug) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000461 printf("Collecting dir #%d %p: %s, leaf %s\n", i, d.get(), d->getPath().c_str(),
462 d->getLeaf().c_str());
Andreas Gampe2412f842014-09-30 20:55:57 -0700463 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800464 collect_files(d, resources);
465
466 // don't try to include the res dir
Andreas Gampe2412f842014-09-30 20:55:57 -0700467 if (kIsDebug) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000468 printf("Removing dir leaf %s\n", d->getLeaf().c_str());
Andreas Gampe2412f842014-09-30 20:55:57 -0700469 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800470 ass->removeDir(d->getLeaf());
471 }
472}
473
474enum {
475 ATTR_OKAY = -1,
476 ATTR_NOT_FOUND = -2,
477 ATTR_LEADING_SPACES = -3,
478 ATTR_TRAILING_SPACES = -4
479};
480static 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);
Dan Albertf348c152014-09-08 18:28:00 -0700487 const char16_t* str;
Adam Lesinski282e1812014-01-23 18:17:42 -0800488 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",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000496 path.c_str(), parser.getLineNumber(),
497 String8(parser.getElementName(&len)).c_str(), attr,
Adam Lesinski282e1812014-01-23 18:17:42 -0800498 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,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000508 specFlags, strIdx, str != NULL ? String8(str).c_str() : "???");
Adam Lesinski282e1812014-01-23 18:17:42 -0800509 #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",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000512 path.c_str(), parser.getLineNumber(),
513 String8(parser.getElementName(&len)).c_str(), attr,
Adam Lesinski282e1812014-01-23 18:17:42 -0800514 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",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000521 path.c_str(), parser.getLineNumber(),
522 String8(parser.getElementName(&len)).c_str(), attr);
Adam Lesinski282e1812014-01-23 18:17:42 -0800523 return ATTR_NOT_FOUND;
524 }
Ryan Mitchell80094e32020-11-16 23:08:18 +0000525 if ((str = UnpackOptionalString(pool->stringAt(value.data), &len)) == NULL) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800526 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has corrupt string value.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000527 path.c_str(), parser.getLineNumber(),
528 String8(parser.getElementName(&len)).c_str(), attr);
Adam Lesinski282e1812014-01-23 18:17:42 -0800529 return ATTR_NOT_FOUND;
530 }
531 } else {
532 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has invalid type %d.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000533 path.c_str(), parser.getLineNumber(),
534 String8(parser.getElementName(&len)).c_str(), attr,
Adam Lesinski282e1812014-01-23 18:17:42 -0800535 value.dataType);
536 return ATTR_NOT_FOUND;
537 }
538 if (validChars) {
539 for (size_t i=0; i<len; i++) {
Adam Lesinski4bf58102014-11-03 11:21:19 -0800540 char16_t c = str[i];
Adam Lesinski282e1812014-01-23 18:17:42 -0800541 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",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000552 path.c_str(), parser.getLineNumber(),
553 String8(parser.getElementName(&len)).c_str(), attr, (char)str[i]);
Adam Lesinski282e1812014-01-23 18:17:42 -0800554 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",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000560 path.c_str(), parser.getLineNumber(),
561 String8(parser.getElementName(&len)).c_str(), attr);
Adam Lesinski282e1812014-01-23 18:17:42 -0800562 return ATTR_LEADING_SPACES;
563 }
Dan Albertd395f792014-10-20 14:44:39 -0700564 if (len != 0 && str[len-1] == ' ') {
Adam Lesinski282e1812014-01-23 18:17:42 -0800565 fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not end with a space.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000566 path.c_str(), parser.getLineNumber(),
567 String8(parser.getElementName(&len)).c_str(), attr);
Adam Lesinski282e1812014-01-23 18:17:42 -0800568 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",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000574 path.c_str(), parser.getLineNumber(),
575 String8(parser.getElementName(&len)).c_str(), attr);
Adam Lesinski282e1812014-01-23 18:17:42 -0800576 return ATTR_NOT_FOUND;
577 }
578 return ATTR_OKAY;
579}
580
581static 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",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000590 path.c_str(), parser.getLineNumber());
Adam Lesinski282e1812014-01-23 18:17:42 -0800591 }
592 }
593 }
594}
595
596static 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) {
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -0700617 const sp<ResourceTypeSet>& overlaySet = overlayRes->valueAt(index);
Adam Lesinski282e1812014-01-23 18:17:42 -0800618
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()) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000624 printf("trying overlaySet Key=%s\n",overlaySet->keyAt(overlayIndex).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800625 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700626 ssize_t baseIndex = -1;
Adam Lesinski282e1812014-01-23 18:17:42 -0800627 if (baseSet->get() != NULL) {
628 baseIndex = (*baseSet)->indexOfKey(overlaySet->keyAt(overlayIndex));
629 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700630 if (baseIndex >= 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800631 // 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,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000644 baseFiles.keyAt(i).toString().c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800645 }
646 for (size_t i=0; i < overlayFiles.size(); i++) {
647 printf("overlayFile " ZD " has flavor %s\n", (ZD_TYPE) i,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000648 overlayFiles.keyAt(i).toString().c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800649 }
650 }
651
652 size_t overlayGroupSize = overlayFiles.size();
653 for (size_t overlayGroupIndex = 0;
654 overlayGroupIndex<overlayGroupSize;
655 overlayGroupIndex++) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700656 ssize_t baseFileIndex =
Adam Lesinski282e1812014-01-23 18:17:42 -0800657 baseGroup->getFiles().indexOfKey(overlayFiles.
658 keyAt(overlayGroupIndex));
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700659 if (baseFileIndex >= 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800660 if (bundle->getVerbose()) {
661 printf("found a match (" ZD ") for overlay file %s, for flavor %s\n",
662 (ZD_TYPE) baseFileIndex,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000663 overlayGroup->getLeaf().c_str(),
664 overlayFiles.keyAt(overlayGroupIndex).toString().c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800665 }
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",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000671 overlayGroup->getLeaf().c_str(),
672 overlayFiles.keyAt(overlayGroupIndex).toString().c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800673 }
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/*
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800707 * Inserts an attribute in a given node.
Adam Lesinski282e1812014-01-23 18:17:42 -0800708 * If errorOnFailedInsert is true, and the attribute already exists, returns false.
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800709 * 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.
Adam Lesinski282e1812014-01-23 18:17:42 -0800712 */
713bool addTagAttribute(const sp<XMLNode>& node, const char* ns8,
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800714 const char* attr8, const char* value, bool errorOnFailedInsert,
715 bool replaceExisting)
Adam Lesinski282e1812014-01-23 18:17:42 -0800716{
717 if (value == NULL) {
718 return true;
719 }
720
721 const String16 ns(ns8);
722 const String16 attr(attr8);
723
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800724 XMLNode::attribute_entry* existingEntry = node->editAttribute(ns, attr);
725 if (existingEntry != NULL) {
726 if (replaceExisting) {
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800727 existingEntry->string = String16(value);
728 return true;
729 }
730
Adam Lesinski282e1812014-01-23 18:17:42 -0800731 if (errorOnFailedInsert) {
732 fprintf(stderr, "Error: AndroidManifest.xml already defines %s (in %s);"
733 " cannot insert new value %s.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000734 String8(attr).c_str(), String8(ns).c_str(), value);
Adam Lesinski282e1812014-01-23 18:17:42 -0800735 return false;
736 }
737
Adam Lesinski282e1812014-01-23 18:17:42 -0800738 // don't stop the build.
739 return true;
740 }
741
742 node->addAttribute(ns, attr, String16(value));
743 return true;
744}
745
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800746/*
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 */
752bool 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
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -0700758static void fullyQualifyClassName(const String8& package, const sp<XMLNode>& node,
Adam Lesinski282e1812014-01-23 18:17:42 -0800759 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;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000769 const char* p = name.c_str();
Adam Lesinski282e1812014-01-23 18:17:42 -0800770 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 }
Andreas Gampe2412f842014-09-30 20:55:57 -0700781 if (kIsDebug) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000782 printf("Qualifying class '%s' to '%s'", name.c_str(), className.c_str());
Andreas Gampe2412f842014-09-30 20:55:57 -0700783 }
Tomasz Wasilczyk31eb3c892023-08-23 22:12:33 +0000784 attr->string = String16(className);
Adam Lesinski282e1812014-01-23 18:17:42 -0800785 }
786}
787
Adam Lesinski99d36ee2017-04-17 16:22:03 -0700788static 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
800static 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
810static 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;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000816 if (!ResTable::expandResourceRef(iconRef.c_str(), iconRef.size(), &iconPackage, &iconType,
Adam Lesinski99d36ee2017-04-17 16:22:03 -0700817 &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;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000830 if (!ResTable::expandResourceRef(roundIconRef.c_str(), roundIconRef.size(), &roundIconPackage,
Adam Lesinski99d36ee2017-04-17 16:22:03 -0700831 &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
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000845 String16 aliasValue = String16(String8::format("@%s:%s/%s", String8(iconPackage).c_str(),
846 String8(iconType).c_str(),
847 String8(iconName).c_str()));
Adam Lesinski99d36ee2017-04-17 16:22:03 -0700848
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
860status_t massageManifest(Bundle* bundle, ResourceTable* table, sp<XMLNode> root)
Adam Lesinski282e1812014-01-23 18:17:42 -0800861{
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();
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800869 bool replaceVersion = bundle->getReplaceVersion();
Adam Lesinski282e1812014-01-23 18:17:42 -0800870
871 if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionCode",
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800872 bundle->getVersionCode(), errorOnFailedInsert, replaceVersion)) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800873 return UNKNOWN_ERROR;
Adam Lesinski6a7d2752014-08-07 21:26:53 -0700874 } else {
875 const XMLNode::attribute_entry* attr = root->getAttribute(
876 String16(RESOURCES_ANDROID_NAMESPACE), String16("versionCode"));
877 if (attr != NULL) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000878 bundle->setVersionCode(strdup(String8(attr->string).c_str()));
Adam Lesinski6a7d2752014-08-07 21:26:53 -0700879 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800880 }
Adam Lesinski6a7d2752014-08-07 21:26:53 -0700881
Adam Lesinski282e1812014-01-23 18:17:42 -0800882 if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionName",
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800883 bundle->getVersionName(), errorOnFailedInsert, replaceVersion)) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800884 return UNKNOWN_ERROR;
Adam Lesinski82a2dd82014-09-17 18:34:15 -0700885 } else {
886 const XMLNode::attribute_entry* attr = root->getAttribute(
887 String16(RESOURCES_ANDROID_NAMESPACE), String16("versionName"));
888 if (attr != NULL) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000889 bundle->setVersionName(strdup(String8(attr->string).c_str()));
Adam Lesinski82a2dd82014-09-17 18:34:15 -0700890 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800891 }
892
Adam Lesinski82a2dd82014-09-17 18:34:15 -0700893 sp<XMLNode> vers = root->getChildElement(String16(), String16("uses-sdk"));
Adam Lesinski282e1812014-01-23 18:17:42 -0800894 if (bundle->getMinSdkVersion() != NULL
895 || bundle->getTargetSdkVersion() != NULL
896 || bundle->getMaxSdkVersion() != NULL) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800897 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
Adam Lesinski82a2dd82014-09-17 18:34:15 -0700916 if (vers != NULL) {
917 const XMLNode::attribute_entry* attr = vers->getAttribute(
918 String16(RESOURCES_ANDROID_NAMESPACE), String16("minSdkVersion"));
919 if (attr != NULL) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000920 bundle->setMinSdkVersion(strdup(String8(attr->string).c_str()));
Adam Lesinski82a2dd82014-09-17 18:34:15 -0700921 }
922 }
923
Alan Viverette11be9312017-11-09 15:41:44 -0500924
925 if (bundle->getCompileSdkVersion() != 0) {
926 if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "compileSdkVersion",
Tomasz Wasilczyk835dfe52023-08-17 16:27:22 +0000927 String8::format("%d", bundle->getCompileSdkVersion()).c_str(),
Alan Viverette11be9312017-11-09 15:41:44 -0500928 errorOnFailedInsert, true)) {
929 return UNKNOWN_ERROR;
930 }
931 }
932
933 if (bundle->getCompileSdkVersionCodename() != "") {
934 if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "compileSdkVersionCodename",
Tomasz Wasilczyk835dfe52023-08-17 16:27:22 +0000935 bundle->getCompileSdkVersionCodename().c_str(), errorOnFailedInsert, true)) {
Alan Viverette11be9312017-11-09 15:41:44 -0500936 return UNKNOWN_ERROR;
937 }
938 }
939
Adam Lesinskiad2d07d2014-08-27 16:21:08 -0700940 if (bundle->getPlatformBuildVersionCode() != "") {
941 if (!addTagAttribute(root, "", "platformBuildVersionCode",
Tomasz Wasilczyk835dfe52023-08-17 16:27:22 +0000942 bundle->getPlatformBuildVersionCode().c_str(), errorOnFailedInsert, true)) {
Adam Lesinskiad2d07d2014-08-27 16:21:08 -0700943 return UNKNOWN_ERROR;
944 }
945 }
946
947 if (bundle->getPlatformBuildVersionName() != "") {
948 if (!addTagAttribute(root, "", "platformBuildVersionName",
Tomasz Wasilczyk835dfe52023-08-17 16:27:22 +0000949 bundle->getPlatformBuildVersionName().c_str(), errorOnFailedInsert, true)) {
Adam Lesinskiad2d07d2014-08-27 16:21:08 -0700950 return UNKNOWN_ERROR;
951 }
952 }
953
Adam Lesinski282e1812014-01-23 18:17:42 -0800954 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);
Tomasz Wasilczyk31eb3c892023-08-23 22:12:33 +0000974 attr->string = String16(manifestPackageNameOverride);
Andreas Gampe2412f842014-09-30 20:55:57 -0700975 if (kIsDebug) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000976 printf("Overriding package '%s' to be '%s'\n", origPackage.c_str(),
Andreas Gampe2412f842014-09-30 20:55:57 -0700977 manifestPackageNameOverride);
978 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800979
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(
Adam Lesinski99d36ee2017-04-17 16:22:03 -07001010 String16(RESOURCES_ANDROID_NAMESPACE), String16("targetPackage"));
Adam Lesinski282e1812014-01-23 18:17:42 -08001011 if (attr != NULL) {
Tomasz Wasilczyk31eb3c892023-08-23 22:12:33 +00001012 attr->string = String16(instrumentationPackageNameOverride);
Adam Lesinski282e1812014-01-23 18:17:42 -08001013 }
1014 }
1015 }
1016 }
1017
Adam Lesinski99d36ee2017-04-17 16:22:03 -07001018 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
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001031 // 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
Adam Lesinski282e1812014-01-23 18:17:42 -08001043 return NO_ERROR;
1044}
1045
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001046static 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
1069enum {
1070 VERSION_CODE_ATTR = 0x0101021b,
1071 VERSION_NAME_ATTR = 0x0101021c,
1072};
1073
Alan Viverette11be9312017-11-09 15:41:44 -05001074static 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");
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001077 const bool useCompileSdkVersion = table.identifierForName(compileSdkVersionName.c_str(),
Alan Viverette11be9312017-11-09 15:41:44 -05001078 compileSdkVersionName.size()) != 0u;
1079
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001080 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
Alan Viverette11be9312017-11-09 15:41:44 -05001109 if (useCompileSdkVersion && versionCode >= 0 && bundle->getCompileSdkVersion() == 0) {
1110 bundle->setCompileSdkVersion(versionCode);
1111 }
1112
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001113 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 }
Alan Viverette11be9312017-11-09 15:41:44 -05001122
1123 if (useCompileSdkVersion && versionName != ""
1124 && bundle->getCompileSdkVersionCodename() == "") {
1125 bundle->setCompileSdkVersionCodename(versionName);
1126 }
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001127 return NO_ERROR;
1128 }
1129
1130 fprintf(stderr, "ERROR: no <manifest> tag found in platform AndroidManifest.xml\n");
1131 return UNKNOWN_ERROR;
1132}
1133
1134static ssize_t extractPlatformBuildVersion(AssetManager& assets, Bundle* bundle) {
1135 int32_t cookie = getPlatformAssetCookie(assets);
1136 if (cookie == 0) {
Adam Lesinski82a2dd82014-09-17 18:34:15 -07001137 // No platform was loaded.
1138 return NO_ERROR;
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001139 }
1140
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001141 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;
Adam Lesinski193ed742016-08-15 14:19:46 -07001148
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 {
Alan Viverette11be9312017-11-09 15:41:44 -05001157 result = extractPlatformBuildVersion(assets.getResources(true), tree, bundle);
Adam Lesinski193ed742016-08-15 14:19:46 -07001158 }
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001159 }
1160
1161 delete asset;
1162 return result;
1163}
1164
Adam Lesinski282e1812014-01-23 18:17:42 -08001165#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
1173status_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
Jeff Sharkey2cfc8482014-07-09 16:10:16 -07001202status_t generateAndroidManifestForSplit(Bundle* bundle, const sp<AaptAssets>& assets,
1203 const sp<ApkSplit>& split, sp<AaptFile>& outFile, ResourceTable* table) {
Adam Lesinskifab50872014-04-16 14:40:42 -07001204 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
Jeff Sharkey2cfc8482014-07-09 16:10:16 -07001212 // Add the 'package' attribute which is set to the package name.
Tomasz Wasilczyk835dfe52023-08-17 16:27:22 +00001213 const char* packageName = assets->getPackage().c_str();
Jeff Sharkey2cfc8482014-07-09 16:10:16 -07001214 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 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001225
Adam Lesinski54de2982014-12-16 09:16:26 -08001226 // 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",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001229 bundle->getRevisionCode().c_str(), true, true)) {
Adam Lesinski54de2982014-12-16 09:16:26 -08001230 return UNKNOWN_ERROR;
1231 }
1232 }
1233
Adam Lesinskifab50872014-04-16 14:40:42 -07001234 // Add the 'split' attribute which describes the configurations included.
Adam Lesinski62408402014-08-07 21:26:53 -07001235 String8 splitName("config.");
1236 splitName.append(split->getPackageSafeName());
Adam Lesinskifab50872014-04-16 14:40:42 -07001237 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"));
Jeff Sharkey78a13012014-07-15 20:18:34 -07001241
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
Adam Lesinskifab50872014-04-16 14:40:42 -07001248 manifest->addChild(app);
1249 root->addChild(manifest);
1250
Adam Lesinskie572c012014-09-19 15:10:04 -07001251 int err = compileXmlFile(bundle, assets, String16(), root, outFile, table);
Jeff Sharkey2cfc8482014-07-09 16:10:16 -07001252 if (err < NO_ERROR) {
Adam Lesinskifab50872014-04-16 14:40:42 -07001253 return err;
1254 }
1255 outFile->setCompressionMethod(ZipEntry::kCompressDeflated);
1256 return NO_ERROR;
1257}
1258
1259status_t buildResources(Bundle* bundle, const sp<AaptAssets>& assets, sp<ApkBuilder>& builder)
Adam Lesinski282e1812014-01-23 18:17:42 -08001260{
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
Andreas Gampe2412f842014-09-30 20:55:57 -07001275 if (kIsDebug) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001276 printf("Creating resources for package %s\n", assets->getPackage().c_str());
Andreas Gampe2412f842014-09-30 20:55:57 -07001277 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001278
Adam Lesinski78713992015-12-07 14:02:15 -08001279 // 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
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001285 ResourceTable::PackageType packageType = ResourceTable::App;
1286 if (bundle->getBuildSharedLibrary()) {
1287 packageType = ResourceTable::SharedLibrary;
1288 } else if (bundle->getExtending()) {
1289 packageType = ResourceTable::System;
Tomasz Wasilczyk7e22cab2023-08-24 19:02:33 +00001290 } else if (!bundle->getFeatureOfPackage().empty()) {
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001291 packageType = ResourceTable::AppFeature;
1292 }
1293
1294 ResourceTable table(bundle, String16(assets->getPackage()), packageType);
Adam Lesinski282e1812014-01-23 18:17:42 -08001295 err = table.addIncludedResources(bundle, assets);
1296 if (err != NO_ERROR) {
1297 return err;
1298 }
1299
Andreas Gampe2412f842014-09-30 20:55:57 -07001300 if (kIsDebug) {
1301 printf("Found %d included resource packages\n", (int)table.size());
1302 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001303
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;
Adam Lesinski282e1812014-01-23 18:17:42 -08001330 sp<ResourceTypeSet> xmls;
1331 sp<ResourceTypeSet> raws;
1332 sp<ResourceTypeSet> colors;
1333 sp<ResourceTypeSet> menus;
1334 sp<ResourceTypeSet> mipmaps;
Adam Lesinski9bbe7872017-01-24 13:52:04 -08001335 sp<ResourceTypeSet> fonts;
Adam Lesinski282e1812014-01-23 18:17:42 -08001336
1337 ASSIGN_IT(drawable);
1338 ASSIGN_IT(layout);
1339 ASSIGN_IT(anim);
1340 ASSIGN_IT(animator);
1341 ASSIGN_IT(interpolator);
1342 ASSIGN_IT(transition);
Adam Lesinski282e1812014-01-23 18:17:42 -08001343 ASSIGN_IT(xml);
1344 ASSIGN_IT(raw);
1345 ASSIGN_IT(color);
1346 ASSIGN_IT(menu);
1347 ASSIGN_IT(mipmap);
Adam Lesinski9bbe7872017-01-24 13:52:04 -08001348 ASSIGN_IT(font);
Adam Lesinski282e1812014-01-23 18:17:42 -08001349
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") ||
Adam Lesinski282e1812014-01-23 18:17:42 -08001367 !applyFileOverlay(bundle, assets, &xmls, "xml") ||
1368 !applyFileOverlay(bundle, assets, &raws, "raw") ||
1369 !applyFileOverlay(bundle, assets, &colors, "color") ||
1370 !applyFileOverlay(bundle, assets, &menus, "menu") ||
Adam Lesinski9bbe7872017-01-24 13:52:04 -08001371 !applyFileOverlay(bundle, assets, &fonts, "font") ||
Adam Lesinski282e1812014-01-23 18:17:42 -08001372 !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
Adam Lesinski9bbe7872017-01-24 13:52:04 -08001406 if (fonts != NULL) {
1407 err = makeFileResources(bundle, assets, &table, fonts, "font");
1408 if (err != NO_ERROR) {
1409 hasErrors = true;
1410 }
1411 }
1412
Adam Lesinski282e1812014-01-23 18:17:42 -08001413 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
Adam Lesinski282e1812014-01-23 18:17:42 -08001441 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) {
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -07001473 const sp<AaptFile>& file = it.getFile();
Adam Lesinski282e1812014-01-23 18:17:42 -08001474 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
Adam Lesinski526d73b2016-07-18 17:01:14 -07001498 if (hasErrors) {
1499 return UNKNOWN_ERROR;
1500 }
1501
Adam Lesinski282e1812014-01-23 18:17:42 -08001502 // --------------------------------------------------------------------
1503 // Assignment of resource IDs and initial generation of resource table.
1504 // --------------------------------------------------------------------
1505
1506 if (table.hasResources()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001507 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();
Adam Lesinskie572c012014-09-19 15:10:04 -07001522 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1523 it.getFile(), &table, xmlFlags);
Adam Lesinskicf1f1d92017-03-16 16:54:23 -07001524 // Only verify IDs if there was no error and the file is non-empty.
1525 if (err == NO_ERROR && it.getFile()->hasData()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001526 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) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001543 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1544 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001545 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) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001559 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1560 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001561 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) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001575 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1576 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001577 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) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001591 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1592 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001593 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
Adam Lesinski282e1812014-01-23 18:17:42 -08001604 if (xmls != NULL) {
1605 ResourceDirIterator it(xmls, String8("xml"));
1606 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001607 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1608 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001609 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) {
Adam Lesinskifab50872014-04-16 14:40:42 -07001621 ResourceDirIterator it(drawables, String8("drawable"));
1622 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001623 err = postProcessImage(bundle, assets, &table, it.getFile());
Adam Lesinskifab50872014-04-16 14:40:42 -07001624 if (err != NO_ERROR) {
1625 hasErrors = true;
1626 }
1627 }
1628
1629 if (err < NO_ERROR) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001630 hasErrors = true;
1631 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001632 err = NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001633 }
1634
Adam Lesinski2d6fa032017-03-10 18:42:32 -08001635 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
Adam Lesinski282e1812014-01-23 18:17:42 -08001650 if (colors != NULL) {
1651 ResourceDirIterator it(colors, String8("color"));
1652 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001653 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1654 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001655 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();
Adam Lesinskie572c012014-09-19 15:10:04 -07001670 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1671 it.getFile(), &table, xmlFlags);
Adam Lesinskicf1f1d92017-03-16 16:54:23 -07001672 if (err == NO_ERROR && it.getFile()->hasData()) {
Adam Lesinskifab50872014-04-16 14:40:42 -07001673 ResXMLTree block;
1674 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
1675 checkForIds(src, block);
1676 } else {
Adam Lesinski282e1812014-01-23 18:17:42 -08001677 hasErrors = true;
1678 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001679 }
1680
1681 if (err < NO_ERROR) {
1682 hasErrors = true;
1683 }
1684 err = NO_ERROR;
1685 }
1686
Adam Lesinski9bbe7872017-01-24 13:52:04 -08001687 if (fonts != NULL) {
1688 ResourceDirIterator it(fonts, String8("font"));
1689 while ((err=it.next()) == NO_ERROR) {
1690 // fonts can be resources other than xml.
Tomasz Wasilczyk804e8192023-08-23 02:22:53 +00001691 if (getPathExtension(it.getFile()->getPath()) == ".xml") {
Adam Lesinski9bbe7872017-01-24 13:52:04 -08001692 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
Adam Lesinskie572c012014-09-19 15:10:04 -07001707 // Now compile any generated resources.
1708 std::queue<CompileResourceWorkItem>& workQueue = table.getWorkQueue();
1709 while (!workQueue.empty()) {
1710 CompileResourceWorkItem& workItem = workQueue.front();
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07001711 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
Adam Lesinskicf1f1d92017-03-16 16:54:23 -07001720 if (err == NO_ERROR && workItem.file->hasData()) {
Tomasz Wasilczyk804e8192023-08-23 02:22:53 +00001721 assets->addResource(getPathLeaf(workItem.resPath),
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07001722 workItem.resPath,
1723 workItem.file,
1724 workItem.file->getResourceType());
Adam Lesinskie572c012014-09-19 15:10:04 -07001725 } else {
1726 hasErrors = true;
1727 }
1728 workQueue.pop();
1729 }
1730
Adam Lesinski282e1812014-01-23 18:17:42 -08001731 if (table.validateLocalizations()) {
1732 hasErrors = true;
1733 }
1734
1735 if (hasErrors) {
1736 return UNKNOWN_ERROR;
1737 }
1738
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001739 // If we're not overriding the platform build versions,
1740 // extract them from the platform APK.
1741 if (packageType != ResourceTable::System &&
1742 (bundle->getPlatformBuildVersionCode() == "" ||
Alan Viverette11be9312017-11-09 15:41:44 -05001743 bundle->getPlatformBuildVersionName() == "" ||
1744 bundle->getCompileSdkVersion() == 0 ||
1745 bundle->getCompileSdkVersionCodename() == "")) {
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001746 err = extractPlatformBuildVersion(assets->getAssetManager(), bundle);
1747 if (err != NO_ERROR) {
1748 return UNKNOWN_ERROR;
1749 }
1750 }
1751
Adam Lesinski282e1812014-01-23 18:17:42 -08001752 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 }
Adam Lesinski99d36ee2017-04-17 16:22:03 -07001761 err = massageManifest(bundle, &table, manifestTree);
Adam Lesinski282e1812014-01-23 18:17:42 -08001762 if (err < NO_ERROR) {
1763 return err;
1764 }
Adam Lesinskie572c012014-09-19 15:10:04 -07001765 err = compileXmlFile(bundle, assets, String16(), manifestTree, manifestFile, &table);
Adam Lesinski282e1812014-01-23 18:17:42 -08001766 if (err < NO_ERROR) {
1767 return err;
1768 }
1769
Adam Lesinski82a2dd82014-09-17 18:34:15 -07001770 if (table.modifyForCompat(bundle) != NO_ERROR) {
1771 return UNKNOWN_ERROR;
1772 }
1773
Adam Lesinski282e1812014-01-23 18:17:42 -08001774 //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
Adam Lesinskide7de472014-11-03 12:03:08 -08001782
Adam Lesinski282e1812014-01-23 18:17:42 -08001783 ResTable finalResTable;
1784 sp<AaptFile> resFile;
1785
1786 if (table.hasResources()) {
1787 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
Adrian Roos58922482015-06-01 17:59:41 -07001788 err = table.addSymbols(symbols, bundle->getSkipSymbolsWithoutDefaultLocalization());
Adam Lesinski282e1812014-01-23 18:17:42 -08001789 if (err < NO_ERROR) {
1790 return err;
1791 }
1792
Adam Lesinskide7de472014-11-03 12:03:08 -08001793 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
Adam Lesinskifab50872014-04-16 14:40:42 -07001800 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());
Adam Lesinski27f69f42014-08-21 13:19:12 -07001806 err = table.flatten(bundle, split->getResourceFilter(),
1807 flattenedTable, split->isBase());
Adam Lesinskifab50872014-04-16 14:40:42 -07001808 if (err != NO_ERROR) {
1809 fprintf(stderr, "Failed to generate resource table for split '%s'\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001810 split->getPrintableName().c_str());
Adam Lesinskifab50872014-04-16 14:40:42 -07001811 return err;
1812 }
1813 split->addEntry(String8("resources.arsc"), flattenedTable);
Adam Lesinski282e1812014-01-23 18:17:42 -08001814
Adam Lesinskifab50872014-04-16 14:40:42 -07001815 if (split->isBase()) {
1816 resFile = flattenedTable;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07001817 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 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001822 } else {
Adam Lesinskide7de472014-11-03 12:03:08 -08001823 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",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001827 split->getPrintableName().c_str());
Adam Lesinskide7de472014-11-03 12:03:08 -08001828 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'",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001855 symbol.toString().c_str(), config.toString().c_str());
Adam Lesinskide7de472014-11-03 12:03:08 -08001856
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",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001863 symbol.toString().c_str(), def.config.toString().c_str());
Adam Lesinskide7de472014-11-03 12:03:08 -08001864 }
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.
Adam Lesinskifab50872014-04-16 14:40:42 -07001880 sp<AaptFile> generatedManifest = new AaptFile(String8("AndroidManifest.xml"),
1881 AaptGroupEntry(), String8());
Jeff Sharkey2cfc8482014-07-09 16:10:16 -07001882 err = generateAndroidManifestForSplit(bundle, assets, split,
1883 generatedManifest, &table);
Adam Lesinskifab50872014-04-16 14:40:42 -07001884 if (err != NO_ERROR) {
1885 fprintf(stderr, "Failed to generate AndroidManifest.xml for split '%s'\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001886 split->getPrintableName().c_str());
Adam Lesinskifab50872014-04-16 14:40:42 -07001887 return err;
1888 }
1889 split->addEntry(String8("AndroidManifest.xml"), generatedManifest);
1890 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001891 }
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 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001906
1907 if (finalResTable.getTableCount() == 0 || resFile == NULL) {
1908 fprintf(stderr, "No resource table was generated.\n");
1909 return UNKNOWN_ERROR;
1910 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001911 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001912
Adam Lesinski282e1812014-01-23 18:17:42 -08001913 // 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());
Adam Lesinskie572c012014-09-19 15:10:04 -07001920 err = compileXmlFile(bundle, assets, String16(), manifestFile,
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07001921 outManifestFile, &table, XML_COMPILE_STANDARD_RESOURCE & ~XML_COMPILE_STRIP_COMMENTS);
Adam Lesinski282e1812014-01-23 18:17:42 -08001922 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");
Adam Lesinskid3edfde2014-08-08 17:32:44 -07001940 String16 feature_group16("feature-group");
1941 String16 uses_feature16("uses-feature");
Adam Lesinski282e1812014-01-23 18:17:42 -08001942 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 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001966 if (strcmp16(block.getElementName(&len), manifest16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001967 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 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001975 } else if (strcmp16(block.getElementName(&len), permission16.c_str()) == 0
1976 || strcmp16(block.getElementName(&len), permission_group16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001977 const bool isGroup = strcmp16(block.getElementName(&len),
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001978 permission_group16.c_str()) == 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08001979 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");
Dan Albertf348c152014-09-08 18:28:00 -07002005 const char16_t* id = block.getAttributeStringValue(index, &len);
Adam Lesinski282e1812014-01-23 18:17:42 -08002006 if (id == NULL) {
2007 fprintf(stderr, "%s:%d: missing name attribute in element <%s>.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002008 manifestPath.c_str(), block.getLineNumber(),
2009 String8(block.getElementName(&len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002010 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",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002044 manifestPath.c_str(), block.getLineNumber(), idStr.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002045 hasErrors = true;
2046 }
2047 syms->addStringSymbol(String8(e), idStr, srcPos);
Dan Albertf348c152014-09-08 18:28:00 -07002048 const char16_t* cmt = block.getComment(&len);
Adam Lesinski282e1812014-01-23 18:17:42 -08002049 if (cmt != NULL && *cmt != 0) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002050 //printf("Comment of %s: %s\n", String8(e).c_str(),
2051 // String8(cmt).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002052 syms->appendComment(String8(e), String16(cmt), srcPos);
Adam Lesinski282e1812014-01-23 18:17:42 -08002053 }
2054 syms->makeSymbolPublic(String8(e), srcPos);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002055 } else if (strcmp16(block.getElementName(&len), uses_permission16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002056 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
2057 "name", packageIdentChars, true) != ATTR_OKAY) {
2058 hasErrors = true;
2059 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002060 } else if (strcmp16(block.getElementName(&len), instrumentation16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002061 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 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002070 } else if (strcmp16(block.getElementName(&len), application16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002071 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 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002090 } else if (strcmp16(block.getElementName(&len), provider16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002091 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 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002110 } 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) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002113 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 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002132 } else if (strcmp16(block.getElementName(&len), action16.c_str()) == 0
2133 || strcmp16(block.getElementName(&len), category16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002134 if (validateAttr(manifestPath, finalResTable, block,
2135 RESOURCES_ANDROID_NAMESPACE, "name",
2136 packageIdentChars, true) != ATTR_OKAY) {
2137 hasErrors = true;
2138 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002139 } else if (strcmp16(block.getElementName(&len), data16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002140 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 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002150 } else if (strcmp16(block.getElementName(&len), feature_group16.c_str()) == 0) {
Adam Lesinskid3edfde2014-08-08 17:32:44 -07002151 int depth = 1;
2152 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
2153 && code > ResXMLTree::BAD_DOCUMENT) {
2154 if (code == ResXMLTree::START_TAG) {
2155 depth++;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002156 if (strcmp16(block.getElementName(&len), uses_feature16.c_str()) == 0) {
Adam Lesinskid3edfde2014-08-08 17:32:44 -07002157 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",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002168 manifestPath.c_str(), block.getLineNumber());
Adam Lesinskid3edfde2014-08-08 17:32:44 -07002169 hasErrors = true;
2170 }
2171 }
2172 } else if (code == ResXMLTree::END_TAG) {
2173 depth--;
2174 if (depth == 0) {
2175 break;
2176 }
2177 }
2178 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002179 }
2180 }
2181 }
2182
Adam Lesinskid3edfde2014-08-08 17:32:44 -07002183 if (hasErrors) {
2184 return UNKNOWN_ERROR;
2185 }
2186
Adam Lesinski282e1812014-01-23 18:17:42 -08002187 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
2200static const char* getIndentSpace(int indent)
2201{
2202static const char whitespace[] =
2203" ";
2204
2205 return whitespace + sizeof(whitespace) - 1 - indent*4;
2206}
2207
2208static 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
2225static String8 getSymbolPackage(const String8& symbol, const sp<AaptAssets>& assets, bool pub) {
2226 ssize_t colon = symbol.find(":", 0);
2227 if (colon >= 0) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002228 return String8(symbol.c_str(), colon);
Adam Lesinski282e1812014-01-23 18:17:42 -08002229 }
2230 return pub ? assets->getPackage() : assets->getSymbolsPrivatePackage();
2231}
2232
2233static String8 getSymbolName(const String8& symbol) {
2234 ssize_t colon = symbol.find(":", 0);
2235 if (colon >= 0) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002236 return String8(symbol.c_str() + colon + 1);
Adam Lesinski282e1812014-01-23 18:17:42 -08002237 }
2238 return symbol;
2239}
2240
2241static 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",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002251 // name.c_str(), String8(asym->getComment(name)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002252 if (outTypeComment != NULL) {
2253 *outTypeComment = asym->getTypeComment(name);
2254 }
2255 return asym->getComment(name);
2256 }
2257 }
2258 return String16();
2259}
2260
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002261static status_t writeResourceLoadedCallbackForLayoutClasses(
2262 FILE* fp, const sp<AaptAssets>& assets,
Andreas Gampe87332a72014-10-01 22:03:58 -07002263 const sp<AaptSymbols>& symbols, int indent, bool /* includePrivate */)
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002264{
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",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002282 indentStr, nclassName.c_str(),
2283 getIndentSpace(indent+1), nclassName.c_str(), nclassName.c_str(),
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002284 indentStr);
Adam Lesinski1e4663852014-08-15 14:47:28 -07002285 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002286
Dan Alberted811ee2016-01-15 12:16:06 -08002287 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002288}
2289
2290static 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);
Adam Lesinskieed58582015-09-10 18:43:34 -07002300 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002301 continue;
Adam Lesinski1e4663852014-08-15 14:47:28 -07002302 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002303 if (!assets->isJavaSymbol(sym, includePrivate)) {
2304 continue;
Adam Lesinski1e4663852014-08-15 14:47:28 -07002305 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002306 String8 flat_name(flattenSymbol(sym.name));
2307 fprintf(fp,
2308 "%s%s.%s = (%s.%s & 0x00ffffff) | (packageId << 24);\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002309 getIndentSpace(indent), className.c_str(), flat_name.c_str(),
2310 className.c_str(), flat_name.c_str());
Adam Lesinski1e4663852014-08-15 14:47:28 -07002311 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002312
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);
Adam Lesinski1e4663852014-08-15 14:47:28 -07002323 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002324 if (err != NO_ERROR) {
2325 return err;
2326 }
Adam Lesinski1e4663852014-08-15 14:47:28 -07002327 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002328
2329 return NO_ERROR;
Adam Lesinski1e4663852014-08-15 14:47:28 -07002330}
2331
Adam Lesinski282e1812014-01-23 18:17:42 -08002332static status_t writeLayoutClasses(
2333 FILE* fp, const sp<AaptAssets>& assets,
Adam Lesinskie8e91922014-08-06 17:41:08 -07002334 const sp<AaptSymbols>& symbols, int indent, bool includePrivate, bool nonConstantId)
Adam Lesinski282e1812014-01-23 18:17:42 -08002335{
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(
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002371 name16.c_str(), name16.size(),
2372 attr16.c_str(), attr16.size(),
2373 package16.c_str(), package16.size(), &typeSpecFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08002374 if (code == 0) {
2375 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002376 nclassName.c_str(), sym.name.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002377 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
Adam Lesinski282e1812014-01-23 18:17:42 -08002388 String16 comment = symbols->getComment(realClassName);
Jeff Browneb490d62014-06-06 19:43:42 -07002389 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002390 fprintf(fp, "%s/** ", indentStr);
2391 if (comment.size() > 0) {
2392 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002393 ann.preprocessComment(cmt);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002394 fprintf(fp, "%s\n", cmt.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002395 } else {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002396 fprintf(fp, "Attributes that can be used with a %s.\n", nclassName.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002397 }
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 }
Michael Wrightfeaf99f2016-05-06 17:16:06 +01002425 if (comment.contains(u"@removed")) {
2426 continue;
2427 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002428 if (comment.size() > 0) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002429 const char16_t* p = comment.c_str();
Adam Lesinski282e1812014-01-23 18:17:42 -08002430 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 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002442 comment = String16(comment.c_str(), p-comment.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002443 }
2444 fprintf(fp, "%s <tr><td><code>{@link #%s_%s %s:%s}</code></td><td>%s</td></tr>\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002445 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());
Adam Lesinski282e1812014-01-23 18:17:42 -08002450 }
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",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002463 indentStr, nclassName.c_str(),
2464 flattenSymbol(sym.name).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002465 }
2466 }
2467 fprintf(fp, "%s */\n", getIndentSpace(indent));
2468
Jeff Browneb490d62014-06-06 19:43:42 -07002469 ann.printAnnotations(fp, indentStr);
Adam Lesinski282e1812014-01-23 18:17:42 -08002470
2471 fprintf(fp,
2472 "%spublic static final int[] %s = {\n"
2473 "%s",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002474 indentStr, nclassName.c_str(),
Adam Lesinski282e1812014-01-23 18:17:42 -08002475 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(
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002509 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);
Adam Lesinski282e1812014-01-23 18:17:42 -08002514 const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
Jeff Browneb490d62014-06-06 19:43:42 -07002515
2516 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002517 fprintf(fp, "%s/**\n", indentStr);
2518 if (comment.size() > 0) {
2519 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002520 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002521 fprintf(fp, "%s <p>\n%s @attr description\n", indentStr, indentStr);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002522 fprintf(fp, "%s %s\n", indentStr, cmt.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002523 } 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,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002528 getSymbolPackage(name8, assets, pub).c_str(),
2529 getSymbolName(name8).c_str(),
2530 indentStr, nclassName.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002531 }
2532 if (typeComment.size() > 0) {
2533 String8 cmt(typeComment);
Jeff Browneb490d62014-06-06 19:43:42 -07002534 ann.preprocessComment(cmt);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002535 fprintf(fp, "\n\n%s %s\n", indentStr, cmt.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002536 }
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,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002543 getSymbolPackage(name8, assets, true).c_str(),
2544 getSymbolName(name8).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002545 } 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,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002551 getSymbolPackage(name8, assets, pub).c_str(),
2552 getSymbolName(name8).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002553 fprintf(fp, "%s*/\n", indentStr);
Jeff Browneb490d62014-06-06 19:43:42 -07002554 ann.printAnnotations(fp, indentStr);
Adam Lesinskie8e91922014-08-06 17:41:08 -07002555
2556 const char * id_format = nonConstantId ?
2557 "%spublic static int %s_%s = %d;\n" :
2558 "%spublic static final int %s_%s = %d;\n";
2559
Adam Lesinski282e1812014-01-23 18:17:42 -08002560 fprintf(fp,
Adam Lesinskie8e91922014-08-06 17:41:08 -07002561 id_format,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002562 indentStr, nclassName.c_str(),
2563 flattenSymbol(name8).c_str(), (int)pos);
Adam Lesinski282e1812014-01-23 18:17:42 -08002564 }
2565 }
2566 }
2567
2568 indent--;
2569 fprintf(fp, "%s};\n", getIndentSpace(indent));
Andreas Gampe2412f842014-09-30 20:55:57 -07002570 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08002571}
2572
2573static 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(
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002604 name16.c_str(), name16.size(),
2605 attr16.c_str(), attr16.size(),
2606 package16.c_str(), package16.size(), &typeSpecFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08002607 if (code == 0) {
2608 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002609 nclassName.c_str(), sym.name.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002610 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
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002621 fprintf(fp, "int[] styleable %s {", nclassName.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002622
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(
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002651 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);
Andreas Gampe2412f842014-09-30 20:55:57 -07002656 //const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08002657
2658 fprintf(fp,
2659 "int styleable %s_%s %d\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002660 nclassName.c_str(),
2661 flattenSymbol(name8).c_str(), (int)pos);
Adam Lesinski282e1812014-01-23 18:17:42 -08002662 }
2663 }
2664 }
2665
Andreas Gampe2412f842014-09-30 20:55:57 -07002666 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08002667}
2668
2669static status_t writeSymbolClass(
2670 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2671 const sp<AaptSymbols>& symbols, const String8& className, int indent,
Adam Lesinski1e4663852014-08-15 14:47:28 -07002672 bool nonConstantId, bool emitCallback)
Adam Lesinski282e1812014-01-23 18:17:42 -08002673{
2674 fprintf(fp, "%spublic %sfinal class %s {\n",
2675 getIndentSpace(indent),
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002676 indent != 0 ? "static " : "", className.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002677 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;
Jeff Browneb490d62014-06-06 19:43:42 -07002698 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002699 if (comment.size() > 0) {
2700 haveComment = true;
2701 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002702 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002703 fprintf(fp,
2704 "%s/** %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002705 getIndentSpace(indent), cmt.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002706 }
2707 String16 typeComment(sym.typeComment);
2708 if (typeComment.size() > 0) {
2709 String8 cmt(typeComment);
Jeff Browneb490d62014-06-06 19:43:42 -07002710 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002711 if (!haveComment) {
2712 haveComment = true;
2713 fprintf(fp,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002714 "%s/** %s\n", getIndentSpace(indent), cmt.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002715 } else {
2716 fprintf(fp,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002717 "%s %s\n", getIndentSpace(indent), cmt.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002718 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002719 }
2720 if (haveComment) {
2721 fprintf(fp,"%s */\n", getIndentSpace(indent));
2722 }
Jeff Browneb490d62014-06-06 19:43:42 -07002723 ann.printAnnotations(fp, getIndentSpace(indent));
Adam Lesinski282e1812014-01-23 18:17:42 -08002724 fprintf(fp, id_format,
2725 getIndentSpace(indent),
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002726 flattenSymbol(name8).c_str(), (int)sym.int32Val);
Adam Lesinski282e1812014-01-23 18:17:42 -08002727 }
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);
Jeff Browneb490d62014-06-06 19:43:42 -07002739 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002740 if (comment.size() > 0) {
2741 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002742 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002743 fprintf(fp,
2744 "%s/** %s\n"
2745 "%s */\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002746 getIndentSpace(indent), cmt.c_str(),
Adam Lesinski282e1812014-01-23 18:17:42 -08002747 getIndentSpace(indent));
Adam Lesinski282e1812014-01-23 18:17:42 -08002748 }
Jeff Browneb490d62014-06-06 19:43:42 -07002749 ann.printAnnotations(fp, getIndentSpace(indent));
Adam Lesinski282e1812014-01-23 18:17:42 -08002750 fprintf(fp, "%spublic static final String %s=\"%s\";\n",
2751 getIndentSpace(indent),
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002752 flattenSymbol(name8).c_str(), sym.stringVal.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002753 }
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 {
Adam Lesinski1e4663852014-08-15 14:47:28 -07002764 err = writeSymbolClass(fp, assets, includePrivate, nsymbols, nclassName,
2765 indent, nonConstantId, false);
Adam Lesinski282e1812014-01-23 18:17:42 -08002766 }
2767 if (err != NO_ERROR) {
2768 return err;
2769 }
2770 }
2771
2772 if (styleableSymbols != NULL) {
Adam Lesinskie8e91922014-08-06 17:41:08 -07002773 err = writeLayoutClasses(fp, assets, styleableSymbols, indent, includePrivate, nonConstantId);
Adam Lesinski282e1812014-01-23 18:17:42 -08002774 if (err != NO_ERROR) {
2775 return err;
2776 }
2777 }
2778
Adam Lesinski1e4663852014-08-15 14:47:28 -07002779 if (emitCallback) {
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002780 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));
Adam Lesinski1e4663852014-08-15 14:47:28 -07002784 }
2785
Adam Lesinski282e1812014-01-23 18:17:42 -08002786 indent--;
2787 fprintf(fp, "%s}\n", getIndentSpace(indent));
2788 return NO_ERROR;
2789}
2790
2791static 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",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002811 className.c_str(),
2812 flattenSymbol(name8).c_str(), (int)sym.int32Val);
Adam Lesinski282e1812014-01-23 18:17:42 -08002813 }
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
2832status_t writeResourceSymbols(Bundle* bundle, const sp<AaptAssets>& assets,
Adam Lesinski1e4663852014-08-15 14:47:28 -07002833 const String8& package, bool includePrivate, bool emitCallback)
Adam Lesinski282e1812014-01-23 18:17:42 -08002834{
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()) {
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -07002849 const String8& pkg(package);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002850 const char* last = pkg.c_str();
Adam Lesinski282e1812014-01-23 18:17:42 -08002851 const char* s = last-1;
2852 do {
2853 s++;
2854 if (s > last && (*s == '.' || *s == 0)) {
2855 String8 part(last, s-last);
Tomasz Wasilczyk804e8192023-08-23 02:22:53 +00002856 appendPath(dest, part);
Elliott Hughese17788c2015-08-17 12:41:46 -07002857#ifdef _WIN32
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002858 _mkdir(dest.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002859#else
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002860 mkdir(dest.c_str(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP);
Adam Lesinski282e1812014-01-23 18:17:42 -08002861#endif
2862 last = s+1;
2863 }
2864 } while (*s);
2865 }
Tomasz Wasilczyk804e8192023-08-23 02:22:53 +00002866 appendPath(dest, className);
Adam Lesinski282e1812014-01-23 18:17:42 -08002867 dest.append(".java");
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002868 FILE* fp = fopen(dest.c_str(), "w+");
Adam Lesinski282e1812014-01-23 18:17:42 -08002869 if (fp == NULL) {
2870 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002871 dest.c_str(), strerror(errno));
Adam Lesinski282e1812014-01-23 18:17:42 -08002872 return UNKNOWN_ERROR;
2873 }
2874 if (bundle->getVerbose()) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002875 printf(" Writing symbols for class %s.\n", className.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002876 }
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"
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002886 "package %s;\n\n", package.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002887
2888 status_t err = writeSymbolClass(fp, assets, includePrivate, symbols,
Adam Lesinski1e4663852014-08-15 14:47:28 -07002889 className, 0, bundle->getNonConstantId(), emitCallback);
Elliott Hughesb30296b2013-10-29 15:25:52 -07002890 fclose(fp);
Adam Lesinski282e1812014-01-23 18:17:42 -08002891 if (err != NO_ERROR) {
2892 return err;
2893 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002894
2895 if (textSymbolsDest != NULL && R == className) {
2896 String8 textDest(textSymbolsDest);
Tomasz Wasilczyk804e8192023-08-23 02:22:53 +00002897 appendPath(textDest, className);
Adam Lesinski282e1812014-01-23 18:17:42 -08002898 textDest.append(".txt");
2899
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002900 FILE* fp = fopen(textDest.c_str(), "w+");
Adam Lesinski282e1812014-01-23 18:17:42 -08002901 if (fp == NULL) {
2902 fprintf(stderr, "ERROR: Unable to open text symbol file %s: %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002903 textDest.c_str(), strerror(errno));
Adam Lesinski282e1812014-01-23 18:17:42 -08002904 return UNKNOWN_ERROR;
2905 }
2906 if (bundle->getVerbose()) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002907 printf(" Writing text symbols for class %s.\n", className.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002908 }
2909
2910 status_t err = writeTextSymbolClass(fp, assets, includePrivate, symbols,
2911 className);
Elliott Hughesb30296b2013-10-29 15:25:52 -07002912 fclose(fp);
Adam Lesinski282e1812014-01-23 18:17:42 -08002913 if (err != NO_ERROR) {
2914 return err;
2915 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002916 }
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());
Tomasz Wasilczyk804e8192023-08-23 02:22:53 +00002923 appendPath(dependencyFile, "R.java.d");
Adam Lesinski282e1812014-01-23 18:17:42 -08002924
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002925 FILE *fp = fopen(dependencyFile.c_str(), "a");
2926 fprintf(fp,"%s \\\n", dest.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002927 fclose(fp);
2928 }
2929 }
2930
2931 return NO_ERROR;
2932}
2933
2934
2935class ProguardKeepSet
2936{
2937public:
2938 // { rule --> { file locations } }
2939 KeyedVector<String8, SortedVector<String8> > rules;
2940
2941 void add(const String8& rule, const String8& where);
2942};
2943
2944void 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
2953void
2954addProguardKeepRule(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
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002962 const char* p = className.c_str();
Adam Lesinski282e1812014-01-23 18:17:42 -08002963 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
2987void
2988addProguardKeepMethodRule(ProguardKeepSet* keep, const String8& memberName,
Andreas Gampe2412f842014-09-30 20:55:57 -07002989 const char* /* pkg */, const String8& srcName, int line)
Adam Lesinski282e1812014-01-23 18:17:42 -08002990{
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
3004status_t
Rohit Agrawal682583c2016-04-21 16:29:58 -07003005writeProguardForAndroidManifest(ProguardKeepSet* keep, const sp<AaptAssets>& assets, bool mainDex)
Adam Lesinski282e1812014-01-23 18:17:42 -08003006{
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;
Rohit Agrawal682583c2016-04-21 16:29:58 -07003017 String8 defaultProcess;
Adam Lesinski282e1812014-01-23 18:17:42 -08003018
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",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003029 assGroup->getFiles().valueAt(0)->getPrintableSource().c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003030 }
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));
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003054 // printf("Depth %d tag %s\n", depth, tag.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003055 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 }
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07003061 pkg = AaptXml::getAttribute(tree, NULL, "package");
Adam Lesinski282e1812014-01-23 18:17:42 -08003062 } else if (depth == 2) {
3063 if (tag == "application") {
3064 inApplication = true;
3065 keepTag = true;
3066
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07003067 String8 agent = AaptXml::getAttribute(tree,
3068 "http://schemas.android.com/apk/res/android",
Adam Lesinski282e1812014-01-23 18:17:42 -08003069 "backupAgent", &error);
3070 if (agent.length() > 0) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003071 addProguardKeepRule(keep, agent, pkg.c_str(),
Adam Lesinski282e1812014-01-23 18:17:42 -08003072 assFile->getPrintableSource(), tree.getLineNumber());
3073 }
Rohit Agrawal682583c2016-04-21 16:29:58 -07003074
3075 if (mainDex) {
3076 defaultProcess = AaptXml::getAttribute(tree,
3077 "http://schemas.android.com/apk/res/android", "process", &error);
3078 if (error != "") {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003079 fprintf(stderr, "ERROR: %s\n", error.c_str());
Rohit Agrawal682583c2016-04-21 16:29:58 -07003080 return -1;
3081 }
3082 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003083 } 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;
Ivan Gavrilovicf580d912016-07-19 12:03:33 +01003090
3091 if (mainDex) {
3092 String8 componentProcess = AaptXml::getAttribute(tree,
3093 "http://schemas.android.com/apk/res/android", "process", &error);
3094 if (error != "") {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003095 fprintf(stderr, "ERROR: %s\n", error.c_str());
Ivan Gavrilovicf580d912016-07-19 12:03:33 +01003096 return -1;
3097 }
3098
3099 const String8& process =
3100 componentProcess.length() > 0 ? componentProcess : defaultProcess;
3101 keepTag = process.length() > 0 && process.find(":") != 0;
3102 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003103 }
3104 }
3105 if (keepTag) {
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07003106 String8 name = AaptXml::getAttribute(tree,
3107 "http://schemas.android.com/apk/res/android", "name", &error);
Adam Lesinski282e1812014-01-23 18:17:42 -08003108 if (error != "") {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003109 fprintf(stderr, "ERROR: %s\n", error.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003110 return -1;
3111 }
Rohit Agrawal682583c2016-04-21 16:29:58 -07003112
3113 keepTag = name.length() > 0;
3114
Rohit Agrawal682583c2016-04-21 16:29:58 -07003115 if (keepTag) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003116 addProguardKeepRule(keep, name, pkg.c_str(),
Adam Lesinski282e1812014-01-23 18:17:42 -08003117 assFile->getPrintableSource(), tree.getLineNumber());
3118 }
3119 }
3120 }
3121
3122 return NO_ERROR;
3123}
3124
3125struct NamespaceAttributePair {
3126 const char* ns;
3127 const char* attr;
3128
3129 NamespaceAttributePair(const char* n, const char* a) : ns(n), attr(a) {}
3130 NamespaceAttributePair() : ns(NULL), attr(NULL) {}
3131};
3132
3133status_t
3134writeProguardForXml(ProguardKeepSet* keep, const sp<AaptFile>& layoutFile,
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003135 const Vector<String8>& startTags, const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs)
Adam Lesinski282e1812014-01-23 18:17:42 -08003136{
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
Tomasz Wasilczyk7e22cab2023-08-24 19:02:33 +00003149 if (!startTags.empty()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003150 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));
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003156 const size_t numStartTags = startTags.size();
3157 for (size_t i = 0; i < numStartTags; i++) {
3158 if (tag == startTags[i]) {
3159 haveStart = true;
3160 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003161 }
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.
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003176 if (strchr(tag.c_str(), '.')) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003177 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",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003189 // layoutFile->getPrintableSource().c_str(), tree.getLineNumber(),
3190 // tag.c_str(), nsAttr.ns, nsAttr.attr);
Adam Lesinski282e1812014-01-23 18:17:42 -08003191 } 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
3212static 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
3226status_t
3227writeProguardForLayouts(ProguardKeepSet* keep, const sp<AaptAssets>& assets)
3228{
3229 status_t err;
Adam Lesinski62c5df52014-12-02 16:19:05 -08003230 const char* kClass = "class";
3231 const char* kFragment = "fragment";
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003232 const String8 kTransition("transition");
3233 const String8 kTransitionPrefix("transition-");
Adam Lesinski282e1812014-01-23 18:17:42 -08003234
3235 // tag:attribute pairs that should be checked in layout files.
3236 KeyedVector<String8, Vector<NamespaceAttributePair> > kLayoutTagAttrPairs;
Adam Lesinski62c5df52014-12-02 16:19:05 -08003237 addTagAttrPair(&kLayoutTagAttrPairs, "view", NULL, kClass);
3238 addTagAttrPair(&kLayoutTagAttrPairs, kFragment, NULL, kClass);
3239 addTagAttrPair(&kLayoutTagAttrPairs, kFragment, RESOURCES_ANDROID_NAMESPACE, "name");
Adam Lesinski282e1812014-01-23 18:17:42 -08003240
3241 // tag:attribute pairs that should be checked in xml files.
3242 KeyedVector<String8, Vector<NamespaceAttributePair> > kXmlTagAttrPairs;
Adam Lesinski62c5df52014-12-02 16:19:05 -08003243 addTagAttrPair(&kXmlTagAttrPairs, "PreferenceScreen", RESOURCES_ANDROID_NAMESPACE, kFragment);
3244 addTagAttrPair(&kXmlTagAttrPairs, "header", RESOURCES_ANDROID_NAMESPACE, kFragment);
Adam Lesinski282e1812014-01-23 18:17:42 -08003245
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003246 // tag:attribute pairs that should be checked in transition files.
3247 KeyedVector<String8, Vector<NamespaceAttributePair> > kTransitionTagAttrPairs;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003248 addTagAttrPair(&kTransitionTagAttrPairs, kTransition.c_str(), NULL, kClass);
Adam Lesinski62c5df52014-12-02 16:19:05 -08003249 addTagAttrPair(&kTransitionTagAttrPairs, "pathMotion", NULL, kClass);
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003250
Adam Lesinski282e1812014-01-23 18:17:42 -08003251 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();
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003256 Vector<String8> startTags;
Adam Lesinski282e1812014-01-23 18:17:42 -08003257 const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs = NULL;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003258 if ((dirName == String8("layout")) || (strncmp(dirName.c_str(), "layout-", 7) == 0)) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003259 tagAttrPairs = &kLayoutTagAttrPairs;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003260 } else if ((dirName == String8("xml")) || (strncmp(dirName.c_str(), "xml-", 4) == 0)) {
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003261 startTags.add(String8("PreferenceScreen"));
3262 startTags.add(String8("preference-headers"));
Adam Lesinski282e1812014-01-23 18:17:42 -08003263 tagAttrPairs = &kXmlTagAttrPairs;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003264 } else if ((dirName == String8("menu")) || (strncmp(dirName.c_str(), "menu-", 5) == 0)) {
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003265 startTags.add(String8("menu"));
Adam Lesinski282e1812014-01-23 18:17:42 -08003266 tagAttrPairs = NULL;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003267 } else if (dirName == kTransition || (strncmp(dirName.c_str(), kTransitionPrefix.c_str(),
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003268 kTransitionPrefix.size()) == 0)) {
3269 tagAttrPairs = &kTransitionTagAttrPairs;
Adam Lesinski282e1812014-01-23 18:17:42 -08003270 } 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++) {
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003281 err = writeProguardForXml(keep, files.valueAt(j), startTags, tagAttrPairs);
Adam Lesinski282e1812014-01-23 18:17:42 -08003282 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
3297status_t
Rohit Agrawal682583c2016-04-21 16:29:58 -07003298writeProguardSpec(const char* filename, const ProguardKeepSet& keep, status_t err)
Adam Lesinski282e1812014-01-23 18:17:42 -08003299{
Rohit Agrawal682583c2016-04-21 16:29:58 -07003300 FILE* fp = fopen(filename, "w+");
Adam Lesinski282e1812014-01-23 18:17:42 -08003301 if (fp == NULL) {
3302 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
Rohit Agrawal682583c2016-04-21 16:29:58 -07003303 filename, strerror(errno));
Adam Lesinski282e1812014-01-23 18:17:42 -08003304 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++) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003313 fprintf(fp, "# %s\n", locations.itemAt(j).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003314 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003315 fprintf(fp, "%s\n\n", rules.keyAt(i).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003316 }
3317 fclose(fp);
3318
3319 return err;
3320}
3321
Rohit Agrawal682583c2016-04-21 16:29:58 -07003322status_t
3323writeProguardFile(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
3346status_t
3347writeMainDexProguardFile(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
Adam Lesinski282e1812014-01-23 18:17:42 -08003365// 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.
3367status_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
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003372 fprintf(fp, "%s \\\n", files->itemAt(file_i).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003373 deps++;
3374 }
3375 return deps;
3376}
3377
3378status_t
Andreas Gampe2412f842014-09-30 20:55:57 -07003379writeDependencyPreReqs(Bundle* /* bundle */, const sp<AaptAssets>& assets, FILE* fp, bool includeRaw)
Adam Lesinski282e1812014-01-23 18:17:42 -08003380{
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}