blob: 9c944e0de075211d3ed194ca84a56dde1916ad94 [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
Adam Lesinskide7de472014-11-03 12:03:08 -080022#include <algorithm>
23
Andreas Gampe2412f842014-09-30 20:55:57 -070024// STATUST: mingw does seem to redefine UNKNOWN_ERROR from our enum value, so a cast is necessary.
Adam Lesinski685d3632014-11-05 12:30:25 -080025
Elliott Hughesb12f2412015-04-03 12:56:45 -070026#if !defined(_WIN32)
Andreas Gampe2412f842014-09-30 20:55:57 -070027# define STATUST(x) x
Adam Lesinski282e1812014-01-23 18:17:42 -080028#else
Andreas Gampe2412f842014-09-30 20:55:57 -070029# define STATUST(x) (status_t)x
Adam Lesinski282e1812014-01-23 18:17:42 -080030#endif
31
Andreas Gampe2412f842014-09-30 20:55:57 -070032// Set to true for noisy debug output.
33static const bool kIsDebug = false;
Adam Lesinski282e1812014-01-23 18:17:42 -080034
35// Number of threads to use for preprocessing images.
36static const size_t MAX_THREADS = 4;
37
38// ==========================================================================
39// ==========================================================================
40// ==========================================================================
41
42class PackageInfo
43{
44public:
45 PackageInfo()
46 {
47 }
48 ~PackageInfo()
49 {
50 }
51
52 status_t parsePackage(const sp<AaptGroup>& grp);
53};
54
55// ==========================================================================
56// ==========================================================================
57// ==========================================================================
58
Adam Lesinskie572c012014-09-19 15:10:04 -070059String8 parseResourceName(const String8& leaf)
Adam Lesinski282e1812014-01-23 18:17:42 -080060{
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +000061 const char* firstDot = strchr(leaf.c_str(), '.');
62 const char* str = leaf.c_str();
Adam Lesinski282e1812014-01-23 18:17:42 -080063
64 if (firstDot) {
65 return String8(str, firstDot-str);
66 } else {
67 return String8(str);
68 }
69}
70
71ResourceTypeSet::ResourceTypeSet()
72 :RefBase(),
73 KeyedVector<String8,sp<AaptGroup> >()
74{
75}
76
77FilePathStore::FilePathStore()
78 :RefBase(),
79 Vector<String8>()
80{
81}
82
83class ResourceDirIterator
84{
85public:
86 ResourceDirIterator(const sp<ResourceTypeSet>& set, const String8& resType)
87 : mResType(resType), mSet(set), mSetPos(0), mGroupPos(0)
88 {
Narayan Kamath91447d82014-01-21 15:32:36 +000089 memset(&mParams, 0, sizeof(ResTable_config));
Adam Lesinski282e1812014-01-23 18:17:42 -080090 }
91
92 inline const sp<AaptGroup>& getGroup() const { return mGroup; }
93 inline const sp<AaptFile>& getFile() const { return mFile; }
94
95 inline const String8& getBaseName() const { return mBaseName; }
96 inline const String8& getLeafName() const { return mLeafName; }
97 inline String8 getPath() const { return mPath; }
98 inline const ResTable_config& getParams() const { return mParams; }
99
100 enum {
101 EOD = 1
102 };
103
104 ssize_t next()
105 {
106 while (true) {
107 sp<AaptGroup> group;
108 sp<AaptFile> file;
109
110 // Try to get next file in this current group.
111 if (mGroup != NULL && mGroupPos < mGroup->getFiles().size()) {
112 group = mGroup;
113 file = group->getFiles().valueAt(mGroupPos++);
114
115 // Try to get the next group/file in this directory
116 } else if (mSetPos < mSet->size()) {
117 mGroup = group = mSet->valueAt(mSetPos++);
118 if (group->getFiles().size() < 1) {
119 continue;
120 }
121 file = group->getFiles().valueAt(0);
122 mGroupPos = 1;
123
124 // All done!
125 } else {
126 return EOD;
127 }
128
129 mFile = file;
130
131 String8 leaf(group->getLeaf());
132 mLeafName = String8(leaf);
133 mParams = file->getGroupEntry().toParams();
Andreas Gampe2412f842014-09-30 20:55:57 -0700134 if (kIsDebug) {
135 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 +0000136 group->getPath().c_str(), mParams.mcc, mParams.mnc,
Andreas Gampe2412f842014-09-30 20:55:57 -0700137 mParams.language[0] ? mParams.language[0] : '-',
138 mParams.language[1] ? mParams.language[1] : '-',
139 mParams.country[0] ? mParams.country[0] : '-',
140 mParams.country[1] ? mParams.country[1] : '-',
141 mParams.orientation, mParams.uiMode,
142 mParams.density, mParams.touchscreen, mParams.keyboard,
143 mParams.inputFlags, mParams.navigation);
144 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800145 mPath = "res";
146 mPath.appendPath(file->getGroupEntry().toDirName(mResType));
147 mPath.appendPath(leaf);
148 mBaseName = parseResourceName(leaf);
149 if (mBaseName == "") {
150 fprintf(stderr, "Error: malformed resource filename %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000151 file->getPrintableSource().c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800152 return UNKNOWN_ERROR;
153 }
154
Andreas Gampe2412f842014-09-30 20:55:57 -0700155 if (kIsDebug) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000156 printf("file name=%s\n", mBaseName.c_str());
Andreas Gampe2412f842014-09-30 20:55:57 -0700157 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800158
159 return NO_ERROR;
160 }
161 }
162
163private:
164 String8 mResType;
165
166 const sp<ResourceTypeSet> mSet;
167 size_t mSetPos;
168
169 sp<AaptGroup> mGroup;
170 size_t mGroupPos;
171
172 sp<AaptFile> mFile;
173 String8 mBaseName;
174 String8 mLeafName;
175 String8 mPath;
176 ResTable_config mParams;
177};
178
Jeff Browneb490d62014-06-06 19:43:42 -0700179class AnnotationProcessor {
180public:
181 AnnotationProcessor() : mDeprecated(false), mSystemApi(false) { }
182
183 void preprocessComment(String8& comment) {
184 if (comment.size() > 0) {
185 if (comment.contains("@deprecated")) {
186 mDeprecated = true;
187 }
188 if (comment.removeAll("@SystemApi")) {
189 mSystemApi = true;
190 }
191 }
192 }
193
194 void printAnnotations(FILE* fp, const char* indentStr) {
195 if (mDeprecated) {
196 fprintf(fp, "%s@Deprecated\n", indentStr);
197 }
198 if (mSystemApi) {
199 fprintf(fp, "%s@android.annotation.SystemApi\n", indentStr);
200 }
201 }
202
203private:
204 bool mDeprecated;
205 bool mSystemApi;
206};
207
Adam Lesinski282e1812014-01-23 18:17:42 -0800208// ==========================================================================
209// ==========================================================================
210// ==========================================================================
211
212bool isValidResourceType(const String8& type)
213{
214 return type == "anim" || type == "animator" || type == "interpolator"
Adam Lesinski83b4f7d2017-01-20 13:19:27 -0800215 || type == "transition" || type == "font"
Adam Lesinski282e1812014-01-23 18:17:42 -0800216 || type == "drawable" || type == "layout"
217 || type == "values" || type == "xml" || type == "raw"
218 || type == "color" || type == "menu" || type == "mipmap";
219}
220
Adam Lesinski282e1812014-01-23 18:17:42 -0800221static status_t parsePackage(Bundle* bundle, const sp<AaptAssets>& assets,
222 const sp<AaptGroup>& grp)
223{
224 if (grp->getFiles().size() != 1) {
225 fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000226 grp->getFiles().valueAt(0)->getPrintableSource().c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800227 }
228
229 sp<AaptFile> file = grp->getFiles().valueAt(0);
230
231 ResXMLTree block;
232 status_t err = parseXMLResource(file, &block);
233 if (err != NO_ERROR) {
234 return err;
235 }
236 //printXMLBlock(&block);
237
238 ResXMLTree::event_code_t code;
239 while ((code=block.next()) != ResXMLTree::START_TAG
240 && code != ResXMLTree::END_DOCUMENT
241 && code != ResXMLTree::BAD_DOCUMENT) {
242 }
243
244 size_t len;
245 if (code != ResXMLTree::START_TAG) {
246 fprintf(stderr, "%s:%d: No start tag found\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000247 file->getPrintableSource().c_str(), block.getLineNumber());
Adam Lesinski282e1812014-01-23 18:17:42 -0800248 return UNKNOWN_ERROR;
249 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000250 if (strcmp16(block.getElementName(&len), String16("manifest").c_str()) != 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800251 fprintf(stderr, "%s:%d: Invalid start tag %s, expected <manifest>\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000252 file->getPrintableSource().c_str(), block.getLineNumber(),
253 String8(block.getElementName(&len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800254 return UNKNOWN_ERROR;
255 }
256
257 ssize_t nameIndex = block.indexOfAttribute(NULL, "package");
258 if (nameIndex < 0) {
259 fprintf(stderr, "%s:%d: <manifest> does not have package attribute.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000260 file->getPrintableSource().c_str(), block.getLineNumber());
Adam Lesinski282e1812014-01-23 18:17:42 -0800261 return UNKNOWN_ERROR;
262 }
263
264 assets->setPackage(String8(block.getAttributeStringValue(nameIndex, &len)));
265
Adam Lesinski54de2982014-12-16 09:16:26 -0800266 ssize_t revisionCodeIndex = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "revisionCode");
267 if (revisionCodeIndex >= 0) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000268 bundle->setRevisionCode(String8(block.getAttributeStringValue(revisionCodeIndex, &len)).c_str());
Adam Lesinski54de2982014-12-16 09:16:26 -0800269 }
270
Adam Lesinski282e1812014-01-23 18:17:42 -0800271 String16 uses_sdk16("uses-sdk");
272 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
273 && code != ResXMLTree::BAD_DOCUMENT) {
274 if (code == ResXMLTree::START_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000275 if (strcmp16(block.getElementName(&len), uses_sdk16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800276 ssize_t minSdkIndex = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE,
277 "minSdkVersion");
278 if (minSdkIndex >= 0) {
Dan Albertf348c152014-09-08 18:28:00 -0700279 const char16_t* minSdk16 = block.getAttributeStringValue(minSdkIndex, &len);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000280 const char* minSdk8 = strdup(String8(minSdk16).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800281 bundle->setManifestMinSdkVersion(minSdk8);
282 }
283 }
284 }
285 }
286
287 return NO_ERROR;
288}
289
290// ==========================================================================
291// ==========================================================================
292// ==========================================================================
293
294static status_t makeFileResources(Bundle* bundle, const sp<AaptAssets>& assets,
295 ResourceTable* table,
296 const sp<ResourceTypeSet>& set,
297 const char* resType)
298{
299 String8 type8(resType);
300 String16 type16(resType);
301
302 bool hasErrors = false;
303
304 ResourceDirIterator it(set, String8(resType));
305 ssize_t res;
306 while ((res=it.next()) == NO_ERROR) {
307 if (bundle->getVerbose()) {
308 printf(" (new resource id %s from %s)\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000309 it.getBaseName().c_str(), it.getFile()->getPrintableSource().c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800310 }
311 String16 baseName(it.getBaseName());
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000312 const char16_t* str = baseName.c_str();
Adam Lesinski282e1812014-01-23 18:17:42 -0800313 const char16_t* const end = str + baseName.size();
314 while (str < end) {
315 if (!((*str >= 'a' && *str <= 'z')
316 || (*str >= '0' && *str <= '9')
317 || *str == '_' || *str == '.')) {
318 fprintf(stderr, "%s: Invalid file name: must contain only [a-z0-9_.]\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000319 it.getPath().c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800320 hasErrors = true;
321 }
322 str++;
323 }
324 String8 resPath = it.getPath();
Elliott Hughes338698e2021-07-13 17:15:19 -0700325 convertToResPath(resPath);
Adam Lesinski526d73b2016-07-18 17:01:14 -0700326 status_t result = table->addEntry(SourcePos(it.getPath(), 0),
327 String16(assets->getPackage()),
Adam Lesinski282e1812014-01-23 18:17:42 -0800328 type16,
329 baseName,
330 String16(resPath),
331 NULL,
332 &it.getParams());
Adam Lesinski526d73b2016-07-18 17:01:14 -0700333 if (result != NO_ERROR) {
334 hasErrors = true;
335 } else {
336 assets->addResource(it.getLeafName(), resPath, it.getFile(), type8);
337 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800338 }
339
Andreas Gampe2412f842014-09-30 20:55:57 -0700340 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -0800341}
342
343class PreProcessImageWorkUnit : public WorkQueue::WorkUnit {
344public:
345 PreProcessImageWorkUnit(const Bundle* bundle, const sp<AaptAssets>& assets,
346 const sp<AaptFile>& file, volatile bool* hasErrors) :
347 mBundle(bundle), mAssets(assets), mFile(file), mHasErrors(hasErrors) {
348 }
349
350 virtual bool run() {
351 status_t status = preProcessImage(mBundle, mAssets, mFile, NULL);
352 if (status) {
353 *mHasErrors = true;
354 }
355 return true; // continue even if there are errors
356 }
357
358private:
359 const Bundle* mBundle;
360 sp<AaptAssets> mAssets;
361 sp<AaptFile> mFile;
362 volatile bool* mHasErrors;
363};
364
365static status_t preProcessImages(const Bundle* bundle, const sp<AaptAssets>& assets,
366 const sp<ResourceTypeSet>& set, const char* type)
367{
368 volatile bool hasErrors = false;
369 ssize_t res = NO_ERROR;
370 if (bundle->getUseCrunchCache() == false) {
371 WorkQueue wq(MAX_THREADS, false);
372 ResourceDirIterator it(set, String8(type));
373 while ((res=it.next()) == NO_ERROR) {
374 PreProcessImageWorkUnit* w = new PreProcessImageWorkUnit(
375 bundle, assets, it.getFile(), &hasErrors);
376 status_t status = wq.schedule(w);
377 if (status) {
378 fprintf(stderr, "preProcessImages failed: schedule() returned %d\n", status);
379 hasErrors = true;
380 delete w;
381 break;
382 }
383 }
384 status_t status = wq.finish();
385 if (status) {
386 fprintf(stderr, "preProcessImages failed: finish() returned %d\n", status);
387 hasErrors = true;
388 }
389 }
Andreas Gampe2412f842014-09-30 20:55:57 -0700390 return (hasErrors || (res < NO_ERROR)) ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -0800391}
392
Adam Lesinski282e1812014-01-23 18:17:42 -0800393static void collect_files(const sp<AaptDir>& dir,
394 KeyedVector<String8, sp<ResourceTypeSet> >* resources)
395{
396 const DefaultKeyedVector<String8, sp<AaptGroup> >& groups = dir->getFiles();
397 int N = groups.size();
398 for (int i=0; i<N; i++) {
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -0700399 const String8& leafName = groups.keyAt(i);
Adam Lesinski282e1812014-01-23 18:17:42 -0800400 const sp<AaptGroup>& group = groups.valueAt(i);
401
402 const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files
403 = group->getFiles();
404
405 if (files.size() == 0) {
406 continue;
407 }
408
409 String8 resType = files.valueAt(0)->getResourceType();
410
411 ssize_t index = resources->indexOfKey(resType);
412
413 if (index < 0) {
414 sp<ResourceTypeSet> set = new ResourceTypeSet();
Andreas Gampe2412f842014-09-30 20:55:57 -0700415 if (kIsDebug) {
416 printf("Creating new resource type set for leaf %s with group %s (%p)\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000417 leafName.c_str(), group->getPath().c_str(), group.get());
Andreas Gampe2412f842014-09-30 20:55:57 -0700418 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800419 set->add(leafName, group);
420 resources->add(resType, set);
421 } else {
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -0700422 const sp<ResourceTypeSet>& set = resources->valueAt(index);
Adam Lesinski282e1812014-01-23 18:17:42 -0800423 index = set->indexOfKey(leafName);
424 if (index < 0) {
Andreas Gampe2412f842014-09-30 20:55:57 -0700425 if (kIsDebug) {
426 printf("Adding to resource type set for leaf %s group %s (%p)\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000427 leafName.c_str(), group->getPath().c_str(), group.get());
Andreas Gampe2412f842014-09-30 20:55:57 -0700428 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800429 set->add(leafName, group);
430 } else {
431 sp<AaptGroup> existingGroup = set->valueAt(index);
Andreas Gampe2412f842014-09-30 20:55:57 -0700432 if (kIsDebug) {
433 printf("Extending to resource type set for leaf %s group %s (%p)\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000434 leafName.c_str(), group->getPath().c_str(), group.get());
Andreas Gampe2412f842014-09-30 20:55:57 -0700435 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800436 for (size_t j=0; j<files.size(); j++) {
Andreas Gampe2412f842014-09-30 20:55:57 -0700437 if (kIsDebug) {
438 printf("Adding file %s in group %s resType %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000439 files.valueAt(j)->getSourceFile().c_str(),
440 files.keyAt(j).toDirName(String8()).c_str(),
441 resType.c_str());
Andreas Gampe2412f842014-09-30 20:55:57 -0700442 }
443 existingGroup->addFile(files.valueAt(j));
Adam Lesinski282e1812014-01-23 18:17:42 -0800444 }
445 }
446 }
447 }
448}
449
450static void collect_files(const sp<AaptAssets>& ass,
451 KeyedVector<String8, sp<ResourceTypeSet> >* resources)
452{
453 const Vector<sp<AaptDir> >& dirs = ass->resDirs();
454 int N = dirs.size();
455
456 for (int i=0; i<N; i++) {
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -0700457 const sp<AaptDir>& d = dirs.itemAt(i);
Andreas Gampe2412f842014-09-30 20:55:57 -0700458 if (kIsDebug) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000459 printf("Collecting dir #%d %p: %s, leaf %s\n", i, d.get(), d->getPath().c_str(),
460 d->getLeaf().c_str());
Andreas Gampe2412f842014-09-30 20:55:57 -0700461 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800462 collect_files(d, resources);
463
464 // don't try to include the res dir
Andreas Gampe2412f842014-09-30 20:55:57 -0700465 if (kIsDebug) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000466 printf("Removing dir leaf %s\n", d->getLeaf().c_str());
Andreas Gampe2412f842014-09-30 20:55:57 -0700467 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800468 ass->removeDir(d->getLeaf());
469 }
470}
471
472enum {
473 ATTR_OKAY = -1,
474 ATTR_NOT_FOUND = -2,
475 ATTR_LEADING_SPACES = -3,
476 ATTR_TRAILING_SPACES = -4
477};
478static int validateAttr(const String8& path, const ResTable& table,
479 const ResXMLParser& parser,
480 const char* ns, const char* attr, const char* validChars, bool required)
481{
482 size_t len;
483
484 ssize_t index = parser.indexOfAttribute(ns, attr);
Dan Albertf348c152014-09-08 18:28:00 -0700485 const char16_t* str;
Adam Lesinski282e1812014-01-23 18:17:42 -0800486 Res_value value;
487 if (index >= 0 && parser.getAttributeValue(index, &value) >= 0) {
488 const ResStringPool* pool = &parser.getStrings();
489 if (value.dataType == Res_value::TYPE_REFERENCE) {
490 uint32_t specFlags = 0;
491 int strIdx;
492 if ((strIdx=table.resolveReference(&value, 0x10000000, NULL, &specFlags)) < 0) {
493 fprintf(stderr, "%s:%d: Tag <%s> attribute %s references unknown resid 0x%08x.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000494 path.c_str(), parser.getLineNumber(),
495 String8(parser.getElementName(&len)).c_str(), attr,
Adam Lesinski282e1812014-01-23 18:17:42 -0800496 value.data);
497 return ATTR_NOT_FOUND;
498 }
499
500 pool = table.getTableStringBlock(strIdx);
501 #if 0
502 if (pool != NULL) {
503 str = pool->stringAt(value.data, &len);
504 }
505 printf("***** RES ATTR: %s specFlags=0x%x strIdx=%d: %s\n", attr,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000506 specFlags, strIdx, str != NULL ? String8(str).c_str() : "???");
Adam Lesinski282e1812014-01-23 18:17:42 -0800507 #endif
508 if ((specFlags&~ResTable_typeSpec::SPEC_PUBLIC) != 0 && false) {
509 fprintf(stderr, "%s:%d: Tag <%s> attribute %s varies by configurations 0x%x.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000510 path.c_str(), parser.getLineNumber(),
511 String8(parser.getElementName(&len)).c_str(), attr,
Adam Lesinski282e1812014-01-23 18:17:42 -0800512 specFlags);
513 return ATTR_NOT_FOUND;
514 }
515 }
516 if (value.dataType == Res_value::TYPE_STRING) {
517 if (pool == NULL) {
518 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has no string block.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000519 path.c_str(), parser.getLineNumber(),
520 String8(parser.getElementName(&len)).c_str(), attr);
Adam Lesinski282e1812014-01-23 18:17:42 -0800521 return ATTR_NOT_FOUND;
522 }
Ryan Mitchell80094e32020-11-16 23:08:18 +0000523 if ((str = UnpackOptionalString(pool->stringAt(value.data), &len)) == NULL) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800524 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has corrupt string value.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000525 path.c_str(), parser.getLineNumber(),
526 String8(parser.getElementName(&len)).c_str(), attr);
Adam Lesinski282e1812014-01-23 18:17:42 -0800527 return ATTR_NOT_FOUND;
528 }
529 } else {
530 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has invalid type %d.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000531 path.c_str(), parser.getLineNumber(),
532 String8(parser.getElementName(&len)).c_str(), attr,
Adam Lesinski282e1812014-01-23 18:17:42 -0800533 value.dataType);
534 return ATTR_NOT_FOUND;
535 }
536 if (validChars) {
537 for (size_t i=0; i<len; i++) {
Adam Lesinski4bf58102014-11-03 11:21:19 -0800538 char16_t c = str[i];
Adam Lesinski282e1812014-01-23 18:17:42 -0800539 const char* p = validChars;
540 bool okay = false;
541 while (*p) {
542 if (c == *p) {
543 okay = true;
544 break;
545 }
546 p++;
547 }
548 if (!okay) {
549 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has invalid character '%c'.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000550 path.c_str(), parser.getLineNumber(),
551 String8(parser.getElementName(&len)).c_str(), attr, (char)str[i]);
Adam Lesinski282e1812014-01-23 18:17:42 -0800552 return (int)i;
553 }
554 }
555 }
556 if (*str == ' ') {
557 fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not start with a space.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000558 path.c_str(), parser.getLineNumber(),
559 String8(parser.getElementName(&len)).c_str(), attr);
Adam Lesinski282e1812014-01-23 18:17:42 -0800560 return ATTR_LEADING_SPACES;
561 }
Dan Albertd395f792014-10-20 14:44:39 -0700562 if (len != 0 && str[len-1] == ' ') {
Adam Lesinski282e1812014-01-23 18:17:42 -0800563 fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not end with a space.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000564 path.c_str(), parser.getLineNumber(),
565 String8(parser.getElementName(&len)).c_str(), attr);
Adam Lesinski282e1812014-01-23 18:17:42 -0800566 return ATTR_TRAILING_SPACES;
567 }
568 return ATTR_OKAY;
569 }
570 if (required) {
571 fprintf(stderr, "%s:%d: Tag <%s> missing required attribute %s.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000572 path.c_str(), parser.getLineNumber(),
573 String8(parser.getElementName(&len)).c_str(), attr);
Adam Lesinski282e1812014-01-23 18:17:42 -0800574 return ATTR_NOT_FOUND;
575 }
576 return ATTR_OKAY;
577}
578
579static void checkForIds(const String8& path, ResXMLParser& parser)
580{
581 ResXMLTree::event_code_t code;
582 while ((code=parser.next()) != ResXMLTree::END_DOCUMENT
583 && code > ResXMLTree::BAD_DOCUMENT) {
584 if (code == ResXMLTree::START_TAG) {
585 ssize_t index = parser.indexOfAttribute(NULL, "id");
586 if (index >= 0) {
587 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 +0000588 path.c_str(), parser.getLineNumber());
Adam Lesinski282e1812014-01-23 18:17:42 -0800589 }
590 }
591 }
592}
593
594static bool applyFileOverlay(Bundle *bundle,
595 const sp<AaptAssets>& assets,
596 sp<ResourceTypeSet> *baseSet,
597 const char *resType)
598{
599 if (bundle->getVerbose()) {
600 printf("applyFileOverlay for %s\n", resType);
601 }
602
603 // Replace any base level files in this category with any found from the overlay
604 // Also add any found only in the overlay.
605 sp<AaptAssets> overlay = assets->getOverlay();
606 String8 resTypeString(resType);
607
608 // work through the linked list of overlays
609 while (overlay.get()) {
610 KeyedVector<String8, sp<ResourceTypeSet> >* overlayRes = overlay->getResources();
611
612 // get the overlay resources of the requested type
613 ssize_t index = overlayRes->indexOfKey(resTypeString);
614 if (index >= 0) {
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -0700615 const sp<ResourceTypeSet>& overlaySet = overlayRes->valueAt(index);
Adam Lesinski282e1812014-01-23 18:17:42 -0800616
617 // for each of the resources, check for a match in the previously built
618 // non-overlay "baseset".
619 size_t overlayCount = overlaySet->size();
620 for (size_t overlayIndex=0; overlayIndex<overlayCount; overlayIndex++) {
621 if (bundle->getVerbose()) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000622 printf("trying overlaySet Key=%s\n",overlaySet->keyAt(overlayIndex).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800623 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700624 ssize_t baseIndex = -1;
Adam Lesinski282e1812014-01-23 18:17:42 -0800625 if (baseSet->get() != NULL) {
626 baseIndex = (*baseSet)->indexOfKey(overlaySet->keyAt(overlayIndex));
627 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700628 if (baseIndex >= 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800629 // look for same flavor. For a given file (strings.xml, for example)
630 // there may be a locale specific or other flavors - we want to match
631 // the same flavor.
632 sp<AaptGroup> overlayGroup = overlaySet->valueAt(overlayIndex);
633 sp<AaptGroup> baseGroup = (*baseSet)->valueAt(baseIndex);
634
635 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > overlayFiles =
636 overlayGroup->getFiles();
637 if (bundle->getVerbose()) {
638 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > baseFiles =
639 baseGroup->getFiles();
640 for (size_t i=0; i < baseFiles.size(); i++) {
641 printf("baseFile " ZD " has flavor %s\n", (ZD_TYPE) i,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000642 baseFiles.keyAt(i).toString().c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800643 }
644 for (size_t i=0; i < overlayFiles.size(); i++) {
645 printf("overlayFile " ZD " has flavor %s\n", (ZD_TYPE) i,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000646 overlayFiles.keyAt(i).toString().c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800647 }
648 }
649
650 size_t overlayGroupSize = overlayFiles.size();
651 for (size_t overlayGroupIndex = 0;
652 overlayGroupIndex<overlayGroupSize;
653 overlayGroupIndex++) {
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700654 ssize_t baseFileIndex =
Adam Lesinski282e1812014-01-23 18:17:42 -0800655 baseGroup->getFiles().indexOfKey(overlayFiles.
656 keyAt(overlayGroupIndex));
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700657 if (baseFileIndex >= 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800658 if (bundle->getVerbose()) {
659 printf("found a match (" ZD ") for overlay file %s, for flavor %s\n",
660 (ZD_TYPE) baseFileIndex,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000661 overlayGroup->getLeaf().c_str(),
662 overlayFiles.keyAt(overlayGroupIndex).toString().c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800663 }
664 baseGroup->removeFile(baseFileIndex);
665 } else {
666 // didn't find a match fall through and add it..
667 if (true || bundle->getVerbose()) {
668 printf("nothing matches overlay file %s, for flavor %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000669 overlayGroup->getLeaf().c_str(),
670 overlayFiles.keyAt(overlayGroupIndex).toString().c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800671 }
672 }
673 baseGroup->addFile(overlayFiles.valueAt(overlayGroupIndex));
674 assets->addGroupEntry(overlayFiles.keyAt(overlayGroupIndex));
675 }
676 } else {
677 if (baseSet->get() == NULL) {
678 *baseSet = new ResourceTypeSet();
679 assets->getResources()->add(String8(resType), *baseSet);
680 }
681 // this group doesn't exist (a file that's only in the overlay)
682 (*baseSet)->add(overlaySet->keyAt(overlayIndex),
683 overlaySet->valueAt(overlayIndex));
684 // make sure all flavors are defined in the resources.
685 sp<AaptGroup> overlayGroup = overlaySet->valueAt(overlayIndex);
686 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > overlayFiles =
687 overlayGroup->getFiles();
688 size_t overlayGroupSize = overlayFiles.size();
689 for (size_t overlayGroupIndex = 0;
690 overlayGroupIndex<overlayGroupSize;
691 overlayGroupIndex++) {
692 assets->addGroupEntry(overlayFiles.keyAt(overlayGroupIndex));
693 }
694 }
695 }
696 // this overlay didn't have resources for this type
697 }
698 // try next overlay
699 overlay = overlay->getOverlay();
700 }
701 return true;
702}
703
704/*
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800705 * Inserts an attribute in a given node.
Adam Lesinski282e1812014-01-23 18:17:42 -0800706 * If errorOnFailedInsert is true, and the attribute already exists, returns false.
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800707 * If replaceExisting is true, the attribute will be updated if it already exists.
708 * Returns true otherwise, even if the attribute already exists, and does not modify
709 * the existing attribute's value.
Adam Lesinski282e1812014-01-23 18:17:42 -0800710 */
711bool addTagAttribute(const sp<XMLNode>& node, const char* ns8,
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800712 const char* attr8, const char* value, bool errorOnFailedInsert,
713 bool replaceExisting)
Adam Lesinski282e1812014-01-23 18:17:42 -0800714{
715 if (value == NULL) {
716 return true;
717 }
718
719 const String16 ns(ns8);
720 const String16 attr(attr8);
721
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800722 XMLNode::attribute_entry* existingEntry = node->editAttribute(ns, attr);
723 if (existingEntry != NULL) {
724 if (replaceExisting) {
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800725 existingEntry->string = String16(value);
726 return true;
727 }
728
Adam Lesinski282e1812014-01-23 18:17:42 -0800729 if (errorOnFailedInsert) {
730 fprintf(stderr, "Error: AndroidManifest.xml already defines %s (in %s);"
731 " cannot insert new value %s.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000732 String8(attr).c_str(), String8(ns).c_str(), value);
Adam Lesinski282e1812014-01-23 18:17:42 -0800733 return false;
734 }
735
Adam Lesinski282e1812014-01-23 18:17:42 -0800736 // don't stop the build.
737 return true;
738 }
739
740 node->addAttribute(ns, attr, String16(value));
741 return true;
742}
743
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800744/*
745 * Inserts an attribute in a given node, only if the attribute does not
746 * exist.
747 * If errorOnFailedInsert is true, and the attribute already exists, returns false.
748 * Returns true otherwise, even if the attribute already exists.
749 */
750bool addTagAttribute(const sp<XMLNode>& node, const char* ns8,
751 const char* attr8, const char* value, bool errorOnFailedInsert)
752{
753 return addTagAttribute(node, ns8, attr8, value, errorOnFailedInsert, false);
754}
755
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -0700756static void fullyQualifyClassName(const String8& package, const sp<XMLNode>& node,
Adam Lesinski282e1812014-01-23 18:17:42 -0800757 const String16& attrName) {
758 XMLNode::attribute_entry* attr = node->editAttribute(
759 String16("http://schemas.android.com/apk/res/android"), attrName);
760 if (attr != NULL) {
761 String8 name(attr->string);
762
763 // asdf --> package.asdf
764 // .asdf .a.b --> package.asdf package.a.b
765 // asdf.adsf --> asdf.asdf
766 String8 className;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000767 const char* p = name.c_str();
Adam Lesinski282e1812014-01-23 18:17:42 -0800768 const char* q = strchr(p, '.');
769 if (p == q) {
770 className += package;
771 className += name;
772 } else if (q == NULL) {
773 className += package;
774 className += ".";
775 className += name;
776 } else {
777 className += name;
778 }
Andreas Gampe2412f842014-09-30 20:55:57 -0700779 if (kIsDebug) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000780 printf("Qualifying class '%s' to '%s'", name.c_str(), className.c_str());
Andreas Gampe2412f842014-09-30 20:55:57 -0700781 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800782 attr->string.setTo(String16(className));
783 }
784}
785
Adam Lesinski99d36ee2017-04-17 16:22:03 -0700786static sp<ResourceTable::ConfigList> findEntry(const String16& packageStr, const String16& typeStr,
787 const String16& nameStr, ResourceTable* table) {
788 sp<ResourceTable::Package> pkg = table->getPackage(packageStr);
789 if (pkg != NULL) {
790 sp<ResourceTable::Type> type = pkg->getTypes().valueFor(typeStr);
791 if (type != NULL) {
792 return type->getConfigs().valueFor(nameStr);
793 }
794 }
795 return NULL;
796}
797
798static uint16_t getMaxSdkVersion(const sp<ResourceTable::ConfigList>& configList) {
799 const DefaultKeyedVector<ConfigDescription, sp<ResourceTable::Entry>>& entries =
800 configList->getEntries();
801 uint16_t maxSdkVersion = 0u;
802 for (size_t i = 0; i < entries.size(); i++) {
803 maxSdkVersion = std::max(maxSdkVersion, entries.keyAt(i).sdkVersion);
804 }
805 return maxSdkVersion;
806}
807
808static void massageRoundIconSupport(const String16& iconRef, const String16& roundIconRef,
809 ResourceTable* table) {
810 bool publicOnly = false;
811 const char* err;
812
813 String16 iconPackage, iconType, iconName;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000814 if (!ResTable::expandResourceRef(iconRef.c_str(), iconRef.size(), &iconPackage, &iconType,
Adam Lesinski99d36ee2017-04-17 16:22:03 -0700815 &iconName, NULL, &table->getAssetsPackage(), &err,
816 &publicOnly)) {
817 // Errors will be raised in later XML compilation.
818 return;
819 }
820
821 sp<ResourceTable::ConfigList> iconEntry = findEntry(iconPackage, iconType, iconName, table);
822 if (iconEntry == NULL || getMaxSdkVersion(iconEntry) < SDK_O) {
823 // The icon is not adaptive, so nothing to massage.
824 return;
825 }
826
827 String16 roundIconPackage, roundIconType, roundIconName;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000828 if (!ResTable::expandResourceRef(roundIconRef.c_str(), roundIconRef.size(), &roundIconPackage,
Adam Lesinski99d36ee2017-04-17 16:22:03 -0700829 &roundIconType, &roundIconName, NULL, &table->getAssetsPackage(),
830 &err, &publicOnly)) {
831 // Errors will be raised in later XML compilation.
832 return;
833 }
834
835 sp<ResourceTable::ConfigList> roundIconEntry = findEntry(roundIconPackage, roundIconType,
836 roundIconName, table);
837 if (roundIconEntry == NULL || getMaxSdkVersion(roundIconEntry) >= SDK_O) {
838 // The developer explicitly used a v26 compatible drawable as the roundIcon, meaning we should
839 // not generate an alias to the icon drawable.
840 return;
841 }
842
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000843 String16 aliasValue = String16(String8::format("@%s:%s/%s", String8(iconPackage).c_str(),
844 String8(iconType).c_str(),
845 String8(iconName).c_str()));
Adam Lesinski99d36ee2017-04-17 16:22:03 -0700846
847 // Add an equivalent v26 entry to the roundIcon for each v26 variant of the regular icon.
848 const DefaultKeyedVector<ConfigDescription, sp<ResourceTable::Entry>>& configList =
849 iconEntry->getEntries();
850 for (size_t i = 0; i < configList.size(); i++) {
851 if (configList.keyAt(i).sdkVersion >= SDK_O) {
852 table->addEntry(SourcePos(), roundIconPackage, roundIconType, roundIconName, aliasValue,
853 NULL, &configList.keyAt(i));
854 }
855 }
856}
857
858status_t massageManifest(Bundle* bundle, ResourceTable* table, sp<XMLNode> root)
Adam Lesinski282e1812014-01-23 18:17:42 -0800859{
860 root = root->searchElement(String16(), String16("manifest"));
861 if (root == NULL) {
862 fprintf(stderr, "No <manifest> tag.\n");
863 return UNKNOWN_ERROR;
864 }
865
866 bool errorOnFailedInsert = bundle->getErrorOnFailedInsert();
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800867 bool replaceVersion = bundle->getReplaceVersion();
Adam Lesinski282e1812014-01-23 18:17:42 -0800868
869 if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionCode",
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800870 bundle->getVersionCode(), errorOnFailedInsert, replaceVersion)) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800871 return UNKNOWN_ERROR;
Adam Lesinski6a7d2752014-08-07 21:26:53 -0700872 } else {
873 const XMLNode::attribute_entry* attr = root->getAttribute(
874 String16(RESOURCES_ANDROID_NAMESPACE), String16("versionCode"));
875 if (attr != NULL) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000876 bundle->setVersionCode(strdup(String8(attr->string).c_str()));
Adam Lesinski6a7d2752014-08-07 21:26:53 -0700877 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800878 }
Adam Lesinski6a7d2752014-08-07 21:26:53 -0700879
Adam Lesinski282e1812014-01-23 18:17:42 -0800880 if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionName",
Jeff Davidsondf08d1c2014-02-25 12:28:08 -0800881 bundle->getVersionName(), errorOnFailedInsert, replaceVersion)) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800882 return UNKNOWN_ERROR;
Adam Lesinski82a2dd82014-09-17 18:34:15 -0700883 } else {
884 const XMLNode::attribute_entry* attr = root->getAttribute(
885 String16(RESOURCES_ANDROID_NAMESPACE), String16("versionName"));
886 if (attr != NULL) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000887 bundle->setVersionName(strdup(String8(attr->string).c_str()));
Adam Lesinski82a2dd82014-09-17 18:34:15 -0700888 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800889 }
890
Adam Lesinski82a2dd82014-09-17 18:34:15 -0700891 sp<XMLNode> vers = root->getChildElement(String16(), String16("uses-sdk"));
Adam Lesinski282e1812014-01-23 18:17:42 -0800892 if (bundle->getMinSdkVersion() != NULL
893 || bundle->getTargetSdkVersion() != NULL
894 || bundle->getMaxSdkVersion() != NULL) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800895 if (vers == NULL) {
896 vers = XMLNode::newElement(root->getFilename(), String16(), String16("uses-sdk"));
897 root->insertChildAt(vers, 0);
898 }
899
900 if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "minSdkVersion",
901 bundle->getMinSdkVersion(), errorOnFailedInsert)) {
902 return UNKNOWN_ERROR;
903 }
904 if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "targetSdkVersion",
905 bundle->getTargetSdkVersion(), errorOnFailedInsert)) {
906 return UNKNOWN_ERROR;
907 }
908 if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "maxSdkVersion",
909 bundle->getMaxSdkVersion(), errorOnFailedInsert)) {
910 return UNKNOWN_ERROR;
911 }
912 }
913
Adam Lesinski82a2dd82014-09-17 18:34:15 -0700914 if (vers != NULL) {
915 const XMLNode::attribute_entry* attr = vers->getAttribute(
916 String16(RESOURCES_ANDROID_NAMESPACE), String16("minSdkVersion"));
917 if (attr != NULL) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000918 bundle->setMinSdkVersion(strdup(String8(attr->string).c_str()));
Adam Lesinski82a2dd82014-09-17 18:34:15 -0700919 }
920 }
921
Alan Viverette11be9312017-11-09 15:41:44 -0500922
923 if (bundle->getCompileSdkVersion() != 0) {
924 if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "compileSdkVersion",
925 String8::format("%d", bundle->getCompileSdkVersion()),
926 errorOnFailedInsert, true)) {
927 return UNKNOWN_ERROR;
928 }
929 }
930
931 if (bundle->getCompileSdkVersionCodename() != "") {
932 if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "compileSdkVersionCodename",
933 bundle->getCompileSdkVersionCodename(), errorOnFailedInsert, true)) {
934 return UNKNOWN_ERROR;
935 }
936 }
937
Adam Lesinskiad2d07d2014-08-27 16:21:08 -0700938 if (bundle->getPlatformBuildVersionCode() != "") {
939 if (!addTagAttribute(root, "", "platformBuildVersionCode",
940 bundle->getPlatformBuildVersionCode(), errorOnFailedInsert, true)) {
941 return UNKNOWN_ERROR;
942 }
943 }
944
945 if (bundle->getPlatformBuildVersionName() != "") {
946 if (!addTagAttribute(root, "", "platformBuildVersionName",
947 bundle->getPlatformBuildVersionName(), errorOnFailedInsert, true)) {
948 return UNKNOWN_ERROR;
949 }
950 }
951
Adam Lesinski282e1812014-01-23 18:17:42 -0800952 if (bundle->getDebugMode()) {
953 sp<XMLNode> application = root->getChildElement(String16(), String16("application"));
954 if (application != NULL) {
955 if (!addTagAttribute(application, RESOURCES_ANDROID_NAMESPACE, "debuggable", "true",
956 errorOnFailedInsert)) {
957 return UNKNOWN_ERROR;
958 }
959 }
960 }
961
962 // Deal with manifest package name overrides
963 const char* manifestPackageNameOverride = bundle->getManifestPackageNameOverride();
964 if (manifestPackageNameOverride != NULL) {
965 // Update the actual package name
966 XMLNode::attribute_entry* attr = root->editAttribute(String16(), String16("package"));
967 if (attr == NULL) {
968 fprintf(stderr, "package name is required with --rename-manifest-package.\n");
969 return UNKNOWN_ERROR;
970 }
971 String8 origPackage(attr->string);
972 attr->string.setTo(String16(manifestPackageNameOverride));
Andreas Gampe2412f842014-09-30 20:55:57 -0700973 if (kIsDebug) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000974 printf("Overriding package '%s' to be '%s'\n", origPackage.c_str(),
Andreas Gampe2412f842014-09-30 20:55:57 -0700975 manifestPackageNameOverride);
976 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800977
978 // Make class names fully qualified
979 sp<XMLNode> application = root->getChildElement(String16(), String16("application"));
980 if (application != NULL) {
981 fullyQualifyClassName(origPackage, application, String16("name"));
982 fullyQualifyClassName(origPackage, application, String16("backupAgent"));
983
984 Vector<sp<XMLNode> >& children = const_cast<Vector<sp<XMLNode> >&>(application->getChildren());
985 for (size_t i = 0; i < children.size(); i++) {
986 sp<XMLNode> child = children.editItemAt(i);
987 String8 tag(child->getElementName());
988 if (tag == "activity" || tag == "service" || tag == "receiver" || tag == "provider") {
989 fullyQualifyClassName(origPackage, child, String16("name"));
990 } else if (tag == "activity-alias") {
991 fullyQualifyClassName(origPackage, child, String16("name"));
992 fullyQualifyClassName(origPackage, child, String16("targetActivity"));
993 }
994 }
995 }
996 }
997
998 // Deal with manifest package name overrides
999 const char* instrumentationPackageNameOverride = bundle->getInstrumentationPackageNameOverride();
1000 if (instrumentationPackageNameOverride != NULL) {
1001 // Fix up instrumentation targets.
1002 Vector<sp<XMLNode> >& children = const_cast<Vector<sp<XMLNode> >&>(root->getChildren());
1003 for (size_t i = 0; i < children.size(); i++) {
1004 sp<XMLNode> child = children.editItemAt(i);
1005 String8 tag(child->getElementName());
1006 if (tag == "instrumentation") {
1007 XMLNode::attribute_entry* attr = child->editAttribute(
Adam Lesinski99d36ee2017-04-17 16:22:03 -07001008 String16(RESOURCES_ANDROID_NAMESPACE), String16("targetPackage"));
Adam Lesinski282e1812014-01-23 18:17:42 -08001009 if (attr != NULL) {
1010 attr->string.setTo(String16(instrumentationPackageNameOverride));
1011 }
1012 }
1013 }
1014 }
1015
Adam Lesinski99d36ee2017-04-17 16:22:03 -07001016 sp<XMLNode> application = root->getChildElement(String16(), String16("application"));
1017 if (application != NULL) {
1018 XMLNode::attribute_entry* icon_attr = application->editAttribute(
1019 String16(RESOURCES_ANDROID_NAMESPACE), String16("icon"));
1020 if (icon_attr != NULL) {
1021 XMLNode::attribute_entry* round_icon_attr = application->editAttribute(
1022 String16(RESOURCES_ANDROID_NAMESPACE), String16("roundIcon"));
1023 if (round_icon_attr != NULL) {
1024 massageRoundIconSupport(icon_attr->string, round_icon_attr->string, table);
1025 }
1026 }
1027 }
1028
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001029 // Generate split name if feature is present.
1030 const XMLNode::attribute_entry* attr = root->getAttribute(String16(), String16("featureName"));
1031 if (attr != NULL) {
1032 String16 splitName("feature_");
1033 splitName.append(attr->string);
1034 status_t err = root->addAttribute(String16(), String16("split"), splitName);
1035 if (err != NO_ERROR) {
1036 ALOGE("Failed to insert split name into AndroidManifest.xml");
1037 return err;
1038 }
1039 }
1040
Adam Lesinski282e1812014-01-23 18:17:42 -08001041 return NO_ERROR;
1042}
1043
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001044static int32_t getPlatformAssetCookie(const AssetManager& assets) {
1045 // Find the system package (0x01). AAPT always generates attributes
1046 // with the type 0x01, so we're looking for the first attribute
1047 // resource in the system package.
1048 const ResTable& table = assets.getResources(true);
1049 Res_value val;
1050 ssize_t idx = table.getResource(0x01010000, &val, true);
1051 if (idx != NO_ERROR) {
1052 // Try as a bag.
1053 const ResTable::bag_entry* entry;
1054 ssize_t cnt = table.lockBag(0x01010000, &entry);
1055 if (cnt >= 0) {
1056 idx = entry->stringBlock;
1057 }
1058 table.unlockBag(entry);
1059 }
1060
1061 if (idx < 0) {
1062 return 0;
1063 }
1064 return table.getTableCookie(idx);
1065}
1066
1067enum {
1068 VERSION_CODE_ATTR = 0x0101021b,
1069 VERSION_NAME_ATTR = 0x0101021c,
1070};
1071
Alan Viverette11be9312017-11-09 15:41:44 -05001072static ssize_t extractPlatformBuildVersion(const ResTable& table, ResXMLTree& tree, Bundle* bundle) {
1073 // First check if we should be recording the compileSdkVersion* attributes.
1074 static const String16 compileSdkVersionName("android:attr/compileSdkVersion");
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001075 const bool useCompileSdkVersion = table.identifierForName(compileSdkVersionName.c_str(),
Alan Viverette11be9312017-11-09 15:41:44 -05001076 compileSdkVersionName.size()) != 0u;
1077
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001078 size_t len;
1079 ResXMLTree::event_code_t code;
1080 while ((code = tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1081 if (code != ResXMLTree::START_TAG) {
1082 continue;
1083 }
1084
1085 const char16_t* ctag16 = tree.getElementName(&len);
1086 if (ctag16 == NULL) {
1087 fprintf(stderr, "ERROR: failed to get XML element name (bad string pool)\n");
1088 return UNKNOWN_ERROR;
1089 }
1090
1091 String8 tag(ctag16, len);
1092 if (tag != "manifest") {
1093 continue;
1094 }
1095
1096 String8 error;
1097 int32_t versionCode = AaptXml::getIntegerAttribute(tree, VERSION_CODE_ATTR, &error);
1098 if (error != "") {
1099 fprintf(stderr, "ERROR: failed to get platform version code\n");
1100 return UNKNOWN_ERROR;
1101 }
1102
1103 if (versionCode >= 0 && bundle->getPlatformBuildVersionCode() == "") {
1104 bundle->setPlatformBuildVersionCode(String8::format("%d", versionCode));
1105 }
1106
Alan Viverette11be9312017-11-09 15:41:44 -05001107 if (useCompileSdkVersion && versionCode >= 0 && bundle->getCompileSdkVersion() == 0) {
1108 bundle->setCompileSdkVersion(versionCode);
1109 }
1110
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001111 String8 versionName = AaptXml::getAttribute(tree, VERSION_NAME_ATTR, &error);
1112 if (error != "") {
1113 fprintf(stderr, "ERROR: failed to get platform version name\n");
1114 return UNKNOWN_ERROR;
1115 }
1116
1117 if (versionName != "" && bundle->getPlatformBuildVersionName() == "") {
1118 bundle->setPlatformBuildVersionName(versionName);
1119 }
Alan Viverette11be9312017-11-09 15:41:44 -05001120
1121 if (useCompileSdkVersion && versionName != ""
1122 && bundle->getCompileSdkVersionCodename() == "") {
1123 bundle->setCompileSdkVersionCodename(versionName);
1124 }
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001125 return NO_ERROR;
1126 }
1127
1128 fprintf(stderr, "ERROR: no <manifest> tag found in platform AndroidManifest.xml\n");
1129 return UNKNOWN_ERROR;
1130}
1131
1132static ssize_t extractPlatformBuildVersion(AssetManager& assets, Bundle* bundle) {
1133 int32_t cookie = getPlatformAssetCookie(assets);
1134 if (cookie == 0) {
Adam Lesinski82a2dd82014-09-17 18:34:15 -07001135 // No platform was loaded.
1136 return NO_ERROR;
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001137 }
1138
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001139 Asset* asset = assets.openNonAsset(cookie, "AndroidManifest.xml", Asset::ACCESS_STREAMING);
1140 if (asset == NULL) {
1141 fprintf(stderr, "ERROR: Platform AndroidManifest.xml not found\n");
1142 return UNKNOWN_ERROR;
1143 }
1144
1145 ssize_t result = NO_ERROR;
Adam Lesinski193ed742016-08-15 14:19:46 -07001146
1147 // Create a new scope so that ResXMLTree is destroyed before we delete the memory over
1148 // which it iterates (asset).
1149 {
1150 ResXMLTree tree;
1151 if (tree.setTo(asset->getBuffer(true), asset->getLength()) != NO_ERROR) {
1152 fprintf(stderr, "ERROR: Platform AndroidManifest.xml is corrupt\n");
1153 result = UNKNOWN_ERROR;
1154 } else {
Alan Viverette11be9312017-11-09 15:41:44 -05001155 result = extractPlatformBuildVersion(assets.getResources(true), tree, bundle);
Adam Lesinski193ed742016-08-15 14:19:46 -07001156 }
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001157 }
1158
1159 delete asset;
1160 return result;
1161}
1162
Adam Lesinski282e1812014-01-23 18:17:42 -08001163#define ASSIGN_IT(n) \
1164 do { \
1165 ssize_t index = resources->indexOfKey(String8(#n)); \
1166 if (index >= 0) { \
1167 n ## s = resources->valueAt(index); \
1168 } \
1169 } while (0)
1170
1171status_t updatePreProcessedCache(Bundle* bundle)
1172{
1173 #if BENCHMARK
1174 fprintf(stdout, "BENCHMARK: Starting PNG PreProcessing \n");
1175 long startPNGTime = clock();
1176 #endif /* BENCHMARK */
1177
1178 String8 source(bundle->getResourceSourceDirs()[0]);
1179 String8 dest(bundle->getCrunchedOutputDir());
1180
1181 FileFinder* ff = new SystemFileFinder();
1182 CrunchCache cc(source,dest,ff);
1183
1184 CacheUpdater* cu = new SystemCacheUpdater(bundle);
1185 size_t numFiles = cc.crunch(cu);
1186
1187 if (bundle->getVerbose())
1188 fprintf(stdout, "Crunched %d PNG files to update cache\n", (int)numFiles);
1189
1190 delete ff;
1191 delete cu;
1192
1193 #if BENCHMARK
1194 fprintf(stdout, "BENCHMARK: End PNG PreProcessing. Time Elapsed: %f ms \n"
1195 ,(clock() - startPNGTime)/1000.0);
1196 #endif /* BENCHMARK */
1197 return 0;
1198}
1199
Jeff Sharkey2cfc8482014-07-09 16:10:16 -07001200status_t generateAndroidManifestForSplit(Bundle* bundle, const sp<AaptAssets>& assets,
1201 const sp<ApkSplit>& split, sp<AaptFile>& outFile, ResourceTable* table) {
Adam Lesinskifab50872014-04-16 14:40:42 -07001202 const String8 filename("AndroidManifest.xml");
1203 const String16 androidPrefix("android");
1204 const String16 androidNSUri("http://schemas.android.com/apk/res/android");
1205 sp<XMLNode> root = XMLNode::newNamespace(filename, androidPrefix, androidNSUri);
1206
1207 // Build the <manifest> tag
1208 sp<XMLNode> manifest = XMLNode::newElement(filename, String16(), String16("manifest"));
1209
Jeff Sharkey2cfc8482014-07-09 16:10:16 -07001210 // Add the 'package' attribute which is set to the package name.
1211 const char* packageName = assets->getPackage();
1212 const char* manifestPackageNameOverride = bundle->getManifestPackageNameOverride();
1213 if (manifestPackageNameOverride != NULL) {
1214 packageName = manifestPackageNameOverride;
1215 }
1216 manifest->addAttribute(String16(), String16("package"), String16(packageName));
1217
1218 // Add the 'versionCode' attribute which is set to the original version code.
1219 if (!addTagAttribute(manifest, RESOURCES_ANDROID_NAMESPACE, "versionCode",
1220 bundle->getVersionCode(), true, true)) {
1221 return UNKNOWN_ERROR;
1222 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001223
Adam Lesinski54de2982014-12-16 09:16:26 -08001224 // Add the 'revisionCode' attribute, which is set to the original revisionCode.
1225 if (bundle->getRevisionCode().size() > 0) {
1226 if (!addTagAttribute(manifest, RESOURCES_ANDROID_NAMESPACE, "revisionCode",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001227 bundle->getRevisionCode().c_str(), true, true)) {
Adam Lesinski54de2982014-12-16 09:16:26 -08001228 return UNKNOWN_ERROR;
1229 }
1230 }
1231
Adam Lesinskifab50872014-04-16 14:40:42 -07001232 // Add the 'split' attribute which describes the configurations included.
Adam Lesinski62408402014-08-07 21:26:53 -07001233 String8 splitName("config.");
1234 splitName.append(split->getPackageSafeName());
Adam Lesinskifab50872014-04-16 14:40:42 -07001235 manifest->addAttribute(String16(), String16("split"), String16(splitName));
1236
1237 // Build an empty <application> tag (required).
1238 sp<XMLNode> app = XMLNode::newElement(filename, String16(), String16("application"));
Jeff Sharkey78a13012014-07-15 20:18:34 -07001239
1240 // Add the 'hasCode' attribute which is never true for resource splits.
1241 if (!addTagAttribute(app, RESOURCES_ANDROID_NAMESPACE, "hasCode",
1242 "false", true, true)) {
1243 return UNKNOWN_ERROR;
1244 }
1245
Adam Lesinskifab50872014-04-16 14:40:42 -07001246 manifest->addChild(app);
1247 root->addChild(manifest);
1248
Adam Lesinskie572c012014-09-19 15:10:04 -07001249 int err = compileXmlFile(bundle, assets, String16(), root, outFile, table);
Jeff Sharkey2cfc8482014-07-09 16:10:16 -07001250 if (err < NO_ERROR) {
Adam Lesinskifab50872014-04-16 14:40:42 -07001251 return err;
1252 }
1253 outFile->setCompressionMethod(ZipEntry::kCompressDeflated);
1254 return NO_ERROR;
1255}
1256
1257status_t buildResources(Bundle* bundle, const sp<AaptAssets>& assets, sp<ApkBuilder>& builder)
Adam Lesinski282e1812014-01-23 18:17:42 -08001258{
1259 // First, look for a package file to parse. This is required to
1260 // be able to generate the resource information.
1261 sp<AaptGroup> androidManifestFile =
1262 assets->getFiles().valueFor(String8("AndroidManifest.xml"));
1263 if (androidManifestFile == NULL) {
1264 fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n");
1265 return UNKNOWN_ERROR;
1266 }
1267
1268 status_t err = parsePackage(bundle, assets, androidManifestFile);
1269 if (err != NO_ERROR) {
1270 return err;
1271 }
1272
Andreas Gampe2412f842014-09-30 20:55:57 -07001273 if (kIsDebug) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001274 printf("Creating resources for package %s\n", assets->getPackage().c_str());
Andreas Gampe2412f842014-09-30 20:55:57 -07001275 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001276
Adam Lesinski78713992015-12-07 14:02:15 -08001277 // Set the private symbols package if it was declared.
1278 // This can also be declared in XML as <private-symbols name="package" />
1279 if (bundle->getPrivateSymbolsPackage().size() != 0) {
1280 assets->setSymbolsPrivatePackage(bundle->getPrivateSymbolsPackage());
1281 }
1282
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001283 ResourceTable::PackageType packageType = ResourceTable::App;
1284 if (bundle->getBuildSharedLibrary()) {
1285 packageType = ResourceTable::SharedLibrary;
1286 } else if (bundle->getExtending()) {
1287 packageType = ResourceTable::System;
1288 } else if (!bundle->getFeatureOfPackage().isEmpty()) {
1289 packageType = ResourceTable::AppFeature;
1290 }
1291
1292 ResourceTable table(bundle, String16(assets->getPackage()), packageType);
Adam Lesinski282e1812014-01-23 18:17:42 -08001293 err = table.addIncludedResources(bundle, assets);
1294 if (err != NO_ERROR) {
1295 return err;
1296 }
1297
Andreas Gampe2412f842014-09-30 20:55:57 -07001298 if (kIsDebug) {
1299 printf("Found %d included resource packages\n", (int)table.size());
1300 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001301
1302 // Standard flags for compiled XML and optional UTF-8 encoding
1303 int xmlFlags = XML_COMPILE_STANDARD_RESOURCE;
1304
1305 /* Only enable UTF-8 if the caller of aapt didn't specifically
1306 * request UTF-16 encoding and the parameters of this package
1307 * allow UTF-8 to be used.
1308 */
1309 if (!bundle->getUTF16StringsOption()) {
1310 xmlFlags |= XML_COMPILE_UTF8;
1311 }
1312
1313 // --------------------------------------------------------------
1314 // First, gather all resource information.
1315 // --------------------------------------------------------------
1316
1317 // resType -> leafName -> group
1318 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
1319 new KeyedVector<String8, sp<ResourceTypeSet> >;
1320 collect_files(assets, resources);
1321
1322 sp<ResourceTypeSet> drawables;
1323 sp<ResourceTypeSet> layouts;
1324 sp<ResourceTypeSet> anims;
1325 sp<ResourceTypeSet> animators;
1326 sp<ResourceTypeSet> interpolators;
1327 sp<ResourceTypeSet> transitions;
Adam Lesinski282e1812014-01-23 18:17:42 -08001328 sp<ResourceTypeSet> xmls;
1329 sp<ResourceTypeSet> raws;
1330 sp<ResourceTypeSet> colors;
1331 sp<ResourceTypeSet> menus;
1332 sp<ResourceTypeSet> mipmaps;
Adam Lesinski9bbe7872017-01-24 13:52:04 -08001333 sp<ResourceTypeSet> fonts;
Adam Lesinski282e1812014-01-23 18:17:42 -08001334
1335 ASSIGN_IT(drawable);
1336 ASSIGN_IT(layout);
1337 ASSIGN_IT(anim);
1338 ASSIGN_IT(animator);
1339 ASSIGN_IT(interpolator);
1340 ASSIGN_IT(transition);
Adam Lesinski282e1812014-01-23 18:17:42 -08001341 ASSIGN_IT(xml);
1342 ASSIGN_IT(raw);
1343 ASSIGN_IT(color);
1344 ASSIGN_IT(menu);
1345 ASSIGN_IT(mipmap);
Adam Lesinski9bbe7872017-01-24 13:52:04 -08001346 ASSIGN_IT(font);
Adam Lesinski282e1812014-01-23 18:17:42 -08001347
1348 assets->setResources(resources);
1349 // now go through any resource overlays and collect their files
1350 sp<AaptAssets> current = assets->getOverlay();
1351 while(current.get()) {
1352 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
1353 new KeyedVector<String8, sp<ResourceTypeSet> >;
1354 current->setResources(resources);
1355 collect_files(current, resources);
1356 current = current->getOverlay();
1357 }
1358 // apply the overlay files to the base set
1359 if (!applyFileOverlay(bundle, assets, &drawables, "drawable") ||
1360 !applyFileOverlay(bundle, assets, &layouts, "layout") ||
1361 !applyFileOverlay(bundle, assets, &anims, "anim") ||
1362 !applyFileOverlay(bundle, assets, &animators, "animator") ||
1363 !applyFileOverlay(bundle, assets, &interpolators, "interpolator") ||
1364 !applyFileOverlay(bundle, assets, &transitions, "transition") ||
Adam Lesinski282e1812014-01-23 18:17:42 -08001365 !applyFileOverlay(bundle, assets, &xmls, "xml") ||
1366 !applyFileOverlay(bundle, assets, &raws, "raw") ||
1367 !applyFileOverlay(bundle, assets, &colors, "color") ||
1368 !applyFileOverlay(bundle, assets, &menus, "menu") ||
Adam Lesinski9bbe7872017-01-24 13:52:04 -08001369 !applyFileOverlay(bundle, assets, &fonts, "font") ||
Adam Lesinski282e1812014-01-23 18:17:42 -08001370 !applyFileOverlay(bundle, assets, &mipmaps, "mipmap")) {
1371 return UNKNOWN_ERROR;
1372 }
1373
1374 bool hasErrors = false;
1375
1376 if (drawables != NULL) {
1377 if (bundle->getOutputAPKFile() != NULL) {
1378 err = preProcessImages(bundle, assets, drawables, "drawable");
1379 }
1380 if (err == NO_ERROR) {
1381 err = makeFileResources(bundle, assets, &table, drawables, "drawable");
1382 if (err != NO_ERROR) {
1383 hasErrors = true;
1384 }
1385 } else {
1386 hasErrors = true;
1387 }
1388 }
1389
1390 if (mipmaps != NULL) {
1391 if (bundle->getOutputAPKFile() != NULL) {
1392 err = preProcessImages(bundle, assets, mipmaps, "mipmap");
1393 }
1394 if (err == NO_ERROR) {
1395 err = makeFileResources(bundle, assets, &table, mipmaps, "mipmap");
1396 if (err != NO_ERROR) {
1397 hasErrors = true;
1398 }
1399 } else {
1400 hasErrors = true;
1401 }
1402 }
1403
Adam Lesinski9bbe7872017-01-24 13:52:04 -08001404 if (fonts != NULL) {
1405 err = makeFileResources(bundle, assets, &table, fonts, "font");
1406 if (err != NO_ERROR) {
1407 hasErrors = true;
1408 }
1409 }
1410
Adam Lesinski282e1812014-01-23 18:17:42 -08001411 if (layouts != NULL) {
1412 err = makeFileResources(bundle, assets, &table, layouts, "layout");
1413 if (err != NO_ERROR) {
1414 hasErrors = true;
1415 }
1416 }
1417
1418 if (anims != NULL) {
1419 err = makeFileResources(bundle, assets, &table, anims, "anim");
1420 if (err != NO_ERROR) {
1421 hasErrors = true;
1422 }
1423 }
1424
1425 if (animators != NULL) {
1426 err = makeFileResources(bundle, assets, &table, animators, "animator");
1427 if (err != NO_ERROR) {
1428 hasErrors = true;
1429 }
1430 }
1431
1432 if (transitions != NULL) {
1433 err = makeFileResources(bundle, assets, &table, transitions, "transition");
1434 if (err != NO_ERROR) {
1435 hasErrors = true;
1436 }
1437 }
1438
Adam Lesinski282e1812014-01-23 18:17:42 -08001439 if (interpolators != NULL) {
1440 err = makeFileResources(bundle, assets, &table, interpolators, "interpolator");
1441 if (err != NO_ERROR) {
1442 hasErrors = true;
1443 }
1444 }
1445
1446 if (xmls != NULL) {
1447 err = makeFileResources(bundle, assets, &table, xmls, "xml");
1448 if (err != NO_ERROR) {
1449 hasErrors = true;
1450 }
1451 }
1452
1453 if (raws != NULL) {
1454 err = makeFileResources(bundle, assets, &table, raws, "raw");
1455 if (err != NO_ERROR) {
1456 hasErrors = true;
1457 }
1458 }
1459
1460 // compile resources
1461 current = assets;
1462 while(current.get()) {
1463 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
1464 current->getResources();
1465
1466 ssize_t index = resources->indexOfKey(String8("values"));
1467 if (index >= 0) {
1468 ResourceDirIterator it(resources->valueAt(index), String8("values"));
1469 ssize_t res;
1470 while ((res=it.next()) == NO_ERROR) {
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -07001471 const sp<AaptFile>& file = it.getFile();
Adam Lesinski282e1812014-01-23 18:17:42 -08001472 res = compileResourceFile(bundle, assets, file, it.getParams(),
1473 (current!=assets), &table);
1474 if (res != NO_ERROR) {
1475 hasErrors = true;
1476 }
1477 }
1478 }
1479 current = current->getOverlay();
1480 }
1481
1482 if (colors != NULL) {
1483 err = makeFileResources(bundle, assets, &table, colors, "color");
1484 if (err != NO_ERROR) {
1485 hasErrors = true;
1486 }
1487 }
1488
1489 if (menus != NULL) {
1490 err = makeFileResources(bundle, assets, &table, menus, "menu");
1491 if (err != NO_ERROR) {
1492 hasErrors = true;
1493 }
1494 }
1495
Adam Lesinski526d73b2016-07-18 17:01:14 -07001496 if (hasErrors) {
1497 return UNKNOWN_ERROR;
1498 }
1499
Adam Lesinski282e1812014-01-23 18:17:42 -08001500 // --------------------------------------------------------------------
1501 // Assignment of resource IDs and initial generation of resource table.
1502 // --------------------------------------------------------------------
1503
1504 if (table.hasResources()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001505 err = table.assignResourceIds();
1506 if (err < NO_ERROR) {
1507 return err;
1508 }
1509 }
1510
1511 // --------------------------------------------------------------
1512 // Finally, we can now we can compile XML files, which may reference
1513 // resources.
1514 // --------------------------------------------------------------
1515
1516 if (layouts != NULL) {
1517 ResourceDirIterator it(layouts, String8("layout"));
1518 while ((err=it.next()) == NO_ERROR) {
1519 String8 src = it.getFile()->getPrintableSource();
Adam Lesinskie572c012014-09-19 15:10:04 -07001520 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1521 it.getFile(), &table, xmlFlags);
Adam Lesinskicf1f1d92017-03-16 16:54:23 -07001522 // Only verify IDs if there was no error and the file is non-empty.
1523 if (err == NO_ERROR && it.getFile()->hasData()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001524 ResXMLTree block;
1525 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
1526 checkForIds(src, block);
1527 } else {
1528 hasErrors = true;
1529 }
1530 }
1531
1532 if (err < NO_ERROR) {
1533 hasErrors = true;
1534 }
1535 err = NO_ERROR;
1536 }
1537
1538 if (anims != NULL) {
1539 ResourceDirIterator it(anims, String8("anim"));
1540 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001541 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1542 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001543 if (err != NO_ERROR) {
1544 hasErrors = true;
1545 }
1546 }
1547
1548 if (err < NO_ERROR) {
1549 hasErrors = true;
1550 }
1551 err = NO_ERROR;
1552 }
1553
1554 if (animators != NULL) {
1555 ResourceDirIterator it(animators, String8("animator"));
1556 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001557 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1558 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001559 if (err != NO_ERROR) {
1560 hasErrors = true;
1561 }
1562 }
1563
1564 if (err < NO_ERROR) {
1565 hasErrors = true;
1566 }
1567 err = NO_ERROR;
1568 }
1569
1570 if (interpolators != NULL) {
1571 ResourceDirIterator it(interpolators, String8("interpolator"));
1572 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001573 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1574 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001575 if (err != NO_ERROR) {
1576 hasErrors = true;
1577 }
1578 }
1579
1580 if (err < NO_ERROR) {
1581 hasErrors = true;
1582 }
1583 err = NO_ERROR;
1584 }
1585
1586 if (transitions != NULL) {
1587 ResourceDirIterator it(transitions, String8("transition"));
1588 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001589 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1590 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001591 if (err != NO_ERROR) {
1592 hasErrors = true;
1593 }
1594 }
1595
1596 if (err < NO_ERROR) {
1597 hasErrors = true;
1598 }
1599 err = NO_ERROR;
1600 }
1601
Adam Lesinski282e1812014-01-23 18:17:42 -08001602 if (xmls != NULL) {
1603 ResourceDirIterator it(xmls, String8("xml"));
1604 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001605 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1606 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001607 if (err != NO_ERROR) {
1608 hasErrors = true;
1609 }
1610 }
1611
1612 if (err < NO_ERROR) {
1613 hasErrors = true;
1614 }
1615 err = NO_ERROR;
1616 }
1617
1618 if (drawables != NULL) {
Adam Lesinskifab50872014-04-16 14:40:42 -07001619 ResourceDirIterator it(drawables, String8("drawable"));
1620 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001621 err = postProcessImage(bundle, assets, &table, it.getFile());
Adam Lesinskifab50872014-04-16 14:40:42 -07001622 if (err != NO_ERROR) {
1623 hasErrors = true;
1624 }
1625 }
1626
1627 if (err < NO_ERROR) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001628 hasErrors = true;
1629 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001630 err = NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001631 }
1632
Adam Lesinski2d6fa032017-03-10 18:42:32 -08001633 if (mipmaps != NULL) {
1634 ResourceDirIterator it(mipmaps, String8("mipmap"));
1635 while ((err=it.next()) == NO_ERROR) {
1636 err = postProcessImage(bundle, assets, &table, it.getFile());
1637 if (err != NO_ERROR) {
1638 hasErrors = true;
1639 }
1640 }
1641
1642 if (err < NO_ERROR) {
1643 hasErrors = true;
1644 }
1645 err = NO_ERROR;
1646 }
1647
Adam Lesinski282e1812014-01-23 18:17:42 -08001648 if (colors != NULL) {
1649 ResourceDirIterator it(colors, String8("color"));
1650 while ((err=it.next()) == NO_ERROR) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001651 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1652 it.getFile(), &table, xmlFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08001653 if (err != NO_ERROR) {
1654 hasErrors = true;
1655 }
1656 }
1657
1658 if (err < NO_ERROR) {
1659 hasErrors = true;
1660 }
1661 err = NO_ERROR;
1662 }
1663
1664 if (menus != NULL) {
1665 ResourceDirIterator it(menus, String8("menu"));
1666 while ((err=it.next()) == NO_ERROR) {
1667 String8 src = it.getFile()->getPrintableSource();
Adam Lesinskie572c012014-09-19 15:10:04 -07001668 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1669 it.getFile(), &table, xmlFlags);
Adam Lesinskicf1f1d92017-03-16 16:54:23 -07001670 if (err == NO_ERROR && it.getFile()->hasData()) {
Adam Lesinskifab50872014-04-16 14:40:42 -07001671 ResXMLTree block;
1672 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
1673 checkForIds(src, block);
1674 } else {
Adam Lesinski282e1812014-01-23 18:17:42 -08001675 hasErrors = true;
1676 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001677 }
1678
1679 if (err < NO_ERROR) {
1680 hasErrors = true;
1681 }
1682 err = NO_ERROR;
1683 }
1684
Adam Lesinski9bbe7872017-01-24 13:52:04 -08001685 if (fonts != NULL) {
1686 ResourceDirIterator it(fonts, String8("font"));
1687 while ((err=it.next()) == NO_ERROR) {
1688 // fonts can be resources other than xml.
1689 if (it.getFile()->getPath().getPathExtension() == ".xml") {
1690 String8 src = it.getFile()->getPrintableSource();
1691 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
1692 it.getFile(), &table, xmlFlags);
1693 if (err != NO_ERROR) {
1694 hasErrors = true;
1695 }
1696 }
1697 }
1698
1699 if (err < NO_ERROR) {
1700 hasErrors = true;
1701 }
1702 err = NO_ERROR;
1703 }
1704
Adam Lesinskie572c012014-09-19 15:10:04 -07001705 // Now compile any generated resources.
1706 std::queue<CompileResourceWorkItem>& workQueue = table.getWorkQueue();
1707 while (!workQueue.empty()) {
1708 CompileResourceWorkItem& workItem = workQueue.front();
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07001709 int xmlCompilationFlags = xmlFlags | XML_COMPILE_PARSE_VALUES
1710 | XML_COMPILE_ASSIGN_ATTRIBUTE_IDS;
1711 if (!workItem.needsCompiling) {
1712 xmlCompilationFlags &= ~XML_COMPILE_ASSIGN_ATTRIBUTE_IDS;
1713 xmlCompilationFlags &= ~XML_COMPILE_PARSE_VALUES;
1714 }
1715 err = compileXmlFile(bundle, assets, workItem.resourceName, workItem.xmlRoot,
1716 workItem.file, &table, xmlCompilationFlags);
1717
Adam Lesinskicf1f1d92017-03-16 16:54:23 -07001718 if (err == NO_ERROR && workItem.file->hasData()) {
Adam Lesinskie572c012014-09-19 15:10:04 -07001719 assets->addResource(workItem.resPath.getPathLeaf(),
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07001720 workItem.resPath,
1721 workItem.file,
1722 workItem.file->getResourceType());
Adam Lesinskie572c012014-09-19 15:10:04 -07001723 } else {
1724 hasErrors = true;
1725 }
1726 workQueue.pop();
1727 }
1728
Adam Lesinski282e1812014-01-23 18:17:42 -08001729 if (table.validateLocalizations()) {
1730 hasErrors = true;
1731 }
1732
1733 if (hasErrors) {
1734 return UNKNOWN_ERROR;
1735 }
1736
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001737 // If we're not overriding the platform build versions,
1738 // extract them from the platform APK.
1739 if (packageType != ResourceTable::System &&
1740 (bundle->getPlatformBuildVersionCode() == "" ||
Alan Viverette11be9312017-11-09 15:41:44 -05001741 bundle->getPlatformBuildVersionName() == "" ||
1742 bundle->getCompileSdkVersion() == 0 ||
1743 bundle->getCompileSdkVersionCodename() == "")) {
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07001744 err = extractPlatformBuildVersion(assets->getAssetManager(), bundle);
1745 if (err != NO_ERROR) {
1746 return UNKNOWN_ERROR;
1747 }
1748 }
1749
Adam Lesinski282e1812014-01-23 18:17:42 -08001750 const sp<AaptFile> manifestFile(androidManifestFile->getFiles().valueAt(0));
1751 String8 manifestPath(manifestFile->getPrintableSource());
1752
1753 // Generate final compiled manifest file.
1754 manifestFile->clearData();
1755 sp<XMLNode> manifestTree = XMLNode::parse(manifestFile);
1756 if (manifestTree == NULL) {
1757 return UNKNOWN_ERROR;
1758 }
Adam Lesinski99d36ee2017-04-17 16:22:03 -07001759 err = massageManifest(bundle, &table, manifestTree);
Adam Lesinski282e1812014-01-23 18:17:42 -08001760 if (err < NO_ERROR) {
1761 return err;
1762 }
Adam Lesinskie572c012014-09-19 15:10:04 -07001763 err = compileXmlFile(bundle, assets, String16(), manifestTree, manifestFile, &table);
Adam Lesinski282e1812014-01-23 18:17:42 -08001764 if (err < NO_ERROR) {
1765 return err;
1766 }
1767
Adam Lesinski82a2dd82014-09-17 18:34:15 -07001768 if (table.modifyForCompat(bundle) != NO_ERROR) {
1769 return UNKNOWN_ERROR;
1770 }
1771
Adam Lesinski282e1812014-01-23 18:17:42 -08001772 //block.restart();
1773 //printXMLBlock(&block);
1774
1775 // --------------------------------------------------------------
1776 // Generate the final resource table.
1777 // Re-flatten because we may have added new resource IDs
1778 // --------------------------------------------------------------
1779
Adam Lesinskide7de472014-11-03 12:03:08 -08001780
Adam Lesinski282e1812014-01-23 18:17:42 -08001781 ResTable finalResTable;
1782 sp<AaptFile> resFile;
1783
1784 if (table.hasResources()) {
1785 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
Adrian Roos58922482015-06-01 17:59:41 -07001786 err = table.addSymbols(symbols, bundle->getSkipSymbolsWithoutDefaultLocalization());
Adam Lesinski282e1812014-01-23 18:17:42 -08001787 if (err < NO_ERROR) {
1788 return err;
1789 }
1790
Adam Lesinskide7de472014-11-03 12:03:08 -08001791 KeyedVector<Symbol, Vector<SymbolDefinition> > densityVaryingResources;
1792 if (builder->getSplits().size() > 1) {
1793 // Only look for density varying resources if we're generating
1794 // splits.
1795 table.getDensityVaryingResources(densityVaryingResources);
1796 }
1797
Adam Lesinskifab50872014-04-16 14:40:42 -07001798 Vector<sp<ApkSplit> >& splits = builder->getSplits();
1799 const size_t numSplits = splits.size();
1800 for (size_t i = 0; i < numSplits; i++) {
1801 sp<ApkSplit>& split = splits.editItemAt(i);
1802 sp<AaptFile> flattenedTable = new AaptFile(String8("resources.arsc"),
1803 AaptGroupEntry(), String8());
Adam Lesinski27f69f42014-08-21 13:19:12 -07001804 err = table.flatten(bundle, split->getResourceFilter(),
1805 flattenedTable, split->isBase());
Adam Lesinskifab50872014-04-16 14:40:42 -07001806 if (err != NO_ERROR) {
1807 fprintf(stderr, "Failed to generate resource table for split '%s'\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001808 split->getPrintableName().c_str());
Adam Lesinskifab50872014-04-16 14:40:42 -07001809 return err;
1810 }
1811 split->addEntry(String8("resources.arsc"), flattenedTable);
Adam Lesinski282e1812014-01-23 18:17:42 -08001812
Adam Lesinskifab50872014-04-16 14:40:42 -07001813 if (split->isBase()) {
1814 resFile = flattenedTable;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07001815 err = finalResTable.add(flattenedTable->getData(), flattenedTable->getSize());
1816 if (err != NO_ERROR) {
1817 fprintf(stderr, "Generated resource table is corrupt.\n");
1818 return err;
1819 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001820 } else {
Adam Lesinskide7de472014-11-03 12:03:08 -08001821 ResTable resTable;
1822 err = resTable.add(flattenedTable->getData(), flattenedTable->getSize());
1823 if (err != NO_ERROR) {
1824 fprintf(stderr, "Generated resource table for split '%s' is corrupt.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001825 split->getPrintableName().c_str());
Adam Lesinskide7de472014-11-03 12:03:08 -08001826 return err;
1827 }
1828
1829 bool hasError = false;
1830 const std::set<ConfigDescription>& splitConfigs = split->getConfigs();
1831 for (std::set<ConfigDescription>::const_iterator iter = splitConfigs.begin();
1832 iter != splitConfigs.end();
1833 ++iter) {
1834 const ConfigDescription& config = *iter;
1835 if (AaptConfig::isDensityOnly(config)) {
1836 // Each density only split must contain all
1837 // density only resources.
1838 Res_value val;
1839 resTable.setParameters(&config);
1840 const size_t densityVaryingResourceCount = densityVaryingResources.size();
1841 for (size_t k = 0; k < densityVaryingResourceCount; k++) {
1842 const Symbol& symbol = densityVaryingResources.keyAt(k);
1843 ssize_t block = resTable.getResource(symbol.id, &val, true);
1844 if (block < 0) {
1845 // Maybe it's in the base?
1846 finalResTable.setParameters(&config);
1847 block = finalResTable.getResource(symbol.id, &val, true);
1848 }
1849
1850 if (block < 0) {
1851 hasError = true;
1852 SourcePos().error("%s has no definition for density split '%s'",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001853 symbol.toString().c_str(), config.toString().c_str());
Adam Lesinskide7de472014-11-03 12:03:08 -08001854
1855 if (bundle->getVerbose()) {
1856 const Vector<SymbolDefinition>& defs = densityVaryingResources[k];
1857 const size_t defCount = std::min(size_t(5), defs.size());
1858 for (size_t d = 0; d < defCount; d++) {
1859 const SymbolDefinition& def = defs[d];
1860 def.source.error("%s has definition for %s",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001861 symbol.toString().c_str(), def.config.toString().c_str());
Adam Lesinskide7de472014-11-03 12:03:08 -08001862 }
1863
1864 if (defCount < defs.size()) {
1865 SourcePos().error("and %d more ...", (int) (defs.size() - defCount));
1866 }
1867 }
1868 }
1869 }
1870 }
1871 }
1872
1873 if (hasError) {
1874 return UNKNOWN_ERROR;
1875 }
1876
1877 // Generate the AndroidManifest for this split.
Adam Lesinskifab50872014-04-16 14:40:42 -07001878 sp<AaptFile> generatedManifest = new AaptFile(String8("AndroidManifest.xml"),
1879 AaptGroupEntry(), String8());
Jeff Sharkey2cfc8482014-07-09 16:10:16 -07001880 err = generateAndroidManifestForSplit(bundle, assets, split,
1881 generatedManifest, &table);
Adam Lesinskifab50872014-04-16 14:40:42 -07001882 if (err != NO_ERROR) {
1883 fprintf(stderr, "Failed to generate AndroidManifest.xml for split '%s'\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001884 split->getPrintableName().c_str());
Adam Lesinskifab50872014-04-16 14:40:42 -07001885 return err;
1886 }
1887 split->addEntry(String8("AndroidManifest.xml"), generatedManifest);
1888 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001889 }
1890
1891 if (bundle->getPublicOutputFile()) {
1892 FILE* fp = fopen(bundle->getPublicOutputFile(), "w+");
1893 if (fp == NULL) {
1894 fprintf(stderr, "ERROR: Unable to open public definitions output file %s: %s\n",
1895 (const char*)bundle->getPublicOutputFile(), strerror(errno));
1896 return UNKNOWN_ERROR;
1897 }
1898 if (bundle->getVerbose()) {
1899 printf(" Writing public definitions to %s.\n", bundle->getPublicOutputFile());
1900 }
1901 table.writePublicDefinitions(String16(assets->getPackage()), fp);
1902 fclose(fp);
1903 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001904
1905 if (finalResTable.getTableCount() == 0 || resFile == NULL) {
1906 fprintf(stderr, "No resource table was generated.\n");
1907 return UNKNOWN_ERROR;
1908 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001909 }
Adam Lesinskifab50872014-04-16 14:40:42 -07001910
Adam Lesinski282e1812014-01-23 18:17:42 -08001911 // Perform a basic validation of the manifest file. This time we
1912 // parse it with the comments intact, so that we can use them to
1913 // generate java docs... so we are not going to write this one
1914 // back out to the final manifest data.
1915 sp<AaptFile> outManifestFile = new AaptFile(manifestFile->getSourceFile(),
1916 manifestFile->getGroupEntry(),
1917 manifestFile->getResourceType());
Adam Lesinskie572c012014-09-19 15:10:04 -07001918 err = compileXmlFile(bundle, assets, String16(), manifestFile,
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07001919 outManifestFile, &table, XML_COMPILE_STANDARD_RESOURCE & ~XML_COMPILE_STRIP_COMMENTS);
Adam Lesinski282e1812014-01-23 18:17:42 -08001920 if (err < NO_ERROR) {
1921 return err;
1922 }
1923 ResXMLTree block;
1924 block.setTo(outManifestFile->getData(), outManifestFile->getSize(), true);
1925 String16 manifest16("manifest");
1926 String16 permission16("permission");
1927 String16 permission_group16("permission-group");
1928 String16 uses_permission16("uses-permission");
1929 String16 instrumentation16("instrumentation");
1930 String16 application16("application");
1931 String16 provider16("provider");
1932 String16 service16("service");
1933 String16 receiver16("receiver");
1934 String16 activity16("activity");
1935 String16 action16("action");
1936 String16 category16("category");
1937 String16 data16("scheme");
Adam Lesinskid3edfde2014-08-08 17:32:44 -07001938 String16 feature_group16("feature-group");
1939 String16 uses_feature16("uses-feature");
Adam Lesinski282e1812014-01-23 18:17:42 -08001940 const char* packageIdentChars = "abcdefghijklmnopqrstuvwxyz"
1941 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789";
1942 const char* packageIdentCharsWithTheStupid = "abcdefghijklmnopqrstuvwxyz"
1943 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
1944 const char* classIdentChars = "abcdefghijklmnopqrstuvwxyz"
1945 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789$";
1946 const char* processIdentChars = "abcdefghijklmnopqrstuvwxyz"
1947 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:";
1948 const char* authoritiesIdentChars = "abcdefghijklmnopqrstuvwxyz"
1949 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-:;";
1950 const char* typeIdentChars = "abcdefghijklmnopqrstuvwxyz"
1951 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:-/*+";
1952 const char* schemeIdentChars = "abcdefghijklmnopqrstuvwxyz"
1953 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
1954 ResXMLTree::event_code_t code;
1955 sp<AaptSymbols> permissionSymbols;
1956 sp<AaptSymbols> permissionGroupSymbols;
1957 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1958 && code > ResXMLTree::BAD_DOCUMENT) {
1959 if (code == ResXMLTree::START_TAG) {
1960 size_t len;
1961 if (block.getElementNamespace(&len) != NULL) {
1962 continue;
1963 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001964 if (strcmp16(block.getElementName(&len), manifest16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001965 if (validateAttr(manifestPath, finalResTable, block, NULL, "package",
1966 packageIdentChars, true) != ATTR_OKAY) {
1967 hasErrors = true;
1968 }
1969 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1970 "sharedUserId", packageIdentChars, false) != ATTR_OKAY) {
1971 hasErrors = true;
1972 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001973 } else if (strcmp16(block.getElementName(&len), permission16.c_str()) == 0
1974 || strcmp16(block.getElementName(&len), permission_group16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001975 const bool isGroup = strcmp16(block.getElementName(&len),
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001976 permission_group16.c_str()) == 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08001977 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1978 "name", isGroup ? packageIdentCharsWithTheStupid
1979 : packageIdentChars, true) != ATTR_OKAY) {
1980 hasErrors = true;
1981 }
1982 SourcePos srcPos(manifestPath, block.getLineNumber());
1983 sp<AaptSymbols> syms;
1984 if (!isGroup) {
1985 syms = permissionSymbols;
1986 if (syms == NULL) {
1987 sp<AaptSymbols> symbols =
1988 assets->getSymbolsFor(String8("Manifest"));
1989 syms = permissionSymbols = symbols->addNestedSymbol(
1990 String8("permission"), srcPos);
1991 }
1992 } else {
1993 syms = permissionGroupSymbols;
1994 if (syms == NULL) {
1995 sp<AaptSymbols> symbols =
1996 assets->getSymbolsFor(String8("Manifest"));
1997 syms = permissionGroupSymbols = symbols->addNestedSymbol(
1998 String8("permission_group"), srcPos);
1999 }
2000 }
2001 size_t len;
2002 ssize_t index = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "name");
Dan Albertf348c152014-09-08 18:28:00 -07002003 const char16_t* id = block.getAttributeStringValue(index, &len);
Adam Lesinski282e1812014-01-23 18:17:42 -08002004 if (id == NULL) {
2005 fprintf(stderr, "%s:%d: missing name attribute in element <%s>.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002006 manifestPath.c_str(), block.getLineNumber(),
2007 String8(block.getElementName(&len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002008 hasErrors = true;
2009 break;
2010 }
2011 String8 idStr(id);
2012 char* p = idStr.lockBuffer(idStr.size());
2013 char* e = p + idStr.size();
2014 bool begins_with_digit = true; // init to true so an empty string fails
2015 while (e > p) {
2016 e--;
2017 if (*e >= '0' && *e <= '9') {
2018 begins_with_digit = true;
2019 continue;
2020 }
2021 if ((*e >= 'a' && *e <= 'z') ||
2022 (*e >= 'A' && *e <= 'Z') ||
2023 (*e == '_')) {
2024 begins_with_digit = false;
2025 continue;
2026 }
2027 if (isGroup && (*e == '-')) {
2028 *e = '_';
2029 begins_with_digit = false;
2030 continue;
2031 }
2032 e++;
2033 break;
2034 }
2035 idStr.unlockBuffer();
2036 // verify that we stopped because we hit a period or
2037 // the beginning of the string, and that the
2038 // identifier didn't begin with a digit.
2039 if (begins_with_digit || (e != p && *(e-1) != '.')) {
2040 fprintf(stderr,
2041 "%s:%d: Permission name <%s> is not a valid Java symbol\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002042 manifestPath.c_str(), block.getLineNumber(), idStr.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002043 hasErrors = true;
2044 }
2045 syms->addStringSymbol(String8(e), idStr, srcPos);
Dan Albertf348c152014-09-08 18:28:00 -07002046 const char16_t* cmt = block.getComment(&len);
Adam Lesinski282e1812014-01-23 18:17:42 -08002047 if (cmt != NULL && *cmt != 0) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002048 //printf("Comment of %s: %s\n", String8(e).c_str(),
2049 // String8(cmt).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002050 syms->appendComment(String8(e), String16(cmt), srcPos);
Adam Lesinski282e1812014-01-23 18:17:42 -08002051 }
2052 syms->makeSymbolPublic(String8(e), srcPos);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002053 } else if (strcmp16(block.getElementName(&len), uses_permission16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002054 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
2055 "name", packageIdentChars, true) != ATTR_OKAY) {
2056 hasErrors = true;
2057 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002058 } else if (strcmp16(block.getElementName(&len), instrumentation16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002059 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
2060 "name", classIdentChars, true) != ATTR_OKAY) {
2061 hasErrors = true;
2062 }
2063 if (validateAttr(manifestPath, finalResTable, block,
2064 RESOURCES_ANDROID_NAMESPACE, "targetPackage",
2065 packageIdentChars, true) != ATTR_OKAY) {
2066 hasErrors = true;
2067 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002068 } else if (strcmp16(block.getElementName(&len), application16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002069 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
2070 "name", classIdentChars, false) != ATTR_OKAY) {
2071 hasErrors = true;
2072 }
2073 if (validateAttr(manifestPath, finalResTable, block,
2074 RESOURCES_ANDROID_NAMESPACE, "permission",
2075 packageIdentChars, false) != ATTR_OKAY) {
2076 hasErrors = true;
2077 }
2078 if (validateAttr(manifestPath, finalResTable, block,
2079 RESOURCES_ANDROID_NAMESPACE, "process",
2080 processIdentChars, false) != ATTR_OKAY) {
2081 hasErrors = true;
2082 }
2083 if (validateAttr(manifestPath, finalResTable, block,
2084 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
2085 processIdentChars, false) != ATTR_OKAY) {
2086 hasErrors = true;
2087 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002088 } else if (strcmp16(block.getElementName(&len), provider16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002089 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
2090 "name", classIdentChars, true) != ATTR_OKAY) {
2091 hasErrors = true;
2092 }
2093 if (validateAttr(manifestPath, finalResTable, block,
2094 RESOURCES_ANDROID_NAMESPACE, "authorities",
2095 authoritiesIdentChars, true) != ATTR_OKAY) {
2096 hasErrors = true;
2097 }
2098 if (validateAttr(manifestPath, finalResTable, block,
2099 RESOURCES_ANDROID_NAMESPACE, "permission",
2100 packageIdentChars, false) != ATTR_OKAY) {
2101 hasErrors = true;
2102 }
2103 if (validateAttr(manifestPath, finalResTable, block,
2104 RESOURCES_ANDROID_NAMESPACE, "process",
2105 processIdentChars, false) != ATTR_OKAY) {
2106 hasErrors = true;
2107 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002108 } else if (strcmp16(block.getElementName(&len), service16.c_str()) == 0
2109 || strcmp16(block.getElementName(&len), receiver16.c_str()) == 0
2110 || strcmp16(block.getElementName(&len), activity16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002111 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
2112 "name", classIdentChars, true) != ATTR_OKAY) {
2113 hasErrors = true;
2114 }
2115 if (validateAttr(manifestPath, finalResTable, block,
2116 RESOURCES_ANDROID_NAMESPACE, "permission",
2117 packageIdentChars, false) != ATTR_OKAY) {
2118 hasErrors = true;
2119 }
2120 if (validateAttr(manifestPath, finalResTable, block,
2121 RESOURCES_ANDROID_NAMESPACE, "process",
2122 processIdentChars, false) != ATTR_OKAY) {
2123 hasErrors = true;
2124 }
2125 if (validateAttr(manifestPath, finalResTable, block,
2126 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
2127 processIdentChars, false) != ATTR_OKAY) {
2128 hasErrors = true;
2129 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002130 } else if (strcmp16(block.getElementName(&len), action16.c_str()) == 0
2131 || strcmp16(block.getElementName(&len), category16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002132 if (validateAttr(manifestPath, finalResTable, block,
2133 RESOURCES_ANDROID_NAMESPACE, "name",
2134 packageIdentChars, true) != ATTR_OKAY) {
2135 hasErrors = true;
2136 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002137 } else if (strcmp16(block.getElementName(&len), data16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002138 if (validateAttr(manifestPath, finalResTable, block,
2139 RESOURCES_ANDROID_NAMESPACE, "mimeType",
2140 typeIdentChars, true) != ATTR_OKAY) {
2141 hasErrors = true;
2142 }
2143 if (validateAttr(manifestPath, finalResTable, block,
2144 RESOURCES_ANDROID_NAMESPACE, "scheme",
2145 schemeIdentChars, true) != ATTR_OKAY) {
2146 hasErrors = true;
2147 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002148 } else if (strcmp16(block.getElementName(&len), feature_group16.c_str()) == 0) {
Adam Lesinskid3edfde2014-08-08 17:32:44 -07002149 int depth = 1;
2150 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
2151 && code > ResXMLTree::BAD_DOCUMENT) {
2152 if (code == ResXMLTree::START_TAG) {
2153 depth++;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002154 if (strcmp16(block.getElementName(&len), uses_feature16.c_str()) == 0) {
Adam Lesinskid3edfde2014-08-08 17:32:44 -07002155 ssize_t idx = block.indexOfAttribute(
2156 RESOURCES_ANDROID_NAMESPACE, "required");
2157 if (idx < 0) {
2158 continue;
2159 }
2160
2161 int32_t data = block.getAttributeData(idx);
2162 if (data == 0) {
2163 fprintf(stderr, "%s:%d: Tag <uses-feature> can not have "
2164 "android:required=\"false\" when inside a "
2165 "<feature-group> tag.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002166 manifestPath.c_str(), block.getLineNumber());
Adam Lesinskid3edfde2014-08-08 17:32:44 -07002167 hasErrors = true;
2168 }
2169 }
2170 } else if (code == ResXMLTree::END_TAG) {
2171 depth--;
2172 if (depth == 0) {
2173 break;
2174 }
2175 }
2176 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002177 }
2178 }
2179 }
2180
Adam Lesinskid3edfde2014-08-08 17:32:44 -07002181 if (hasErrors) {
2182 return UNKNOWN_ERROR;
2183 }
2184
Adam Lesinski282e1812014-01-23 18:17:42 -08002185 if (resFile != NULL) {
2186 // These resources are now considered to be a part of the included
2187 // resources, for others to reference.
2188 err = assets->addIncludedResources(resFile);
2189 if (err < NO_ERROR) {
2190 fprintf(stderr, "ERROR: Unable to parse generated resources, aborting.\n");
2191 return err;
2192 }
2193 }
2194
2195 return err;
2196}
2197
2198static const char* getIndentSpace(int indent)
2199{
2200static const char whitespace[] =
2201" ";
2202
2203 return whitespace + sizeof(whitespace) - 1 - indent*4;
2204}
2205
2206static String8 flattenSymbol(const String8& symbol) {
2207 String8 result(symbol);
2208 ssize_t first;
2209 if ((first = symbol.find(":", 0)) >= 0
2210 || (first = symbol.find(".", 0)) >= 0) {
2211 size_t size = symbol.size();
2212 char* buf = result.lockBuffer(size);
2213 for (size_t i = first; i < size; i++) {
2214 if (buf[i] == ':' || buf[i] == '.') {
2215 buf[i] = '_';
2216 }
2217 }
2218 result.unlockBuffer(size);
2219 }
2220 return result;
2221}
2222
2223static String8 getSymbolPackage(const String8& symbol, const sp<AaptAssets>& assets, bool pub) {
2224 ssize_t colon = symbol.find(":", 0);
2225 if (colon >= 0) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002226 return String8(symbol.c_str(), colon);
Adam Lesinski282e1812014-01-23 18:17:42 -08002227 }
2228 return pub ? assets->getPackage() : assets->getSymbolsPrivatePackage();
2229}
2230
2231static String8 getSymbolName(const String8& symbol) {
2232 ssize_t colon = symbol.find(":", 0);
2233 if (colon >= 0) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002234 return String8(symbol.c_str() + colon + 1);
Adam Lesinski282e1812014-01-23 18:17:42 -08002235 }
2236 return symbol;
2237}
2238
2239static String16 getAttributeComment(const sp<AaptAssets>& assets,
2240 const String8& name,
2241 String16* outTypeComment = NULL)
2242{
2243 sp<AaptSymbols> asym = assets->getSymbolsFor(String8("R"));
2244 if (asym != NULL) {
2245 //printf("Got R symbols!\n");
2246 asym = asym->getNestedSymbols().valueFor(String8("attr"));
2247 if (asym != NULL) {
2248 //printf("Got attrs symbols! comment %s=%s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002249 // name.c_str(), String8(asym->getComment(name)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002250 if (outTypeComment != NULL) {
2251 *outTypeComment = asym->getTypeComment(name);
2252 }
2253 return asym->getComment(name);
2254 }
2255 }
2256 return String16();
2257}
2258
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002259static status_t writeResourceLoadedCallbackForLayoutClasses(
2260 FILE* fp, const sp<AaptAssets>& assets,
Andreas Gampe87332a72014-10-01 22:03:58 -07002261 const sp<AaptSymbols>& symbols, int indent, bool /* includePrivate */)
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002262{
2263 String16 attr16("attr");
2264 String16 package16(assets->getPackage());
2265
2266 const char* indentStr = getIndentSpace(indent);
2267 bool hasErrors = false;
2268
2269 size_t i;
2270 size_t N = symbols->getNestedSymbols().size();
2271 for (i=0; i<N; i++) {
2272 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2273 String8 realClassName(symbols->getNestedSymbols().keyAt(i));
2274 String8 nclassName(flattenSymbol(realClassName));
2275
2276 fprintf(fp,
2277 "%sfor(int i = 0; i < styleable.%s.length; ++i) {\n"
2278 "%sstyleable.%s[i] = (styleable.%s[i] & 0x00ffffff) | (packageId << 24);\n"
2279 "%s}\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002280 indentStr, nclassName.c_str(),
2281 getIndentSpace(indent+1), nclassName.c_str(), nclassName.c_str(),
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002282 indentStr);
Adam Lesinski1e4663852014-08-15 14:47:28 -07002283 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002284
Dan Alberted811ee2016-01-15 12:16:06 -08002285 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002286}
2287
2288static status_t writeResourceLoadedCallback(
2289 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2290 const sp<AaptSymbols>& symbols, const String8& className, int indent)
2291{
2292 size_t i;
2293 status_t err = NO_ERROR;
2294
2295 size_t N = symbols->getSymbols().size();
2296 for (i=0; i<N; i++) {
2297 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
Adam Lesinskieed58582015-09-10 18:43:34 -07002298 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002299 continue;
Adam Lesinski1e4663852014-08-15 14:47:28 -07002300 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002301 if (!assets->isJavaSymbol(sym, includePrivate)) {
2302 continue;
Adam Lesinski1e4663852014-08-15 14:47:28 -07002303 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002304 String8 flat_name(flattenSymbol(sym.name));
2305 fprintf(fp,
2306 "%s%s.%s = (%s.%s & 0x00ffffff) | (packageId << 24);\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002307 getIndentSpace(indent), className.c_str(), flat_name.c_str(),
2308 className.c_str(), flat_name.c_str());
Adam Lesinski1e4663852014-08-15 14:47:28 -07002309 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002310
2311 N = symbols->getNestedSymbols().size();
2312 for (i=0; i<N; i++) {
2313 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2314 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2315 if (nclassName == "styleable") {
2316 err = writeResourceLoadedCallbackForLayoutClasses(
2317 fp, assets, nsymbols, indent, includePrivate);
2318 } else {
2319 err = writeResourceLoadedCallback(fp, assets, includePrivate, nsymbols,
2320 nclassName, indent);
Adam Lesinski1e4663852014-08-15 14:47:28 -07002321 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002322 if (err != NO_ERROR) {
2323 return err;
2324 }
Adam Lesinski1e4663852014-08-15 14:47:28 -07002325 }
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002326
2327 return NO_ERROR;
Adam Lesinski1e4663852014-08-15 14:47:28 -07002328}
2329
Adam Lesinski282e1812014-01-23 18:17:42 -08002330static status_t writeLayoutClasses(
2331 FILE* fp, const sp<AaptAssets>& assets,
Adam Lesinskie8e91922014-08-06 17:41:08 -07002332 const sp<AaptSymbols>& symbols, int indent, bool includePrivate, bool nonConstantId)
Adam Lesinski282e1812014-01-23 18:17:42 -08002333{
2334 const char* indentStr = getIndentSpace(indent);
2335 if (!includePrivate) {
2336 fprintf(fp, "%s/** @doconly */\n", indentStr);
2337 }
2338 fprintf(fp, "%spublic static final class styleable {\n", indentStr);
2339 indent++;
2340
2341 String16 attr16("attr");
2342 String16 package16(assets->getPackage());
2343
2344 indentStr = getIndentSpace(indent);
2345 bool hasErrors = false;
2346
2347 size_t i;
2348 size_t N = symbols->getNestedSymbols().size();
2349 for (i=0; i<N; i++) {
2350 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2351 String8 realClassName(symbols->getNestedSymbols().keyAt(i));
2352 String8 nclassName(flattenSymbol(realClassName));
2353
2354 SortedVector<uint32_t> idents;
2355 Vector<uint32_t> origOrder;
2356 Vector<bool> publicFlags;
2357
2358 size_t a;
2359 size_t NA = nsymbols->getSymbols().size();
2360 for (a=0; a<NA; a++) {
2361 const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a));
2362 int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32
2363 ? sym.int32Val : 0;
2364 bool isPublic = true;
2365 if (code == 0) {
2366 String16 name16(sym.name);
2367 uint32_t typeSpecFlags;
2368 code = assets->getIncludedResources().identifierForName(
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002369 name16.c_str(), name16.size(),
2370 attr16.c_str(), attr16.size(),
2371 package16.c_str(), package16.size(), &typeSpecFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08002372 if (code == 0) {
2373 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002374 nclassName.c_str(), sym.name.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002375 hasErrors = true;
2376 }
2377 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
2378 }
2379 idents.add(code);
2380 origOrder.add(code);
2381 publicFlags.add(isPublic);
2382 }
2383
2384 NA = idents.size();
2385
Adam Lesinski282e1812014-01-23 18:17:42 -08002386 String16 comment = symbols->getComment(realClassName);
Jeff Browneb490d62014-06-06 19:43:42 -07002387 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002388 fprintf(fp, "%s/** ", indentStr);
2389 if (comment.size() > 0) {
2390 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002391 ann.preprocessComment(cmt);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002392 fprintf(fp, "%s\n", cmt.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002393 } else {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002394 fprintf(fp, "Attributes that can be used with a %s.\n", nclassName.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002395 }
2396 bool hasTable = false;
2397 for (a=0; a<NA; a++) {
2398 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2399 if (pos >= 0) {
2400 if (!hasTable) {
2401 hasTable = true;
2402 fprintf(fp,
2403 "%s <p>Includes the following attributes:</p>\n"
2404 "%s <table>\n"
2405 "%s <colgroup align=\"left\" />\n"
2406 "%s <colgroup align=\"left\" />\n"
2407 "%s <tr><th>Attribute</th><th>Description</th></tr>\n",
2408 indentStr,
2409 indentStr,
2410 indentStr,
2411 indentStr,
2412 indentStr);
2413 }
2414 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2415 if (!publicFlags.itemAt(a) && !includePrivate) {
2416 continue;
2417 }
2418 String8 name8(sym.name);
2419 String16 comment(sym.comment);
2420 if (comment.size() <= 0) {
2421 comment = getAttributeComment(assets, name8);
2422 }
Michael Wrightfeaf99f2016-05-06 17:16:06 +01002423 if (comment.contains(u"@removed")) {
2424 continue;
2425 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002426 if (comment.size() > 0) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002427 const char16_t* p = comment.c_str();
Adam Lesinski282e1812014-01-23 18:17:42 -08002428 while (*p != 0 && *p != '.') {
2429 if (*p == '{') {
2430 while (*p != 0 && *p != '}') {
2431 p++;
2432 }
2433 } else {
2434 p++;
2435 }
2436 }
2437 if (*p == '.') {
2438 p++;
2439 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002440 comment = String16(comment.c_str(), p-comment.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002441 }
2442 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 +00002443 indentStr, nclassName.c_str(),
2444 flattenSymbol(name8).c_str(),
2445 getSymbolPackage(name8, assets, true).c_str(),
2446 getSymbolName(name8).c_str(),
2447 String8(comment).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002448 }
2449 }
2450 if (hasTable) {
2451 fprintf(fp, "%s </table>\n", indentStr);
2452 }
2453 for (a=0; a<NA; a++) {
2454 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2455 if (pos >= 0) {
2456 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2457 if (!publicFlags.itemAt(a) && !includePrivate) {
2458 continue;
2459 }
2460 fprintf(fp, "%s @see #%s_%s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002461 indentStr, nclassName.c_str(),
2462 flattenSymbol(sym.name).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002463 }
2464 }
2465 fprintf(fp, "%s */\n", getIndentSpace(indent));
2466
Jeff Browneb490d62014-06-06 19:43:42 -07002467 ann.printAnnotations(fp, indentStr);
Adam Lesinski282e1812014-01-23 18:17:42 -08002468
2469 fprintf(fp,
2470 "%spublic static final int[] %s = {\n"
2471 "%s",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002472 indentStr, nclassName.c_str(),
Adam Lesinski282e1812014-01-23 18:17:42 -08002473 getIndentSpace(indent+1));
2474
2475 for (a=0; a<NA; a++) {
2476 if (a != 0) {
2477 if ((a&3) == 0) {
2478 fprintf(fp, ",\n%s", getIndentSpace(indent+1));
2479 } else {
2480 fprintf(fp, ", ");
2481 }
2482 }
2483 fprintf(fp, "0x%08x", idents[a]);
2484 }
2485
2486 fprintf(fp, "\n%s};\n", indentStr);
2487
2488 for (a=0; a<NA; a++) {
2489 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2490 if (pos >= 0) {
2491 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2492 if (!publicFlags.itemAt(a) && !includePrivate) {
2493 continue;
2494 }
2495 String8 name8(sym.name);
2496 String16 comment(sym.comment);
2497 String16 typeComment;
2498 if (comment.size() <= 0) {
2499 comment = getAttributeComment(assets, name8, &typeComment);
2500 } else {
2501 getAttributeComment(assets, name8, &typeComment);
2502 }
2503
2504 uint32_t typeSpecFlags = 0;
2505 String16 name16(sym.name);
2506 assets->getIncludedResources().identifierForName(
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002507 name16.c_str(), name16.size(),
2508 attr16.c_str(), attr16.size(),
2509 package16.c_str(), package16.size(), &typeSpecFlags);
2510 //printf("%s:%s/%s: 0x%08x\n", String8(package16).c_str(),
2511 // String8(attr16).c_str(), String8(name16).c_str(), typeSpecFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08002512 const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
Jeff Browneb490d62014-06-06 19:43:42 -07002513
2514 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002515 fprintf(fp, "%s/**\n", indentStr);
2516 if (comment.size() > 0) {
2517 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002518 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002519 fprintf(fp, "%s <p>\n%s @attr description\n", indentStr, indentStr);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002520 fprintf(fp, "%s %s\n", indentStr, cmt.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002521 } else {
2522 fprintf(fp,
2523 "%s <p>This symbol is the offset where the {@link %s.R.attr#%s}\n"
2524 "%s attribute's value can be found in the {@link #%s} array.\n",
2525 indentStr,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002526 getSymbolPackage(name8, assets, pub).c_str(),
2527 getSymbolName(name8).c_str(),
2528 indentStr, nclassName.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002529 }
2530 if (typeComment.size() > 0) {
2531 String8 cmt(typeComment);
Jeff Browneb490d62014-06-06 19:43:42 -07002532 ann.preprocessComment(cmt);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002533 fprintf(fp, "\n\n%s %s\n", indentStr, cmt.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002534 }
2535 if (comment.size() > 0) {
2536 if (pub) {
2537 fprintf(fp,
2538 "%s <p>This corresponds to the global attribute\n"
2539 "%s resource symbol {@link %s.R.attr#%s}.\n",
2540 indentStr, indentStr,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002541 getSymbolPackage(name8, assets, true).c_str(),
2542 getSymbolName(name8).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002543 } else {
2544 fprintf(fp,
2545 "%s <p>This is a private symbol.\n", indentStr);
2546 }
2547 }
2548 fprintf(fp, "%s @attr name %s:%s\n", indentStr,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002549 getSymbolPackage(name8, assets, pub).c_str(),
2550 getSymbolName(name8).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002551 fprintf(fp, "%s*/\n", indentStr);
Jeff Browneb490d62014-06-06 19:43:42 -07002552 ann.printAnnotations(fp, indentStr);
Adam Lesinskie8e91922014-08-06 17:41:08 -07002553
2554 const char * id_format = nonConstantId ?
2555 "%spublic static int %s_%s = %d;\n" :
2556 "%spublic static final int %s_%s = %d;\n";
2557
Adam Lesinski282e1812014-01-23 18:17:42 -08002558 fprintf(fp,
Adam Lesinskie8e91922014-08-06 17:41:08 -07002559 id_format,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002560 indentStr, nclassName.c_str(),
2561 flattenSymbol(name8).c_str(), (int)pos);
Adam Lesinski282e1812014-01-23 18:17:42 -08002562 }
2563 }
2564 }
2565
2566 indent--;
2567 fprintf(fp, "%s};\n", getIndentSpace(indent));
Andreas Gampe2412f842014-09-30 20:55:57 -07002568 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08002569}
2570
2571static status_t writeTextLayoutClasses(
2572 FILE* fp, const sp<AaptAssets>& assets,
2573 const sp<AaptSymbols>& symbols, bool includePrivate)
2574{
2575 String16 attr16("attr");
2576 String16 package16(assets->getPackage());
2577
2578 bool hasErrors = false;
2579
2580 size_t i;
2581 size_t N = symbols->getNestedSymbols().size();
2582 for (i=0; i<N; i++) {
2583 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2584 String8 realClassName(symbols->getNestedSymbols().keyAt(i));
2585 String8 nclassName(flattenSymbol(realClassName));
2586
2587 SortedVector<uint32_t> idents;
2588 Vector<uint32_t> origOrder;
2589 Vector<bool> publicFlags;
2590
2591 size_t a;
2592 size_t NA = nsymbols->getSymbols().size();
2593 for (a=0; a<NA; a++) {
2594 const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a));
2595 int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32
2596 ? sym.int32Val : 0;
2597 bool isPublic = true;
2598 if (code == 0) {
2599 String16 name16(sym.name);
2600 uint32_t typeSpecFlags;
2601 code = assets->getIncludedResources().identifierForName(
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002602 name16.c_str(), name16.size(),
2603 attr16.c_str(), attr16.size(),
2604 package16.c_str(), package16.size(), &typeSpecFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -08002605 if (code == 0) {
2606 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002607 nclassName.c_str(), sym.name.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002608 hasErrors = true;
2609 }
2610 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
2611 }
2612 idents.add(code);
2613 origOrder.add(code);
2614 publicFlags.add(isPublic);
2615 }
2616
2617 NA = idents.size();
2618
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002619 fprintf(fp, "int[] styleable %s {", nclassName.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002620
2621 for (a=0; a<NA; a++) {
2622 if (a != 0) {
2623 fprintf(fp, ",");
2624 }
2625 fprintf(fp, " 0x%08x", idents[a]);
2626 }
2627
2628 fprintf(fp, " }\n");
2629
2630 for (a=0; a<NA; a++) {
2631 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
2632 if (pos >= 0) {
2633 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
2634 if (!publicFlags.itemAt(a) && !includePrivate) {
2635 continue;
2636 }
2637 String8 name8(sym.name);
2638 String16 comment(sym.comment);
2639 String16 typeComment;
2640 if (comment.size() <= 0) {
2641 comment = getAttributeComment(assets, name8, &typeComment);
2642 } else {
2643 getAttributeComment(assets, name8, &typeComment);
2644 }
2645
2646 uint32_t typeSpecFlags = 0;
2647 String16 name16(sym.name);
2648 assets->getIncludedResources().identifierForName(
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002649 name16.c_str(), name16.size(),
2650 attr16.c_str(), attr16.size(),
2651 package16.c_str(), package16.size(), &typeSpecFlags);
2652 //printf("%s:%s/%s: 0x%08x\n", String8(package16).c_str(),
2653 // String8(attr16).c_str(), String8(name16).c_str(), typeSpecFlags);
Andreas Gampe2412f842014-09-30 20:55:57 -07002654 //const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08002655
2656 fprintf(fp,
2657 "int styleable %s_%s %d\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002658 nclassName.c_str(),
2659 flattenSymbol(name8).c_str(), (int)pos);
Adam Lesinski282e1812014-01-23 18:17:42 -08002660 }
2661 }
2662 }
2663
Andreas Gampe2412f842014-09-30 20:55:57 -07002664 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08002665}
2666
2667static status_t writeSymbolClass(
2668 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2669 const sp<AaptSymbols>& symbols, const String8& className, int indent,
Adam Lesinski1e4663852014-08-15 14:47:28 -07002670 bool nonConstantId, bool emitCallback)
Adam Lesinski282e1812014-01-23 18:17:42 -08002671{
2672 fprintf(fp, "%spublic %sfinal class %s {\n",
2673 getIndentSpace(indent),
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002674 indent != 0 ? "static " : "", className.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002675 indent++;
2676
2677 size_t i;
2678 status_t err = NO_ERROR;
2679
2680 const char * id_format = nonConstantId ?
2681 "%spublic static int %s=0x%08x;\n" :
2682 "%spublic static final int %s=0x%08x;\n";
2683
2684 size_t N = symbols->getSymbols().size();
2685 for (i=0; i<N; i++) {
2686 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2687 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
2688 continue;
2689 }
2690 if (!assets->isJavaSymbol(sym, includePrivate)) {
2691 continue;
2692 }
2693 String8 name8(sym.name);
2694 String16 comment(sym.comment);
2695 bool haveComment = false;
Jeff Browneb490d62014-06-06 19:43:42 -07002696 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002697 if (comment.size() > 0) {
2698 haveComment = true;
2699 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002700 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002701 fprintf(fp,
2702 "%s/** %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002703 getIndentSpace(indent), cmt.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002704 }
2705 String16 typeComment(sym.typeComment);
2706 if (typeComment.size() > 0) {
2707 String8 cmt(typeComment);
Jeff Browneb490d62014-06-06 19:43:42 -07002708 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002709 if (!haveComment) {
2710 haveComment = true;
2711 fprintf(fp,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002712 "%s/** %s\n", getIndentSpace(indent), cmt.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002713 } else {
2714 fprintf(fp,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002715 "%s %s\n", getIndentSpace(indent), cmt.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002716 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002717 }
2718 if (haveComment) {
2719 fprintf(fp,"%s */\n", getIndentSpace(indent));
2720 }
Jeff Browneb490d62014-06-06 19:43:42 -07002721 ann.printAnnotations(fp, getIndentSpace(indent));
Adam Lesinski282e1812014-01-23 18:17:42 -08002722 fprintf(fp, id_format,
2723 getIndentSpace(indent),
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002724 flattenSymbol(name8).c_str(), (int)sym.int32Val);
Adam Lesinski282e1812014-01-23 18:17:42 -08002725 }
2726
2727 for (i=0; i<N; i++) {
2728 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2729 if (sym.typeCode != AaptSymbolEntry::TYPE_STRING) {
2730 continue;
2731 }
2732 if (!assets->isJavaSymbol(sym, includePrivate)) {
2733 continue;
2734 }
2735 String8 name8(sym.name);
2736 String16 comment(sym.comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002737 AnnotationProcessor ann;
Adam Lesinski282e1812014-01-23 18:17:42 -08002738 if (comment.size() > 0) {
2739 String8 cmt(comment);
Jeff Browneb490d62014-06-06 19:43:42 -07002740 ann.preprocessComment(cmt);
Adam Lesinski282e1812014-01-23 18:17:42 -08002741 fprintf(fp,
2742 "%s/** %s\n"
2743 "%s */\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002744 getIndentSpace(indent), cmt.c_str(),
Adam Lesinski282e1812014-01-23 18:17:42 -08002745 getIndentSpace(indent));
Adam Lesinski282e1812014-01-23 18:17:42 -08002746 }
Jeff Browneb490d62014-06-06 19:43:42 -07002747 ann.printAnnotations(fp, getIndentSpace(indent));
Adam Lesinski282e1812014-01-23 18:17:42 -08002748 fprintf(fp, "%spublic static final String %s=\"%s\";\n",
2749 getIndentSpace(indent),
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002750 flattenSymbol(name8).c_str(), sym.stringVal.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002751 }
2752
2753 sp<AaptSymbols> styleableSymbols;
2754
2755 N = symbols->getNestedSymbols().size();
2756 for (i=0; i<N; i++) {
2757 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2758 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2759 if (nclassName == "styleable") {
2760 styleableSymbols = nsymbols;
2761 } else {
Adam Lesinski1e4663852014-08-15 14:47:28 -07002762 err = writeSymbolClass(fp, assets, includePrivate, nsymbols, nclassName,
2763 indent, nonConstantId, false);
Adam Lesinski282e1812014-01-23 18:17:42 -08002764 }
2765 if (err != NO_ERROR) {
2766 return err;
2767 }
2768 }
2769
2770 if (styleableSymbols != NULL) {
Adam Lesinskie8e91922014-08-06 17:41:08 -07002771 err = writeLayoutClasses(fp, assets, styleableSymbols, indent, includePrivate, nonConstantId);
Adam Lesinski282e1812014-01-23 18:17:42 -08002772 if (err != NO_ERROR) {
2773 return err;
2774 }
2775 }
2776
Adam Lesinski1e4663852014-08-15 14:47:28 -07002777 if (emitCallback) {
Marcin Kosiba0f3a5a62014-09-11 13:48:48 +01002778 fprintf(fp, "%spublic static void onResourcesLoaded(int packageId) {\n",
2779 getIndentSpace(indent));
2780 writeResourceLoadedCallback(fp, assets, includePrivate, symbols, className, indent + 1);
2781 fprintf(fp, "%s}\n", getIndentSpace(indent));
Adam Lesinski1e4663852014-08-15 14:47:28 -07002782 }
2783
Adam Lesinski282e1812014-01-23 18:17:42 -08002784 indent--;
2785 fprintf(fp, "%s}\n", getIndentSpace(indent));
2786 return NO_ERROR;
2787}
2788
2789static status_t writeTextSymbolClass(
2790 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2791 const sp<AaptSymbols>& symbols, const String8& className)
2792{
2793 size_t i;
2794 status_t err = NO_ERROR;
2795
2796 size_t N = symbols->getSymbols().size();
2797 for (i=0; i<N; i++) {
2798 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2799 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
2800 continue;
2801 }
2802
2803 if (!assets->isJavaSymbol(sym, includePrivate)) {
2804 continue;
2805 }
2806
2807 String8 name8(sym.name);
2808 fprintf(fp, "int %s %s 0x%08x\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002809 className.c_str(),
2810 flattenSymbol(name8).c_str(), (int)sym.int32Val);
Adam Lesinski282e1812014-01-23 18:17:42 -08002811 }
2812
2813 N = symbols->getNestedSymbols().size();
2814 for (i=0; i<N; i++) {
2815 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2816 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2817 if (nclassName == "styleable") {
2818 err = writeTextLayoutClasses(fp, assets, nsymbols, includePrivate);
2819 } else {
2820 err = writeTextSymbolClass(fp, assets, includePrivate, nsymbols, nclassName);
2821 }
2822 if (err != NO_ERROR) {
2823 return err;
2824 }
2825 }
2826
2827 return NO_ERROR;
2828}
2829
2830status_t writeResourceSymbols(Bundle* bundle, const sp<AaptAssets>& assets,
Adam Lesinski1e4663852014-08-15 14:47:28 -07002831 const String8& package, bool includePrivate, bool emitCallback)
Adam Lesinski282e1812014-01-23 18:17:42 -08002832{
2833 if (!bundle->getRClassDir()) {
2834 return NO_ERROR;
2835 }
2836
2837 const char* textSymbolsDest = bundle->getOutputTextSymbols();
2838
2839 String8 R("R");
2840 const size_t N = assets->getSymbols().size();
2841 for (size_t i=0; i<N; i++) {
2842 sp<AaptSymbols> symbols = assets->getSymbols().valueAt(i);
2843 String8 className(assets->getSymbols().keyAt(i));
2844 String8 dest(bundle->getRClassDir());
2845
2846 if (bundle->getMakePackageDirs()) {
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -07002847 const String8& pkg(package);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002848 const char* last = pkg.c_str();
Adam Lesinski282e1812014-01-23 18:17:42 -08002849 const char* s = last-1;
2850 do {
2851 s++;
2852 if (s > last && (*s == '.' || *s == 0)) {
2853 String8 part(last, s-last);
2854 dest.appendPath(part);
Elliott Hughese17788c2015-08-17 12:41:46 -07002855#ifdef _WIN32
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002856 _mkdir(dest.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002857#else
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002858 mkdir(dest.c_str(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP);
Adam Lesinski282e1812014-01-23 18:17:42 -08002859#endif
2860 last = s+1;
2861 }
2862 } while (*s);
2863 }
2864 dest.appendPath(className);
2865 dest.append(".java");
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002866 FILE* fp = fopen(dest.c_str(), "w+");
Adam Lesinski282e1812014-01-23 18:17:42 -08002867 if (fp == NULL) {
2868 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002869 dest.c_str(), strerror(errno));
Adam Lesinski282e1812014-01-23 18:17:42 -08002870 return UNKNOWN_ERROR;
2871 }
2872 if (bundle->getVerbose()) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002873 printf(" Writing symbols for class %s.\n", className.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002874 }
2875
2876 fprintf(fp,
2877 "/* AUTO-GENERATED FILE. DO NOT MODIFY.\n"
2878 " *\n"
2879 " * This class was automatically generated by the\n"
2880 " * aapt tool from the resource data it found. It\n"
2881 " * should not be modified by hand.\n"
2882 " */\n"
2883 "\n"
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002884 "package %s;\n\n", package.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002885
2886 status_t err = writeSymbolClass(fp, assets, includePrivate, symbols,
Adam Lesinski1e4663852014-08-15 14:47:28 -07002887 className, 0, bundle->getNonConstantId(), emitCallback);
Elliott Hughesb30296b2013-10-29 15:25:52 -07002888 fclose(fp);
Adam Lesinski282e1812014-01-23 18:17:42 -08002889 if (err != NO_ERROR) {
2890 return err;
2891 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002892
2893 if (textSymbolsDest != NULL && R == className) {
2894 String8 textDest(textSymbolsDest);
2895 textDest.appendPath(className);
2896 textDest.append(".txt");
2897
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002898 FILE* fp = fopen(textDest.c_str(), "w+");
Adam Lesinski282e1812014-01-23 18:17:42 -08002899 if (fp == NULL) {
2900 fprintf(stderr, "ERROR: Unable to open text symbol file %s: %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002901 textDest.c_str(), strerror(errno));
Adam Lesinski282e1812014-01-23 18:17:42 -08002902 return UNKNOWN_ERROR;
2903 }
2904 if (bundle->getVerbose()) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002905 printf(" Writing text symbols for class %s.\n", className.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002906 }
2907
2908 status_t err = writeTextSymbolClass(fp, assets, includePrivate, symbols,
2909 className);
Elliott Hughesb30296b2013-10-29 15:25:52 -07002910 fclose(fp);
Adam Lesinski282e1812014-01-23 18:17:42 -08002911 if (err != NO_ERROR) {
2912 return err;
2913 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002914 }
2915
2916 // If we were asked to generate a dependency file, we'll go ahead and add this R.java
2917 // as a target in the dependency file right next to it.
2918 if (bundle->getGenDependencies() && R == className) {
2919 // Add this R.java to the dependency file
2920 String8 dependencyFile(bundle->getRClassDir());
2921 dependencyFile.appendPath("R.java.d");
2922
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002923 FILE *fp = fopen(dependencyFile.c_str(), "a");
2924 fprintf(fp,"%s \\\n", dest.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002925 fclose(fp);
2926 }
2927 }
2928
2929 return NO_ERROR;
2930}
2931
2932
2933class ProguardKeepSet
2934{
2935public:
2936 // { rule --> { file locations } }
2937 KeyedVector<String8, SortedVector<String8> > rules;
2938
2939 void add(const String8& rule, const String8& where);
2940};
2941
2942void ProguardKeepSet::add(const String8& rule, const String8& where)
2943{
2944 ssize_t index = rules.indexOfKey(rule);
2945 if (index < 0) {
2946 index = rules.add(rule, SortedVector<String8>());
2947 }
2948 rules.editValueAt(index).add(where);
2949}
2950
2951void
2952addProguardKeepRule(ProguardKeepSet* keep, const String8& inClassName,
2953 const char* pkg, const String8& srcName, int line)
2954{
2955 String8 className(inClassName);
2956 if (pkg != NULL) {
2957 // asdf --> package.asdf
2958 // .asdf .a.b --> package.asdf package.a.b
2959 // asdf.adsf --> asdf.asdf
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002960 const char* p = className.c_str();
Adam Lesinski282e1812014-01-23 18:17:42 -08002961 const char* q = strchr(p, '.');
2962 if (p == q) {
2963 className = pkg;
2964 className.append(inClassName);
2965 } else if (q == NULL) {
2966 className = pkg;
2967 className.append(".");
2968 className.append(inClassName);
2969 }
2970 }
2971
2972 String8 rule("-keep class ");
2973 rule += className;
2974 rule += " { <init>(...); }";
2975
2976 String8 location("view ");
2977 location += srcName;
2978 char lineno[20];
2979 sprintf(lineno, ":%d", line);
2980 location += lineno;
2981
2982 keep->add(rule, location);
2983}
2984
2985void
2986addProguardKeepMethodRule(ProguardKeepSet* keep, const String8& memberName,
Andreas Gampe2412f842014-09-30 20:55:57 -07002987 const char* /* pkg */, const String8& srcName, int line)
Adam Lesinski282e1812014-01-23 18:17:42 -08002988{
2989 String8 rule("-keepclassmembers class * { *** ");
2990 rule += memberName;
2991 rule += "(...); }";
2992
2993 String8 location("onClick ");
2994 location += srcName;
2995 char lineno[20];
2996 sprintf(lineno, ":%d", line);
2997 location += lineno;
2998
2999 keep->add(rule, location);
3000}
3001
3002status_t
Rohit Agrawal682583c2016-04-21 16:29:58 -07003003writeProguardForAndroidManifest(ProguardKeepSet* keep, const sp<AaptAssets>& assets, bool mainDex)
Adam Lesinski282e1812014-01-23 18:17:42 -08003004{
3005 status_t err;
3006 ResXMLTree tree;
3007 size_t len;
3008 ResXMLTree::event_code_t code;
3009 int depth = 0;
3010 bool inApplication = false;
3011 String8 error;
3012 sp<AaptGroup> assGroup;
3013 sp<AaptFile> assFile;
3014 String8 pkg;
Rohit Agrawal682583c2016-04-21 16:29:58 -07003015 String8 defaultProcess;
Adam Lesinski282e1812014-01-23 18:17:42 -08003016
3017 // First, look for a package file to parse. This is required to
3018 // be able to generate the resource information.
3019 assGroup = assets->getFiles().valueFor(String8("AndroidManifest.xml"));
3020 if (assGroup == NULL) {
3021 fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n");
3022 return -1;
3023 }
3024
3025 if (assGroup->getFiles().size() != 1) {
3026 fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003027 assGroup->getFiles().valueAt(0)->getPrintableSource().c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003028 }
3029
3030 assFile = assGroup->getFiles().valueAt(0);
3031
3032 err = parseXMLResource(assFile, &tree);
3033 if (err != NO_ERROR) {
3034 return err;
3035 }
3036
3037 tree.restart();
3038
3039 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
3040 if (code == ResXMLTree::END_TAG) {
3041 if (/* name == "Application" && */ depth == 2) {
3042 inApplication = false;
3043 }
3044 depth--;
3045 continue;
3046 }
3047 if (code != ResXMLTree::START_TAG) {
3048 continue;
3049 }
3050 depth++;
3051 String8 tag(tree.getElementName(&len));
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003052 // printf("Depth %d tag %s\n", depth, tag.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003053 bool keepTag = false;
3054 if (depth == 1) {
3055 if (tag != "manifest") {
3056 fprintf(stderr, "ERROR: manifest does not start with <manifest> tag\n");
3057 return -1;
3058 }
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07003059 pkg = AaptXml::getAttribute(tree, NULL, "package");
Adam Lesinski282e1812014-01-23 18:17:42 -08003060 } else if (depth == 2) {
3061 if (tag == "application") {
3062 inApplication = true;
3063 keepTag = true;
3064
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07003065 String8 agent = AaptXml::getAttribute(tree,
3066 "http://schemas.android.com/apk/res/android",
Adam Lesinski282e1812014-01-23 18:17:42 -08003067 "backupAgent", &error);
3068 if (agent.length() > 0) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003069 addProguardKeepRule(keep, agent, pkg.c_str(),
Adam Lesinski282e1812014-01-23 18:17:42 -08003070 assFile->getPrintableSource(), tree.getLineNumber());
3071 }
Rohit Agrawal682583c2016-04-21 16:29:58 -07003072
3073 if (mainDex) {
3074 defaultProcess = AaptXml::getAttribute(tree,
3075 "http://schemas.android.com/apk/res/android", "process", &error);
3076 if (error != "") {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003077 fprintf(stderr, "ERROR: %s\n", error.c_str());
Rohit Agrawal682583c2016-04-21 16:29:58 -07003078 return -1;
3079 }
3080 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003081 } else if (tag == "instrumentation") {
3082 keepTag = true;
3083 }
3084 }
3085 if (!keepTag && inApplication && depth == 3) {
3086 if (tag == "activity" || tag == "service" || tag == "receiver" || tag == "provider") {
3087 keepTag = true;
Ivan Gavrilovicf580d912016-07-19 12:03:33 +01003088
3089 if (mainDex) {
3090 String8 componentProcess = AaptXml::getAttribute(tree,
3091 "http://schemas.android.com/apk/res/android", "process", &error);
3092 if (error != "") {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003093 fprintf(stderr, "ERROR: %s\n", error.c_str());
Ivan Gavrilovicf580d912016-07-19 12:03:33 +01003094 return -1;
3095 }
3096
3097 const String8& process =
3098 componentProcess.length() > 0 ? componentProcess : defaultProcess;
3099 keepTag = process.length() > 0 && process.find(":") != 0;
3100 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003101 }
3102 }
3103 if (keepTag) {
Adam Lesinskiad2d07d2014-08-27 16:21:08 -07003104 String8 name = AaptXml::getAttribute(tree,
3105 "http://schemas.android.com/apk/res/android", "name", &error);
Adam Lesinski282e1812014-01-23 18:17:42 -08003106 if (error != "") {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003107 fprintf(stderr, "ERROR: %s\n", error.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003108 return -1;
3109 }
Rohit Agrawal682583c2016-04-21 16:29:58 -07003110
3111 keepTag = name.length() > 0;
3112
Rohit Agrawal682583c2016-04-21 16:29:58 -07003113 if (keepTag) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003114 addProguardKeepRule(keep, name, pkg.c_str(),
Adam Lesinski282e1812014-01-23 18:17:42 -08003115 assFile->getPrintableSource(), tree.getLineNumber());
3116 }
3117 }
3118 }
3119
3120 return NO_ERROR;
3121}
3122
3123struct NamespaceAttributePair {
3124 const char* ns;
3125 const char* attr;
3126
3127 NamespaceAttributePair(const char* n, const char* a) : ns(n), attr(a) {}
3128 NamespaceAttributePair() : ns(NULL), attr(NULL) {}
3129};
3130
3131status_t
3132writeProguardForXml(ProguardKeepSet* keep, const sp<AaptFile>& layoutFile,
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003133 const Vector<String8>& startTags, const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs)
Adam Lesinski282e1812014-01-23 18:17:42 -08003134{
3135 status_t err;
3136 ResXMLTree tree;
3137 size_t len;
3138 ResXMLTree::event_code_t code;
3139
3140 err = parseXMLResource(layoutFile, &tree);
3141 if (err != NO_ERROR) {
3142 return err;
3143 }
3144
3145 tree.restart();
3146
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003147 if (!startTags.isEmpty()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003148 bool haveStart = false;
3149 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
3150 if (code != ResXMLTree::START_TAG) {
3151 continue;
3152 }
3153 String8 tag(tree.getElementName(&len));
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003154 const size_t numStartTags = startTags.size();
3155 for (size_t i = 0; i < numStartTags; i++) {
3156 if (tag == startTags[i]) {
3157 haveStart = true;
3158 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003159 }
3160 break;
3161 }
3162 if (!haveStart) {
3163 return NO_ERROR;
3164 }
3165 }
3166
3167 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
3168 if (code != ResXMLTree::START_TAG) {
3169 continue;
3170 }
3171 String8 tag(tree.getElementName(&len));
3172
3173 // If there is no '.', we'll assume that it's one of the built in names.
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003174 if (strchr(tag.c_str(), '.')) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003175 addProguardKeepRule(keep, tag, NULL,
3176 layoutFile->getPrintableSource(), tree.getLineNumber());
3177 } else if (tagAttrPairs != NULL) {
3178 ssize_t tagIndex = tagAttrPairs->indexOfKey(tag);
3179 if (tagIndex >= 0) {
3180 const Vector<NamespaceAttributePair>& nsAttrVector = tagAttrPairs->valueAt(tagIndex);
3181 for (size_t i = 0; i < nsAttrVector.size(); i++) {
3182 const NamespaceAttributePair& nsAttr = nsAttrVector[i];
3183
3184 ssize_t attrIndex = tree.indexOfAttribute(nsAttr.ns, nsAttr.attr);
3185 if (attrIndex < 0) {
3186 // fprintf(stderr, "%s:%d: <%s> does not have attribute %s:%s.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003187 // layoutFile->getPrintableSource().c_str(), tree.getLineNumber(),
3188 // tag.c_str(), nsAttr.ns, nsAttr.attr);
Adam Lesinski282e1812014-01-23 18:17:42 -08003189 } else {
3190 size_t len;
3191 addProguardKeepRule(keep,
3192 String8(tree.getAttributeStringValue(attrIndex, &len)), NULL,
3193 layoutFile->getPrintableSource(), tree.getLineNumber());
3194 }
3195 }
3196 }
3197 }
3198 ssize_t attrIndex = tree.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "onClick");
3199 if (attrIndex >= 0) {
3200 size_t len;
3201 addProguardKeepMethodRule(keep,
3202 String8(tree.getAttributeStringValue(attrIndex, &len)), NULL,
3203 layoutFile->getPrintableSource(), tree.getLineNumber());
3204 }
3205 }
3206
3207 return NO_ERROR;
3208}
3209
3210static void addTagAttrPair(KeyedVector<String8, Vector<NamespaceAttributePair> >* dest,
3211 const char* tag, const char* ns, const char* attr) {
3212 String8 tagStr(tag);
3213 ssize_t index = dest->indexOfKey(tagStr);
3214
3215 if (index < 0) {
3216 Vector<NamespaceAttributePair> vector;
3217 vector.add(NamespaceAttributePair(ns, attr));
3218 dest->add(tagStr, vector);
3219 } else {
3220 dest->editValueAt(index).add(NamespaceAttributePair(ns, attr));
3221 }
3222}
3223
3224status_t
3225writeProguardForLayouts(ProguardKeepSet* keep, const sp<AaptAssets>& assets)
3226{
3227 status_t err;
Adam Lesinski62c5df52014-12-02 16:19:05 -08003228 const char* kClass = "class";
3229 const char* kFragment = "fragment";
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003230 const String8 kTransition("transition");
3231 const String8 kTransitionPrefix("transition-");
Adam Lesinski282e1812014-01-23 18:17:42 -08003232
3233 // tag:attribute pairs that should be checked in layout files.
3234 KeyedVector<String8, Vector<NamespaceAttributePair> > kLayoutTagAttrPairs;
Adam Lesinski62c5df52014-12-02 16:19:05 -08003235 addTagAttrPair(&kLayoutTagAttrPairs, "view", NULL, kClass);
3236 addTagAttrPair(&kLayoutTagAttrPairs, kFragment, NULL, kClass);
3237 addTagAttrPair(&kLayoutTagAttrPairs, kFragment, RESOURCES_ANDROID_NAMESPACE, "name");
Adam Lesinski282e1812014-01-23 18:17:42 -08003238
3239 // tag:attribute pairs that should be checked in xml files.
3240 KeyedVector<String8, Vector<NamespaceAttributePair> > kXmlTagAttrPairs;
Adam Lesinski62c5df52014-12-02 16:19:05 -08003241 addTagAttrPair(&kXmlTagAttrPairs, "PreferenceScreen", RESOURCES_ANDROID_NAMESPACE, kFragment);
3242 addTagAttrPair(&kXmlTagAttrPairs, "header", RESOURCES_ANDROID_NAMESPACE, kFragment);
Adam Lesinski282e1812014-01-23 18:17:42 -08003243
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003244 // tag:attribute pairs that should be checked in transition files.
3245 KeyedVector<String8, Vector<NamespaceAttributePair> > kTransitionTagAttrPairs;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003246 addTagAttrPair(&kTransitionTagAttrPairs, kTransition.c_str(), NULL, kClass);
Adam Lesinski62c5df52014-12-02 16:19:05 -08003247 addTagAttrPair(&kTransitionTagAttrPairs, "pathMotion", NULL, kClass);
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003248
Adam Lesinski282e1812014-01-23 18:17:42 -08003249 const Vector<sp<AaptDir> >& dirs = assets->resDirs();
3250 const size_t K = dirs.size();
3251 for (size_t k=0; k<K; k++) {
3252 const sp<AaptDir>& d = dirs.itemAt(k);
3253 const String8& dirName = d->getLeaf();
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003254 Vector<String8> startTags;
Adam Lesinski282e1812014-01-23 18:17:42 -08003255 const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs = NULL;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003256 if ((dirName == String8("layout")) || (strncmp(dirName.c_str(), "layout-", 7) == 0)) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003257 tagAttrPairs = &kLayoutTagAttrPairs;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003258 } else if ((dirName == String8("xml")) || (strncmp(dirName.c_str(), "xml-", 4) == 0)) {
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003259 startTags.add(String8("PreferenceScreen"));
3260 startTags.add(String8("preference-headers"));
Adam Lesinski282e1812014-01-23 18:17:42 -08003261 tagAttrPairs = &kXmlTagAttrPairs;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003262 } else if ((dirName == String8("menu")) || (strncmp(dirName.c_str(), "menu-", 5) == 0)) {
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003263 startTags.add(String8("menu"));
Adam Lesinski282e1812014-01-23 18:17:42 -08003264 tagAttrPairs = NULL;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003265 } else if (dirName == kTransition || (strncmp(dirName.c_str(), kTransitionPrefix.c_str(),
Adam Lesinski4c488ff2014-12-02 14:50:21 -08003266 kTransitionPrefix.size()) == 0)) {
3267 tagAttrPairs = &kTransitionTagAttrPairs;
Adam Lesinski282e1812014-01-23 18:17:42 -08003268 } else {
3269 continue;
3270 }
3271
3272 const KeyedVector<String8,sp<AaptGroup> > groups = d->getFiles();
3273 const size_t N = groups.size();
3274 for (size_t i=0; i<N; i++) {
3275 const sp<AaptGroup>& group = groups.valueAt(i);
3276 const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files = group->getFiles();
3277 const size_t M = files.size();
3278 for (size_t j=0; j<M; j++) {
Adam Lesinski9cf4b4a2014-04-25 11:36:02 -07003279 err = writeProguardForXml(keep, files.valueAt(j), startTags, tagAttrPairs);
Adam Lesinski282e1812014-01-23 18:17:42 -08003280 if (err < 0) {
3281 return err;
3282 }
3283 }
3284 }
3285 }
3286 // Handle the overlays
3287 sp<AaptAssets> overlay = assets->getOverlay();
3288 if (overlay.get()) {
3289 return writeProguardForLayouts(keep, overlay);
3290 }
3291
3292 return NO_ERROR;
3293}
3294
3295status_t
Rohit Agrawal682583c2016-04-21 16:29:58 -07003296writeProguardSpec(const char* filename, const ProguardKeepSet& keep, status_t err)
Adam Lesinski282e1812014-01-23 18:17:42 -08003297{
Rohit Agrawal682583c2016-04-21 16:29:58 -07003298 FILE* fp = fopen(filename, "w+");
Adam Lesinski282e1812014-01-23 18:17:42 -08003299 if (fp == NULL) {
3300 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
Rohit Agrawal682583c2016-04-21 16:29:58 -07003301 filename, strerror(errno));
Adam Lesinski282e1812014-01-23 18:17:42 -08003302 return UNKNOWN_ERROR;
3303 }
3304
3305 const KeyedVector<String8, SortedVector<String8> >& rules = keep.rules;
3306 const size_t N = rules.size();
3307 for (size_t i=0; i<N; i++) {
3308 const SortedVector<String8>& locations = rules.valueAt(i);
3309 const size_t M = locations.size();
3310 for (size_t j=0; j<M; j++) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003311 fprintf(fp, "# %s\n", locations.itemAt(j).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003312 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003313 fprintf(fp, "%s\n\n", rules.keyAt(i).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003314 }
3315 fclose(fp);
3316
3317 return err;
3318}
3319
Rohit Agrawal682583c2016-04-21 16:29:58 -07003320status_t
3321writeProguardFile(Bundle* bundle, const sp<AaptAssets>& assets)
3322{
3323 status_t err = -1;
3324
3325 if (!bundle->getProguardFile()) {
3326 return NO_ERROR;
3327 }
3328
3329 ProguardKeepSet keep;
3330
3331 err = writeProguardForAndroidManifest(&keep, assets, false);
3332 if (err < 0) {
3333 return err;
3334 }
3335
3336 err = writeProguardForLayouts(&keep, assets);
3337 if (err < 0) {
3338 return err;
3339 }
3340
3341 return writeProguardSpec(bundle->getProguardFile(), keep, err);
3342}
3343
3344status_t
3345writeMainDexProguardFile(Bundle* bundle, const sp<AaptAssets>& assets)
3346{
3347 status_t err = -1;
3348
3349 if (!bundle->getMainDexProguardFile()) {
3350 return NO_ERROR;
3351 }
3352
3353 ProguardKeepSet keep;
3354
3355 err = writeProguardForAndroidManifest(&keep, assets, true);
3356 if (err < 0) {
3357 return err;
3358 }
3359
3360 return writeProguardSpec(bundle->getMainDexProguardFile(), keep, err);
3361}
3362
Adam Lesinski282e1812014-01-23 18:17:42 -08003363// Loops through the string paths and writes them to the file pointer
3364// Each file path is written on its own line with a terminating backslash.
3365status_t writePathsToFile(const sp<FilePathStore>& files, FILE* fp)
3366{
3367 status_t deps = -1;
3368 for (size_t file_i = 0; file_i < files->size(); ++file_i) {
3369 // Add the full file path to the dependency file
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003370 fprintf(fp, "%s \\\n", files->itemAt(file_i).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003371 deps++;
3372 }
3373 return deps;
3374}
3375
3376status_t
Andreas Gampe2412f842014-09-30 20:55:57 -07003377writeDependencyPreReqs(Bundle* /* bundle */, const sp<AaptAssets>& assets, FILE* fp, bool includeRaw)
Adam Lesinski282e1812014-01-23 18:17:42 -08003378{
3379 status_t deps = -1;
3380 deps += writePathsToFile(assets->getFullResPaths(), fp);
3381 if (includeRaw) {
3382 deps += writePathsToFile(assets->getFullAssetPaths(), fp);
3383 }
3384 return deps;
3385}