blob: 421cae78b08b0a8c45c2d9641096913033ba8ef3 [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) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001367 name.setTo(block.getAttributeStringValue(i, &length));
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001368 } else if (strcmp16(attr, translatable16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001369 translatable.setTo(block.getAttributeStringValue(i, &length));
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001370 } else if (strcmp16(attr, formatted16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001371 formatted.setTo(block.getAttributeStringValue(i, &length));
1372 }
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) {
1545 parentIdent.setTo(ident, sep);
1546 }
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) {
2835 config.setTo(start, comma - start);
2836 start = comma + 1;
2837 } else {
2838 config.setTo(start);
2839 }
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));
2897 if (packageId > 0x01 && packageId != 0x7f &&
2898 packageName != String16("android")) {
2899 libraryPackages.add(sp<Package>(new Package(packageName, packageId)));
2900 }
2901 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08002902
Adam Lesinski282e1812014-01-23 18:17:42 -08002903 // Iterate through all data, collecting all values (strings,
2904 // references, etc).
2905 StringPool valueStrings(useUTF8);
2906 Vector<sp<Entry> > allEntries;
2907 for (pi=0; pi<N; pi++) {
2908 sp<Package> p = mOrderedPackages.itemAt(pi);
2909 if (p->getTypes().size() == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002910 continue;
2911 }
2912
2913 StringPool typeStrings(useUTF8);
2914 StringPool keyStrings(useUTF8);
2915
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002916 ssize_t stringsAdded = 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08002917 const size_t N = p->getOrderedTypes().size();
2918 for (size_t ti=0; ti<N; ti++) {
2919 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2920 if (t == NULL) {
2921 typeStrings.add(String16("<empty>"), false);
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002922 stringsAdded++;
Adam Lesinski282e1812014-01-23 18:17:42 -08002923 continue;
2924 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002925
2926 while (stringsAdded < t->getIndex() - 1) {
2927 typeStrings.add(String16("<empty>"), false);
2928 stringsAdded++;
2929 }
2930
Adam Lesinski282e1812014-01-23 18:17:42 -08002931 const String16 typeName(t->getName());
2932 typeStrings.add(typeName, false);
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002933 stringsAdded++;
Adam Lesinski282e1812014-01-23 18:17:42 -08002934
2935 // This is a hack to tweak the sorting order of the final strings,
2936 // to put stuff that is generally not language-specific first.
2937 String8 configTypeName(typeName);
2938 if (configTypeName == "drawable" || configTypeName == "layout"
2939 || configTypeName == "color" || configTypeName == "anim"
2940 || configTypeName == "interpolator" || configTypeName == "animator"
2941 || configTypeName == "xml" || configTypeName == "menu"
2942 || configTypeName == "mipmap" || configTypeName == "raw") {
2943 configTypeName = "1complex";
2944 } else {
2945 configTypeName = "2value";
2946 }
2947
Adam Lesinski27f69f42014-08-21 13:19:12 -07002948 // mipmaps don't get filtered, so they will
2949 // allways end up in the base. Make sure they
2950 // don't end up in a split.
2951 if (typeName == mipmap16 && !isBase) {
2952 continue;
2953 }
2954
Adam Lesinski282e1812014-01-23 18:17:42 -08002955 const bool filterable = (typeName != mipmap16);
2956
2957 const size_t N = t->getOrderedConfigs().size();
2958 for (size_t ci=0; ci<N; ci++) {
2959 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2960 if (c == NULL) {
2961 continue;
2962 }
2963 const size_t N = c->getEntries().size();
2964 for (size_t ei=0; ei<N; ei++) {
2965 ConfigDescription config = c->getEntries().keyAt(ei);
Adam Lesinskifab50872014-04-16 14:40:42 -07002966 if (filterable && !filter->match(config)) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002967 continue;
2968 }
2969 sp<Entry> e = c->getEntries().valueAt(ei);
2970 if (e == NULL) {
2971 continue;
2972 }
2973 e->setNameIndex(keyStrings.add(e->getName(), true));
2974
Adam Lesinski282e1812014-01-23 18:17:42 -08002975 status_t err = e->prepareFlatten(&valueStrings, this,
2976 &configTypeName, &config);
2977 if (err != NO_ERROR) {
2978 return err;
2979 }
2980 allEntries.add(e);
2981 }
2982 }
2983 }
2984
2985 p->setTypeStrings(typeStrings.createStringBlock());
2986 p->setKeyStrings(keyStrings.createStringBlock());
2987 }
2988
2989 if (bundle->getOutputAPKFile() != NULL) {
2990 // Now we want to sort the value strings for better locality. This will
2991 // cause the positions of the strings to change, so we need to go back
2992 // through out resource entries and update them accordingly. Only need
2993 // to do this if actually writing the output file.
2994 valueStrings.sortByConfig();
2995 for (pi=0; pi<allEntries.size(); pi++) {
2996 allEntries[pi]->remapStringValue(&valueStrings);
2997 }
2998 }
2999
3000 ssize_t strAmt = 0;
Adam Lesinskide898ff2014-01-29 18:20:45 -08003001
Adam Lesinski282e1812014-01-23 18:17:42 -08003002 // Now build the array of package chunks.
3003 Vector<sp<AaptFile> > flatPackages;
3004 for (pi=0; pi<N; pi++) {
3005 sp<Package> p = mOrderedPackages.itemAt(pi);
3006 if (p->getTypes().size() == 0) {
3007 // Empty, skip!
3008 continue;
3009 }
3010
3011 const size_t N = p->getTypeStrings().size();
3012
3013 const size_t baseSize = sizeof(ResTable_package);
3014
3015 // Start the package data.
3016 sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
3017 ResTable_package* header = (ResTable_package*)data->editData(baseSize);
3018 if (header == NULL) {
3019 fprintf(stderr, "ERROR: out of memory creating ResTable_package\n");
3020 return NO_MEMORY;
3021 }
3022 memset(header, 0, sizeof(*header));
3023 header->header.type = htods(RES_TABLE_PACKAGE_TYPE);
3024 header->header.headerSize = htods(sizeof(*header));
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003025 header->id = htodl(static_cast<uint32_t>(p->getAssignedId()));
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003026 strcpy16_htod(header->name, p->getName().c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003027
3028 // Write the string blocks.
3029 const size_t typeStringsStart = data->getSize();
3030 sp<AaptFile> strFile = p->getTypeStringsData();
3031 ssize_t amt = data->writeData(strFile->getData(), strFile->getSize());
Andreas Gampe2412f842014-09-30 20:55:57 -07003032 if (kPrintStringMetrics) {
Pirama Arumuga Nainardc36bb62018-05-11 15:52:49 -07003033 fprintf(stderr, "**** type strings: %zd\n", amt);
Andreas Gampe2412f842014-09-30 20:55:57 -07003034 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003035 strAmt += amt;
3036 if (amt < 0) {
3037 return amt;
3038 }
3039 const size_t keyStringsStart = data->getSize();
3040 strFile = p->getKeyStringsData();
3041 amt = data->writeData(strFile->getData(), strFile->getSize());
Andreas Gampe2412f842014-09-30 20:55:57 -07003042 if (kPrintStringMetrics) {
Pirama Arumuga Nainardc36bb62018-05-11 15:52:49 -07003043 fprintf(stderr, "**** key strings: %zd\n", amt);
Andreas Gampe2412f842014-09-30 20:55:57 -07003044 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003045 strAmt += amt;
3046 if (amt < 0) {
3047 return amt;
3048 }
3049
Adam Lesinski27f69f42014-08-21 13:19:12 -07003050 if (isBase) {
3051 status_t err = flattenLibraryTable(data, libraryPackages);
3052 if (err != NO_ERROR) {
3053 fprintf(stderr, "ERROR: failed to write library table\n");
3054 return err;
3055 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08003056 }
3057
Adam Lesinski282e1812014-01-23 18:17:42 -08003058 // Build the type chunks inside of this package.
3059 for (size_t ti=0; ti<N; ti++) {
3060 // Retrieve them in the same order as the type string block.
3061 size_t len;
Ryan Mitchell80094e32020-11-16 23:08:18 +00003062 String16 typeName(UnpackOptionalString(p->getTypeStrings().stringAt(ti), &len));
Adam Lesinski282e1812014-01-23 18:17:42 -08003063 sp<Type> t = p->getTypes().valueFor(typeName);
3064 LOG_ALWAYS_FATAL_IF(t == NULL && typeName != String16("<empty>"),
3065 "Type name %s not found",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003066 String8(typeName).c_str());
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003067 if (t == NULL) {
3068 continue;
3069 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003070 const bool filterable = (typeName != mipmap16);
Adam Lesinski27f69f42014-08-21 13:19:12 -07003071 const bool skipEntireType = (typeName == mipmap16 && !isBase);
Adam Lesinski282e1812014-01-23 18:17:42 -08003072
3073 const size_t N = t != NULL ? t->getOrderedConfigs().size() : 0;
3074
3075 // Until a non-NO_ENTRY value has been written for a resource,
3076 // that resource is invalid; validResources[i] represents
3077 // the item at t->getOrderedConfigs().itemAt(i).
3078 Vector<bool> validResources;
3079 validResources.insertAt(false, 0, N);
3080
3081 // First write the typeSpec chunk, containing information about
3082 // each resource entry in this type.
3083 {
3084 const size_t typeSpecSize = sizeof(ResTable_typeSpec) + sizeof(uint32_t)*N;
3085 const size_t typeSpecStart = data->getSize();
3086 ResTable_typeSpec* tsHeader = (ResTable_typeSpec*)
3087 (((uint8_t*)data->editData(typeSpecStart+typeSpecSize)) + typeSpecStart);
3088 if (tsHeader == NULL) {
3089 fprintf(stderr, "ERROR: out of memory creating ResTable_typeSpec\n");
3090 return NO_MEMORY;
3091 }
3092 memset(tsHeader, 0, sizeof(*tsHeader));
3093 tsHeader->header.type = htods(RES_TABLE_TYPE_SPEC_TYPE);
3094 tsHeader->header.headerSize = htods(sizeof(*tsHeader));
3095 tsHeader->header.size = htodl(typeSpecSize);
3096 tsHeader->id = ti+1;
3097 tsHeader->entryCount = htodl(N);
3098
3099 uint32_t* typeSpecFlags = (uint32_t*)
3100 (((uint8_t*)data->editData())
3101 + typeSpecStart + sizeof(ResTable_typeSpec));
3102 memset(typeSpecFlags, 0, sizeof(uint32_t)*N);
3103
3104 for (size_t ei=0; ei<N; ei++) {
3105 sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
Adam Lesinski9b624c12014-11-19 17:49:26 -08003106 if (cl == NULL) {
3107 continue;
3108 }
3109
Adam Lesinski282e1812014-01-23 18:17:42 -08003110 if (cl->getPublic()) {
3111 typeSpecFlags[ei] |= htodl(ResTable_typeSpec::SPEC_PUBLIC);
3112 }
Adam Lesinski27f69f42014-08-21 13:19:12 -07003113
3114 if (skipEntireType) {
3115 continue;
3116 }
3117
Adam Lesinski282e1812014-01-23 18:17:42 -08003118 const size_t CN = cl->getEntries().size();
3119 for (size_t ci=0; ci<CN; ci++) {
Adam Lesinskifab50872014-04-16 14:40:42 -07003120 if (filterable && !filter->match(cl->getEntries().keyAt(ci))) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003121 continue;
3122 }
3123 for (size_t cj=ci+1; cj<CN; cj++) {
Adam Lesinskifab50872014-04-16 14:40:42 -07003124 if (filterable && !filter->match(cl->getEntries().keyAt(cj))) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003125 continue;
3126 }
3127 typeSpecFlags[ei] |= htodl(
3128 cl->getEntries().keyAt(ci).diff(cl->getEntries().keyAt(cj)));
3129 }
3130 }
3131 }
3132 }
3133
Adam Lesinski27f69f42014-08-21 13:19:12 -07003134 if (skipEntireType) {
3135 continue;
3136 }
3137
Adam Lesinski282e1812014-01-23 18:17:42 -08003138 // We need to write one type chunk for each configuration for
3139 // which we have entries in this type.
Adam Lesinskie97908d2014-12-05 11:06:21 -08003140 SortedVector<ConfigDescription> uniqueConfigs;
3141 if (t != NULL) {
3142 uniqueConfigs = t->getUniqueConfigs();
3143 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003144
3145 const size_t typeSize = sizeof(ResTable_type) + sizeof(uint32_t)*N;
3146
Adam Lesinskie97908d2014-12-05 11:06:21 -08003147 const size_t NC = uniqueConfigs.size();
Adam Lesinski282e1812014-01-23 18:17:42 -08003148 for (size_t ci=0; ci<NC; ci++) {
Adam Lesinski9b624c12014-11-19 17:49:26 -08003149 const ConfigDescription& config = uniqueConfigs[ci];
Adam Lesinski282e1812014-01-23 18:17:42 -08003150
Andreas Gampe2412f842014-09-30 20:55:57 -07003151 if (kIsDebug) {
3152 printf("Writing config %zu config: imsi:%d/%d lang:%c%c cnt:%c%c "
3153 "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
3154 "sw%ddp w%ddp h%ddp layout:%d\n",
3155 ti + 1,
3156 config.mcc, config.mnc,
3157 config.language[0] ? config.language[0] : '-',
3158 config.language[1] ? config.language[1] : '-',
3159 config.country[0] ? config.country[0] : '-',
3160 config.country[1] ? config.country[1] : '-',
3161 config.orientation,
3162 config.uiMode,
3163 config.touchscreen,
3164 config.density,
3165 config.keyboard,
3166 config.inputFlags,
3167 config.navigation,
3168 config.screenWidth,
3169 config.screenHeight,
3170 config.smallestScreenWidthDp,
3171 config.screenWidthDp,
3172 config.screenHeightDp,
3173 config.screenLayout);
3174 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003175
Adam Lesinskifab50872014-04-16 14:40:42 -07003176 if (filterable && !filter->match(config)) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003177 continue;
3178 }
3179
3180 const size_t typeStart = data->getSize();
3181
3182 ResTable_type* tHeader = (ResTable_type*)
3183 (((uint8_t*)data->editData(typeStart+typeSize)) + typeStart);
3184 if (tHeader == NULL) {
3185 fprintf(stderr, "ERROR: out of memory creating ResTable_type\n");
3186 return NO_MEMORY;
3187 }
3188
3189 memset(tHeader, 0, sizeof(*tHeader));
3190 tHeader->header.type = htods(RES_TABLE_TYPE_TYPE);
3191 tHeader->header.headerSize = htods(sizeof(*tHeader));
3192 tHeader->id = ti+1;
3193 tHeader->entryCount = htodl(N);
3194 tHeader->entriesStart = htodl(typeSize);
3195 tHeader->config = config;
Andreas Gampe2412f842014-09-30 20:55:57 -07003196 if (kIsDebug) {
3197 printf("Writing type %zu config: imsi:%d/%d lang:%c%c cnt:%c%c "
3198 "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
3199 "sw%ddp w%ddp h%ddp layout:%d\n",
3200 ti + 1,
3201 tHeader->config.mcc, tHeader->config.mnc,
3202 tHeader->config.language[0] ? tHeader->config.language[0] : '-',
3203 tHeader->config.language[1] ? tHeader->config.language[1] : '-',
3204 tHeader->config.country[0] ? tHeader->config.country[0] : '-',
3205 tHeader->config.country[1] ? tHeader->config.country[1] : '-',
3206 tHeader->config.orientation,
3207 tHeader->config.uiMode,
3208 tHeader->config.touchscreen,
3209 tHeader->config.density,
3210 tHeader->config.keyboard,
3211 tHeader->config.inputFlags,
3212 tHeader->config.navigation,
3213 tHeader->config.screenWidth,
3214 tHeader->config.screenHeight,
3215 tHeader->config.smallestScreenWidthDp,
3216 tHeader->config.screenWidthDp,
3217 tHeader->config.screenHeightDp,
3218 tHeader->config.screenLayout);
3219 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003220 tHeader->config.swapHtoD();
3221
3222 // Build the entries inside of this type.
3223 for (size_t ei=0; ei<N; ei++) {
3224 sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
Adam Lesinski9b624c12014-11-19 17:49:26 -08003225 sp<Entry> e = NULL;
3226 if (cl != NULL) {
3227 e = cl->getEntries().valueFor(config);
3228 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003229
3230 // Set the offset for this entry in its type.
3231 uint32_t* index = (uint32_t*)
3232 (((uint8_t*)data->editData())
3233 + typeStart + sizeof(ResTable_type));
3234 if (e != NULL) {
3235 index[ei] = htodl(data->getSize()-typeStart-typeSize);
3236
3237 // Create the entry.
3238 ssize_t amt = e->flatten(bundle, data, cl->getPublic());
3239 if (amt < 0) {
3240 return amt;
3241 }
3242 validResources.editItemAt(ei) = true;
3243 } else {
3244 index[ei] = htodl(ResTable_type::NO_ENTRY);
3245 }
3246 }
3247
3248 // Fill in the rest of the type information.
3249 tHeader = (ResTable_type*)
3250 (((uint8_t*)data->editData()) + typeStart);
3251 tHeader->header.size = htodl(data->getSize()-typeStart);
3252 }
3253
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003254 // If we're building splits, then each invocation of the flattening
3255 // step will have 'missing' entries. Don't warn/error for this case.
Tomasz Wasilczyk7e22cab2023-08-24 19:02:33 +00003256 if (bundle->getSplitConfigurations().empty()) {
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003257 bool missing_entry = false;
3258 const char* log_prefix = bundle->getErrorOnMissingConfigEntry() ?
3259 "error" : "warning";
3260 for (size_t i = 0; i < N; ++i) {
3261 if (!validResources[i]) {
3262 sp<ConfigList> c = t->getOrderedConfigs().itemAt(i);
Adam Lesinski9b624c12014-11-19 17:49:26 -08003263 if (c != NULL) {
Colin Cross01f18562015-04-08 17:29:00 -07003264 fprintf(stderr, "%s: no entries written for %s/%s (0x%08zx)\n", log_prefix,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003265 String8(typeName).c_str(), String8(c->getName()).c_str(),
Adam Lesinski9b624c12014-11-19 17:49:26 -08003266 Res_MAKEID(p->getAssignedId() - 1, ti, i));
3267 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003268 missing_entry = true;
3269 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003270 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003271 if (bundle->getErrorOnMissingConfigEntry() && missing_entry) {
3272 fprintf(stderr, "Error: Missing entries, quit!\n");
3273 return NOT_ENOUGH_DATA;
3274 }
Ying Wangcd28bd32013-11-14 17:12:10 -08003275 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003276 }
3277
3278 // Fill in the rest of the package information.
3279 header = (ResTable_package*)data->editData();
3280 header->header.size = htodl(data->getSize());
3281 header->typeStrings = htodl(typeStringsStart);
3282 header->lastPublicType = htodl(p->getTypeStrings().size());
3283 header->keyStrings = htodl(keyStringsStart);
3284 header->lastPublicKey = htodl(p->getKeyStrings().size());
3285
3286 flatPackages.add(data);
3287 }
3288
3289 // And now write out the final chunks.
3290 const size_t dataStart = dest->getSize();
3291
3292 {
3293 // blah
3294 ResTable_header header;
3295 memset(&header, 0, sizeof(header));
3296 header.header.type = htods(RES_TABLE_TYPE);
3297 header.header.headerSize = htods(sizeof(header));
3298 header.packageCount = htodl(flatPackages.size());
3299 status_t err = dest->writeData(&header, sizeof(header));
3300 if (err != NO_ERROR) {
3301 fprintf(stderr, "ERROR: out of memory creating ResTable_header\n");
3302 return err;
3303 }
3304 }
3305
3306 ssize_t strStart = dest->getSize();
Adam Lesinskifab50872014-04-16 14:40:42 -07003307 status_t err = valueStrings.writeStringBlock(dest);
Adam Lesinski282e1812014-01-23 18:17:42 -08003308 if (err != NO_ERROR) {
3309 return err;
3310 }
3311
3312 ssize_t amt = (dest->getSize()-strStart);
3313 strAmt += amt;
Andreas Gampe2412f842014-09-30 20:55:57 -07003314 if (kPrintStringMetrics) {
Pirama Arumuga Nainardc36bb62018-05-11 15:52:49 -07003315 fprintf(stderr, "**** value strings: %zd\n", amt);
3316 fprintf(stderr, "**** total strings: %zd\n", amt);
Andreas Gampe2412f842014-09-30 20:55:57 -07003317 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08003318
Adam Lesinski282e1812014-01-23 18:17:42 -08003319 for (pi=0; pi<flatPackages.size(); pi++) {
3320 err = dest->writeData(flatPackages[pi]->getData(),
3321 flatPackages[pi]->getSize());
3322 if (err != NO_ERROR) {
3323 fprintf(stderr, "ERROR: out of memory creating package chunk for ResTable_header\n");
3324 return err;
3325 }
3326 }
3327
3328 ResTable_header* header = (ResTable_header*)
3329 (((uint8_t*)dest->getData()) + dataStart);
3330 header->header.size = htodl(dest->getSize() - dataStart);
3331
Andreas Gampe2412f842014-09-30 20:55:57 -07003332 if (kPrintStringMetrics) {
3333 fprintf(stderr, "**** total resource table size: %zu / %zu%% strings\n",
3334 dest->getSize(), (size_t)(strAmt*100)/dest->getSize());
3335 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003336
3337 return NO_ERROR;
3338}
3339
Adam Lesinskide898ff2014-01-29 18:20:45 -08003340status_t ResourceTable::flattenLibraryTable(const sp<AaptFile>& dest, const Vector<sp<Package> >& libs) {
3341 // Write out the library table if necessary
3342 if (libs.size() > 0) {
Andreas Gampe87332a72014-10-01 22:03:58 -07003343 if (kIsDebug) {
3344 fprintf(stderr, "Writing library reference table\n");
3345 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08003346
3347 const size_t libStart = dest->getSize();
3348 const size_t count = libs.size();
Adam Lesinski6022deb2014-08-20 14:59:19 -07003349 ResTable_lib_header* libHeader = (ResTable_lib_header*) dest->editDataInRange(
3350 libStart, sizeof(ResTable_lib_header));
Adam Lesinskide898ff2014-01-29 18:20:45 -08003351
3352 memset(libHeader, 0, sizeof(*libHeader));
3353 libHeader->header.type = htods(RES_TABLE_LIBRARY_TYPE);
3354 libHeader->header.headerSize = htods(sizeof(*libHeader));
3355 libHeader->header.size = htodl(sizeof(*libHeader) + (sizeof(ResTable_lib_entry) * count));
3356 libHeader->count = htodl(count);
3357
3358 // Write the library entries
3359 for (size_t i = 0; i < count; i++) {
3360 const size_t entryStart = dest->getSize();
3361 sp<Package> libPackage = libs[i];
Andreas Gampe87332a72014-10-01 22:03:58 -07003362 if (kIsDebug) {
3363 fprintf(stderr, " Entry %s -> 0x%02x\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003364 String8(libPackage->getName()).c_str(),
Andreas Gampe87332a72014-10-01 22:03:58 -07003365 (uint8_t)libPackage->getAssignedId());
3366 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08003367
Adam Lesinski6022deb2014-08-20 14:59:19 -07003368 ResTable_lib_entry* entry = (ResTable_lib_entry*) dest->editDataInRange(
3369 entryStart, sizeof(ResTable_lib_entry));
Adam Lesinskide898ff2014-01-29 18:20:45 -08003370 memset(entry, 0, sizeof(*entry));
3371 entry->packageId = htodl(libPackage->getAssignedId());
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003372 strcpy16_htod(entry->packageName, libPackage->getName().c_str());
Adam Lesinskide898ff2014-01-29 18:20:45 -08003373 }
3374 }
3375 return NO_ERROR;
3376}
3377
Adam Lesinski282e1812014-01-23 18:17:42 -08003378void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp)
3379{
3380 fprintf(fp,
3381 "<!-- This file contains <public> resource definitions for all\n"
3382 " resources that were generated from the source data. -->\n"
3383 "\n"
3384 "<resources>\n");
3385
3386 writePublicDefinitions(package, fp, true);
3387 writePublicDefinitions(package, fp, false);
3388
3389 fprintf(fp,
3390 "\n"
3391 "</resources>\n");
3392}
3393
3394void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp, bool pub)
3395{
3396 bool didHeader = false;
3397
3398 sp<Package> pkg = mPackages.valueFor(package);
3399 if (pkg != NULL) {
3400 const size_t NT = pkg->getOrderedTypes().size();
3401 for (size_t i=0; i<NT; i++) {
3402 sp<Type> t = pkg->getOrderedTypes().itemAt(i);
3403 if (t == NULL) {
3404 continue;
3405 }
3406
3407 bool didType = false;
3408
3409 const size_t NC = t->getOrderedConfigs().size();
3410 for (size_t j=0; j<NC; j++) {
3411 sp<ConfigList> c = t->getOrderedConfigs().itemAt(j);
3412 if (c == NULL) {
3413 continue;
3414 }
3415
3416 if (c->getPublic() != pub) {
3417 continue;
3418 }
3419
3420 if (!didType) {
3421 fprintf(fp, "\n");
3422 didType = true;
3423 }
3424 if (!didHeader) {
3425 if (pub) {
3426 fprintf(fp," <!-- PUBLIC SECTION. These resources have been declared public.\n");
3427 fprintf(fp," Changes to these definitions will break binary compatibility. -->\n\n");
3428 } else {
3429 fprintf(fp," <!-- PRIVATE SECTION. These resources have not been declared public.\n");
3430 fprintf(fp," You can make them public my moving these lines into a file in res/values. -->\n\n");
3431 }
3432 didHeader = true;
3433 }
3434 if (!pub) {
3435 const size_t NE = c->getEntries().size();
3436 for (size_t k=0; k<NE; k++) {
3437 const SourcePos& pos = c->getEntries().valueAt(k)->getPos();
3438 if (pos.file != "") {
3439 fprintf(fp," <!-- Declared at %s:%d -->\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003440 pos.file.c_str(), pos.line);
Adam Lesinski282e1812014-01-23 18:17:42 -08003441 }
3442 }
3443 }
3444 fprintf(fp, " <public type=\"%s\" name=\"%s\" id=\"0x%08x\" />\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003445 String8(t->getName()).c_str(),
3446 String8(c->getName()).c_str(),
Adam Lesinski282e1812014-01-23 18:17:42 -08003447 getResId(pkg, t, c->getEntryIndex()));
3448 }
3449 }
3450 }
3451}
3452
3453ResourceTable::Item::Item(const SourcePos& _sourcePos,
3454 bool _isId,
3455 const String16& _value,
3456 const Vector<StringPool::entry_style_span>* _style,
3457 int32_t _format)
3458 : sourcePos(_sourcePos)
3459 , isId(_isId)
3460 , value(_value)
3461 , format(_format)
3462 , bagKeyId(0)
3463 , evaluating(false)
3464{
3465 if (_style) {
3466 style = *_style;
3467 }
3468}
3469
Adam Lesinski82a2dd82014-09-17 18:34:15 -07003470ResourceTable::Entry::Entry(const Entry& entry)
3471 : RefBase()
3472 , mName(entry.mName)
3473 , mParent(entry.mParent)
3474 , mType(entry.mType)
3475 , mItem(entry.mItem)
3476 , mItemFormat(entry.mItemFormat)
3477 , mBag(entry.mBag)
3478 , mNameIndex(entry.mNameIndex)
3479 , mParentId(entry.mParentId)
3480 , mPos(entry.mPos) {}
3481
Adam Lesinski978ab9d2014-09-24 19:02:52 -07003482ResourceTable::Entry& ResourceTable::Entry::operator=(const Entry& entry) {
3483 mName = entry.mName;
3484 mParent = entry.mParent;
3485 mType = entry.mType;
3486 mItem = entry.mItem;
3487 mItemFormat = entry.mItemFormat;
3488 mBag = entry.mBag;
3489 mNameIndex = entry.mNameIndex;
3490 mParentId = entry.mParentId;
3491 mPos = entry.mPos;
3492 return *this;
3493}
3494
Adam Lesinski282e1812014-01-23 18:17:42 -08003495status_t ResourceTable::Entry::makeItABag(const SourcePos& sourcePos)
3496{
3497 if (mType == TYPE_BAG) {
3498 return NO_ERROR;
3499 }
3500 if (mType == TYPE_UNKNOWN) {
3501 mType = TYPE_BAG;
3502 return NO_ERROR;
3503 }
3504 sourcePos.error("Resource entry %s is already defined as a single item.\n"
3505 "%s:%d: Originally defined here.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003506 String8(mName).c_str(),
3507 mItem.sourcePos.file.c_str(), mItem.sourcePos.line);
Adam Lesinski282e1812014-01-23 18:17:42 -08003508 return UNKNOWN_ERROR;
3509}
3510
3511status_t ResourceTable::Entry::setItem(const SourcePos& sourcePos,
3512 const String16& value,
3513 const Vector<StringPool::entry_style_span>* style,
3514 int32_t format,
3515 const bool overwrite)
3516{
3517 Item item(sourcePos, false, value, style);
3518
3519 if (mType == TYPE_BAG) {
Adam Lesinski43a0df02014-08-18 17:14:57 -07003520 if (mBag.size() == 0) {
3521 sourcePos.error("Resource entry %s is already defined as a bag.",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003522 String8(mName).c_str());
Adam Lesinski43a0df02014-08-18 17:14:57 -07003523 } else {
3524 const Item& item(mBag.valueAt(0));
3525 sourcePos.error("Resource entry %s is already defined as a bag.\n"
3526 "%s:%d: Originally defined here.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003527 String8(mName).c_str(),
3528 item.sourcePos.file.c_str(), item.sourcePos.line);
Adam Lesinski43a0df02014-08-18 17:14:57 -07003529 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003530 return UNKNOWN_ERROR;
3531 }
3532 if ( (mType != TYPE_UNKNOWN) && (overwrite == false) ) {
3533 sourcePos.error("Resource entry %s is already defined.\n"
3534 "%s:%d: Originally defined here.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003535 String8(mName).c_str(),
3536 mItem.sourcePos.file.c_str(), mItem.sourcePos.line);
Adam Lesinski282e1812014-01-23 18:17:42 -08003537 return UNKNOWN_ERROR;
3538 }
3539
3540 mType = TYPE_ITEM;
3541 mItem = item;
3542 mItemFormat = format;
3543 return NO_ERROR;
3544}
3545
3546status_t ResourceTable::Entry::addToBag(const SourcePos& sourcePos,
3547 const String16& key, const String16& value,
3548 const Vector<StringPool::entry_style_span>* style,
3549 bool replace, bool isId, int32_t format)
3550{
3551 status_t err = makeItABag(sourcePos);
3552 if (err != NO_ERROR) {
3553 return err;
3554 }
3555
3556 Item item(sourcePos, isId, value, style, format);
3557
3558 // XXX NOTE: there is an error if you try to have a bag with two keys,
3559 // one an attr and one an id, with the same name. Not something we
3560 // currently ever have to worry about.
3561 ssize_t origKey = mBag.indexOfKey(key);
3562 if (origKey >= 0) {
3563 if (!replace) {
3564 const Item& item(mBag.valueAt(origKey));
3565 sourcePos.error("Resource entry %s already has bag item %s.\n"
3566 "%s:%d: Originally defined here.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003567 String8(mName).c_str(), String8(key).c_str(),
3568 item.sourcePos.file.c_str(), item.sourcePos.line);
Adam Lesinski282e1812014-01-23 18:17:42 -08003569 return UNKNOWN_ERROR;
3570 }
3571 //printf("Replacing %s with %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003572 // String8(mBag.valueFor(key).value).c_str(), String8(value).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003573 mBag.replaceValueFor(key, item);
3574 }
3575
3576 mBag.add(key, item);
3577 return NO_ERROR;
3578}
3579
Adam Lesinski82a2dd82014-09-17 18:34:15 -07003580status_t ResourceTable::Entry::removeFromBag(const String16& key) {
3581 if (mType != Entry::TYPE_BAG) {
3582 return NO_ERROR;
3583 }
3584
3585 if (mBag.removeItem(key) >= 0) {
3586 return NO_ERROR;
3587 }
3588 return UNKNOWN_ERROR;
3589}
3590
Adam Lesinski282e1812014-01-23 18:17:42 -08003591status_t ResourceTable::Entry::emptyBag(const SourcePos& sourcePos)
3592{
3593 status_t err = makeItABag(sourcePos);
3594 if (err != NO_ERROR) {
3595 return err;
3596 }
3597
3598 mBag.clear();
3599 return NO_ERROR;
3600}
3601
3602status_t ResourceTable::Entry::generateAttributes(ResourceTable* table,
3603 const String16& package)
3604{
3605 const String16 attr16("attr");
3606 const String16 id16("id");
3607 const size_t N = mBag.size();
3608 for (size_t i=0; i<N; i++) {
3609 const String16& key = mBag.keyAt(i);
3610 const Item& it = mBag.valueAt(i);
3611 if (it.isId) {
3612 if (!table->hasBagOrEntry(key, &id16, &package)) {
3613 String16 value("false");
Andreas Gampe87332a72014-10-01 22:03:58 -07003614 if (kIsDebug) {
3615 fprintf(stderr, "Generating %s:id/%s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003616 String8(package).c_str(),
3617 String8(key).c_str());
Andreas Gampe87332a72014-10-01 22:03:58 -07003618 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003619 status_t err = table->addEntry(SourcePos(String8("<generated>"), 0), package,
3620 id16, key, value);
3621 if (err != NO_ERROR) {
3622 return err;
3623 }
3624 }
3625 } else if (!table->hasBagOrEntry(key, &attr16, &package)) {
3626
3627#if 1
3628// fprintf(stderr, "ERROR: Bag attribute '%s' has not been defined.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003629// String8(key).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003630// const Item& item(mBag.valueAt(i));
3631// fprintf(stderr, "Referenced from file %s line %d\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003632// item.sourcePos.file.c_str(), item.sourcePos.line);
Adam Lesinski282e1812014-01-23 18:17:42 -08003633// return UNKNOWN_ERROR;
3634#else
3635 char numberStr[16];
3636 sprintf(numberStr, "%d", ResTable_map::TYPE_ANY);
3637 status_t err = table->addBag(SourcePos("<generated>", 0), package,
3638 attr16, key, String16(""),
3639 String16("^type"),
3640 String16(numberStr), NULL, NULL);
3641 if (err != NO_ERROR) {
3642 return err;
3643 }
3644#endif
3645 }
3646 }
3647 return NO_ERROR;
3648}
3649
3650status_t ResourceTable::Entry::assignResourceIds(ResourceTable* table,
Andreas Gampe2412f842014-09-30 20:55:57 -07003651 const String16& /* package */)
Adam Lesinski282e1812014-01-23 18:17:42 -08003652{
3653 bool hasErrors = false;
3654
3655 if (mType == TYPE_BAG) {
3656 const char* errorMsg;
3657 const String16 style16("style");
3658 const String16 attr16("attr");
3659 const String16 id16("id");
3660 mParentId = 0;
3661 if (mParent.size() > 0) {
3662 mParentId = table->getResId(mParent, &style16, NULL, &errorMsg);
3663 if (mParentId == 0) {
3664 mPos.error("Error retrieving parent for item: %s '%s'.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003665 errorMsg, String8(mParent).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003666 hasErrors = true;
3667 }
3668 }
3669 const size_t N = mBag.size();
3670 for (size_t i=0; i<N; i++) {
3671 const String16& key = mBag.keyAt(i);
3672 Item& it = mBag.editValueAt(i);
3673 it.bagKeyId = table->getResId(key,
3674 it.isId ? &id16 : &attr16, NULL, &errorMsg);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003675 //printf("Bag key of %s: #%08x\n", String8(key).c_str(), it.bagKeyId);
Adam Lesinski282e1812014-01-23 18:17:42 -08003676 if (it.bagKeyId == 0) {
3677 it.sourcePos.error("Error: %s: %s '%s'.\n", errorMsg,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003678 String8(it.isId ? id16 : attr16).c_str(),
3679 String8(key).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003680 hasErrors = true;
3681 }
3682 }
3683 }
Andreas Gampe2412f842014-09-30 20:55:57 -07003684 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08003685}
3686
3687status_t ResourceTable::Entry::prepareFlatten(StringPool* strings, ResourceTable* table,
3688 const String8* configTypeName, const ConfigDescription* config)
3689{
3690 if (mType == TYPE_ITEM) {
3691 Item& it = mItem;
3692 AccessorCookie ac(it.sourcePos, String8(mName), String8(it.value));
3693 if (!table->stringToValue(&it.parsedValue, strings,
3694 it.value, false, true, 0,
3695 &it.style, NULL, &ac, mItemFormat,
3696 configTypeName, config)) {
3697 return UNKNOWN_ERROR;
3698 }
3699 } else if (mType == TYPE_BAG) {
3700 const size_t N = mBag.size();
3701 for (size_t i=0; i<N; i++) {
3702 const String16& key = mBag.keyAt(i);
3703 Item& it = mBag.editValueAt(i);
3704 AccessorCookie ac(it.sourcePos, String8(key), String8(it.value));
3705 if (!table->stringToValue(&it.parsedValue, strings,
3706 it.value, false, true, it.bagKeyId,
3707 &it.style, NULL, &ac, it.format,
3708 configTypeName, config)) {
3709 return UNKNOWN_ERROR;
3710 }
3711 }
3712 } else {
3713 mPos.error("Error: entry %s is not a single item or a bag.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003714 String8(mName).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003715 return UNKNOWN_ERROR;
3716 }
3717 return NO_ERROR;
3718}
3719
3720status_t ResourceTable::Entry::remapStringValue(StringPool* strings)
3721{
3722 if (mType == TYPE_ITEM) {
3723 Item& it = mItem;
3724 if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3725 it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3726 }
3727 } else if (mType == TYPE_BAG) {
3728 const size_t N = mBag.size();
3729 for (size_t i=0; i<N; i++) {
3730 Item& it = mBag.editValueAt(i);
3731 if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3732 it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3733 }
3734 }
3735 } else {
3736 mPos.error("Error: entry %s is not a single item or a bag.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003737 String8(mName).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003738 return UNKNOWN_ERROR;
3739 }
3740 return NO_ERROR;
3741}
3742
Andreas Gampe2412f842014-09-30 20:55:57 -07003743ssize_t ResourceTable::Entry::flatten(Bundle* /* bundle */, const sp<AaptFile>& data, bool isPublic)
Adam Lesinski282e1812014-01-23 18:17:42 -08003744{
3745 size_t amt = 0;
3746 ResTable_entry header;
3747 memset(&header, 0, sizeof(header));
3748 header.size = htods(sizeof(header));
Andreas Gampe2412f842014-09-30 20:55:57 -07003749 const type ty = mType;
3750 if (ty == TYPE_BAG) {
3751 header.flags |= htods(header.FLAG_COMPLEX);
Adam Lesinski282e1812014-01-23 18:17:42 -08003752 }
Andreas Gampe2412f842014-09-30 20:55:57 -07003753 if (isPublic) {
3754 header.flags |= htods(header.FLAG_PUBLIC);
3755 }
3756 header.key.index = htodl(mNameIndex);
Adam Lesinski282e1812014-01-23 18:17:42 -08003757 if (ty != TYPE_BAG) {
3758 status_t err = data->writeData(&header, sizeof(header));
3759 if (err != NO_ERROR) {
3760 fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3761 return err;
3762 }
3763
3764 const Item& it = mItem;
3765 Res_value par;
3766 memset(&par, 0, sizeof(par));
3767 par.size = htods(it.parsedValue.size);
3768 par.dataType = it.parsedValue.dataType;
3769 par.res0 = it.parsedValue.res0;
3770 par.data = htodl(it.parsedValue.data);
3771 #if 0
3772 printf("Writing item (%s): type=%d, data=0x%x, res0=0x%x\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003773 String8(mName).c_str(), it.parsedValue.dataType,
Adam Lesinski282e1812014-01-23 18:17:42 -08003774 it.parsedValue.data, par.res0);
3775 #endif
3776 err = data->writeData(&par, it.parsedValue.size);
3777 if (err != NO_ERROR) {
3778 fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3779 return err;
3780 }
3781 amt += it.parsedValue.size;
3782 } else {
3783 size_t N = mBag.size();
3784 size_t i;
3785 // Create correct ordering of items.
3786 KeyedVector<uint32_t, const Item*> items;
3787 for (i=0; i<N; i++) {
3788 const Item& it = mBag.valueAt(i);
3789 items.add(it.bagKeyId, &it);
3790 }
3791 N = items.size();
3792
3793 ResTable_map_entry mapHeader;
3794 memcpy(&mapHeader, &header, sizeof(header));
3795 mapHeader.size = htods(sizeof(mapHeader));
3796 mapHeader.parent.ident = htodl(mParentId);
3797 mapHeader.count = htodl(N);
3798 status_t err = data->writeData(&mapHeader, sizeof(mapHeader));
3799 if (err != NO_ERROR) {
3800 fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3801 return err;
3802 }
3803
3804 for (i=0; i<N; i++) {
3805 const Item& it = *items.valueAt(i);
3806 ResTable_map map;
3807 map.name.ident = htodl(it.bagKeyId);
3808 map.value.size = htods(it.parsedValue.size);
3809 map.value.dataType = it.parsedValue.dataType;
3810 map.value.res0 = it.parsedValue.res0;
3811 map.value.data = htodl(it.parsedValue.data);
3812 err = data->writeData(&map, sizeof(map));
3813 if (err != NO_ERROR) {
3814 fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3815 return err;
3816 }
3817 amt += sizeof(map);
3818 }
3819 }
3820 return amt;
3821}
3822
3823void ResourceTable::ConfigList::appendComment(const String16& comment,
3824 bool onlyIfEmpty)
3825{
3826 if (comment.size() <= 0) {
3827 return;
3828 }
3829 if (onlyIfEmpty && mComment.size() > 0) {
3830 return;
3831 }
3832 if (mComment.size() > 0) {
3833 mComment.append(String16("\n"));
3834 }
3835 mComment.append(comment);
3836}
3837
3838void ResourceTable::ConfigList::appendTypeComment(const String16& comment)
3839{
3840 if (comment.size() <= 0) {
3841 return;
3842 }
3843 if (mTypeComment.size() > 0) {
3844 mTypeComment.append(String16("\n"));
3845 }
3846 mTypeComment.append(comment);
3847}
3848
3849status_t ResourceTable::Type::addPublic(const SourcePos& sourcePos,
3850 const String16& name,
3851 const uint32_t ident)
3852{
3853 #if 0
3854 int32_t entryIdx = Res_GETENTRY(ident);
3855 if (entryIdx < 0) {
3856 sourcePos.error("Public resource %s/%s has an invalid 0 identifier (0x%08x).\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003857 String8(mName).c_str(), String8(name).c_str(), ident);
Adam Lesinski282e1812014-01-23 18:17:42 -08003858 return UNKNOWN_ERROR;
3859 }
3860 #endif
3861
3862 int32_t typeIdx = Res_GETTYPE(ident);
3863 if (typeIdx >= 0) {
3864 typeIdx++;
3865 if (mPublicIndex > 0 && mPublicIndex != typeIdx) {
3866 sourcePos.error("Public resource %s/%s has conflicting type codes for its"
3867 " public identifiers (0x%x vs 0x%x).\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003868 String8(mName).c_str(), String8(name).c_str(),
Adam Lesinski282e1812014-01-23 18:17:42 -08003869 mPublicIndex, typeIdx);
3870 return UNKNOWN_ERROR;
3871 }
3872 mPublicIndex = typeIdx;
3873 }
3874
3875 if (mFirstPublicSourcePos == NULL) {
3876 mFirstPublicSourcePos = new SourcePos(sourcePos);
3877 }
3878
3879 if (mPublic.indexOfKey(name) < 0) {
3880 mPublic.add(name, Public(sourcePos, String16(), ident));
3881 } else {
3882 Public& p = mPublic.editValueFor(name);
3883 if (p.ident != ident) {
3884 sourcePos.error("Public resource %s/%s has conflicting public identifiers"
3885 " (0x%08x vs 0x%08x).\n"
3886 "%s:%d: Originally defined here.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003887 String8(mName).c_str(), String8(name).c_str(), p.ident, ident,
3888 p.sourcePos.file.c_str(), p.sourcePos.line);
Adam Lesinski282e1812014-01-23 18:17:42 -08003889 return UNKNOWN_ERROR;
3890 }
3891 }
3892
3893 return NO_ERROR;
3894}
3895
3896void ResourceTable::Type::canAddEntry(const String16& name)
3897{
3898 mCanAddEntries.add(name);
3899}
3900
3901sp<ResourceTable::Entry> ResourceTable::Type::getEntry(const String16& entry,
3902 const SourcePos& sourcePos,
3903 const ResTable_config* config,
3904 bool doSetIndex,
3905 bool overlay,
3906 bool autoAddOverlay)
3907{
3908 int pos = -1;
3909 sp<ConfigList> c = mConfigs.valueFor(entry);
3910 if (c == NULL) {
3911 if (overlay && !autoAddOverlay && mCanAddEntries.indexOf(entry) < 0) {
3912 sourcePos.error("Resource at %s appears in overlay but not"
3913 " in the base package; use <add-resource> to add.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003914 String8(entry).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003915 return NULL;
3916 }
3917 c = new ConfigList(entry, sourcePos);
3918 mConfigs.add(entry, c);
3919 pos = (int)mOrderedConfigs.size();
3920 mOrderedConfigs.add(c);
3921 if (doSetIndex) {
3922 c->setEntryIndex(pos);
3923 }
3924 }
3925
3926 ConfigDescription cdesc;
3927 if (config) cdesc = *config;
3928
3929 sp<Entry> e = c->getEntries().valueFor(cdesc);
3930 if (e == NULL) {
Andreas Gampe2412f842014-09-30 20:55:57 -07003931 if (kIsDebug) {
3932 if (config != NULL) {
3933 printf("New entry at %s:%d: imsi:%d/%d lang:%c%c cnt:%c%c "
Adam Lesinski282e1812014-01-23 18:17:42 -08003934 "orien:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
Andreas Gampe2412f842014-09-30 20:55:57 -07003935 "sw%ddp w%ddp h%ddp layout:%d\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003936 sourcePos.file.c_str(), sourcePos.line,
Adam Lesinski282e1812014-01-23 18:17:42 -08003937 config->mcc, config->mnc,
3938 config->language[0] ? config->language[0] : '-',
3939 config->language[1] ? config->language[1] : '-',
3940 config->country[0] ? config->country[0] : '-',
3941 config->country[1] ? config->country[1] : '-',
3942 config->orientation,
3943 config->touchscreen,
3944 config->density,
3945 config->keyboard,
3946 config->inputFlags,
3947 config->navigation,
3948 config->screenWidth,
3949 config->screenHeight,
3950 config->smallestScreenWidthDp,
3951 config->screenWidthDp,
3952 config->screenHeightDp,
Andreas Gampe2412f842014-09-30 20:55:57 -07003953 config->screenLayout);
3954 } else {
3955 printf("New entry at %s:%d: NULL config\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003956 sourcePos.file.c_str(), sourcePos.line);
Andreas Gampe2412f842014-09-30 20:55:57 -07003957 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003958 }
3959 e = new Entry(entry, sourcePos);
3960 c->addEntry(cdesc, e);
3961 /*
3962 if (doSetIndex) {
3963 if (pos < 0) {
3964 for (pos=0; pos<(int)mOrderedConfigs.size(); pos++) {
3965 if (mOrderedConfigs[pos] == c) {
3966 break;
3967 }
3968 }
3969 if (pos >= (int)mOrderedConfigs.size()) {
3970 sourcePos.error("Internal error: config not found in mOrderedConfigs when adding entry");
3971 return NULL;
3972 }
3973 }
3974 e->setEntryIndex(pos);
3975 }
3976 */
3977 }
3978
Adam Lesinski282e1812014-01-23 18:17:42 -08003979 return e;
3980}
3981
Adam Lesinski9b624c12014-11-19 17:49:26 -08003982sp<ResourceTable::ConfigList> ResourceTable::Type::removeEntry(const String16& entry) {
3983 ssize_t idx = mConfigs.indexOfKey(entry);
3984 if (idx < 0) {
3985 return NULL;
3986 }
3987
3988 sp<ConfigList> removed = mConfigs.valueAt(idx);
3989 mConfigs.removeItemsAt(idx);
3990
3991 Vector<sp<ConfigList> >::iterator iter = std::find(
3992 mOrderedConfigs.begin(), mOrderedConfigs.end(), removed);
3993 if (iter != mOrderedConfigs.end()) {
3994 mOrderedConfigs.erase(iter);
3995 }
3996
3997 mPublic.removeItem(entry);
3998 return removed;
3999}
4000
4001SortedVector<ConfigDescription> ResourceTable::Type::getUniqueConfigs() const {
4002 SortedVector<ConfigDescription> unique;
4003 const size_t entryCount = mOrderedConfigs.size();
4004 for (size_t i = 0; i < entryCount; i++) {
4005 if (mOrderedConfigs[i] == NULL) {
4006 continue;
4007 }
4008 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& configs =
4009 mOrderedConfigs[i]->getEntries();
4010 const size_t configCount = configs.size();
4011 for (size_t j = 0; j < configCount; j++) {
4012 unique.add(configs.keyAt(j));
4013 }
4014 }
4015 return unique;
4016}
4017
Adam Lesinski282e1812014-01-23 18:17:42 -08004018status_t ResourceTable::Type::applyPublicEntryOrder()
4019{
4020 size_t N = mOrderedConfigs.size();
4021 Vector<sp<ConfigList> > origOrder(mOrderedConfigs);
4022 bool hasError = false;
4023
4024 size_t i;
4025 for (i=0; i<N; i++) {
4026 mOrderedConfigs.replaceAt(NULL, i);
4027 }
4028
4029 const size_t NP = mPublic.size();
4030 //printf("Ordering %d configs from %d public defs\n", N, NP);
4031 size_t j;
4032 for (j=0; j<NP; j++) {
4033 const String16& name = mPublic.keyAt(j);
4034 const Public& p = mPublic.valueAt(j);
4035 int32_t idx = Res_GETENTRY(p.ident);
4036 //printf("Looking for entry \"%s\"/\"%s\" (0x%08x) in %d...\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004037 // String8(mName).c_str(), String8(name).c_str(), p.ident, N);
Adam Lesinski282e1812014-01-23 18:17:42 -08004038 bool found = false;
4039 for (i=0; i<N; i++) {
4040 sp<ConfigList> e = origOrder.itemAt(i);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004041 //printf("#%d: \"%s\"\n", i, String8(e->getName()).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08004042 if (e->getName() == name) {
4043 if (idx >= (int32_t)mOrderedConfigs.size()) {
Adam Lesinski9b624c12014-11-19 17:49:26 -08004044 mOrderedConfigs.resize(idx + 1);
4045 }
4046
4047 if (mOrderedConfigs.itemAt(idx) == NULL) {
Adam Lesinski282e1812014-01-23 18:17:42 -08004048 e->setPublic(true);
4049 e->setPublicSourcePos(p.sourcePos);
4050 mOrderedConfigs.replaceAt(e, idx);
4051 origOrder.removeAt(i);
4052 N--;
4053 found = true;
4054 break;
4055 } else {
4056 sp<ConfigList> oe = mOrderedConfigs.itemAt(idx);
4057
4058 p.sourcePos.error("Multiple entry names declared for public entry"
4059 " identifier 0x%x in type %s (%s vs %s).\n"
4060 "%s:%d: Originally defined here.",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004061 idx+1, String8(mName).c_str(),
4062 String8(oe->getName()).c_str(),
4063 String8(name).c_str(),
4064 oe->getPublicSourcePos().file.c_str(),
Adam Lesinski282e1812014-01-23 18:17:42 -08004065 oe->getPublicSourcePos().line);
4066 hasError = true;
4067 }
4068 }
4069 }
4070
4071 if (!found) {
4072 p.sourcePos.error("Public symbol %s/%s declared here is not defined.",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004073 String8(mName).c_str(), String8(name).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08004074 hasError = true;
4075 }
4076 }
4077
4078 //printf("Copying back in %d non-public configs, have %d\n", N, origOrder.size());
4079
4080 if (N != origOrder.size()) {
4081 printf("Internal error: remaining private symbol count mismatch\n");
4082 N = origOrder.size();
4083 }
4084
4085 j = 0;
4086 for (i=0; i<N; i++) {
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -07004087 const sp<ConfigList>& e = origOrder.itemAt(i);
Adam Lesinski282e1812014-01-23 18:17:42 -08004088 // There will always be enough room for the remaining entries.
4089 while (mOrderedConfigs.itemAt(j) != NULL) {
4090 j++;
4091 }
4092 mOrderedConfigs.replaceAt(e, j);
4093 j++;
4094 }
4095
Andreas Gampe2412f842014-09-30 20:55:57 -07004096 return hasError ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08004097}
4098
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004099ResourceTable::Package::Package(const String16& name, size_t packageId)
4100 : mName(name), mPackageId(packageId),
Adam Lesinski282e1812014-01-23 18:17:42 -08004101 mTypeStringsMapping(0xffffffff),
4102 mKeyStringsMapping(0xffffffff)
4103{
4104}
4105
4106sp<ResourceTable::Type> ResourceTable::Package::getType(const String16& type,
4107 const SourcePos& sourcePos,
4108 bool doSetIndex)
4109{
4110 sp<Type> t = mTypes.valueFor(type);
4111 if (t == NULL) {
4112 t = new Type(type, sourcePos);
4113 mTypes.add(type, t);
4114 mOrderedTypes.add(t);
4115 if (doSetIndex) {
4116 // For some reason the type's index is set to one plus the index
4117 // in the mOrderedTypes list, rather than just the index.
4118 t->setIndex(mOrderedTypes.size());
4119 }
4120 }
4121 return t;
4122}
4123
4124status_t ResourceTable::Package::setTypeStrings(const sp<AaptFile>& data)
4125{
Adam Lesinski282e1812014-01-23 18:17:42 -08004126 status_t err = setStrings(data, &mTypeStrings, &mTypeStringsMapping);
4127 if (err != NO_ERROR) {
4128 fprintf(stderr, "ERROR: Type string data is corrupt!\n");
Adam Lesinski57079512014-07-29 11:51:35 -07004129 return err;
Adam Lesinski282e1812014-01-23 18:17:42 -08004130 }
Adam Lesinski57079512014-07-29 11:51:35 -07004131
4132 // Retain a reference to the new data after we've successfully replaced
4133 // all uses of the old reference (in setStrings() ).
4134 mTypeStringsData = data;
4135 return NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08004136}
4137
4138status_t ResourceTable::Package::setKeyStrings(const sp<AaptFile>& data)
4139{
Adam Lesinski282e1812014-01-23 18:17:42 -08004140 status_t err = setStrings(data, &mKeyStrings, &mKeyStringsMapping);
4141 if (err != NO_ERROR) {
4142 fprintf(stderr, "ERROR: Key string data is corrupt!\n");
Adam Lesinski57079512014-07-29 11:51:35 -07004143 return err;
Adam Lesinski282e1812014-01-23 18:17:42 -08004144 }
Adam Lesinski57079512014-07-29 11:51:35 -07004145
4146 // Retain a reference to the new data after we've successfully replaced
4147 // all uses of the old reference (in setStrings() ).
4148 mKeyStringsData = data;
4149 return NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08004150}
4151
4152status_t ResourceTable::Package::setStrings(const sp<AaptFile>& data,
4153 ResStringPool* strings,
4154 DefaultKeyedVector<String16, uint32_t>* mappings)
4155{
4156 if (data->getData() == NULL) {
4157 return UNKNOWN_ERROR;
4158 }
4159
Adam Lesinski282e1812014-01-23 18:17:42 -08004160 status_t err = strings->setTo(data->getData(), data->getSize());
4161 if (err == NO_ERROR) {
4162 const size_t N = strings->size();
4163 for (size_t i=0; i<N; i++) {
4164 size_t len;
Ryan Mitchell80094e32020-11-16 23:08:18 +00004165 mappings->add(String16(UnpackOptionalString(strings->stringAt(i), &len)), i);
Adam Lesinski282e1812014-01-23 18:17:42 -08004166 }
4167 }
4168 return err;
4169}
4170
4171status_t ResourceTable::Package::applyPublicTypeOrder()
4172{
4173 size_t N = mOrderedTypes.size();
4174 Vector<sp<Type> > origOrder(mOrderedTypes);
4175
4176 size_t i;
4177 for (i=0; i<N; i++) {
4178 mOrderedTypes.replaceAt(NULL, i);
4179 }
4180
4181 for (i=0; i<N; i++) {
4182 sp<Type> t = origOrder.itemAt(i);
4183 int32_t idx = t->getPublicIndex();
4184 if (idx > 0) {
4185 idx--;
4186 while (idx >= (int32_t)mOrderedTypes.size()) {
4187 mOrderedTypes.add();
4188 }
4189 if (mOrderedTypes.itemAt(idx) != NULL) {
4190 sp<Type> ot = mOrderedTypes.itemAt(idx);
4191 t->getFirstPublicSourcePos().error("Multiple type names declared for public type"
4192 " identifier 0x%x (%s vs %s).\n"
4193 "%s:%d: Originally defined here.",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004194 idx, String8(ot->getName()).c_str(),
4195 String8(t->getName()).c_str(),
4196 ot->getFirstPublicSourcePos().file.c_str(),
Adam Lesinski282e1812014-01-23 18:17:42 -08004197 ot->getFirstPublicSourcePos().line);
4198 return UNKNOWN_ERROR;
4199 }
4200 mOrderedTypes.replaceAt(t, idx);
4201 origOrder.removeAt(i);
4202 i--;
4203 N--;
4204 }
4205 }
4206
4207 size_t j=0;
4208 for (i=0; i<N; i++) {
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -07004209 const sp<Type>& t = origOrder.itemAt(i);
Adam Lesinski282e1812014-01-23 18:17:42 -08004210 // There will always be enough room for the remaining types.
4211 while (mOrderedTypes.itemAt(j) != NULL) {
4212 j++;
4213 }
4214 mOrderedTypes.replaceAt(t, j);
4215 }
4216
4217 return NO_ERROR;
4218}
4219
Adam Lesinski9b624c12014-11-19 17:49:26 -08004220void ResourceTable::Package::movePrivateAttrs() {
4221 sp<Type> attr = mTypes.valueFor(String16("attr"));
4222 if (attr == NULL) {
4223 // Nothing to do.
4224 return;
4225 }
4226
4227 Vector<sp<ConfigList> > privateAttrs;
4228
4229 bool hasPublic = false;
4230 const Vector<sp<ConfigList> >& configs = attr->getOrderedConfigs();
4231 const size_t configCount = configs.size();
4232 for (size_t i = 0; i < configCount; i++) {
4233 if (configs[i] == NULL) {
4234 continue;
4235 }
4236
4237 if (attr->isPublic(configs[i]->getName())) {
4238 hasPublic = true;
4239 } else {
4240 privateAttrs.add(configs[i]);
4241 }
4242 }
4243
4244 // Only if we have public attributes do we create a separate type for
4245 // private attributes.
4246 if (!hasPublic) {
4247 return;
4248 }
4249
4250 // Create a new type for private attributes.
4251 sp<Type> privateAttrType = getType(String16(kAttrPrivateType), SourcePos());
4252
4253 const size_t privateAttrCount = privateAttrs.size();
4254 for (size_t i = 0; i < privateAttrCount; i++) {
4255 const sp<ConfigList>& cl = privateAttrs[i];
4256
4257 // Remove the private attributes from their current type.
4258 attr->removeEntry(cl->getName());
4259
4260 // Add it to the new type.
4261 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& entries = cl->getEntries();
4262 const size_t entryCount = entries.size();
4263 for (size_t j = 0; j < entryCount; j++) {
4264 const sp<Entry>& oldEntry = entries[j];
4265 sp<Entry> entry = privateAttrType->getEntry(
4266 cl->getName(), oldEntry->getPos(), &entries.keyAt(j));
4267 *entry = *oldEntry;
4268 }
4269
4270 // Move the symbols to the new type.
4271
4272 }
4273}
4274
Adam Lesinski282e1812014-01-23 18:17:42 -08004275sp<ResourceTable::Package> ResourceTable::getPackage(const String16& package)
4276{
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004277 if (package != mAssetsPackage) {
4278 return NULL;
Adam Lesinski282e1812014-01-23 18:17:42 -08004279 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004280 return mPackages.valueFor(package);
Adam Lesinski282e1812014-01-23 18:17:42 -08004281}
4282
4283sp<ResourceTable::Type> ResourceTable::getType(const String16& package,
4284 const String16& type,
4285 const SourcePos& sourcePos,
4286 bool doSetIndex)
4287{
4288 sp<Package> p = getPackage(package);
4289 if (p == NULL) {
4290 return NULL;
4291 }
4292 return p->getType(type, sourcePos, doSetIndex);
4293}
4294
4295sp<ResourceTable::Entry> ResourceTable::getEntry(const String16& package,
4296 const String16& type,
4297 const String16& name,
4298 const SourcePos& sourcePos,
4299 bool overlay,
4300 const ResTable_config* config,
4301 bool doSetIndex)
4302{
4303 sp<Type> t = getType(package, type, sourcePos, doSetIndex);
4304 if (t == NULL) {
4305 return NULL;
4306 }
4307 return t->getEntry(name, sourcePos, config, doSetIndex, overlay, mBundle->getAutoAddOverlay());
4308}
4309
Adam Lesinskie572c012014-09-19 15:10:04 -07004310sp<ResourceTable::ConfigList> ResourceTable::getConfigList(const String16& package,
4311 const String16& type, const String16& name) const
4312{
4313 const size_t packageCount = mOrderedPackages.size();
4314 for (size_t pi = 0; pi < packageCount; pi++) {
4315 const sp<Package>& p = mOrderedPackages[pi];
4316 if (p == NULL || p->getName() != package) {
4317 continue;
4318 }
4319
4320 const Vector<sp<Type> >& types = p->getOrderedTypes();
4321 const size_t typeCount = types.size();
4322 for (size_t ti = 0; ti < typeCount; ti++) {
4323 const sp<Type>& t = types[ti];
4324 if (t == NULL || t->getName() != type) {
4325 continue;
4326 }
4327
4328 const Vector<sp<ConfigList> >& configs = t->getOrderedConfigs();
4329 const size_t configCount = configs.size();
4330 for (size_t ci = 0; ci < configCount; ci++) {
4331 const sp<ConfigList>& cl = configs[ci];
4332 if (cl == NULL || cl->getName() != name) {
4333 continue;
4334 }
4335
4336 return cl;
4337 }
4338 }
4339 }
4340 return NULL;
4341}
4342
Adam Lesinski282e1812014-01-23 18:17:42 -08004343sp<const ResourceTable::Entry> ResourceTable::getEntry(uint32_t resID,
4344 const ResTable_config* config) const
4345{
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004346 size_t pid = Res_GETPACKAGE(resID)+1;
Adam Lesinski282e1812014-01-23 18:17:42 -08004347 const size_t N = mOrderedPackages.size();
Adam Lesinski282e1812014-01-23 18:17:42 -08004348 sp<Package> p;
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004349 for (size_t i = 0; i < N; i++) {
Adam Lesinski282e1812014-01-23 18:17:42 -08004350 sp<Package> check = mOrderedPackages[i];
4351 if (check->getAssignedId() == pid) {
4352 p = check;
4353 break;
4354 }
4355
4356 }
4357 if (p == NULL) {
4358 fprintf(stderr, "warning: Package not found for resource #%08x\n", resID);
4359 return NULL;
4360 }
4361
4362 int tid = Res_GETTYPE(resID);
4363 if (tid < 0 || tid >= (int)p->getOrderedTypes().size()) {
4364 fprintf(stderr, "warning: Type not found for resource #%08x\n", resID);
4365 return NULL;
4366 }
4367 sp<Type> t = p->getOrderedTypes()[tid];
4368
4369 int eid = Res_GETENTRY(resID);
4370 if (eid < 0 || eid >= (int)t->getOrderedConfigs().size()) {
4371 fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
4372 return NULL;
4373 }
4374
4375 sp<ConfigList> c = t->getOrderedConfigs()[eid];
4376 if (c == NULL) {
4377 fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
4378 return NULL;
4379 }
4380
4381 ConfigDescription cdesc;
4382 if (config) cdesc = *config;
4383 sp<Entry> e = c->getEntries().valueFor(cdesc);
4384 if (c == NULL) {
4385 fprintf(stderr, "warning: Entry configuration not found for resource #%08x\n", resID);
4386 return NULL;
4387 }
4388
4389 return e;
4390}
4391
4392const ResourceTable::Item* ResourceTable::getItem(uint32_t resID, uint32_t attrID) const
4393{
4394 sp<const Entry> e = getEntry(resID);
4395 if (e == NULL) {
4396 return NULL;
4397 }
4398
4399 const size_t N = e->getBag().size();
4400 for (size_t i=0; i<N; i++) {
4401 const Item& it = e->getBag().valueAt(i);
4402 if (it.bagKeyId == 0) {
4403 fprintf(stderr, "warning: ID not yet assigned to '%s' in bag '%s'\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004404 String8(e->getName()).c_str(),
4405 String8(e->getBag().keyAt(i)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08004406 }
4407 if (it.bagKeyId == attrID) {
4408 return &it;
4409 }
4410 }
4411
4412 return NULL;
4413}
4414
4415bool ResourceTable::getItemValue(
4416 uint32_t resID, uint32_t attrID, Res_value* outValue)
4417{
4418 const Item* item = getItem(resID, attrID);
4419
4420 bool res = false;
4421 if (item != NULL) {
4422 if (item->evaluating) {
4423 sp<const Entry> e = getEntry(resID);
4424 const size_t N = e->getBag().size();
4425 size_t i;
4426 for (i=0; i<N; i++) {
4427 if (&e->getBag().valueAt(i) == item) {
4428 break;
4429 }
4430 }
4431 fprintf(stderr, "warning: Circular reference detected in key '%s' of bag '%s'\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004432 String8(e->getName()).c_str(),
4433 String8(e->getBag().keyAt(i)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08004434 return false;
4435 }
4436 item->evaluating = true;
4437 res = stringToValue(outValue, NULL, item->value, false, false, item->bagKeyId);
Andreas Gampe2412f842014-09-30 20:55:57 -07004438 if (kIsDebug) {
Adam Lesinski282e1812014-01-23 18:17:42 -08004439 if (res) {
4440 printf("getItemValue of #%08x[#%08x] (%s): type=#%08x, data=#%08x\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004441 resID, attrID, String8(getEntry(resID)->getName()).c_str(),
Adam Lesinski282e1812014-01-23 18:17:42 -08004442 outValue->dataType, outValue->data);
4443 } else {
4444 printf("getItemValue of #%08x[#%08x]: failed\n",
4445 resID, attrID);
4446 }
Andreas Gampe2412f842014-09-30 20:55:57 -07004447 }
Adam Lesinski282e1812014-01-23 18:17:42 -08004448 item->evaluating = false;
4449 }
4450 return res;
4451}
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004452
4453/**
Adam Lesinski28994d82015-01-13 13:42:41 -08004454 * Returns the SDK version at which the attribute was
4455 * made public, or -1 if the resource ID is not an attribute
4456 * or is not public.
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004457 */
Adam Lesinski28994d82015-01-13 13:42:41 -08004458int ResourceTable::getPublicAttributeSdkLevel(uint32_t attrId) const {
4459 if (Res_GETPACKAGE(attrId) + 1 != 0x01 || Res_GETTYPE(attrId) + 1 != 0x01) {
4460 return -1;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004461 }
4462
4463 uint32_t specFlags;
4464 if (!mAssets->getIncludedResources().getResourceFlags(attrId, &specFlags)) {
Adam Lesinski28994d82015-01-13 13:42:41 -08004465 return -1;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004466 }
4467
Adam Lesinski28994d82015-01-13 13:42:41 -08004468 if ((specFlags & ResTable_typeSpec::SPEC_PUBLIC) == 0) {
4469 return -1;
4470 }
4471
4472 const size_t entryId = Res_GETENTRY(attrId);
4473 if (entryId <= 0x021c) {
4474 return 1;
4475 } else if (entryId <= 0x021d) {
4476 return 2;
4477 } else if (entryId <= 0x0269) {
4478 return SDK_CUPCAKE;
4479 } else if (entryId <= 0x028d) {
4480 return SDK_DONUT;
4481 } else if (entryId <= 0x02ad) {
4482 return SDK_ECLAIR;
4483 } else if (entryId <= 0x02b3) {
4484 return SDK_ECLAIR_0_1;
4485 } else if (entryId <= 0x02b5) {
4486 return SDK_ECLAIR_MR1;
4487 } else if (entryId <= 0x02bd) {
4488 return SDK_FROYO;
4489 } else if (entryId <= 0x02cb) {
4490 return SDK_GINGERBREAD;
4491 } else if (entryId <= 0x0361) {
4492 return SDK_HONEYCOMB;
4493 } else if (entryId <= 0x0366) {
4494 return SDK_HONEYCOMB_MR1;
4495 } else if (entryId <= 0x03a6) {
4496 return SDK_HONEYCOMB_MR2;
4497 } else if (entryId <= 0x03ae) {
4498 return SDK_JELLY_BEAN;
4499 } else if (entryId <= 0x03cc) {
4500 return SDK_JELLY_BEAN_MR1;
4501 } else if (entryId <= 0x03da) {
4502 return SDK_JELLY_BEAN_MR2;
4503 } else if (entryId <= 0x03f1) {
4504 return SDK_KITKAT;
4505 } else if (entryId <= 0x03f6) {
4506 return SDK_KITKAT_WATCH;
4507 } else if (entryId <= 0x04ce) {
4508 return SDK_LOLLIPOP;
4509 } else {
4510 // Anything else is marked as defined in
4511 // SDK_LOLLIPOP_MR1 since after this
4512 // version no attribute compat work
4513 // needs to be done.
4514 return SDK_LOLLIPOP_MR1;
4515 }
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004516}
4517
Adam Lesinski28994d82015-01-13 13:42:41 -08004518/**
4519 * First check the Manifest, then check the command line flag.
4520 */
4521static int getMinSdkVersion(const Bundle* bundle) {
4522 if (bundle->getManifestMinSdkVersion() != NULL && strlen(bundle->getManifestMinSdkVersion()) > 0) {
4523 return atoi(bundle->getManifestMinSdkVersion());
4524 } else if (bundle->getMinSdkVersion() != NULL && strlen(bundle->getMinSdkVersion()) > 0) {
4525 return atoi(bundle->getMinSdkVersion());
Adam Lesinskie572c012014-09-19 15:10:04 -07004526 }
Adam Lesinski28994d82015-01-13 13:42:41 -08004527 return 0;
Adam Lesinskie572c012014-09-19 15:10:04 -07004528}
4529
Adam Lesinskibeb9e332015-08-14 13:16:18 -07004530bool ResourceTable::shouldGenerateVersionedResource(
4531 const sp<ResourceTable::ConfigList>& configList,
4532 const ConfigDescription& sourceConfig,
4533 const int sdkVersionToGenerate) {
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004534 assert(sdkVersionToGenerate > sourceConfig.sdkVersion);
Adam Lesinski526d73b2016-07-18 17:01:14 -07004535 assert(configList != NULL);
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004536 const DefaultKeyedVector<ConfigDescription, sp<ResourceTable::Entry>>& entries
4537 = configList->getEntries();
4538 ssize_t idx = entries.indexOfKey(sourceConfig);
4539
4540 // The source config came from this list, so it should be here.
4541 assert(idx >= 0);
4542
Adam Lesinskibeb9e332015-08-14 13:16:18 -07004543 // The next configuration either only varies in sdkVersion, or it is completely different
4544 // and therefore incompatible. If it is incompatible, we must generate the versioned resource.
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004545
Adam Lesinskibeb9e332015-08-14 13:16:18 -07004546 // NOTE: The ordering of configurations takes sdkVersion as higher precedence than other
4547 // qualifiers, so we need to iterate through the entire list to be sure there
4548 // are no higher sdk level versions of this resource.
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004549 ConfigDescription tempConfig(sourceConfig);
Adam Lesinskibeb9e332015-08-14 13:16:18 -07004550 for (size_t i = static_cast<size_t>(idx) + 1; i < entries.size(); i++) {
4551 const ConfigDescription& nextConfig = entries.keyAt(i);
4552 tempConfig.sdkVersion = nextConfig.sdkVersion;
4553 if (tempConfig == nextConfig) {
4554 // The two configs are the same, check the sdk version.
4555 return sdkVersionToGenerate < nextConfig.sdkVersion;
4556 }
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004557 }
Adam Lesinskibeb9e332015-08-14 13:16:18 -07004558
4559 // No match was found, so we should generate the versioned resource.
4560 return true;
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004561}
4562
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004563/**
4564 * Modifies the entries in the resource table to account for compatibility
4565 * issues with older versions of Android.
4566 *
4567 * This primarily handles the issue of private/public attribute clashes
4568 * in framework resources.
4569 *
4570 * AAPT has traditionally assigned resource IDs to public attributes,
4571 * and then followed those public definitions with private attributes.
4572 *
4573 * --- PUBLIC ---
4574 * | 0x01010234 | attr/color
4575 * | 0x01010235 | attr/background
4576 *
4577 * --- PRIVATE ---
4578 * | 0x01010236 | attr/secret
4579 * | 0x01010237 | attr/shhh
4580 *
4581 * Each release, when attributes are added, they take the place of the private
4582 * attributes and the private attributes are shifted down again.
4583 *
4584 * --- PUBLIC ---
4585 * | 0x01010234 | attr/color
4586 * | 0x01010235 | attr/background
4587 * | 0x01010236 | attr/shinyNewAttr
4588 * | 0x01010237 | attr/highlyValuedFeature
4589 *
4590 * --- PRIVATE ---
4591 * | 0x01010238 | attr/secret
4592 * | 0x01010239 | attr/shhh
4593 *
4594 * Platform code may look for private attributes set in a theme. If an app
4595 * compiled against a newer version of the platform uses a new public
4596 * attribute that happens to have the same ID as the private attribute
4597 * the older platform is expecting, then the behavior is undefined.
4598 *
4599 * We get around this by detecting any newly defined attributes (in L),
4600 * copy the resource into a -v21 qualified resource, and delete the
4601 * attribute from the original resource. This ensures that older platforms
4602 * don't see the new attribute, but when running on L+ platforms, the
4603 * attribute will be respected.
4604 */
4605status_t ResourceTable::modifyForCompat(const Bundle* bundle) {
Adam Lesinski28994d82015-01-13 13:42:41 -08004606 const int minSdk = getMinSdkVersion(bundle);
4607 if (minSdk >= SDK_LOLLIPOP_MR1) {
4608 // Lollipop MR1 and up handles public attributes differently, no
4609 // need to do any compat modifications.
Adam Lesinskie572c012014-09-19 15:10:04 -07004610 return NO_ERROR;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004611 }
4612
4613 const String16 attr16("attr");
4614
4615 const size_t packageCount = mOrderedPackages.size();
4616 for (size_t pi = 0; pi < packageCount; pi++) {
4617 sp<Package> p = mOrderedPackages.itemAt(pi);
4618 if (p == NULL || p->getTypes().size() == 0) {
4619 // Empty, skip!
4620 continue;
4621 }
4622
4623 const size_t typeCount = p->getOrderedTypes().size();
4624 for (size_t ti = 0; ti < typeCount; ti++) {
4625 sp<Type> t = p->getOrderedTypes().itemAt(ti);
4626 if (t == NULL) {
4627 continue;
4628 }
4629
4630 const size_t configCount = t->getOrderedConfigs().size();
4631 for (size_t ci = 0; ci < configCount; ci++) {
4632 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
4633 if (c == NULL) {
4634 continue;
4635 }
4636
4637 Vector<key_value_pair_t<ConfigDescription, sp<Entry> > > entriesToAdd;
4638 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& entries =
4639 c->getEntries();
4640 const size_t entryCount = entries.size();
4641 for (size_t ei = 0; ei < entryCount; ei++) {
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -07004642 const sp<Entry>& e = entries.valueAt(ei);
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004643 if (e == NULL || e->getType() != Entry::TYPE_BAG) {
4644 continue;
4645 }
4646
4647 const ConfigDescription& config = entries.keyAt(ei);
Adam Lesinski28994d82015-01-13 13:42:41 -08004648 if (config.sdkVersion >= SDK_LOLLIPOP_MR1) {
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004649 continue;
4650 }
4651
Adam Lesinski28994d82015-01-13 13:42:41 -08004652 KeyedVector<int, Vector<String16> > attributesToRemove;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004653 const KeyedVector<String16, Item>& bag = e->getBag();
4654 const size_t bagCount = bag.size();
4655 for (size_t bi = 0; bi < bagCount; bi++) {
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004656 const uint32_t attrId = getResId(bag.keyAt(bi), &attr16);
Adam Lesinski28994d82015-01-13 13:42:41 -08004657 const int sdkLevel = getPublicAttributeSdkLevel(attrId);
4658 if (sdkLevel > 1 && sdkLevel > config.sdkVersion && sdkLevel > minSdk) {
4659 AaptUtil::appendValue(attributesToRemove, sdkLevel, bag.keyAt(bi));
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004660 }
4661 }
4662
4663 if (attributesToRemove.isEmpty()) {
4664 continue;
4665 }
4666
Adam Lesinski28994d82015-01-13 13:42:41 -08004667 const size_t sdkCount = attributesToRemove.size();
4668 for (size_t i = 0; i < sdkCount; i++) {
4669 const int sdkLevel = attributesToRemove.keyAt(i);
4670
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004671 if (!shouldGenerateVersionedResource(c, config, sdkLevel)) {
4672 // There is a style that will override this generated one.
4673 continue;
4674 }
4675
Adam Lesinski28994d82015-01-13 13:42:41 -08004676 // Duplicate the entry under the same configuration
4677 // but with sdkVersion == sdkLevel.
4678 ConfigDescription newConfig(config);
4679 newConfig.sdkVersion = sdkLevel;
4680
4681 sp<Entry> newEntry = new Entry(*e);
4682
4683 // Remove all items that have a higher SDK level than
4684 // the one we are synthesizing.
4685 for (size_t j = 0; j < sdkCount; j++) {
4686 if (j == i) {
4687 continue;
4688 }
4689
4690 if (attributesToRemove.keyAt(j) > sdkLevel) {
4691 const size_t attrCount = attributesToRemove[j].size();
4692 for (size_t k = 0; k < attrCount; k++) {
4693 newEntry->removeFromBag(attributesToRemove[j][k]);
4694 }
4695 }
4696 }
4697
4698 entriesToAdd.add(key_value_pair_t<ConfigDescription, sp<Entry> >(
4699 newConfig, newEntry));
4700 }
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004701
4702 // Remove the attribute from the original.
4703 for (size_t i = 0; i < attributesToRemove.size(); i++) {
Adam Lesinski28994d82015-01-13 13:42:41 -08004704 for (size_t j = 0; j < attributesToRemove[i].size(); j++) {
4705 e->removeFromBag(attributesToRemove[i][j]);
4706 }
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004707 }
4708 }
4709
4710 const size_t entriesToAddCount = entriesToAdd.size();
4711 for (size_t i = 0; i < entriesToAddCount; i++) {
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004712 assert(entries.indexOfKey(entriesToAdd[i].key) < 0);
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004713
Adam Lesinskif15de2e2014-10-03 14:57:28 -07004714 if (bundle->getVerbose()) {
4715 entriesToAdd[i].value->getPos()
4716 .printf("using v%d attributes; synthesizing resource %s:%s/%s for configuration %s.",
Adam Lesinski28994d82015-01-13 13:42:41 -08004717 entriesToAdd[i].key.sdkVersion,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004718 String8(p->getName()).c_str(),
4719 String8(t->getName()).c_str(),
4720 String8(entriesToAdd[i].value->getName()).c_str(),
4721 entriesToAdd[i].key.toString().c_str());
Adam Lesinskif15de2e2014-10-03 14:57:28 -07004722 }
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004723
Adam Lesinski978ab9d2014-09-24 19:02:52 -07004724 sp<Entry> newEntry = t->getEntry(c->getName(),
4725 entriesToAdd[i].value->getPos(),
4726 &entriesToAdd[i].key);
4727
4728 *newEntry = *entriesToAdd[i].value;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004729 }
4730 }
4731 }
4732 }
4733 return NO_ERROR;
4734}
Adam Lesinskie572c012014-09-19 15:10:04 -07004735
Yuichi Araki4d35cca2017-01-18 20:42:17 +09004736const String16 kTransitionElements[] = {
4737 String16("fade"),
4738 String16("changeBounds"),
4739 String16("slide"),
4740 String16("explode"),
4741 String16("changeImageTransform"),
4742 String16("changeTransform"),
4743 String16("changeClipBounds"),
4744 String16("autoTransition"),
4745 String16("recolor"),
4746 String16("changeScroll"),
4747 String16("transitionSet"),
4748 String16("transition"),
4749 String16("transitionManager"),
4750};
4751
4752static bool IsTransitionElement(const String16& name) {
4753 for (int i = 0, size = sizeof(kTransitionElements) / sizeof(kTransitionElements[0]);
4754 i < size; ++i) {
4755 if (name == kTransitionElements[i]) {
4756 return true;
4757 }
4758 }
4759 return false;
4760}
4761
Adam Lesinskicf1f1d92017-03-16 16:54:23 -07004762bool ResourceTable::versionForCompat(const Bundle* bundle, const String16& resourceName,
4763 const sp<AaptFile>& target, const sp<XMLNode>& root) {
4764 XMLNode* node = root.get();
4765 while (node->getType() != XMLNode::TYPE_ELEMENT) {
4766 // We're assuming the root element is what we're looking for, which can only be under a
4767 // bunch of namespace declarations.
4768 if (node->getChildren().size() != 1) {
4769 // Not sure what to do, bail.
4770 return false;
4771 }
4772 node = node->getChildren().itemAt(0).get();
4773 }
4774
4775 if (node->getElementNamespace().size() != 0) {
4776 // Not something we care about.
4777 return false;
4778 }
4779
4780 int versionedSdk = 0;
4781 if (node->getElementName() == String16("adaptive-icon")) {
4782 versionedSdk = SDK_O;
4783 }
4784
4785 const int minSdkVersion = getMinSdkVersion(bundle);
4786 const ConfigDescription config(target->getGroupEntry().toParams());
4787 if (versionedSdk <= minSdkVersion || versionedSdk <= config.sdkVersion) {
4788 return false;
4789 }
4790
4791 sp<ConfigList> cl = getConfigList(String16(mAssets->getPackage()),
4792 String16(target->getResourceType()), resourceName);
4793 if (!shouldGenerateVersionedResource(cl, config, versionedSdk)) {
4794 return false;
4795 }
4796
4797 // Remove the original entry.
4798 cl->removeEntry(config);
4799
4800 // We need to wholesale version this file.
4801 ConfigDescription newConfig(config);
4802 newConfig.sdkVersion = versionedSdk;
4803 sp<AaptFile> newFile = new AaptFile(target->getSourceFile(),
4804 AaptGroupEntry(newConfig), target->getResourceType());
4805 String8 resPath = String8::format("res/%s/%s.xml",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004806 newFile->getGroupEntry().toDirName(target->getResourceType()).c_str(),
4807 String8(resourceName).c_str());
Elliott Hughes338698e2021-07-13 17:15:19 -07004808 convertToResPath(resPath);
Adam Lesinskicf1f1d92017-03-16 16:54:23 -07004809
4810 // Add a resource table entry.
4811 addEntry(SourcePos(),
4812 String16(mAssets->getPackage()),
4813 String16(target->getResourceType()),
4814 resourceName,
4815 String16(resPath),
4816 NULL,
4817 &newConfig);
4818
4819 // Schedule this to be compiled.
4820 CompileResourceWorkItem item;
4821 item.resourceName = resourceName;
4822 item.resPath = resPath;
4823 item.file = newFile;
4824 item.xmlRoot = root->clone();
Adam Lesinski54b58ba2017-04-14 18:44:30 -07004825 item.needsCompiling = true;
Adam Lesinskicf1f1d92017-03-16 16:54:23 -07004826 mWorkQueue.push(item);
4827
4828 // Now mark the old entry as deleted.
4829 return true;
4830}
4831
Adam Lesinskie572c012014-09-19 15:10:04 -07004832status_t ResourceTable::modifyForCompat(const Bundle* bundle,
4833 const String16& resourceName,
4834 const sp<AaptFile>& target,
4835 const sp<XMLNode>& root) {
Adam Lesinski6e460562015-04-21 14:20:15 -07004836 const String16 vector16("vector");
4837 const String16 animatedVector16("animated-vector");
ztenghui010df882017-03-07 15:50:03 -08004838 const String16 pathInterpolator16("pathInterpolator");
ztenghui20554852017-03-21 16:28:57 -07004839 const String16 objectAnimator16("objectAnimator");
ztenghuiab2a38c2017-10-13 15:56:08 -07004840 const String16 gradient16("gradient");
Nick Butchere78a8162018-01-09 15:24:21 +00004841 const String16 animatedSelector16("animated-selector");
Adam Lesinski6e460562015-04-21 14:20:15 -07004842
Adam Lesinski28994d82015-01-13 13:42:41 -08004843 const int minSdk = getMinSdkVersion(bundle);
4844 if (minSdk >= SDK_LOLLIPOP_MR1) {
4845 // Lollipop MR1 and up handles public attributes differently, no
4846 // need to do any compat modifications.
Adam Lesinskie572c012014-09-19 15:10:04 -07004847 return NO_ERROR;
4848 }
4849
Adam Lesinski28994d82015-01-13 13:42:41 -08004850 const ConfigDescription config(target->getGroupEntry().toParams());
4851 if (target->getResourceType() == "" || config.sdkVersion >= SDK_LOLLIPOP_MR1) {
Adam Lesinski6e460562015-04-21 14:20:15 -07004852 // Skip resources that have no type (AndroidManifest.xml) or are already version qualified
4853 // with v21 or higher.
Adam Lesinskie572c012014-09-19 15:10:04 -07004854 return NO_ERROR;
4855 }
4856
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004857 sp<XMLNode> newRoot = NULL;
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004858 int sdkVersionToGenerate = SDK_LOLLIPOP_MR1;
Adam Lesinskie572c012014-09-19 15:10:04 -07004859
4860 Vector<sp<XMLNode> > nodesToVisit;
4861 nodesToVisit.push(root);
Tomasz Wasilczyk7e22cab2023-08-24 19:02:33 +00004862 while (!nodesToVisit.empty()) {
Adam Lesinskie572c012014-09-19 15:10:04 -07004863 sp<XMLNode> node = nodesToVisit.top();
4864 nodesToVisit.pop();
4865
Adam Lesinski6e460562015-04-21 14:20:15 -07004866 if (bundle->getNoVersionVectors() && (node->getElementName() == vector16 ||
ztenghui010df882017-03-07 15:50:03 -08004867 node->getElementName() == animatedVector16 ||
ztenghui20554852017-03-21 16:28:57 -07004868 node->getElementName() == objectAnimator16 ||
ztenghuiab2a38c2017-10-13 15:56:08 -07004869 node->getElementName() == pathInterpolator16 ||
Nick Butchere78a8162018-01-09 15:24:21 +00004870 node->getElementName() == gradient16 ||
4871 node->getElementName() == animatedSelector16)) {
Adam Lesinski6e460562015-04-21 14:20:15 -07004872 // We were told not to version vector tags, so skip the children here.
4873 continue;
4874 }
4875
Yuichi Araki4d35cca2017-01-18 20:42:17 +09004876 if (bundle->getNoVersionTransitions() && (IsTransitionElement(node->getElementName()))) {
4877 // We were told not to version transition tags, so skip the children here.
4878 continue;
4879 }
4880
Adam Lesinskie572c012014-09-19 15:10:04 -07004881 const Vector<XMLNode::attribute_entry>& attrs = node->getAttributes();
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004882 for (size_t i = 0; i < attrs.size(); i++) {
Adam Lesinskie572c012014-09-19 15:10:04 -07004883 const XMLNode::attribute_entry& attr = attrs[i];
Adam Lesinski28994d82015-01-13 13:42:41 -08004884 const int sdkLevel = getPublicAttributeSdkLevel(attr.nameResId);
4885 if (sdkLevel > 1 && sdkLevel > config.sdkVersion && sdkLevel > minSdk) {
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004886 if (newRoot == NULL) {
4887 newRoot = root->clone();
4888 }
4889
Adam Lesinski28994d82015-01-13 13:42:41 -08004890 // Find the smallest sdk version that we need to synthesize for
4891 // and do that one. Subsequent versions will be processed on
4892 // the next pass.
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004893 sdkVersionToGenerate = std::min(sdkLevel, sdkVersionToGenerate);
Adam Lesinski28994d82015-01-13 13:42:41 -08004894
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004895 if (bundle->getVerbose()) {
4896 SourcePos(node->getFilename(), node->getStartLineNumber()).printf(
4897 "removing attribute %s%s%s from <%s>",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004898 String8(attr.ns).c_str(),
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004899 (attr.ns.size() == 0 ? "" : ":"),
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004900 String8(attr.name).c_str(),
4901 String8(node->getElementName()).c_str());
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004902 }
4903 node->removeAttribute(i);
4904 i--;
Adam Lesinskie572c012014-09-19 15:10:04 -07004905 }
4906 }
4907
4908 // Schedule a visit to the children.
4909 const Vector<sp<XMLNode> >& children = node->getChildren();
4910 const size_t childCount = children.size();
4911 for (size_t i = 0; i < childCount; i++) {
4912 nodesToVisit.push(children[i]);
4913 }
4914 }
4915
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004916 if (newRoot == NULL) {
Adam Lesinskie572c012014-09-19 15:10:04 -07004917 return NO_ERROR;
4918 }
4919
Adam Lesinskie572c012014-09-19 15:10:04 -07004920 // Look to see if we already have an overriding v21 configuration.
4921 sp<ConfigList> cl = getConfigList(String16(mAssets->getPackage()),
4922 String16(target->getResourceType()), resourceName);
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004923 if (shouldGenerateVersionedResource(cl, config, sdkVersionToGenerate)) {
Adam Lesinskie572c012014-09-19 15:10:04 -07004924 // We don't have an overriding entry for v21, so we must duplicate this one.
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004925 ConfigDescription newConfig(config);
4926 newConfig.sdkVersion = sdkVersionToGenerate;
Adam Lesinskie572c012014-09-19 15:10:04 -07004927 sp<AaptFile> newFile = new AaptFile(target->getSourceFile(),
4928 AaptGroupEntry(newConfig), target->getResourceType());
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07004929 String8 resPath = String8::format("res/%s/%s.xml",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004930 newFile->getGroupEntry().toDirName(target->getResourceType()).c_str(),
4931 String8(resourceName).c_str());
Elliott Hughes338698e2021-07-13 17:15:19 -07004932 convertToResPath(resPath);
Adam Lesinskie572c012014-09-19 15:10:04 -07004933
4934 // Add a resource table entry.
Adam Lesinskif15de2e2014-10-03 14:57:28 -07004935 if (bundle->getVerbose()) {
4936 SourcePos(target->getSourceFile(), -1).printf(
4937 "using v%d attributes; synthesizing resource %s:%s/%s for configuration %s.",
Adam Lesinski28994d82015-01-13 13:42:41 -08004938 newConfig.sdkVersion,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004939 mAssets->getPackage().c_str(),
4940 newFile->getResourceType().c_str(),
4941 String8(resourceName).c_str(),
4942 newConfig.toString().c_str());
Adam Lesinskif15de2e2014-10-03 14:57:28 -07004943 }
Adam Lesinskie572c012014-09-19 15:10:04 -07004944
4945 addEntry(SourcePos(),
4946 String16(mAssets->getPackage()),
4947 String16(target->getResourceType()),
4948 resourceName,
4949 String16(resPath),
4950 NULL,
4951 &newConfig);
4952
4953 // Schedule this to be compiled.
4954 CompileResourceWorkItem item;
4955 item.resourceName = resourceName;
4956 item.resPath = resPath;
4957 item.file = newFile;
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07004958 item.xmlRoot = newRoot;
4959 item.needsCompiling = false; // This step occurs after we parse/assign, so we don't need
4960 // to do it again.
Adam Lesinskie572c012014-09-19 15:10:04 -07004961 mWorkQueue.push(item);
4962 }
Adam Lesinskie572c012014-09-19 15:10:04 -07004963 return NO_ERROR;
4964}
Adam Lesinskide7de472014-11-03 12:03:08 -08004965
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004966void ResourceTable::getDensityVaryingResources(
4967 KeyedVector<Symbol, Vector<SymbolDefinition> >& resources) {
Adam Lesinskide7de472014-11-03 12:03:08 -08004968 const ConfigDescription nullConfig;
4969
4970 const size_t packageCount = mOrderedPackages.size();
4971 for (size_t p = 0; p < packageCount; p++) {
4972 const Vector<sp<Type> >& types = mOrderedPackages[p]->getOrderedTypes();
4973 const size_t typeCount = types.size();
4974 for (size_t t = 0; t < typeCount; t++) {
Adam Lesinski081d1b42016-08-15 18:45:00 -07004975 const sp<Type>& type = types[t];
4976 if (type == NULL) {
4977 continue;
4978 }
4979
4980 const Vector<sp<ConfigList> >& configs = type->getOrderedConfigs();
Adam Lesinskide7de472014-11-03 12:03:08 -08004981 const size_t configCount = configs.size();
4982 for (size_t c = 0; c < configCount; c++) {
Adam Lesinski081d1b42016-08-15 18:45:00 -07004983 const sp<ConfigList>& configList = configs[c];
4984 if (configList == NULL) {
4985 continue;
4986 }
4987
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004988 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& configEntries
Adam Lesinski081d1b42016-08-15 18:45:00 -07004989 = configList->getEntries();
Adam Lesinskide7de472014-11-03 12:03:08 -08004990 const size_t configEntryCount = configEntries.size();
4991 for (size_t ce = 0; ce < configEntryCount; ce++) {
Adam Lesinski081d1b42016-08-15 18:45:00 -07004992 const sp<Entry>& entry = configEntries.valueAt(ce);
4993 if (entry == NULL) {
4994 continue;
4995 }
4996
Adam Lesinskide7de472014-11-03 12:03:08 -08004997 const ConfigDescription& config = configEntries.keyAt(ce);
4998 if (AaptConfig::isDensityOnly(config)) {
4999 // This configuration only varies with regards to density.
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07005000 const Symbol symbol(
5001 mOrderedPackages[p]->getName(),
Adam Lesinski081d1b42016-08-15 18:45:00 -07005002 type->getName(),
5003 configList->getName(),
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07005004 getResId(mOrderedPackages[p], types[t],
Adam Lesinski081d1b42016-08-15 18:45:00 -07005005 configList->getEntryIndex()));
Adam Lesinskide7de472014-11-03 12:03:08 -08005006
Adam Lesinski081d1b42016-08-15 18:45:00 -07005007
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07005008 AaptUtil::appendValue(resources, symbol,
5009 SymbolDefinition(symbol, config, entry->getPos()));
Adam Lesinskide7de472014-11-03 12:03:08 -08005010 }
5011 }
5012 }
5013 }
5014 }
5015}
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07005016
5017static String16 buildNamespace(const String16& package) {
5018 return String16("http://schemas.android.com/apk/res/") + package;
5019}
5020
5021static sp<XMLNode> findOnlyChildElement(const sp<XMLNode>& parent) {
5022 const Vector<sp<XMLNode> >& children = parent->getChildren();
5023 sp<XMLNode> onlyChild;
5024 for (size_t i = 0; i < children.size(); i++) {
5025 if (children[i]->getType() != XMLNode::TYPE_CDATA) {
5026 if (onlyChild != NULL) {
5027 return NULL;
5028 }
5029 onlyChild = children[i];
5030 }
5031 }
5032 return onlyChild;
5033}
5034
5035/**
5036 * Detects use of the `bundle' format and extracts nested resources into their own top level
5037 * resources. The bundle format looks like this:
5038 *
5039 * <!-- res/drawable/bundle.xml -->
5040 * <animated-vector xmlns:aapt="http://schemas.android.com/aapt">
5041 * <aapt:attr name="android:drawable">
5042 * <vector android:width="60dp"
5043 * android:height="60dp">
5044 * <path android:name="v"
5045 * android:fillColor="#000000"
5046 * android:pathData="M300,70 l 0,-70 70,..." />
5047 * </vector>
5048 * </aapt:attr>
5049 * </animated-vector>
5050 *
5051 * When AAPT sees the <aapt:attr> tag, it will extract its single element and its children
5052 * into a new high-level resource, assigning it a name and ID. Then value of the `name`
5053 * attribute must be a resource attribute. That resource attribute is inserted into the parent
5054 * with the reference to the extracted resource as the value.
5055 *
5056 * <!-- res/drawable/bundle.xml -->
5057 * <animated-vector android:drawable="@drawable/bundle_1.xml">
5058 * </animated-vector>
5059 *
5060 * <!-- res/drawable/bundle_1.xml -->
5061 * <vector android:width="60dp"
5062 * android:height="60dp">
5063 * <path android:name="v"
5064 * android:fillColor="#000000"
5065 * android:pathData="M300,70 l 0,-70 70,..." />
5066 * </vector>
5067 */
5068status_t ResourceTable::processBundleFormat(const Bundle* bundle,
5069 const String16& resourceName,
5070 const sp<AaptFile>& target,
5071 const sp<XMLNode>& root) {
5072 Vector<sp<XMLNode> > namespaces;
5073 if (root->getType() == XMLNode::TYPE_NAMESPACE) {
5074 namespaces.push(root);
5075 }
5076 return processBundleFormatImpl(bundle, resourceName, target, root, &namespaces);
5077}
5078
5079status_t ResourceTable::processBundleFormatImpl(const Bundle* bundle,
5080 const String16& resourceName,
5081 const sp<AaptFile>& target,
5082 const sp<XMLNode>& parent,
5083 Vector<sp<XMLNode> >* namespaces) {
5084 const String16 kAaptNamespaceUri16("http://schemas.android.com/aapt");
5085 const String16 kName16("name");
5086 const String16 kAttr16("attr");
5087 const String16 kAssetPackage16(mAssets->getPackage());
5088
5089 Vector<sp<XMLNode> >& children = parent->getChildren();
5090 for (size_t i = 0; i < children.size(); i++) {
5091 const sp<XMLNode>& child = children[i];
5092
5093 if (child->getType() == XMLNode::TYPE_CDATA) {
5094 continue;
5095 } else if (child->getType() == XMLNode::TYPE_NAMESPACE) {
5096 namespaces->push(child);
5097 }
5098
5099 if (child->getElementNamespace() != kAaptNamespaceUri16 ||
5100 child->getElementName() != kAttr16) {
5101 status_t result = processBundleFormatImpl(bundle, resourceName, target, child,
5102 namespaces);
5103 if (result != NO_ERROR) {
5104 return result;
5105 }
5106
5107 if (child->getType() == XMLNode::TYPE_NAMESPACE) {
5108 namespaces->pop();
5109 }
5110 continue;
5111 }
5112
5113 // This is the <aapt:attr> tag. Look for the 'name' attribute.
5114 SourcePos source(child->getFilename(), child->getStartLineNumber());
5115
5116 sp<XMLNode> nestedRoot = findOnlyChildElement(child);
5117 if (nestedRoot == NULL) {
5118 source.error("<%s:%s> must have exactly one child element",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00005119 String8(child->getElementNamespace()).c_str(),
5120 String8(child->getElementName()).c_str());
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07005121 return UNKNOWN_ERROR;
5122 }
5123
5124 // Find the special attribute 'parent-attr'. This attribute's value contains
5125 // the resource attribute for which this element should be assigned in the parent.
5126 const XMLNode::attribute_entry* attr = child->getAttribute(String16(), kName16);
5127 if (attr == NULL) {
5128 source.error("inline resource definition must specify an attribute via 'name'");
5129 return UNKNOWN_ERROR;
5130 }
5131
5132 // Parse the attribute name.
5133 const char* errorMsg = NULL;
5134 String16 attrPackage, attrType, attrName;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00005135 bool result = ResTable::expandResourceRef(attr->string.c_str(),
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07005136 attr->string.size(),
5137 &attrPackage, &attrType, &attrName,
5138 &kAttr16, &kAssetPackage16,
5139 &errorMsg, NULL);
5140 if (!result) {
5141 source.error("invalid attribute name for 'name': %s", errorMsg);
5142 return UNKNOWN_ERROR;
5143 }
5144
5145 if (attrType != kAttr16) {
5146 // The value of the 'name' attribute must be an attribute reference.
5147 source.error("value of 'name' must be an attribute reference.");
5148 return UNKNOWN_ERROR;
5149 }
5150
5151 // Generate a name for this nested resource and try to add it to the table.
5152 // We do this in a loop because the name may be taken, in which case we will
5153 // increment a suffix until we succeed.
5154 String8 nestedResourceName;
5155 String8 nestedResourcePath;
5156 int suffix = 1;
5157 while (true) {
5158 // This child element will be extracted into its own resource file.
5159 // Generate a name and path for it from its parent.
5160 nestedResourceName = String8::format("%s_%d",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00005161 String8(resourceName).c_str(), suffix++);
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07005162 nestedResourcePath = String8::format("res/%s/%s.xml",
5163 target->getGroupEntry().toDirName(target->getResourceType())
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00005164 .c_str(),
5165 nestedResourceName.c_str());
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07005166
5167 // Lookup or create the entry for this name.
5168 sp<Entry> entry = getEntry(kAssetPackage16,
5169 String16(target->getResourceType()),
5170 String16(nestedResourceName),
5171 source,
5172 false,
5173 &target->getGroupEntry().toParams(),
5174 true);
5175 if (entry == NULL) {
5176 return UNKNOWN_ERROR;
5177 }
5178
5179 if (entry->getType() == Entry::TYPE_UNKNOWN) {
5180 // The value for this resource has never been set,
5181 // meaning we're good!
5182 entry->setItem(source, String16(nestedResourcePath));
5183 break;
5184 }
5185
5186 // We failed (name already exists), so try with a different name
5187 // (increment the suffix).
5188 }
5189
5190 if (bundle->getVerbose()) {
5191 source.printf("generating nested resource %s:%s/%s",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00005192 mAssets->getPackage().c_str(), target->getResourceType().c_str(),
5193 nestedResourceName.c_str());
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07005194 }
5195
5196 // Build the attribute reference and assign it to the parent.
5197 String16 nestedResourceRef = String16(String8::format("@%s:%s/%s",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00005198 mAssets->getPackage().c_str(), target->getResourceType().c_str(),
5199 nestedResourceName.c_str()));
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07005200
5201 String16 attrNs = buildNamespace(attrPackage);
5202 if (parent->getAttribute(attrNs, attrName) != NULL) {
5203 SourcePos(parent->getFilename(), parent->getStartLineNumber())
5204 .error("parent of nested resource already defines attribute '%s:%s'",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00005205 String8(attrPackage).c_str(), String8(attrName).c_str());
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07005206 return UNKNOWN_ERROR;
5207 }
5208
5209 // Add the reference to the inline resource.
5210 parent->addAttribute(attrNs, attrName, nestedResourceRef);
5211
5212 // Remove the <aapt:attr> child element from here.
5213 children.removeAt(i);
5214 i--;
5215
5216 // Append all namespace declarations that we've seen on this branch in the XML tree
5217 // to this resource.
5218 // We do this because the order of namespace declarations and prefix usage is determined
5219 // by the developer and we do not want to override any decisions. Be conservative.
5220 for (size_t nsIndex = namespaces->size(); nsIndex > 0; nsIndex--) {
5221 const sp<XMLNode>& ns = namespaces->itemAt(nsIndex - 1);
5222 sp<XMLNode> newNs = XMLNode::newNamespace(ns->getFilename(), ns->getNamespacePrefix(),
5223 ns->getNamespaceUri());
5224 newNs->addChild(nestedRoot);
5225 nestedRoot = newNs;
5226 }
5227
5228 // Schedule compilation of the nested resource.
5229 CompileResourceWorkItem workItem;
5230 workItem.resPath = nestedResourcePath;
5231 workItem.resourceName = String16(nestedResourceName);
5232 workItem.xmlRoot = nestedRoot;
5233 workItem.file = new AaptFile(target->getSourceFile(), target->getGroupEntry(),
5234 target->getResourceType());
5235 mWorkQueue.push(workItem);
5236 }
5237 return NO_ERROR;
5238}