blob: 713f8a18620c642949b4e3c78ad6d02f2c50ba0e [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//
6
7#include "ResourceTable.h"
8
Adam Lesinskide7de472014-11-03 12:03:08 -08009#include "AaptUtil.h"
Adam Lesinski282e1812014-01-23 18:17:42 -080010#include "XMLNode.h"
11#include "ResourceFilter.h"
12#include "ResourceIdCache.h"
Adam Lesinskidcdfe9f2014-11-06 12:54:36 -080013#include "SdkConstants.h"
Elliott Hughes338698e2021-07-13 17:15:19 -070014#include "Utils.h"
Adam Lesinski282e1812014-01-23 18:17:42 -080015
Adam Lesinski9b624c12014-11-19 17:49:26 -080016#include <algorithm>
Tomasz Wasilczyk804e8192023-08-23 02:22:53 +000017#include <androidfw/PathUtils.h>
Adam Lesinski282e1812014-01-23 18:17:42 -080018#include <androidfw/ResourceTypes.h>
19#include <utils/ByteOrder.h>
Adam Lesinski82a2dd82014-09-17 18:34:15 -070020#include <utils/TypeHelpers.h>
Adam Lesinski282e1812014-01-23 18:17:42 -080021#include <stdarg.h>
22
Andreas Gampe2412f842014-09-30 20:55:57 -070023// STATUST: mingw does seem to redefine UNKNOWN_ERROR from our enum value, so a cast is necessary.
Elliott Hughesb12f2412015-04-03 12:56:45 -070024#if !defined(_WIN32)
Andreas Gampe2412f842014-09-30 20:55:57 -070025# define STATUST(x) x
26#else
Andreas Gampe2412f842014-09-30 20:55:57 -070027# define STATUST(x) (status_t)x
28#endif
29
30// Set to true for noisy debug output.
31static const bool kIsDebug = false;
32
33#if PRINT_STRING_METRICS
34static const bool kPrintStringMetrics = true;
35#else
36static const bool kPrintStringMetrics = false;
37#endif
Adam Lesinski282e1812014-01-23 18:17:42 -080038
Adam Lesinski9b624c12014-11-19 17:49:26 -080039static const char* kAttrPrivateType = "^attr-private";
40
Adam Lesinskie572c012014-09-19 15:10:04 -070041status_t compileXmlFile(const Bundle* bundle,
42 const sp<AaptAssets>& assets,
43 const String16& resourceName,
Adam Lesinski282e1812014-01-23 18:17:42 -080044 const sp<AaptFile>& target,
45 ResourceTable* table,
46 int options)
47{
48 sp<XMLNode> root = XMLNode::parse(target);
49 if (root == NULL) {
50 return UNKNOWN_ERROR;
51 }
Anton Krumina2ef5c02014-03-12 14:46:44 -070052
Adam Lesinskie572c012014-09-19 15:10:04 -070053 return compileXmlFile(bundle, assets, resourceName, root, target, table, options);
Adam Lesinski282e1812014-01-23 18:17:42 -080054}
55
Adam Lesinskie572c012014-09-19 15:10:04 -070056status_t compileXmlFile(const Bundle* bundle,
57 const sp<AaptAssets>& assets,
58 const String16& resourceName,
Adam Lesinski282e1812014-01-23 18:17:42 -080059 const sp<AaptFile>& target,
60 const sp<AaptFile>& outTarget,
61 ResourceTable* table,
62 int options)
63{
64 sp<XMLNode> root = XMLNode::parse(target);
65 if (root == NULL) {
66 return UNKNOWN_ERROR;
67 }
68
Adam Lesinskie572c012014-09-19 15:10:04 -070069 return compileXmlFile(bundle, assets, resourceName, root, outTarget, table, options);
Adam Lesinski282e1812014-01-23 18:17:42 -080070}
71
Adam Lesinskie572c012014-09-19 15:10:04 -070072status_t compileXmlFile(const Bundle* bundle,
73 const sp<AaptAssets>& assets,
74 const String16& resourceName,
Adam Lesinski282e1812014-01-23 18:17:42 -080075 const sp<XMLNode>& root,
76 const sp<AaptFile>& target,
77 ResourceTable* table,
78 int options)
79{
Adam Lesinskicf1f1d92017-03-16 16:54:23 -070080 if (table->versionForCompat(bundle, resourceName, target, root)) {
81 // The file was versioned, so stop processing here.
82 // The resource entry has already been removed and the new one added.
83 // Remove the assets entry.
84 sp<AaptDir> resDir = assets->getDirs().valueFor(String8("res"));
85 sp<AaptDir> dir = resDir->getDirs().valueFor(target->getGroupEntry().toDirName(
86 target->getResourceType()));
Tomasz Wasilczyk804e8192023-08-23 02:22:53 +000087 dir->removeFile(getPathLeaf(target->getPath()));
Adam Lesinskicf1f1d92017-03-16 16:54:23 -070088 return NO_ERROR;
89 }
90
Adam Lesinski282e1812014-01-23 18:17:42 -080091 if ((options&XML_COMPILE_STRIP_WHITESPACE) != 0) {
92 root->removeWhitespace(true, NULL);
93 } else if ((options&XML_COMPILE_COMPACT_WHITESPACE) != 0) {
94 root->removeWhitespace(false, NULL);
95 }
96
97 if ((options&XML_COMPILE_UTF8) != 0) {
98 root->setUTF8(true);
99 }
100
Adam Lesinski07dfd2d2015-10-28 15:44:27 -0700101 if (table->processBundleFormat(bundle, resourceName, target, root) != NO_ERROR) {
102 return UNKNOWN_ERROR;
103 }
Adam Lesinski5b9847c2015-11-30 21:07:44 +0000104
Adam Lesinski07dfd2d2015-10-28 15:44:27 -0700105 bool hasErrors = false;
Adam Lesinski282e1812014-01-23 18:17:42 -0800106 if ((options&XML_COMPILE_ASSIGN_ATTRIBUTE_IDS) != 0) {
107 status_t err = root->assignResourceIds(assets, table);
108 if (err != NO_ERROR) {
109 hasErrors = true;
110 }
111 }
112
Adam Lesinski07dfd2d2015-10-28 15:44:27 -0700113 if ((options&XML_COMPILE_PARSE_VALUES) != 0) {
114 status_t err = root->parseValues(assets, table);
115 if (err != NO_ERROR) {
116 hasErrors = true;
117 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800118 }
119
120 if (hasErrors) {
121 return UNKNOWN_ERROR;
122 }
Adam Lesinskie572c012014-09-19 15:10:04 -0700123
124 if (table->modifyForCompat(bundle, resourceName, target, root) != NO_ERROR) {
125 return UNKNOWN_ERROR;
126 }
Andreas Gampe87332a72014-10-01 22:03:58 -0700127
Andreas Gampe2412f842014-09-30 20:55:57 -0700128 if (kIsDebug) {
129 printf("Input XML Resource:\n");
130 root->print();
131 }
Adam Lesinski07dfd2d2015-10-28 15:44:27 -0700132 status_t err = root->flatten(target,
Adam Lesinski282e1812014-01-23 18:17:42 -0800133 (options&XML_COMPILE_STRIP_COMMENTS) != 0,
134 (options&XML_COMPILE_STRIP_RAW_VALUES) != 0);
135 if (err != NO_ERROR) {
136 return err;
137 }
138
Andreas Gampe2412f842014-09-30 20:55:57 -0700139 if (kIsDebug) {
140 printf("Output XML Resource:\n");
141 ResXMLTree tree;
Adam Lesinski282e1812014-01-23 18:17:42 -0800142 tree.setTo(target->getData(), target->getSize());
Andreas Gampe2412f842014-09-30 20:55:57 -0700143 printXMLBlock(&tree);
144 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800145
146 target->setCompressionMethod(ZipEntry::kCompressDeflated);
147
148 return err;
149}
150
Adam Lesinski282e1812014-01-23 18:17:42 -0800151struct flag_entry
152{
153 const char16_t* name;
154 size_t nameLen;
155 uint32_t value;
156 const char* description;
157};
158
159static const char16_t referenceArray[] =
160 { 'r', 'e', 'f', 'e', 'r', 'e', 'n', 'c', 'e' };
161static const char16_t stringArray[] =
162 { 's', 't', 'r', 'i', 'n', 'g' };
163static const char16_t integerArray[] =
164 { 'i', 'n', 't', 'e', 'g', 'e', 'r' };
165static const char16_t booleanArray[] =
166 { 'b', 'o', 'o', 'l', 'e', 'a', 'n' };
167static const char16_t colorArray[] =
168 { 'c', 'o', 'l', 'o', 'r' };
169static const char16_t floatArray[] =
170 { 'f', 'l', 'o', 'a', 't' };
171static const char16_t dimensionArray[] =
172 { 'd', 'i', 'm', 'e', 'n', 's', 'i', 'o', 'n' };
173static const char16_t fractionArray[] =
174 { 'f', 'r', 'a', 'c', 't', 'i', 'o', 'n' };
175static const char16_t enumArray[] =
176 { 'e', 'n', 'u', 'm' };
177static const char16_t flagsArray[] =
178 { 'f', 'l', 'a', 'g', 's' };
179
180static const flag_entry gFormatFlags[] = {
181 { referenceArray, sizeof(referenceArray)/2, ResTable_map::TYPE_REFERENCE,
182 "a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\n"
183 "or to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\"."},
184 { stringArray, sizeof(stringArray)/2, ResTable_map::TYPE_STRING,
185 "a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character." },
186 { integerArray, sizeof(integerArray)/2, ResTable_map::TYPE_INTEGER,
187 "an integer value, such as \"<code>100</code>\"." },
188 { booleanArray, sizeof(booleanArray)/2, ResTable_map::TYPE_BOOLEAN,
189 "a boolean value, either \"<code>true</code>\" or \"<code>false</code>\"." },
190 { colorArray, sizeof(colorArray)/2, ResTable_map::TYPE_COLOR,
191 "a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n"
192 "\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\"." },
193 { floatArray, sizeof(floatArray)/2, ResTable_map::TYPE_FLOAT,
194 "a floating point value, such as \"<code>1.2</code>\"."},
195 { dimensionArray, sizeof(dimensionArray)/2, ResTable_map::TYPE_DIMENSION,
196 "a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\n"
197 "Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\n"
198 "in (inches), mm (millimeters)." },
199 { fractionArray, sizeof(fractionArray)/2, ResTable_map::TYPE_FRACTION,
200 "a fractional value, which is a floating point number appended with either % or %p, such as \"<code>14.5%</code>\".\n"
201 "The % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to\n"
202 "some parent container." },
203 { enumArray, sizeof(enumArray)/2, ResTable_map::TYPE_ENUM, NULL },
204 { flagsArray, sizeof(flagsArray)/2, ResTable_map::TYPE_FLAGS, NULL },
205 { NULL, 0, 0, NULL }
206};
207
208static const char16_t suggestedArray[] = { 's', 'u', 'g', 'g', 'e', 's', 't', 'e', 'd' };
209
210static const flag_entry l10nRequiredFlags[] = {
211 { suggestedArray, sizeof(suggestedArray)/2, ResTable_map::L10N_SUGGESTED, NULL },
212 { NULL, 0, 0, NULL }
213};
214
215static const char16_t nulStr[] = { 0 };
216
217static uint32_t parse_flags(const char16_t* str, size_t len,
218 const flag_entry* flags, bool* outError = NULL)
219{
220 while (len > 0 && isspace(*str)) {
221 str++;
222 len--;
223 }
224 while (len > 0 && isspace(str[len-1])) {
225 len--;
226 }
227
228 const char16_t* const end = str + len;
229 uint32_t value = 0;
230
231 while (str < end) {
232 const char16_t* div = str;
233 while (div < end && *div != '|') {
234 div++;
235 }
236
237 const flag_entry* cur = flags;
238 while (cur->name) {
239 if (strzcmp16(cur->name, cur->nameLen, str, div-str) == 0) {
240 value |= cur->value;
241 break;
242 }
243 cur++;
244 }
245
246 if (!cur->name) {
247 if (outError) *outError = true;
248 return 0;
249 }
250
251 str = div < end ? div+1 : div;
252 }
253
254 if (outError) *outError = false;
255 return value;
256}
257
258static String16 mayOrMust(int type, int flags)
259{
260 if ((type&(~flags)) == 0) {
261 return String16("<p>Must");
262 }
263
264 return String16("<p>May");
265}
266
267static void appendTypeInfo(ResourceTable* outTable, const String16& pkg,
268 const String16& typeName, const String16& ident, int type,
269 const flag_entry* flags)
270{
271 bool hadType = false;
272 while (flags->name) {
273 if ((type&flags->value) != 0 && flags->description != NULL) {
274 String16 fullMsg(mayOrMust(type, flags->value));
275 fullMsg.append(String16(" be "));
276 fullMsg.append(String16(flags->description));
277 outTable->appendTypeComment(pkg, typeName, ident, fullMsg);
278 hadType = true;
279 }
280 flags++;
281 }
282 if (hadType && (type&ResTable_map::TYPE_REFERENCE) == 0) {
283 outTable->appendTypeComment(pkg, typeName, ident,
284 String16("<p>This may also be a reference to a resource (in the form\n"
285 "\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\n"
286 "theme attribute (in the form\n"
287 "\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\n"
288 "containing a value of this type."));
289 }
290}
291
292struct PendingAttribute
293{
294 const String16 myPackage;
295 const SourcePos sourcePos;
296 const bool appendComment;
297 int32_t type;
298 String16 ident;
299 String16 comment;
300 bool hasErrors;
301 bool added;
302
303 PendingAttribute(String16 _package, const sp<AaptFile>& in,
304 ResXMLTree& block, bool _appendComment)
305 : myPackage(_package)
306 , sourcePos(in->getPrintableSource(), block.getLineNumber())
307 , appendComment(_appendComment)
308 , type(ResTable_map::TYPE_ANY)
309 , hasErrors(false)
310 , added(false)
311 {
312 }
313
314 status_t createIfNeeded(ResourceTable* outTable)
315 {
316 if (added || hasErrors) {
317 return NO_ERROR;
318 }
319 added = true;
320
Adam Lesinskiafc79be2016-02-22 09:16:33 -0800321 if (!outTable->makeAttribute(myPackage, ident, sourcePos, type, comment, appendComment)) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800322 hasErrors = true;
323 return UNKNOWN_ERROR;
324 }
Adam Lesinskiafc79be2016-02-22 09:16:33 -0800325 return NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -0800326 }
327};
328
329static status_t compileAttribute(const sp<AaptFile>& in,
330 ResXMLTree& block,
331 const String16& myPackage,
332 ResourceTable* outTable,
333 String16* outIdent = NULL,
334 bool inStyleable = false)
335{
336 PendingAttribute attr(myPackage, in, block, inStyleable);
337
338 const String16 attr16("attr");
339 const String16 id16("id");
340
341 // Attribute type constants.
342 const String16 enum16("enum");
343 const String16 flag16("flag");
344
345 ResXMLTree::event_code_t code;
346 size_t len;
347 status_t err;
348
349 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
350 if (identIdx >= 0) {
351 attr.ident = String16(block.getAttributeStringValue(identIdx, &len));
352 if (outIdent) {
353 *outIdent = attr.ident;
354 }
355 } else {
356 attr.sourcePos.error("A 'name' attribute is required for <attr>\n");
357 attr.hasErrors = true;
358 }
359
360 attr.comment = String16(
361 block.getComment(&len) ? block.getComment(&len) : nulStr);
362
363 ssize_t typeIdx = block.indexOfAttribute(NULL, "format");
364 if (typeIdx >= 0) {
365 String16 typeStr = String16(block.getAttributeStringValue(typeIdx, &len));
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000366 attr.type = parse_flags(typeStr.c_str(), typeStr.size(), gFormatFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -0800367 if (attr.type == 0) {
368 attr.sourcePos.error("Tag <attr> 'format' attribute value \"%s\" not valid\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000369 String8(typeStr).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800370 attr.hasErrors = true;
371 }
372 attr.createIfNeeded(outTable);
373 } else if (!inStyleable) {
374 // Attribute definitions outside of styleables always define the
375 // attribute as a generic value.
376 attr.createIfNeeded(outTable);
377 }
378
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000379 //printf("Attribute %s: type=0x%08x\n", String8(attr.ident).c_str(), attr.type);
Adam Lesinski282e1812014-01-23 18:17:42 -0800380
381 ssize_t minIdx = block.indexOfAttribute(NULL, "min");
382 if (minIdx >= 0) {
383 String16 val = String16(block.getAttributeStringValue(minIdx, &len));
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000384 if (!ResTable::stringToInt(val.c_str(), val.size(), NULL)) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800385 attr.sourcePos.error("Tag <attr> 'min' attribute must be a number, not \"%s\"\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000386 String8(val).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800387 attr.hasErrors = true;
388 }
389 attr.createIfNeeded(outTable);
390 if (!attr.hasErrors) {
391 err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
392 String16(""), String16("^min"), String16(val), NULL, NULL);
393 if (err != NO_ERROR) {
394 attr.hasErrors = true;
395 }
396 }
397 }
398
399 ssize_t maxIdx = block.indexOfAttribute(NULL, "max");
400 if (maxIdx >= 0) {
401 String16 val = String16(block.getAttributeStringValue(maxIdx, &len));
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000402 if (!ResTable::stringToInt(val.c_str(), val.size(), NULL)) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800403 attr.sourcePos.error("Tag <attr> 'max' attribute must be a number, not \"%s\"\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000404 String8(val).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800405 attr.hasErrors = true;
406 }
407 attr.createIfNeeded(outTable);
408 if (!attr.hasErrors) {
409 err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
410 String16(""), String16("^max"), String16(val), NULL, NULL);
411 attr.hasErrors = true;
412 }
413 }
414
415 if ((minIdx >= 0 || maxIdx >= 0) && (attr.type&ResTable_map::TYPE_INTEGER) == 0) {
416 attr.sourcePos.error("Tag <attr> must have format=integer attribute if using max or min\n");
417 attr.hasErrors = true;
418 }
419
420 ssize_t l10nIdx = block.indexOfAttribute(NULL, "localization");
421 if (l10nIdx >= 0) {
Dan Albertf348c152014-09-08 18:28:00 -0700422 const char16_t* str = block.getAttributeStringValue(l10nIdx, &len);
Adam Lesinski282e1812014-01-23 18:17:42 -0800423 bool error;
424 uint32_t l10n_required = parse_flags(str, len, l10nRequiredFlags, &error);
425 if (error) {
426 attr.sourcePos.error("Tag <attr> 'localization' attribute value \"%s\" not valid\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000427 String8(str).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800428 attr.hasErrors = true;
429 }
430 attr.createIfNeeded(outTable);
431 if (!attr.hasErrors) {
432 char buf[11];
433 sprintf(buf, "%d", l10n_required);
434 err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
435 String16(""), String16("^l10n"), String16(buf), NULL, NULL);
436 if (err != NO_ERROR) {
437 attr.hasErrors = true;
438 }
439 }
440 }
441
442 String16 enumOrFlagsComment;
443
444 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
445 if (code == ResXMLTree::START_TAG) {
446 uint32_t localType = 0;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000447 if (strcmp16(block.getElementName(&len), enum16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800448 localType = ResTable_map::TYPE_ENUM;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000449 } else if (strcmp16(block.getElementName(&len), flag16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800450 localType = ResTable_map::TYPE_FLAGS;
451 } else {
452 SourcePos(in->getPrintableSource(), block.getLineNumber())
453 .error("Tag <%s> can not appear inside <attr>, only <enum> or <flag>\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000454 String8(block.getElementName(&len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800455 return UNKNOWN_ERROR;
456 }
457
458 attr.createIfNeeded(outTable);
459
460 if (attr.type == ResTable_map::TYPE_ANY) {
461 // No type was explicitly stated, so supplying enum tags
462 // implicitly creates an enum or flag.
463 attr.type = 0;
464 }
465
466 if ((attr.type&(ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS)) == 0) {
467 // Wasn't originally specified as an enum, so update its type.
468 attr.type |= localType;
469 if (!attr.hasErrors) {
470 char numberStr[16];
471 sprintf(numberStr, "%d", attr.type);
472 err = outTable->addBag(SourcePos(in->getPrintableSource(), block.getLineNumber()),
473 myPackage, attr16, attr.ident, String16(""),
474 String16("^type"), String16(numberStr), NULL, NULL, true);
475 if (err != NO_ERROR) {
476 attr.hasErrors = true;
477 }
478 }
479 } else if ((uint32_t)(attr.type&(ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS)) != localType) {
480 if (localType == ResTable_map::TYPE_ENUM) {
481 SourcePos(in->getPrintableSource(), block.getLineNumber())
482 .error("<enum> attribute can not be used inside a flags format\n");
483 attr.hasErrors = true;
484 } else {
485 SourcePos(in->getPrintableSource(), block.getLineNumber())
486 .error("<flag> attribute can not be used inside a enum format\n");
487 attr.hasErrors = true;
488 }
489 }
490
491 String16 itemIdent;
492 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "name");
493 if (itemIdentIdx >= 0) {
494 itemIdent = String16(block.getAttributeStringValue(itemIdentIdx, &len));
495 } else {
496 SourcePos(in->getPrintableSource(), block.getLineNumber())
497 .error("A 'name' attribute is required for <enum> or <flag>\n");
498 attr.hasErrors = true;
499 }
500
501 String16 value;
502 ssize_t valueIdx = block.indexOfAttribute(NULL, "value");
503 if (valueIdx >= 0) {
504 value = String16(block.getAttributeStringValue(valueIdx, &len));
505 } else {
506 SourcePos(in->getPrintableSource(), block.getLineNumber())
507 .error("A 'value' attribute is required for <enum> or <flag>\n");
508 attr.hasErrors = true;
509 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000510 if (!attr.hasErrors && !ResTable::stringToInt(value.c_str(), value.size(), NULL)) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800511 SourcePos(in->getPrintableSource(), block.getLineNumber())
512 .error("Tag <enum> or <flag> 'value' attribute must be a number,"
513 " not \"%s\"\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000514 String8(value).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800515 attr.hasErrors = true;
516 }
517
Adam Lesinski282e1812014-01-23 18:17:42 -0800518 if (!attr.hasErrors) {
519 if (enumOrFlagsComment.size() == 0) {
520 enumOrFlagsComment.append(mayOrMust(attr.type,
521 ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS));
522 enumOrFlagsComment.append((attr.type&ResTable_map::TYPE_ENUM)
523 ? String16(" be one of the following constant values.")
524 : String16(" be one or more (separated by '|') of the following constant values."));
525 enumOrFlagsComment.append(String16("</p>\n<table>\n"
526 "<colgroup align=\"left\" />\n"
527 "<colgroup align=\"left\" />\n"
528 "<colgroup align=\"left\" />\n"
529 "<tr><th>Constant</th><th>Value</th><th>Description</th></tr>"));
530 }
531
532 enumOrFlagsComment.append(String16("\n<tr><td><code>"));
533 enumOrFlagsComment.append(itemIdent);
534 enumOrFlagsComment.append(String16("</code></td><td>"));
535 enumOrFlagsComment.append(value);
536 enumOrFlagsComment.append(String16("</td><td>"));
537 if (block.getComment(&len)) {
538 enumOrFlagsComment.append(String16(block.getComment(&len)));
539 }
540 enumOrFlagsComment.append(String16("</td></tr>"));
541
542 err = outTable->addBag(SourcePos(in->getPrintableSource(), block.getLineNumber()),
543 myPackage,
544 attr16, attr.ident, String16(""),
545 itemIdent, value, NULL, NULL, false, true);
546 if (err != NO_ERROR) {
547 attr.hasErrors = true;
548 }
549 }
550 } else if (code == ResXMLTree::END_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000551 if (strcmp16(block.getElementName(&len), attr16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800552 break;
553 }
554 if ((attr.type&ResTable_map::TYPE_ENUM) != 0) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000555 if (strcmp16(block.getElementName(&len), enum16.c_str()) != 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800556 SourcePos(in->getPrintableSource(), block.getLineNumber())
557 .error("Found tag </%s> where </enum> is expected\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000558 String8(block.getElementName(&len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800559 return UNKNOWN_ERROR;
560 }
561 } else {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000562 if (strcmp16(block.getElementName(&len), flag16.c_str()) != 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800563 SourcePos(in->getPrintableSource(), block.getLineNumber())
564 .error("Found tag </%s> where </flag> is expected\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000565 String8(block.getElementName(&len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800566 return UNKNOWN_ERROR;
567 }
568 }
569 }
570 }
571
572 if (!attr.hasErrors && attr.added) {
573 appendTypeInfo(outTable, myPackage, attr16, attr.ident, attr.type, gFormatFlags);
574 }
575
576 if (!attr.hasErrors && enumOrFlagsComment.size() > 0) {
577 enumOrFlagsComment.append(String16("\n</table>"));
578 outTable->appendTypeComment(myPackage, attr16, attr.ident, enumOrFlagsComment);
579 }
580
581
582 return NO_ERROR;
583}
584
585bool localeIsDefined(const ResTable_config& config)
586{
587 return config.locale == 0;
588}
589
590status_t parseAndAddBag(Bundle* bundle,
591 const sp<AaptFile>& in,
592 ResXMLTree* block,
593 const ResTable_config& config,
594 const String16& myPackage,
595 const String16& curType,
596 const String16& ident,
597 const String16& parentIdent,
598 const String16& itemIdent,
599 int32_t curFormat,
600 bool isFormatted,
Andreas Gampe2412f842014-09-30 20:55:57 -0700601 const String16& /* product */,
Anton Krumina2ef5c02014-03-12 14:46:44 -0700602 PseudolocalizationMethod pseudolocalize,
Adam Lesinski282e1812014-01-23 18:17:42 -0800603 const bool overwrite,
604 ResourceTable* outTable)
605{
606 status_t err;
607 const String16 item16("item");
Anton Krumina2ef5c02014-03-12 14:46:44 -0700608
Adam Lesinski282e1812014-01-23 18:17:42 -0800609 String16 str;
610 Vector<StringPool::entry_style_span> spans;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000611 err = parseStyledString(bundle, in->getPrintableSource().c_str(),
Adam Lesinski282e1812014-01-23 18:17:42 -0800612 block, item16, &str, &spans, isFormatted,
613 pseudolocalize);
614 if (err != NO_ERROR) {
615 return err;
616 }
Andreas Gampe2412f842014-09-30 20:55:57 -0700617
618 if (kIsDebug) {
619 printf("Adding resource bag entry l=%c%c c=%c%c orien=%d d=%d "
620 " pid=%s, bag=%s, id=%s: %s\n",
621 config.language[0], config.language[1],
622 config.country[0], config.country[1],
623 config.orientation, config.density,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000624 String8(parentIdent).c_str(),
625 String8(ident).c_str(),
626 String8(itemIdent).c_str(),
627 String8(str).c_str());
Andreas Gampe2412f842014-09-30 20:55:57 -0700628 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800629
630 err = outTable->addBag(SourcePos(in->getPrintableSource(), block->getLineNumber()),
631 myPackage, curType, ident, parentIdent, itemIdent, str,
632 &spans, &config, overwrite, false, curFormat);
633 return err;
634}
635
636/*
637 * Returns true if needle is one of the elements in the comma-separated list
638 * haystack, false otherwise.
639 */
640bool isInProductList(const String16& needle, const String16& haystack) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000641 const char16_t *needle2 = needle.c_str();
642 const char16_t *haystack2 = haystack.c_str();
Adam Lesinski282e1812014-01-23 18:17:42 -0800643 size_t needlesize = needle.size();
644
645 while (*haystack2 != '\0') {
646 if (strncmp16(haystack2, needle2, needlesize) == 0) {
647 if (haystack2[needlesize] == '\0' || haystack2[needlesize] == ',') {
648 return true;
649 }
650 }
651
652 while (*haystack2 != '\0' && *haystack2 != ',') {
653 haystack2++;
654 }
655 if (*haystack2 == ',') {
656 haystack2++;
657 }
658 }
659
660 return false;
661}
662
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700663/*
664 * A simple container that holds a resource type and name. It is ordered first by type then
665 * by name.
666 */
667struct type_ident_pair_t {
668 String16 type;
669 String16 ident;
670
671 type_ident_pair_t() { };
672 type_ident_pair_t(const String16& t, const String16& i) : type(t), ident(i) { }
673 type_ident_pair_t(const type_ident_pair_t& o) : type(o.type), ident(o.ident) { }
674 inline bool operator < (const type_ident_pair_t& o) const {
675 int cmp = compare_type(type, o.type);
676 if (cmp < 0) {
677 return true;
678 } else if (cmp > 0) {
679 return false;
680 } else {
681 return strictly_order_type(ident, o.ident);
682 }
683 }
684};
685
686
Adam Lesinski282e1812014-01-23 18:17:42 -0800687status_t parseAndAddEntry(Bundle* bundle,
688 const sp<AaptFile>& in,
689 ResXMLTree* block,
690 const ResTable_config& config,
691 const String16& myPackage,
692 const String16& curType,
693 const String16& ident,
694 const String16& curTag,
695 bool curIsStyled,
696 int32_t curFormat,
697 bool isFormatted,
698 const String16& product,
Anton Krumina2ef5c02014-03-12 14:46:44 -0700699 PseudolocalizationMethod pseudolocalize,
Adam Lesinski282e1812014-01-23 18:17:42 -0800700 const bool overwrite,
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700701 KeyedVector<type_ident_pair_t, bool>* skippedResourceNames,
Adam Lesinski282e1812014-01-23 18:17:42 -0800702 ResourceTable* outTable)
703{
704 status_t err;
705
706 String16 str;
707 Vector<StringPool::entry_style_span> spans;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000708 err = parseStyledString(bundle, in->getPrintableSource().c_str(), block,
Adam Lesinski282e1812014-01-23 18:17:42 -0800709 curTag, &str, curIsStyled ? &spans : NULL,
710 isFormatted, pseudolocalize);
711
712 if (err < NO_ERROR) {
713 return err;
714 }
715
716 /*
717 * If a product type was specified on the command line
718 * and also in the string, and the two are not the same,
719 * return without adding the string.
720 */
721
722 const char *bundleProduct = bundle->getProduct();
723 if (bundleProduct == NULL) {
724 bundleProduct = "";
725 }
726
727 if (product.size() != 0) {
728 /*
729 * If the command-line-specified product is empty, only "default"
730 * matches. Other variants are skipped. This is so generation
731 * of the R.java file when the product is not known is predictable.
732 */
733
734 if (bundleProduct[0] == '\0') {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000735 if (strcmp16(String16("default").c_str(), product.c_str()) != 0) {
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700736 /*
737 * This string has a product other than 'default'. Do not add it,
738 * but record it so that if we do not see the same string with
739 * product 'default' or no product, then report an error.
740 */
741 skippedResourceNames->replaceValueFor(
742 type_ident_pair_t(curType, ident), true);
Adam Lesinski282e1812014-01-23 18:17:42 -0800743 return NO_ERROR;
744 }
745 } else {
746 /*
747 * The command-line product is not empty.
748 * If the product for this string is on the command-line list,
749 * it matches. "default" also matches, but only if nothing
750 * else has matched already.
751 */
752
753 if (isInProductList(product, String16(bundleProduct))) {
754 ;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000755 } else if (strcmp16(String16("default").c_str(), product.c_str()) == 0 &&
Adam Lesinski282e1812014-01-23 18:17:42 -0800756 !outTable->hasBagOrEntry(myPackage, curType, ident, config)) {
757 ;
758 } else {
759 return NO_ERROR;
760 }
761 }
762 }
763
Andreas Gampe2412f842014-09-30 20:55:57 -0700764 if (kIsDebug) {
765 printf("Adding resource entry l=%c%c c=%c%c orien=%d d=%d id=%s: %s\n",
766 config.language[0], config.language[1],
767 config.country[0], config.country[1],
768 config.orientation, config.density,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000769 String8(ident).c_str(), String8(str).c_str());
Andreas Gampe2412f842014-09-30 20:55:57 -0700770 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800771
772 err = outTable->addEntry(SourcePos(in->getPrintableSource(), block->getLineNumber()),
773 myPackage, curType, ident, str, &spans, &config,
774 false, curFormat, overwrite);
775
776 return err;
777}
778
779status_t compileResourceFile(Bundle* bundle,
780 const sp<AaptAssets>& assets,
781 const sp<AaptFile>& in,
782 const ResTable_config& defParams,
783 const bool overwrite,
784 ResourceTable* outTable)
785{
786 ResXMLTree block;
787 status_t err = parseXMLResource(in, &block, false, true);
788 if (err != NO_ERROR) {
789 return err;
790 }
791
792 // Top-level tag.
793 const String16 resources16("resources");
794
795 // Identifier declaration tags.
796 const String16 declare_styleable16("declare-styleable");
797 const String16 attr16("attr");
798
799 // Data creation organizational tags.
800 const String16 string16("string");
801 const String16 drawable16("drawable");
802 const String16 color16("color");
803 const String16 bool16("bool");
804 const String16 integer16("integer");
805 const String16 dimen16("dimen");
806 const String16 fraction16("fraction");
807 const String16 style16("style");
808 const String16 plurals16("plurals");
809 const String16 array16("array");
810 const String16 string_array16("string-array");
811 const String16 integer_array16("integer-array");
812 const String16 public16("public");
813 const String16 public_padding16("public-padding");
814 const String16 private_symbols16("private-symbols");
815 const String16 java_symbol16("java-symbol");
816 const String16 add_resource16("add-resource");
817 const String16 skip16("skip");
818 const String16 eat_comment16("eat-comment");
819
820 // Data creation tags.
821 const String16 bag16("bag");
822 const String16 item16("item");
823
824 // Attribute type constants.
825 const String16 enum16("enum");
826
827 // plural values
828 const String16 other16("other");
829 const String16 quantityOther16("^other");
830 const String16 zero16("zero");
831 const String16 quantityZero16("^zero");
832 const String16 one16("one");
833 const String16 quantityOne16("^one");
834 const String16 two16("two");
835 const String16 quantityTwo16("^two");
836 const String16 few16("few");
837 const String16 quantityFew16("^few");
838 const String16 many16("many");
839 const String16 quantityMany16("^many");
840
841 // useful attribute names and special values
842 const String16 name16("name");
843 const String16 translatable16("translatable");
844 const String16 formatted16("formatted");
845 const String16 false16("false");
846
847 const String16 myPackage(assets->getPackage());
848
849 bool hasErrors = false;
850
851 bool fileIsTranslatable = true;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000852 if (strstr(in->getPrintableSource().c_str(), "donottranslate") != NULL) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800853 fileIsTranslatable = false;
854 }
855
856 DefaultKeyedVector<String16, uint32_t> nextPublicId(0);
857
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700858 // Stores the resource names that were skipped. Typically this happens when
859 // AAPT is invoked without a product specified and a resource has no
860 // 'default' product attribute.
861 KeyedVector<type_ident_pair_t, bool> skippedResourceNames;
862
Adam Lesinski282e1812014-01-23 18:17:42 -0800863 ResXMLTree::event_code_t code;
864 do {
865 code = block.next();
866 } while (code == ResXMLTree::START_NAMESPACE);
867
868 size_t len;
869 if (code != ResXMLTree::START_TAG) {
870 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
871 "No start tag found\n");
872 return UNKNOWN_ERROR;
873 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000874 if (strcmp16(block.getElementName(&len), resources16.c_str()) != 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800875 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000876 "Invalid start tag %s\n", String8(block.getElementName(&len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800877 return UNKNOWN_ERROR;
878 }
879
880 ResTable_config curParams(defParams);
881
882 ResTable_config pseudoParams(curParams);
Anton Krumina2ef5c02014-03-12 14:46:44 -0700883 pseudoParams.language[0] = 'e';
884 pseudoParams.language[1] = 'n';
885 pseudoParams.country[0] = 'X';
886 pseudoParams.country[1] = 'A';
887
888 ResTable_config pseudoBidiParams(curParams);
889 pseudoBidiParams.language[0] = 'a';
890 pseudoBidiParams.language[1] = 'r';
891 pseudoBidiParams.country[0] = 'X';
892 pseudoBidiParams.country[1] = 'B';
Adam Lesinski282e1812014-01-23 18:17:42 -0800893
Igor Viarheichyk47843df2014-05-01 17:04:39 -0700894 // We should skip resources for pseudolocales if they were
895 // already added automatically. This is a fix for a transition period when
896 // manually pseudolocalized resources may be expected.
897 // TODO: remove this check after next SDK version release.
898 if ((bundle->getPseudolocalize() & PSEUDO_ACCENTED &&
899 curParams.locale == pseudoParams.locale) ||
900 (bundle->getPseudolocalize() & PSEUDO_BIDI &&
901 curParams.locale == pseudoBidiParams.locale)) {
902 SourcePos(in->getPrintableSource(), 0).warning(
903 "Resource file %s is skipped as pseudolocalization"
904 " was done automatically.",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000905 in->getPrintableSource().c_str());
Igor Viarheichyk47843df2014-05-01 17:04:39 -0700906 return NO_ERROR;
907 }
908
Adam Lesinski282e1812014-01-23 18:17:42 -0800909 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
910 if (code == ResXMLTree::START_TAG) {
911 const String16* curTag = NULL;
912 String16 curType;
Adrian Roos58922482015-06-01 17:59:41 -0700913 String16 curName;
Adam Lesinski282e1812014-01-23 18:17:42 -0800914 int32_t curFormat = ResTable_map::TYPE_ANY;
915 bool curIsBag = false;
916 bool curIsBagReplaceOnOverwrite = false;
917 bool curIsStyled = false;
918 bool curIsPseudolocalizable = false;
919 bool curIsFormatted = fileIsTranslatable;
920 bool localHasErrors = false;
921
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000922 if (strcmp16(block.getElementName(&len), skip16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800923 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
924 && code != ResXMLTree::BAD_DOCUMENT) {
925 if (code == ResXMLTree::END_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000926 if (strcmp16(block.getElementName(&len), skip16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800927 break;
928 }
929 }
930 }
931 continue;
932
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000933 } else if (strcmp16(block.getElementName(&len), eat_comment16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800934 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
935 && code != ResXMLTree::BAD_DOCUMENT) {
936 if (code == ResXMLTree::END_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000937 if (strcmp16(block.getElementName(&len), eat_comment16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800938 break;
939 }
940 }
941 }
942 continue;
943
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000944 } else if (strcmp16(block.getElementName(&len), public16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800945 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
946
947 String16 type;
948 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
949 if (typeIdx < 0) {
950 srcPos.error("A 'type' attribute is required for <public>\n");
951 hasErrors = localHasErrors = true;
952 }
953 type = String16(block.getAttributeStringValue(typeIdx, &len));
954
955 String16 name;
956 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
957 if (nameIdx < 0) {
958 srcPos.error("A 'name' attribute is required for <public>\n");
959 hasErrors = localHasErrors = true;
960 }
961 name = String16(block.getAttributeStringValue(nameIdx, &len));
962
963 uint32_t ident = 0;
964 ssize_t identIdx = block.indexOfAttribute(NULL, "id");
965 if (identIdx >= 0) {
966 const char16_t* identStr = block.getAttributeStringValue(identIdx, &len);
967 Res_value identValue;
968 if (!ResTable::stringToInt(identStr, len, &identValue)) {
969 srcPos.error("Given 'id' attribute is not an integer: %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000970 String8(block.getAttributeStringValue(identIdx, &len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800971 hasErrors = localHasErrors = true;
972 } else {
973 ident = identValue.data;
974 nextPublicId.replaceValueFor(type, ident+1);
975 }
976 } else if (nextPublicId.indexOfKey(type) < 0) {
977 srcPos.error("No 'id' attribute supplied <public>,"
978 " and no previous id defined in this file.\n");
979 hasErrors = localHasErrors = true;
980 } else if (!localHasErrors) {
981 ident = nextPublicId.valueFor(type);
982 nextPublicId.replaceValueFor(type, ident+1);
983 }
984
985 if (!localHasErrors) {
986 err = outTable->addPublic(srcPos, myPackage, type, name, ident);
987 if (err < NO_ERROR) {
988 hasErrors = localHasErrors = true;
989 }
990 }
991 if (!localHasErrors) {
992 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
993 if (symbols != NULL) {
994 symbols = symbols->addNestedSymbol(String8(type), srcPos);
995 }
996 if (symbols != NULL) {
997 symbols->makeSymbolPublic(String8(name), srcPos);
998 String16 comment(
999 block.getComment(&len) ? block.getComment(&len) : nulStr);
1000 symbols->appendComment(String8(name), comment, srcPos);
1001 } else {
1002 srcPos.error("Unable to create symbols!\n");
1003 hasErrors = localHasErrors = true;
1004 }
1005 }
1006
1007 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1008 if (code == ResXMLTree::END_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001009 if (strcmp16(block.getElementName(&len), public16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001010 break;
1011 }
1012 }
1013 }
1014 continue;
1015
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001016 } else if (strcmp16(block.getElementName(&len), public_padding16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001017 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1018
1019 String16 type;
1020 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
1021 if (typeIdx < 0) {
1022 srcPos.error("A 'type' attribute is required for <public-padding>\n");
1023 hasErrors = localHasErrors = true;
1024 }
1025 type = String16(block.getAttributeStringValue(typeIdx, &len));
1026
1027 String16 name;
1028 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1029 if (nameIdx < 0) {
1030 srcPos.error("A 'name' attribute is required for <public-padding>\n");
1031 hasErrors = localHasErrors = true;
1032 }
1033 name = String16(block.getAttributeStringValue(nameIdx, &len));
1034
1035 uint32_t start = 0;
1036 ssize_t startIdx = block.indexOfAttribute(NULL, "start");
1037 if (startIdx >= 0) {
1038 const char16_t* startStr = block.getAttributeStringValue(startIdx, &len);
1039 Res_value startValue;
1040 if (!ResTable::stringToInt(startStr, len, &startValue)) {
1041 srcPos.error("Given 'start' attribute is not an integer: %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001042 String8(block.getAttributeStringValue(startIdx, &len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001043 hasErrors = localHasErrors = true;
1044 } else {
1045 start = startValue.data;
1046 }
1047 } else if (nextPublicId.indexOfKey(type) < 0) {
1048 srcPos.error("No 'start' attribute supplied <public-padding>,"
1049 " and no previous id defined in this file.\n");
1050 hasErrors = localHasErrors = true;
1051 } else if (!localHasErrors) {
1052 start = nextPublicId.valueFor(type);
1053 }
1054
1055 uint32_t end = 0;
1056 ssize_t endIdx = block.indexOfAttribute(NULL, "end");
1057 if (endIdx >= 0) {
1058 const char16_t* endStr = block.getAttributeStringValue(endIdx, &len);
1059 Res_value endValue;
1060 if (!ResTable::stringToInt(endStr, len, &endValue)) {
1061 srcPos.error("Given 'end' attribute is not an integer: %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001062 String8(block.getAttributeStringValue(endIdx, &len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001063 hasErrors = localHasErrors = true;
1064 } else {
1065 end = endValue.data;
1066 }
1067 } else {
1068 srcPos.error("No 'end' attribute supplied <public-padding>\n");
1069 hasErrors = localHasErrors = true;
1070 }
1071
1072 if (end >= start) {
1073 nextPublicId.replaceValueFor(type, end+1);
1074 } else {
1075 srcPos.error("Padding start '%ul' is after end '%ul'\n",
1076 start, end);
1077 hasErrors = localHasErrors = true;
1078 }
1079
1080 String16 comment(
1081 block.getComment(&len) ? block.getComment(&len) : nulStr);
1082 for (uint32_t curIdent=start; curIdent<=end; curIdent++) {
1083 if (localHasErrors) {
1084 break;
1085 }
1086 String16 curName(name);
1087 char buf[64];
1088 sprintf(buf, "%d", (int)(end-curIdent+1));
1089 curName.append(String16(buf));
1090
1091 err = outTable->addEntry(srcPos, myPackage, type, curName,
1092 String16("padding"), NULL, &curParams, false,
1093 ResTable_map::TYPE_STRING, overwrite);
1094 if (err < NO_ERROR) {
1095 hasErrors = localHasErrors = true;
1096 break;
1097 }
1098 err = outTable->addPublic(srcPos, myPackage, type,
1099 curName, curIdent);
1100 if (err < NO_ERROR) {
1101 hasErrors = localHasErrors = true;
1102 break;
1103 }
1104 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1105 if (symbols != NULL) {
1106 symbols = symbols->addNestedSymbol(String8(type), srcPos);
1107 }
1108 if (symbols != NULL) {
1109 symbols->makeSymbolPublic(String8(curName), srcPos);
1110 symbols->appendComment(String8(curName), comment, srcPos);
1111 } else {
1112 srcPos.error("Unable to create symbols!\n");
1113 hasErrors = localHasErrors = true;
1114 }
1115 }
1116
1117 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1118 if (code == ResXMLTree::END_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001119 if (strcmp16(block.getElementName(&len), public_padding16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001120 break;
1121 }
1122 }
1123 }
1124 continue;
1125
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001126 } else if (strcmp16(block.getElementName(&len), private_symbols16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001127 String16 pkg;
1128 ssize_t pkgIdx = block.indexOfAttribute(NULL, "package");
1129 if (pkgIdx < 0) {
1130 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1131 "A 'package' attribute is required for <private-symbols>\n");
1132 hasErrors = localHasErrors = true;
1133 }
1134 pkg = String16(block.getAttributeStringValue(pkgIdx, &len));
1135 if (!localHasErrors) {
Adam Lesinski78713992015-12-07 14:02:15 -08001136 SourcePos(in->getPrintableSource(), block.getLineNumber()).warning(
1137 "<private-symbols> is deprecated. Use the command line flag "
1138 "--private-symbols instead.\n");
1139 if (assets->havePrivateSymbols()) {
1140 SourcePos(in->getPrintableSource(), block.getLineNumber()).warning(
1141 "private symbol package already specified. Ignoring...\n");
1142 } else {
1143 assets->setSymbolsPrivatePackage(String8(pkg));
1144 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001145 }
1146
1147 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1148 if (code == ResXMLTree::END_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001149 if (strcmp16(block.getElementName(&len), private_symbols16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001150 break;
1151 }
1152 }
1153 }
1154 continue;
1155
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001156 } else if (strcmp16(block.getElementName(&len), java_symbol16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001157 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1158
1159 String16 type;
1160 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
1161 if (typeIdx < 0) {
1162 srcPos.error("A 'type' attribute is required for <public>\n");
1163 hasErrors = localHasErrors = true;
1164 }
1165 type = String16(block.getAttributeStringValue(typeIdx, &len));
1166
1167 String16 name;
1168 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1169 if (nameIdx < 0) {
1170 srcPos.error("A 'name' attribute is required for <public>\n");
1171 hasErrors = localHasErrors = true;
1172 }
1173 name = String16(block.getAttributeStringValue(nameIdx, &len));
1174
1175 sp<AaptSymbols> symbols = assets->getJavaSymbolsFor(String8("R"));
1176 if (symbols != NULL) {
1177 symbols = symbols->addNestedSymbol(String8(type), srcPos);
1178 }
1179 if (symbols != NULL) {
1180 symbols->makeSymbolJavaSymbol(String8(name), srcPos);
1181 String16 comment(
1182 block.getComment(&len) ? block.getComment(&len) : nulStr);
1183 symbols->appendComment(String8(name), comment, srcPos);
1184 } else {
1185 srcPos.error("Unable to create symbols!\n");
1186 hasErrors = localHasErrors = true;
1187 }
1188
1189 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1190 if (code == ResXMLTree::END_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001191 if (strcmp16(block.getElementName(&len), java_symbol16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001192 break;
1193 }
1194 }
1195 }
1196 continue;
1197
1198
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001199 } else if (strcmp16(block.getElementName(&len), add_resource16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001200 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1201
1202 String16 typeName;
1203 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
1204 if (typeIdx < 0) {
1205 srcPos.error("A 'type' attribute is required for <add-resource>\n");
1206 hasErrors = localHasErrors = true;
1207 }
1208 typeName = String16(block.getAttributeStringValue(typeIdx, &len));
1209
1210 String16 name;
1211 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1212 if (nameIdx < 0) {
1213 srcPos.error("A 'name' attribute is required for <add-resource>\n");
1214 hasErrors = localHasErrors = true;
1215 }
1216 name = String16(block.getAttributeStringValue(nameIdx, &len));
1217
1218 outTable->canAddEntry(srcPos, myPackage, typeName, name);
1219
1220 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1221 if (code == ResXMLTree::END_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001222 if (strcmp16(block.getElementName(&len), add_resource16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001223 break;
1224 }
1225 }
1226 }
1227 continue;
1228
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001229 } else if (strcmp16(block.getElementName(&len), declare_styleable16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001230 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1231
1232 String16 ident;
1233 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
1234 if (identIdx < 0) {
1235 srcPos.error("A 'name' attribute is required for <declare-styleable>\n");
1236 hasErrors = localHasErrors = true;
1237 }
1238 ident = String16(block.getAttributeStringValue(identIdx, &len));
1239
1240 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1241 if (!localHasErrors) {
1242 if (symbols != NULL) {
1243 symbols = symbols->addNestedSymbol(String8("styleable"), srcPos);
1244 }
1245 sp<AaptSymbols> styleSymbols = symbols;
1246 if (symbols != NULL) {
1247 symbols = symbols->addNestedSymbol(String8(ident), srcPos);
1248 }
1249 if (symbols == NULL) {
1250 srcPos.error("Unable to create symbols!\n");
1251 return UNKNOWN_ERROR;
1252 }
1253
1254 String16 comment(
1255 block.getComment(&len) ? block.getComment(&len) : nulStr);
1256 styleSymbols->appendComment(String8(ident), comment, srcPos);
1257 } else {
1258 symbols = NULL;
1259 }
1260
1261 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1262 if (code == ResXMLTree::START_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001263 if (strcmp16(block.getElementName(&len), skip16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001264 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1265 && code != ResXMLTree::BAD_DOCUMENT) {
1266 if (code == ResXMLTree::END_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001267 if (strcmp16(block.getElementName(&len), skip16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001268 break;
1269 }
1270 }
1271 }
1272 continue;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001273 } else if (strcmp16(block.getElementName(&len), eat_comment16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001274 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1275 && code != ResXMLTree::BAD_DOCUMENT) {
1276 if (code == ResXMLTree::END_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001277 if (strcmp16(block.getElementName(&len), eat_comment16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001278 break;
1279 }
1280 }
1281 }
1282 continue;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001283 } else if (strcmp16(block.getElementName(&len), attr16.c_str()) != 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001284 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1285 "Tag <%s> can not appear inside <declare-styleable>, only <attr>\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001286 String8(block.getElementName(&len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001287 return UNKNOWN_ERROR;
1288 }
1289
1290 String16 comment(
1291 block.getComment(&len) ? block.getComment(&len) : nulStr);
1292 String16 itemIdent;
1293 err = compileAttribute(in, block, myPackage, outTable, &itemIdent, true);
1294 if (err != NO_ERROR) {
1295 hasErrors = localHasErrors = true;
1296 }
1297
1298 if (symbols != NULL) {
1299 SourcePos srcPos(String8(in->getPrintableSource()), block.getLineNumber());
1300 symbols->addSymbol(String8(itemIdent), 0, srcPos);
1301 symbols->appendComment(String8(itemIdent), comment, srcPos);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001302 //printf("Attribute %s comment: %s\n", String8(itemIdent).c_str(),
1303 // String8(comment).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001304 }
1305 } else if (code == ResXMLTree::END_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001306 if (strcmp16(block.getElementName(&len), declare_styleable16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001307 break;
1308 }
1309
1310 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1311 "Found tag </%s> where </attr> is expected\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001312 String8(block.getElementName(&len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001313 return UNKNOWN_ERROR;
1314 }
1315 }
1316 continue;
1317
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001318 } else if (strcmp16(block.getElementName(&len), attr16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001319 err = compileAttribute(in, block, myPackage, outTable, NULL);
1320 if (err != NO_ERROR) {
1321 hasErrors = true;
1322 }
1323 continue;
1324
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001325 } else if (strcmp16(block.getElementName(&len), item16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001326 curTag = &item16;
1327 ssize_t attri = block.indexOfAttribute(NULL, "type");
1328 if (attri >= 0) {
1329 curType = String16(block.getAttributeStringValue(attri, &len));
Adrian Roos58922482015-06-01 17:59:41 -07001330 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1331 if (nameIdx >= 0) {
1332 curName = String16(block.getAttributeStringValue(nameIdx, &len));
1333 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001334 ssize_t formatIdx = block.indexOfAttribute(NULL, "format");
1335 if (formatIdx >= 0) {
1336 String16 formatStr = String16(block.getAttributeStringValue(
1337 formatIdx, &len));
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001338 curFormat = parse_flags(formatStr.c_str(), formatStr.size(),
Adam Lesinski282e1812014-01-23 18:17:42 -08001339 gFormatFlags);
1340 if (curFormat == 0) {
1341 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1342 "Tag <item> 'format' attribute value \"%s\" not valid\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001343 String8(formatStr).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001344 hasErrors = localHasErrors = true;
1345 }
1346 }
1347 } else {
1348 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1349 "A 'type' attribute is required for <item>\n");
1350 hasErrors = localHasErrors = true;
1351 }
1352 curIsStyled = true;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001353 } else if (strcmp16(block.getElementName(&len), string16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001354 // Note the existence and locale of every string we process
Narayan Kamath91447d82014-01-21 15:32:36 +00001355 char rawLocale[RESTABLE_MAX_LOCALE_LEN];
1356 curParams.getBcp47Locale(rawLocale);
Adam Lesinski282e1812014-01-23 18:17:42 -08001357 String8 locale(rawLocale);
1358 String16 name;
1359 String16 translatable;
1360 String16 formatted;
1361
1362 size_t n = block.getAttributeCount();
1363 for (size_t i = 0; i < n; i++) {
1364 size_t length;
Dan Albertf348c152014-09-08 18:28:00 -07001365 const char16_t* attr = block.getAttributeName(i, &length);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001366 if (strcmp16(attr, name16.c_str()) == 0) {
Tomasz Wasilczyk31eb3c892023-08-23 22:12:33 +00001367 name = String16(block.getAttributeStringValue(i, &length));
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001368 } else if (strcmp16(attr, translatable16.c_str()) == 0) {
Tomasz Wasilczyk31eb3c892023-08-23 22:12:33 +00001369 translatable = String16(block.getAttributeStringValue(i, &length));
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001370 } else if (strcmp16(attr, formatted16.c_str()) == 0) {
Tomasz Wasilczyk31eb3c892023-08-23 22:12:33 +00001371 formatted = String16(block.getAttributeStringValue(i, &length));
Adam Lesinski282e1812014-01-23 18:17:42 -08001372 }
1373 }
1374
1375 if (name.size() > 0) {
Adrian Roos58922482015-06-01 17:59:41 -07001376 if (locale.size() == 0) {
1377 outTable->addDefaultLocalization(name);
1378 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001379 if (translatable == false16) {
1380 curIsFormatted = false;
1381 // Untranslatable strings must only exist in the default [empty] locale
1382 if (locale.size() > 0) {
Adam Lesinskia01a9372014-03-20 18:04:57 -07001383 SourcePos(in->getPrintableSource(), block.getLineNumber()).warning(
1384 "string '%s' marked untranslatable but exists in locale '%s'\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001385 String8(name).c_str(),
1386 locale.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001387 // hasErrors = localHasErrors = true;
1388 } else {
1389 // Intentionally empty block:
1390 //
1391 // Don't add untranslatable strings to the localization table; that
1392 // way if we later see localizations of them, they'll be flagged as
1393 // having no default translation.
1394 }
1395 } else {
Adam Lesinskia01a9372014-03-20 18:04:57 -07001396 outTable->addLocalization(
1397 name,
1398 locale,
1399 SourcePos(in->getPrintableSource(), block.getLineNumber()));
Adam Lesinski282e1812014-01-23 18:17:42 -08001400 }
1401
1402 if (formatted == false16) {
1403 curIsFormatted = false;
1404 }
1405 }
1406
1407 curTag = &string16;
1408 curType = string16;
1409 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
1410 curIsStyled = true;
Igor Viarheichyk84410b02014-04-30 11:56:42 -07001411 curIsPseudolocalizable = fileIsTranslatable && (translatable != false16);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001412 } else if (strcmp16(block.getElementName(&len), drawable16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001413 curTag = &drawable16;
1414 curType = drawable16;
1415 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001416 } else if (strcmp16(block.getElementName(&len), color16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001417 curTag = &color16;
1418 curType = color16;
1419 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001420 } else if (strcmp16(block.getElementName(&len), bool16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001421 curTag = &bool16;
1422 curType = bool16;
1423 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_BOOLEAN;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001424 } else if (strcmp16(block.getElementName(&len), integer16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001425 curTag = &integer16;
1426 curType = integer16;
1427 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001428 } else if (strcmp16(block.getElementName(&len), dimen16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001429 curTag = &dimen16;
1430 curType = dimen16;
1431 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_DIMENSION;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001432 } else if (strcmp16(block.getElementName(&len), fraction16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001433 curTag = &fraction16;
1434 curType = fraction16;
1435 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_FRACTION;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001436 } else if (strcmp16(block.getElementName(&len), bag16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001437 curTag = &bag16;
1438 curIsBag = true;
1439 ssize_t attri = block.indexOfAttribute(NULL, "type");
1440 if (attri >= 0) {
1441 curType = String16(block.getAttributeStringValue(attri, &len));
1442 } else {
1443 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1444 "A 'type' attribute is required for <bag>\n");
1445 hasErrors = localHasErrors = true;
1446 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001447 } else if (strcmp16(block.getElementName(&len), style16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001448 curTag = &style16;
1449 curType = style16;
1450 curIsBag = true;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001451 } else if (strcmp16(block.getElementName(&len), plurals16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001452 curTag = &plurals16;
1453 curType = plurals16;
1454 curIsBag = true;
Anton Krumina2ef5c02014-03-12 14:46:44 -07001455 curIsPseudolocalizable = fileIsTranslatable;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001456 } else if (strcmp16(block.getElementName(&len), array16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001457 curTag = &array16;
1458 curType = array16;
1459 curIsBag = true;
1460 curIsBagReplaceOnOverwrite = true;
1461 ssize_t formatIdx = block.indexOfAttribute(NULL, "format");
1462 if (formatIdx >= 0) {
1463 String16 formatStr = String16(block.getAttributeStringValue(
1464 formatIdx, &len));
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001465 curFormat = parse_flags(formatStr.c_str(), formatStr.size(),
Adam Lesinski282e1812014-01-23 18:17:42 -08001466 gFormatFlags);
1467 if (curFormat == 0) {
1468 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1469 "Tag <array> 'format' attribute value \"%s\" not valid\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001470 String8(formatStr).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001471 hasErrors = localHasErrors = true;
1472 }
1473 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001474 } else if (strcmp16(block.getElementName(&len), string_array16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001475 // Check whether these strings need valid formats.
1476 // (simplified form of what string16 does above)
Anton Krumina2ef5c02014-03-12 14:46:44 -07001477 bool isTranslatable = false;
Adam Lesinski282e1812014-01-23 18:17:42 -08001478 size_t n = block.getAttributeCount();
Narayan Kamath9a9fa162013-12-18 13:27:30 +00001479
1480 // Pseudolocalizable by default, unless this string array isn't
1481 // translatable.
Adam Lesinski282e1812014-01-23 18:17:42 -08001482 for (size_t i = 0; i < n; i++) {
1483 size_t length;
Dan Albertf348c152014-09-08 18:28:00 -07001484 const char16_t* attr = block.getAttributeName(i, &length);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001485 if (strcmp16(attr, formatted16.c_str()) == 0) {
Dan Albertf348c152014-09-08 18:28:00 -07001486 const char16_t* value = block.getAttributeStringValue(i, &length);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001487 if (strcmp16(value, false16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001488 curIsFormatted = false;
Adam Lesinski282e1812014-01-23 18:17:42 -08001489 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001490 } else if (strcmp16(attr, translatable16.c_str()) == 0) {
Dan Albertf348c152014-09-08 18:28:00 -07001491 const char16_t* value = block.getAttributeStringValue(i, &length);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001492 if (strcmp16(value, false16.c_str()) == 0) {
Anton Krumina2ef5c02014-03-12 14:46:44 -07001493 isTranslatable = false;
1494 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001495 }
1496 }
1497
1498 curTag = &string_array16;
1499 curType = array16;
1500 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
1501 curIsBag = true;
1502 curIsBagReplaceOnOverwrite = true;
Anton Krumina2ef5c02014-03-12 14:46:44 -07001503 curIsPseudolocalizable = isTranslatable && fileIsTranslatable;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001504 } else if (strcmp16(block.getElementName(&len), integer_array16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001505 curTag = &integer_array16;
1506 curType = array16;
1507 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
1508 curIsBag = true;
1509 curIsBagReplaceOnOverwrite = true;
1510 } else {
1511 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1512 "Found tag %s where item is expected\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001513 String8(block.getElementName(&len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001514 return UNKNOWN_ERROR;
1515 }
1516
1517 String16 ident;
1518 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
1519 if (identIdx >= 0) {
1520 ident = String16(block.getAttributeStringValue(identIdx, &len));
1521 } else {
1522 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1523 "A 'name' attribute is required for <%s>\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001524 String8(*curTag).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001525 hasErrors = localHasErrors = true;
1526 }
1527
1528 String16 product;
1529 identIdx = block.indexOfAttribute(NULL, "product");
1530 if (identIdx >= 0) {
1531 product = String16(block.getAttributeStringValue(identIdx, &len));
1532 }
1533
1534 String16 comment(block.getComment(&len) ? block.getComment(&len) : nulStr);
1535
1536 if (curIsBag) {
1537 // Figure out the parent of this bag...
1538 String16 parentIdent;
1539 ssize_t parentIdentIdx = block.indexOfAttribute(NULL, "parent");
1540 if (parentIdentIdx >= 0) {
1541 parentIdent = String16(block.getAttributeStringValue(parentIdentIdx, &len));
1542 } else {
1543 ssize_t sep = ident.findLast('.');
1544 if (sep >= 0) {
Tomasz Wasilczyk31eb3c892023-08-23 22:12:33 +00001545 parentIdent = String16(ident, sep);
Adam Lesinski282e1812014-01-23 18:17:42 -08001546 }
1547 }
1548
1549 if (!localHasErrors) {
1550 err = outTable->startBag(SourcePos(in->getPrintableSource(),
1551 block.getLineNumber()), myPackage, curType, ident,
1552 parentIdent, &curParams,
1553 overwrite, curIsBagReplaceOnOverwrite);
1554 if (err != NO_ERROR) {
1555 hasErrors = localHasErrors = true;
1556 }
1557 }
1558
1559 ssize_t elmIndex = 0;
1560 char elmIndexStr[14];
1561 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1562 && code != ResXMLTree::BAD_DOCUMENT) {
1563
1564 if (code == ResXMLTree::START_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001565 if (strcmp16(block.getElementName(&len), item16.c_str()) != 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001566 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1567 "Tag <%s> can not appear inside <%s>, only <item>\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001568 String8(block.getElementName(&len)).c_str(),
1569 String8(*curTag).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001570 return UNKNOWN_ERROR;
1571 }
1572
1573 String16 itemIdent;
1574 if (curType == array16) {
1575 sprintf(elmIndexStr, "^index_%d", (int)elmIndex++);
1576 itemIdent = String16(elmIndexStr);
1577 } else if (curType == plurals16) {
1578 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "quantity");
1579 if (itemIdentIdx >= 0) {
1580 String16 quantity16(block.getAttributeStringValue(itemIdentIdx, &len));
1581 if (quantity16 == other16) {
1582 itemIdent = quantityOther16;
1583 }
1584 else if (quantity16 == zero16) {
1585 itemIdent = quantityZero16;
1586 }
1587 else if (quantity16 == one16) {
1588 itemIdent = quantityOne16;
1589 }
1590 else if (quantity16 == two16) {
1591 itemIdent = quantityTwo16;
1592 }
1593 else if (quantity16 == few16) {
1594 itemIdent = quantityFew16;
1595 }
1596 else if (quantity16 == many16) {
1597 itemIdent = quantityMany16;
1598 }
1599 else {
1600 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1601 "Illegal 'quantity' attribute is <item> inside <plurals>\n");
1602 hasErrors = localHasErrors = true;
1603 }
1604 } else {
1605 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1606 "A 'quantity' attribute is required for <item> inside <plurals>\n");
1607 hasErrors = localHasErrors = true;
1608 }
1609 } else {
1610 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "name");
1611 if (itemIdentIdx >= 0) {
1612 itemIdent = String16(block.getAttributeStringValue(itemIdentIdx, &len));
1613 } else {
1614 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1615 "A 'name' attribute is required for <item>\n");
1616 hasErrors = localHasErrors = true;
1617 }
1618 }
1619
1620 ResXMLParser::ResXMLPosition parserPosition;
1621 block.getPosition(&parserPosition);
1622
1623 err = parseAndAddBag(bundle, in, &block, curParams, myPackage, curType,
1624 ident, parentIdent, itemIdent, curFormat, curIsFormatted,
Anton Krumina2ef5c02014-03-12 14:46:44 -07001625 product, NO_PSEUDOLOCALIZATION, overwrite, outTable);
Adam Lesinski282e1812014-01-23 18:17:42 -08001626 if (err == NO_ERROR) {
1627 if (curIsPseudolocalizable && localeIsDefined(curParams)
Anton Krumina2ef5c02014-03-12 14:46:44 -07001628 && bundle->getPseudolocalize() > 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001629 // pseudolocalize here
Anton Krumina2ef5c02014-03-12 14:46:44 -07001630 if ((PSEUDO_ACCENTED & bundle->getPseudolocalize()) ==
1631 PSEUDO_ACCENTED) {
1632 block.setPosition(parserPosition);
1633 err = parseAndAddBag(bundle, in, &block, pseudoParams, myPackage,
1634 curType, ident, parentIdent, itemIdent, curFormat,
1635 curIsFormatted, product, PSEUDO_ACCENTED,
1636 overwrite, outTable);
1637 }
1638 if ((PSEUDO_BIDI & bundle->getPseudolocalize()) ==
1639 PSEUDO_BIDI) {
1640 block.setPosition(parserPosition);
1641 err = parseAndAddBag(bundle, in, &block, pseudoBidiParams, myPackage,
1642 curType, ident, parentIdent, itemIdent, curFormat,
1643 curIsFormatted, product, PSEUDO_BIDI,
1644 overwrite, outTable);
1645 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001646 }
Anton Krumina2ef5c02014-03-12 14:46:44 -07001647 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001648 if (err != NO_ERROR) {
1649 hasErrors = localHasErrors = true;
1650 }
1651 } else if (code == ResXMLTree::END_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001652 if (strcmp16(block.getElementName(&len), curTag->c_str()) != 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001653 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1654 "Found tag </%s> where </%s> is expected\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001655 String8(block.getElementName(&len)).c_str(),
1656 String8(*curTag).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001657 return UNKNOWN_ERROR;
1658 }
1659 break;
1660 }
1661 }
1662 } else {
1663 ResXMLParser::ResXMLPosition parserPosition;
1664 block.getPosition(&parserPosition);
1665
1666 err = parseAndAddEntry(bundle, in, &block, curParams, myPackage, curType, ident,
1667 *curTag, curIsStyled, curFormat, curIsFormatted,
Anton Krumina2ef5c02014-03-12 14:46:44 -07001668 product, NO_PSEUDOLOCALIZATION, overwrite, &skippedResourceNames, outTable);
Adam Lesinski282e1812014-01-23 18:17:42 -08001669
1670 if (err < NO_ERROR) { // Why err < NO_ERROR instead of err != NO_ERROR?
1671 hasErrors = localHasErrors = true;
1672 }
1673 else if (err == NO_ERROR) {
Adrian Roos58922482015-06-01 17:59:41 -07001674 if (curType == string16 && !curParams.language[0] && !curParams.country[0]) {
1675 outTable->addDefaultLocalization(curName);
1676 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001677 if (curIsPseudolocalizable && localeIsDefined(curParams)
Anton Krumina2ef5c02014-03-12 14:46:44 -07001678 && bundle->getPseudolocalize() > 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001679 // pseudolocalize here
Anton Krumina2ef5c02014-03-12 14:46:44 -07001680 if ((PSEUDO_ACCENTED & bundle->getPseudolocalize()) ==
1681 PSEUDO_ACCENTED) {
1682 block.setPosition(parserPosition);
1683 err = parseAndAddEntry(bundle, in, &block, pseudoParams, myPackage, curType,
1684 ident, *curTag, curIsStyled, curFormat,
1685 curIsFormatted, product,
1686 PSEUDO_ACCENTED, overwrite, &skippedResourceNames, outTable);
1687 }
1688 if ((PSEUDO_BIDI & bundle->getPseudolocalize()) ==
1689 PSEUDO_BIDI) {
1690 block.setPosition(parserPosition);
1691 err = parseAndAddEntry(bundle, in, &block, pseudoBidiParams,
1692 myPackage, curType, ident, *curTag, curIsStyled, curFormat,
1693 curIsFormatted, product,
1694 PSEUDO_BIDI, overwrite, &skippedResourceNames, outTable);
1695 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001696 if (err != NO_ERROR) {
1697 hasErrors = localHasErrors = true;
1698 }
1699 }
1700 }
1701 }
1702
1703#if 0
1704 if (comment.size() > 0) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001705 printf("Comment for @%s:%s/%s: %s\n", String8(myPackage).c_str(),
1706 String8(curType).c_str(), String8(ident).c_str(),
1707 String8(comment).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001708 }
1709#endif
1710 if (!localHasErrors) {
1711 outTable->appendComment(myPackage, curType, ident, comment, false);
1712 }
1713 }
1714 else if (code == ResXMLTree::END_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001715 if (strcmp16(block.getElementName(&len), resources16.c_str()) != 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001716 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001717 "Unexpected end tag %s\n", String8(block.getElementName(&len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001718 return UNKNOWN_ERROR;
1719 }
1720 }
1721 else if (code == ResXMLTree::START_NAMESPACE || code == ResXMLTree::END_NAMESPACE) {
1722 }
1723 else if (code == ResXMLTree::TEXT) {
1724 if (isWhitespace(block.getText(&len))) {
1725 continue;
1726 }
1727 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1728 "Found text \"%s\" where item tag is expected\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001729 String8(block.getText(&len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001730 return UNKNOWN_ERROR;
1731 }
1732 }
1733
Adam Lesinski8ff15b42013-10-07 16:54:01 -07001734 // For every resource defined, there must be exist one variant with a product attribute
1735 // set to 'default' (or no product attribute at all).
1736 // We check to see that for every resource that was ignored because of a mismatched
1737 // product attribute, some product variant of that resource was processed.
1738 for (size_t i = 0; i < skippedResourceNames.size(); i++) {
1739 if (skippedResourceNames[i]) {
1740 const type_ident_pair_t& p = skippedResourceNames.keyAt(i);
1741 if (!outTable->hasBagOrEntry(myPackage, p.type, p.ident)) {
1742 const char* bundleProduct =
1743 (bundle->getProduct() == NULL) ? "" : bundle->getProduct();
1744 fprintf(stderr, "In resource file %s: %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001745 in->getPrintableSource().c_str(),
1746 curParams.toString().c_str());
Adam Lesinski8ff15b42013-10-07 16:54:01 -07001747
1748 fprintf(stderr, "\t%s '%s' does not match product %s.\n"
1749 "\tYou may have forgotten to include a 'default' product variant"
1750 " of the resource.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001751 String8(p.type).c_str(), String8(p.ident).c_str(),
Adam Lesinski8ff15b42013-10-07 16:54:01 -07001752 bundleProduct[0] == 0 ? "default" : bundleProduct);
1753 return UNKNOWN_ERROR;
1754 }
1755 }
1756 }
1757
Andreas Gampe2412f842014-09-30 20:55:57 -07001758 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001759}
1760
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001761ResourceTable::ResourceTable(Bundle* bundle, const String16& assetsPackage, ResourceTable::PackageType type)
1762 : mAssetsPackage(assetsPackage)
1763 , mPackageType(type)
1764 , mTypeIdOffset(0)
1765 , mNumLocal(0)
1766 , mBundle(bundle)
Adam Lesinski282e1812014-01-23 18:17:42 -08001767{
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001768 ssize_t packageId = -1;
1769 switch (mPackageType) {
1770 case App:
1771 case AppFeature:
1772 packageId = 0x7f;
1773 break;
1774
1775 case System:
1776 packageId = 0x01;
1777 break;
1778
1779 case SharedLibrary:
1780 packageId = 0x00;
1781 break;
1782
1783 default:
1784 assert(0);
1785 break;
1786 }
1787 sp<Package> package = new Package(mAssetsPackage, packageId);
1788 mPackages.add(assetsPackage, package);
1789 mOrderedPackages.add(package);
1790
1791 // Every resource table always has one first entry, the bag attributes.
1792 const SourcePos unknown(String8("????"), 0);
1793 getType(mAssetsPackage, String16("attr"), unknown);
1794}
1795
1796static uint32_t findLargestTypeIdForPackage(const ResTable& table, const String16& packageName) {
1797 const size_t basePackageCount = table.getBasePackageCount();
1798 for (size_t i = 0; i < basePackageCount; i++) {
1799 if (packageName == table.getBasePackageName(i)) {
1800 return table.getLastTypeIdForPackage(i);
1801 }
1802 }
1803 return 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08001804}
1805
1806status_t ResourceTable::addIncludedResources(Bundle* bundle, const sp<AaptAssets>& assets)
1807{
1808 status_t err = assets->buildIncludedResources(bundle);
1809 if (err != NO_ERROR) {
1810 return err;
1811 }
1812
Adam Lesinski282e1812014-01-23 18:17:42 -08001813 mAssets = assets;
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001814 mTypeIdOffset = findLargestTypeIdForPackage(assets->getIncludedResources(), mAssetsPackage);
Adam Lesinski282e1812014-01-23 18:17:42 -08001815
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001816 const String8& featureAfter = bundle->getFeatureAfterPackage();
Tomasz Wasilczyk7e22cab2023-08-24 19:02:33 +00001817 if (!featureAfter.empty()) {
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001818 AssetManager featureAssetManager;
1819 if (!featureAssetManager.addAssetPath(featureAfter, NULL)) {
1820 fprintf(stderr, "ERROR: Feature package '%s' not found.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001821 featureAfter.c_str());
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001822 return UNKNOWN_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001823 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001824
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001825 const ResTable& featureTable = featureAssetManager.getResources(false);
Dan Albert030f5362015-03-04 13:54:20 -08001826 mTypeIdOffset = std::max(mTypeIdOffset,
Tomasz Wasilczyk7e22cab2023-08-24 19:02:33 +00001827 findLargestTypeIdForPackage(featureTable, mAssetsPackage));
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001828 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001829
1830 return NO_ERROR;
1831}
1832
1833status_t ResourceTable::addPublic(const SourcePos& sourcePos,
1834 const String16& package,
1835 const String16& type,
1836 const String16& name,
1837 const uint32_t ident)
1838{
1839 uint32_t rid = mAssets->getIncludedResources()
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001840 .identifierForName(name.c_str(), name.size(),
1841 type.c_str(), type.size(),
1842 package.c_str(), package.size());
Adam Lesinski282e1812014-01-23 18:17:42 -08001843 if (rid != 0) {
1844 sourcePos.error("Error declaring public resource %s/%s for included package %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001845 String8(type).c_str(), String8(name).c_str(),
1846 String8(package).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001847 return UNKNOWN_ERROR;
1848 }
1849
1850 sp<Type> t = getType(package, type, sourcePos);
1851 if (t == NULL) {
1852 return UNKNOWN_ERROR;
1853 }
1854 return t->addPublic(sourcePos, name, ident);
1855}
1856
1857status_t ResourceTable::addEntry(const SourcePos& sourcePos,
1858 const String16& package,
1859 const String16& type,
1860 const String16& name,
1861 const String16& value,
1862 const Vector<StringPool::entry_style_span>* style,
1863 const ResTable_config* params,
1864 const bool doSetIndex,
1865 const int32_t format,
1866 const bool overwrite)
1867{
Adam Lesinski282e1812014-01-23 18:17:42 -08001868 uint32_t rid = mAssets->getIncludedResources()
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001869 .identifierForName(name.c_str(), name.size(),
1870 type.c_str(), type.size(),
1871 package.c_str(), package.size());
Adam Lesinski282e1812014-01-23 18:17:42 -08001872 if (rid != 0) {
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001873 sourcePos.error("Resource entry %s/%s is already defined in package %s.",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001874 String8(type).c_str(), String8(name).c_str(), String8(package).c_str());
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001875 return UNKNOWN_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001876 }
1877
Adam Lesinski282e1812014-01-23 18:17:42 -08001878 sp<Entry> e = getEntry(package, type, name, sourcePos, overwrite,
1879 params, doSetIndex);
1880 if (e == NULL) {
1881 return UNKNOWN_ERROR;
1882 }
1883 status_t err = e->setItem(sourcePos, value, style, format, overwrite);
1884 if (err == NO_ERROR) {
1885 mNumLocal++;
1886 }
1887 return err;
1888}
1889
1890status_t ResourceTable::startBag(const SourcePos& sourcePos,
1891 const String16& package,
1892 const String16& type,
1893 const String16& name,
1894 const String16& bagParent,
1895 const ResTable_config* params,
1896 bool overlay,
Andreas Gampe2412f842014-09-30 20:55:57 -07001897 bool replace, bool /* isId */)
Adam Lesinski282e1812014-01-23 18:17:42 -08001898{
1899 status_t result = NO_ERROR;
1900
1901 // Check for adding entries in other packages... for now we do
1902 // nothing. We need to do the right thing here to support skinning.
1903 uint32_t rid = mAssets->getIncludedResources()
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001904 .identifierForName(name.c_str(), name.size(),
1905 type.c_str(), type.size(),
1906 package.c_str(), package.size());
Adam Lesinski282e1812014-01-23 18:17:42 -08001907 if (rid != 0) {
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001908 sourcePos.error("Resource entry %s/%s is already defined in package %s.",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001909 String8(type).c_str(), String8(name).c_str(), String8(package).c_str());
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001910 return UNKNOWN_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001911 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001912
Adam Lesinski282e1812014-01-23 18:17:42 -08001913 if (overlay && !mBundle->getAutoAddOverlay() && !hasBagOrEntry(package, type, name)) {
1914 bool canAdd = false;
1915 sp<Package> p = mPackages.valueFor(package);
1916 if (p != NULL) {
1917 sp<Type> t = p->getTypes().valueFor(type);
1918 if (t != NULL) {
1919 if (t->getCanAddEntries().indexOf(name) >= 0) {
1920 canAdd = true;
1921 }
1922 }
1923 }
1924 if (!canAdd) {
1925 sourcePos.error("Resource does not already exist in overlay at '%s'; use <add-resource> to add.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001926 String8(name).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001927 return UNKNOWN_ERROR;
1928 }
1929 }
1930 sp<Entry> e = getEntry(package, type, name, sourcePos, overlay, params);
1931 if (e == NULL) {
1932 return UNKNOWN_ERROR;
1933 }
1934
1935 // If a parent is explicitly specified, set it.
1936 if (bagParent.size() > 0) {
1937 e->setParent(bagParent);
1938 }
1939
1940 if ((result = e->makeItABag(sourcePos)) != NO_ERROR) {
1941 return result;
1942 }
1943
1944 if (overlay && replace) {
1945 return e->emptyBag(sourcePos);
1946 }
1947 return result;
1948}
1949
1950status_t ResourceTable::addBag(const SourcePos& sourcePos,
1951 const String16& package,
1952 const String16& type,
1953 const String16& name,
1954 const String16& bagParent,
1955 const String16& bagKey,
1956 const String16& value,
1957 const Vector<StringPool::entry_style_span>* style,
1958 const ResTable_config* params,
1959 bool replace, bool isId, const int32_t format)
1960{
1961 // Check for adding entries in other packages... for now we do
1962 // nothing. We need to do the right thing here to support skinning.
1963 uint32_t rid = mAssets->getIncludedResources()
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001964 .identifierForName(name.c_str(), name.size(),
1965 type.c_str(), type.size(),
1966 package.c_str(), package.size());
Adam Lesinski282e1812014-01-23 18:17:42 -08001967 if (rid != 0) {
1968 return NO_ERROR;
1969 }
1970
1971#if 0
1972 if (name == String16("left")) {
1973 printf("Adding bag left: file=%s, line=%d, type=%s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001974 sourcePos.file.striing(), sourcePos.line, String8(type).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001975 }
1976#endif
1977 sp<Entry> e = getEntry(package, type, name, sourcePos, replace, params);
1978 if (e == NULL) {
1979 return UNKNOWN_ERROR;
1980 }
1981
1982 // If a parent is explicitly specified, set it.
1983 if (bagParent.size() > 0) {
1984 e->setParent(bagParent);
1985 }
1986
1987 const bool first = e->getBag().indexOfKey(bagKey) < 0;
1988 status_t err = e->addToBag(sourcePos, bagKey, value, style, replace, isId, format);
1989 if (err == NO_ERROR && first) {
1990 mNumLocal++;
1991 }
1992 return err;
1993}
1994
1995bool ResourceTable::hasBagOrEntry(const String16& package,
1996 const String16& type,
1997 const String16& name) const
1998{
1999 // First look for this in the included resources...
2000 uint32_t rid = mAssets->getIncludedResources()
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002001 .identifierForName(name.c_str(), name.size(),
2002 type.c_str(), type.size(),
2003 package.c_str(), package.size());
Adam Lesinski282e1812014-01-23 18:17:42 -08002004 if (rid != 0) {
2005 return true;
2006 }
2007
2008 sp<Package> p = mPackages.valueFor(package);
2009 if (p != NULL) {
2010 sp<Type> t = p->getTypes().valueFor(type);
2011 if (t != NULL) {
2012 sp<ConfigList> c = t->getConfigs().valueFor(name);
2013 if (c != NULL) return true;
2014 }
2015 }
2016
2017 return false;
2018}
2019
2020bool ResourceTable::hasBagOrEntry(const String16& package,
2021 const String16& type,
2022 const String16& name,
2023 const ResTable_config& config) const
2024{
2025 // First look for this in the included resources...
2026 uint32_t rid = mAssets->getIncludedResources()
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002027 .identifierForName(name.c_str(), name.size(),
2028 type.c_str(), type.size(),
2029 package.c_str(), package.size());
Adam Lesinski282e1812014-01-23 18:17:42 -08002030 if (rid != 0) {
2031 return true;
2032 }
2033
2034 sp<Package> p = mPackages.valueFor(package);
2035 if (p != NULL) {
2036 sp<Type> t = p->getTypes().valueFor(type);
2037 if (t != NULL) {
2038 sp<ConfigList> c = t->getConfigs().valueFor(name);
2039 if (c != NULL) {
2040 sp<Entry> e = c->getEntries().valueFor(config);
2041 if (e != NULL) {
2042 return true;
2043 }
2044 }
2045 }
2046 }
2047
2048 return false;
2049}
2050
2051bool ResourceTable::hasBagOrEntry(const String16& ref,
2052 const String16* defType,
2053 const String16* defPackage)
2054{
2055 String16 package, type, name;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002056 if (!ResTable::expandResourceRef(ref.c_str(), ref.size(), &package, &type, &name,
Adam Lesinski282e1812014-01-23 18:17:42 -08002057 defType, defPackage ? defPackage:&mAssetsPackage, NULL)) {
2058 return false;
2059 }
2060 return hasBagOrEntry(package, type, name);
2061}
2062
2063bool ResourceTable::appendComment(const String16& package,
2064 const String16& type,
2065 const String16& name,
2066 const String16& comment,
2067 bool onlyIfEmpty)
2068{
2069 if (comment.size() <= 0) {
2070 return true;
2071 }
2072
2073 sp<Package> p = mPackages.valueFor(package);
2074 if (p != NULL) {
2075 sp<Type> t = p->getTypes().valueFor(type);
2076 if (t != NULL) {
2077 sp<ConfigList> c = t->getConfigs().valueFor(name);
2078 if (c != NULL) {
2079 c->appendComment(comment, onlyIfEmpty);
2080 return true;
2081 }
2082 }
2083 }
2084 return false;
2085}
2086
2087bool ResourceTable::appendTypeComment(const String16& package,
2088 const String16& type,
2089 const String16& name,
2090 const String16& comment)
2091{
2092 if (comment.size() <= 0) {
2093 return true;
2094 }
2095
2096 sp<Package> p = mPackages.valueFor(package);
2097 if (p != NULL) {
2098 sp<Type> t = p->getTypes().valueFor(type);
2099 if (t != NULL) {
2100 sp<ConfigList> c = t->getConfigs().valueFor(name);
2101 if (c != NULL) {
2102 c->appendTypeComment(comment);
2103 return true;
2104 }
2105 }
2106 }
2107 return false;
2108}
2109
Adam Lesinskiafc79be2016-02-22 09:16:33 -08002110bool ResourceTable::makeAttribute(const String16& package,
2111 const String16& name,
2112 const SourcePos& source,
2113 int32_t format,
2114 const String16& comment,
2115 bool shouldAppendComment) {
2116 const String16 attr16("attr");
2117
2118 // First look for this in the included resources...
2119 uint32_t rid = mAssets->getIncludedResources()
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002120 .identifierForName(name.c_str(), name.size(),
2121 attr16.c_str(), attr16.size(),
2122 package.c_str(), package.size());
Adam Lesinskiafc79be2016-02-22 09:16:33 -08002123 if (rid != 0) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002124 source.error("Attribute \"%s\" has already been defined", String8(name).c_str());
Adam Lesinskiafc79be2016-02-22 09:16:33 -08002125 return false;
2126 }
2127
2128 sp<ResourceTable::Entry> entry = getEntry(package, attr16, name, source, false);
2129 if (entry == NULL) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002130 source.error("Failed to create entry attr/%s", String8(name).c_str());
Adam Lesinskiafc79be2016-02-22 09:16:33 -08002131 return false;
2132 }
2133
2134 if (entry->makeItABag(source) != NO_ERROR) {
2135 return false;
2136 }
2137
2138 const String16 formatKey16("^type");
2139 const String16 formatValue16(String8::format("%d", format));
2140
2141 ssize_t idx = entry->getBag().indexOfKey(formatKey16);
2142 if (idx >= 0) {
2143 // We have already set a format for this attribute, check if they are different.
2144 // We allow duplicate attribute definitions so long as they are identical.
2145 // This is to ensure inter-operation with libraries that define the same generic attribute.
2146 const Item& formatItem = entry->getBag().valueAt(idx);
2147 if ((format & (ResTable_map::TYPE_ENUM | ResTable_map::TYPE_FLAGS)) ||
2148 formatItem.value != formatValue16) {
2149 source.error("Attribute \"%s\" already defined with incompatible format.\n"
2150 "%s:%d: Original attribute defined here.",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002151 String8(name).c_str(), formatItem.sourcePos.file.c_str(),
Adam Lesinskiafc79be2016-02-22 09:16:33 -08002152 formatItem.sourcePos.line);
2153 return false;
2154 }
2155 } else {
2156 entry->addToBag(source, formatKey16, formatValue16);
2157 // Increment the number of resources we have. This is used to determine if we should
2158 // even generate a resource table.
2159 mNumLocal++;
2160 }
2161 appendComment(package, attr16, name, comment, shouldAppendComment);
2162 return true;
2163}
2164
Adam Lesinski282e1812014-01-23 18:17:42 -08002165void ResourceTable::canAddEntry(const SourcePos& pos,
2166 const String16& package, const String16& type, const String16& name)
2167{
2168 sp<Type> t = getType(package, type, pos);
2169 if (t != NULL) {
2170 t->canAddEntry(name);
2171 }
2172}
2173
2174size_t ResourceTable::size() const {
2175 return mPackages.size();
2176}
2177
2178size_t ResourceTable::numLocalResources() const {
2179 return mNumLocal;
2180}
2181
2182bool ResourceTable::hasResources() const {
2183 return mNumLocal > 0;
2184}
2185
Adam Lesinski27f69f42014-08-21 13:19:12 -07002186sp<AaptFile> ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& filter,
2187 const bool isBase)
Adam Lesinski282e1812014-01-23 18:17:42 -08002188{
2189 sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
Adam Lesinski27f69f42014-08-21 13:19:12 -07002190 status_t err = flatten(bundle, filter, data, isBase);
Adam Lesinski282e1812014-01-23 18:17:42 -08002191 return err == NO_ERROR ? data : NULL;
2192}
2193
2194inline uint32_t ResourceTable::getResId(const sp<Package>& p,
2195 const sp<Type>& t,
2196 uint32_t nameId)
2197{
2198 return makeResId(p->getAssignedId(), t->getIndex(), nameId);
2199}
2200
2201uint32_t ResourceTable::getResId(const String16& package,
2202 const String16& type,
2203 const String16& name,
2204 bool onlyPublic) const
2205{
2206 uint32_t id = ResourceIdCache::lookup(package, type, name, onlyPublic);
2207 if (id != 0) return id; // cache hit
2208
Adam Lesinski282e1812014-01-23 18:17:42 -08002209 // First look for this in the included resources...
2210 uint32_t specFlags = 0;
2211 uint32_t rid = mAssets->getIncludedResources()
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002212 .identifierForName(name.c_str(), name.size(),
2213 type.c_str(), type.size(),
2214 package.c_str(), package.size(),
Adam Lesinski282e1812014-01-23 18:17:42 -08002215 &specFlags);
2216 if (rid != 0) {
Adam Lesinskifa1e9d72017-01-24 16:16:09 -08002217 if (onlyPublic && (specFlags & ResTable_typeSpec::SPEC_PUBLIC) == 0) {
2218 // If this is a feature split and the resource has the same
2219 // package name as us, then everything is public.
2220 if (mPackageType != AppFeature || mAssetsPackage != package) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002221 return 0;
2222 }
2223 }
2224
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002225 return ResourceIdCache::store(package, type, name, onlyPublic, rid);
Adam Lesinski282e1812014-01-23 18:17:42 -08002226 }
2227
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002228 sp<Package> p = mPackages.valueFor(package);
2229 if (p == NULL) return 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08002230 sp<Type> t = p->getTypes().valueFor(type);
2231 if (t == NULL) return 0;
Adam Lesinski9b624c12014-11-19 17:49:26 -08002232 sp<ConfigList> c = t->getConfigs().valueFor(name);
2233 if (c == NULL) {
2234 if (type != String16("attr")) {
2235 return 0;
2236 }
2237 t = p->getTypes().valueFor(String16(kAttrPrivateType));
2238 if (t == NULL) return 0;
2239 c = t->getConfigs().valueFor(name);
2240 if (c == NULL) return 0;
2241 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002242 int32_t ei = c->getEntryIndex();
2243 if (ei < 0) return 0;
2244
2245 return ResourceIdCache::store(package, type, name, onlyPublic,
2246 getResId(p, t, ei));
2247}
2248
2249uint32_t ResourceTable::getResId(const String16& ref,
2250 const String16* defType,
2251 const String16* defPackage,
2252 const char** outErrorMsg,
2253 bool onlyPublic) const
2254{
2255 String16 package, type, name;
2256 bool refOnlyPublic = true;
2257 if (!ResTable::expandResourceRef(
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002258 ref.c_str(), ref.size(), &package, &type, &name,
Adam Lesinski282e1812014-01-23 18:17:42 -08002259 defType, defPackage ? defPackage:&mAssetsPackage,
2260 outErrorMsg, &refOnlyPublic)) {
Andreas Gampe2412f842014-09-30 20:55:57 -07002261 if (kIsDebug) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002262 printf("Expanding resource: ref=%s\n", String8(ref).c_str());
Andreas Gampe2412f842014-09-30 20:55:57 -07002263 printf("Expanding resource: defType=%s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002264 defType ? String8(*defType).c_str() : "NULL");
Andreas Gampe2412f842014-09-30 20:55:57 -07002265 printf("Expanding resource: defPackage=%s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002266 defPackage ? String8(*defPackage).c_str() : "NULL");
2267 printf("Expanding resource: ref=%s\n", String8(ref).c_str());
Andreas Gampe2412f842014-09-30 20:55:57 -07002268 printf("Expanded resource: p=%s, t=%s, n=%s, res=0\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002269 String8(package).c_str(), String8(type).c_str(),
2270 String8(name).c_str());
Andreas Gampe2412f842014-09-30 20:55:57 -07002271 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002272 return 0;
2273 }
2274 uint32_t res = getResId(package, type, name, onlyPublic && refOnlyPublic);
Andreas Gampe2412f842014-09-30 20:55:57 -07002275 if (kIsDebug) {
2276 printf("Expanded resource: p=%s, t=%s, n=%s, res=%d\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002277 String8(package).c_str(), String8(type).c_str(),
2278 String8(name).c_str(), res);
Andreas Gampe2412f842014-09-30 20:55:57 -07002279 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002280 if (res == 0) {
2281 if (outErrorMsg)
2282 *outErrorMsg = "No resource found that matches the given name";
2283 }
2284 return res;
2285}
2286
2287bool ResourceTable::isValidResourceName(const String16& s)
2288{
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002289 const char16_t* p = s.c_str();
Adam Lesinski282e1812014-01-23 18:17:42 -08002290 bool first = true;
2291 while (*p) {
2292 if ((*p >= 'a' && *p <= 'z')
2293 || (*p >= 'A' && *p <= 'Z')
2294 || *p == '_'
2295 || (!first && *p >= '0' && *p <= '9')) {
2296 first = false;
2297 p++;
2298 continue;
2299 }
2300 return false;
2301 }
2302 return true;
2303}
2304
2305bool ResourceTable::stringToValue(Res_value* outValue, StringPool* pool,
2306 const String16& str,
2307 bool preserveSpaces, bool coerceType,
2308 uint32_t attrID,
2309 const Vector<StringPool::entry_style_span>* style,
2310 String16* outStr, void* accessorCookie,
2311 uint32_t attrType, const String8* configTypeName,
2312 const ConfigDescription* config)
2313{
2314 String16 finalStr;
2315
2316 bool res = true;
2317 if (style == NULL || style->size() == 0) {
2318 // Text is not styled so it can be any type... let's figure it out.
2319 res = mAssets->getIncludedResources()
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002320 .stringToValue(outValue, &finalStr, str.c_str(), str.size(), preserveSpaces,
Adam Lesinski282e1812014-01-23 18:17:42 -08002321 coerceType, attrID, NULL, &mAssetsPackage, this,
2322 accessorCookie, attrType);
2323 } else {
2324 // Styled text can only be a string, and while collecting the style
2325 // information we have already processed that string!
2326 outValue->size = sizeof(Res_value);
2327 outValue->res0 = 0;
2328 outValue->dataType = outValue->TYPE_STRING;
2329 outValue->data = 0;
2330 finalStr = str;
2331 }
2332
2333 if (!res) {
2334 return false;
2335 }
2336
2337 if (outValue->dataType == outValue->TYPE_STRING) {
2338 // Should do better merging styles.
2339 if (pool) {
2340 String8 configStr;
2341 if (config != NULL) {
2342 configStr = config->toString();
2343 } else {
2344 configStr = "(null)";
2345 }
Andreas Gampe2412f842014-09-30 20:55:57 -07002346 if (kIsDebug) {
2347 printf("Adding to pool string style #%zu config %s: %s\n",
2348 style != NULL ? style->size() : 0U,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002349 configStr.c_str(), String8(finalStr).c_str());
Andreas Gampe2412f842014-09-30 20:55:57 -07002350 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002351 if (style != NULL && style->size() > 0) {
2352 outValue->data = pool->add(finalStr, *style, configTypeName, config);
2353 } else {
2354 outValue->data = pool->add(finalStr, true, configTypeName, config);
2355 }
2356 } else {
2357 // Caller will fill this in later.
2358 outValue->data = 0;
2359 }
2360
2361 if (outStr) {
2362 *outStr = finalStr;
2363 }
2364
2365 }
2366
2367 return true;
2368}
2369
2370uint32_t ResourceTable::getCustomResource(
2371 const String16& package, const String16& type, const String16& name) const
2372{
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002373 //printf("getCustomResource: %s %s %s\n", String8(package).c_str(),
2374 // String8(type).c_str(), String8(name).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002375 sp<Package> p = mPackages.valueFor(package);
2376 if (p == NULL) return 0;
2377 sp<Type> t = p->getTypes().valueFor(type);
2378 if (t == NULL) return 0;
2379 sp<ConfigList> c = t->getConfigs().valueFor(name);
Adam Lesinski9b624c12014-11-19 17:49:26 -08002380 if (c == NULL) {
2381 if (type != String16("attr")) {
2382 return 0;
2383 }
2384 t = p->getTypes().valueFor(String16(kAttrPrivateType));
2385 if (t == NULL) return 0;
2386 c = t->getConfigs().valueFor(name);
2387 if (c == NULL) return 0;
2388 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002389 int32_t ei = c->getEntryIndex();
2390 if (ei < 0) return 0;
2391 return getResId(p, t, ei);
2392}
2393
2394uint32_t ResourceTable::getCustomResourceWithCreation(
2395 const String16& package, const String16& type, const String16& name,
2396 const bool createIfNotFound)
2397{
2398 uint32_t resId = getCustomResource(package, type, name);
2399 if (resId != 0 || !createIfNotFound) {
2400 return resId;
2401 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002402
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002403 if (mAssetsPackage != package) {
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002404 mCurrentXmlPos.error("creating resource for external package %s: %s/%s.",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002405 String8(package).c_str(), String8(type).c_str(), String8(name).c_str());
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002406 if (package == String16("android")) {
2407 mCurrentXmlPos.printf("did you mean to use @+id instead of @+android:id?");
2408 }
2409 return 0;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002410 }
2411
2412 String16 value("false");
Adam Lesinski282e1812014-01-23 18:17:42 -08002413 status_t status = addEntry(mCurrentXmlPos, package, type, name, value, NULL, NULL, true);
2414 if (status == NO_ERROR) {
2415 resId = getResId(package, type, name);
2416 return resId;
2417 }
2418 return 0;
2419}
2420
2421uint32_t ResourceTable::getRemappedPackage(uint32_t origPackage) const
2422{
2423 return origPackage;
2424}
2425
2426bool ResourceTable::getAttributeType(uint32_t attrID, uint32_t* outType)
2427{
2428 //printf("getAttributeType #%08x\n", attrID);
2429 Res_value value;
2430 if (getItemValue(attrID, ResTable_map::ATTR_TYPE, &value)) {
2431 //printf("getAttributeType #%08x (%s): #%08x\n", attrID,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002432 // String8(getEntry(attrID)->getName()).c_str(), value.data);
Adam Lesinski282e1812014-01-23 18:17:42 -08002433 *outType = value.data;
2434 return true;
2435 }
2436 return false;
2437}
2438
2439bool ResourceTable::getAttributeMin(uint32_t attrID, uint32_t* outMin)
2440{
2441 //printf("getAttributeMin #%08x\n", attrID);
2442 Res_value value;
2443 if (getItemValue(attrID, ResTable_map::ATTR_MIN, &value)) {
2444 *outMin = value.data;
2445 return true;
2446 }
2447 return false;
2448}
2449
2450bool ResourceTable::getAttributeMax(uint32_t attrID, uint32_t* outMax)
2451{
2452 //printf("getAttributeMax #%08x\n", attrID);
2453 Res_value value;
2454 if (getItemValue(attrID, ResTable_map::ATTR_MAX, &value)) {
2455 *outMax = value.data;
2456 return true;
2457 }
2458 return false;
2459}
2460
2461uint32_t ResourceTable::getAttributeL10N(uint32_t attrID)
2462{
2463 //printf("getAttributeL10N #%08x\n", attrID);
2464 Res_value value;
2465 if (getItemValue(attrID, ResTable_map::ATTR_L10N, &value)) {
2466 return value.data;
2467 }
2468 return ResTable_map::L10N_NOT_REQUIRED;
2469}
2470
2471bool ResourceTable::getLocalizationSetting()
2472{
2473 return mBundle->getRequireLocalization();
2474}
2475
2476void ResourceTable::reportError(void* accessorCookie, const char* fmt, ...)
2477{
2478 if (accessorCookie != NULL && fmt != NULL) {
2479 AccessorCookie* ac = (AccessorCookie*)accessorCookie;
Adam Lesinski282e1812014-01-23 18:17:42 -08002480 char buf[1024];
2481 va_list ap;
2482 va_start(ap, fmt);
Yi Kong82ac8682021-08-20 02:48:22 +08002483 vsnprintf(buf, sizeof(buf), fmt, ap);
Adam Lesinski282e1812014-01-23 18:17:42 -08002484 va_end(ap);
2485 ac->sourcePos.error("Error: %s (at '%s' with value '%s').\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002486 buf, ac->attr.c_str(), ac->value.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002487 }
2488}
2489
2490bool ResourceTable::getAttributeKeys(
2491 uint32_t attrID, Vector<String16>* outKeys)
2492{
2493 sp<const Entry> e = getEntry(attrID);
2494 if (e != NULL) {
2495 const size_t N = e->getBag().size();
2496 for (size_t i=0; i<N; i++) {
2497 const String16& key = e->getBag().keyAt(i);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002498 if (key.size() > 0 && key.c_str()[0] != '^') {
Adam Lesinski282e1812014-01-23 18:17:42 -08002499 outKeys->add(key);
2500 }
2501 }
2502 return true;
2503 }
2504 return false;
2505}
2506
2507bool ResourceTable::getAttributeEnum(
2508 uint32_t attrID, const char16_t* name, size_t nameLen,
2509 Res_value* outValue)
2510{
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002511 //printf("getAttributeEnum #%08x %s\n", attrID, String8(name, nameLen).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002512 String16 nameStr(name, nameLen);
2513 sp<const Entry> e = getEntry(attrID);
2514 if (e != NULL) {
2515 const size_t N = e->getBag().size();
2516 for (size_t i=0; i<N; i++) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002517 //printf("Comparing %s to %s\n", String8(name, nameLen).c_str(),
2518 // String8(e->getBag().keyAt(i)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002519 if (e->getBag().keyAt(i) == nameStr) {
2520 return getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, outValue);
2521 }
2522 }
2523 }
2524 return false;
2525}
2526
2527bool ResourceTable::getAttributeFlags(
2528 uint32_t attrID, const char16_t* name, size_t nameLen,
2529 Res_value* outValue)
2530{
2531 outValue->dataType = Res_value::TYPE_INT_HEX;
2532 outValue->data = 0;
2533
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002534 //printf("getAttributeFlags #%08x %s\n", attrID, String8(name, nameLen).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002535 String16 nameStr(name, nameLen);
2536 sp<const Entry> e = getEntry(attrID);
2537 if (e != NULL) {
2538 const size_t N = e->getBag().size();
2539
2540 const char16_t* end = name + nameLen;
2541 const char16_t* pos = name;
2542 while (pos < end) {
2543 const char16_t* start = pos;
2544 while (pos < end && *pos != '|') {
2545 pos++;
2546 }
2547
2548 String16 nameStr(start, pos-start);
2549 size_t i;
2550 for (i=0; i<N; i++) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002551 //printf("Comparing \"%s\" to \"%s\"\n", String8(nameStr).c_str(),
2552 // String8(e->getBag().keyAt(i)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002553 if (e->getBag().keyAt(i) == nameStr) {
2554 Res_value val;
2555 bool got = getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, &val);
2556 if (!got) {
2557 return false;
2558 }
2559 //printf("Got value: 0x%08x\n", val.data);
2560 outValue->data |= val.data;
2561 break;
2562 }
2563 }
2564
2565 if (i >= N) {
2566 // Didn't find this flag identifier.
2567 return false;
2568 }
2569 pos++;
2570 }
2571
2572 return true;
2573 }
2574 return false;
2575}
2576
2577status_t ResourceTable::assignResourceIds()
2578{
2579 const size_t N = mOrderedPackages.size();
2580 size_t pi;
2581 status_t firstError = NO_ERROR;
2582
2583 // First generate all bag attributes and assign indices.
2584 for (pi=0; pi<N; pi++) {
2585 sp<Package> p = mOrderedPackages.itemAt(pi);
2586 if (p == NULL || p->getTypes().size() == 0) {
2587 // Empty, skip!
2588 continue;
2589 }
2590
Adam Lesinski9b624c12014-11-19 17:49:26 -08002591 if (mPackageType == System) {
2592 p->movePrivateAttrs();
2593 }
2594
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002595 // This has no sense for packages being built as AppFeature (aka with a non-zero offset).
Adam Lesinski282e1812014-01-23 18:17:42 -08002596 status_t err = p->applyPublicTypeOrder();
2597 if (err != NO_ERROR && firstError == NO_ERROR) {
2598 firstError = err;
2599 }
2600
2601 // Generate attributes...
2602 const size_t N = p->getOrderedTypes().size();
2603 size_t ti;
2604 for (ti=0; ti<N; ti++) {
2605 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2606 if (t == NULL) {
2607 continue;
2608 }
2609 const size_t N = t->getOrderedConfigs().size();
2610 for (size_t ci=0; ci<N; ci++) {
2611 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2612 if (c == NULL) {
2613 continue;
2614 }
2615 const size_t N = c->getEntries().size();
2616 for (size_t ei=0; ei<N; ei++) {
2617 sp<Entry> e = c->getEntries().valueAt(ei);
2618 if (e == NULL) {
2619 continue;
2620 }
2621 status_t err = e->generateAttributes(this, p->getName());
2622 if (err != NO_ERROR && firstError == NO_ERROR) {
2623 firstError = err;
2624 }
2625 }
2626 }
2627 }
2628
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002629 uint32_t typeIdOffset = 0;
2630 if (mPackageType == AppFeature && p->getName() == mAssetsPackage) {
2631 typeIdOffset = mTypeIdOffset;
2632 }
2633
Adam Lesinski282e1812014-01-23 18:17:42 -08002634 const SourcePos unknown(String8("????"), 0);
2635 sp<Type> attr = p->getType(String16("attr"), unknown);
2636
Adam Lesinski4d219da2016-08-03 15:40:19 -07002637 // Force creation of ID if we are building feature splits.
2638 // Auto-generated ID resources won't apply the type ID offset correctly unless
2639 // the offset is applied here first.
2640 // b/30607637
2641 if (mPackageType == AppFeature && p->getName() == mAssetsPackage) {
2642 sp<Type> id = p->getType(String16("id"), unknown);
2643 }
2644
Adam Lesinski282e1812014-01-23 18:17:42 -08002645 // Assign indices...
Adam Lesinski43a0df02014-08-18 17:14:57 -07002646 const size_t typeCount = p->getOrderedTypes().size();
2647 for (size_t ti = 0; ti < typeCount; ti++) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002648 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2649 if (t == NULL) {
2650 continue;
2651 }
Adam Lesinski43a0df02014-08-18 17:14:57 -07002652
Adam Lesinski282e1812014-01-23 18:17:42 -08002653 err = t->applyPublicEntryOrder();
2654 if (err != NO_ERROR && firstError == NO_ERROR) {
2655 firstError = err;
2656 }
2657
2658 const size_t N = t->getOrderedConfigs().size();
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002659 t->setIndex(ti + 1 + typeIdOffset);
Adam Lesinski282e1812014-01-23 18:17:42 -08002660
2661 LOG_ALWAYS_FATAL_IF(ti == 0 && attr != t,
2662 "First type is not attr!");
2663
2664 for (size_t ei=0; ei<N; ei++) {
2665 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ei);
2666 if (c == NULL) {
2667 continue;
2668 }
2669 c->setEntryIndex(ei);
2670 }
2671 }
2672
Adam Lesinski9b624c12014-11-19 17:49:26 -08002673
Adam Lesinski282e1812014-01-23 18:17:42 -08002674 // Assign resource IDs to keys in bags...
Adam Lesinski43a0df02014-08-18 17:14:57 -07002675 for (size_t ti = 0; ti < typeCount; ti++) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002676 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2677 if (t == NULL) {
2678 continue;
2679 }
Adam Lesinski9b624c12014-11-19 17:49:26 -08002680
Adam Lesinski282e1812014-01-23 18:17:42 -08002681 const size_t N = t->getOrderedConfigs().size();
2682 for (size_t ci=0; ci<N; ci++) {
2683 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
Adam Lesinski9b624c12014-11-19 17:49:26 -08002684 if (c == NULL) {
2685 continue;
2686 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002687 //printf("Ordered config #%d: %p\n", ci, c.get());
2688 const size_t N = c->getEntries().size();
2689 for (size_t ei=0; ei<N; ei++) {
2690 sp<Entry> e = c->getEntries().valueAt(ei);
2691 if (e == NULL) {
2692 continue;
2693 }
2694 status_t err = e->assignResourceIds(this, p->getName());
2695 if (err != NO_ERROR && firstError == NO_ERROR) {
2696 firstError = err;
2697 }
2698 }
2699 }
2700 }
2701 }
2702 return firstError;
2703}
2704
Adrian Roos58922482015-06-01 17:59:41 -07002705status_t ResourceTable::addSymbols(const sp<AaptSymbols>& outSymbols,
2706 bool skipSymbolsWithoutDefaultLocalization) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002707 const size_t N = mOrderedPackages.size();
Adrian Roos58922482015-06-01 17:59:41 -07002708 const String8 defaultLocale;
2709 const String16 stringType("string");
Adam Lesinski282e1812014-01-23 18:17:42 -08002710 size_t pi;
2711
2712 for (pi=0; pi<N; pi++) {
2713 sp<Package> p = mOrderedPackages.itemAt(pi);
2714 if (p->getTypes().size() == 0) {
2715 // Empty, skip!
2716 continue;
2717 }
2718
2719 const size_t N = p->getOrderedTypes().size();
2720 size_t ti;
2721
2722 for (ti=0; ti<N; ti++) {
2723 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2724 if (t == NULL) {
2725 continue;
2726 }
Adam Lesinski9b624c12014-11-19 17:49:26 -08002727
Adam Lesinski282e1812014-01-23 18:17:42 -08002728 const size_t N = t->getOrderedConfigs().size();
Adam Lesinski9b624c12014-11-19 17:49:26 -08002729 sp<AaptSymbols> typeSymbols;
2730 if (t->getName() == String16(kAttrPrivateType)) {
2731 typeSymbols = outSymbols->addNestedSymbol(String8("attr"), t->getPos());
2732 } else {
2733 typeSymbols = outSymbols->addNestedSymbol(String8(t->getName()), t->getPos());
2734 }
2735
Adam Lesinski3fb8c9b2014-09-09 16:05:10 -07002736 if (typeSymbols == NULL) {
2737 return UNKNOWN_ERROR;
2738 }
2739
Adam Lesinski282e1812014-01-23 18:17:42 -08002740 for (size_t ci=0; ci<N; ci++) {
2741 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2742 if (c == NULL) {
2743 continue;
2744 }
2745 uint32_t rid = getResId(p, t, ci);
2746 if (rid == 0) {
2747 return UNKNOWN_ERROR;
2748 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002749 if (Res_GETPACKAGE(rid) + 1 == p->getAssignedId()) {
Adrian Roos58922482015-06-01 17:59:41 -07002750
2751 if (skipSymbolsWithoutDefaultLocalization &&
2752 t->getName() == stringType) {
2753
2754 // Don't generate symbols for strings without a default localization.
2755 if (mHasDefaultLocalization.find(c->getName())
2756 == mHasDefaultLocalization.end()) {
2757 // printf("Skip symbol [%08x] %s\n", rid,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002758 // String8(c->getName()).c_str());
Adrian Roos58922482015-06-01 17:59:41 -07002759 continue;
2760 }
2761 }
2762
Adam Lesinski282e1812014-01-23 18:17:42 -08002763 typeSymbols->addSymbol(String8(c->getName()), rid, c->getPos());
2764
2765 String16 comment(c->getComment());
2766 typeSymbols->appendComment(String8(c->getName()), comment, c->getPos());
Adam Lesinski8ff15b42013-10-07 16:54:01 -07002767 //printf("Type symbol [%08x] %s comment: %s\n", rid,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002768 // String8(c->getName()).c_str(), String8(comment).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002769 comment = c->getTypeComment();
2770 typeSymbols->appendTypeComment(String8(c->getName()), comment);
Adam Lesinski282e1812014-01-23 18:17:42 -08002771 }
2772 }
2773 }
2774 }
2775 return NO_ERROR;
2776}
2777
2778
2779void
Adam Lesinskia01a9372014-03-20 18:04:57 -07002780ResourceTable::addLocalization(const String16& name, const String8& locale, const SourcePos& src)
Adam Lesinski282e1812014-01-23 18:17:42 -08002781{
Adam Lesinskia01a9372014-03-20 18:04:57 -07002782 mLocalizations[name][locale] = src;
Adam Lesinski282e1812014-01-23 18:17:42 -08002783}
2784
Adrian Roos58922482015-06-01 17:59:41 -07002785void
2786ResourceTable::addDefaultLocalization(const String16& name)
2787{
2788 mHasDefaultLocalization.insert(name);
2789}
2790
Adam Lesinski282e1812014-01-23 18:17:42 -08002791
2792/*!
2793 * Flag various sorts of localization problems. '+' indicates checks already implemented;
2794 * '-' indicates checks that will be implemented in the future.
2795 *
2796 * + A localized string for which no default-locale version exists => warning
2797 * + A string for which no version in an explicitly-requested locale exists => warning
2798 * + A localized translation of an translateable="false" string => warning
2799 * - A localized string not provided in every locale used by the table
2800 */
2801status_t
2802ResourceTable::validateLocalizations(void)
2803{
2804 status_t err = NO_ERROR;
2805 const String8 defaultLocale;
2806
2807 // For all strings...
Dan Albert030f5362015-03-04 13:54:20 -08002808 for (const auto& nameIter : mLocalizations) {
2809 const std::map<String8, SourcePos>& configSrcMap = nameIter.second;
Adam Lesinski282e1812014-01-23 18:17:42 -08002810
2811 // Look for strings with no default localization
Adam Lesinskia01a9372014-03-20 18:04:57 -07002812 if (configSrcMap.count(defaultLocale) == 0) {
2813 SourcePos().warning("string '%s' has no default translation.",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002814 String8(nameIter.first).c_str());
Adam Lesinskia01a9372014-03-20 18:04:57 -07002815 if (mBundle->getVerbose()) {
Dan Albert030f5362015-03-04 13:54:20 -08002816 for (const auto& locale : configSrcMap) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002817 locale.second.printf("locale %s found", locale.first.c_str());
Adam Lesinskia01a9372014-03-20 18:04:57 -07002818 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002819 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002820 // !!! TODO: throw an error here in some circumstances
2821 }
2822
2823 // Check that all requested localizations are present for this string
Adam Lesinskifab50872014-04-16 14:40:42 -07002824 if (mBundle->getConfigurations().size() > 0 && mBundle->getRequireLocalization()) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002825 const char* allConfigs = mBundle->getConfigurations().c_str();
Adam Lesinski282e1812014-01-23 18:17:42 -08002826 const char* start = allConfigs;
2827 const char* comma;
Dan Albert030f5362015-03-04 13:54:20 -08002828
2829 std::set<String8> missingConfigs;
Adam Lesinskia01a9372014-03-20 18:04:57 -07002830 AaptLocaleValue locale;
Adam Lesinski282e1812014-01-23 18:17:42 -08002831 do {
2832 String8 config;
2833 comma = strchr(start, ',');
2834 if (comma != NULL) {
Tomasz Wasilczyk31eb3c892023-08-23 22:12:33 +00002835 config = String8(start, comma - start);
Adam Lesinski282e1812014-01-23 18:17:42 -08002836 start = comma + 1;
2837 } else {
Tomasz Wasilczyk31eb3c892023-08-23 22:12:33 +00002838 config = start;
Adam Lesinski282e1812014-01-23 18:17:42 -08002839 }
2840
Adam Lesinskia01a9372014-03-20 18:04:57 -07002841 if (!locale.initFromFilterString(config)) {
2842 continue;
2843 }
2844
Anton Krumina2ef5c02014-03-12 14:46:44 -07002845 // don't bother with the pseudolocale "en_XA" or "ar_XB"
2846 if (config != "en_XA" && config != "ar_XB") {
Adam Lesinskia01a9372014-03-20 18:04:57 -07002847 if (configSrcMap.find(config) == configSrcMap.end()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002848 // okay, no specific localization found. it's possible that we are
2849 // requiring a specific regional localization [e.g. de_DE] but there is an
2850 // available string in the generic language localization [e.g. de];
2851 // consider that string to have fulfilled the localization requirement.
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002852 String8 region(config.c_str(), 2);
Adam Lesinskia01a9372014-03-20 18:04:57 -07002853 if (configSrcMap.find(region) == configSrcMap.end() &&
2854 configSrcMap.count(defaultLocale) == 0) {
2855 missingConfigs.insert(config);
Adam Lesinski282e1812014-01-23 18:17:42 -08002856 }
2857 }
2858 }
Adam Lesinskia01a9372014-03-20 18:04:57 -07002859 } while (comma != NULL);
2860
2861 if (!missingConfigs.empty()) {
2862 String8 configStr;
Dan Albert030f5362015-03-04 13:54:20 -08002863 for (const auto& iter : missingConfigs) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002864 configStr.appendFormat(" %s", iter.c_str());
Adam Lesinskia01a9372014-03-20 18:04:57 -07002865 }
2866 SourcePos().warning("string '%s' is missing %u required localizations:%s",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002867 String8(nameIter.first).c_str(),
Adam Lesinskia01a9372014-03-20 18:04:57 -07002868 (unsigned int)missingConfigs.size(),
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002869 configStr.c_str());
Adam Lesinskia01a9372014-03-20 18:04:57 -07002870 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002871 }
2872 }
2873
2874 return err;
2875}
2876
Adam Lesinski27f69f42014-08-21 13:19:12 -07002877status_t ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& filter,
2878 const sp<AaptFile>& dest,
2879 const bool isBase)
Adam Lesinski282e1812014-01-23 18:17:42 -08002880{
Adam Lesinski282e1812014-01-23 18:17:42 -08002881 const ConfigDescription nullConfig;
2882
2883 const size_t N = mOrderedPackages.size();
2884 size_t pi;
2885
2886 const static String16 mipmap16("mipmap");
2887
2888 bool useUTF8 = !bundle->getUTF16StringsOption();
2889
Adam Lesinskide898ff2014-01-29 18:20:45 -08002890 // The libraries this table references.
2891 Vector<sp<Package> > libraryPackages;
Adam Lesinski6022deb2014-08-20 14:59:19 -07002892 const ResTable& table = mAssets->getIncludedResources();
2893 const size_t basePackageCount = table.getBasePackageCount();
2894 for (size_t i = 0; i < basePackageCount; i++) {
2895 size_t packageId = table.getBasePackageId(i);
2896 String16 packageName(table.getBasePackageName(i));
Adnan Begovic14e307c12015-07-06 20:06:36 -07002897 if (packageId > 0x01 && packageId != 0x7f && packageId != 0x3f &&
2898 packageName != String16("android") &&
2899 packageName != String16("omnirom.platform")) {
Adam Lesinski6022deb2014-08-20 14:59:19 -07002900 libraryPackages.add(sp<Package>(new Package(packageName, packageId)));
2901 }
2902 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08002903
Adam Lesinski282e1812014-01-23 18:17:42 -08002904 // Iterate through all data, collecting all values (strings,
2905 // references, etc).
2906 StringPool valueStrings(useUTF8);
2907 Vector<sp<Entry> > allEntries;
2908 for (pi=0; pi<N; pi++) {
2909 sp<Package> p = mOrderedPackages.itemAt(pi);
2910 if (p->getTypes().size() == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002911 continue;
2912 }
2913
2914 StringPool typeStrings(useUTF8);
2915 StringPool keyStrings(useUTF8);
2916
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002917 ssize_t stringsAdded = 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08002918 const size_t N = p->getOrderedTypes().size();
2919 for (size_t ti=0; ti<N; ti++) {
2920 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2921 if (t == NULL) {
2922 typeStrings.add(String16("<empty>"), false);
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002923 stringsAdded++;
Adam Lesinski282e1812014-01-23 18:17:42 -08002924 continue;
2925 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002926
2927 while (stringsAdded < t->getIndex() - 1) {
2928 typeStrings.add(String16("<empty>"), false);
2929 stringsAdded++;
2930 }
2931
Adam Lesinski282e1812014-01-23 18:17:42 -08002932 const String16 typeName(t->getName());
2933 typeStrings.add(typeName, false);
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002934 stringsAdded++;
Adam Lesinski282e1812014-01-23 18:17:42 -08002935
2936 // This is a hack to tweak the sorting order of the final strings,
2937 // to put stuff that is generally not language-specific first.
2938 String8 configTypeName(typeName);
2939 if (configTypeName == "drawable" || configTypeName == "layout"
2940 || configTypeName == "color" || configTypeName == "anim"
2941 || configTypeName == "interpolator" || configTypeName == "animator"
2942 || configTypeName == "xml" || configTypeName == "menu"
2943 || configTypeName == "mipmap" || configTypeName == "raw") {
2944 configTypeName = "1complex";
2945 } else {
2946 configTypeName = "2value";
2947 }
2948
Adam Lesinski27f69f42014-08-21 13:19:12 -07002949 // mipmaps don't get filtered, so they will
2950 // allways end up in the base. Make sure they
2951 // don't end up in a split.
2952 if (typeName == mipmap16 && !isBase) {
2953 continue;
2954 }
2955
Adam Lesinski282e1812014-01-23 18:17:42 -08002956 const bool filterable = (typeName != mipmap16);
2957
2958 const size_t N = t->getOrderedConfigs().size();
2959 for (size_t ci=0; ci<N; ci++) {
2960 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2961 if (c == NULL) {
2962 continue;
2963 }
2964 const size_t N = c->getEntries().size();
2965 for (size_t ei=0; ei<N; ei++) {
2966 ConfigDescription config = c->getEntries().keyAt(ei);
Adam Lesinskifab50872014-04-16 14:40:42 -07002967 if (filterable && !filter->match(config)) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002968 continue;
2969 }
2970 sp<Entry> e = c->getEntries().valueAt(ei);
2971 if (e == NULL) {
2972 continue;
2973 }
2974 e->setNameIndex(keyStrings.add(e->getName(), true));
2975
Adam Lesinski282e1812014-01-23 18:17:42 -08002976 status_t err = e->prepareFlatten(&valueStrings, this,
2977 &configTypeName, &config);
2978 if (err != NO_ERROR) {
2979 return err;
2980 }
2981 allEntries.add(e);
2982 }
2983 }
2984 }
2985
2986 p->setTypeStrings(typeStrings.createStringBlock());
2987 p->setKeyStrings(keyStrings.createStringBlock());
2988 }
2989
2990 if (bundle->getOutputAPKFile() != NULL) {
2991 // Now we want to sort the value strings for better locality. This will
2992 // cause the positions of the strings to change, so we need to go back
2993 // through out resource entries and update them accordingly. Only need
2994 // to do this if actually writing the output file.
2995 valueStrings.sortByConfig();
2996 for (pi=0; pi<allEntries.size(); pi++) {
2997 allEntries[pi]->remapStringValue(&valueStrings);
2998 }
2999 }
3000
3001 ssize_t strAmt = 0;
Adam Lesinskide898ff2014-01-29 18:20:45 -08003002
Adam Lesinski282e1812014-01-23 18:17:42 -08003003 // Now build the array of package chunks.
3004 Vector<sp<AaptFile> > flatPackages;
3005 for (pi=0; pi<N; pi++) {
3006 sp<Package> p = mOrderedPackages.itemAt(pi);
3007 if (p->getTypes().size() == 0) {
3008 // Empty, skip!
3009 continue;
3010 }
3011
3012 const size_t N = p->getTypeStrings().size();
3013
3014 const size_t baseSize = sizeof(ResTable_package);
3015
3016 // Start the package data.
3017 sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
3018 ResTable_package* header = (ResTable_package*)data->editData(baseSize);
3019 if (header == NULL) {
3020 fprintf(stderr, "ERROR: out of memory creating ResTable_package\n");
3021 return NO_MEMORY;
3022 }
3023 memset(header, 0, sizeof(*header));
3024 header->header.type = htods(RES_TABLE_PACKAGE_TYPE);
3025 header->header.headerSize = htods(sizeof(*header));
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003026 header->id = htodl(static_cast<uint32_t>(p->getAssignedId()));
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003027 strcpy16_htod(header->name, p->getName().c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003028
3029 // Write the string blocks.
3030 const size_t typeStringsStart = data->getSize();
3031 sp<AaptFile> strFile = p->getTypeStringsData();
3032 ssize_t amt = data->writeData(strFile->getData(), strFile->getSize());
Andreas Gampe2412f842014-09-30 20:55:57 -07003033 if (kPrintStringMetrics) {
Pirama Arumuga Nainardc36bb62018-05-11 15:52:49 -07003034 fprintf(stderr, "**** type strings: %zd\n", amt);
Andreas Gampe2412f842014-09-30 20:55:57 -07003035 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003036 strAmt += amt;
3037 if (amt < 0) {
3038 return amt;
3039 }
3040 const size_t keyStringsStart = data->getSize();
3041 strFile = p->getKeyStringsData();
3042 amt = data->writeData(strFile->getData(), strFile->getSize());
Andreas Gampe2412f842014-09-30 20:55:57 -07003043 if (kPrintStringMetrics) {
Pirama Arumuga Nainardc36bb62018-05-11 15:52:49 -07003044 fprintf(stderr, "**** key strings: %zd\n", amt);
Andreas Gampe2412f842014-09-30 20:55:57 -07003045 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003046 strAmt += amt;
3047 if (amt < 0) {
3048 return amt;
3049 }
3050
Adam Lesinski27f69f42014-08-21 13:19:12 -07003051 if (isBase) {
3052 status_t err = flattenLibraryTable(data, libraryPackages);
3053 if (err != NO_ERROR) {
3054 fprintf(stderr, "ERROR: failed to write library table\n");
3055 return err;
3056 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08003057 }
3058
Adam Lesinski282e1812014-01-23 18:17:42 -08003059 // Build the type chunks inside of this package.
3060 for (size_t ti=0; ti<N; ti++) {
3061 // Retrieve them in the same order as the type string block.
3062 size_t len;
Ryan Mitchell80094e32020-11-16 23:08:18 +00003063 String16 typeName(UnpackOptionalString(p->getTypeStrings().stringAt(ti), &len));
Adam Lesinski282e1812014-01-23 18:17:42 -08003064 sp<Type> t = p->getTypes().valueFor(typeName);
3065 LOG_ALWAYS_FATAL_IF(t == NULL && typeName != String16("<empty>"),
3066 "Type name %s not found",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003067 String8(typeName).c_str());
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003068 if (t == NULL) {
3069 continue;
3070 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003071 const bool filterable = (typeName != mipmap16);
Adam Lesinski27f69f42014-08-21 13:19:12 -07003072 const bool skipEntireType = (typeName == mipmap16 && !isBase);
Adam Lesinski282e1812014-01-23 18:17:42 -08003073
3074 const size_t N = t != NULL ? t->getOrderedConfigs().size() : 0;
3075
3076 // Until a non-NO_ENTRY value has been written for a resource,
3077 // that resource is invalid; validResources[i] represents
3078 // the item at t->getOrderedConfigs().itemAt(i).
3079 Vector<bool> validResources;
3080 validResources.insertAt(false, 0, N);
3081
3082 // First write the typeSpec chunk, containing information about
3083 // each resource entry in this type.
3084 {
3085 const size_t typeSpecSize = sizeof(ResTable_typeSpec) + sizeof(uint32_t)*N;
3086 const size_t typeSpecStart = data->getSize();
3087 ResTable_typeSpec* tsHeader = (ResTable_typeSpec*)
3088 (((uint8_t*)data->editData(typeSpecStart+typeSpecSize)) + typeSpecStart);
3089 if (tsHeader == NULL) {
3090 fprintf(stderr, "ERROR: out of memory creating ResTable_typeSpec\n");
3091 return NO_MEMORY;
3092 }
3093 memset(tsHeader, 0, sizeof(*tsHeader));
3094 tsHeader->header.type = htods(RES_TABLE_TYPE_SPEC_TYPE);
3095 tsHeader->header.headerSize = htods(sizeof(*tsHeader));
3096 tsHeader->header.size = htodl(typeSpecSize);
3097 tsHeader->id = ti+1;
3098 tsHeader->entryCount = htodl(N);
3099
3100 uint32_t* typeSpecFlags = (uint32_t*)
3101 (((uint8_t*)data->editData())
3102 + typeSpecStart + sizeof(ResTable_typeSpec));
3103 memset(typeSpecFlags, 0, sizeof(uint32_t)*N);
3104
3105 for (size_t ei=0; ei<N; ei++) {
3106 sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
Adam Lesinski9b624c12014-11-19 17:49:26 -08003107 if (cl == NULL) {
3108 continue;
3109 }
3110
Adam Lesinski282e1812014-01-23 18:17:42 -08003111 if (cl->getPublic()) {
3112 typeSpecFlags[ei] |= htodl(ResTable_typeSpec::SPEC_PUBLIC);
3113 }
Adam Lesinski27f69f42014-08-21 13:19:12 -07003114
3115 if (skipEntireType) {
3116 continue;
3117 }
3118
Adam Lesinski282e1812014-01-23 18:17:42 -08003119 const size_t CN = cl->getEntries().size();
3120 for (size_t ci=0; ci<CN; ci++) {
Adam Lesinskifab50872014-04-16 14:40:42 -07003121 if (filterable && !filter->match(cl->getEntries().keyAt(ci))) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003122 continue;
3123 }
3124 for (size_t cj=ci+1; cj<CN; cj++) {
Adam Lesinskifab50872014-04-16 14:40:42 -07003125 if (filterable && !filter->match(cl->getEntries().keyAt(cj))) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003126 continue;
3127 }
3128 typeSpecFlags[ei] |= htodl(
3129 cl->getEntries().keyAt(ci).diff(cl->getEntries().keyAt(cj)));
3130 }
3131 }
3132 }
3133 }
3134
Adam Lesinski27f69f42014-08-21 13:19:12 -07003135 if (skipEntireType) {
3136 continue;
3137 }
3138
Adam Lesinski282e1812014-01-23 18:17:42 -08003139 // We need to write one type chunk for each configuration for
3140 // which we have entries in this type.
Adam Lesinskie97908d2014-12-05 11:06:21 -08003141 SortedVector<ConfigDescription> uniqueConfigs;
3142 if (t != NULL) {
3143 uniqueConfigs = t->getUniqueConfigs();
3144 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003145
3146 const size_t typeSize = sizeof(ResTable_type) + sizeof(uint32_t)*N;
3147
Adam Lesinskie97908d2014-12-05 11:06:21 -08003148 const size_t NC = uniqueConfigs.size();
Adam Lesinski282e1812014-01-23 18:17:42 -08003149 for (size_t ci=0; ci<NC; ci++) {
Adam Lesinski9b624c12014-11-19 17:49:26 -08003150 const ConfigDescription& config = uniqueConfigs[ci];
Adam Lesinski282e1812014-01-23 18:17:42 -08003151
Andreas Gampe2412f842014-09-30 20:55:57 -07003152 if (kIsDebug) {
3153 printf("Writing config %zu config: imsi:%d/%d lang:%c%c cnt:%c%c "
3154 "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
3155 "sw%ddp w%ddp h%ddp layout:%d\n",
3156 ti + 1,
3157 config.mcc, config.mnc,
3158 config.language[0] ? config.language[0] : '-',
3159 config.language[1] ? config.language[1] : '-',
3160 config.country[0] ? config.country[0] : '-',
3161 config.country[1] ? config.country[1] : '-',
3162 config.orientation,
3163 config.uiMode,
3164 config.touchscreen,
3165 config.density,
3166 config.keyboard,
3167 config.inputFlags,
3168 config.navigation,
3169 config.screenWidth,
3170 config.screenHeight,
3171 config.smallestScreenWidthDp,
3172 config.screenWidthDp,
3173 config.screenHeightDp,
3174 config.screenLayout);
3175 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003176
Adam Lesinskifab50872014-04-16 14:40:42 -07003177 if (filterable && !filter->match(config)) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003178 continue;
3179 }
3180
3181 const size_t typeStart = data->getSize();
3182
3183 ResTable_type* tHeader = (ResTable_type*)
3184 (((uint8_t*)data->editData(typeStart+typeSize)) + typeStart);
3185 if (tHeader == NULL) {
3186 fprintf(stderr, "ERROR: out of memory creating ResTable_type\n");
3187 return NO_MEMORY;
3188 }
3189
3190 memset(tHeader, 0, sizeof(*tHeader));
3191 tHeader->header.type = htods(RES_TABLE_TYPE_TYPE);
3192 tHeader->header.headerSize = htods(sizeof(*tHeader));
3193 tHeader->id = ti+1;
3194 tHeader->entryCount = htodl(N);
3195 tHeader->entriesStart = htodl(typeSize);
3196 tHeader->config = config;
Andreas Gampe2412f842014-09-30 20:55:57 -07003197 if (kIsDebug) {
3198 printf("Writing type %zu config: imsi:%d/%d lang:%c%c cnt:%c%c "
3199 "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
3200 "sw%ddp w%ddp h%ddp layout:%d\n",
3201 ti + 1,
3202 tHeader->config.mcc, tHeader->config.mnc,
3203 tHeader->config.language[0] ? tHeader->config.language[0] : '-',
3204 tHeader->config.language[1] ? tHeader->config.language[1] : '-',
3205 tHeader->config.country[0] ? tHeader->config.country[0] : '-',
3206 tHeader->config.country[1] ? tHeader->config.country[1] : '-',
3207 tHeader->config.orientation,
3208 tHeader->config.uiMode,
3209 tHeader->config.touchscreen,
3210 tHeader->config.density,
3211 tHeader->config.keyboard,
3212 tHeader->config.inputFlags,
3213 tHeader->config.navigation,
3214 tHeader->config.screenWidth,
3215 tHeader->config.screenHeight,
3216 tHeader->config.smallestScreenWidthDp,
3217 tHeader->config.screenWidthDp,
3218 tHeader->config.screenHeightDp,
3219 tHeader->config.screenLayout);
3220 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003221 tHeader->config.swapHtoD();
3222
3223 // Build the entries inside of this type.
3224 for (size_t ei=0; ei<N; ei++) {
3225 sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
Adam Lesinski9b624c12014-11-19 17:49:26 -08003226 sp<Entry> e = NULL;
3227 if (cl != NULL) {
3228 e = cl->getEntries().valueFor(config);
3229 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003230
3231 // Set the offset for this entry in its type.
3232 uint32_t* index = (uint32_t*)
3233 (((uint8_t*)data->editData())
3234 + typeStart + sizeof(ResTable_type));
3235 if (e != NULL) {
3236 index[ei] = htodl(data->getSize()-typeStart-typeSize);
3237
3238 // Create the entry.
3239 ssize_t amt = e->flatten(bundle, data, cl->getPublic());
3240 if (amt < 0) {
3241 return amt;
3242 }
3243 validResources.editItemAt(ei) = true;
3244 } else {
3245 index[ei] = htodl(ResTable_type::NO_ENTRY);
3246 }
3247 }
3248
3249 // Fill in the rest of the type information.
3250 tHeader = (ResTable_type*)
3251 (((uint8_t*)data->editData()) + typeStart);
3252 tHeader->header.size = htodl(data->getSize()-typeStart);
3253 }
3254
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003255 // If we're building splits, then each invocation of the flattening
3256 // step will have 'missing' entries. Don't warn/error for this case.
Tomasz Wasilczyk7e22cab2023-08-24 19:02:33 +00003257 if (bundle->getSplitConfigurations().empty()) {
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003258 bool missing_entry = false;
3259 const char* log_prefix = bundle->getErrorOnMissingConfigEntry() ?
3260 "error" : "warning";
3261 for (size_t i = 0; i < N; ++i) {
3262 if (!validResources[i]) {
3263 sp<ConfigList> c = t->getOrderedConfigs().itemAt(i);
Adam Lesinski9b624c12014-11-19 17:49:26 -08003264 if (c != NULL) {
Colin Cross01f18562015-04-08 17:29:00 -07003265 fprintf(stderr, "%s: no entries written for %s/%s (0x%08zx)\n", log_prefix,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003266 String8(typeName).c_str(), String8(c->getName()).c_str(),
Adam Lesinski9b624c12014-11-19 17:49:26 -08003267 Res_MAKEID(p->getAssignedId() - 1, ti, i));
3268 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003269 missing_entry = true;
3270 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003271 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003272 if (bundle->getErrorOnMissingConfigEntry() && missing_entry) {
3273 fprintf(stderr, "Error: Missing entries, quit!\n");
3274 return NOT_ENOUGH_DATA;
3275 }
Ying Wangcd28bd32013-11-14 17:12:10 -08003276 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003277 }
3278
3279 // Fill in the rest of the package information.
3280 header = (ResTable_package*)data->editData();
3281 header->header.size = htodl(data->getSize());
3282 header->typeStrings = htodl(typeStringsStart);
3283 header->lastPublicType = htodl(p->getTypeStrings().size());
3284 header->keyStrings = htodl(keyStringsStart);
3285 header->lastPublicKey = htodl(p->getKeyStrings().size());
3286
3287 flatPackages.add(data);
3288 }
3289
3290 // And now write out the final chunks.
3291 const size_t dataStart = dest->getSize();
3292
3293 {
3294 // blah
3295 ResTable_header header;
3296 memset(&header, 0, sizeof(header));
3297 header.header.type = htods(RES_TABLE_TYPE);
3298 header.header.headerSize = htods(sizeof(header));
3299 header.packageCount = htodl(flatPackages.size());
3300 status_t err = dest->writeData(&header, sizeof(header));
3301 if (err != NO_ERROR) {
3302 fprintf(stderr, "ERROR: out of memory creating ResTable_header\n");
3303 return err;
3304 }
3305 }
3306
3307 ssize_t strStart = dest->getSize();
Adam Lesinskifab50872014-04-16 14:40:42 -07003308 status_t err = valueStrings.writeStringBlock(dest);
Adam Lesinski282e1812014-01-23 18:17:42 -08003309 if (err != NO_ERROR) {
3310 return err;
3311 }
3312
3313 ssize_t amt = (dest->getSize()-strStart);
3314 strAmt += amt;
Andreas Gampe2412f842014-09-30 20:55:57 -07003315 if (kPrintStringMetrics) {
Pirama Arumuga Nainardc36bb62018-05-11 15:52:49 -07003316 fprintf(stderr, "**** value strings: %zd\n", amt);
3317 fprintf(stderr, "**** total strings: %zd\n", amt);
Andreas Gampe2412f842014-09-30 20:55:57 -07003318 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08003319
Adam Lesinski282e1812014-01-23 18:17:42 -08003320 for (pi=0; pi<flatPackages.size(); pi++) {
3321 err = dest->writeData(flatPackages[pi]->getData(),
3322 flatPackages[pi]->getSize());
3323 if (err != NO_ERROR) {
3324 fprintf(stderr, "ERROR: out of memory creating package chunk for ResTable_header\n");
3325 return err;
3326 }
3327 }
3328
3329 ResTable_header* header = (ResTable_header*)
3330 (((uint8_t*)dest->getData()) + dataStart);
3331 header->header.size = htodl(dest->getSize() - dataStart);
3332
Andreas Gampe2412f842014-09-30 20:55:57 -07003333 if (kPrintStringMetrics) {
3334 fprintf(stderr, "**** total resource table size: %zu / %zu%% strings\n",
3335 dest->getSize(), (size_t)(strAmt*100)/dest->getSize());
3336 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003337
3338 return NO_ERROR;
3339}
3340
Adam Lesinskide898ff2014-01-29 18:20:45 -08003341status_t ResourceTable::flattenLibraryTable(const sp<AaptFile>& dest, const Vector<sp<Package> >& libs) {
3342 // Write out the library table if necessary
3343 if (libs.size() > 0) {
Andreas Gampe87332a72014-10-01 22:03:58 -07003344 if (kIsDebug) {
3345 fprintf(stderr, "Writing library reference table\n");
3346 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08003347
3348 const size_t libStart = dest->getSize();
3349 const size_t count = libs.size();
Adam Lesinski6022deb2014-08-20 14:59:19 -07003350 ResTable_lib_header* libHeader = (ResTable_lib_header*) dest->editDataInRange(
3351 libStart, sizeof(ResTable_lib_header));
Adam Lesinskide898ff2014-01-29 18:20:45 -08003352
3353 memset(libHeader, 0, sizeof(*libHeader));
3354 libHeader->header.type = htods(RES_TABLE_LIBRARY_TYPE);
3355 libHeader->header.headerSize = htods(sizeof(*libHeader));
3356 libHeader->header.size = htodl(sizeof(*libHeader) + (sizeof(ResTable_lib_entry) * count));
3357 libHeader->count = htodl(count);
3358
3359 // Write the library entries
3360 for (size_t i = 0; i < count; i++) {
3361 const size_t entryStart = dest->getSize();
3362 sp<Package> libPackage = libs[i];
Andreas Gampe87332a72014-10-01 22:03:58 -07003363 if (kIsDebug) {
3364 fprintf(stderr, " Entry %s -> 0x%02x\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003365 String8(libPackage->getName()).c_str(),
Andreas Gampe87332a72014-10-01 22:03:58 -07003366 (uint8_t)libPackage->getAssignedId());
3367 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08003368
Adam Lesinski6022deb2014-08-20 14:59:19 -07003369 ResTable_lib_entry* entry = (ResTable_lib_entry*) dest->editDataInRange(
3370 entryStart, sizeof(ResTable_lib_entry));
Adam Lesinskide898ff2014-01-29 18:20:45 -08003371 memset(entry, 0, sizeof(*entry));
3372 entry->packageId = htodl(libPackage->getAssignedId());
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003373 strcpy16_htod(entry->packageName, libPackage->getName().c_str());
Adam Lesinskide898ff2014-01-29 18:20:45 -08003374 }
3375 }
3376 return NO_ERROR;
3377}
3378
Adam Lesinski282e1812014-01-23 18:17:42 -08003379void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp)
3380{
3381 fprintf(fp,
3382 "<!-- This file contains <public> resource definitions for all\n"
3383 " resources that were generated from the source data. -->\n"
3384 "\n"
3385 "<resources>\n");
3386
3387 writePublicDefinitions(package, fp, true);
3388 writePublicDefinitions(package, fp, false);
3389
3390 fprintf(fp,
3391 "\n"
3392 "</resources>\n");
3393}
3394
3395void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp, bool pub)
3396{
3397 bool didHeader = false;
3398
3399 sp<Package> pkg = mPackages.valueFor(package);
3400 if (pkg != NULL) {
3401 const size_t NT = pkg->getOrderedTypes().size();
3402 for (size_t i=0; i<NT; i++) {
3403 sp<Type> t = pkg->getOrderedTypes().itemAt(i);
3404 if (t == NULL) {
3405 continue;
3406 }
3407
3408 bool didType = false;
3409
3410 const size_t NC = t->getOrderedConfigs().size();
3411 for (size_t j=0; j<NC; j++) {
3412 sp<ConfigList> c = t->getOrderedConfigs().itemAt(j);
3413 if (c == NULL) {
3414 continue;
3415 }
3416
3417 if (c->getPublic() != pub) {
3418 continue;
3419 }
3420
3421 if (!didType) {
3422 fprintf(fp, "\n");
3423 didType = true;
3424 }
3425 if (!didHeader) {
3426 if (pub) {
3427 fprintf(fp," <!-- PUBLIC SECTION. These resources have been declared public.\n");
3428 fprintf(fp," Changes to these definitions will break binary compatibility. -->\n\n");
3429 } else {
3430 fprintf(fp," <!-- PRIVATE SECTION. These resources have not been declared public.\n");
3431 fprintf(fp," You can make them public my moving these lines into a file in res/values. -->\n\n");
3432 }
3433 didHeader = true;
3434 }
3435 if (!pub) {
3436 const size_t NE = c->getEntries().size();
3437 for (size_t k=0; k<NE; k++) {
3438 const SourcePos& pos = c->getEntries().valueAt(k)->getPos();
3439 if (pos.file != "") {
3440 fprintf(fp," <!-- Declared at %s:%d -->\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003441 pos.file.c_str(), pos.line);
Adam Lesinski282e1812014-01-23 18:17:42 -08003442 }
3443 }
3444 }
3445 fprintf(fp, " <public type=\"%s\" name=\"%s\" id=\"0x%08x\" />\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003446 String8(t->getName()).c_str(),
3447 String8(c->getName()).c_str(),
Adam Lesinski282e1812014-01-23 18:17:42 -08003448 getResId(pkg, t, c->getEntryIndex()));
3449 }
3450 }
3451 }
3452}
3453
3454ResourceTable::Item::Item(const SourcePos& _sourcePos,
3455 bool _isId,
3456 const String16& _value,
3457 const Vector<StringPool::entry_style_span>* _style,
3458 int32_t _format)
3459 : sourcePos(_sourcePos)
3460 , isId(_isId)
3461 , value(_value)
3462 , format(_format)
3463 , bagKeyId(0)
3464 , evaluating(false)
3465{
3466 if (_style) {
3467 style = *_style;
3468 }
3469}
3470
Adam Lesinski82a2dd82014-09-17 18:34:15 -07003471ResourceTable::Entry::Entry(const Entry& entry)
3472 : RefBase()
3473 , mName(entry.mName)
3474 , mParent(entry.mParent)
3475 , mType(entry.mType)
3476 , mItem(entry.mItem)
3477 , mItemFormat(entry.mItemFormat)
3478 , mBag(entry.mBag)
3479 , mNameIndex(entry.mNameIndex)
3480 , mParentId(entry.mParentId)
3481 , mPos(entry.mPos) {}
3482
Adam Lesinski978ab9d2014-09-24 19:02:52 -07003483ResourceTable::Entry& ResourceTable::Entry::operator=(const Entry& entry) {
3484 mName = entry.mName;
3485 mParent = entry.mParent;
3486 mType = entry.mType;
3487 mItem = entry.mItem;
3488 mItemFormat = entry.mItemFormat;
3489 mBag = entry.mBag;
3490 mNameIndex = entry.mNameIndex;
3491 mParentId = entry.mParentId;
3492 mPos = entry.mPos;
3493 return *this;
3494}
3495
Adam Lesinski282e1812014-01-23 18:17:42 -08003496status_t ResourceTable::Entry::makeItABag(const SourcePos& sourcePos)
3497{
3498 if (mType == TYPE_BAG) {
3499 return NO_ERROR;
3500 }
3501 if (mType == TYPE_UNKNOWN) {
3502 mType = TYPE_BAG;
3503 return NO_ERROR;
3504 }
3505 sourcePos.error("Resource entry %s is already defined as a single item.\n"
3506 "%s:%d: Originally defined here.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003507 String8(mName).c_str(),
3508 mItem.sourcePos.file.c_str(), mItem.sourcePos.line);
Adam Lesinski282e1812014-01-23 18:17:42 -08003509 return UNKNOWN_ERROR;
3510}
3511
3512status_t ResourceTable::Entry::setItem(const SourcePos& sourcePos,
3513 const String16& value,
3514 const Vector<StringPool::entry_style_span>* style,
3515 int32_t format,
3516 const bool overwrite)
3517{
3518 Item item(sourcePos, false, value, style);
3519
3520 if (mType == TYPE_BAG) {
Adam Lesinski43a0df02014-08-18 17:14:57 -07003521 if (mBag.size() == 0) {
3522 sourcePos.error("Resource entry %s is already defined as a bag.",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003523 String8(mName).c_str());
Adam Lesinski43a0df02014-08-18 17:14:57 -07003524 } else {
3525 const Item& item(mBag.valueAt(0));
3526 sourcePos.error("Resource entry %s is already defined as a bag.\n"
3527 "%s:%d: Originally defined here.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003528 String8(mName).c_str(),
3529 item.sourcePos.file.c_str(), item.sourcePos.line);
Adam Lesinski43a0df02014-08-18 17:14:57 -07003530 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003531 return UNKNOWN_ERROR;
3532 }
3533 if ( (mType != TYPE_UNKNOWN) && (overwrite == false) ) {
3534 sourcePos.error("Resource entry %s is already defined.\n"
3535 "%s:%d: Originally defined here.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003536 String8(mName).c_str(),
3537 mItem.sourcePos.file.c_str(), mItem.sourcePos.line);
Adam Lesinski282e1812014-01-23 18:17:42 -08003538 return UNKNOWN_ERROR;
3539 }
3540
3541 mType = TYPE_ITEM;
3542 mItem = item;
3543 mItemFormat = format;
3544 return NO_ERROR;
3545}
3546
3547status_t ResourceTable::Entry::addToBag(const SourcePos& sourcePos,
3548 const String16& key, const String16& value,
3549 const Vector<StringPool::entry_style_span>* style,
3550 bool replace, bool isId, int32_t format)
3551{
3552 status_t err = makeItABag(sourcePos);
3553 if (err != NO_ERROR) {
3554 return err;
3555 }
3556
3557 Item item(sourcePos, isId, value, style, format);
3558
3559 // XXX NOTE: there is an error if you try to have a bag with two keys,
3560 // one an attr and one an id, with the same name. Not something we
3561 // currently ever have to worry about.
3562 ssize_t origKey = mBag.indexOfKey(key);
3563 if (origKey >= 0) {
3564 if (!replace) {
3565 const Item& item(mBag.valueAt(origKey));
3566 sourcePos.error("Resource entry %s already has bag item %s.\n"
3567 "%s:%d: Originally defined here.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003568 String8(mName).c_str(), String8(key).c_str(),
3569 item.sourcePos.file.c_str(), item.sourcePos.line);
Adam Lesinski282e1812014-01-23 18:17:42 -08003570 return UNKNOWN_ERROR;
3571 }
3572 //printf("Replacing %s with %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003573 // String8(mBag.valueFor(key).value).c_str(), String8(value).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003574 mBag.replaceValueFor(key, item);
3575 }
3576
3577 mBag.add(key, item);
3578 return NO_ERROR;
3579}
3580
Adam Lesinski82a2dd82014-09-17 18:34:15 -07003581status_t ResourceTable::Entry::removeFromBag(const String16& key) {
3582 if (mType != Entry::TYPE_BAG) {
3583 return NO_ERROR;
3584 }
3585
3586 if (mBag.removeItem(key) >= 0) {
3587 return NO_ERROR;
3588 }
3589 return UNKNOWN_ERROR;
3590}
3591
Adam Lesinski282e1812014-01-23 18:17:42 -08003592status_t ResourceTable::Entry::emptyBag(const SourcePos& sourcePos)
3593{
3594 status_t err = makeItABag(sourcePos);
3595 if (err != NO_ERROR) {
3596 return err;
3597 }
3598
3599 mBag.clear();
3600 return NO_ERROR;
3601}
3602
3603status_t ResourceTable::Entry::generateAttributes(ResourceTable* table,
3604 const String16& package)
3605{
3606 const String16 attr16("attr");
3607 const String16 id16("id");
3608 const size_t N = mBag.size();
3609 for (size_t i=0; i<N; i++) {
3610 const String16& key = mBag.keyAt(i);
3611 const Item& it = mBag.valueAt(i);
3612 if (it.isId) {
3613 if (!table->hasBagOrEntry(key, &id16, &package)) {
3614 String16 value("false");
Andreas Gampe87332a72014-10-01 22:03:58 -07003615 if (kIsDebug) {
3616 fprintf(stderr, "Generating %s:id/%s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003617 String8(package).c_str(),
3618 String8(key).c_str());
Andreas Gampe87332a72014-10-01 22:03:58 -07003619 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003620 status_t err = table->addEntry(SourcePos(String8("<generated>"), 0), package,
3621 id16, key, value);
3622 if (err != NO_ERROR) {
3623 return err;
3624 }
3625 }
3626 } else if (!table->hasBagOrEntry(key, &attr16, &package)) {
3627
3628#if 1
3629// fprintf(stderr, "ERROR: Bag attribute '%s' has not been defined.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003630// String8(key).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003631// const Item& item(mBag.valueAt(i));
3632// fprintf(stderr, "Referenced from file %s line %d\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003633// item.sourcePos.file.c_str(), item.sourcePos.line);
Adam Lesinski282e1812014-01-23 18:17:42 -08003634// return UNKNOWN_ERROR;
3635#else
3636 char numberStr[16];
3637 sprintf(numberStr, "%d", ResTable_map::TYPE_ANY);
3638 status_t err = table->addBag(SourcePos("<generated>", 0), package,
3639 attr16, key, String16(""),
3640 String16("^type"),
3641 String16(numberStr), NULL, NULL);
3642 if (err != NO_ERROR) {
3643 return err;
3644 }
3645#endif
3646 }
3647 }
3648 return NO_ERROR;
3649}
3650
3651status_t ResourceTable::Entry::assignResourceIds(ResourceTable* table,
Andreas Gampe2412f842014-09-30 20:55:57 -07003652 const String16& /* package */)
Adam Lesinski282e1812014-01-23 18:17:42 -08003653{
3654 bool hasErrors = false;
3655
3656 if (mType == TYPE_BAG) {
3657 const char* errorMsg;
3658 const String16 style16("style");
3659 const String16 attr16("attr");
3660 const String16 id16("id");
3661 mParentId = 0;
3662 if (mParent.size() > 0) {
3663 mParentId = table->getResId(mParent, &style16, NULL, &errorMsg);
3664 if (mParentId == 0) {
3665 mPos.error("Error retrieving parent for item: %s '%s'.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003666 errorMsg, String8(mParent).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003667 hasErrors = true;
3668 }
3669 }
3670 const size_t N = mBag.size();
3671 for (size_t i=0; i<N; i++) {
3672 const String16& key = mBag.keyAt(i);
3673 Item& it = mBag.editValueAt(i);
3674 it.bagKeyId = table->getResId(key,
3675 it.isId ? &id16 : &attr16, NULL, &errorMsg);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003676 //printf("Bag key of %s: #%08x\n", String8(key).c_str(), it.bagKeyId);
Adam Lesinski282e1812014-01-23 18:17:42 -08003677 if (it.bagKeyId == 0) {
3678 it.sourcePos.error("Error: %s: %s '%s'.\n", errorMsg,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003679 String8(it.isId ? id16 : attr16).c_str(),
3680 String8(key).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003681 hasErrors = true;
3682 }
3683 }
3684 }
Andreas Gampe2412f842014-09-30 20:55:57 -07003685 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08003686}
3687
3688status_t ResourceTable::Entry::prepareFlatten(StringPool* strings, ResourceTable* table,
3689 const String8* configTypeName, const ConfigDescription* config)
3690{
3691 if (mType == TYPE_ITEM) {
3692 Item& it = mItem;
3693 AccessorCookie ac(it.sourcePos, String8(mName), String8(it.value));
3694 if (!table->stringToValue(&it.parsedValue, strings,
3695 it.value, false, true, 0,
3696 &it.style, NULL, &ac, mItemFormat,
3697 configTypeName, config)) {
3698 return UNKNOWN_ERROR;
3699 }
3700 } else if (mType == TYPE_BAG) {
3701 const size_t N = mBag.size();
3702 for (size_t i=0; i<N; i++) {
3703 const String16& key = mBag.keyAt(i);
3704 Item& it = mBag.editValueAt(i);
3705 AccessorCookie ac(it.sourcePos, String8(key), String8(it.value));
3706 if (!table->stringToValue(&it.parsedValue, strings,
3707 it.value, false, true, it.bagKeyId,
3708 &it.style, NULL, &ac, it.format,
3709 configTypeName, config)) {
3710 return UNKNOWN_ERROR;
3711 }
3712 }
3713 } else {
3714 mPos.error("Error: entry %s is not a single item or a bag.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003715 String8(mName).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003716 return UNKNOWN_ERROR;
3717 }
3718 return NO_ERROR;
3719}
3720
3721status_t ResourceTable::Entry::remapStringValue(StringPool* strings)
3722{
3723 if (mType == TYPE_ITEM) {
3724 Item& it = mItem;
3725 if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3726 it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3727 }
3728 } else if (mType == TYPE_BAG) {
3729 const size_t N = mBag.size();
3730 for (size_t i=0; i<N; i++) {
3731 Item& it = mBag.editValueAt(i);
3732 if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3733 it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3734 }
3735 }
3736 } else {
3737 mPos.error("Error: entry %s is not a single item or a bag.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003738 String8(mName).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003739 return UNKNOWN_ERROR;
3740 }
3741 return NO_ERROR;
3742}
3743
Andreas Gampe2412f842014-09-30 20:55:57 -07003744ssize_t ResourceTable::Entry::flatten(Bundle* /* bundle */, const sp<AaptFile>& data, bool isPublic)
Adam Lesinski282e1812014-01-23 18:17:42 -08003745{
3746 size_t amt = 0;
3747 ResTable_entry header;
3748 memset(&header, 0, sizeof(header));
Eric Miao368cd192022-09-09 15:46:14 -07003749 header.full.size = htods(sizeof(header));
Andreas Gampe2412f842014-09-30 20:55:57 -07003750 const type ty = mType;
3751 if (ty == TYPE_BAG) {
Eric Miao368cd192022-09-09 15:46:14 -07003752 header.full.flags |= htods(header.FLAG_COMPLEX);
Adam Lesinski282e1812014-01-23 18:17:42 -08003753 }
Andreas Gampe2412f842014-09-30 20:55:57 -07003754 if (isPublic) {
Eric Miao368cd192022-09-09 15:46:14 -07003755 header.full.flags |= htods(header.FLAG_PUBLIC);
Andreas Gampe2412f842014-09-30 20:55:57 -07003756 }
Eric Miao368cd192022-09-09 15:46:14 -07003757 header.full.key.index = htodl(mNameIndex);
Adam Lesinski282e1812014-01-23 18:17:42 -08003758 if (ty != TYPE_BAG) {
3759 status_t err = data->writeData(&header, sizeof(header));
3760 if (err != NO_ERROR) {
3761 fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3762 return err;
3763 }
3764
3765 const Item& it = mItem;
3766 Res_value par;
3767 memset(&par, 0, sizeof(par));
3768 par.size = htods(it.parsedValue.size);
3769 par.dataType = it.parsedValue.dataType;
3770 par.res0 = it.parsedValue.res0;
3771 par.data = htodl(it.parsedValue.data);
3772 #if 0
3773 printf("Writing item (%s): type=%d, data=0x%x, res0=0x%x\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003774 String8(mName).c_str(), it.parsedValue.dataType,
Adam Lesinski282e1812014-01-23 18:17:42 -08003775 it.parsedValue.data, par.res0);
3776 #endif
3777 err = data->writeData(&par, it.parsedValue.size);
3778 if (err != NO_ERROR) {
3779 fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3780 return err;
3781 }
3782 amt += it.parsedValue.size;
3783 } else {
3784 size_t N = mBag.size();
3785 size_t i;
3786 // Create correct ordering of items.
3787 KeyedVector<uint32_t, const Item*> items;
3788 for (i=0; i<N; i++) {
3789 const Item& it = mBag.valueAt(i);
3790 items.add(it.bagKeyId, &it);
3791 }
3792 N = items.size();
3793
3794 ResTable_map_entry mapHeader;
3795 memcpy(&mapHeader, &header, sizeof(header));
3796 mapHeader.size = htods(sizeof(mapHeader));
3797 mapHeader.parent.ident = htodl(mParentId);
3798 mapHeader.count = htodl(N);
3799 status_t err = data->writeData(&mapHeader, sizeof(mapHeader));
3800 if (err != NO_ERROR) {
3801 fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3802 return err;
3803 }
3804
3805 for (i=0; i<N; i++) {
3806 const Item& it = *items.valueAt(i);
3807 ResTable_map map;
3808 map.name.ident = htodl(it.bagKeyId);
3809 map.value.size = htods(it.parsedValue.size);
3810 map.value.dataType = it.parsedValue.dataType;
3811 map.value.res0 = it.parsedValue.res0;
3812 map.value.data = htodl(it.parsedValue.data);
3813 err = data->writeData(&map, sizeof(map));
3814 if (err != NO_ERROR) {
3815 fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3816 return err;
3817 }
3818 amt += sizeof(map);
3819 }
3820 }
3821 return amt;
3822}
3823
3824void ResourceTable::ConfigList::appendComment(const String16& comment,
3825 bool onlyIfEmpty)
3826{
3827 if (comment.size() <= 0) {
3828 return;
3829 }
3830 if (onlyIfEmpty && mComment.size() > 0) {
3831 return;
3832 }
3833 if (mComment.size() > 0) {
3834 mComment.append(String16("\n"));
3835 }
3836 mComment.append(comment);
3837}
3838
3839void ResourceTable::ConfigList::appendTypeComment(const String16& comment)
3840{
3841 if (comment.size() <= 0) {
3842 return;
3843 }
3844 if (mTypeComment.size() > 0) {
3845 mTypeComment.append(String16("\n"));
3846 }
3847 mTypeComment.append(comment);
3848}
3849
3850status_t ResourceTable::Type::addPublic(const SourcePos& sourcePos,
3851 const String16& name,
3852 const uint32_t ident)
3853{
3854 #if 0
3855 int32_t entryIdx = Res_GETENTRY(ident);
3856 if (entryIdx < 0) {
3857 sourcePos.error("Public resource %s/%s has an invalid 0 identifier (0x%08x).\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003858 String8(mName).c_str(), String8(name).c_str(), ident);
Adam Lesinski282e1812014-01-23 18:17:42 -08003859 return UNKNOWN_ERROR;
3860 }
3861 #endif
3862
3863 int32_t typeIdx = Res_GETTYPE(ident);
3864 if (typeIdx >= 0) {
3865 typeIdx++;
3866 if (mPublicIndex > 0 && mPublicIndex != typeIdx) {
3867 sourcePos.error("Public resource %s/%s has conflicting type codes for its"
3868 " public identifiers (0x%x vs 0x%x).\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003869 String8(mName).c_str(), String8(name).c_str(),
Adam Lesinski282e1812014-01-23 18:17:42 -08003870 mPublicIndex, typeIdx);
3871 return UNKNOWN_ERROR;
3872 }
3873 mPublicIndex = typeIdx;
3874 }
3875
3876 if (mFirstPublicSourcePos == NULL) {
3877 mFirstPublicSourcePos = new SourcePos(sourcePos);
3878 }
3879
3880 if (mPublic.indexOfKey(name) < 0) {
3881 mPublic.add(name, Public(sourcePos, String16(), ident));
3882 } else {
3883 Public& p = mPublic.editValueFor(name);
3884 if (p.ident != ident) {
3885 sourcePos.error("Public resource %s/%s has conflicting public identifiers"
3886 " (0x%08x vs 0x%08x).\n"
3887 "%s:%d: Originally defined here.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003888 String8(mName).c_str(), String8(name).c_str(), p.ident, ident,
3889 p.sourcePos.file.c_str(), p.sourcePos.line);
Adam Lesinski282e1812014-01-23 18:17:42 -08003890 return UNKNOWN_ERROR;
3891 }
3892 }
3893
3894 return NO_ERROR;
3895}
3896
3897void ResourceTable::Type::canAddEntry(const String16& name)
3898{
3899 mCanAddEntries.add(name);
3900}
3901
3902sp<ResourceTable::Entry> ResourceTable::Type::getEntry(const String16& entry,
3903 const SourcePos& sourcePos,
3904 const ResTable_config* config,
3905 bool doSetIndex,
3906 bool overlay,
3907 bool autoAddOverlay)
3908{
3909 int pos = -1;
3910 sp<ConfigList> c = mConfigs.valueFor(entry);
3911 if (c == NULL) {
3912 if (overlay && !autoAddOverlay && mCanAddEntries.indexOf(entry) < 0) {
3913 sourcePos.error("Resource at %s appears in overlay but not"
3914 " in the base package; use <add-resource> to add.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003915 String8(entry).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003916 return NULL;
3917 }
3918 c = new ConfigList(entry, sourcePos);
3919 mConfigs.add(entry, c);
3920 pos = (int)mOrderedConfigs.size();
3921 mOrderedConfigs.add(c);
3922 if (doSetIndex) {
3923 c->setEntryIndex(pos);
3924 }
3925 }
3926
3927 ConfigDescription cdesc;
3928 if (config) cdesc = *config;
3929
3930 sp<Entry> e = c->getEntries().valueFor(cdesc);
3931 if (e == NULL) {
Andreas Gampe2412f842014-09-30 20:55:57 -07003932 if (kIsDebug) {
3933 if (config != NULL) {
3934 printf("New entry at %s:%d: imsi:%d/%d lang:%c%c cnt:%c%c "
Adam Lesinski282e1812014-01-23 18:17:42 -08003935 "orien:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
Andreas Gampe2412f842014-09-30 20:55:57 -07003936 "sw%ddp w%ddp h%ddp layout:%d\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003937 sourcePos.file.c_str(), sourcePos.line,
Adam Lesinski282e1812014-01-23 18:17:42 -08003938 config->mcc, config->mnc,
3939 config->language[0] ? config->language[0] : '-',
3940 config->language[1] ? config->language[1] : '-',
3941 config->country[0] ? config->country[0] : '-',
3942 config->country[1] ? config->country[1] : '-',
3943 config->orientation,
3944 config->touchscreen,
3945 config->density,
3946 config->keyboard,
3947 config->inputFlags,
3948 config->navigation,
3949 config->screenWidth,
3950 config->screenHeight,
3951 config->smallestScreenWidthDp,
3952 config->screenWidthDp,
3953 config->screenHeightDp,
Andreas Gampe2412f842014-09-30 20:55:57 -07003954 config->screenLayout);
3955 } else {
3956 printf("New entry at %s:%d: NULL config\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003957 sourcePos.file.c_str(), sourcePos.line);
Andreas Gampe2412f842014-09-30 20:55:57 -07003958 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003959 }
3960 e = new Entry(entry, sourcePos);
3961 c->addEntry(cdesc, e);
3962 /*
3963 if (doSetIndex) {
3964 if (pos < 0) {
3965 for (pos=0; pos<(int)mOrderedConfigs.size(); pos++) {
3966 if (mOrderedConfigs[pos] == c) {
3967 break;
3968 }
3969 }
3970 if (pos >= (int)mOrderedConfigs.size()) {
3971 sourcePos.error("Internal error: config not found in mOrderedConfigs when adding entry");
3972 return NULL;
3973 }
3974 }
3975 e->setEntryIndex(pos);
3976 }
3977 */
3978 }
3979
Adam Lesinski282e1812014-01-23 18:17:42 -08003980 return e;
3981}
3982
Adam Lesinski9b624c12014-11-19 17:49:26 -08003983sp<ResourceTable::ConfigList> ResourceTable::Type::removeEntry(const String16& entry) {
3984 ssize_t idx = mConfigs.indexOfKey(entry);
3985 if (idx < 0) {
3986 return NULL;
3987 }
3988
3989 sp<ConfigList> removed = mConfigs.valueAt(idx);
3990 mConfigs.removeItemsAt(idx);
3991
3992 Vector<sp<ConfigList> >::iterator iter = std::find(
3993 mOrderedConfigs.begin(), mOrderedConfigs.end(), removed);
3994 if (iter != mOrderedConfigs.end()) {
3995 mOrderedConfigs.erase(iter);
3996 }
3997
3998 mPublic.removeItem(entry);
3999 return removed;
4000}
4001
4002SortedVector<ConfigDescription> ResourceTable::Type::getUniqueConfigs() const {
4003 SortedVector<ConfigDescription> unique;
4004 const size_t entryCount = mOrderedConfigs.size();
4005 for (size_t i = 0; i < entryCount; i++) {
4006 if (mOrderedConfigs[i] == NULL) {
4007 continue;
4008 }
4009 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& configs =
4010 mOrderedConfigs[i]->getEntries();
4011 const size_t configCount = configs.size();
4012 for (size_t j = 0; j < configCount; j++) {
4013 unique.add(configs.keyAt(j));
4014 }
4015 }
4016 return unique;
4017}
4018
Adam Lesinski282e1812014-01-23 18:17:42 -08004019status_t ResourceTable::Type::applyPublicEntryOrder()
4020{
4021 size_t N = mOrderedConfigs.size();
4022 Vector<sp<ConfigList> > origOrder(mOrderedConfigs);
4023 bool hasError = false;
4024
4025 size_t i;
4026 for (i=0; i<N; i++) {
4027 mOrderedConfigs.replaceAt(NULL, i);
4028 }
4029
4030 const size_t NP = mPublic.size();
4031 //printf("Ordering %d configs from %d public defs\n", N, NP);
4032 size_t j;
4033 for (j=0; j<NP; j++) {
4034 const String16& name = mPublic.keyAt(j);
4035 const Public& p = mPublic.valueAt(j);
4036 int32_t idx = Res_GETENTRY(p.ident);
4037 //printf("Looking for entry \"%s\"/\"%s\" (0x%08x) in %d...\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004038 // String8(mName).c_str(), String8(name).c_str(), p.ident, N);
Adam Lesinski282e1812014-01-23 18:17:42 -08004039 bool found = false;
4040 for (i=0; i<N; i++) {
4041 sp<ConfigList> e = origOrder.itemAt(i);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004042 //printf("#%d: \"%s\"\n", i, String8(e->getName()).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08004043 if (e->getName() == name) {
4044 if (idx >= (int32_t)mOrderedConfigs.size()) {
Adam Lesinski9b624c12014-11-19 17:49:26 -08004045 mOrderedConfigs.resize(idx + 1);
4046 }
4047
4048 if (mOrderedConfigs.itemAt(idx) == NULL) {
Adam Lesinski282e1812014-01-23 18:17:42 -08004049 e->setPublic(true);
4050 e->setPublicSourcePos(p.sourcePos);
4051 mOrderedConfigs.replaceAt(e, idx);
4052 origOrder.removeAt(i);
4053 N--;
4054 found = true;
4055 break;
4056 } else {
4057 sp<ConfigList> oe = mOrderedConfigs.itemAt(idx);
4058
4059 p.sourcePos.error("Multiple entry names declared for public entry"
4060 " identifier 0x%x in type %s (%s vs %s).\n"
4061 "%s:%d: Originally defined here.",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004062 idx+1, String8(mName).c_str(),
4063 String8(oe->getName()).c_str(),
4064 String8(name).c_str(),
4065 oe->getPublicSourcePos().file.c_str(),
Adam Lesinski282e1812014-01-23 18:17:42 -08004066 oe->getPublicSourcePos().line);
4067 hasError = true;
4068 }
4069 }
4070 }
4071
4072 if (!found) {
4073 p.sourcePos.error("Public symbol %s/%s declared here is not defined.",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004074 String8(mName).c_str(), String8(name).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08004075 hasError = true;
4076 }
4077 }
4078
4079 //printf("Copying back in %d non-public configs, have %d\n", N, origOrder.size());
4080
4081 if (N != origOrder.size()) {
4082 printf("Internal error: remaining private symbol count mismatch\n");
4083 N = origOrder.size();
4084 }
4085
4086 j = 0;
4087 for (i=0; i<N; i++) {
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -07004088 const sp<ConfigList>& e = origOrder.itemAt(i);
Adam Lesinski282e1812014-01-23 18:17:42 -08004089 // There will always be enough room for the remaining entries.
4090 while (mOrderedConfigs.itemAt(j) != NULL) {
4091 j++;
4092 }
4093 mOrderedConfigs.replaceAt(e, j);
4094 j++;
4095 }
4096
Andreas Gampe2412f842014-09-30 20:55:57 -07004097 return hasError ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08004098}
4099
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004100ResourceTable::Package::Package(const String16& name, size_t packageId)
4101 : mName(name), mPackageId(packageId),
Adam Lesinski282e1812014-01-23 18:17:42 -08004102 mTypeStringsMapping(0xffffffff),
4103 mKeyStringsMapping(0xffffffff)
4104{
4105}
4106
4107sp<ResourceTable::Type> ResourceTable::Package::getType(const String16& type,
4108 const SourcePos& sourcePos,
4109 bool doSetIndex)
4110{
4111 sp<Type> t = mTypes.valueFor(type);
4112 if (t == NULL) {
4113 t = new Type(type, sourcePos);
4114 mTypes.add(type, t);
4115 mOrderedTypes.add(t);
4116 if (doSetIndex) {
4117 // For some reason the type's index is set to one plus the index
4118 // in the mOrderedTypes list, rather than just the index.
4119 t->setIndex(mOrderedTypes.size());
4120 }
4121 }
4122 return t;
4123}
4124
4125status_t ResourceTable::Package::setTypeStrings(const sp<AaptFile>& data)
4126{
Adam Lesinski282e1812014-01-23 18:17:42 -08004127 status_t err = setStrings(data, &mTypeStrings, &mTypeStringsMapping);
4128 if (err != NO_ERROR) {
4129 fprintf(stderr, "ERROR: Type string data is corrupt!\n");
Adam Lesinski57079512014-07-29 11:51:35 -07004130 return err;
Adam Lesinski282e1812014-01-23 18:17:42 -08004131 }
Adam Lesinski57079512014-07-29 11:51:35 -07004132
4133 // Retain a reference to the new data after we've successfully replaced
4134 // all uses of the old reference (in setStrings() ).
4135 mTypeStringsData = data;
4136 return NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08004137}
4138
4139status_t ResourceTable::Package::setKeyStrings(const sp<AaptFile>& data)
4140{
Adam Lesinski282e1812014-01-23 18:17:42 -08004141 status_t err = setStrings(data, &mKeyStrings, &mKeyStringsMapping);
4142 if (err != NO_ERROR) {
4143 fprintf(stderr, "ERROR: Key string data is corrupt!\n");
Adam Lesinski57079512014-07-29 11:51:35 -07004144 return err;
Adam Lesinski282e1812014-01-23 18:17:42 -08004145 }
Adam Lesinski57079512014-07-29 11:51:35 -07004146
4147 // Retain a reference to the new data after we've successfully replaced
4148 // all uses of the old reference (in setStrings() ).
4149 mKeyStringsData = data;
4150 return NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08004151}
4152
4153status_t ResourceTable::Package::setStrings(const sp<AaptFile>& data,
4154 ResStringPool* strings,
4155 DefaultKeyedVector<String16, uint32_t>* mappings)
4156{
4157 if (data->getData() == NULL) {
4158 return UNKNOWN_ERROR;
4159 }
4160
Adam Lesinski282e1812014-01-23 18:17:42 -08004161 status_t err = strings->setTo(data->getData(), data->getSize());
4162 if (err == NO_ERROR) {
4163 const size_t N = strings->size();
4164 for (size_t i=0; i<N; i++) {
4165 size_t len;
Ryan Mitchell80094e32020-11-16 23:08:18 +00004166 mappings->add(String16(UnpackOptionalString(strings->stringAt(i), &len)), i);
Adam Lesinski282e1812014-01-23 18:17:42 -08004167 }
4168 }
4169 return err;
4170}
4171
4172status_t ResourceTable::Package::applyPublicTypeOrder()
4173{
4174 size_t N = mOrderedTypes.size();
4175 Vector<sp<Type> > origOrder(mOrderedTypes);
4176
4177 size_t i;
4178 for (i=0; i<N; i++) {
4179 mOrderedTypes.replaceAt(NULL, i);
4180 }
4181
4182 for (i=0; i<N; i++) {
4183 sp<Type> t = origOrder.itemAt(i);
4184 int32_t idx = t->getPublicIndex();
4185 if (idx > 0) {
4186 idx--;
4187 while (idx >= (int32_t)mOrderedTypes.size()) {
4188 mOrderedTypes.add();
4189 }
4190 if (mOrderedTypes.itemAt(idx) != NULL) {
4191 sp<Type> ot = mOrderedTypes.itemAt(idx);
4192 t->getFirstPublicSourcePos().error("Multiple type names declared for public type"
4193 " identifier 0x%x (%s vs %s).\n"
4194 "%s:%d: Originally defined here.",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004195 idx, String8(ot->getName()).c_str(),
4196 String8(t->getName()).c_str(),
4197 ot->getFirstPublicSourcePos().file.c_str(),
Adam Lesinski282e1812014-01-23 18:17:42 -08004198 ot->getFirstPublicSourcePos().line);
4199 return UNKNOWN_ERROR;
4200 }
4201 mOrderedTypes.replaceAt(t, idx);
4202 origOrder.removeAt(i);
4203 i--;
4204 N--;
4205 }
4206 }
4207
4208 size_t j=0;
4209 for (i=0; i<N; i++) {
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -07004210 const sp<Type>& t = origOrder.itemAt(i);
Adam Lesinski282e1812014-01-23 18:17:42 -08004211 // There will always be enough room for the remaining types.
4212 while (mOrderedTypes.itemAt(j) != NULL) {
4213 j++;
4214 }
4215 mOrderedTypes.replaceAt(t, j);
4216 }
4217
4218 return NO_ERROR;
4219}
4220
Adam Lesinski9b624c12014-11-19 17:49:26 -08004221void ResourceTable::Package::movePrivateAttrs() {
4222 sp<Type> attr = mTypes.valueFor(String16("attr"));
4223 if (attr == NULL) {
4224 // Nothing to do.
4225 return;
4226 }
4227
4228 Vector<sp<ConfigList> > privateAttrs;
4229
4230 bool hasPublic = false;
4231 const Vector<sp<ConfigList> >& configs = attr->getOrderedConfigs();
4232 const size_t configCount = configs.size();
4233 for (size_t i = 0; i < configCount; i++) {
4234 if (configs[i] == NULL) {
4235 continue;
4236 }
4237
4238 if (attr->isPublic(configs[i]->getName())) {
4239 hasPublic = true;
4240 } else {
4241 privateAttrs.add(configs[i]);
4242 }
4243 }
4244
4245 // Only if we have public attributes do we create a separate type for
4246 // private attributes.
4247 if (!hasPublic) {
4248 return;
4249 }
4250
4251 // Create a new type for private attributes.
4252 sp<Type> privateAttrType = getType(String16(kAttrPrivateType), SourcePos());
4253
4254 const size_t privateAttrCount = privateAttrs.size();
4255 for (size_t i = 0; i < privateAttrCount; i++) {
4256 const sp<ConfigList>& cl = privateAttrs[i];
4257
4258 // Remove the private attributes from their current type.
4259 attr->removeEntry(cl->getName());
4260
4261 // Add it to the new type.
4262 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& entries = cl->getEntries();
4263 const size_t entryCount = entries.size();
4264 for (size_t j = 0; j < entryCount; j++) {
4265 const sp<Entry>& oldEntry = entries[j];
4266 sp<Entry> entry = privateAttrType->getEntry(
4267 cl->getName(), oldEntry->getPos(), &entries.keyAt(j));
4268 *entry = *oldEntry;
4269 }
4270
4271 // Move the symbols to the new type.
4272
4273 }
4274}
4275
Adam Lesinski282e1812014-01-23 18:17:42 -08004276sp<ResourceTable::Package> ResourceTable::getPackage(const String16& package)
4277{
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004278 if (package != mAssetsPackage) {
4279 return NULL;
Adam Lesinski282e1812014-01-23 18:17:42 -08004280 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004281 return mPackages.valueFor(package);
Adam Lesinski282e1812014-01-23 18:17:42 -08004282}
4283
4284sp<ResourceTable::Type> ResourceTable::getType(const String16& package,
4285 const String16& type,
4286 const SourcePos& sourcePos,
4287 bool doSetIndex)
4288{
4289 sp<Package> p = getPackage(package);
4290 if (p == NULL) {
4291 return NULL;
4292 }
4293 return p->getType(type, sourcePos, doSetIndex);
4294}
4295
4296sp<ResourceTable::Entry> ResourceTable::getEntry(const String16& package,
4297 const String16& type,
4298 const String16& name,
4299 const SourcePos& sourcePos,
4300 bool overlay,
4301 const ResTable_config* config,
4302 bool doSetIndex)
4303{
4304 sp<Type> t = getType(package, type, sourcePos, doSetIndex);
4305 if (t == NULL) {
4306 return NULL;
4307 }
4308 return t->getEntry(name, sourcePos, config, doSetIndex, overlay, mBundle->getAutoAddOverlay());
4309}
4310
Adam Lesinskie572c012014-09-19 15:10:04 -07004311sp<ResourceTable::ConfigList> ResourceTable::getConfigList(const String16& package,
4312 const String16& type, const String16& name) const
4313{
4314 const size_t packageCount = mOrderedPackages.size();
4315 for (size_t pi = 0; pi < packageCount; pi++) {
4316 const sp<Package>& p = mOrderedPackages[pi];
4317 if (p == NULL || p->getName() != package) {
4318 continue;
4319 }
4320
4321 const Vector<sp<Type> >& types = p->getOrderedTypes();
4322 const size_t typeCount = types.size();
4323 for (size_t ti = 0; ti < typeCount; ti++) {
4324 const sp<Type>& t = types[ti];
4325 if (t == NULL || t->getName() != type) {
4326 continue;
4327 }
4328
4329 const Vector<sp<ConfigList> >& configs = t->getOrderedConfigs();
4330 const size_t configCount = configs.size();
4331 for (size_t ci = 0; ci < configCount; ci++) {
4332 const sp<ConfigList>& cl = configs[ci];
4333 if (cl == NULL || cl->getName() != name) {
4334 continue;
4335 }
4336
4337 return cl;
4338 }
4339 }
4340 }
4341 return NULL;
4342}
4343
Adam Lesinski282e1812014-01-23 18:17:42 -08004344sp<const ResourceTable::Entry> ResourceTable::getEntry(uint32_t resID,
4345 const ResTable_config* config) const
4346{
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004347 size_t pid = Res_GETPACKAGE(resID)+1;
Adam Lesinski282e1812014-01-23 18:17:42 -08004348 const size_t N = mOrderedPackages.size();
Adam Lesinski282e1812014-01-23 18:17:42 -08004349 sp<Package> p;
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004350 for (size_t i = 0; i < N; i++) {
Adam Lesinski282e1812014-01-23 18:17:42 -08004351 sp<Package> check = mOrderedPackages[i];
4352 if (check->getAssignedId() == pid) {
4353 p = check;
4354 break;
4355 }
4356
4357 }
4358 if (p == NULL) {
4359 fprintf(stderr, "warning: Package not found for resource #%08x\n", resID);
4360 return NULL;
4361 }
4362
4363 int tid = Res_GETTYPE(resID);
4364 if (tid < 0 || tid >= (int)p->getOrderedTypes().size()) {
4365 fprintf(stderr, "warning: Type not found for resource #%08x\n", resID);
4366 return NULL;
4367 }
4368 sp<Type> t = p->getOrderedTypes()[tid];
4369
4370 int eid = Res_GETENTRY(resID);
4371 if (eid < 0 || eid >= (int)t->getOrderedConfigs().size()) {
4372 fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
4373 return NULL;
4374 }
4375
4376 sp<ConfigList> c = t->getOrderedConfigs()[eid];
4377 if (c == NULL) {
4378 fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
4379 return NULL;
4380 }
4381
4382 ConfigDescription cdesc;
4383 if (config) cdesc = *config;
4384 sp<Entry> e = c->getEntries().valueFor(cdesc);
4385 if (c == NULL) {
4386 fprintf(stderr, "warning: Entry configuration not found for resource #%08x\n", resID);
4387 return NULL;
4388 }
4389
4390 return e;
4391}
4392
4393const ResourceTable::Item* ResourceTable::getItem(uint32_t resID, uint32_t attrID) const
4394{
4395 sp<const Entry> e = getEntry(resID);
4396 if (e == NULL) {
4397 return NULL;
4398 }
4399
4400 const size_t N = e->getBag().size();
4401 for (size_t i=0; i<N; i++) {
4402 const Item& it = e->getBag().valueAt(i);
4403 if (it.bagKeyId == 0) {
4404 fprintf(stderr, "warning: ID not yet assigned to '%s' in bag '%s'\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004405 String8(e->getName()).c_str(),
4406 String8(e->getBag().keyAt(i)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08004407 }
4408 if (it.bagKeyId == attrID) {
4409 return &it;
4410 }
4411 }
4412
4413 return NULL;
4414}
4415
4416bool ResourceTable::getItemValue(
4417 uint32_t resID, uint32_t attrID, Res_value* outValue)
4418{
4419 const Item* item = getItem(resID, attrID);
4420
4421 bool res = false;
4422 if (item != NULL) {
4423 if (item->evaluating) {
4424 sp<const Entry> e = getEntry(resID);
4425 const size_t N = e->getBag().size();
4426 size_t i;
4427 for (i=0; i<N; i++) {
4428 if (&e->getBag().valueAt(i) == item) {
4429 break;
4430 }
4431 }
4432 fprintf(stderr, "warning: Circular reference detected in key '%s' of bag '%s'\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004433 String8(e->getName()).c_str(),
4434 String8(e->getBag().keyAt(i)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08004435 return false;
4436 }
4437 item->evaluating = true;
4438 res = stringToValue(outValue, NULL, item->value, false, false, item->bagKeyId);
Andreas Gampe2412f842014-09-30 20:55:57 -07004439 if (kIsDebug) {
Adam Lesinski282e1812014-01-23 18:17:42 -08004440 if (res) {
4441 printf("getItemValue of #%08x[#%08x] (%s): type=#%08x, data=#%08x\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004442 resID, attrID, String8(getEntry(resID)->getName()).c_str(),
Adam Lesinski282e1812014-01-23 18:17:42 -08004443 outValue->dataType, outValue->data);
4444 } else {
4445 printf("getItemValue of #%08x[#%08x]: failed\n",
4446 resID, attrID);
4447 }
Andreas Gampe2412f842014-09-30 20:55:57 -07004448 }
Adam Lesinski282e1812014-01-23 18:17:42 -08004449 item->evaluating = false;
4450 }
4451 return res;
4452}
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004453
4454/**
Adam Lesinski28994d82015-01-13 13:42:41 -08004455 * Returns the SDK version at which the attribute was
4456 * made public, or -1 if the resource ID is not an attribute
4457 * or is not public.
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004458 */
Adam Lesinski28994d82015-01-13 13:42:41 -08004459int ResourceTable::getPublicAttributeSdkLevel(uint32_t attrId) const {
4460 if (Res_GETPACKAGE(attrId) + 1 != 0x01 || Res_GETTYPE(attrId) + 1 != 0x01) {
4461 return -1;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004462 }
4463
4464 uint32_t specFlags;
4465 if (!mAssets->getIncludedResources().getResourceFlags(attrId, &specFlags)) {
Adam Lesinski28994d82015-01-13 13:42:41 -08004466 return -1;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004467 }
4468
Adam Lesinski28994d82015-01-13 13:42:41 -08004469 if ((specFlags & ResTable_typeSpec::SPEC_PUBLIC) == 0) {
4470 return -1;
4471 }
4472
4473 const size_t entryId = Res_GETENTRY(attrId);
4474 if (entryId <= 0x021c) {
4475 return 1;
4476 } else if (entryId <= 0x021d) {
4477 return 2;
4478 } else if (entryId <= 0x0269) {
4479 return SDK_CUPCAKE;
4480 } else if (entryId <= 0x028d) {
4481 return SDK_DONUT;
4482 } else if (entryId <= 0x02ad) {
4483 return SDK_ECLAIR;
4484 } else if (entryId <= 0x02b3) {
4485 return SDK_ECLAIR_0_1;
4486 } else if (entryId <= 0x02b5) {
4487 return SDK_ECLAIR_MR1;
4488 } else if (entryId <= 0x02bd) {
4489 return SDK_FROYO;
4490 } else if (entryId <= 0x02cb) {
4491 return SDK_GINGERBREAD;
4492 } else if (entryId <= 0x0361) {
4493 return SDK_HONEYCOMB;
4494 } else if (entryId <= 0x0366) {
4495 return SDK_HONEYCOMB_MR1;
4496 } else if (entryId <= 0x03a6) {
4497 return SDK_HONEYCOMB_MR2;
4498 } else if (entryId <= 0x03ae) {
4499 return SDK_JELLY_BEAN;
4500 } else if (entryId <= 0x03cc) {
4501 return SDK_JELLY_BEAN_MR1;
4502 } else if (entryId <= 0x03da) {
4503 return SDK_JELLY_BEAN_MR2;
4504 } else if (entryId <= 0x03f1) {
4505 return SDK_KITKAT;
4506 } else if (entryId <= 0x03f6) {
4507 return SDK_KITKAT_WATCH;
4508 } else if (entryId <= 0x04ce) {
4509 return SDK_LOLLIPOP;
4510 } else {
4511 // Anything else is marked as defined in
4512 // SDK_LOLLIPOP_MR1 since after this
4513 // version no attribute compat work
4514 // needs to be done.
4515 return SDK_LOLLIPOP_MR1;
4516 }
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004517}
4518
Adam Lesinski28994d82015-01-13 13:42:41 -08004519/**
4520 * First check the Manifest, then check the command line flag.
4521 */
4522static int getMinSdkVersion(const Bundle* bundle) {
4523 if (bundle->getManifestMinSdkVersion() != NULL && strlen(bundle->getManifestMinSdkVersion()) > 0) {
4524 return atoi(bundle->getManifestMinSdkVersion());
4525 } else if (bundle->getMinSdkVersion() != NULL && strlen(bundle->getMinSdkVersion()) > 0) {
4526 return atoi(bundle->getMinSdkVersion());
Adam Lesinskie572c012014-09-19 15:10:04 -07004527 }
Adam Lesinski28994d82015-01-13 13:42:41 -08004528 return 0;
Adam Lesinskie572c012014-09-19 15:10:04 -07004529}
4530
Adam Lesinskibeb9e332015-08-14 13:16:18 -07004531bool ResourceTable::shouldGenerateVersionedResource(
4532 const sp<ResourceTable::ConfigList>& configList,
4533 const ConfigDescription& sourceConfig,
4534 const int sdkVersionToGenerate) {
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004535 assert(sdkVersionToGenerate > sourceConfig.sdkVersion);
Adam Lesinski526d73b2016-07-18 17:01:14 -07004536 assert(configList != NULL);
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004537 const DefaultKeyedVector<ConfigDescription, sp<ResourceTable::Entry>>& entries
4538 = configList->getEntries();
4539 ssize_t idx = entries.indexOfKey(sourceConfig);
4540
4541 // The source config came from this list, so it should be here.
4542 assert(idx >= 0);
4543
Adam Lesinskibeb9e332015-08-14 13:16:18 -07004544 // The next configuration either only varies in sdkVersion, or it is completely different
4545 // and therefore incompatible. If it is incompatible, we must generate the versioned resource.
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004546
Adam Lesinskibeb9e332015-08-14 13:16:18 -07004547 // NOTE: The ordering of configurations takes sdkVersion as higher precedence than other
4548 // qualifiers, so we need to iterate through the entire list to be sure there
4549 // are no higher sdk level versions of this resource.
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004550 ConfigDescription tempConfig(sourceConfig);
Adam Lesinskibeb9e332015-08-14 13:16:18 -07004551 for (size_t i = static_cast<size_t>(idx) + 1; i < entries.size(); i++) {
4552 const ConfigDescription& nextConfig = entries.keyAt(i);
4553 tempConfig.sdkVersion = nextConfig.sdkVersion;
4554 if (tempConfig == nextConfig) {
4555 // The two configs are the same, check the sdk version.
4556 return sdkVersionToGenerate < nextConfig.sdkVersion;
4557 }
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004558 }
Adam Lesinskibeb9e332015-08-14 13:16:18 -07004559
4560 // No match was found, so we should generate the versioned resource.
4561 return true;
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004562}
4563
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004564/**
4565 * Modifies the entries in the resource table to account for compatibility
4566 * issues with older versions of Android.
4567 *
4568 * This primarily handles the issue of private/public attribute clashes
4569 * in framework resources.
4570 *
4571 * AAPT has traditionally assigned resource IDs to public attributes,
4572 * and then followed those public definitions with private attributes.
4573 *
4574 * --- PUBLIC ---
4575 * | 0x01010234 | attr/color
4576 * | 0x01010235 | attr/background
4577 *
4578 * --- PRIVATE ---
4579 * | 0x01010236 | attr/secret
4580 * | 0x01010237 | attr/shhh
4581 *
4582 * Each release, when attributes are added, they take the place of the private
4583 * attributes and the private attributes are shifted down again.
4584 *
4585 * --- PUBLIC ---
4586 * | 0x01010234 | attr/color
4587 * | 0x01010235 | attr/background
4588 * | 0x01010236 | attr/shinyNewAttr
4589 * | 0x01010237 | attr/highlyValuedFeature
4590 *
4591 * --- PRIVATE ---
4592 * | 0x01010238 | attr/secret
4593 * | 0x01010239 | attr/shhh
4594 *
4595 * Platform code may look for private attributes set in a theme. If an app
4596 * compiled against a newer version of the platform uses a new public
4597 * attribute that happens to have the same ID as the private attribute
4598 * the older platform is expecting, then the behavior is undefined.
4599 *
4600 * We get around this by detecting any newly defined attributes (in L),
4601 * copy the resource into a -v21 qualified resource, and delete the
4602 * attribute from the original resource. This ensures that older platforms
4603 * don't see the new attribute, but when running on L+ platforms, the
4604 * attribute will be respected.
4605 */
4606status_t ResourceTable::modifyForCompat(const Bundle* bundle) {
Adam Lesinski28994d82015-01-13 13:42:41 -08004607 const int minSdk = getMinSdkVersion(bundle);
4608 if (minSdk >= SDK_LOLLIPOP_MR1) {
4609 // Lollipop MR1 and up handles public attributes differently, no
4610 // need to do any compat modifications.
Adam Lesinskie572c012014-09-19 15:10:04 -07004611 return NO_ERROR;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004612 }
4613
4614 const String16 attr16("attr");
4615
4616 const size_t packageCount = mOrderedPackages.size();
4617 for (size_t pi = 0; pi < packageCount; pi++) {
4618 sp<Package> p = mOrderedPackages.itemAt(pi);
4619 if (p == NULL || p->getTypes().size() == 0) {
4620 // Empty, skip!
4621 continue;
4622 }
4623
4624 const size_t typeCount = p->getOrderedTypes().size();
4625 for (size_t ti = 0; ti < typeCount; ti++) {
4626 sp<Type> t = p->getOrderedTypes().itemAt(ti);
4627 if (t == NULL) {
4628 continue;
4629 }
4630
4631 const size_t configCount = t->getOrderedConfigs().size();
4632 for (size_t ci = 0; ci < configCount; ci++) {
4633 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
4634 if (c == NULL) {
4635 continue;
4636 }
4637
4638 Vector<key_value_pair_t<ConfigDescription, sp<Entry> > > entriesToAdd;
4639 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& entries =
4640 c->getEntries();
4641 const size_t entryCount = entries.size();
4642 for (size_t ei = 0; ei < entryCount; ei++) {
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -07004643 const sp<Entry>& e = entries.valueAt(ei);
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004644 if (e == NULL || e->getType() != Entry::TYPE_BAG) {
4645 continue;
4646 }
4647
4648 const ConfigDescription& config = entries.keyAt(ei);
Adam Lesinski28994d82015-01-13 13:42:41 -08004649 if (config.sdkVersion >= SDK_LOLLIPOP_MR1) {
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004650 continue;
4651 }
4652
Adam Lesinski28994d82015-01-13 13:42:41 -08004653 KeyedVector<int, Vector<String16> > attributesToRemove;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004654 const KeyedVector<String16, Item>& bag = e->getBag();
4655 const size_t bagCount = bag.size();
4656 for (size_t bi = 0; bi < bagCount; bi++) {
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004657 const uint32_t attrId = getResId(bag.keyAt(bi), &attr16);
Adam Lesinski28994d82015-01-13 13:42:41 -08004658 const int sdkLevel = getPublicAttributeSdkLevel(attrId);
4659 if (sdkLevel > 1 && sdkLevel > config.sdkVersion && sdkLevel > minSdk) {
4660 AaptUtil::appendValue(attributesToRemove, sdkLevel, bag.keyAt(bi));
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004661 }
4662 }
4663
4664 if (attributesToRemove.isEmpty()) {
4665 continue;
4666 }
4667
Adam Lesinski28994d82015-01-13 13:42:41 -08004668 const size_t sdkCount = attributesToRemove.size();
4669 for (size_t i = 0; i < sdkCount; i++) {
4670 const int sdkLevel = attributesToRemove.keyAt(i);
4671
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004672 if (!shouldGenerateVersionedResource(c, config, sdkLevel)) {
4673 // There is a style that will override this generated one.
4674 continue;
4675 }
4676
Adam Lesinski28994d82015-01-13 13:42:41 -08004677 // Duplicate the entry under the same configuration
4678 // but with sdkVersion == sdkLevel.
4679 ConfigDescription newConfig(config);
4680 newConfig.sdkVersion = sdkLevel;
4681
4682 sp<Entry> newEntry = new Entry(*e);
4683
4684 // Remove all items that have a higher SDK level than
4685 // the one we are synthesizing.
4686 for (size_t j = 0; j < sdkCount; j++) {
4687 if (j == i) {
4688 continue;
4689 }
4690
4691 if (attributesToRemove.keyAt(j) > sdkLevel) {
4692 const size_t attrCount = attributesToRemove[j].size();
4693 for (size_t k = 0; k < attrCount; k++) {
4694 newEntry->removeFromBag(attributesToRemove[j][k]);
4695 }
4696 }
4697 }
4698
4699 entriesToAdd.add(key_value_pair_t<ConfigDescription, sp<Entry> >(
4700 newConfig, newEntry));
4701 }
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004702
4703 // Remove the attribute from the original.
4704 for (size_t i = 0; i < attributesToRemove.size(); i++) {
Adam Lesinski28994d82015-01-13 13:42:41 -08004705 for (size_t j = 0; j < attributesToRemove[i].size(); j++) {
4706 e->removeFromBag(attributesToRemove[i][j]);
4707 }
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004708 }
4709 }
4710
4711 const size_t entriesToAddCount = entriesToAdd.size();
4712 for (size_t i = 0; i < entriesToAddCount; i++) {
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004713 assert(entries.indexOfKey(entriesToAdd[i].key) < 0);
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004714
Adam Lesinskif15de2e2014-10-03 14:57:28 -07004715 if (bundle->getVerbose()) {
4716 entriesToAdd[i].value->getPos()
4717 .printf("using v%d attributes; synthesizing resource %s:%s/%s for configuration %s.",
Adam Lesinski28994d82015-01-13 13:42:41 -08004718 entriesToAdd[i].key.sdkVersion,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004719 String8(p->getName()).c_str(),
4720 String8(t->getName()).c_str(),
4721 String8(entriesToAdd[i].value->getName()).c_str(),
4722 entriesToAdd[i].key.toString().c_str());
Adam Lesinskif15de2e2014-10-03 14:57:28 -07004723 }
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004724
Adam Lesinski978ab9d2014-09-24 19:02:52 -07004725 sp<Entry> newEntry = t->getEntry(c->getName(),
4726 entriesToAdd[i].value->getPos(),
4727 &entriesToAdd[i].key);
4728
4729 *newEntry = *entriesToAdd[i].value;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004730 }
4731 }
4732 }
4733 }
4734 return NO_ERROR;
4735}
Adam Lesinskie572c012014-09-19 15:10:04 -07004736
Yuichi Araki4d35cca2017-01-18 20:42:17 +09004737const String16 kTransitionElements[] = {
4738 String16("fade"),
4739 String16("changeBounds"),
4740 String16("slide"),
4741 String16("explode"),
4742 String16("changeImageTransform"),
4743 String16("changeTransform"),
4744 String16("changeClipBounds"),
4745 String16("autoTransition"),
4746 String16("recolor"),
4747 String16("changeScroll"),
4748 String16("transitionSet"),
4749 String16("transition"),
4750 String16("transitionManager"),
4751};
4752
4753static bool IsTransitionElement(const String16& name) {
4754 for (int i = 0, size = sizeof(kTransitionElements) / sizeof(kTransitionElements[0]);
4755 i < size; ++i) {
4756 if (name == kTransitionElements[i]) {
4757 return true;
4758 }
4759 }
4760 return false;
4761}
4762
Adam Lesinskicf1f1d92017-03-16 16:54:23 -07004763bool ResourceTable::versionForCompat(const Bundle* bundle, const String16& resourceName,
4764 const sp<AaptFile>& target, const sp<XMLNode>& root) {
4765 XMLNode* node = root.get();
4766 while (node->getType() != XMLNode::TYPE_ELEMENT) {
4767 // We're assuming the root element is what we're looking for, which can only be under a
4768 // bunch of namespace declarations.
4769 if (node->getChildren().size() != 1) {
4770 // Not sure what to do, bail.
4771 return false;
4772 }
4773 node = node->getChildren().itemAt(0).get();
4774 }
4775
4776 if (node->getElementNamespace().size() != 0) {
4777 // Not something we care about.
4778 return false;
4779 }
4780
4781 int versionedSdk = 0;
4782 if (node->getElementName() == String16("adaptive-icon")) {
4783 versionedSdk = SDK_O;
4784 }
4785
4786 const int minSdkVersion = getMinSdkVersion(bundle);
4787 const ConfigDescription config(target->getGroupEntry().toParams());
4788 if (versionedSdk <= minSdkVersion || versionedSdk <= config.sdkVersion) {
4789 return false;
4790 }
4791
4792 sp<ConfigList> cl = getConfigList(String16(mAssets->getPackage()),
4793 String16(target->getResourceType()), resourceName);
4794 if (!shouldGenerateVersionedResource(cl, config, versionedSdk)) {
4795 return false;
4796 }
4797
4798 // Remove the original entry.
4799 cl->removeEntry(config);
4800
4801 // We need to wholesale version this file.
4802 ConfigDescription newConfig(config);
4803 newConfig.sdkVersion = versionedSdk;
4804 sp<AaptFile> newFile = new AaptFile(target->getSourceFile(),
4805 AaptGroupEntry(newConfig), target->getResourceType());
4806 String8 resPath = String8::format("res/%s/%s.xml",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004807 newFile->getGroupEntry().toDirName(target->getResourceType()).c_str(),
4808 String8(resourceName).c_str());
Elliott Hughes338698e2021-07-13 17:15:19 -07004809 convertToResPath(resPath);
Adam Lesinskicf1f1d92017-03-16 16:54:23 -07004810
4811 // Add a resource table entry.
4812 addEntry(SourcePos(),
4813 String16(mAssets->getPackage()),
4814 String16(target->getResourceType()),
4815 resourceName,
4816 String16(resPath),
4817 NULL,
4818 &newConfig);
4819
4820 // Schedule this to be compiled.
4821 CompileResourceWorkItem item;
4822 item.resourceName = resourceName;
4823 item.resPath = resPath;
4824 item.file = newFile;
4825 item.xmlRoot = root->clone();
Adam Lesinski54b58ba2017-04-14 18:44:30 -07004826 item.needsCompiling = true;
Adam Lesinskicf1f1d92017-03-16 16:54:23 -07004827 mWorkQueue.push(item);
4828
4829 // Now mark the old entry as deleted.
4830 return true;
4831}
4832
Adam Lesinskie572c012014-09-19 15:10:04 -07004833status_t ResourceTable::modifyForCompat(const Bundle* bundle,
4834 const String16& resourceName,
4835 const sp<AaptFile>& target,
4836 const sp<XMLNode>& root) {
Adam Lesinski6e460562015-04-21 14:20:15 -07004837 const String16 vector16("vector");
4838 const String16 animatedVector16("animated-vector");
ztenghui010df882017-03-07 15:50:03 -08004839 const String16 pathInterpolator16("pathInterpolator");
ztenghui20554852017-03-21 16:28:57 -07004840 const String16 objectAnimator16("objectAnimator");
ztenghuiab2a38c2017-10-13 15:56:08 -07004841 const String16 gradient16("gradient");
Nick Butchere78a8162018-01-09 15:24:21 +00004842 const String16 animatedSelector16("animated-selector");
Adam Lesinski6e460562015-04-21 14:20:15 -07004843
Adam Lesinski28994d82015-01-13 13:42:41 -08004844 const int minSdk = getMinSdkVersion(bundle);
4845 if (minSdk >= SDK_LOLLIPOP_MR1) {
4846 // Lollipop MR1 and up handles public attributes differently, no
4847 // need to do any compat modifications.
Adam Lesinskie572c012014-09-19 15:10:04 -07004848 return NO_ERROR;
4849 }
4850
Adam Lesinski28994d82015-01-13 13:42:41 -08004851 const ConfigDescription config(target->getGroupEntry().toParams());
4852 if (target->getResourceType() == "" || config.sdkVersion >= SDK_LOLLIPOP_MR1) {
Adam Lesinski6e460562015-04-21 14:20:15 -07004853 // Skip resources that have no type (AndroidManifest.xml) or are already version qualified
4854 // with v21 or higher.
Adam Lesinskie572c012014-09-19 15:10:04 -07004855 return NO_ERROR;
4856 }
4857
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004858 sp<XMLNode> newRoot = NULL;
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004859 int sdkVersionToGenerate = SDK_LOLLIPOP_MR1;
Adam Lesinskie572c012014-09-19 15:10:04 -07004860
4861 Vector<sp<XMLNode> > nodesToVisit;
4862 nodesToVisit.push(root);
Tomasz Wasilczyk7e22cab2023-08-24 19:02:33 +00004863 while (!nodesToVisit.empty()) {
Adam Lesinskie572c012014-09-19 15:10:04 -07004864 sp<XMLNode> node = nodesToVisit.top();
4865 nodesToVisit.pop();
4866
Adam Lesinski6e460562015-04-21 14:20:15 -07004867 if (bundle->getNoVersionVectors() && (node->getElementName() == vector16 ||
ztenghui010df882017-03-07 15:50:03 -08004868 node->getElementName() == animatedVector16 ||
ztenghui20554852017-03-21 16:28:57 -07004869 node->getElementName() == objectAnimator16 ||
ztenghuiab2a38c2017-10-13 15:56:08 -07004870 node->getElementName() == pathInterpolator16 ||
Nick Butchere78a8162018-01-09 15:24:21 +00004871 node->getElementName() == gradient16 ||
4872 node->getElementName() == animatedSelector16)) {
Adam Lesinski6e460562015-04-21 14:20:15 -07004873 // We were told not to version vector tags, so skip the children here.
4874 continue;
4875 }
4876
Yuichi Araki4d35cca2017-01-18 20:42:17 +09004877 if (bundle->getNoVersionTransitions() && (IsTransitionElement(node->getElementName()))) {
4878 // We were told not to version transition tags, so skip the children here.
4879 continue;
4880 }
4881
Adam Lesinskie572c012014-09-19 15:10:04 -07004882 const Vector<XMLNode::attribute_entry>& attrs = node->getAttributes();
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004883 for (size_t i = 0; i < attrs.size(); i++) {
Adam Lesinskie572c012014-09-19 15:10:04 -07004884 const XMLNode::attribute_entry& attr = attrs[i];
Adam Lesinski28994d82015-01-13 13:42:41 -08004885 const int sdkLevel = getPublicAttributeSdkLevel(attr.nameResId);
4886 if (sdkLevel > 1 && sdkLevel > config.sdkVersion && sdkLevel > minSdk) {
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004887 if (newRoot == NULL) {
4888 newRoot = root->clone();
4889 }
4890
Adam Lesinski28994d82015-01-13 13:42:41 -08004891 // Find the smallest sdk version that we need to synthesize for
4892 // and do that one. Subsequent versions will be processed on
4893 // the next pass.
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004894 sdkVersionToGenerate = std::min(sdkLevel, sdkVersionToGenerate);
Adam Lesinski28994d82015-01-13 13:42:41 -08004895
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004896 if (bundle->getVerbose()) {
4897 SourcePos(node->getFilename(), node->getStartLineNumber()).printf(
4898 "removing attribute %s%s%s from <%s>",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004899 String8(attr.ns).c_str(),
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004900 (attr.ns.size() == 0 ? "" : ":"),
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004901 String8(attr.name).c_str(),
4902 String8(node->getElementName()).c_str());
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004903 }
4904 node->removeAttribute(i);
4905 i--;
Adam Lesinskie572c012014-09-19 15:10:04 -07004906 }
4907 }
4908
4909 // Schedule a visit to the children.
4910 const Vector<sp<XMLNode> >& children = node->getChildren();
4911 const size_t childCount = children.size();
4912 for (size_t i = 0; i < childCount; i++) {
4913 nodesToVisit.push(children[i]);
4914 }
4915 }
4916
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004917 if (newRoot == NULL) {
Adam Lesinskie572c012014-09-19 15:10:04 -07004918 return NO_ERROR;
4919 }
4920
Adam Lesinskie572c012014-09-19 15:10:04 -07004921 // Look to see if we already have an overriding v21 configuration.
4922 sp<ConfigList> cl = getConfigList(String16(mAssets->getPackage()),
4923 String16(target->getResourceType()), resourceName);
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004924 if (shouldGenerateVersionedResource(cl, config, sdkVersionToGenerate)) {
Adam Lesinskie572c012014-09-19 15:10:04 -07004925 // We don't have an overriding entry for v21, so we must duplicate this one.
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004926 ConfigDescription newConfig(config);
4927 newConfig.sdkVersion = sdkVersionToGenerate;
Adam Lesinskie572c012014-09-19 15:10:04 -07004928 sp<AaptFile> newFile = new AaptFile(target->getSourceFile(),
4929 AaptGroupEntry(newConfig), target->getResourceType());
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07004930 String8 resPath = String8::format("res/%s/%s.xml",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004931 newFile->getGroupEntry().toDirName(target->getResourceType()).c_str(),
4932 String8(resourceName).c_str());
Elliott Hughes338698e2021-07-13 17:15:19 -07004933 convertToResPath(resPath);
Adam Lesinskie572c012014-09-19 15:10:04 -07004934
4935 // Add a resource table entry.
Adam Lesinskif15de2e2014-10-03 14:57:28 -07004936 if (bundle->getVerbose()) {
4937 SourcePos(target->getSourceFile(), -1).printf(
4938 "using v%d attributes; synthesizing resource %s:%s/%s for configuration %s.",
Adam Lesinski28994d82015-01-13 13:42:41 -08004939 newConfig.sdkVersion,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004940 mAssets->getPackage().c_str(),
4941 newFile->getResourceType().c_str(),
4942 String8(resourceName).c_str(),
4943 newConfig.toString().c_str());
Adam Lesinskif15de2e2014-10-03 14:57:28 -07004944 }
Adam Lesinskie572c012014-09-19 15:10:04 -07004945
4946 addEntry(SourcePos(),
4947 String16(mAssets->getPackage()),
4948 String16(target->getResourceType()),
4949 resourceName,
4950 String16(resPath),
4951 NULL,
4952 &newConfig);
4953
4954 // Schedule this to be compiled.
4955 CompileResourceWorkItem item;
4956 item.resourceName = resourceName;
4957 item.resPath = resPath;
4958 item.file = newFile;
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07004959 item.xmlRoot = newRoot;
4960 item.needsCompiling = false; // This step occurs after we parse/assign, so we don't need
4961 // to do it again.
Adam Lesinskie572c012014-09-19 15:10:04 -07004962 mWorkQueue.push(item);
4963 }
Adam Lesinskie572c012014-09-19 15:10:04 -07004964 return NO_ERROR;
4965}
Adam Lesinskide7de472014-11-03 12:03:08 -08004966
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004967void ResourceTable::getDensityVaryingResources(
4968 KeyedVector<Symbol, Vector<SymbolDefinition> >& resources) {
Adam Lesinskide7de472014-11-03 12:03:08 -08004969 const ConfigDescription nullConfig;
4970
4971 const size_t packageCount = mOrderedPackages.size();
4972 for (size_t p = 0; p < packageCount; p++) {
4973 const Vector<sp<Type> >& types = mOrderedPackages[p]->getOrderedTypes();
4974 const size_t typeCount = types.size();
4975 for (size_t t = 0; t < typeCount; t++) {
Adam Lesinski081d1b42016-08-15 18:45:00 -07004976 const sp<Type>& type = types[t];
4977 if (type == NULL) {
4978 continue;
4979 }
4980
4981 const Vector<sp<ConfigList> >& configs = type->getOrderedConfigs();
Adam Lesinskide7de472014-11-03 12:03:08 -08004982 const size_t configCount = configs.size();
4983 for (size_t c = 0; c < configCount; c++) {
Adam Lesinski081d1b42016-08-15 18:45:00 -07004984 const sp<ConfigList>& configList = configs[c];
4985 if (configList == NULL) {
4986 continue;
4987 }
4988
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004989 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& configEntries
Adam Lesinski081d1b42016-08-15 18:45:00 -07004990 = configList->getEntries();
Adam Lesinskide7de472014-11-03 12:03:08 -08004991 const size_t configEntryCount = configEntries.size();
4992 for (size_t ce = 0; ce < configEntryCount; ce++) {
Adam Lesinski081d1b42016-08-15 18:45:00 -07004993 const sp<Entry>& entry = configEntries.valueAt(ce);
4994 if (entry == NULL) {
4995 continue;
4996 }
4997
Adam Lesinskide7de472014-11-03 12:03:08 -08004998 const ConfigDescription& config = configEntries.keyAt(ce);
4999 if (AaptConfig::isDensityOnly(config)) {
5000 // This configuration only varies with regards to density.
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07005001 const Symbol symbol(
5002 mOrderedPackages[p]->getName(),
Adam Lesinski081d1b42016-08-15 18:45:00 -07005003 type->getName(),
5004 configList->getName(),
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07005005 getResId(mOrderedPackages[p], types[t],
Adam Lesinski081d1b42016-08-15 18:45:00 -07005006 configList->getEntryIndex()));
Adam Lesinskide7de472014-11-03 12:03:08 -08005007
Adam Lesinski081d1b42016-08-15 18:45:00 -07005008
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07005009 AaptUtil::appendValue(resources, symbol,
5010 SymbolDefinition(symbol, config, entry->getPos()));
Adam Lesinskide7de472014-11-03 12:03:08 -08005011 }
5012 }
5013 }
5014 }
5015 }
5016}
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07005017
5018static String16 buildNamespace(const String16& package) {
5019 return String16("http://schemas.android.com/apk/res/") + package;
5020}
5021
5022static sp<XMLNode> findOnlyChildElement(const sp<XMLNode>& parent) {
5023 const Vector<sp<XMLNode> >& children = parent->getChildren();
5024 sp<XMLNode> onlyChild;
5025 for (size_t i = 0; i < children.size(); i++) {
5026 if (children[i]->getType() != XMLNode::TYPE_CDATA) {
5027 if (onlyChild != NULL) {
5028 return NULL;
5029 }
5030 onlyChild = children[i];
5031 }
5032 }
5033 return onlyChild;
5034}
5035
5036/**
5037 * Detects use of the `bundle' format and extracts nested resources into their own top level
5038 * resources. The bundle format looks like this:
5039 *
5040 * <!-- res/drawable/bundle.xml -->
5041 * <animated-vector xmlns:aapt="http://schemas.android.com/aapt">
5042 * <aapt:attr name="android:drawable">
5043 * <vector android:width="60dp"
5044 * android:height="60dp">
5045 * <path android:name="v"
5046 * android:fillColor="#000000"
5047 * android:pathData="M300,70 l 0,-70 70,..." />
5048 * </vector>
5049 * </aapt:attr>
5050 * </animated-vector>
5051 *
5052 * When AAPT sees the <aapt:attr> tag, it will extract its single element and its children
5053 * into a new high-level resource, assigning it a name and ID. Then value of the `name`
5054 * attribute must be a resource attribute. That resource attribute is inserted into the parent
5055 * with the reference to the extracted resource as the value.
5056 *
5057 * <!-- res/drawable/bundle.xml -->
5058 * <animated-vector android:drawable="@drawable/bundle_1.xml">
5059 * </animated-vector>
5060 *
5061 * <!-- res/drawable/bundle_1.xml -->
5062 * <vector android:width="60dp"
5063 * android:height="60dp">
5064 * <path android:name="v"
5065 * android:fillColor="#000000"
5066 * android:pathData="M300,70 l 0,-70 70,..." />
5067 * </vector>
5068 */
5069status_t ResourceTable::processBundleFormat(const Bundle* bundle,
5070 const String16& resourceName,
5071 const sp<AaptFile>& target,
5072 const sp<XMLNode>& root) {
5073 Vector<sp<XMLNode> > namespaces;
5074 if (root->getType() == XMLNode::TYPE_NAMESPACE) {
5075 namespaces.push(root);
5076 }
5077 return processBundleFormatImpl(bundle, resourceName, target, root, &namespaces);
5078}
5079
5080status_t ResourceTable::processBundleFormatImpl(const Bundle* bundle,
5081 const String16& resourceName,
5082 const sp<AaptFile>& target,
5083 const sp<XMLNode>& parent,
5084 Vector<sp<XMLNode> >* namespaces) {
5085 const String16 kAaptNamespaceUri16("http://schemas.android.com/aapt");
5086 const String16 kName16("name");
5087 const String16 kAttr16("attr");
5088 const String16 kAssetPackage16(mAssets->getPackage());
5089
5090 Vector<sp<XMLNode> >& children = parent->getChildren();
5091 for (size_t i = 0; i < children.size(); i++) {
5092 const sp<XMLNode>& child = children[i];
5093
5094 if (child->getType() == XMLNode::TYPE_CDATA) {
5095 continue;
5096 } else if (child->getType() == XMLNode::TYPE_NAMESPACE) {
5097 namespaces->push(child);
5098 }
5099
5100 if (child->getElementNamespace() != kAaptNamespaceUri16 ||
5101 child->getElementName() != kAttr16) {
5102 status_t result = processBundleFormatImpl(bundle, resourceName, target, child,
5103 namespaces);
5104 if (result != NO_ERROR) {
5105 return result;
5106 }
5107
5108 if (child->getType() == XMLNode::TYPE_NAMESPACE) {
5109 namespaces->pop();
5110 }
5111 continue;
5112 }
5113
5114 // This is the <aapt:attr> tag. Look for the 'name' attribute.
5115 SourcePos source(child->getFilename(), child->getStartLineNumber());
5116
5117 sp<XMLNode> nestedRoot = findOnlyChildElement(child);
5118 if (nestedRoot == NULL) {
5119 source.error("<%s:%s> must have exactly one child element",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00005120 String8(child->getElementNamespace()).c_str(),
5121 String8(child->getElementName()).c_str());
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07005122 return UNKNOWN_ERROR;
5123 }
5124
5125 // Find the special attribute 'parent-attr'. This attribute's value contains
5126 // the resource attribute for which this element should be assigned in the parent.
5127 const XMLNode::attribute_entry* attr = child->getAttribute(String16(), kName16);
5128 if (attr == NULL) {
5129 source.error("inline resource definition must specify an attribute via 'name'");
5130 return UNKNOWN_ERROR;
5131 }
5132
5133 // Parse the attribute name.
5134 const char* errorMsg = NULL;
5135 String16 attrPackage, attrType, attrName;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00005136 bool result = ResTable::expandResourceRef(attr->string.c_str(),
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07005137 attr->string.size(),
5138 &attrPackage, &attrType, &attrName,
5139 &kAttr16, &kAssetPackage16,
5140 &errorMsg, NULL);
5141 if (!result) {
5142 source.error("invalid attribute name for 'name': %s", errorMsg);
5143 return UNKNOWN_ERROR;
5144 }
5145
5146 if (attrType != kAttr16) {
5147 // The value of the 'name' attribute must be an attribute reference.
5148 source.error("value of 'name' must be an attribute reference.");
5149 return UNKNOWN_ERROR;
5150 }
5151
5152 // Generate a name for this nested resource and try to add it to the table.
5153 // We do this in a loop because the name may be taken, in which case we will
5154 // increment a suffix until we succeed.
5155 String8 nestedResourceName;
5156 String8 nestedResourcePath;
5157 int suffix = 1;
5158 while (true) {
5159 // This child element will be extracted into its own resource file.
5160 // Generate a name and path for it from its parent.
5161 nestedResourceName = String8::format("%s_%d",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00005162 String8(resourceName).c_str(), suffix++);
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07005163 nestedResourcePath = String8::format("res/%s/%s.xml",
5164 target->getGroupEntry().toDirName(target->getResourceType())
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00005165 .c_str(),
5166 nestedResourceName.c_str());
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07005167
5168 // Lookup or create the entry for this name.
5169 sp<Entry> entry = getEntry(kAssetPackage16,
5170 String16(target->getResourceType()),
5171 String16(nestedResourceName),
5172 source,
5173 false,
5174 &target->getGroupEntry().toParams(),
5175 true);
5176 if (entry == NULL) {
5177 return UNKNOWN_ERROR;
5178 }
5179
5180 if (entry->getType() == Entry::TYPE_UNKNOWN) {
5181 // The value for this resource has never been set,
5182 // meaning we're good!
5183 entry->setItem(source, String16(nestedResourcePath));
5184 break;
5185 }
5186
5187 // We failed (name already exists), so try with a different name
5188 // (increment the suffix).
5189 }
5190
5191 if (bundle->getVerbose()) {
5192 source.printf("generating nested resource %s:%s/%s",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00005193 mAssets->getPackage().c_str(), target->getResourceType().c_str(),
5194 nestedResourceName.c_str());
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07005195 }
5196
5197 // Build the attribute reference and assign it to the parent.
5198 String16 nestedResourceRef = String16(String8::format("@%s:%s/%s",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00005199 mAssets->getPackage().c_str(), target->getResourceType().c_str(),
5200 nestedResourceName.c_str()));
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07005201
5202 String16 attrNs = buildNamespace(attrPackage);
5203 if (parent->getAttribute(attrNs, attrName) != NULL) {
5204 SourcePos(parent->getFilename(), parent->getStartLineNumber())
5205 .error("parent of nested resource already defines attribute '%s:%s'",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00005206 String8(attrPackage).c_str(), String8(attrName).c_str());
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07005207 return UNKNOWN_ERROR;
5208 }
5209
5210 // Add the reference to the inline resource.
5211 parent->addAttribute(attrNs, attrName, nestedResourceRef);
5212
5213 // Remove the <aapt:attr> child element from here.
5214 children.removeAt(i);
5215 i--;
5216
5217 // Append all namespace declarations that we've seen on this branch in the XML tree
5218 // to this resource.
5219 // We do this because the order of namespace declarations and prefix usage is determined
5220 // by the developer and we do not want to override any decisions. Be conservative.
5221 for (size_t nsIndex = namespaces->size(); nsIndex > 0; nsIndex--) {
5222 const sp<XMLNode>& ns = namespaces->itemAt(nsIndex - 1);
5223 sp<XMLNode> newNs = XMLNode::newNamespace(ns->getFilename(), ns->getNamespacePrefix(),
5224 ns->getNamespaceUri());
5225 newNs->addChild(nestedRoot);
5226 nestedRoot = newNs;
5227 }
5228
5229 // Schedule compilation of the nested resource.
5230 CompileResourceWorkItem workItem;
5231 workItem.resPath = nestedResourcePath;
5232 workItem.resourceName = String16(nestedResourceName);
5233 workItem.xmlRoot = nestedRoot;
5234 workItem.file = new AaptFile(target->getSourceFile(), target->getGroupEntry(),
5235 target->getResourceType());
5236 mWorkQueue.push(workItem);
5237 }
5238 return NO_ERROR;
5239}