blob: b54b1e14542771394edbf0099d9fe3d3a56f1ae1 [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>
Adam Lesinski282e1812014-01-23 18:17:42 -080017#include <androidfw/ResourceTypes.h>
18#include <utils/ByteOrder.h>
Adam Lesinski82a2dd82014-09-17 18:34:15 -070019#include <utils/TypeHelpers.h>
Adam Lesinski282e1812014-01-23 18:17:42 -080020#include <stdarg.h>
21
Andreas Gampe2412f842014-09-30 20:55:57 -070022// STATUST: mingw does seem to redefine UNKNOWN_ERROR from our enum value, so a cast is necessary.
Elliott Hughesb12f2412015-04-03 12:56:45 -070023#if !defined(_WIN32)
Andreas Gampe2412f842014-09-30 20:55:57 -070024# define STATUST(x) x
25#else
Andreas Gampe2412f842014-09-30 20:55:57 -070026# define STATUST(x) (status_t)x
27#endif
28
29// Set to true for noisy debug output.
30static const bool kIsDebug = false;
31
32#if PRINT_STRING_METRICS
33static const bool kPrintStringMetrics = true;
34#else
35static const bool kPrintStringMetrics = false;
36#endif
Adam Lesinski282e1812014-01-23 18:17:42 -080037
Adam Lesinski9b624c12014-11-19 17:49:26 -080038static const char* kAttrPrivateType = "^attr-private";
39
Adam Lesinskie572c012014-09-19 15:10:04 -070040status_t compileXmlFile(const Bundle* bundle,
41 const sp<AaptAssets>& assets,
42 const String16& resourceName,
Adam Lesinski282e1812014-01-23 18:17:42 -080043 const sp<AaptFile>& target,
44 ResourceTable* table,
45 int options)
46{
47 sp<XMLNode> root = XMLNode::parse(target);
48 if (root == NULL) {
49 return UNKNOWN_ERROR;
50 }
Anton Krumina2ef5c02014-03-12 14:46:44 -070051
Adam Lesinskie572c012014-09-19 15:10:04 -070052 return compileXmlFile(bundle, assets, resourceName, root, target, table, options);
Adam Lesinski282e1812014-01-23 18:17:42 -080053}
54
Adam Lesinskie572c012014-09-19 15:10:04 -070055status_t compileXmlFile(const Bundle* bundle,
56 const sp<AaptAssets>& assets,
57 const String16& resourceName,
Adam Lesinski282e1812014-01-23 18:17:42 -080058 const sp<AaptFile>& target,
59 const sp<AaptFile>& outTarget,
60 ResourceTable* table,
61 int options)
62{
63 sp<XMLNode> root = XMLNode::parse(target);
64 if (root == NULL) {
65 return UNKNOWN_ERROR;
66 }
67
Adam Lesinskie572c012014-09-19 15:10:04 -070068 return compileXmlFile(bundle, assets, resourceName, root, outTarget, table, options);
Adam Lesinski282e1812014-01-23 18:17:42 -080069}
70
Adam Lesinskie572c012014-09-19 15:10:04 -070071status_t compileXmlFile(const Bundle* bundle,
72 const sp<AaptAssets>& assets,
73 const String16& resourceName,
Adam Lesinski282e1812014-01-23 18:17:42 -080074 const sp<XMLNode>& root,
75 const sp<AaptFile>& target,
76 ResourceTable* table,
77 int options)
78{
Adam Lesinskicf1f1d92017-03-16 16:54:23 -070079 if (table->versionForCompat(bundle, resourceName, target, root)) {
80 // The file was versioned, so stop processing here.
81 // The resource entry has already been removed and the new one added.
82 // Remove the assets entry.
83 sp<AaptDir> resDir = assets->getDirs().valueFor(String8("res"));
84 sp<AaptDir> dir = resDir->getDirs().valueFor(target->getGroupEntry().toDirName(
85 target->getResourceType()));
86 dir->removeFile(target->getPath().getPathLeaf());
87 return NO_ERROR;
88 }
89
Adam Lesinski282e1812014-01-23 18:17:42 -080090 if ((options&XML_COMPILE_STRIP_WHITESPACE) != 0) {
91 root->removeWhitespace(true, NULL);
92 } else if ((options&XML_COMPILE_COMPACT_WHITESPACE) != 0) {
93 root->removeWhitespace(false, NULL);
94 }
95
96 if ((options&XML_COMPILE_UTF8) != 0) {
97 root->setUTF8(true);
98 }
99
Adam Lesinski07dfd2d2015-10-28 15:44:27 -0700100 if (table->processBundleFormat(bundle, resourceName, target, root) != NO_ERROR) {
101 return UNKNOWN_ERROR;
102 }
Adam Lesinski5b9847c2015-11-30 21:07:44 +0000103
Adam Lesinski07dfd2d2015-10-28 15:44:27 -0700104 bool hasErrors = false;
Adam Lesinski282e1812014-01-23 18:17:42 -0800105 if ((options&XML_COMPILE_ASSIGN_ATTRIBUTE_IDS) != 0) {
106 status_t err = root->assignResourceIds(assets, table);
107 if (err != NO_ERROR) {
108 hasErrors = true;
109 }
110 }
111
Adam Lesinski07dfd2d2015-10-28 15:44:27 -0700112 if ((options&XML_COMPILE_PARSE_VALUES) != 0) {
113 status_t err = root->parseValues(assets, table);
114 if (err != NO_ERROR) {
115 hasErrors = true;
116 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800117 }
118
119 if (hasErrors) {
120 return UNKNOWN_ERROR;
121 }
Adam Lesinskie572c012014-09-19 15:10:04 -0700122
123 if (table->modifyForCompat(bundle, resourceName, target, root) != NO_ERROR) {
124 return UNKNOWN_ERROR;
125 }
Andreas Gampe87332a72014-10-01 22:03:58 -0700126
Andreas Gampe2412f842014-09-30 20:55:57 -0700127 if (kIsDebug) {
128 printf("Input XML Resource:\n");
129 root->print();
130 }
Adam Lesinski07dfd2d2015-10-28 15:44:27 -0700131 status_t err = root->flatten(target,
Adam Lesinski282e1812014-01-23 18:17:42 -0800132 (options&XML_COMPILE_STRIP_COMMENTS) != 0,
133 (options&XML_COMPILE_STRIP_RAW_VALUES) != 0);
134 if (err != NO_ERROR) {
135 return err;
136 }
137
Andreas Gampe2412f842014-09-30 20:55:57 -0700138 if (kIsDebug) {
139 printf("Output XML Resource:\n");
140 ResXMLTree tree;
Adam Lesinski282e1812014-01-23 18:17:42 -0800141 tree.setTo(target->getData(), target->getSize());
Andreas Gampe2412f842014-09-30 20:55:57 -0700142 printXMLBlock(&tree);
143 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800144
145 target->setCompressionMethod(ZipEntry::kCompressDeflated);
146
147 return err;
148}
149
Adam Lesinski282e1812014-01-23 18:17:42 -0800150struct flag_entry
151{
152 const char16_t* name;
153 size_t nameLen;
154 uint32_t value;
155 const char* description;
156};
157
158static const char16_t referenceArray[] =
159 { 'r', 'e', 'f', 'e', 'r', 'e', 'n', 'c', 'e' };
160static const char16_t stringArray[] =
161 { 's', 't', 'r', 'i', 'n', 'g' };
162static const char16_t integerArray[] =
163 { 'i', 'n', 't', 'e', 'g', 'e', 'r' };
164static const char16_t booleanArray[] =
165 { 'b', 'o', 'o', 'l', 'e', 'a', 'n' };
166static const char16_t colorArray[] =
167 { 'c', 'o', 'l', 'o', 'r' };
168static const char16_t floatArray[] =
169 { 'f', 'l', 'o', 'a', 't' };
170static const char16_t dimensionArray[] =
171 { 'd', 'i', 'm', 'e', 'n', 's', 'i', 'o', 'n' };
172static const char16_t fractionArray[] =
173 { 'f', 'r', 'a', 'c', 't', 'i', 'o', 'n' };
174static const char16_t enumArray[] =
175 { 'e', 'n', 'u', 'm' };
176static const char16_t flagsArray[] =
177 { 'f', 'l', 'a', 'g', 's' };
178
179static const flag_entry gFormatFlags[] = {
180 { referenceArray, sizeof(referenceArray)/2, ResTable_map::TYPE_REFERENCE,
181 "a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\n"
182 "or to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\"."},
183 { stringArray, sizeof(stringArray)/2, ResTable_map::TYPE_STRING,
184 "a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character." },
185 { integerArray, sizeof(integerArray)/2, ResTable_map::TYPE_INTEGER,
186 "an integer value, such as \"<code>100</code>\"." },
187 { booleanArray, sizeof(booleanArray)/2, ResTable_map::TYPE_BOOLEAN,
188 "a boolean value, either \"<code>true</code>\" or \"<code>false</code>\"." },
189 { colorArray, sizeof(colorArray)/2, ResTable_map::TYPE_COLOR,
190 "a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n"
191 "\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\"." },
192 { floatArray, sizeof(floatArray)/2, ResTable_map::TYPE_FLOAT,
193 "a floating point value, such as \"<code>1.2</code>\"."},
194 { dimensionArray, sizeof(dimensionArray)/2, ResTable_map::TYPE_DIMENSION,
195 "a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\n"
196 "Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\n"
197 "in (inches), mm (millimeters)." },
198 { fractionArray, sizeof(fractionArray)/2, ResTable_map::TYPE_FRACTION,
199 "a fractional value, which is a floating point number appended with either % or %p, such as \"<code>14.5%</code>\".\n"
200 "The % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to\n"
201 "some parent container." },
202 { enumArray, sizeof(enumArray)/2, ResTable_map::TYPE_ENUM, NULL },
203 { flagsArray, sizeof(flagsArray)/2, ResTable_map::TYPE_FLAGS, NULL },
204 { NULL, 0, 0, NULL }
205};
206
207static const char16_t suggestedArray[] = { 's', 'u', 'g', 'g', 'e', 's', 't', 'e', 'd' };
208
209static const flag_entry l10nRequiredFlags[] = {
210 { suggestedArray, sizeof(suggestedArray)/2, ResTable_map::L10N_SUGGESTED, NULL },
211 { NULL, 0, 0, NULL }
212};
213
214static const char16_t nulStr[] = { 0 };
215
216static uint32_t parse_flags(const char16_t* str, size_t len,
217 const flag_entry* flags, bool* outError = NULL)
218{
219 while (len > 0 && isspace(*str)) {
220 str++;
221 len--;
222 }
223 while (len > 0 && isspace(str[len-1])) {
224 len--;
225 }
226
227 const char16_t* const end = str + len;
228 uint32_t value = 0;
229
230 while (str < end) {
231 const char16_t* div = str;
232 while (div < end && *div != '|') {
233 div++;
234 }
235
236 const flag_entry* cur = flags;
237 while (cur->name) {
238 if (strzcmp16(cur->name, cur->nameLen, str, div-str) == 0) {
239 value |= cur->value;
240 break;
241 }
242 cur++;
243 }
244
245 if (!cur->name) {
246 if (outError) *outError = true;
247 return 0;
248 }
249
250 str = div < end ? div+1 : div;
251 }
252
253 if (outError) *outError = false;
254 return value;
255}
256
257static String16 mayOrMust(int type, int flags)
258{
259 if ((type&(~flags)) == 0) {
260 return String16("<p>Must");
261 }
262
263 return String16("<p>May");
264}
265
266static void appendTypeInfo(ResourceTable* outTable, const String16& pkg,
267 const String16& typeName, const String16& ident, int type,
268 const flag_entry* flags)
269{
270 bool hadType = false;
271 while (flags->name) {
272 if ((type&flags->value) != 0 && flags->description != NULL) {
273 String16 fullMsg(mayOrMust(type, flags->value));
274 fullMsg.append(String16(" be "));
275 fullMsg.append(String16(flags->description));
276 outTable->appendTypeComment(pkg, typeName, ident, fullMsg);
277 hadType = true;
278 }
279 flags++;
280 }
281 if (hadType && (type&ResTable_map::TYPE_REFERENCE) == 0) {
282 outTable->appendTypeComment(pkg, typeName, ident,
283 String16("<p>This may also be a reference to a resource (in the form\n"
284 "\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\n"
285 "theme attribute (in the form\n"
286 "\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\n"
287 "containing a value of this type."));
288 }
289}
290
291struct PendingAttribute
292{
293 const String16 myPackage;
294 const SourcePos sourcePos;
295 const bool appendComment;
296 int32_t type;
297 String16 ident;
298 String16 comment;
299 bool hasErrors;
300 bool added;
301
302 PendingAttribute(String16 _package, const sp<AaptFile>& in,
303 ResXMLTree& block, bool _appendComment)
304 : myPackage(_package)
305 , sourcePos(in->getPrintableSource(), block.getLineNumber())
306 , appendComment(_appendComment)
307 , type(ResTable_map::TYPE_ANY)
308 , hasErrors(false)
309 , added(false)
310 {
311 }
312
313 status_t createIfNeeded(ResourceTable* outTable)
314 {
315 if (added || hasErrors) {
316 return NO_ERROR;
317 }
318 added = true;
319
Adam Lesinskiafc79be2016-02-22 09:16:33 -0800320 if (!outTable->makeAttribute(myPackage, ident, sourcePos, type, comment, appendComment)) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800321 hasErrors = true;
322 return UNKNOWN_ERROR;
323 }
Adam Lesinskiafc79be2016-02-22 09:16:33 -0800324 return NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -0800325 }
326};
327
328static status_t compileAttribute(const sp<AaptFile>& in,
329 ResXMLTree& block,
330 const String16& myPackage,
331 ResourceTable* outTable,
332 String16* outIdent = NULL,
333 bool inStyleable = false)
334{
335 PendingAttribute attr(myPackage, in, block, inStyleable);
336
337 const String16 attr16("attr");
338 const String16 id16("id");
339
340 // Attribute type constants.
341 const String16 enum16("enum");
342 const String16 flag16("flag");
343
344 ResXMLTree::event_code_t code;
345 size_t len;
346 status_t err;
347
348 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
349 if (identIdx >= 0) {
350 attr.ident = String16(block.getAttributeStringValue(identIdx, &len));
351 if (outIdent) {
352 *outIdent = attr.ident;
353 }
354 } else {
355 attr.sourcePos.error("A 'name' attribute is required for <attr>\n");
356 attr.hasErrors = true;
357 }
358
359 attr.comment = String16(
360 block.getComment(&len) ? block.getComment(&len) : nulStr);
361
362 ssize_t typeIdx = block.indexOfAttribute(NULL, "format");
363 if (typeIdx >= 0) {
364 String16 typeStr = String16(block.getAttributeStringValue(typeIdx, &len));
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000365 attr.type = parse_flags(typeStr.c_str(), typeStr.size(), gFormatFlags);
Adam Lesinski282e1812014-01-23 18:17:42 -0800366 if (attr.type == 0) {
367 attr.sourcePos.error("Tag <attr> 'format' attribute value \"%s\" not valid\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000368 String8(typeStr).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800369 attr.hasErrors = true;
370 }
371 attr.createIfNeeded(outTable);
372 } else if (!inStyleable) {
373 // Attribute definitions outside of styleables always define the
374 // attribute as a generic value.
375 attr.createIfNeeded(outTable);
376 }
377
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000378 //printf("Attribute %s: type=0x%08x\n", String8(attr.ident).c_str(), attr.type);
Adam Lesinski282e1812014-01-23 18:17:42 -0800379
380 ssize_t minIdx = block.indexOfAttribute(NULL, "min");
381 if (minIdx >= 0) {
382 String16 val = String16(block.getAttributeStringValue(minIdx, &len));
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000383 if (!ResTable::stringToInt(val.c_str(), val.size(), NULL)) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800384 attr.sourcePos.error("Tag <attr> 'min' attribute must be a number, not \"%s\"\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000385 String8(val).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800386 attr.hasErrors = true;
387 }
388 attr.createIfNeeded(outTable);
389 if (!attr.hasErrors) {
390 err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
391 String16(""), String16("^min"), String16(val), NULL, NULL);
392 if (err != NO_ERROR) {
393 attr.hasErrors = true;
394 }
395 }
396 }
397
398 ssize_t maxIdx = block.indexOfAttribute(NULL, "max");
399 if (maxIdx >= 0) {
400 String16 val = String16(block.getAttributeStringValue(maxIdx, &len));
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000401 if (!ResTable::stringToInt(val.c_str(), val.size(), NULL)) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800402 attr.sourcePos.error("Tag <attr> 'max' attribute must be a number, not \"%s\"\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000403 String8(val).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800404 attr.hasErrors = true;
405 }
406 attr.createIfNeeded(outTable);
407 if (!attr.hasErrors) {
408 err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
409 String16(""), String16("^max"), String16(val), NULL, NULL);
410 attr.hasErrors = true;
411 }
412 }
413
414 if ((minIdx >= 0 || maxIdx >= 0) && (attr.type&ResTable_map::TYPE_INTEGER) == 0) {
415 attr.sourcePos.error("Tag <attr> must have format=integer attribute if using max or min\n");
416 attr.hasErrors = true;
417 }
418
419 ssize_t l10nIdx = block.indexOfAttribute(NULL, "localization");
420 if (l10nIdx >= 0) {
Dan Albertf348c152014-09-08 18:28:00 -0700421 const char16_t* str = block.getAttributeStringValue(l10nIdx, &len);
Adam Lesinski282e1812014-01-23 18:17:42 -0800422 bool error;
423 uint32_t l10n_required = parse_flags(str, len, l10nRequiredFlags, &error);
424 if (error) {
425 attr.sourcePos.error("Tag <attr> 'localization' attribute value \"%s\" not valid\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000426 String8(str).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800427 attr.hasErrors = true;
428 }
429 attr.createIfNeeded(outTable);
430 if (!attr.hasErrors) {
431 char buf[11];
432 sprintf(buf, "%d", l10n_required);
433 err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
434 String16(""), String16("^l10n"), String16(buf), NULL, NULL);
435 if (err != NO_ERROR) {
436 attr.hasErrors = true;
437 }
438 }
439 }
440
441 String16 enumOrFlagsComment;
442
443 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
444 if (code == ResXMLTree::START_TAG) {
445 uint32_t localType = 0;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000446 if (strcmp16(block.getElementName(&len), enum16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800447 localType = ResTable_map::TYPE_ENUM;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000448 } else if (strcmp16(block.getElementName(&len), flag16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800449 localType = ResTable_map::TYPE_FLAGS;
450 } else {
451 SourcePos(in->getPrintableSource(), block.getLineNumber())
452 .error("Tag <%s> can not appear inside <attr>, only <enum> or <flag>\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000453 String8(block.getElementName(&len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800454 return UNKNOWN_ERROR;
455 }
456
457 attr.createIfNeeded(outTable);
458
459 if (attr.type == ResTable_map::TYPE_ANY) {
460 // No type was explicitly stated, so supplying enum tags
461 // implicitly creates an enum or flag.
462 attr.type = 0;
463 }
464
465 if ((attr.type&(ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS)) == 0) {
466 // Wasn't originally specified as an enum, so update its type.
467 attr.type |= localType;
468 if (!attr.hasErrors) {
469 char numberStr[16];
470 sprintf(numberStr, "%d", attr.type);
471 err = outTable->addBag(SourcePos(in->getPrintableSource(), block.getLineNumber()),
472 myPackage, attr16, attr.ident, String16(""),
473 String16("^type"), String16(numberStr), NULL, NULL, true);
474 if (err != NO_ERROR) {
475 attr.hasErrors = true;
476 }
477 }
478 } else if ((uint32_t)(attr.type&(ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS)) != localType) {
479 if (localType == ResTable_map::TYPE_ENUM) {
480 SourcePos(in->getPrintableSource(), block.getLineNumber())
481 .error("<enum> attribute can not be used inside a flags format\n");
482 attr.hasErrors = true;
483 } else {
484 SourcePos(in->getPrintableSource(), block.getLineNumber())
485 .error("<flag> attribute can not be used inside a enum format\n");
486 attr.hasErrors = true;
487 }
488 }
489
490 String16 itemIdent;
491 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "name");
492 if (itemIdentIdx >= 0) {
493 itemIdent = String16(block.getAttributeStringValue(itemIdentIdx, &len));
494 } else {
495 SourcePos(in->getPrintableSource(), block.getLineNumber())
496 .error("A 'name' attribute is required for <enum> or <flag>\n");
497 attr.hasErrors = true;
498 }
499
500 String16 value;
501 ssize_t valueIdx = block.indexOfAttribute(NULL, "value");
502 if (valueIdx >= 0) {
503 value = String16(block.getAttributeStringValue(valueIdx, &len));
504 } else {
505 SourcePos(in->getPrintableSource(), block.getLineNumber())
506 .error("A 'value' attribute is required for <enum> or <flag>\n");
507 attr.hasErrors = true;
508 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000509 if (!attr.hasErrors && !ResTable::stringToInt(value.c_str(), value.size(), NULL)) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800510 SourcePos(in->getPrintableSource(), block.getLineNumber())
511 .error("Tag <enum> or <flag> 'value' attribute must be a number,"
512 " not \"%s\"\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000513 String8(value).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800514 attr.hasErrors = true;
515 }
516
Adam Lesinski282e1812014-01-23 18:17:42 -0800517 if (!attr.hasErrors) {
518 if (enumOrFlagsComment.size() == 0) {
519 enumOrFlagsComment.append(mayOrMust(attr.type,
520 ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS));
521 enumOrFlagsComment.append((attr.type&ResTable_map::TYPE_ENUM)
522 ? String16(" be one of the following constant values.")
523 : String16(" be one or more (separated by '|') of the following constant values."));
524 enumOrFlagsComment.append(String16("</p>\n<table>\n"
525 "<colgroup align=\"left\" />\n"
526 "<colgroup align=\"left\" />\n"
527 "<colgroup align=\"left\" />\n"
528 "<tr><th>Constant</th><th>Value</th><th>Description</th></tr>"));
529 }
530
531 enumOrFlagsComment.append(String16("\n<tr><td><code>"));
532 enumOrFlagsComment.append(itemIdent);
533 enumOrFlagsComment.append(String16("</code></td><td>"));
534 enumOrFlagsComment.append(value);
535 enumOrFlagsComment.append(String16("</td><td>"));
536 if (block.getComment(&len)) {
537 enumOrFlagsComment.append(String16(block.getComment(&len)));
538 }
539 enumOrFlagsComment.append(String16("</td></tr>"));
540
541 err = outTable->addBag(SourcePos(in->getPrintableSource(), block.getLineNumber()),
542 myPackage,
543 attr16, attr.ident, String16(""),
544 itemIdent, value, NULL, NULL, false, true);
545 if (err != NO_ERROR) {
546 attr.hasErrors = true;
547 }
548 }
549 } else if (code == ResXMLTree::END_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000550 if (strcmp16(block.getElementName(&len), attr16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800551 break;
552 }
553 if ((attr.type&ResTable_map::TYPE_ENUM) != 0) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000554 if (strcmp16(block.getElementName(&len), enum16.c_str()) != 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800555 SourcePos(in->getPrintableSource(), block.getLineNumber())
556 .error("Found tag </%s> where </enum> is expected\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000557 String8(block.getElementName(&len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800558 return UNKNOWN_ERROR;
559 }
560 } else {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000561 if (strcmp16(block.getElementName(&len), flag16.c_str()) != 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800562 SourcePos(in->getPrintableSource(), block.getLineNumber())
563 .error("Found tag </%s> where </flag> is expected\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000564 String8(block.getElementName(&len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800565 return UNKNOWN_ERROR;
566 }
567 }
568 }
569 }
570
571 if (!attr.hasErrors && attr.added) {
572 appendTypeInfo(outTable, myPackage, attr16, attr.ident, attr.type, gFormatFlags);
573 }
574
575 if (!attr.hasErrors && enumOrFlagsComment.size() > 0) {
576 enumOrFlagsComment.append(String16("\n</table>"));
577 outTable->appendTypeComment(myPackage, attr16, attr.ident, enumOrFlagsComment);
578 }
579
580
581 return NO_ERROR;
582}
583
584bool localeIsDefined(const ResTable_config& config)
585{
586 return config.locale == 0;
587}
588
589status_t parseAndAddBag(Bundle* bundle,
590 const sp<AaptFile>& in,
591 ResXMLTree* block,
592 const ResTable_config& config,
593 const String16& myPackage,
594 const String16& curType,
595 const String16& ident,
596 const String16& parentIdent,
597 const String16& itemIdent,
598 int32_t curFormat,
599 bool isFormatted,
Andreas Gampe2412f842014-09-30 20:55:57 -0700600 const String16& /* product */,
Anton Krumina2ef5c02014-03-12 14:46:44 -0700601 PseudolocalizationMethod pseudolocalize,
Adam Lesinski282e1812014-01-23 18:17:42 -0800602 const bool overwrite,
603 ResourceTable* outTable)
604{
605 status_t err;
606 const String16 item16("item");
Anton Krumina2ef5c02014-03-12 14:46:44 -0700607
Adam Lesinski282e1812014-01-23 18:17:42 -0800608 String16 str;
609 Vector<StringPool::entry_style_span> spans;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000610 err = parseStyledString(bundle, in->getPrintableSource().c_str(),
Adam Lesinski282e1812014-01-23 18:17:42 -0800611 block, item16, &str, &spans, isFormatted,
612 pseudolocalize);
613 if (err != NO_ERROR) {
614 return err;
615 }
Andreas Gampe2412f842014-09-30 20:55:57 -0700616
617 if (kIsDebug) {
618 printf("Adding resource bag entry l=%c%c c=%c%c orien=%d d=%d "
619 " pid=%s, bag=%s, id=%s: %s\n",
620 config.language[0], config.language[1],
621 config.country[0], config.country[1],
622 config.orientation, config.density,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000623 String8(parentIdent).c_str(),
624 String8(ident).c_str(),
625 String8(itemIdent).c_str(),
626 String8(str).c_str());
Andreas Gampe2412f842014-09-30 20:55:57 -0700627 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800628
629 err = outTable->addBag(SourcePos(in->getPrintableSource(), block->getLineNumber()),
630 myPackage, curType, ident, parentIdent, itemIdent, str,
631 &spans, &config, overwrite, false, curFormat);
632 return err;
633}
634
635/*
636 * Returns true if needle is one of the elements in the comma-separated list
637 * haystack, false otherwise.
638 */
639bool isInProductList(const String16& needle, const String16& haystack) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000640 const char16_t *needle2 = needle.c_str();
641 const char16_t *haystack2 = haystack.c_str();
Adam Lesinski282e1812014-01-23 18:17:42 -0800642 size_t needlesize = needle.size();
643
644 while (*haystack2 != '\0') {
645 if (strncmp16(haystack2, needle2, needlesize) == 0) {
646 if (haystack2[needlesize] == '\0' || haystack2[needlesize] == ',') {
647 return true;
648 }
649 }
650
651 while (*haystack2 != '\0' && *haystack2 != ',') {
652 haystack2++;
653 }
654 if (*haystack2 == ',') {
655 haystack2++;
656 }
657 }
658
659 return false;
660}
661
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700662/*
663 * A simple container that holds a resource type and name. It is ordered first by type then
664 * by name.
665 */
666struct type_ident_pair_t {
667 String16 type;
668 String16 ident;
669
670 type_ident_pair_t() { };
671 type_ident_pair_t(const String16& t, const String16& i) : type(t), ident(i) { }
672 type_ident_pair_t(const type_ident_pair_t& o) : type(o.type), ident(o.ident) { }
673 inline bool operator < (const type_ident_pair_t& o) const {
674 int cmp = compare_type(type, o.type);
675 if (cmp < 0) {
676 return true;
677 } else if (cmp > 0) {
678 return false;
679 } else {
680 return strictly_order_type(ident, o.ident);
681 }
682 }
683};
684
685
Adam Lesinski282e1812014-01-23 18:17:42 -0800686status_t parseAndAddEntry(Bundle* bundle,
687 const sp<AaptFile>& in,
688 ResXMLTree* block,
689 const ResTable_config& config,
690 const String16& myPackage,
691 const String16& curType,
692 const String16& ident,
693 const String16& curTag,
694 bool curIsStyled,
695 int32_t curFormat,
696 bool isFormatted,
697 const String16& product,
Anton Krumina2ef5c02014-03-12 14:46:44 -0700698 PseudolocalizationMethod pseudolocalize,
Adam Lesinski282e1812014-01-23 18:17:42 -0800699 const bool overwrite,
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700700 KeyedVector<type_ident_pair_t, bool>* skippedResourceNames,
Adam Lesinski282e1812014-01-23 18:17:42 -0800701 ResourceTable* outTable)
702{
703 status_t err;
704
705 String16 str;
706 Vector<StringPool::entry_style_span> spans;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000707 err = parseStyledString(bundle, in->getPrintableSource().c_str(), block,
Adam Lesinski282e1812014-01-23 18:17:42 -0800708 curTag, &str, curIsStyled ? &spans : NULL,
709 isFormatted, pseudolocalize);
710
711 if (err < NO_ERROR) {
712 return err;
713 }
714
715 /*
716 * If a product type was specified on the command line
717 * and also in the string, and the two are not the same,
718 * return without adding the string.
719 */
720
721 const char *bundleProduct = bundle->getProduct();
722 if (bundleProduct == NULL) {
723 bundleProduct = "";
724 }
725
726 if (product.size() != 0) {
727 /*
728 * If the command-line-specified product is empty, only "default"
729 * matches. Other variants are skipped. This is so generation
730 * of the R.java file when the product is not known is predictable.
731 */
732
733 if (bundleProduct[0] == '\0') {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000734 if (strcmp16(String16("default").c_str(), product.c_str()) != 0) {
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700735 /*
736 * This string has a product other than 'default'. Do not add it,
737 * but record it so that if we do not see the same string with
738 * product 'default' or no product, then report an error.
739 */
740 skippedResourceNames->replaceValueFor(
741 type_ident_pair_t(curType, ident), true);
Adam Lesinski282e1812014-01-23 18:17:42 -0800742 return NO_ERROR;
743 }
744 } else {
745 /*
746 * The command-line product is not empty.
747 * If the product for this string is on the command-line list,
748 * it matches. "default" also matches, but only if nothing
749 * else has matched already.
750 */
751
752 if (isInProductList(product, String16(bundleProduct))) {
753 ;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000754 } else if (strcmp16(String16("default").c_str(), product.c_str()) == 0 &&
Adam Lesinski282e1812014-01-23 18:17:42 -0800755 !outTable->hasBagOrEntry(myPackage, curType, ident, config)) {
756 ;
757 } else {
758 return NO_ERROR;
759 }
760 }
761 }
762
Andreas Gampe2412f842014-09-30 20:55:57 -0700763 if (kIsDebug) {
764 printf("Adding resource entry l=%c%c c=%c%c orien=%d d=%d id=%s: %s\n",
765 config.language[0], config.language[1],
766 config.country[0], config.country[1],
767 config.orientation, config.density,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000768 String8(ident).c_str(), String8(str).c_str());
Andreas Gampe2412f842014-09-30 20:55:57 -0700769 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800770
771 err = outTable->addEntry(SourcePos(in->getPrintableSource(), block->getLineNumber()),
772 myPackage, curType, ident, str, &spans, &config,
773 false, curFormat, overwrite);
774
775 return err;
776}
777
778status_t compileResourceFile(Bundle* bundle,
779 const sp<AaptAssets>& assets,
780 const sp<AaptFile>& in,
781 const ResTable_config& defParams,
782 const bool overwrite,
783 ResourceTable* outTable)
784{
785 ResXMLTree block;
786 status_t err = parseXMLResource(in, &block, false, true);
787 if (err != NO_ERROR) {
788 return err;
789 }
790
791 // Top-level tag.
792 const String16 resources16("resources");
793
794 // Identifier declaration tags.
795 const String16 declare_styleable16("declare-styleable");
796 const String16 attr16("attr");
797
798 // Data creation organizational tags.
799 const String16 string16("string");
800 const String16 drawable16("drawable");
801 const String16 color16("color");
802 const String16 bool16("bool");
803 const String16 integer16("integer");
804 const String16 dimen16("dimen");
805 const String16 fraction16("fraction");
806 const String16 style16("style");
807 const String16 plurals16("plurals");
808 const String16 array16("array");
809 const String16 string_array16("string-array");
810 const String16 integer_array16("integer-array");
811 const String16 public16("public");
812 const String16 public_padding16("public-padding");
813 const String16 private_symbols16("private-symbols");
814 const String16 java_symbol16("java-symbol");
815 const String16 add_resource16("add-resource");
816 const String16 skip16("skip");
817 const String16 eat_comment16("eat-comment");
818
819 // Data creation tags.
820 const String16 bag16("bag");
821 const String16 item16("item");
822
823 // Attribute type constants.
824 const String16 enum16("enum");
825
826 // plural values
827 const String16 other16("other");
828 const String16 quantityOther16("^other");
829 const String16 zero16("zero");
830 const String16 quantityZero16("^zero");
831 const String16 one16("one");
832 const String16 quantityOne16("^one");
833 const String16 two16("two");
834 const String16 quantityTwo16("^two");
835 const String16 few16("few");
836 const String16 quantityFew16("^few");
837 const String16 many16("many");
838 const String16 quantityMany16("^many");
839
840 // useful attribute names and special values
841 const String16 name16("name");
842 const String16 translatable16("translatable");
843 const String16 formatted16("formatted");
844 const String16 false16("false");
845
846 const String16 myPackage(assets->getPackage());
847
848 bool hasErrors = false;
849
850 bool fileIsTranslatable = true;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000851 if (strstr(in->getPrintableSource().c_str(), "donottranslate") != NULL) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800852 fileIsTranslatable = false;
853 }
854
855 DefaultKeyedVector<String16, uint32_t> nextPublicId(0);
856
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700857 // Stores the resource names that were skipped. Typically this happens when
858 // AAPT is invoked without a product specified and a resource has no
859 // 'default' product attribute.
860 KeyedVector<type_ident_pair_t, bool> skippedResourceNames;
861
Adam Lesinski282e1812014-01-23 18:17:42 -0800862 ResXMLTree::event_code_t code;
863 do {
864 code = block.next();
865 } while (code == ResXMLTree::START_NAMESPACE);
866
867 size_t len;
868 if (code != ResXMLTree::START_TAG) {
869 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
870 "No start tag found\n");
871 return UNKNOWN_ERROR;
872 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000873 if (strcmp16(block.getElementName(&len), resources16.c_str()) != 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800874 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000875 "Invalid start tag %s\n", String8(block.getElementName(&len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800876 return UNKNOWN_ERROR;
877 }
878
879 ResTable_config curParams(defParams);
880
881 ResTable_config pseudoParams(curParams);
Anton Krumina2ef5c02014-03-12 14:46:44 -0700882 pseudoParams.language[0] = 'e';
883 pseudoParams.language[1] = 'n';
884 pseudoParams.country[0] = 'X';
885 pseudoParams.country[1] = 'A';
886
887 ResTable_config pseudoBidiParams(curParams);
888 pseudoBidiParams.language[0] = 'a';
889 pseudoBidiParams.language[1] = 'r';
890 pseudoBidiParams.country[0] = 'X';
891 pseudoBidiParams.country[1] = 'B';
Adam Lesinski282e1812014-01-23 18:17:42 -0800892
Igor Viarheichyk47843df2014-05-01 17:04:39 -0700893 // We should skip resources for pseudolocales if they were
894 // already added automatically. This is a fix for a transition period when
895 // manually pseudolocalized resources may be expected.
896 // TODO: remove this check after next SDK version release.
897 if ((bundle->getPseudolocalize() & PSEUDO_ACCENTED &&
898 curParams.locale == pseudoParams.locale) ||
899 (bundle->getPseudolocalize() & PSEUDO_BIDI &&
900 curParams.locale == pseudoBidiParams.locale)) {
901 SourcePos(in->getPrintableSource(), 0).warning(
902 "Resource file %s is skipped as pseudolocalization"
903 " was done automatically.",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000904 in->getPrintableSource().c_str());
Igor Viarheichyk47843df2014-05-01 17:04:39 -0700905 return NO_ERROR;
906 }
907
Adam Lesinski282e1812014-01-23 18:17:42 -0800908 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
909 if (code == ResXMLTree::START_TAG) {
910 const String16* curTag = NULL;
911 String16 curType;
Adrian Roos58922482015-06-01 17:59:41 -0700912 String16 curName;
Adam Lesinski282e1812014-01-23 18:17:42 -0800913 int32_t curFormat = ResTable_map::TYPE_ANY;
914 bool curIsBag = false;
915 bool curIsBagReplaceOnOverwrite = false;
916 bool curIsStyled = false;
917 bool curIsPseudolocalizable = false;
918 bool curIsFormatted = fileIsTranslatable;
919 bool localHasErrors = false;
920
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000921 if (strcmp16(block.getElementName(&len), skip16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800922 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
923 && code != ResXMLTree::BAD_DOCUMENT) {
924 if (code == ResXMLTree::END_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000925 if (strcmp16(block.getElementName(&len), skip16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800926 break;
927 }
928 }
929 }
930 continue;
931
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000932 } else if (strcmp16(block.getElementName(&len), eat_comment16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800933 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
934 && code != ResXMLTree::BAD_DOCUMENT) {
935 if (code == ResXMLTree::END_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000936 if (strcmp16(block.getElementName(&len), eat_comment16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800937 break;
938 }
939 }
940 }
941 continue;
942
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000943 } else if (strcmp16(block.getElementName(&len), public16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -0800944 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
945
946 String16 type;
947 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
948 if (typeIdx < 0) {
949 srcPos.error("A 'type' attribute is required for <public>\n");
950 hasErrors = localHasErrors = true;
951 }
952 type = String16(block.getAttributeStringValue(typeIdx, &len));
953
954 String16 name;
955 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
956 if (nameIdx < 0) {
957 srcPos.error("A 'name' attribute is required for <public>\n");
958 hasErrors = localHasErrors = true;
959 }
960 name = String16(block.getAttributeStringValue(nameIdx, &len));
961
962 uint32_t ident = 0;
963 ssize_t identIdx = block.indexOfAttribute(NULL, "id");
964 if (identIdx >= 0) {
965 const char16_t* identStr = block.getAttributeStringValue(identIdx, &len);
966 Res_value identValue;
967 if (!ResTable::stringToInt(identStr, len, &identValue)) {
968 srcPos.error("Given 'id' attribute is not an integer: %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +0000969 String8(block.getAttributeStringValue(identIdx, &len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -0800970 hasErrors = localHasErrors = true;
971 } else {
972 ident = identValue.data;
973 nextPublicId.replaceValueFor(type, ident+1);
974 }
975 } else if (nextPublicId.indexOfKey(type) < 0) {
976 srcPos.error("No 'id' attribute supplied <public>,"
977 " and no previous id defined in this file.\n");
978 hasErrors = localHasErrors = true;
979 } else if (!localHasErrors) {
980 ident = nextPublicId.valueFor(type);
981 nextPublicId.replaceValueFor(type, ident+1);
982 }
983
984 if (!localHasErrors) {
985 err = outTable->addPublic(srcPos, myPackage, type, name, ident);
986 if (err < NO_ERROR) {
987 hasErrors = localHasErrors = true;
988 }
989 }
990 if (!localHasErrors) {
991 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
992 if (symbols != NULL) {
993 symbols = symbols->addNestedSymbol(String8(type), srcPos);
994 }
995 if (symbols != NULL) {
996 symbols->makeSymbolPublic(String8(name), srcPos);
997 String16 comment(
998 block.getComment(&len) ? block.getComment(&len) : nulStr);
999 symbols->appendComment(String8(name), comment, srcPos);
1000 } else {
1001 srcPos.error("Unable to create symbols!\n");
1002 hasErrors = localHasErrors = true;
1003 }
1004 }
1005
1006 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1007 if (code == ResXMLTree::END_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001008 if (strcmp16(block.getElementName(&len), public16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001009 break;
1010 }
1011 }
1012 }
1013 continue;
1014
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001015 } else if (strcmp16(block.getElementName(&len), public_padding16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001016 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1017
1018 String16 type;
1019 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
1020 if (typeIdx < 0) {
1021 srcPos.error("A 'type' attribute is required for <public-padding>\n");
1022 hasErrors = localHasErrors = true;
1023 }
1024 type = String16(block.getAttributeStringValue(typeIdx, &len));
1025
1026 String16 name;
1027 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1028 if (nameIdx < 0) {
1029 srcPos.error("A 'name' attribute is required for <public-padding>\n");
1030 hasErrors = localHasErrors = true;
1031 }
1032 name = String16(block.getAttributeStringValue(nameIdx, &len));
1033
1034 uint32_t start = 0;
1035 ssize_t startIdx = block.indexOfAttribute(NULL, "start");
1036 if (startIdx >= 0) {
1037 const char16_t* startStr = block.getAttributeStringValue(startIdx, &len);
1038 Res_value startValue;
1039 if (!ResTable::stringToInt(startStr, len, &startValue)) {
1040 srcPos.error("Given 'start' attribute is not an integer: %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001041 String8(block.getAttributeStringValue(startIdx, &len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001042 hasErrors = localHasErrors = true;
1043 } else {
1044 start = startValue.data;
1045 }
1046 } else if (nextPublicId.indexOfKey(type) < 0) {
1047 srcPos.error("No 'start' attribute supplied <public-padding>,"
1048 " and no previous id defined in this file.\n");
1049 hasErrors = localHasErrors = true;
1050 } else if (!localHasErrors) {
1051 start = nextPublicId.valueFor(type);
1052 }
1053
1054 uint32_t end = 0;
1055 ssize_t endIdx = block.indexOfAttribute(NULL, "end");
1056 if (endIdx >= 0) {
1057 const char16_t* endStr = block.getAttributeStringValue(endIdx, &len);
1058 Res_value endValue;
1059 if (!ResTable::stringToInt(endStr, len, &endValue)) {
1060 srcPos.error("Given 'end' attribute is not an integer: %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001061 String8(block.getAttributeStringValue(endIdx, &len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001062 hasErrors = localHasErrors = true;
1063 } else {
1064 end = endValue.data;
1065 }
1066 } else {
1067 srcPos.error("No 'end' attribute supplied <public-padding>\n");
1068 hasErrors = localHasErrors = true;
1069 }
1070
1071 if (end >= start) {
1072 nextPublicId.replaceValueFor(type, end+1);
1073 } else {
1074 srcPos.error("Padding start '%ul' is after end '%ul'\n",
1075 start, end);
1076 hasErrors = localHasErrors = true;
1077 }
1078
1079 String16 comment(
1080 block.getComment(&len) ? block.getComment(&len) : nulStr);
1081 for (uint32_t curIdent=start; curIdent<=end; curIdent++) {
1082 if (localHasErrors) {
1083 break;
1084 }
1085 String16 curName(name);
1086 char buf[64];
1087 sprintf(buf, "%d", (int)(end-curIdent+1));
1088 curName.append(String16(buf));
1089
1090 err = outTable->addEntry(srcPos, myPackage, type, curName,
1091 String16("padding"), NULL, &curParams, false,
1092 ResTable_map::TYPE_STRING, overwrite);
1093 if (err < NO_ERROR) {
1094 hasErrors = localHasErrors = true;
1095 break;
1096 }
1097 err = outTable->addPublic(srcPos, myPackage, type,
1098 curName, curIdent);
1099 if (err < NO_ERROR) {
1100 hasErrors = localHasErrors = true;
1101 break;
1102 }
1103 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1104 if (symbols != NULL) {
1105 symbols = symbols->addNestedSymbol(String8(type), srcPos);
1106 }
1107 if (symbols != NULL) {
1108 symbols->makeSymbolPublic(String8(curName), srcPos);
1109 symbols->appendComment(String8(curName), comment, srcPos);
1110 } else {
1111 srcPos.error("Unable to create symbols!\n");
1112 hasErrors = localHasErrors = true;
1113 }
1114 }
1115
1116 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1117 if (code == ResXMLTree::END_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001118 if (strcmp16(block.getElementName(&len), public_padding16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001119 break;
1120 }
1121 }
1122 }
1123 continue;
1124
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001125 } else if (strcmp16(block.getElementName(&len), private_symbols16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001126 String16 pkg;
1127 ssize_t pkgIdx = block.indexOfAttribute(NULL, "package");
1128 if (pkgIdx < 0) {
1129 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1130 "A 'package' attribute is required for <private-symbols>\n");
1131 hasErrors = localHasErrors = true;
1132 }
1133 pkg = String16(block.getAttributeStringValue(pkgIdx, &len));
1134 if (!localHasErrors) {
Adam Lesinski78713992015-12-07 14:02:15 -08001135 SourcePos(in->getPrintableSource(), block.getLineNumber()).warning(
1136 "<private-symbols> is deprecated. Use the command line flag "
1137 "--private-symbols instead.\n");
1138 if (assets->havePrivateSymbols()) {
1139 SourcePos(in->getPrintableSource(), block.getLineNumber()).warning(
1140 "private symbol package already specified. Ignoring...\n");
1141 } else {
1142 assets->setSymbolsPrivatePackage(String8(pkg));
1143 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001144 }
1145
1146 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1147 if (code == ResXMLTree::END_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001148 if (strcmp16(block.getElementName(&len), private_symbols16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001149 break;
1150 }
1151 }
1152 }
1153 continue;
1154
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001155 } else if (strcmp16(block.getElementName(&len), java_symbol16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001156 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1157
1158 String16 type;
1159 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
1160 if (typeIdx < 0) {
1161 srcPos.error("A 'type' attribute is required for <public>\n");
1162 hasErrors = localHasErrors = true;
1163 }
1164 type = String16(block.getAttributeStringValue(typeIdx, &len));
1165
1166 String16 name;
1167 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1168 if (nameIdx < 0) {
1169 srcPos.error("A 'name' attribute is required for <public>\n");
1170 hasErrors = localHasErrors = true;
1171 }
1172 name = String16(block.getAttributeStringValue(nameIdx, &len));
1173
1174 sp<AaptSymbols> symbols = assets->getJavaSymbolsFor(String8("R"));
1175 if (symbols != NULL) {
1176 symbols = symbols->addNestedSymbol(String8(type), srcPos);
1177 }
1178 if (symbols != NULL) {
1179 symbols->makeSymbolJavaSymbol(String8(name), srcPos);
1180 String16 comment(
1181 block.getComment(&len) ? block.getComment(&len) : nulStr);
1182 symbols->appendComment(String8(name), comment, srcPos);
1183 } else {
1184 srcPos.error("Unable to create symbols!\n");
1185 hasErrors = localHasErrors = true;
1186 }
1187
1188 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1189 if (code == ResXMLTree::END_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001190 if (strcmp16(block.getElementName(&len), java_symbol16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001191 break;
1192 }
1193 }
1194 }
1195 continue;
1196
1197
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001198 } else if (strcmp16(block.getElementName(&len), add_resource16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001199 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1200
1201 String16 typeName;
1202 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
1203 if (typeIdx < 0) {
1204 srcPos.error("A 'type' attribute is required for <add-resource>\n");
1205 hasErrors = localHasErrors = true;
1206 }
1207 typeName = String16(block.getAttributeStringValue(typeIdx, &len));
1208
1209 String16 name;
1210 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1211 if (nameIdx < 0) {
1212 srcPos.error("A 'name' attribute is required for <add-resource>\n");
1213 hasErrors = localHasErrors = true;
1214 }
1215 name = String16(block.getAttributeStringValue(nameIdx, &len));
1216
1217 outTable->canAddEntry(srcPos, myPackage, typeName, name);
1218
1219 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1220 if (code == ResXMLTree::END_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001221 if (strcmp16(block.getElementName(&len), add_resource16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001222 break;
1223 }
1224 }
1225 }
1226 continue;
1227
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001228 } else if (strcmp16(block.getElementName(&len), declare_styleable16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001229 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1230
1231 String16 ident;
1232 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
1233 if (identIdx < 0) {
1234 srcPos.error("A 'name' attribute is required for <declare-styleable>\n");
1235 hasErrors = localHasErrors = true;
1236 }
1237 ident = String16(block.getAttributeStringValue(identIdx, &len));
1238
1239 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1240 if (!localHasErrors) {
1241 if (symbols != NULL) {
1242 symbols = symbols->addNestedSymbol(String8("styleable"), srcPos);
1243 }
1244 sp<AaptSymbols> styleSymbols = symbols;
1245 if (symbols != NULL) {
1246 symbols = symbols->addNestedSymbol(String8(ident), srcPos);
1247 }
1248 if (symbols == NULL) {
1249 srcPos.error("Unable to create symbols!\n");
1250 return UNKNOWN_ERROR;
1251 }
1252
1253 String16 comment(
1254 block.getComment(&len) ? block.getComment(&len) : nulStr);
1255 styleSymbols->appendComment(String8(ident), comment, srcPos);
1256 } else {
1257 symbols = NULL;
1258 }
1259
1260 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1261 if (code == ResXMLTree::START_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001262 if (strcmp16(block.getElementName(&len), skip16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001263 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1264 && code != ResXMLTree::BAD_DOCUMENT) {
1265 if (code == ResXMLTree::END_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001266 if (strcmp16(block.getElementName(&len), skip16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001267 break;
1268 }
1269 }
1270 }
1271 continue;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001272 } else if (strcmp16(block.getElementName(&len), eat_comment16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001273 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1274 && code != ResXMLTree::BAD_DOCUMENT) {
1275 if (code == ResXMLTree::END_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001276 if (strcmp16(block.getElementName(&len), eat_comment16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001277 break;
1278 }
1279 }
1280 }
1281 continue;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001282 } else if (strcmp16(block.getElementName(&len), attr16.c_str()) != 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001283 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1284 "Tag <%s> can not appear inside <declare-styleable>, only <attr>\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001285 String8(block.getElementName(&len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001286 return UNKNOWN_ERROR;
1287 }
1288
1289 String16 comment(
1290 block.getComment(&len) ? block.getComment(&len) : nulStr);
1291 String16 itemIdent;
1292 err = compileAttribute(in, block, myPackage, outTable, &itemIdent, true);
1293 if (err != NO_ERROR) {
1294 hasErrors = localHasErrors = true;
1295 }
1296
1297 if (symbols != NULL) {
1298 SourcePos srcPos(String8(in->getPrintableSource()), block.getLineNumber());
1299 symbols->addSymbol(String8(itemIdent), 0, srcPos);
1300 symbols->appendComment(String8(itemIdent), comment, srcPos);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001301 //printf("Attribute %s comment: %s\n", String8(itemIdent).c_str(),
1302 // String8(comment).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001303 }
1304 } else if (code == ResXMLTree::END_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001305 if (strcmp16(block.getElementName(&len), declare_styleable16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001306 break;
1307 }
1308
1309 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1310 "Found tag </%s> where </attr> is expected\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001311 String8(block.getElementName(&len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001312 return UNKNOWN_ERROR;
1313 }
1314 }
1315 continue;
1316
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001317 } else if (strcmp16(block.getElementName(&len), attr16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001318 err = compileAttribute(in, block, myPackage, outTable, NULL);
1319 if (err != NO_ERROR) {
1320 hasErrors = true;
1321 }
1322 continue;
1323
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001324 } else if (strcmp16(block.getElementName(&len), item16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001325 curTag = &item16;
1326 ssize_t attri = block.indexOfAttribute(NULL, "type");
1327 if (attri >= 0) {
1328 curType = String16(block.getAttributeStringValue(attri, &len));
Adrian Roos58922482015-06-01 17:59:41 -07001329 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1330 if (nameIdx >= 0) {
1331 curName = String16(block.getAttributeStringValue(nameIdx, &len));
1332 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001333 ssize_t formatIdx = block.indexOfAttribute(NULL, "format");
1334 if (formatIdx >= 0) {
1335 String16 formatStr = String16(block.getAttributeStringValue(
1336 formatIdx, &len));
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001337 curFormat = parse_flags(formatStr.c_str(), formatStr.size(),
Adam Lesinski282e1812014-01-23 18:17:42 -08001338 gFormatFlags);
1339 if (curFormat == 0) {
1340 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1341 "Tag <item> 'format' attribute value \"%s\" not valid\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001342 String8(formatStr).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001343 hasErrors = localHasErrors = true;
1344 }
1345 }
1346 } else {
1347 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1348 "A 'type' attribute is required for <item>\n");
1349 hasErrors = localHasErrors = true;
1350 }
1351 curIsStyled = true;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001352 } else if (strcmp16(block.getElementName(&len), string16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001353 // Note the existence and locale of every string we process
Narayan Kamath91447d82014-01-21 15:32:36 +00001354 char rawLocale[RESTABLE_MAX_LOCALE_LEN];
1355 curParams.getBcp47Locale(rawLocale);
Adam Lesinski282e1812014-01-23 18:17:42 -08001356 String8 locale(rawLocale);
1357 String16 name;
1358 String16 translatable;
1359 String16 formatted;
1360
1361 size_t n = block.getAttributeCount();
1362 for (size_t i = 0; i < n; i++) {
1363 size_t length;
Dan Albertf348c152014-09-08 18:28:00 -07001364 const char16_t* attr = block.getAttributeName(i, &length);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001365 if (strcmp16(attr, name16.c_str()) == 0) {
Tomasz Wasilczyk31eb3c892023-08-23 22:12:33 +00001366 name = String16(block.getAttributeStringValue(i, &length));
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001367 } else if (strcmp16(attr, translatable16.c_str()) == 0) {
Tomasz Wasilczyk31eb3c892023-08-23 22:12:33 +00001368 translatable = String16(block.getAttributeStringValue(i, &length));
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001369 } else if (strcmp16(attr, formatted16.c_str()) == 0) {
Tomasz Wasilczyk31eb3c892023-08-23 22:12:33 +00001370 formatted = String16(block.getAttributeStringValue(i, &length));
Adam Lesinski282e1812014-01-23 18:17:42 -08001371 }
1372 }
1373
1374 if (name.size() > 0) {
Adrian Roos58922482015-06-01 17:59:41 -07001375 if (locale.size() == 0) {
1376 outTable->addDefaultLocalization(name);
1377 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001378 if (translatable == false16) {
1379 curIsFormatted = false;
1380 // Untranslatable strings must only exist in the default [empty] locale
1381 if (locale.size() > 0) {
Adam Lesinskia01a9372014-03-20 18:04:57 -07001382 SourcePos(in->getPrintableSource(), block.getLineNumber()).warning(
1383 "string '%s' marked untranslatable but exists in locale '%s'\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001384 String8(name).c_str(),
1385 locale.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001386 // hasErrors = localHasErrors = true;
1387 } else {
1388 // Intentionally empty block:
1389 //
1390 // Don't add untranslatable strings to the localization table; that
1391 // way if we later see localizations of them, they'll be flagged as
1392 // having no default translation.
1393 }
1394 } else {
Adam Lesinskia01a9372014-03-20 18:04:57 -07001395 outTable->addLocalization(
1396 name,
1397 locale,
1398 SourcePos(in->getPrintableSource(), block.getLineNumber()));
Adam Lesinski282e1812014-01-23 18:17:42 -08001399 }
1400
1401 if (formatted == false16) {
1402 curIsFormatted = false;
1403 }
1404 }
1405
1406 curTag = &string16;
1407 curType = string16;
1408 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
1409 curIsStyled = true;
Igor Viarheichyk84410b02014-04-30 11:56:42 -07001410 curIsPseudolocalizable = fileIsTranslatable && (translatable != false16);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001411 } else if (strcmp16(block.getElementName(&len), drawable16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001412 curTag = &drawable16;
1413 curType = drawable16;
1414 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001415 } else if (strcmp16(block.getElementName(&len), color16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001416 curTag = &color16;
1417 curType = color16;
1418 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001419 } else if (strcmp16(block.getElementName(&len), bool16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001420 curTag = &bool16;
1421 curType = bool16;
1422 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_BOOLEAN;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001423 } else if (strcmp16(block.getElementName(&len), integer16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001424 curTag = &integer16;
1425 curType = integer16;
1426 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001427 } else if (strcmp16(block.getElementName(&len), dimen16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001428 curTag = &dimen16;
1429 curType = dimen16;
1430 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_DIMENSION;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001431 } else if (strcmp16(block.getElementName(&len), fraction16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001432 curTag = &fraction16;
1433 curType = fraction16;
1434 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_FRACTION;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001435 } else if (strcmp16(block.getElementName(&len), bag16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001436 curTag = &bag16;
1437 curIsBag = true;
1438 ssize_t attri = block.indexOfAttribute(NULL, "type");
1439 if (attri >= 0) {
1440 curType = String16(block.getAttributeStringValue(attri, &len));
1441 } else {
1442 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1443 "A 'type' attribute is required for <bag>\n");
1444 hasErrors = localHasErrors = true;
1445 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001446 } else if (strcmp16(block.getElementName(&len), style16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001447 curTag = &style16;
1448 curType = style16;
1449 curIsBag = true;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001450 } else if (strcmp16(block.getElementName(&len), plurals16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001451 curTag = &plurals16;
1452 curType = plurals16;
1453 curIsBag = true;
Anton Krumina2ef5c02014-03-12 14:46:44 -07001454 curIsPseudolocalizable = fileIsTranslatable;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001455 } else if (strcmp16(block.getElementName(&len), array16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001456 curTag = &array16;
1457 curType = array16;
1458 curIsBag = true;
1459 curIsBagReplaceOnOverwrite = true;
1460 ssize_t formatIdx = block.indexOfAttribute(NULL, "format");
1461 if (formatIdx >= 0) {
1462 String16 formatStr = String16(block.getAttributeStringValue(
1463 formatIdx, &len));
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001464 curFormat = parse_flags(formatStr.c_str(), formatStr.size(),
Adam Lesinski282e1812014-01-23 18:17:42 -08001465 gFormatFlags);
1466 if (curFormat == 0) {
1467 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1468 "Tag <array> 'format' attribute value \"%s\" not valid\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001469 String8(formatStr).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001470 hasErrors = localHasErrors = true;
1471 }
1472 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001473 } else if (strcmp16(block.getElementName(&len), string_array16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001474 // Check whether these strings need valid formats.
1475 // (simplified form of what string16 does above)
Anton Krumina2ef5c02014-03-12 14:46:44 -07001476 bool isTranslatable = false;
Adam Lesinski282e1812014-01-23 18:17:42 -08001477 size_t n = block.getAttributeCount();
Narayan Kamath9a9fa162013-12-18 13:27:30 +00001478
1479 // Pseudolocalizable by default, unless this string array isn't
1480 // translatable.
Adam Lesinski282e1812014-01-23 18:17:42 -08001481 for (size_t i = 0; i < n; i++) {
1482 size_t length;
Dan Albertf348c152014-09-08 18:28:00 -07001483 const char16_t* attr = block.getAttributeName(i, &length);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001484 if (strcmp16(attr, formatted16.c_str()) == 0) {
Dan Albertf348c152014-09-08 18:28:00 -07001485 const char16_t* value = block.getAttributeStringValue(i, &length);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001486 if (strcmp16(value, false16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001487 curIsFormatted = false;
Adam Lesinski282e1812014-01-23 18:17:42 -08001488 }
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001489 } else if (strcmp16(attr, translatable16.c_str()) == 0) {
Dan Albertf348c152014-09-08 18:28:00 -07001490 const char16_t* value = block.getAttributeStringValue(i, &length);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001491 if (strcmp16(value, false16.c_str()) == 0) {
Anton Krumina2ef5c02014-03-12 14:46:44 -07001492 isTranslatable = false;
1493 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001494 }
1495 }
1496
1497 curTag = &string_array16;
1498 curType = array16;
1499 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
1500 curIsBag = true;
1501 curIsBagReplaceOnOverwrite = true;
Anton Krumina2ef5c02014-03-12 14:46:44 -07001502 curIsPseudolocalizable = isTranslatable && fileIsTranslatable;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001503 } else if (strcmp16(block.getElementName(&len), integer_array16.c_str()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001504 curTag = &integer_array16;
1505 curType = array16;
1506 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
1507 curIsBag = true;
1508 curIsBagReplaceOnOverwrite = true;
1509 } else {
1510 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1511 "Found tag %s where item is expected\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001512 String8(block.getElementName(&len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001513 return UNKNOWN_ERROR;
1514 }
1515
1516 String16 ident;
1517 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
1518 if (identIdx >= 0) {
1519 ident = String16(block.getAttributeStringValue(identIdx, &len));
1520 } else {
1521 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1522 "A 'name' attribute is required for <%s>\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001523 String8(*curTag).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001524 hasErrors = localHasErrors = true;
1525 }
1526
1527 String16 product;
1528 identIdx = block.indexOfAttribute(NULL, "product");
1529 if (identIdx >= 0) {
1530 product = String16(block.getAttributeStringValue(identIdx, &len));
1531 }
1532
1533 String16 comment(block.getComment(&len) ? block.getComment(&len) : nulStr);
1534
1535 if (curIsBag) {
1536 // Figure out the parent of this bag...
1537 String16 parentIdent;
1538 ssize_t parentIdentIdx = block.indexOfAttribute(NULL, "parent");
1539 if (parentIdentIdx >= 0) {
1540 parentIdent = String16(block.getAttributeStringValue(parentIdentIdx, &len));
1541 } else {
1542 ssize_t sep = ident.findLast('.');
1543 if (sep >= 0) {
Tomasz Wasilczyk31eb3c892023-08-23 22:12:33 +00001544 parentIdent = String16(ident, sep);
Adam Lesinski282e1812014-01-23 18:17:42 -08001545 }
1546 }
1547
1548 if (!localHasErrors) {
1549 err = outTable->startBag(SourcePos(in->getPrintableSource(),
1550 block.getLineNumber()), myPackage, curType, ident,
1551 parentIdent, &curParams,
1552 overwrite, curIsBagReplaceOnOverwrite);
1553 if (err != NO_ERROR) {
1554 hasErrors = localHasErrors = true;
1555 }
1556 }
1557
1558 ssize_t elmIndex = 0;
1559 char elmIndexStr[14];
1560 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1561 && code != ResXMLTree::BAD_DOCUMENT) {
1562
1563 if (code == ResXMLTree::START_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001564 if (strcmp16(block.getElementName(&len), item16.c_str()) != 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001565 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1566 "Tag <%s> can not appear inside <%s>, only <item>\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001567 String8(block.getElementName(&len)).c_str(),
1568 String8(*curTag).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001569 return UNKNOWN_ERROR;
1570 }
1571
1572 String16 itemIdent;
1573 if (curType == array16) {
1574 sprintf(elmIndexStr, "^index_%d", (int)elmIndex++);
1575 itemIdent = String16(elmIndexStr);
1576 } else if (curType == plurals16) {
1577 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "quantity");
1578 if (itemIdentIdx >= 0) {
1579 String16 quantity16(block.getAttributeStringValue(itemIdentIdx, &len));
1580 if (quantity16 == other16) {
1581 itemIdent = quantityOther16;
1582 }
1583 else if (quantity16 == zero16) {
1584 itemIdent = quantityZero16;
1585 }
1586 else if (quantity16 == one16) {
1587 itemIdent = quantityOne16;
1588 }
1589 else if (quantity16 == two16) {
1590 itemIdent = quantityTwo16;
1591 }
1592 else if (quantity16 == few16) {
1593 itemIdent = quantityFew16;
1594 }
1595 else if (quantity16 == many16) {
1596 itemIdent = quantityMany16;
1597 }
1598 else {
1599 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1600 "Illegal 'quantity' attribute is <item> inside <plurals>\n");
1601 hasErrors = localHasErrors = true;
1602 }
1603 } else {
1604 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1605 "A 'quantity' attribute is required for <item> inside <plurals>\n");
1606 hasErrors = localHasErrors = true;
1607 }
1608 } else {
1609 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "name");
1610 if (itemIdentIdx >= 0) {
1611 itemIdent = String16(block.getAttributeStringValue(itemIdentIdx, &len));
1612 } else {
1613 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1614 "A 'name' attribute is required for <item>\n");
1615 hasErrors = localHasErrors = true;
1616 }
1617 }
1618
1619 ResXMLParser::ResXMLPosition parserPosition;
1620 block.getPosition(&parserPosition);
1621
1622 err = parseAndAddBag(bundle, in, &block, curParams, myPackage, curType,
1623 ident, parentIdent, itemIdent, curFormat, curIsFormatted,
Anton Krumina2ef5c02014-03-12 14:46:44 -07001624 product, NO_PSEUDOLOCALIZATION, overwrite, outTable);
Adam Lesinski282e1812014-01-23 18:17:42 -08001625 if (err == NO_ERROR) {
1626 if (curIsPseudolocalizable && localeIsDefined(curParams)
Anton Krumina2ef5c02014-03-12 14:46:44 -07001627 && bundle->getPseudolocalize() > 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001628 // pseudolocalize here
Anton Krumina2ef5c02014-03-12 14:46:44 -07001629 if ((PSEUDO_ACCENTED & bundle->getPseudolocalize()) ==
1630 PSEUDO_ACCENTED) {
1631 block.setPosition(parserPosition);
1632 err = parseAndAddBag(bundle, in, &block, pseudoParams, myPackage,
1633 curType, ident, parentIdent, itemIdent, curFormat,
1634 curIsFormatted, product, PSEUDO_ACCENTED,
1635 overwrite, outTable);
1636 }
1637 if ((PSEUDO_BIDI & bundle->getPseudolocalize()) ==
1638 PSEUDO_BIDI) {
1639 block.setPosition(parserPosition);
1640 err = parseAndAddBag(bundle, in, &block, pseudoBidiParams, myPackage,
1641 curType, ident, parentIdent, itemIdent, curFormat,
1642 curIsFormatted, product, PSEUDO_BIDI,
1643 overwrite, outTable);
1644 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001645 }
Anton Krumina2ef5c02014-03-12 14:46:44 -07001646 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001647 if (err != NO_ERROR) {
1648 hasErrors = localHasErrors = true;
1649 }
1650 } else if (code == ResXMLTree::END_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001651 if (strcmp16(block.getElementName(&len), curTag->c_str()) != 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001652 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1653 "Found tag </%s> where </%s> is expected\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001654 String8(block.getElementName(&len)).c_str(),
1655 String8(*curTag).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001656 return UNKNOWN_ERROR;
1657 }
1658 break;
1659 }
1660 }
1661 } else {
1662 ResXMLParser::ResXMLPosition parserPosition;
1663 block.getPosition(&parserPosition);
1664
1665 err = parseAndAddEntry(bundle, in, &block, curParams, myPackage, curType, ident,
1666 *curTag, curIsStyled, curFormat, curIsFormatted,
Anton Krumina2ef5c02014-03-12 14:46:44 -07001667 product, NO_PSEUDOLOCALIZATION, overwrite, &skippedResourceNames, outTable);
Adam Lesinski282e1812014-01-23 18:17:42 -08001668
1669 if (err < NO_ERROR) { // Why err < NO_ERROR instead of err != NO_ERROR?
1670 hasErrors = localHasErrors = true;
1671 }
1672 else if (err == NO_ERROR) {
Adrian Roos58922482015-06-01 17:59:41 -07001673 if (curType == string16 && !curParams.language[0] && !curParams.country[0]) {
1674 outTable->addDefaultLocalization(curName);
1675 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001676 if (curIsPseudolocalizable && localeIsDefined(curParams)
Anton Krumina2ef5c02014-03-12 14:46:44 -07001677 && bundle->getPseudolocalize() > 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001678 // pseudolocalize here
Anton Krumina2ef5c02014-03-12 14:46:44 -07001679 if ((PSEUDO_ACCENTED & bundle->getPseudolocalize()) ==
1680 PSEUDO_ACCENTED) {
1681 block.setPosition(parserPosition);
1682 err = parseAndAddEntry(bundle, in, &block, pseudoParams, myPackage, curType,
1683 ident, *curTag, curIsStyled, curFormat,
1684 curIsFormatted, product,
1685 PSEUDO_ACCENTED, overwrite, &skippedResourceNames, outTable);
1686 }
1687 if ((PSEUDO_BIDI & bundle->getPseudolocalize()) ==
1688 PSEUDO_BIDI) {
1689 block.setPosition(parserPosition);
1690 err = parseAndAddEntry(bundle, in, &block, pseudoBidiParams,
1691 myPackage, curType, ident, *curTag, curIsStyled, curFormat,
1692 curIsFormatted, product,
1693 PSEUDO_BIDI, overwrite, &skippedResourceNames, outTable);
1694 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001695 if (err != NO_ERROR) {
1696 hasErrors = localHasErrors = true;
1697 }
1698 }
1699 }
1700 }
1701
1702#if 0
1703 if (comment.size() > 0) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001704 printf("Comment for @%s:%s/%s: %s\n", String8(myPackage).c_str(),
1705 String8(curType).c_str(), String8(ident).c_str(),
1706 String8(comment).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001707 }
1708#endif
1709 if (!localHasErrors) {
1710 outTable->appendComment(myPackage, curType, ident, comment, false);
1711 }
1712 }
1713 else if (code == ResXMLTree::END_TAG) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001714 if (strcmp16(block.getElementName(&len), resources16.c_str()) != 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001715 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001716 "Unexpected end tag %s\n", String8(block.getElementName(&len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001717 return UNKNOWN_ERROR;
1718 }
1719 }
1720 else if (code == ResXMLTree::START_NAMESPACE || code == ResXMLTree::END_NAMESPACE) {
1721 }
1722 else if (code == ResXMLTree::TEXT) {
1723 if (isWhitespace(block.getText(&len))) {
1724 continue;
1725 }
1726 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1727 "Found text \"%s\" where item tag is expected\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001728 String8(block.getText(&len)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001729 return UNKNOWN_ERROR;
1730 }
1731 }
1732
Adam Lesinski8ff15b42013-10-07 16:54:01 -07001733 // For every resource defined, there must be exist one variant with a product attribute
1734 // set to 'default' (or no product attribute at all).
1735 // We check to see that for every resource that was ignored because of a mismatched
1736 // product attribute, some product variant of that resource was processed.
1737 for (size_t i = 0; i < skippedResourceNames.size(); i++) {
1738 if (skippedResourceNames[i]) {
1739 const type_ident_pair_t& p = skippedResourceNames.keyAt(i);
1740 if (!outTable->hasBagOrEntry(myPackage, p.type, p.ident)) {
1741 const char* bundleProduct =
1742 (bundle->getProduct() == NULL) ? "" : bundle->getProduct();
1743 fprintf(stderr, "In resource file %s: %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001744 in->getPrintableSource().c_str(),
1745 curParams.toString().c_str());
Adam Lesinski8ff15b42013-10-07 16:54:01 -07001746
1747 fprintf(stderr, "\t%s '%s' does not match product %s.\n"
1748 "\tYou may have forgotten to include a 'default' product variant"
1749 " of the resource.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001750 String8(p.type).c_str(), String8(p.ident).c_str(),
Adam Lesinski8ff15b42013-10-07 16:54:01 -07001751 bundleProduct[0] == 0 ? "default" : bundleProduct);
1752 return UNKNOWN_ERROR;
1753 }
1754 }
1755 }
1756
Andreas Gampe2412f842014-09-30 20:55:57 -07001757 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001758}
1759
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001760ResourceTable::ResourceTable(Bundle* bundle, const String16& assetsPackage, ResourceTable::PackageType type)
1761 : mAssetsPackage(assetsPackage)
1762 , mPackageType(type)
1763 , mTypeIdOffset(0)
1764 , mNumLocal(0)
1765 , mBundle(bundle)
Adam Lesinski282e1812014-01-23 18:17:42 -08001766{
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001767 ssize_t packageId = -1;
1768 switch (mPackageType) {
1769 case App:
1770 case AppFeature:
1771 packageId = 0x7f;
1772 break;
1773
1774 case System:
1775 packageId = 0x01;
1776 break;
1777
1778 case SharedLibrary:
1779 packageId = 0x00;
1780 break;
1781
1782 default:
1783 assert(0);
1784 break;
1785 }
1786 sp<Package> package = new Package(mAssetsPackage, packageId);
1787 mPackages.add(assetsPackage, package);
1788 mOrderedPackages.add(package);
1789
1790 // Every resource table always has one first entry, the bag attributes.
1791 const SourcePos unknown(String8("????"), 0);
1792 getType(mAssetsPackage, String16("attr"), unknown);
1793}
1794
1795static uint32_t findLargestTypeIdForPackage(const ResTable& table, const String16& packageName) {
1796 const size_t basePackageCount = table.getBasePackageCount();
1797 for (size_t i = 0; i < basePackageCount; i++) {
1798 if (packageName == table.getBasePackageName(i)) {
1799 return table.getLastTypeIdForPackage(i);
1800 }
1801 }
1802 return 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08001803}
1804
1805status_t ResourceTable::addIncludedResources(Bundle* bundle, const sp<AaptAssets>& assets)
1806{
1807 status_t err = assets->buildIncludedResources(bundle);
1808 if (err != NO_ERROR) {
1809 return err;
1810 }
1811
Adam Lesinski282e1812014-01-23 18:17:42 -08001812 mAssets = assets;
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001813 mTypeIdOffset = findLargestTypeIdForPackage(assets->getIncludedResources(), mAssetsPackage);
Adam Lesinski282e1812014-01-23 18:17:42 -08001814
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001815 const String8& featureAfter = bundle->getFeatureAfterPackage();
Tomasz Wasilczyk7e22cab2023-08-24 19:02:33 +00001816 if (!featureAfter.empty()) {
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001817 AssetManager featureAssetManager;
1818 if (!featureAssetManager.addAssetPath(featureAfter, NULL)) {
1819 fprintf(stderr, "ERROR: Feature package '%s' not found.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001820 featureAfter.c_str());
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001821 return UNKNOWN_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001822 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001823
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001824 const ResTable& featureTable = featureAssetManager.getResources(false);
Dan Albert030f5362015-03-04 13:54:20 -08001825 mTypeIdOffset = std::max(mTypeIdOffset,
Tomasz Wasilczyk7e22cab2023-08-24 19:02:33 +00001826 findLargestTypeIdForPackage(featureTable, mAssetsPackage));
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001827 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001828
1829 return NO_ERROR;
1830}
1831
1832status_t ResourceTable::addPublic(const SourcePos& sourcePos,
1833 const String16& package,
1834 const String16& type,
1835 const String16& name,
1836 const uint32_t ident)
1837{
1838 uint32_t rid = mAssets->getIncludedResources()
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001839 .identifierForName(name.c_str(), name.size(),
1840 type.c_str(), type.size(),
1841 package.c_str(), package.size());
Adam Lesinski282e1812014-01-23 18:17:42 -08001842 if (rid != 0) {
1843 sourcePos.error("Error declaring public resource %s/%s for included package %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001844 String8(type).c_str(), String8(name).c_str(),
1845 String8(package).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001846 return UNKNOWN_ERROR;
1847 }
1848
1849 sp<Type> t = getType(package, type, sourcePos);
1850 if (t == NULL) {
1851 return UNKNOWN_ERROR;
1852 }
1853 return t->addPublic(sourcePos, name, ident);
1854}
1855
1856status_t ResourceTable::addEntry(const SourcePos& sourcePos,
1857 const String16& package,
1858 const String16& type,
1859 const String16& name,
1860 const String16& value,
1861 const Vector<StringPool::entry_style_span>* style,
1862 const ResTable_config* params,
1863 const bool doSetIndex,
1864 const int32_t format,
1865 const bool overwrite)
1866{
Adam Lesinski282e1812014-01-23 18:17:42 -08001867 uint32_t rid = mAssets->getIncludedResources()
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001868 .identifierForName(name.c_str(), name.size(),
1869 type.c_str(), type.size(),
1870 package.c_str(), package.size());
Adam Lesinski282e1812014-01-23 18:17:42 -08001871 if (rid != 0) {
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001872 sourcePos.error("Resource entry %s/%s is already defined in package %s.",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001873 String8(type).c_str(), String8(name).c_str(), String8(package).c_str());
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001874 return UNKNOWN_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001875 }
1876
Adam Lesinski282e1812014-01-23 18:17:42 -08001877 sp<Entry> e = getEntry(package, type, name, sourcePos, overwrite,
1878 params, doSetIndex);
1879 if (e == NULL) {
1880 return UNKNOWN_ERROR;
1881 }
1882 status_t err = e->setItem(sourcePos, value, style, format, overwrite);
1883 if (err == NO_ERROR) {
1884 mNumLocal++;
1885 }
1886 return err;
1887}
1888
1889status_t ResourceTable::startBag(const SourcePos& sourcePos,
1890 const String16& package,
1891 const String16& type,
1892 const String16& name,
1893 const String16& bagParent,
1894 const ResTable_config* params,
1895 bool overlay,
Andreas Gampe2412f842014-09-30 20:55:57 -07001896 bool replace, bool /* isId */)
Adam Lesinski282e1812014-01-23 18:17:42 -08001897{
1898 status_t result = NO_ERROR;
1899
1900 // Check for adding entries in other packages... for now we do
1901 // nothing. We need to do the right thing here to support skinning.
1902 uint32_t rid = mAssets->getIncludedResources()
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001903 .identifierForName(name.c_str(), name.size(),
1904 type.c_str(), type.size(),
1905 package.c_str(), package.size());
Adam Lesinski282e1812014-01-23 18:17:42 -08001906 if (rid != 0) {
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001907 sourcePos.error("Resource entry %s/%s is already defined in package %s.",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001908 String8(type).c_str(), String8(name).c_str(), String8(package).c_str());
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001909 return UNKNOWN_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001910 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001911
Adam Lesinski282e1812014-01-23 18:17:42 -08001912 if (overlay && !mBundle->getAutoAddOverlay() && !hasBagOrEntry(package, type, name)) {
1913 bool canAdd = false;
1914 sp<Package> p = mPackages.valueFor(package);
1915 if (p != NULL) {
1916 sp<Type> t = p->getTypes().valueFor(type);
1917 if (t != NULL) {
1918 if (t->getCanAddEntries().indexOf(name) >= 0) {
1919 canAdd = true;
1920 }
1921 }
1922 }
1923 if (!canAdd) {
1924 sourcePos.error("Resource does not already exist in overlay at '%s'; use <add-resource> to add.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001925 String8(name).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001926 return UNKNOWN_ERROR;
1927 }
1928 }
1929 sp<Entry> e = getEntry(package, type, name, sourcePos, overlay, params);
1930 if (e == NULL) {
1931 return UNKNOWN_ERROR;
1932 }
1933
1934 // If a parent is explicitly specified, set it.
1935 if (bagParent.size() > 0) {
1936 e->setParent(bagParent);
1937 }
1938
1939 if ((result = e->makeItABag(sourcePos)) != NO_ERROR) {
1940 return result;
1941 }
1942
1943 if (overlay && replace) {
1944 return e->emptyBag(sourcePos);
1945 }
1946 return result;
1947}
1948
1949status_t ResourceTable::addBag(const SourcePos& sourcePos,
1950 const String16& package,
1951 const String16& type,
1952 const String16& name,
1953 const String16& bagParent,
1954 const String16& bagKey,
1955 const String16& value,
1956 const Vector<StringPool::entry_style_span>* style,
1957 const ResTable_config* params,
1958 bool replace, bool isId, const int32_t format)
1959{
1960 // Check for adding entries in other packages... for now we do
1961 // nothing. We need to do the right thing here to support skinning.
1962 uint32_t rid = mAssets->getIncludedResources()
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001963 .identifierForName(name.c_str(), name.size(),
1964 type.c_str(), type.size(),
1965 package.c_str(), package.size());
Adam Lesinski282e1812014-01-23 18:17:42 -08001966 if (rid != 0) {
1967 return NO_ERROR;
1968 }
1969
1970#if 0
1971 if (name == String16("left")) {
1972 printf("Adding bag left: file=%s, line=%d, type=%s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00001973 sourcePos.file.striing(), sourcePos.line, String8(type).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08001974 }
1975#endif
1976 sp<Entry> e = getEntry(package, type, name, sourcePos, replace, params);
1977 if (e == NULL) {
1978 return UNKNOWN_ERROR;
1979 }
1980
1981 // If a parent is explicitly specified, set it.
1982 if (bagParent.size() > 0) {
1983 e->setParent(bagParent);
1984 }
1985
1986 const bool first = e->getBag().indexOfKey(bagKey) < 0;
1987 status_t err = e->addToBag(sourcePos, bagKey, value, style, replace, isId, format);
1988 if (err == NO_ERROR && first) {
1989 mNumLocal++;
1990 }
1991 return err;
1992}
1993
1994bool ResourceTable::hasBagOrEntry(const String16& package,
1995 const String16& type,
1996 const String16& name) const
1997{
1998 // First look for this in the included resources...
1999 uint32_t rid = mAssets->getIncludedResources()
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002000 .identifierForName(name.c_str(), name.size(),
2001 type.c_str(), type.size(),
2002 package.c_str(), package.size());
Adam Lesinski282e1812014-01-23 18:17:42 -08002003 if (rid != 0) {
2004 return true;
2005 }
2006
2007 sp<Package> p = mPackages.valueFor(package);
2008 if (p != NULL) {
2009 sp<Type> t = p->getTypes().valueFor(type);
2010 if (t != NULL) {
2011 sp<ConfigList> c = t->getConfigs().valueFor(name);
2012 if (c != NULL) return true;
2013 }
2014 }
2015
2016 return false;
2017}
2018
2019bool ResourceTable::hasBagOrEntry(const String16& package,
2020 const String16& type,
2021 const String16& name,
2022 const ResTable_config& config) const
2023{
2024 // First look for this in the included resources...
2025 uint32_t rid = mAssets->getIncludedResources()
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002026 .identifierForName(name.c_str(), name.size(),
2027 type.c_str(), type.size(),
2028 package.c_str(), package.size());
Adam Lesinski282e1812014-01-23 18:17:42 -08002029 if (rid != 0) {
2030 return true;
2031 }
2032
2033 sp<Package> p = mPackages.valueFor(package);
2034 if (p != NULL) {
2035 sp<Type> t = p->getTypes().valueFor(type);
2036 if (t != NULL) {
2037 sp<ConfigList> c = t->getConfigs().valueFor(name);
2038 if (c != NULL) {
2039 sp<Entry> e = c->getEntries().valueFor(config);
2040 if (e != NULL) {
2041 return true;
2042 }
2043 }
2044 }
2045 }
2046
2047 return false;
2048}
2049
2050bool ResourceTable::hasBagOrEntry(const String16& ref,
2051 const String16* defType,
2052 const String16* defPackage)
2053{
2054 String16 package, type, name;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002055 if (!ResTable::expandResourceRef(ref.c_str(), ref.size(), &package, &type, &name,
Adam Lesinski282e1812014-01-23 18:17:42 -08002056 defType, defPackage ? defPackage:&mAssetsPackage, NULL)) {
2057 return false;
2058 }
2059 return hasBagOrEntry(package, type, name);
2060}
2061
2062bool ResourceTable::appendComment(const String16& package,
2063 const String16& type,
2064 const String16& name,
2065 const String16& comment,
2066 bool onlyIfEmpty)
2067{
2068 if (comment.size() <= 0) {
2069 return true;
2070 }
2071
2072 sp<Package> p = mPackages.valueFor(package);
2073 if (p != NULL) {
2074 sp<Type> t = p->getTypes().valueFor(type);
2075 if (t != NULL) {
2076 sp<ConfigList> c = t->getConfigs().valueFor(name);
2077 if (c != NULL) {
2078 c->appendComment(comment, onlyIfEmpty);
2079 return true;
2080 }
2081 }
2082 }
2083 return false;
2084}
2085
2086bool ResourceTable::appendTypeComment(const String16& package,
2087 const String16& type,
2088 const String16& name,
2089 const String16& comment)
2090{
2091 if (comment.size() <= 0) {
2092 return true;
2093 }
2094
2095 sp<Package> p = mPackages.valueFor(package);
2096 if (p != NULL) {
2097 sp<Type> t = p->getTypes().valueFor(type);
2098 if (t != NULL) {
2099 sp<ConfigList> c = t->getConfigs().valueFor(name);
2100 if (c != NULL) {
2101 c->appendTypeComment(comment);
2102 return true;
2103 }
2104 }
2105 }
2106 return false;
2107}
2108
Adam Lesinskiafc79be2016-02-22 09:16:33 -08002109bool ResourceTable::makeAttribute(const String16& package,
2110 const String16& name,
2111 const SourcePos& source,
2112 int32_t format,
2113 const String16& comment,
2114 bool shouldAppendComment) {
2115 const String16 attr16("attr");
2116
2117 // First look for this in the included resources...
2118 uint32_t rid = mAssets->getIncludedResources()
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002119 .identifierForName(name.c_str(), name.size(),
2120 attr16.c_str(), attr16.size(),
2121 package.c_str(), package.size());
Adam Lesinskiafc79be2016-02-22 09:16:33 -08002122 if (rid != 0) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002123 source.error("Attribute \"%s\" has already been defined", String8(name).c_str());
Adam Lesinskiafc79be2016-02-22 09:16:33 -08002124 return false;
2125 }
2126
2127 sp<ResourceTable::Entry> entry = getEntry(package, attr16, name, source, false);
2128 if (entry == NULL) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002129 source.error("Failed to create entry attr/%s", String8(name).c_str());
Adam Lesinskiafc79be2016-02-22 09:16:33 -08002130 return false;
2131 }
2132
2133 if (entry->makeItABag(source) != NO_ERROR) {
2134 return false;
2135 }
2136
2137 const String16 formatKey16("^type");
2138 const String16 formatValue16(String8::format("%d", format));
2139
2140 ssize_t idx = entry->getBag().indexOfKey(formatKey16);
2141 if (idx >= 0) {
2142 // We have already set a format for this attribute, check if they are different.
2143 // We allow duplicate attribute definitions so long as they are identical.
2144 // This is to ensure inter-operation with libraries that define the same generic attribute.
2145 const Item& formatItem = entry->getBag().valueAt(idx);
2146 if ((format & (ResTable_map::TYPE_ENUM | ResTable_map::TYPE_FLAGS)) ||
2147 formatItem.value != formatValue16) {
2148 source.error("Attribute \"%s\" already defined with incompatible format.\n"
2149 "%s:%d: Original attribute defined here.",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002150 String8(name).c_str(), formatItem.sourcePos.file.c_str(),
Adam Lesinskiafc79be2016-02-22 09:16:33 -08002151 formatItem.sourcePos.line);
2152 return false;
2153 }
2154 } else {
2155 entry->addToBag(source, formatKey16, formatValue16);
2156 // Increment the number of resources we have. This is used to determine if we should
2157 // even generate a resource table.
2158 mNumLocal++;
2159 }
2160 appendComment(package, attr16, name, comment, shouldAppendComment);
2161 return true;
2162}
2163
Adam Lesinski282e1812014-01-23 18:17:42 -08002164void ResourceTable::canAddEntry(const SourcePos& pos,
2165 const String16& package, const String16& type, const String16& name)
2166{
2167 sp<Type> t = getType(package, type, pos);
2168 if (t != NULL) {
2169 t->canAddEntry(name);
2170 }
2171}
2172
2173size_t ResourceTable::size() const {
2174 return mPackages.size();
2175}
2176
2177size_t ResourceTable::numLocalResources() const {
2178 return mNumLocal;
2179}
2180
2181bool ResourceTable::hasResources() const {
2182 return mNumLocal > 0;
2183}
2184
Adam Lesinski27f69f42014-08-21 13:19:12 -07002185sp<AaptFile> ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& filter,
2186 const bool isBase)
Adam Lesinski282e1812014-01-23 18:17:42 -08002187{
2188 sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
Adam Lesinski27f69f42014-08-21 13:19:12 -07002189 status_t err = flatten(bundle, filter, data, isBase);
Adam Lesinski282e1812014-01-23 18:17:42 -08002190 return err == NO_ERROR ? data : NULL;
2191}
2192
2193inline uint32_t ResourceTable::getResId(const sp<Package>& p,
2194 const sp<Type>& t,
2195 uint32_t nameId)
2196{
2197 return makeResId(p->getAssignedId(), t->getIndex(), nameId);
2198}
2199
2200uint32_t ResourceTable::getResId(const String16& package,
2201 const String16& type,
2202 const String16& name,
2203 bool onlyPublic) const
2204{
2205 uint32_t id = ResourceIdCache::lookup(package, type, name, onlyPublic);
2206 if (id != 0) return id; // cache hit
2207
Adam Lesinski282e1812014-01-23 18:17:42 -08002208 // First look for this in the included resources...
2209 uint32_t specFlags = 0;
2210 uint32_t rid = mAssets->getIncludedResources()
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002211 .identifierForName(name.c_str(), name.size(),
2212 type.c_str(), type.size(),
2213 package.c_str(), package.size(),
Adam Lesinski282e1812014-01-23 18:17:42 -08002214 &specFlags);
2215 if (rid != 0) {
Adam Lesinskifa1e9d72017-01-24 16:16:09 -08002216 if (onlyPublic && (specFlags & ResTable_typeSpec::SPEC_PUBLIC) == 0) {
2217 // If this is a feature split and the resource has the same
2218 // package name as us, then everything is public.
2219 if (mPackageType != AppFeature || mAssetsPackage != package) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002220 return 0;
2221 }
2222 }
2223
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002224 return ResourceIdCache::store(package, type, name, onlyPublic, rid);
Adam Lesinski282e1812014-01-23 18:17:42 -08002225 }
2226
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002227 sp<Package> p = mPackages.valueFor(package);
2228 if (p == NULL) return 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08002229 sp<Type> t = p->getTypes().valueFor(type);
2230 if (t == NULL) return 0;
Adam Lesinski9b624c12014-11-19 17:49:26 -08002231 sp<ConfigList> c = t->getConfigs().valueFor(name);
2232 if (c == NULL) {
2233 if (type != String16("attr")) {
2234 return 0;
2235 }
2236 t = p->getTypes().valueFor(String16(kAttrPrivateType));
2237 if (t == NULL) return 0;
2238 c = t->getConfigs().valueFor(name);
2239 if (c == NULL) return 0;
2240 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002241 int32_t ei = c->getEntryIndex();
2242 if (ei < 0) return 0;
2243
2244 return ResourceIdCache::store(package, type, name, onlyPublic,
2245 getResId(p, t, ei));
2246}
2247
2248uint32_t ResourceTable::getResId(const String16& ref,
2249 const String16* defType,
2250 const String16* defPackage,
2251 const char** outErrorMsg,
2252 bool onlyPublic) const
2253{
2254 String16 package, type, name;
2255 bool refOnlyPublic = true;
2256 if (!ResTable::expandResourceRef(
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002257 ref.c_str(), ref.size(), &package, &type, &name,
Adam Lesinski282e1812014-01-23 18:17:42 -08002258 defType, defPackage ? defPackage:&mAssetsPackage,
2259 outErrorMsg, &refOnlyPublic)) {
Andreas Gampe2412f842014-09-30 20:55:57 -07002260 if (kIsDebug) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002261 printf("Expanding resource: ref=%s\n", String8(ref).c_str());
Andreas Gampe2412f842014-09-30 20:55:57 -07002262 printf("Expanding resource: defType=%s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002263 defType ? String8(*defType).c_str() : "NULL");
Andreas Gampe2412f842014-09-30 20:55:57 -07002264 printf("Expanding resource: defPackage=%s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002265 defPackage ? String8(*defPackage).c_str() : "NULL");
2266 printf("Expanding resource: ref=%s\n", String8(ref).c_str());
Andreas Gampe2412f842014-09-30 20:55:57 -07002267 printf("Expanded resource: p=%s, t=%s, n=%s, res=0\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002268 String8(package).c_str(), String8(type).c_str(),
2269 String8(name).c_str());
Andreas Gampe2412f842014-09-30 20:55:57 -07002270 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002271 return 0;
2272 }
2273 uint32_t res = getResId(package, type, name, onlyPublic && refOnlyPublic);
Andreas Gampe2412f842014-09-30 20:55:57 -07002274 if (kIsDebug) {
2275 printf("Expanded resource: p=%s, t=%s, n=%s, res=%d\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002276 String8(package).c_str(), String8(type).c_str(),
2277 String8(name).c_str(), res);
Andreas Gampe2412f842014-09-30 20:55:57 -07002278 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002279 if (res == 0) {
2280 if (outErrorMsg)
2281 *outErrorMsg = "No resource found that matches the given name";
2282 }
2283 return res;
2284}
2285
2286bool ResourceTable::isValidResourceName(const String16& s)
2287{
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002288 const char16_t* p = s.c_str();
Adam Lesinski282e1812014-01-23 18:17:42 -08002289 bool first = true;
2290 while (*p) {
2291 if ((*p >= 'a' && *p <= 'z')
2292 || (*p >= 'A' && *p <= 'Z')
2293 || *p == '_'
2294 || (!first && *p >= '0' && *p <= '9')) {
2295 first = false;
2296 p++;
2297 continue;
2298 }
2299 return false;
2300 }
2301 return true;
2302}
2303
2304bool ResourceTable::stringToValue(Res_value* outValue, StringPool* pool,
2305 const String16& str,
2306 bool preserveSpaces, bool coerceType,
2307 uint32_t attrID,
2308 const Vector<StringPool::entry_style_span>* style,
2309 String16* outStr, void* accessorCookie,
2310 uint32_t attrType, const String8* configTypeName,
2311 const ConfigDescription* config)
2312{
2313 String16 finalStr;
2314
2315 bool res = true;
2316 if (style == NULL || style->size() == 0) {
2317 // Text is not styled so it can be any type... let's figure it out.
2318 res = mAssets->getIncludedResources()
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002319 .stringToValue(outValue, &finalStr, str.c_str(), str.size(), preserveSpaces,
Adam Lesinski282e1812014-01-23 18:17:42 -08002320 coerceType, attrID, NULL, &mAssetsPackage, this,
2321 accessorCookie, attrType);
2322 } else {
2323 // Styled text can only be a string, and while collecting the style
2324 // information we have already processed that string!
2325 outValue->size = sizeof(Res_value);
2326 outValue->res0 = 0;
2327 outValue->dataType = outValue->TYPE_STRING;
2328 outValue->data = 0;
2329 finalStr = str;
2330 }
2331
2332 if (!res) {
2333 return false;
2334 }
2335
2336 if (outValue->dataType == outValue->TYPE_STRING) {
2337 // Should do better merging styles.
2338 if (pool) {
2339 String8 configStr;
2340 if (config != NULL) {
2341 configStr = config->toString();
2342 } else {
2343 configStr = "(null)";
2344 }
Andreas Gampe2412f842014-09-30 20:55:57 -07002345 if (kIsDebug) {
2346 printf("Adding to pool string style #%zu config %s: %s\n",
2347 style != NULL ? style->size() : 0U,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002348 configStr.c_str(), String8(finalStr).c_str());
Andreas Gampe2412f842014-09-30 20:55:57 -07002349 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002350 if (style != NULL && style->size() > 0) {
2351 outValue->data = pool->add(finalStr, *style, configTypeName, config);
2352 } else {
2353 outValue->data = pool->add(finalStr, true, configTypeName, config);
2354 }
2355 } else {
2356 // Caller will fill this in later.
2357 outValue->data = 0;
2358 }
2359
2360 if (outStr) {
2361 *outStr = finalStr;
2362 }
2363
2364 }
2365
2366 return true;
2367}
2368
2369uint32_t ResourceTable::getCustomResource(
2370 const String16& package, const String16& type, const String16& name) const
2371{
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002372 //printf("getCustomResource: %s %s %s\n", String8(package).c_str(),
2373 // String8(type).c_str(), String8(name).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002374 sp<Package> p = mPackages.valueFor(package);
2375 if (p == NULL) return 0;
2376 sp<Type> t = p->getTypes().valueFor(type);
2377 if (t == NULL) return 0;
2378 sp<ConfigList> c = t->getConfigs().valueFor(name);
Adam Lesinski9b624c12014-11-19 17:49:26 -08002379 if (c == NULL) {
2380 if (type != String16("attr")) {
2381 return 0;
2382 }
2383 t = p->getTypes().valueFor(String16(kAttrPrivateType));
2384 if (t == NULL) return 0;
2385 c = t->getConfigs().valueFor(name);
2386 if (c == NULL) return 0;
2387 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002388 int32_t ei = c->getEntryIndex();
2389 if (ei < 0) return 0;
2390 return getResId(p, t, ei);
2391}
2392
2393uint32_t ResourceTable::getCustomResourceWithCreation(
2394 const String16& package, const String16& type, const String16& name,
2395 const bool createIfNotFound)
2396{
2397 uint32_t resId = getCustomResource(package, type, name);
2398 if (resId != 0 || !createIfNotFound) {
2399 return resId;
2400 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002401
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002402 if (mAssetsPackage != package) {
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002403 mCurrentXmlPos.error("creating resource for external package %s: %s/%s.",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002404 String8(package).c_str(), String8(type).c_str(), String8(name).c_str());
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002405 if (package == String16("android")) {
2406 mCurrentXmlPos.printf("did you mean to use @+id instead of @+android:id?");
2407 }
2408 return 0;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002409 }
2410
2411 String16 value("false");
Adam Lesinski282e1812014-01-23 18:17:42 -08002412 status_t status = addEntry(mCurrentXmlPos, package, type, name, value, NULL, NULL, true);
2413 if (status == NO_ERROR) {
2414 resId = getResId(package, type, name);
2415 return resId;
2416 }
2417 return 0;
2418}
2419
2420uint32_t ResourceTable::getRemappedPackage(uint32_t origPackage) const
2421{
2422 return origPackage;
2423}
2424
2425bool ResourceTable::getAttributeType(uint32_t attrID, uint32_t* outType)
2426{
2427 //printf("getAttributeType #%08x\n", attrID);
2428 Res_value value;
2429 if (getItemValue(attrID, ResTable_map::ATTR_TYPE, &value)) {
2430 //printf("getAttributeType #%08x (%s): #%08x\n", attrID,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002431 // String8(getEntry(attrID)->getName()).c_str(), value.data);
Adam Lesinski282e1812014-01-23 18:17:42 -08002432 *outType = value.data;
2433 return true;
2434 }
2435 return false;
2436}
2437
2438bool ResourceTable::getAttributeMin(uint32_t attrID, uint32_t* outMin)
2439{
2440 //printf("getAttributeMin #%08x\n", attrID);
2441 Res_value value;
2442 if (getItemValue(attrID, ResTable_map::ATTR_MIN, &value)) {
2443 *outMin = value.data;
2444 return true;
2445 }
2446 return false;
2447}
2448
2449bool ResourceTable::getAttributeMax(uint32_t attrID, uint32_t* outMax)
2450{
2451 //printf("getAttributeMax #%08x\n", attrID);
2452 Res_value value;
2453 if (getItemValue(attrID, ResTable_map::ATTR_MAX, &value)) {
2454 *outMax = value.data;
2455 return true;
2456 }
2457 return false;
2458}
2459
2460uint32_t ResourceTable::getAttributeL10N(uint32_t attrID)
2461{
2462 //printf("getAttributeL10N #%08x\n", attrID);
2463 Res_value value;
2464 if (getItemValue(attrID, ResTable_map::ATTR_L10N, &value)) {
2465 return value.data;
2466 }
2467 return ResTable_map::L10N_NOT_REQUIRED;
2468}
2469
2470bool ResourceTable::getLocalizationSetting()
2471{
2472 return mBundle->getRequireLocalization();
2473}
2474
2475void ResourceTable::reportError(void* accessorCookie, const char* fmt, ...)
2476{
2477 if (accessorCookie != NULL && fmt != NULL) {
2478 AccessorCookie* ac = (AccessorCookie*)accessorCookie;
Adam Lesinski282e1812014-01-23 18:17:42 -08002479 char buf[1024];
2480 va_list ap;
2481 va_start(ap, fmt);
Yi Kong82ac8682021-08-20 02:48:22 +08002482 vsnprintf(buf, sizeof(buf), fmt, ap);
Adam Lesinski282e1812014-01-23 18:17:42 -08002483 va_end(ap);
2484 ac->sourcePos.error("Error: %s (at '%s' with value '%s').\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002485 buf, ac->attr.c_str(), ac->value.c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002486 }
2487}
2488
2489bool ResourceTable::getAttributeKeys(
2490 uint32_t attrID, Vector<String16>* outKeys)
2491{
2492 sp<const Entry> e = getEntry(attrID);
2493 if (e != NULL) {
2494 const size_t N = e->getBag().size();
2495 for (size_t i=0; i<N; i++) {
2496 const String16& key = e->getBag().keyAt(i);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002497 if (key.size() > 0 && key.c_str()[0] != '^') {
Adam Lesinski282e1812014-01-23 18:17:42 -08002498 outKeys->add(key);
2499 }
2500 }
2501 return true;
2502 }
2503 return false;
2504}
2505
2506bool ResourceTable::getAttributeEnum(
2507 uint32_t attrID, const char16_t* name, size_t nameLen,
2508 Res_value* outValue)
2509{
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002510 //printf("getAttributeEnum #%08x %s\n", attrID, String8(name, nameLen).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002511 String16 nameStr(name, nameLen);
2512 sp<const Entry> e = getEntry(attrID);
2513 if (e != NULL) {
2514 const size_t N = e->getBag().size();
2515 for (size_t i=0; i<N; i++) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002516 //printf("Comparing %s to %s\n", String8(name, nameLen).c_str(),
2517 // String8(e->getBag().keyAt(i)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002518 if (e->getBag().keyAt(i) == nameStr) {
2519 return getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, outValue);
2520 }
2521 }
2522 }
2523 return false;
2524}
2525
2526bool ResourceTable::getAttributeFlags(
2527 uint32_t attrID, const char16_t* name, size_t nameLen,
2528 Res_value* outValue)
2529{
2530 outValue->dataType = Res_value::TYPE_INT_HEX;
2531 outValue->data = 0;
2532
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002533 //printf("getAttributeFlags #%08x %s\n", attrID, String8(name, nameLen).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002534 String16 nameStr(name, nameLen);
2535 sp<const Entry> e = getEntry(attrID);
2536 if (e != NULL) {
2537 const size_t N = e->getBag().size();
2538
2539 const char16_t* end = name + nameLen;
2540 const char16_t* pos = name;
2541 while (pos < end) {
2542 const char16_t* start = pos;
2543 while (pos < end && *pos != '|') {
2544 pos++;
2545 }
2546
2547 String16 nameStr(start, pos-start);
2548 size_t i;
2549 for (i=0; i<N; i++) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002550 //printf("Comparing \"%s\" to \"%s\"\n", String8(nameStr).c_str(),
2551 // String8(e->getBag().keyAt(i)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002552 if (e->getBag().keyAt(i) == nameStr) {
2553 Res_value val;
2554 bool got = getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, &val);
2555 if (!got) {
2556 return false;
2557 }
2558 //printf("Got value: 0x%08x\n", val.data);
2559 outValue->data |= val.data;
2560 break;
2561 }
2562 }
2563
2564 if (i >= N) {
2565 // Didn't find this flag identifier.
2566 return false;
2567 }
2568 pos++;
2569 }
2570
2571 return true;
2572 }
2573 return false;
2574}
2575
2576status_t ResourceTable::assignResourceIds()
2577{
2578 const size_t N = mOrderedPackages.size();
2579 size_t pi;
2580 status_t firstError = NO_ERROR;
2581
2582 // First generate all bag attributes and assign indices.
2583 for (pi=0; pi<N; pi++) {
2584 sp<Package> p = mOrderedPackages.itemAt(pi);
2585 if (p == NULL || p->getTypes().size() == 0) {
2586 // Empty, skip!
2587 continue;
2588 }
2589
Adam Lesinski9b624c12014-11-19 17:49:26 -08002590 if (mPackageType == System) {
2591 p->movePrivateAttrs();
2592 }
2593
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002594 // This has no sense for packages being built as AppFeature (aka with a non-zero offset).
Adam Lesinski282e1812014-01-23 18:17:42 -08002595 status_t err = p->applyPublicTypeOrder();
2596 if (err != NO_ERROR && firstError == NO_ERROR) {
2597 firstError = err;
2598 }
2599
2600 // Generate attributes...
2601 const size_t N = p->getOrderedTypes().size();
2602 size_t ti;
2603 for (ti=0; ti<N; ti++) {
2604 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2605 if (t == NULL) {
2606 continue;
2607 }
2608 const size_t N = t->getOrderedConfigs().size();
2609 for (size_t ci=0; ci<N; ci++) {
2610 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2611 if (c == NULL) {
2612 continue;
2613 }
2614 const size_t N = c->getEntries().size();
2615 for (size_t ei=0; ei<N; ei++) {
2616 sp<Entry> e = c->getEntries().valueAt(ei);
2617 if (e == NULL) {
2618 continue;
2619 }
2620 status_t err = e->generateAttributes(this, p->getName());
2621 if (err != NO_ERROR && firstError == NO_ERROR) {
2622 firstError = err;
2623 }
2624 }
2625 }
2626 }
2627
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002628 uint32_t typeIdOffset = 0;
2629 if (mPackageType == AppFeature && p->getName() == mAssetsPackage) {
2630 typeIdOffset = mTypeIdOffset;
2631 }
2632
Adam Lesinski282e1812014-01-23 18:17:42 -08002633 const SourcePos unknown(String8("????"), 0);
2634 sp<Type> attr = p->getType(String16("attr"), unknown);
2635
Adam Lesinski4d219da2016-08-03 15:40:19 -07002636 // Force creation of ID if we are building feature splits.
2637 // Auto-generated ID resources won't apply the type ID offset correctly unless
2638 // the offset is applied here first.
2639 // b/30607637
2640 if (mPackageType == AppFeature && p->getName() == mAssetsPackage) {
2641 sp<Type> id = p->getType(String16("id"), unknown);
2642 }
2643
Adam Lesinski282e1812014-01-23 18:17:42 -08002644 // Assign indices...
Adam Lesinski43a0df02014-08-18 17:14:57 -07002645 const size_t typeCount = p->getOrderedTypes().size();
2646 for (size_t ti = 0; ti < typeCount; ti++) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002647 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2648 if (t == NULL) {
2649 continue;
2650 }
Adam Lesinski43a0df02014-08-18 17:14:57 -07002651
Adam Lesinski282e1812014-01-23 18:17:42 -08002652 err = t->applyPublicEntryOrder();
2653 if (err != NO_ERROR && firstError == NO_ERROR) {
2654 firstError = err;
2655 }
2656
2657 const size_t N = t->getOrderedConfigs().size();
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002658 t->setIndex(ti + 1 + typeIdOffset);
Adam Lesinski282e1812014-01-23 18:17:42 -08002659
2660 LOG_ALWAYS_FATAL_IF(ti == 0 && attr != t,
2661 "First type is not attr!");
2662
2663 for (size_t ei=0; ei<N; ei++) {
2664 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ei);
2665 if (c == NULL) {
2666 continue;
2667 }
2668 c->setEntryIndex(ei);
2669 }
2670 }
2671
Adam Lesinski9b624c12014-11-19 17:49:26 -08002672
Adam Lesinski282e1812014-01-23 18:17:42 -08002673 // Assign resource IDs to keys in bags...
Adam Lesinski43a0df02014-08-18 17:14:57 -07002674 for (size_t ti = 0; ti < typeCount; ti++) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002675 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2676 if (t == NULL) {
2677 continue;
2678 }
Adam Lesinski9b624c12014-11-19 17:49:26 -08002679
Adam Lesinski282e1812014-01-23 18:17:42 -08002680 const size_t N = t->getOrderedConfigs().size();
2681 for (size_t ci=0; ci<N; ci++) {
2682 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
Adam Lesinski9b624c12014-11-19 17:49:26 -08002683 if (c == NULL) {
2684 continue;
2685 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002686 //printf("Ordered config #%d: %p\n", ci, c.get());
2687 const size_t N = c->getEntries().size();
2688 for (size_t ei=0; ei<N; ei++) {
2689 sp<Entry> e = c->getEntries().valueAt(ei);
2690 if (e == NULL) {
2691 continue;
2692 }
2693 status_t err = e->assignResourceIds(this, p->getName());
2694 if (err != NO_ERROR && firstError == NO_ERROR) {
2695 firstError = err;
2696 }
2697 }
2698 }
2699 }
2700 }
2701 return firstError;
2702}
2703
Adrian Roos58922482015-06-01 17:59:41 -07002704status_t ResourceTable::addSymbols(const sp<AaptSymbols>& outSymbols,
2705 bool skipSymbolsWithoutDefaultLocalization) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002706 const size_t N = mOrderedPackages.size();
Adrian Roos58922482015-06-01 17:59:41 -07002707 const String8 defaultLocale;
2708 const String16 stringType("string");
Adam Lesinski282e1812014-01-23 18:17:42 -08002709 size_t pi;
2710
2711 for (pi=0; pi<N; pi++) {
2712 sp<Package> p = mOrderedPackages.itemAt(pi);
2713 if (p->getTypes().size() == 0) {
2714 // Empty, skip!
2715 continue;
2716 }
2717
2718 const size_t N = p->getOrderedTypes().size();
2719 size_t ti;
2720
2721 for (ti=0; ti<N; ti++) {
2722 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2723 if (t == NULL) {
2724 continue;
2725 }
Adam Lesinski9b624c12014-11-19 17:49:26 -08002726
Adam Lesinski282e1812014-01-23 18:17:42 -08002727 const size_t N = t->getOrderedConfigs().size();
Adam Lesinski9b624c12014-11-19 17:49:26 -08002728 sp<AaptSymbols> typeSymbols;
2729 if (t->getName() == String16(kAttrPrivateType)) {
2730 typeSymbols = outSymbols->addNestedSymbol(String8("attr"), t->getPos());
2731 } else {
2732 typeSymbols = outSymbols->addNestedSymbol(String8(t->getName()), t->getPos());
2733 }
2734
Adam Lesinski3fb8c9b2014-09-09 16:05:10 -07002735 if (typeSymbols == NULL) {
2736 return UNKNOWN_ERROR;
2737 }
2738
Adam Lesinski282e1812014-01-23 18:17:42 -08002739 for (size_t ci=0; ci<N; ci++) {
2740 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2741 if (c == NULL) {
2742 continue;
2743 }
2744 uint32_t rid = getResId(p, t, ci);
2745 if (rid == 0) {
2746 return UNKNOWN_ERROR;
2747 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002748 if (Res_GETPACKAGE(rid) + 1 == p->getAssignedId()) {
Adrian Roos58922482015-06-01 17:59:41 -07002749
2750 if (skipSymbolsWithoutDefaultLocalization &&
2751 t->getName() == stringType) {
2752
2753 // Don't generate symbols for strings without a default localization.
2754 if (mHasDefaultLocalization.find(c->getName())
2755 == mHasDefaultLocalization.end()) {
2756 // printf("Skip symbol [%08x] %s\n", rid,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002757 // String8(c->getName()).c_str());
Adrian Roos58922482015-06-01 17:59:41 -07002758 continue;
2759 }
2760 }
2761
Adam Lesinski282e1812014-01-23 18:17:42 -08002762 typeSymbols->addSymbol(String8(c->getName()), rid, c->getPos());
2763
2764 String16 comment(c->getComment());
2765 typeSymbols->appendComment(String8(c->getName()), comment, c->getPos());
Adam Lesinski8ff15b42013-10-07 16:54:01 -07002766 //printf("Type symbol [%08x] %s comment: %s\n", rid,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002767 // String8(c->getName()).c_str(), String8(comment).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08002768 comment = c->getTypeComment();
2769 typeSymbols->appendTypeComment(String8(c->getName()), comment);
Adam Lesinski282e1812014-01-23 18:17:42 -08002770 }
2771 }
2772 }
2773 }
2774 return NO_ERROR;
2775}
2776
2777
2778void
Adam Lesinskia01a9372014-03-20 18:04:57 -07002779ResourceTable::addLocalization(const String16& name, const String8& locale, const SourcePos& src)
Adam Lesinski282e1812014-01-23 18:17:42 -08002780{
Adam Lesinskia01a9372014-03-20 18:04:57 -07002781 mLocalizations[name][locale] = src;
Adam Lesinski282e1812014-01-23 18:17:42 -08002782}
2783
Adrian Roos58922482015-06-01 17:59:41 -07002784void
2785ResourceTable::addDefaultLocalization(const String16& name)
2786{
2787 mHasDefaultLocalization.insert(name);
2788}
2789
Adam Lesinski282e1812014-01-23 18:17:42 -08002790
2791/*!
2792 * Flag various sorts of localization problems. '+' indicates checks already implemented;
2793 * '-' indicates checks that will be implemented in the future.
2794 *
2795 * + A localized string for which no default-locale version exists => warning
2796 * + A string for which no version in an explicitly-requested locale exists => warning
2797 * + A localized translation of an translateable="false" string => warning
2798 * - A localized string not provided in every locale used by the table
2799 */
2800status_t
2801ResourceTable::validateLocalizations(void)
2802{
2803 status_t err = NO_ERROR;
2804 const String8 defaultLocale;
2805
2806 // For all strings...
Dan Albert030f5362015-03-04 13:54:20 -08002807 for (const auto& nameIter : mLocalizations) {
2808 const std::map<String8, SourcePos>& configSrcMap = nameIter.second;
Adam Lesinski282e1812014-01-23 18:17:42 -08002809
2810 // Look for strings with no default localization
Adam Lesinskia01a9372014-03-20 18:04:57 -07002811 if (configSrcMap.count(defaultLocale) == 0) {
2812 SourcePos().warning("string '%s' has no default translation.",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002813 String8(nameIter.first).c_str());
Adam Lesinskia01a9372014-03-20 18:04:57 -07002814 if (mBundle->getVerbose()) {
Dan Albert030f5362015-03-04 13:54:20 -08002815 for (const auto& locale : configSrcMap) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002816 locale.second.printf("locale %s found", locale.first.c_str());
Adam Lesinskia01a9372014-03-20 18:04:57 -07002817 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002818 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002819 // !!! TODO: throw an error here in some circumstances
2820 }
2821
2822 // Check that all requested localizations are present for this string
Adam Lesinskifab50872014-04-16 14:40:42 -07002823 if (mBundle->getConfigurations().size() > 0 && mBundle->getRequireLocalization()) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002824 const char* allConfigs = mBundle->getConfigurations().c_str();
Adam Lesinski282e1812014-01-23 18:17:42 -08002825 const char* start = allConfigs;
2826 const char* comma;
Dan Albert030f5362015-03-04 13:54:20 -08002827
2828 std::set<String8> missingConfigs;
Adam Lesinskia01a9372014-03-20 18:04:57 -07002829 AaptLocaleValue locale;
Adam Lesinski282e1812014-01-23 18:17:42 -08002830 do {
2831 String8 config;
2832 comma = strchr(start, ',');
2833 if (comma != NULL) {
Tomasz Wasilczyk31eb3c892023-08-23 22:12:33 +00002834 config = String8(start, comma - start);
Adam Lesinski282e1812014-01-23 18:17:42 -08002835 start = comma + 1;
2836 } else {
Tomasz Wasilczyk31eb3c892023-08-23 22:12:33 +00002837 config = start;
Adam Lesinski282e1812014-01-23 18:17:42 -08002838 }
2839
Adam Lesinskia01a9372014-03-20 18:04:57 -07002840 if (!locale.initFromFilterString(config)) {
2841 continue;
2842 }
2843
Anton Krumina2ef5c02014-03-12 14:46:44 -07002844 // don't bother with the pseudolocale "en_XA" or "ar_XB"
2845 if (config != "en_XA" && config != "ar_XB") {
Adam Lesinskia01a9372014-03-20 18:04:57 -07002846 if (configSrcMap.find(config) == configSrcMap.end()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002847 // okay, no specific localization found. it's possible that we are
2848 // requiring a specific regional localization [e.g. de_DE] but there is an
2849 // available string in the generic language localization [e.g. de];
2850 // consider that string to have fulfilled the localization requirement.
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002851 String8 region(config.c_str(), 2);
Adam Lesinskia01a9372014-03-20 18:04:57 -07002852 if (configSrcMap.find(region) == configSrcMap.end() &&
2853 configSrcMap.count(defaultLocale) == 0) {
2854 missingConfigs.insert(config);
Adam Lesinski282e1812014-01-23 18:17:42 -08002855 }
2856 }
2857 }
Adam Lesinskia01a9372014-03-20 18:04:57 -07002858 } while (comma != NULL);
2859
2860 if (!missingConfigs.empty()) {
2861 String8 configStr;
Dan Albert030f5362015-03-04 13:54:20 -08002862 for (const auto& iter : missingConfigs) {
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002863 configStr.appendFormat(" %s", iter.c_str());
Adam Lesinskia01a9372014-03-20 18:04:57 -07002864 }
2865 SourcePos().warning("string '%s' is missing %u required localizations:%s",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002866 String8(nameIter.first).c_str(),
Adam Lesinskia01a9372014-03-20 18:04:57 -07002867 (unsigned int)missingConfigs.size(),
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00002868 configStr.c_str());
Adam Lesinskia01a9372014-03-20 18:04:57 -07002869 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002870 }
2871 }
2872
2873 return err;
2874}
2875
Adam Lesinski27f69f42014-08-21 13:19:12 -07002876status_t ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& filter,
2877 const sp<AaptFile>& dest,
2878 const bool isBase)
Adam Lesinski282e1812014-01-23 18:17:42 -08002879{
Adam Lesinski282e1812014-01-23 18:17:42 -08002880 const ConfigDescription nullConfig;
2881
2882 const size_t N = mOrderedPackages.size();
2883 size_t pi;
2884
2885 const static String16 mipmap16("mipmap");
2886
2887 bool useUTF8 = !bundle->getUTF16StringsOption();
2888
Adam Lesinskide898ff2014-01-29 18:20:45 -08002889 // The libraries this table references.
2890 Vector<sp<Package> > libraryPackages;
Adam Lesinski6022deb2014-08-20 14:59:19 -07002891 const ResTable& table = mAssets->getIncludedResources();
2892 const size_t basePackageCount = table.getBasePackageCount();
2893 for (size_t i = 0; i < basePackageCount; i++) {
2894 size_t packageId = table.getBasePackageId(i);
2895 String16 packageName(table.getBasePackageName(i));
2896 if (packageId > 0x01 && packageId != 0x7f &&
2897 packageName != String16("android")) {
2898 libraryPackages.add(sp<Package>(new Package(packageName, packageId)));
2899 }
2900 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08002901
Adam Lesinski282e1812014-01-23 18:17:42 -08002902 // Iterate through all data, collecting all values (strings,
2903 // references, etc).
2904 StringPool valueStrings(useUTF8);
2905 Vector<sp<Entry> > allEntries;
2906 for (pi=0; pi<N; pi++) {
2907 sp<Package> p = mOrderedPackages.itemAt(pi);
2908 if (p->getTypes().size() == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002909 continue;
2910 }
2911
2912 StringPool typeStrings(useUTF8);
2913 StringPool keyStrings(useUTF8);
2914
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002915 ssize_t stringsAdded = 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08002916 const size_t N = p->getOrderedTypes().size();
2917 for (size_t ti=0; ti<N; ti++) {
2918 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2919 if (t == NULL) {
2920 typeStrings.add(String16("<empty>"), false);
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002921 stringsAdded++;
Adam Lesinski282e1812014-01-23 18:17:42 -08002922 continue;
2923 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002924
2925 while (stringsAdded < t->getIndex() - 1) {
2926 typeStrings.add(String16("<empty>"), false);
2927 stringsAdded++;
2928 }
2929
Adam Lesinski282e1812014-01-23 18:17:42 -08002930 const String16 typeName(t->getName());
2931 typeStrings.add(typeName, false);
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002932 stringsAdded++;
Adam Lesinski282e1812014-01-23 18:17:42 -08002933
2934 // This is a hack to tweak the sorting order of the final strings,
2935 // to put stuff that is generally not language-specific first.
2936 String8 configTypeName(typeName);
2937 if (configTypeName == "drawable" || configTypeName == "layout"
2938 || configTypeName == "color" || configTypeName == "anim"
2939 || configTypeName == "interpolator" || configTypeName == "animator"
2940 || configTypeName == "xml" || configTypeName == "menu"
2941 || configTypeName == "mipmap" || configTypeName == "raw") {
2942 configTypeName = "1complex";
2943 } else {
2944 configTypeName = "2value";
2945 }
2946
Adam Lesinski27f69f42014-08-21 13:19:12 -07002947 // mipmaps don't get filtered, so they will
2948 // allways end up in the base. Make sure they
2949 // don't end up in a split.
2950 if (typeName == mipmap16 && !isBase) {
2951 continue;
2952 }
2953
Adam Lesinski282e1812014-01-23 18:17:42 -08002954 const bool filterable = (typeName != mipmap16);
2955
2956 const size_t N = t->getOrderedConfigs().size();
2957 for (size_t ci=0; ci<N; ci++) {
2958 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2959 if (c == NULL) {
2960 continue;
2961 }
2962 const size_t N = c->getEntries().size();
2963 for (size_t ei=0; ei<N; ei++) {
2964 ConfigDescription config = c->getEntries().keyAt(ei);
Adam Lesinskifab50872014-04-16 14:40:42 -07002965 if (filterable && !filter->match(config)) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002966 continue;
2967 }
2968 sp<Entry> e = c->getEntries().valueAt(ei);
2969 if (e == NULL) {
2970 continue;
2971 }
2972 e->setNameIndex(keyStrings.add(e->getName(), true));
2973
Adam Lesinski282e1812014-01-23 18:17:42 -08002974 status_t err = e->prepareFlatten(&valueStrings, this,
2975 &configTypeName, &config);
2976 if (err != NO_ERROR) {
2977 return err;
2978 }
2979 allEntries.add(e);
2980 }
2981 }
2982 }
2983
2984 p->setTypeStrings(typeStrings.createStringBlock());
2985 p->setKeyStrings(keyStrings.createStringBlock());
2986 }
2987
2988 if (bundle->getOutputAPKFile() != NULL) {
2989 // Now we want to sort the value strings for better locality. This will
2990 // cause the positions of the strings to change, so we need to go back
2991 // through out resource entries and update them accordingly. Only need
2992 // to do this if actually writing the output file.
2993 valueStrings.sortByConfig();
2994 for (pi=0; pi<allEntries.size(); pi++) {
2995 allEntries[pi]->remapStringValue(&valueStrings);
2996 }
2997 }
2998
2999 ssize_t strAmt = 0;
Adam Lesinskide898ff2014-01-29 18:20:45 -08003000
Adam Lesinski282e1812014-01-23 18:17:42 -08003001 // Now build the array of package chunks.
3002 Vector<sp<AaptFile> > flatPackages;
3003 for (pi=0; pi<N; pi++) {
3004 sp<Package> p = mOrderedPackages.itemAt(pi);
3005 if (p->getTypes().size() == 0) {
3006 // Empty, skip!
3007 continue;
3008 }
3009
3010 const size_t N = p->getTypeStrings().size();
3011
3012 const size_t baseSize = sizeof(ResTable_package);
3013
3014 // Start the package data.
3015 sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
3016 ResTable_package* header = (ResTable_package*)data->editData(baseSize);
3017 if (header == NULL) {
3018 fprintf(stderr, "ERROR: out of memory creating ResTable_package\n");
3019 return NO_MEMORY;
3020 }
3021 memset(header, 0, sizeof(*header));
3022 header->header.type = htods(RES_TABLE_PACKAGE_TYPE);
3023 header->header.headerSize = htods(sizeof(*header));
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003024 header->id = htodl(static_cast<uint32_t>(p->getAssignedId()));
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003025 strcpy16_htod(header->name, p->getName().c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003026
3027 // Write the string blocks.
3028 const size_t typeStringsStart = data->getSize();
3029 sp<AaptFile> strFile = p->getTypeStringsData();
3030 ssize_t amt = data->writeData(strFile->getData(), strFile->getSize());
Andreas Gampe2412f842014-09-30 20:55:57 -07003031 if (kPrintStringMetrics) {
Pirama Arumuga Nainardc36bb62018-05-11 15:52:49 -07003032 fprintf(stderr, "**** type strings: %zd\n", amt);
Andreas Gampe2412f842014-09-30 20:55:57 -07003033 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003034 strAmt += amt;
3035 if (amt < 0) {
3036 return amt;
3037 }
3038 const size_t keyStringsStart = data->getSize();
3039 strFile = p->getKeyStringsData();
3040 amt = data->writeData(strFile->getData(), strFile->getSize());
Andreas Gampe2412f842014-09-30 20:55:57 -07003041 if (kPrintStringMetrics) {
Pirama Arumuga Nainardc36bb62018-05-11 15:52:49 -07003042 fprintf(stderr, "**** key strings: %zd\n", amt);
Andreas Gampe2412f842014-09-30 20:55:57 -07003043 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003044 strAmt += amt;
3045 if (amt < 0) {
3046 return amt;
3047 }
3048
Adam Lesinski27f69f42014-08-21 13:19:12 -07003049 if (isBase) {
3050 status_t err = flattenLibraryTable(data, libraryPackages);
3051 if (err != NO_ERROR) {
3052 fprintf(stderr, "ERROR: failed to write library table\n");
3053 return err;
3054 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08003055 }
3056
Adam Lesinski282e1812014-01-23 18:17:42 -08003057 // Build the type chunks inside of this package.
3058 for (size_t ti=0; ti<N; ti++) {
3059 // Retrieve them in the same order as the type string block.
3060 size_t len;
Ryan Mitchell80094e32020-11-16 23:08:18 +00003061 String16 typeName(UnpackOptionalString(p->getTypeStrings().stringAt(ti), &len));
Adam Lesinski282e1812014-01-23 18:17:42 -08003062 sp<Type> t = p->getTypes().valueFor(typeName);
3063 LOG_ALWAYS_FATAL_IF(t == NULL && typeName != String16("<empty>"),
3064 "Type name %s not found",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003065 String8(typeName).c_str());
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003066 if (t == NULL) {
3067 continue;
3068 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003069 const bool filterable = (typeName != mipmap16);
Adam Lesinski27f69f42014-08-21 13:19:12 -07003070 const bool skipEntireType = (typeName == mipmap16 && !isBase);
Adam Lesinski282e1812014-01-23 18:17:42 -08003071
3072 const size_t N = t != NULL ? t->getOrderedConfigs().size() : 0;
3073
3074 // Until a non-NO_ENTRY value has been written for a resource,
3075 // that resource is invalid; validResources[i] represents
3076 // the item at t->getOrderedConfigs().itemAt(i).
3077 Vector<bool> validResources;
3078 validResources.insertAt(false, 0, N);
3079
3080 // First write the typeSpec chunk, containing information about
3081 // each resource entry in this type.
3082 {
3083 const size_t typeSpecSize = sizeof(ResTable_typeSpec) + sizeof(uint32_t)*N;
3084 const size_t typeSpecStart = data->getSize();
3085 ResTable_typeSpec* tsHeader = (ResTable_typeSpec*)
3086 (((uint8_t*)data->editData(typeSpecStart+typeSpecSize)) + typeSpecStart);
3087 if (tsHeader == NULL) {
3088 fprintf(stderr, "ERROR: out of memory creating ResTable_typeSpec\n");
3089 return NO_MEMORY;
3090 }
3091 memset(tsHeader, 0, sizeof(*tsHeader));
3092 tsHeader->header.type = htods(RES_TABLE_TYPE_SPEC_TYPE);
3093 tsHeader->header.headerSize = htods(sizeof(*tsHeader));
3094 tsHeader->header.size = htodl(typeSpecSize);
3095 tsHeader->id = ti+1;
3096 tsHeader->entryCount = htodl(N);
3097
3098 uint32_t* typeSpecFlags = (uint32_t*)
3099 (((uint8_t*)data->editData())
3100 + typeSpecStart + sizeof(ResTable_typeSpec));
3101 memset(typeSpecFlags, 0, sizeof(uint32_t)*N);
3102
3103 for (size_t ei=0; ei<N; ei++) {
3104 sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
Adam Lesinski9b624c12014-11-19 17:49:26 -08003105 if (cl == NULL) {
3106 continue;
3107 }
3108
Adam Lesinski282e1812014-01-23 18:17:42 -08003109 if (cl->getPublic()) {
3110 typeSpecFlags[ei] |= htodl(ResTable_typeSpec::SPEC_PUBLIC);
3111 }
Adam Lesinski27f69f42014-08-21 13:19:12 -07003112
3113 if (skipEntireType) {
3114 continue;
3115 }
3116
Adam Lesinski282e1812014-01-23 18:17:42 -08003117 const size_t CN = cl->getEntries().size();
3118 for (size_t ci=0; ci<CN; ci++) {
Adam Lesinskifab50872014-04-16 14:40:42 -07003119 if (filterable && !filter->match(cl->getEntries().keyAt(ci))) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003120 continue;
3121 }
3122 for (size_t cj=ci+1; cj<CN; cj++) {
Adam Lesinskifab50872014-04-16 14:40:42 -07003123 if (filterable && !filter->match(cl->getEntries().keyAt(cj))) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003124 continue;
3125 }
3126 typeSpecFlags[ei] |= htodl(
3127 cl->getEntries().keyAt(ci).diff(cl->getEntries().keyAt(cj)));
3128 }
3129 }
3130 }
3131 }
3132
Adam Lesinski27f69f42014-08-21 13:19:12 -07003133 if (skipEntireType) {
3134 continue;
3135 }
3136
Adam Lesinski282e1812014-01-23 18:17:42 -08003137 // We need to write one type chunk for each configuration for
3138 // which we have entries in this type.
Adam Lesinskie97908d2014-12-05 11:06:21 -08003139 SortedVector<ConfigDescription> uniqueConfigs;
3140 if (t != NULL) {
3141 uniqueConfigs = t->getUniqueConfigs();
3142 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003143
3144 const size_t typeSize = sizeof(ResTable_type) + sizeof(uint32_t)*N;
3145
Adam Lesinskie97908d2014-12-05 11:06:21 -08003146 const size_t NC = uniqueConfigs.size();
Adam Lesinski282e1812014-01-23 18:17:42 -08003147 for (size_t ci=0; ci<NC; ci++) {
Adam Lesinski9b624c12014-11-19 17:49:26 -08003148 const ConfigDescription& config = uniqueConfigs[ci];
Adam Lesinski282e1812014-01-23 18:17:42 -08003149
Andreas Gampe2412f842014-09-30 20:55:57 -07003150 if (kIsDebug) {
3151 printf("Writing config %zu config: imsi:%d/%d lang:%c%c cnt:%c%c "
3152 "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
3153 "sw%ddp w%ddp h%ddp layout:%d\n",
3154 ti + 1,
3155 config.mcc, config.mnc,
3156 config.language[0] ? config.language[0] : '-',
3157 config.language[1] ? config.language[1] : '-',
3158 config.country[0] ? config.country[0] : '-',
3159 config.country[1] ? config.country[1] : '-',
3160 config.orientation,
3161 config.uiMode,
3162 config.touchscreen,
3163 config.density,
3164 config.keyboard,
3165 config.inputFlags,
3166 config.navigation,
3167 config.screenWidth,
3168 config.screenHeight,
3169 config.smallestScreenWidthDp,
3170 config.screenWidthDp,
3171 config.screenHeightDp,
3172 config.screenLayout);
3173 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003174
Adam Lesinskifab50872014-04-16 14:40:42 -07003175 if (filterable && !filter->match(config)) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003176 continue;
3177 }
3178
3179 const size_t typeStart = data->getSize();
3180
3181 ResTable_type* tHeader = (ResTable_type*)
3182 (((uint8_t*)data->editData(typeStart+typeSize)) + typeStart);
3183 if (tHeader == NULL) {
3184 fprintf(stderr, "ERROR: out of memory creating ResTable_type\n");
3185 return NO_MEMORY;
3186 }
3187
3188 memset(tHeader, 0, sizeof(*tHeader));
3189 tHeader->header.type = htods(RES_TABLE_TYPE_TYPE);
3190 tHeader->header.headerSize = htods(sizeof(*tHeader));
3191 tHeader->id = ti+1;
3192 tHeader->entryCount = htodl(N);
3193 tHeader->entriesStart = htodl(typeSize);
3194 tHeader->config = config;
Andreas Gampe2412f842014-09-30 20:55:57 -07003195 if (kIsDebug) {
3196 printf("Writing type %zu config: imsi:%d/%d lang:%c%c cnt:%c%c "
3197 "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
3198 "sw%ddp w%ddp h%ddp layout:%d\n",
3199 ti + 1,
3200 tHeader->config.mcc, tHeader->config.mnc,
3201 tHeader->config.language[0] ? tHeader->config.language[0] : '-',
3202 tHeader->config.language[1] ? tHeader->config.language[1] : '-',
3203 tHeader->config.country[0] ? tHeader->config.country[0] : '-',
3204 tHeader->config.country[1] ? tHeader->config.country[1] : '-',
3205 tHeader->config.orientation,
3206 tHeader->config.uiMode,
3207 tHeader->config.touchscreen,
3208 tHeader->config.density,
3209 tHeader->config.keyboard,
3210 tHeader->config.inputFlags,
3211 tHeader->config.navigation,
3212 tHeader->config.screenWidth,
3213 tHeader->config.screenHeight,
3214 tHeader->config.smallestScreenWidthDp,
3215 tHeader->config.screenWidthDp,
3216 tHeader->config.screenHeightDp,
3217 tHeader->config.screenLayout);
3218 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003219 tHeader->config.swapHtoD();
3220
3221 // Build the entries inside of this type.
3222 for (size_t ei=0; ei<N; ei++) {
3223 sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
Adam Lesinski9b624c12014-11-19 17:49:26 -08003224 sp<Entry> e = NULL;
3225 if (cl != NULL) {
3226 e = cl->getEntries().valueFor(config);
3227 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003228
3229 // Set the offset for this entry in its type.
3230 uint32_t* index = (uint32_t*)
3231 (((uint8_t*)data->editData())
3232 + typeStart + sizeof(ResTable_type));
3233 if (e != NULL) {
3234 index[ei] = htodl(data->getSize()-typeStart-typeSize);
3235
3236 // Create the entry.
3237 ssize_t amt = e->flatten(bundle, data, cl->getPublic());
3238 if (amt < 0) {
3239 return amt;
3240 }
3241 validResources.editItemAt(ei) = true;
3242 } else {
3243 index[ei] = htodl(ResTable_type::NO_ENTRY);
3244 }
3245 }
3246
3247 // Fill in the rest of the type information.
3248 tHeader = (ResTable_type*)
3249 (((uint8_t*)data->editData()) + typeStart);
3250 tHeader->header.size = htodl(data->getSize()-typeStart);
3251 }
3252
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003253 // If we're building splits, then each invocation of the flattening
3254 // step will have 'missing' entries. Don't warn/error for this case.
Tomasz Wasilczyk7e22cab2023-08-24 19:02:33 +00003255 if (bundle->getSplitConfigurations().empty()) {
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003256 bool missing_entry = false;
3257 const char* log_prefix = bundle->getErrorOnMissingConfigEntry() ?
3258 "error" : "warning";
3259 for (size_t i = 0; i < N; ++i) {
3260 if (!validResources[i]) {
3261 sp<ConfigList> c = t->getOrderedConfigs().itemAt(i);
Adam Lesinski9b624c12014-11-19 17:49:26 -08003262 if (c != NULL) {
Colin Cross01f18562015-04-08 17:29:00 -07003263 fprintf(stderr, "%s: no entries written for %s/%s (0x%08zx)\n", log_prefix,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003264 String8(typeName).c_str(), String8(c->getName()).c_str(),
Adam Lesinski9b624c12014-11-19 17:49:26 -08003265 Res_MAKEID(p->getAssignedId() - 1, ti, i));
3266 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003267 missing_entry = true;
3268 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003269 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003270 if (bundle->getErrorOnMissingConfigEntry() && missing_entry) {
3271 fprintf(stderr, "Error: Missing entries, quit!\n");
3272 return NOT_ENOUGH_DATA;
3273 }
Ying Wangcd28bd32013-11-14 17:12:10 -08003274 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003275 }
3276
3277 // Fill in the rest of the package information.
3278 header = (ResTable_package*)data->editData();
3279 header->header.size = htodl(data->getSize());
3280 header->typeStrings = htodl(typeStringsStart);
3281 header->lastPublicType = htodl(p->getTypeStrings().size());
3282 header->keyStrings = htodl(keyStringsStart);
3283 header->lastPublicKey = htodl(p->getKeyStrings().size());
3284
3285 flatPackages.add(data);
3286 }
3287
3288 // And now write out the final chunks.
3289 const size_t dataStart = dest->getSize();
3290
3291 {
3292 // blah
3293 ResTable_header header;
3294 memset(&header, 0, sizeof(header));
3295 header.header.type = htods(RES_TABLE_TYPE);
3296 header.header.headerSize = htods(sizeof(header));
3297 header.packageCount = htodl(flatPackages.size());
3298 status_t err = dest->writeData(&header, sizeof(header));
3299 if (err != NO_ERROR) {
3300 fprintf(stderr, "ERROR: out of memory creating ResTable_header\n");
3301 return err;
3302 }
3303 }
3304
3305 ssize_t strStart = dest->getSize();
Adam Lesinskifab50872014-04-16 14:40:42 -07003306 status_t err = valueStrings.writeStringBlock(dest);
Adam Lesinski282e1812014-01-23 18:17:42 -08003307 if (err != NO_ERROR) {
3308 return err;
3309 }
3310
3311 ssize_t amt = (dest->getSize()-strStart);
3312 strAmt += amt;
Andreas Gampe2412f842014-09-30 20:55:57 -07003313 if (kPrintStringMetrics) {
Pirama Arumuga Nainardc36bb62018-05-11 15:52:49 -07003314 fprintf(stderr, "**** value strings: %zd\n", amt);
3315 fprintf(stderr, "**** total strings: %zd\n", amt);
Andreas Gampe2412f842014-09-30 20:55:57 -07003316 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08003317
Adam Lesinski282e1812014-01-23 18:17:42 -08003318 for (pi=0; pi<flatPackages.size(); pi++) {
3319 err = dest->writeData(flatPackages[pi]->getData(),
3320 flatPackages[pi]->getSize());
3321 if (err != NO_ERROR) {
3322 fprintf(stderr, "ERROR: out of memory creating package chunk for ResTable_header\n");
3323 return err;
3324 }
3325 }
3326
3327 ResTable_header* header = (ResTable_header*)
3328 (((uint8_t*)dest->getData()) + dataStart);
3329 header->header.size = htodl(dest->getSize() - dataStart);
3330
Andreas Gampe2412f842014-09-30 20:55:57 -07003331 if (kPrintStringMetrics) {
3332 fprintf(stderr, "**** total resource table size: %zu / %zu%% strings\n",
3333 dest->getSize(), (size_t)(strAmt*100)/dest->getSize());
3334 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003335
3336 return NO_ERROR;
3337}
3338
Adam Lesinskide898ff2014-01-29 18:20:45 -08003339status_t ResourceTable::flattenLibraryTable(const sp<AaptFile>& dest, const Vector<sp<Package> >& libs) {
3340 // Write out the library table if necessary
3341 if (libs.size() > 0) {
Andreas Gampe87332a72014-10-01 22:03:58 -07003342 if (kIsDebug) {
3343 fprintf(stderr, "Writing library reference table\n");
3344 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08003345
3346 const size_t libStart = dest->getSize();
3347 const size_t count = libs.size();
Adam Lesinski6022deb2014-08-20 14:59:19 -07003348 ResTable_lib_header* libHeader = (ResTable_lib_header*) dest->editDataInRange(
3349 libStart, sizeof(ResTable_lib_header));
Adam Lesinskide898ff2014-01-29 18:20:45 -08003350
3351 memset(libHeader, 0, sizeof(*libHeader));
3352 libHeader->header.type = htods(RES_TABLE_LIBRARY_TYPE);
3353 libHeader->header.headerSize = htods(sizeof(*libHeader));
3354 libHeader->header.size = htodl(sizeof(*libHeader) + (sizeof(ResTable_lib_entry) * count));
3355 libHeader->count = htodl(count);
3356
3357 // Write the library entries
3358 for (size_t i = 0; i < count; i++) {
3359 const size_t entryStart = dest->getSize();
3360 sp<Package> libPackage = libs[i];
Andreas Gampe87332a72014-10-01 22:03:58 -07003361 if (kIsDebug) {
3362 fprintf(stderr, " Entry %s -> 0x%02x\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003363 String8(libPackage->getName()).c_str(),
Andreas Gampe87332a72014-10-01 22:03:58 -07003364 (uint8_t)libPackage->getAssignedId());
3365 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08003366
Adam Lesinski6022deb2014-08-20 14:59:19 -07003367 ResTable_lib_entry* entry = (ResTable_lib_entry*) dest->editDataInRange(
3368 entryStart, sizeof(ResTable_lib_entry));
Adam Lesinskide898ff2014-01-29 18:20:45 -08003369 memset(entry, 0, sizeof(*entry));
3370 entry->packageId = htodl(libPackage->getAssignedId());
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003371 strcpy16_htod(entry->packageName, libPackage->getName().c_str());
Adam Lesinskide898ff2014-01-29 18:20:45 -08003372 }
3373 }
3374 return NO_ERROR;
3375}
3376
Adam Lesinski282e1812014-01-23 18:17:42 -08003377void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp)
3378{
3379 fprintf(fp,
3380 "<!-- This file contains <public> resource definitions for all\n"
3381 " resources that were generated from the source data. -->\n"
3382 "\n"
3383 "<resources>\n");
3384
3385 writePublicDefinitions(package, fp, true);
3386 writePublicDefinitions(package, fp, false);
3387
3388 fprintf(fp,
3389 "\n"
3390 "</resources>\n");
3391}
3392
3393void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp, bool pub)
3394{
3395 bool didHeader = false;
3396
3397 sp<Package> pkg = mPackages.valueFor(package);
3398 if (pkg != NULL) {
3399 const size_t NT = pkg->getOrderedTypes().size();
3400 for (size_t i=0; i<NT; i++) {
3401 sp<Type> t = pkg->getOrderedTypes().itemAt(i);
3402 if (t == NULL) {
3403 continue;
3404 }
3405
3406 bool didType = false;
3407
3408 const size_t NC = t->getOrderedConfigs().size();
3409 for (size_t j=0; j<NC; j++) {
3410 sp<ConfigList> c = t->getOrderedConfigs().itemAt(j);
3411 if (c == NULL) {
3412 continue;
3413 }
3414
3415 if (c->getPublic() != pub) {
3416 continue;
3417 }
3418
3419 if (!didType) {
3420 fprintf(fp, "\n");
3421 didType = true;
3422 }
3423 if (!didHeader) {
3424 if (pub) {
3425 fprintf(fp," <!-- PUBLIC SECTION. These resources have been declared public.\n");
3426 fprintf(fp," Changes to these definitions will break binary compatibility. -->\n\n");
3427 } else {
3428 fprintf(fp," <!-- PRIVATE SECTION. These resources have not been declared public.\n");
3429 fprintf(fp," You can make them public my moving these lines into a file in res/values. -->\n\n");
3430 }
3431 didHeader = true;
3432 }
3433 if (!pub) {
3434 const size_t NE = c->getEntries().size();
3435 for (size_t k=0; k<NE; k++) {
3436 const SourcePos& pos = c->getEntries().valueAt(k)->getPos();
3437 if (pos.file != "") {
3438 fprintf(fp," <!-- Declared at %s:%d -->\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003439 pos.file.c_str(), pos.line);
Adam Lesinski282e1812014-01-23 18:17:42 -08003440 }
3441 }
3442 }
3443 fprintf(fp, " <public type=\"%s\" name=\"%s\" id=\"0x%08x\" />\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003444 String8(t->getName()).c_str(),
3445 String8(c->getName()).c_str(),
Adam Lesinski282e1812014-01-23 18:17:42 -08003446 getResId(pkg, t, c->getEntryIndex()));
3447 }
3448 }
3449 }
3450}
3451
3452ResourceTable::Item::Item(const SourcePos& _sourcePos,
3453 bool _isId,
3454 const String16& _value,
3455 const Vector<StringPool::entry_style_span>* _style,
3456 int32_t _format)
3457 : sourcePos(_sourcePos)
3458 , isId(_isId)
3459 , value(_value)
3460 , format(_format)
3461 , bagKeyId(0)
3462 , evaluating(false)
3463{
3464 if (_style) {
3465 style = *_style;
3466 }
3467}
3468
Adam Lesinski82a2dd82014-09-17 18:34:15 -07003469ResourceTable::Entry::Entry(const Entry& entry)
3470 : RefBase()
3471 , mName(entry.mName)
3472 , mParent(entry.mParent)
3473 , mType(entry.mType)
3474 , mItem(entry.mItem)
3475 , mItemFormat(entry.mItemFormat)
3476 , mBag(entry.mBag)
3477 , mNameIndex(entry.mNameIndex)
3478 , mParentId(entry.mParentId)
3479 , mPos(entry.mPos) {}
3480
Adam Lesinski978ab9d2014-09-24 19:02:52 -07003481ResourceTable::Entry& ResourceTable::Entry::operator=(const Entry& entry) {
3482 mName = entry.mName;
3483 mParent = entry.mParent;
3484 mType = entry.mType;
3485 mItem = entry.mItem;
3486 mItemFormat = entry.mItemFormat;
3487 mBag = entry.mBag;
3488 mNameIndex = entry.mNameIndex;
3489 mParentId = entry.mParentId;
3490 mPos = entry.mPos;
3491 return *this;
3492}
3493
Adam Lesinski282e1812014-01-23 18:17:42 -08003494status_t ResourceTable::Entry::makeItABag(const SourcePos& sourcePos)
3495{
3496 if (mType == TYPE_BAG) {
3497 return NO_ERROR;
3498 }
3499 if (mType == TYPE_UNKNOWN) {
3500 mType = TYPE_BAG;
3501 return NO_ERROR;
3502 }
3503 sourcePos.error("Resource entry %s is already defined as a single item.\n"
3504 "%s:%d: Originally defined here.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003505 String8(mName).c_str(),
3506 mItem.sourcePos.file.c_str(), mItem.sourcePos.line);
Adam Lesinski282e1812014-01-23 18:17:42 -08003507 return UNKNOWN_ERROR;
3508}
3509
3510status_t ResourceTable::Entry::setItem(const SourcePos& sourcePos,
3511 const String16& value,
3512 const Vector<StringPool::entry_style_span>* style,
3513 int32_t format,
3514 const bool overwrite)
3515{
3516 Item item(sourcePos, false, value, style);
3517
3518 if (mType == TYPE_BAG) {
Adam Lesinski43a0df02014-08-18 17:14:57 -07003519 if (mBag.size() == 0) {
3520 sourcePos.error("Resource entry %s is already defined as a bag.",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003521 String8(mName).c_str());
Adam Lesinski43a0df02014-08-18 17:14:57 -07003522 } else {
3523 const Item& item(mBag.valueAt(0));
3524 sourcePos.error("Resource entry %s is already defined as a bag.\n"
3525 "%s:%d: Originally defined here.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003526 String8(mName).c_str(),
3527 item.sourcePos.file.c_str(), item.sourcePos.line);
Adam Lesinski43a0df02014-08-18 17:14:57 -07003528 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003529 return UNKNOWN_ERROR;
3530 }
3531 if ( (mType != TYPE_UNKNOWN) && (overwrite == false) ) {
3532 sourcePos.error("Resource entry %s is already defined.\n"
3533 "%s:%d: Originally defined here.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003534 String8(mName).c_str(),
3535 mItem.sourcePos.file.c_str(), mItem.sourcePos.line);
Adam Lesinski282e1812014-01-23 18:17:42 -08003536 return UNKNOWN_ERROR;
3537 }
3538
3539 mType = TYPE_ITEM;
3540 mItem = item;
3541 mItemFormat = format;
3542 return NO_ERROR;
3543}
3544
3545status_t ResourceTable::Entry::addToBag(const SourcePos& sourcePos,
3546 const String16& key, const String16& value,
3547 const Vector<StringPool::entry_style_span>* style,
3548 bool replace, bool isId, int32_t format)
3549{
3550 status_t err = makeItABag(sourcePos);
3551 if (err != NO_ERROR) {
3552 return err;
3553 }
3554
3555 Item item(sourcePos, isId, value, style, format);
3556
3557 // XXX NOTE: there is an error if you try to have a bag with two keys,
3558 // one an attr and one an id, with the same name. Not something we
3559 // currently ever have to worry about.
3560 ssize_t origKey = mBag.indexOfKey(key);
3561 if (origKey >= 0) {
3562 if (!replace) {
3563 const Item& item(mBag.valueAt(origKey));
3564 sourcePos.error("Resource entry %s already has bag item %s.\n"
3565 "%s:%d: Originally defined here.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003566 String8(mName).c_str(), String8(key).c_str(),
3567 item.sourcePos.file.c_str(), item.sourcePos.line);
Adam Lesinski282e1812014-01-23 18:17:42 -08003568 return UNKNOWN_ERROR;
3569 }
3570 //printf("Replacing %s with %s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003571 // String8(mBag.valueFor(key).value).c_str(), String8(value).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003572 mBag.replaceValueFor(key, item);
3573 }
3574
3575 mBag.add(key, item);
3576 return NO_ERROR;
3577}
3578
Adam Lesinski82a2dd82014-09-17 18:34:15 -07003579status_t ResourceTable::Entry::removeFromBag(const String16& key) {
3580 if (mType != Entry::TYPE_BAG) {
3581 return NO_ERROR;
3582 }
3583
3584 if (mBag.removeItem(key) >= 0) {
3585 return NO_ERROR;
3586 }
3587 return UNKNOWN_ERROR;
3588}
3589
Adam Lesinski282e1812014-01-23 18:17:42 -08003590status_t ResourceTable::Entry::emptyBag(const SourcePos& sourcePos)
3591{
3592 status_t err = makeItABag(sourcePos);
3593 if (err != NO_ERROR) {
3594 return err;
3595 }
3596
3597 mBag.clear();
3598 return NO_ERROR;
3599}
3600
3601status_t ResourceTable::Entry::generateAttributes(ResourceTable* table,
3602 const String16& package)
3603{
3604 const String16 attr16("attr");
3605 const String16 id16("id");
3606 const size_t N = mBag.size();
3607 for (size_t i=0; i<N; i++) {
3608 const String16& key = mBag.keyAt(i);
3609 const Item& it = mBag.valueAt(i);
3610 if (it.isId) {
3611 if (!table->hasBagOrEntry(key, &id16, &package)) {
3612 String16 value("false");
Andreas Gampe87332a72014-10-01 22:03:58 -07003613 if (kIsDebug) {
3614 fprintf(stderr, "Generating %s:id/%s\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003615 String8(package).c_str(),
3616 String8(key).c_str());
Andreas Gampe87332a72014-10-01 22:03:58 -07003617 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003618 status_t err = table->addEntry(SourcePos(String8("<generated>"), 0), package,
3619 id16, key, value);
3620 if (err != NO_ERROR) {
3621 return err;
3622 }
3623 }
3624 } else if (!table->hasBagOrEntry(key, &attr16, &package)) {
3625
3626#if 1
3627// fprintf(stderr, "ERROR: Bag attribute '%s' has not been defined.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003628// String8(key).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003629// const Item& item(mBag.valueAt(i));
3630// fprintf(stderr, "Referenced from file %s line %d\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003631// item.sourcePos.file.c_str(), item.sourcePos.line);
Adam Lesinski282e1812014-01-23 18:17:42 -08003632// return UNKNOWN_ERROR;
3633#else
3634 char numberStr[16];
3635 sprintf(numberStr, "%d", ResTable_map::TYPE_ANY);
3636 status_t err = table->addBag(SourcePos("<generated>", 0), package,
3637 attr16, key, String16(""),
3638 String16("^type"),
3639 String16(numberStr), NULL, NULL);
3640 if (err != NO_ERROR) {
3641 return err;
3642 }
3643#endif
3644 }
3645 }
3646 return NO_ERROR;
3647}
3648
3649status_t ResourceTable::Entry::assignResourceIds(ResourceTable* table,
Andreas Gampe2412f842014-09-30 20:55:57 -07003650 const String16& /* package */)
Adam Lesinski282e1812014-01-23 18:17:42 -08003651{
3652 bool hasErrors = false;
3653
3654 if (mType == TYPE_BAG) {
3655 const char* errorMsg;
3656 const String16 style16("style");
3657 const String16 attr16("attr");
3658 const String16 id16("id");
3659 mParentId = 0;
3660 if (mParent.size() > 0) {
3661 mParentId = table->getResId(mParent, &style16, NULL, &errorMsg);
3662 if (mParentId == 0) {
3663 mPos.error("Error retrieving parent for item: %s '%s'.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003664 errorMsg, String8(mParent).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003665 hasErrors = true;
3666 }
3667 }
3668 const size_t N = mBag.size();
3669 for (size_t i=0; i<N; i++) {
3670 const String16& key = mBag.keyAt(i);
3671 Item& it = mBag.editValueAt(i);
3672 it.bagKeyId = table->getResId(key,
3673 it.isId ? &id16 : &attr16, NULL, &errorMsg);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003674 //printf("Bag key of %s: #%08x\n", String8(key).c_str(), it.bagKeyId);
Adam Lesinski282e1812014-01-23 18:17:42 -08003675 if (it.bagKeyId == 0) {
3676 it.sourcePos.error("Error: %s: %s '%s'.\n", errorMsg,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003677 String8(it.isId ? id16 : attr16).c_str(),
3678 String8(key).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003679 hasErrors = true;
3680 }
3681 }
3682 }
Andreas Gampe2412f842014-09-30 20:55:57 -07003683 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08003684}
3685
3686status_t ResourceTable::Entry::prepareFlatten(StringPool* strings, ResourceTable* table,
3687 const String8* configTypeName, const ConfigDescription* config)
3688{
3689 if (mType == TYPE_ITEM) {
3690 Item& it = mItem;
3691 AccessorCookie ac(it.sourcePos, String8(mName), String8(it.value));
3692 if (!table->stringToValue(&it.parsedValue, strings,
3693 it.value, false, true, 0,
3694 &it.style, NULL, &ac, mItemFormat,
3695 configTypeName, config)) {
3696 return UNKNOWN_ERROR;
3697 }
3698 } else if (mType == TYPE_BAG) {
3699 const size_t N = mBag.size();
3700 for (size_t i=0; i<N; i++) {
3701 const String16& key = mBag.keyAt(i);
3702 Item& it = mBag.editValueAt(i);
3703 AccessorCookie ac(it.sourcePos, String8(key), String8(it.value));
3704 if (!table->stringToValue(&it.parsedValue, strings,
3705 it.value, false, true, it.bagKeyId,
3706 &it.style, NULL, &ac, it.format,
3707 configTypeName, config)) {
3708 return UNKNOWN_ERROR;
3709 }
3710 }
3711 } else {
3712 mPos.error("Error: entry %s is not a single item or a bag.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003713 String8(mName).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003714 return UNKNOWN_ERROR;
3715 }
3716 return NO_ERROR;
3717}
3718
3719status_t ResourceTable::Entry::remapStringValue(StringPool* strings)
3720{
3721 if (mType == TYPE_ITEM) {
3722 Item& it = mItem;
3723 if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3724 it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3725 }
3726 } else if (mType == TYPE_BAG) {
3727 const size_t N = mBag.size();
3728 for (size_t i=0; i<N; i++) {
3729 Item& it = mBag.editValueAt(i);
3730 if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3731 it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3732 }
3733 }
3734 } else {
3735 mPos.error("Error: entry %s is not a single item or a bag.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003736 String8(mName).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003737 return UNKNOWN_ERROR;
3738 }
3739 return NO_ERROR;
3740}
3741
Andreas Gampe2412f842014-09-30 20:55:57 -07003742ssize_t ResourceTable::Entry::flatten(Bundle* /* bundle */, const sp<AaptFile>& data, bool isPublic)
Adam Lesinski282e1812014-01-23 18:17:42 -08003743{
3744 size_t amt = 0;
3745 ResTable_entry header;
3746 memset(&header, 0, sizeof(header));
3747 header.size = htods(sizeof(header));
Andreas Gampe2412f842014-09-30 20:55:57 -07003748 const type ty = mType;
3749 if (ty == TYPE_BAG) {
3750 header.flags |= htods(header.FLAG_COMPLEX);
Adam Lesinski282e1812014-01-23 18:17:42 -08003751 }
Andreas Gampe2412f842014-09-30 20:55:57 -07003752 if (isPublic) {
3753 header.flags |= htods(header.FLAG_PUBLIC);
3754 }
3755 header.key.index = htodl(mNameIndex);
Adam Lesinski282e1812014-01-23 18:17:42 -08003756 if (ty != TYPE_BAG) {
3757 status_t err = data->writeData(&header, sizeof(header));
3758 if (err != NO_ERROR) {
3759 fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3760 return err;
3761 }
3762
3763 const Item& it = mItem;
3764 Res_value par;
3765 memset(&par, 0, sizeof(par));
3766 par.size = htods(it.parsedValue.size);
3767 par.dataType = it.parsedValue.dataType;
3768 par.res0 = it.parsedValue.res0;
3769 par.data = htodl(it.parsedValue.data);
3770 #if 0
3771 printf("Writing item (%s): type=%d, data=0x%x, res0=0x%x\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003772 String8(mName).c_str(), it.parsedValue.dataType,
Adam Lesinski282e1812014-01-23 18:17:42 -08003773 it.parsedValue.data, par.res0);
3774 #endif
3775 err = data->writeData(&par, it.parsedValue.size);
3776 if (err != NO_ERROR) {
3777 fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3778 return err;
3779 }
3780 amt += it.parsedValue.size;
3781 } else {
3782 size_t N = mBag.size();
3783 size_t i;
3784 // Create correct ordering of items.
3785 KeyedVector<uint32_t, const Item*> items;
3786 for (i=0; i<N; i++) {
3787 const Item& it = mBag.valueAt(i);
3788 items.add(it.bagKeyId, &it);
3789 }
3790 N = items.size();
3791
3792 ResTable_map_entry mapHeader;
3793 memcpy(&mapHeader, &header, sizeof(header));
3794 mapHeader.size = htods(sizeof(mapHeader));
3795 mapHeader.parent.ident = htodl(mParentId);
3796 mapHeader.count = htodl(N);
3797 status_t err = data->writeData(&mapHeader, sizeof(mapHeader));
3798 if (err != NO_ERROR) {
3799 fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3800 return err;
3801 }
3802
3803 for (i=0; i<N; i++) {
3804 const Item& it = *items.valueAt(i);
3805 ResTable_map map;
3806 map.name.ident = htodl(it.bagKeyId);
3807 map.value.size = htods(it.parsedValue.size);
3808 map.value.dataType = it.parsedValue.dataType;
3809 map.value.res0 = it.parsedValue.res0;
3810 map.value.data = htodl(it.parsedValue.data);
3811 err = data->writeData(&map, sizeof(map));
3812 if (err != NO_ERROR) {
3813 fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3814 return err;
3815 }
3816 amt += sizeof(map);
3817 }
3818 }
3819 return amt;
3820}
3821
3822void ResourceTable::ConfigList::appendComment(const String16& comment,
3823 bool onlyIfEmpty)
3824{
3825 if (comment.size() <= 0) {
3826 return;
3827 }
3828 if (onlyIfEmpty && mComment.size() > 0) {
3829 return;
3830 }
3831 if (mComment.size() > 0) {
3832 mComment.append(String16("\n"));
3833 }
3834 mComment.append(comment);
3835}
3836
3837void ResourceTable::ConfigList::appendTypeComment(const String16& comment)
3838{
3839 if (comment.size() <= 0) {
3840 return;
3841 }
3842 if (mTypeComment.size() > 0) {
3843 mTypeComment.append(String16("\n"));
3844 }
3845 mTypeComment.append(comment);
3846}
3847
3848status_t ResourceTable::Type::addPublic(const SourcePos& sourcePos,
3849 const String16& name,
3850 const uint32_t ident)
3851{
3852 #if 0
3853 int32_t entryIdx = Res_GETENTRY(ident);
3854 if (entryIdx < 0) {
3855 sourcePos.error("Public resource %s/%s has an invalid 0 identifier (0x%08x).\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003856 String8(mName).c_str(), String8(name).c_str(), ident);
Adam Lesinski282e1812014-01-23 18:17:42 -08003857 return UNKNOWN_ERROR;
3858 }
3859 #endif
3860
3861 int32_t typeIdx = Res_GETTYPE(ident);
3862 if (typeIdx >= 0) {
3863 typeIdx++;
3864 if (mPublicIndex > 0 && mPublicIndex != typeIdx) {
3865 sourcePos.error("Public resource %s/%s has conflicting type codes for its"
3866 " public identifiers (0x%x vs 0x%x).\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003867 String8(mName).c_str(), String8(name).c_str(),
Adam Lesinski282e1812014-01-23 18:17:42 -08003868 mPublicIndex, typeIdx);
3869 return UNKNOWN_ERROR;
3870 }
3871 mPublicIndex = typeIdx;
3872 }
3873
3874 if (mFirstPublicSourcePos == NULL) {
3875 mFirstPublicSourcePos = new SourcePos(sourcePos);
3876 }
3877
3878 if (mPublic.indexOfKey(name) < 0) {
3879 mPublic.add(name, Public(sourcePos, String16(), ident));
3880 } else {
3881 Public& p = mPublic.editValueFor(name);
3882 if (p.ident != ident) {
3883 sourcePos.error("Public resource %s/%s has conflicting public identifiers"
3884 " (0x%08x vs 0x%08x).\n"
3885 "%s:%d: Originally defined here.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003886 String8(mName).c_str(), String8(name).c_str(), p.ident, ident,
3887 p.sourcePos.file.c_str(), p.sourcePos.line);
Adam Lesinski282e1812014-01-23 18:17:42 -08003888 return UNKNOWN_ERROR;
3889 }
3890 }
3891
3892 return NO_ERROR;
3893}
3894
3895void ResourceTable::Type::canAddEntry(const String16& name)
3896{
3897 mCanAddEntries.add(name);
3898}
3899
3900sp<ResourceTable::Entry> ResourceTable::Type::getEntry(const String16& entry,
3901 const SourcePos& sourcePos,
3902 const ResTable_config* config,
3903 bool doSetIndex,
3904 bool overlay,
3905 bool autoAddOverlay)
3906{
3907 int pos = -1;
3908 sp<ConfigList> c = mConfigs.valueFor(entry);
3909 if (c == NULL) {
3910 if (overlay && !autoAddOverlay && mCanAddEntries.indexOf(entry) < 0) {
3911 sourcePos.error("Resource at %s appears in overlay but not"
3912 " in the base package; use <add-resource> to add.\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003913 String8(entry).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08003914 return NULL;
3915 }
3916 c = new ConfigList(entry, sourcePos);
3917 mConfigs.add(entry, c);
3918 pos = (int)mOrderedConfigs.size();
3919 mOrderedConfigs.add(c);
3920 if (doSetIndex) {
3921 c->setEntryIndex(pos);
3922 }
3923 }
3924
3925 ConfigDescription cdesc;
3926 if (config) cdesc = *config;
3927
3928 sp<Entry> e = c->getEntries().valueFor(cdesc);
3929 if (e == NULL) {
Andreas Gampe2412f842014-09-30 20:55:57 -07003930 if (kIsDebug) {
3931 if (config != NULL) {
3932 printf("New entry at %s:%d: imsi:%d/%d lang:%c%c cnt:%c%c "
Adam Lesinski282e1812014-01-23 18:17:42 -08003933 "orien:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
Andreas Gampe2412f842014-09-30 20:55:57 -07003934 "sw%ddp w%ddp h%ddp layout:%d\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003935 sourcePos.file.c_str(), sourcePos.line,
Adam Lesinski282e1812014-01-23 18:17:42 -08003936 config->mcc, config->mnc,
3937 config->language[0] ? config->language[0] : '-',
3938 config->language[1] ? config->language[1] : '-',
3939 config->country[0] ? config->country[0] : '-',
3940 config->country[1] ? config->country[1] : '-',
3941 config->orientation,
3942 config->touchscreen,
3943 config->density,
3944 config->keyboard,
3945 config->inputFlags,
3946 config->navigation,
3947 config->screenWidth,
3948 config->screenHeight,
3949 config->smallestScreenWidthDp,
3950 config->screenWidthDp,
3951 config->screenHeightDp,
Andreas Gampe2412f842014-09-30 20:55:57 -07003952 config->screenLayout);
3953 } else {
3954 printf("New entry at %s:%d: NULL config\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00003955 sourcePos.file.c_str(), sourcePos.line);
Andreas Gampe2412f842014-09-30 20:55:57 -07003956 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003957 }
3958 e = new Entry(entry, sourcePos);
3959 c->addEntry(cdesc, e);
3960 /*
3961 if (doSetIndex) {
3962 if (pos < 0) {
3963 for (pos=0; pos<(int)mOrderedConfigs.size(); pos++) {
3964 if (mOrderedConfigs[pos] == c) {
3965 break;
3966 }
3967 }
3968 if (pos >= (int)mOrderedConfigs.size()) {
3969 sourcePos.error("Internal error: config not found in mOrderedConfigs when adding entry");
3970 return NULL;
3971 }
3972 }
3973 e->setEntryIndex(pos);
3974 }
3975 */
3976 }
3977
Adam Lesinski282e1812014-01-23 18:17:42 -08003978 return e;
3979}
3980
Adam Lesinski9b624c12014-11-19 17:49:26 -08003981sp<ResourceTable::ConfigList> ResourceTable::Type::removeEntry(const String16& entry) {
3982 ssize_t idx = mConfigs.indexOfKey(entry);
3983 if (idx < 0) {
3984 return NULL;
3985 }
3986
3987 sp<ConfigList> removed = mConfigs.valueAt(idx);
3988 mConfigs.removeItemsAt(idx);
3989
3990 Vector<sp<ConfigList> >::iterator iter = std::find(
3991 mOrderedConfigs.begin(), mOrderedConfigs.end(), removed);
3992 if (iter != mOrderedConfigs.end()) {
3993 mOrderedConfigs.erase(iter);
3994 }
3995
3996 mPublic.removeItem(entry);
3997 return removed;
3998}
3999
4000SortedVector<ConfigDescription> ResourceTable::Type::getUniqueConfigs() const {
4001 SortedVector<ConfigDescription> unique;
4002 const size_t entryCount = mOrderedConfigs.size();
4003 for (size_t i = 0; i < entryCount; i++) {
4004 if (mOrderedConfigs[i] == NULL) {
4005 continue;
4006 }
4007 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& configs =
4008 mOrderedConfigs[i]->getEntries();
4009 const size_t configCount = configs.size();
4010 for (size_t j = 0; j < configCount; j++) {
4011 unique.add(configs.keyAt(j));
4012 }
4013 }
4014 return unique;
4015}
4016
Adam Lesinski282e1812014-01-23 18:17:42 -08004017status_t ResourceTable::Type::applyPublicEntryOrder()
4018{
4019 size_t N = mOrderedConfigs.size();
4020 Vector<sp<ConfigList> > origOrder(mOrderedConfigs);
4021 bool hasError = false;
4022
4023 size_t i;
4024 for (i=0; i<N; i++) {
4025 mOrderedConfigs.replaceAt(NULL, i);
4026 }
4027
4028 const size_t NP = mPublic.size();
4029 //printf("Ordering %d configs from %d public defs\n", N, NP);
4030 size_t j;
4031 for (j=0; j<NP; j++) {
4032 const String16& name = mPublic.keyAt(j);
4033 const Public& p = mPublic.valueAt(j);
4034 int32_t idx = Res_GETENTRY(p.ident);
4035 //printf("Looking for entry \"%s\"/\"%s\" (0x%08x) in %d...\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004036 // String8(mName).c_str(), String8(name).c_str(), p.ident, N);
Adam Lesinski282e1812014-01-23 18:17:42 -08004037 bool found = false;
4038 for (i=0; i<N; i++) {
4039 sp<ConfigList> e = origOrder.itemAt(i);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004040 //printf("#%d: \"%s\"\n", i, String8(e->getName()).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08004041 if (e->getName() == name) {
4042 if (idx >= (int32_t)mOrderedConfigs.size()) {
Adam Lesinski9b624c12014-11-19 17:49:26 -08004043 mOrderedConfigs.resize(idx + 1);
4044 }
4045
4046 if (mOrderedConfigs.itemAt(idx) == NULL) {
Adam Lesinski282e1812014-01-23 18:17:42 -08004047 e->setPublic(true);
4048 e->setPublicSourcePos(p.sourcePos);
4049 mOrderedConfigs.replaceAt(e, idx);
4050 origOrder.removeAt(i);
4051 N--;
4052 found = true;
4053 break;
4054 } else {
4055 sp<ConfigList> oe = mOrderedConfigs.itemAt(idx);
4056
4057 p.sourcePos.error("Multiple entry names declared for public entry"
4058 " identifier 0x%x in type %s (%s vs %s).\n"
4059 "%s:%d: Originally defined here.",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004060 idx+1, String8(mName).c_str(),
4061 String8(oe->getName()).c_str(),
4062 String8(name).c_str(),
4063 oe->getPublicSourcePos().file.c_str(),
Adam Lesinski282e1812014-01-23 18:17:42 -08004064 oe->getPublicSourcePos().line);
4065 hasError = true;
4066 }
4067 }
4068 }
4069
4070 if (!found) {
4071 p.sourcePos.error("Public symbol %s/%s declared here is not defined.",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004072 String8(mName).c_str(), String8(name).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08004073 hasError = true;
4074 }
4075 }
4076
4077 //printf("Copying back in %d non-public configs, have %d\n", N, origOrder.size());
4078
4079 if (N != origOrder.size()) {
4080 printf("Internal error: remaining private symbol count mismatch\n");
4081 N = origOrder.size();
4082 }
4083
4084 j = 0;
4085 for (i=0; i<N; i++) {
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -07004086 const sp<ConfigList>& e = origOrder.itemAt(i);
Adam Lesinski282e1812014-01-23 18:17:42 -08004087 // There will always be enough room for the remaining entries.
4088 while (mOrderedConfigs.itemAt(j) != NULL) {
4089 j++;
4090 }
4091 mOrderedConfigs.replaceAt(e, j);
4092 j++;
4093 }
4094
Andreas Gampe2412f842014-09-30 20:55:57 -07004095 return hasError ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08004096}
4097
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004098ResourceTable::Package::Package(const String16& name, size_t packageId)
4099 : mName(name), mPackageId(packageId),
Adam Lesinski282e1812014-01-23 18:17:42 -08004100 mTypeStringsMapping(0xffffffff),
4101 mKeyStringsMapping(0xffffffff)
4102{
4103}
4104
4105sp<ResourceTable::Type> ResourceTable::Package::getType(const String16& type,
4106 const SourcePos& sourcePos,
4107 bool doSetIndex)
4108{
4109 sp<Type> t = mTypes.valueFor(type);
4110 if (t == NULL) {
4111 t = new Type(type, sourcePos);
4112 mTypes.add(type, t);
4113 mOrderedTypes.add(t);
4114 if (doSetIndex) {
4115 // For some reason the type's index is set to one plus the index
4116 // in the mOrderedTypes list, rather than just the index.
4117 t->setIndex(mOrderedTypes.size());
4118 }
4119 }
4120 return t;
4121}
4122
4123status_t ResourceTable::Package::setTypeStrings(const sp<AaptFile>& data)
4124{
Adam Lesinski282e1812014-01-23 18:17:42 -08004125 status_t err = setStrings(data, &mTypeStrings, &mTypeStringsMapping);
4126 if (err != NO_ERROR) {
4127 fprintf(stderr, "ERROR: Type string data is corrupt!\n");
Adam Lesinski57079512014-07-29 11:51:35 -07004128 return err;
Adam Lesinski282e1812014-01-23 18:17:42 -08004129 }
Adam Lesinski57079512014-07-29 11:51:35 -07004130
4131 // Retain a reference to the new data after we've successfully replaced
4132 // all uses of the old reference (in setStrings() ).
4133 mTypeStringsData = data;
4134 return NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08004135}
4136
4137status_t ResourceTable::Package::setKeyStrings(const sp<AaptFile>& data)
4138{
Adam Lesinski282e1812014-01-23 18:17:42 -08004139 status_t err = setStrings(data, &mKeyStrings, &mKeyStringsMapping);
4140 if (err != NO_ERROR) {
4141 fprintf(stderr, "ERROR: Key string data is corrupt!\n");
Adam Lesinski57079512014-07-29 11:51:35 -07004142 return err;
Adam Lesinski282e1812014-01-23 18:17:42 -08004143 }
Adam Lesinski57079512014-07-29 11:51:35 -07004144
4145 // Retain a reference to the new data after we've successfully replaced
4146 // all uses of the old reference (in setStrings() ).
4147 mKeyStringsData = data;
4148 return NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08004149}
4150
4151status_t ResourceTable::Package::setStrings(const sp<AaptFile>& data,
4152 ResStringPool* strings,
4153 DefaultKeyedVector<String16, uint32_t>* mappings)
4154{
4155 if (data->getData() == NULL) {
4156 return UNKNOWN_ERROR;
4157 }
4158
Adam Lesinski282e1812014-01-23 18:17:42 -08004159 status_t err = strings->setTo(data->getData(), data->getSize());
4160 if (err == NO_ERROR) {
4161 const size_t N = strings->size();
4162 for (size_t i=0; i<N; i++) {
4163 size_t len;
Ryan Mitchell80094e32020-11-16 23:08:18 +00004164 mappings->add(String16(UnpackOptionalString(strings->stringAt(i), &len)), i);
Adam Lesinski282e1812014-01-23 18:17:42 -08004165 }
4166 }
4167 return err;
4168}
4169
4170status_t ResourceTable::Package::applyPublicTypeOrder()
4171{
4172 size_t N = mOrderedTypes.size();
4173 Vector<sp<Type> > origOrder(mOrderedTypes);
4174
4175 size_t i;
4176 for (i=0; i<N; i++) {
4177 mOrderedTypes.replaceAt(NULL, i);
4178 }
4179
4180 for (i=0; i<N; i++) {
4181 sp<Type> t = origOrder.itemAt(i);
4182 int32_t idx = t->getPublicIndex();
4183 if (idx > 0) {
4184 idx--;
4185 while (idx >= (int32_t)mOrderedTypes.size()) {
4186 mOrderedTypes.add();
4187 }
4188 if (mOrderedTypes.itemAt(idx) != NULL) {
4189 sp<Type> ot = mOrderedTypes.itemAt(idx);
4190 t->getFirstPublicSourcePos().error("Multiple type names declared for public type"
4191 " identifier 0x%x (%s vs %s).\n"
4192 "%s:%d: Originally defined here.",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004193 idx, String8(ot->getName()).c_str(),
4194 String8(t->getName()).c_str(),
4195 ot->getFirstPublicSourcePos().file.c_str(),
Adam Lesinski282e1812014-01-23 18:17:42 -08004196 ot->getFirstPublicSourcePos().line);
4197 return UNKNOWN_ERROR;
4198 }
4199 mOrderedTypes.replaceAt(t, idx);
4200 origOrder.removeAt(i);
4201 i--;
4202 N--;
4203 }
4204 }
4205
4206 size_t j=0;
4207 for (i=0; i<N; i++) {
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -07004208 const sp<Type>& t = origOrder.itemAt(i);
Adam Lesinski282e1812014-01-23 18:17:42 -08004209 // There will always be enough room for the remaining types.
4210 while (mOrderedTypes.itemAt(j) != NULL) {
4211 j++;
4212 }
4213 mOrderedTypes.replaceAt(t, j);
4214 }
4215
4216 return NO_ERROR;
4217}
4218
Adam Lesinski9b624c12014-11-19 17:49:26 -08004219void ResourceTable::Package::movePrivateAttrs() {
4220 sp<Type> attr = mTypes.valueFor(String16("attr"));
4221 if (attr == NULL) {
4222 // Nothing to do.
4223 return;
4224 }
4225
4226 Vector<sp<ConfigList> > privateAttrs;
4227
4228 bool hasPublic = false;
4229 const Vector<sp<ConfigList> >& configs = attr->getOrderedConfigs();
4230 const size_t configCount = configs.size();
4231 for (size_t i = 0; i < configCount; i++) {
4232 if (configs[i] == NULL) {
4233 continue;
4234 }
4235
4236 if (attr->isPublic(configs[i]->getName())) {
4237 hasPublic = true;
4238 } else {
4239 privateAttrs.add(configs[i]);
4240 }
4241 }
4242
4243 // Only if we have public attributes do we create a separate type for
4244 // private attributes.
4245 if (!hasPublic) {
4246 return;
4247 }
4248
4249 // Create a new type for private attributes.
4250 sp<Type> privateAttrType = getType(String16(kAttrPrivateType), SourcePos());
4251
4252 const size_t privateAttrCount = privateAttrs.size();
4253 for (size_t i = 0; i < privateAttrCount; i++) {
4254 const sp<ConfigList>& cl = privateAttrs[i];
4255
4256 // Remove the private attributes from their current type.
4257 attr->removeEntry(cl->getName());
4258
4259 // Add it to the new type.
4260 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& entries = cl->getEntries();
4261 const size_t entryCount = entries.size();
4262 for (size_t j = 0; j < entryCount; j++) {
4263 const sp<Entry>& oldEntry = entries[j];
4264 sp<Entry> entry = privateAttrType->getEntry(
4265 cl->getName(), oldEntry->getPos(), &entries.keyAt(j));
4266 *entry = *oldEntry;
4267 }
4268
4269 // Move the symbols to the new type.
4270
4271 }
4272}
4273
Adam Lesinski282e1812014-01-23 18:17:42 -08004274sp<ResourceTable::Package> ResourceTable::getPackage(const String16& package)
4275{
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004276 if (package != mAssetsPackage) {
4277 return NULL;
Adam Lesinski282e1812014-01-23 18:17:42 -08004278 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004279 return mPackages.valueFor(package);
Adam Lesinski282e1812014-01-23 18:17:42 -08004280}
4281
4282sp<ResourceTable::Type> ResourceTable::getType(const String16& package,
4283 const String16& type,
4284 const SourcePos& sourcePos,
4285 bool doSetIndex)
4286{
4287 sp<Package> p = getPackage(package);
4288 if (p == NULL) {
4289 return NULL;
4290 }
4291 return p->getType(type, sourcePos, doSetIndex);
4292}
4293
4294sp<ResourceTable::Entry> ResourceTable::getEntry(const String16& package,
4295 const String16& type,
4296 const String16& name,
4297 const SourcePos& sourcePos,
4298 bool overlay,
4299 const ResTable_config* config,
4300 bool doSetIndex)
4301{
4302 sp<Type> t = getType(package, type, sourcePos, doSetIndex);
4303 if (t == NULL) {
4304 return NULL;
4305 }
4306 return t->getEntry(name, sourcePos, config, doSetIndex, overlay, mBundle->getAutoAddOverlay());
4307}
4308
Adam Lesinskie572c012014-09-19 15:10:04 -07004309sp<ResourceTable::ConfigList> ResourceTable::getConfigList(const String16& package,
4310 const String16& type, const String16& name) const
4311{
4312 const size_t packageCount = mOrderedPackages.size();
4313 for (size_t pi = 0; pi < packageCount; pi++) {
4314 const sp<Package>& p = mOrderedPackages[pi];
4315 if (p == NULL || p->getName() != package) {
4316 continue;
4317 }
4318
4319 const Vector<sp<Type> >& types = p->getOrderedTypes();
4320 const size_t typeCount = types.size();
4321 for (size_t ti = 0; ti < typeCount; ti++) {
4322 const sp<Type>& t = types[ti];
4323 if (t == NULL || t->getName() != type) {
4324 continue;
4325 }
4326
4327 const Vector<sp<ConfigList> >& configs = t->getOrderedConfigs();
4328 const size_t configCount = configs.size();
4329 for (size_t ci = 0; ci < configCount; ci++) {
4330 const sp<ConfigList>& cl = configs[ci];
4331 if (cl == NULL || cl->getName() != name) {
4332 continue;
4333 }
4334
4335 return cl;
4336 }
4337 }
4338 }
4339 return NULL;
4340}
4341
Adam Lesinski282e1812014-01-23 18:17:42 -08004342sp<const ResourceTable::Entry> ResourceTable::getEntry(uint32_t resID,
4343 const ResTable_config* config) const
4344{
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004345 size_t pid = Res_GETPACKAGE(resID)+1;
Adam Lesinski282e1812014-01-23 18:17:42 -08004346 const size_t N = mOrderedPackages.size();
Adam Lesinski282e1812014-01-23 18:17:42 -08004347 sp<Package> p;
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004348 for (size_t i = 0; i < N; i++) {
Adam Lesinski282e1812014-01-23 18:17:42 -08004349 sp<Package> check = mOrderedPackages[i];
4350 if (check->getAssignedId() == pid) {
4351 p = check;
4352 break;
4353 }
4354
4355 }
4356 if (p == NULL) {
4357 fprintf(stderr, "warning: Package not found for resource #%08x\n", resID);
4358 return NULL;
4359 }
4360
4361 int tid = Res_GETTYPE(resID);
4362 if (tid < 0 || tid >= (int)p->getOrderedTypes().size()) {
4363 fprintf(stderr, "warning: Type not found for resource #%08x\n", resID);
4364 return NULL;
4365 }
4366 sp<Type> t = p->getOrderedTypes()[tid];
4367
4368 int eid = Res_GETENTRY(resID);
4369 if (eid < 0 || eid >= (int)t->getOrderedConfigs().size()) {
4370 fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
4371 return NULL;
4372 }
4373
4374 sp<ConfigList> c = t->getOrderedConfigs()[eid];
4375 if (c == NULL) {
4376 fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
4377 return NULL;
4378 }
4379
4380 ConfigDescription cdesc;
4381 if (config) cdesc = *config;
4382 sp<Entry> e = c->getEntries().valueFor(cdesc);
4383 if (c == NULL) {
4384 fprintf(stderr, "warning: Entry configuration not found for resource #%08x\n", resID);
4385 return NULL;
4386 }
4387
4388 return e;
4389}
4390
4391const ResourceTable::Item* ResourceTable::getItem(uint32_t resID, uint32_t attrID) const
4392{
4393 sp<const Entry> e = getEntry(resID);
4394 if (e == NULL) {
4395 return NULL;
4396 }
4397
4398 const size_t N = e->getBag().size();
4399 for (size_t i=0; i<N; i++) {
4400 const Item& it = e->getBag().valueAt(i);
4401 if (it.bagKeyId == 0) {
4402 fprintf(stderr, "warning: ID not yet assigned to '%s' in bag '%s'\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004403 String8(e->getName()).c_str(),
4404 String8(e->getBag().keyAt(i)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08004405 }
4406 if (it.bagKeyId == attrID) {
4407 return &it;
4408 }
4409 }
4410
4411 return NULL;
4412}
4413
4414bool ResourceTable::getItemValue(
4415 uint32_t resID, uint32_t attrID, Res_value* outValue)
4416{
4417 const Item* item = getItem(resID, attrID);
4418
4419 bool res = false;
4420 if (item != NULL) {
4421 if (item->evaluating) {
4422 sp<const Entry> e = getEntry(resID);
4423 const size_t N = e->getBag().size();
4424 size_t i;
4425 for (i=0; i<N; i++) {
4426 if (&e->getBag().valueAt(i) == item) {
4427 break;
4428 }
4429 }
4430 fprintf(stderr, "warning: Circular reference detected in key '%s' of bag '%s'\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004431 String8(e->getName()).c_str(),
4432 String8(e->getBag().keyAt(i)).c_str());
Adam Lesinski282e1812014-01-23 18:17:42 -08004433 return false;
4434 }
4435 item->evaluating = true;
4436 res = stringToValue(outValue, NULL, item->value, false, false, item->bagKeyId);
Andreas Gampe2412f842014-09-30 20:55:57 -07004437 if (kIsDebug) {
Adam Lesinski282e1812014-01-23 18:17:42 -08004438 if (res) {
4439 printf("getItemValue of #%08x[#%08x] (%s): type=#%08x, data=#%08x\n",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004440 resID, attrID, String8(getEntry(resID)->getName()).c_str(),
Adam Lesinski282e1812014-01-23 18:17:42 -08004441 outValue->dataType, outValue->data);
4442 } else {
4443 printf("getItemValue of #%08x[#%08x]: failed\n",
4444 resID, attrID);
4445 }
Andreas Gampe2412f842014-09-30 20:55:57 -07004446 }
Adam Lesinski282e1812014-01-23 18:17:42 -08004447 item->evaluating = false;
4448 }
4449 return res;
4450}
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004451
4452/**
Adam Lesinski28994d82015-01-13 13:42:41 -08004453 * Returns the SDK version at which the attribute was
4454 * made public, or -1 if the resource ID is not an attribute
4455 * or is not public.
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004456 */
Adam Lesinski28994d82015-01-13 13:42:41 -08004457int ResourceTable::getPublicAttributeSdkLevel(uint32_t attrId) const {
4458 if (Res_GETPACKAGE(attrId) + 1 != 0x01 || Res_GETTYPE(attrId) + 1 != 0x01) {
4459 return -1;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004460 }
4461
4462 uint32_t specFlags;
4463 if (!mAssets->getIncludedResources().getResourceFlags(attrId, &specFlags)) {
Adam Lesinski28994d82015-01-13 13:42:41 -08004464 return -1;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004465 }
4466
Adam Lesinski28994d82015-01-13 13:42:41 -08004467 if ((specFlags & ResTable_typeSpec::SPEC_PUBLIC) == 0) {
4468 return -1;
4469 }
4470
4471 const size_t entryId = Res_GETENTRY(attrId);
4472 if (entryId <= 0x021c) {
4473 return 1;
4474 } else if (entryId <= 0x021d) {
4475 return 2;
4476 } else if (entryId <= 0x0269) {
4477 return SDK_CUPCAKE;
4478 } else if (entryId <= 0x028d) {
4479 return SDK_DONUT;
4480 } else if (entryId <= 0x02ad) {
4481 return SDK_ECLAIR;
4482 } else if (entryId <= 0x02b3) {
4483 return SDK_ECLAIR_0_1;
4484 } else if (entryId <= 0x02b5) {
4485 return SDK_ECLAIR_MR1;
4486 } else if (entryId <= 0x02bd) {
4487 return SDK_FROYO;
4488 } else if (entryId <= 0x02cb) {
4489 return SDK_GINGERBREAD;
4490 } else if (entryId <= 0x0361) {
4491 return SDK_HONEYCOMB;
4492 } else if (entryId <= 0x0366) {
4493 return SDK_HONEYCOMB_MR1;
4494 } else if (entryId <= 0x03a6) {
4495 return SDK_HONEYCOMB_MR2;
4496 } else if (entryId <= 0x03ae) {
4497 return SDK_JELLY_BEAN;
4498 } else if (entryId <= 0x03cc) {
4499 return SDK_JELLY_BEAN_MR1;
4500 } else if (entryId <= 0x03da) {
4501 return SDK_JELLY_BEAN_MR2;
4502 } else if (entryId <= 0x03f1) {
4503 return SDK_KITKAT;
4504 } else if (entryId <= 0x03f6) {
4505 return SDK_KITKAT_WATCH;
4506 } else if (entryId <= 0x04ce) {
4507 return SDK_LOLLIPOP;
4508 } else {
4509 // Anything else is marked as defined in
4510 // SDK_LOLLIPOP_MR1 since after this
4511 // version no attribute compat work
4512 // needs to be done.
4513 return SDK_LOLLIPOP_MR1;
4514 }
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004515}
4516
Adam Lesinski28994d82015-01-13 13:42:41 -08004517/**
4518 * First check the Manifest, then check the command line flag.
4519 */
4520static int getMinSdkVersion(const Bundle* bundle) {
4521 if (bundle->getManifestMinSdkVersion() != NULL && strlen(bundle->getManifestMinSdkVersion()) > 0) {
4522 return atoi(bundle->getManifestMinSdkVersion());
4523 } else if (bundle->getMinSdkVersion() != NULL && strlen(bundle->getMinSdkVersion()) > 0) {
4524 return atoi(bundle->getMinSdkVersion());
Adam Lesinskie572c012014-09-19 15:10:04 -07004525 }
Adam Lesinski28994d82015-01-13 13:42:41 -08004526 return 0;
Adam Lesinskie572c012014-09-19 15:10:04 -07004527}
4528
Adam Lesinskibeb9e332015-08-14 13:16:18 -07004529bool ResourceTable::shouldGenerateVersionedResource(
4530 const sp<ResourceTable::ConfigList>& configList,
4531 const ConfigDescription& sourceConfig,
4532 const int sdkVersionToGenerate) {
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004533 assert(sdkVersionToGenerate > sourceConfig.sdkVersion);
Adam Lesinski526d73b2016-07-18 17:01:14 -07004534 assert(configList != NULL);
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004535 const DefaultKeyedVector<ConfigDescription, sp<ResourceTable::Entry>>& entries
4536 = configList->getEntries();
4537 ssize_t idx = entries.indexOfKey(sourceConfig);
4538
4539 // The source config came from this list, so it should be here.
4540 assert(idx >= 0);
4541
Adam Lesinskibeb9e332015-08-14 13:16:18 -07004542 // The next configuration either only varies in sdkVersion, or it is completely different
4543 // and therefore incompatible. If it is incompatible, we must generate the versioned resource.
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004544
Adam Lesinskibeb9e332015-08-14 13:16:18 -07004545 // NOTE: The ordering of configurations takes sdkVersion as higher precedence than other
4546 // qualifiers, so we need to iterate through the entire list to be sure there
4547 // are no higher sdk level versions of this resource.
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004548 ConfigDescription tempConfig(sourceConfig);
Adam Lesinskibeb9e332015-08-14 13:16:18 -07004549 for (size_t i = static_cast<size_t>(idx) + 1; i < entries.size(); i++) {
4550 const ConfigDescription& nextConfig = entries.keyAt(i);
4551 tempConfig.sdkVersion = nextConfig.sdkVersion;
4552 if (tempConfig == nextConfig) {
4553 // The two configs are the same, check the sdk version.
4554 return sdkVersionToGenerate < nextConfig.sdkVersion;
4555 }
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004556 }
Adam Lesinskibeb9e332015-08-14 13:16:18 -07004557
4558 // No match was found, so we should generate the versioned resource.
4559 return true;
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004560}
4561
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004562/**
4563 * Modifies the entries in the resource table to account for compatibility
4564 * issues with older versions of Android.
4565 *
4566 * This primarily handles the issue of private/public attribute clashes
4567 * in framework resources.
4568 *
4569 * AAPT has traditionally assigned resource IDs to public attributes,
4570 * and then followed those public definitions with private attributes.
4571 *
4572 * --- PUBLIC ---
4573 * | 0x01010234 | attr/color
4574 * | 0x01010235 | attr/background
4575 *
4576 * --- PRIVATE ---
4577 * | 0x01010236 | attr/secret
4578 * | 0x01010237 | attr/shhh
4579 *
4580 * Each release, when attributes are added, they take the place of the private
4581 * attributes and the private attributes are shifted down again.
4582 *
4583 * --- PUBLIC ---
4584 * | 0x01010234 | attr/color
4585 * | 0x01010235 | attr/background
4586 * | 0x01010236 | attr/shinyNewAttr
4587 * | 0x01010237 | attr/highlyValuedFeature
4588 *
4589 * --- PRIVATE ---
4590 * | 0x01010238 | attr/secret
4591 * | 0x01010239 | attr/shhh
4592 *
4593 * Platform code may look for private attributes set in a theme. If an app
4594 * compiled against a newer version of the platform uses a new public
4595 * attribute that happens to have the same ID as the private attribute
4596 * the older platform is expecting, then the behavior is undefined.
4597 *
4598 * We get around this by detecting any newly defined attributes (in L),
4599 * copy the resource into a -v21 qualified resource, and delete the
4600 * attribute from the original resource. This ensures that older platforms
4601 * don't see the new attribute, but when running on L+ platforms, the
4602 * attribute will be respected.
4603 */
4604status_t ResourceTable::modifyForCompat(const Bundle* bundle) {
Adam Lesinski28994d82015-01-13 13:42:41 -08004605 const int minSdk = getMinSdkVersion(bundle);
4606 if (minSdk >= SDK_LOLLIPOP_MR1) {
4607 // Lollipop MR1 and up handles public attributes differently, no
4608 // need to do any compat modifications.
Adam Lesinskie572c012014-09-19 15:10:04 -07004609 return NO_ERROR;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004610 }
4611
4612 const String16 attr16("attr");
4613
4614 const size_t packageCount = mOrderedPackages.size();
4615 for (size_t pi = 0; pi < packageCount; pi++) {
4616 sp<Package> p = mOrderedPackages.itemAt(pi);
4617 if (p == NULL || p->getTypes().size() == 0) {
4618 // Empty, skip!
4619 continue;
4620 }
4621
4622 const size_t typeCount = p->getOrderedTypes().size();
4623 for (size_t ti = 0; ti < typeCount; ti++) {
4624 sp<Type> t = p->getOrderedTypes().itemAt(ti);
4625 if (t == NULL) {
4626 continue;
4627 }
4628
4629 const size_t configCount = t->getOrderedConfigs().size();
4630 for (size_t ci = 0; ci < configCount; ci++) {
4631 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
4632 if (c == NULL) {
4633 continue;
4634 }
4635
4636 Vector<key_value_pair_t<ConfigDescription, sp<Entry> > > entriesToAdd;
4637 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& entries =
4638 c->getEntries();
4639 const size_t entryCount = entries.size();
4640 for (size_t ei = 0; ei < entryCount; ei++) {
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -07004641 const sp<Entry>& e = entries.valueAt(ei);
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004642 if (e == NULL || e->getType() != Entry::TYPE_BAG) {
4643 continue;
4644 }
4645
4646 const ConfigDescription& config = entries.keyAt(ei);
Adam Lesinski28994d82015-01-13 13:42:41 -08004647 if (config.sdkVersion >= SDK_LOLLIPOP_MR1) {
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004648 continue;
4649 }
4650
Adam Lesinski28994d82015-01-13 13:42:41 -08004651 KeyedVector<int, Vector<String16> > attributesToRemove;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004652 const KeyedVector<String16, Item>& bag = e->getBag();
4653 const size_t bagCount = bag.size();
4654 for (size_t bi = 0; bi < bagCount; bi++) {
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004655 const uint32_t attrId = getResId(bag.keyAt(bi), &attr16);
Adam Lesinski28994d82015-01-13 13:42:41 -08004656 const int sdkLevel = getPublicAttributeSdkLevel(attrId);
4657 if (sdkLevel > 1 && sdkLevel > config.sdkVersion && sdkLevel > minSdk) {
4658 AaptUtil::appendValue(attributesToRemove, sdkLevel, bag.keyAt(bi));
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004659 }
4660 }
4661
4662 if (attributesToRemove.isEmpty()) {
4663 continue;
4664 }
4665
Adam Lesinski28994d82015-01-13 13:42:41 -08004666 const size_t sdkCount = attributesToRemove.size();
4667 for (size_t i = 0; i < sdkCount; i++) {
4668 const int sdkLevel = attributesToRemove.keyAt(i);
4669
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004670 if (!shouldGenerateVersionedResource(c, config, sdkLevel)) {
4671 // There is a style that will override this generated one.
4672 continue;
4673 }
4674
Adam Lesinski28994d82015-01-13 13:42:41 -08004675 // Duplicate the entry under the same configuration
4676 // but with sdkVersion == sdkLevel.
4677 ConfigDescription newConfig(config);
4678 newConfig.sdkVersion = sdkLevel;
4679
4680 sp<Entry> newEntry = new Entry(*e);
4681
4682 // Remove all items that have a higher SDK level than
4683 // the one we are synthesizing.
4684 for (size_t j = 0; j < sdkCount; j++) {
4685 if (j == i) {
4686 continue;
4687 }
4688
4689 if (attributesToRemove.keyAt(j) > sdkLevel) {
4690 const size_t attrCount = attributesToRemove[j].size();
4691 for (size_t k = 0; k < attrCount; k++) {
4692 newEntry->removeFromBag(attributesToRemove[j][k]);
4693 }
4694 }
4695 }
4696
4697 entriesToAdd.add(key_value_pair_t<ConfigDescription, sp<Entry> >(
4698 newConfig, newEntry));
4699 }
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004700
4701 // Remove the attribute from the original.
4702 for (size_t i = 0; i < attributesToRemove.size(); i++) {
Adam Lesinski28994d82015-01-13 13:42:41 -08004703 for (size_t j = 0; j < attributesToRemove[i].size(); j++) {
4704 e->removeFromBag(attributesToRemove[i][j]);
4705 }
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004706 }
4707 }
4708
4709 const size_t entriesToAddCount = entriesToAdd.size();
4710 for (size_t i = 0; i < entriesToAddCount; i++) {
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004711 assert(entries.indexOfKey(entriesToAdd[i].key) < 0);
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004712
Adam Lesinskif15de2e2014-10-03 14:57:28 -07004713 if (bundle->getVerbose()) {
4714 entriesToAdd[i].value->getPos()
4715 .printf("using v%d attributes; synthesizing resource %s:%s/%s for configuration %s.",
Adam Lesinski28994d82015-01-13 13:42:41 -08004716 entriesToAdd[i].key.sdkVersion,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004717 String8(p->getName()).c_str(),
4718 String8(t->getName()).c_str(),
4719 String8(entriesToAdd[i].value->getName()).c_str(),
4720 entriesToAdd[i].key.toString().c_str());
Adam Lesinskif15de2e2014-10-03 14:57:28 -07004721 }
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004722
Adam Lesinski978ab9d2014-09-24 19:02:52 -07004723 sp<Entry> newEntry = t->getEntry(c->getName(),
4724 entriesToAdd[i].value->getPos(),
4725 &entriesToAdd[i].key);
4726
4727 *newEntry = *entriesToAdd[i].value;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004728 }
4729 }
4730 }
4731 }
4732 return NO_ERROR;
4733}
Adam Lesinskie572c012014-09-19 15:10:04 -07004734
Yuichi Araki4d35cca2017-01-18 20:42:17 +09004735const String16 kTransitionElements[] = {
4736 String16("fade"),
4737 String16("changeBounds"),
4738 String16("slide"),
4739 String16("explode"),
4740 String16("changeImageTransform"),
4741 String16("changeTransform"),
4742 String16("changeClipBounds"),
4743 String16("autoTransition"),
4744 String16("recolor"),
4745 String16("changeScroll"),
4746 String16("transitionSet"),
4747 String16("transition"),
4748 String16("transitionManager"),
4749};
4750
4751static bool IsTransitionElement(const String16& name) {
4752 for (int i = 0, size = sizeof(kTransitionElements) / sizeof(kTransitionElements[0]);
4753 i < size; ++i) {
4754 if (name == kTransitionElements[i]) {
4755 return true;
4756 }
4757 }
4758 return false;
4759}
4760
Adam Lesinskicf1f1d92017-03-16 16:54:23 -07004761bool ResourceTable::versionForCompat(const Bundle* bundle, const String16& resourceName,
4762 const sp<AaptFile>& target, const sp<XMLNode>& root) {
4763 XMLNode* node = root.get();
4764 while (node->getType() != XMLNode::TYPE_ELEMENT) {
4765 // We're assuming the root element is what we're looking for, which can only be under a
4766 // bunch of namespace declarations.
4767 if (node->getChildren().size() != 1) {
4768 // Not sure what to do, bail.
4769 return false;
4770 }
4771 node = node->getChildren().itemAt(0).get();
4772 }
4773
4774 if (node->getElementNamespace().size() != 0) {
4775 // Not something we care about.
4776 return false;
4777 }
4778
4779 int versionedSdk = 0;
4780 if (node->getElementName() == String16("adaptive-icon")) {
4781 versionedSdk = SDK_O;
4782 }
4783
4784 const int minSdkVersion = getMinSdkVersion(bundle);
4785 const ConfigDescription config(target->getGroupEntry().toParams());
4786 if (versionedSdk <= minSdkVersion || versionedSdk <= config.sdkVersion) {
4787 return false;
4788 }
4789
4790 sp<ConfigList> cl = getConfigList(String16(mAssets->getPackage()),
4791 String16(target->getResourceType()), resourceName);
4792 if (!shouldGenerateVersionedResource(cl, config, versionedSdk)) {
4793 return false;
4794 }
4795
4796 // Remove the original entry.
4797 cl->removeEntry(config);
4798
4799 // We need to wholesale version this file.
4800 ConfigDescription newConfig(config);
4801 newConfig.sdkVersion = versionedSdk;
4802 sp<AaptFile> newFile = new AaptFile(target->getSourceFile(),
4803 AaptGroupEntry(newConfig), target->getResourceType());
4804 String8 resPath = String8::format("res/%s/%s.xml",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004805 newFile->getGroupEntry().toDirName(target->getResourceType()).c_str(),
4806 String8(resourceName).c_str());
Elliott Hughes338698e2021-07-13 17:15:19 -07004807 convertToResPath(resPath);
Adam Lesinskicf1f1d92017-03-16 16:54:23 -07004808
4809 // Add a resource table entry.
4810 addEntry(SourcePos(),
4811 String16(mAssets->getPackage()),
4812 String16(target->getResourceType()),
4813 resourceName,
4814 String16(resPath),
4815 NULL,
4816 &newConfig);
4817
4818 // Schedule this to be compiled.
4819 CompileResourceWorkItem item;
4820 item.resourceName = resourceName;
4821 item.resPath = resPath;
4822 item.file = newFile;
4823 item.xmlRoot = root->clone();
Adam Lesinski54b58ba2017-04-14 18:44:30 -07004824 item.needsCompiling = true;
Adam Lesinskicf1f1d92017-03-16 16:54:23 -07004825 mWorkQueue.push(item);
4826
4827 // Now mark the old entry as deleted.
4828 return true;
4829}
4830
Adam Lesinskie572c012014-09-19 15:10:04 -07004831status_t ResourceTable::modifyForCompat(const Bundle* bundle,
4832 const String16& resourceName,
4833 const sp<AaptFile>& target,
4834 const sp<XMLNode>& root) {
Adam Lesinski6e460562015-04-21 14:20:15 -07004835 const String16 vector16("vector");
4836 const String16 animatedVector16("animated-vector");
ztenghui010df882017-03-07 15:50:03 -08004837 const String16 pathInterpolator16("pathInterpolator");
ztenghui20554852017-03-21 16:28:57 -07004838 const String16 objectAnimator16("objectAnimator");
ztenghuiab2a38c2017-10-13 15:56:08 -07004839 const String16 gradient16("gradient");
Nick Butchere78a8162018-01-09 15:24:21 +00004840 const String16 animatedSelector16("animated-selector");
Adam Lesinski6e460562015-04-21 14:20:15 -07004841
Adam Lesinski28994d82015-01-13 13:42:41 -08004842 const int minSdk = getMinSdkVersion(bundle);
4843 if (minSdk >= SDK_LOLLIPOP_MR1) {
4844 // Lollipop MR1 and up handles public attributes differently, no
4845 // need to do any compat modifications.
Adam Lesinskie572c012014-09-19 15:10:04 -07004846 return NO_ERROR;
4847 }
4848
Adam Lesinski28994d82015-01-13 13:42:41 -08004849 const ConfigDescription config(target->getGroupEntry().toParams());
4850 if (target->getResourceType() == "" || config.sdkVersion >= SDK_LOLLIPOP_MR1) {
Adam Lesinski6e460562015-04-21 14:20:15 -07004851 // Skip resources that have no type (AndroidManifest.xml) or are already version qualified
4852 // with v21 or higher.
Adam Lesinskie572c012014-09-19 15:10:04 -07004853 return NO_ERROR;
4854 }
4855
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004856 sp<XMLNode> newRoot = NULL;
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004857 int sdkVersionToGenerate = SDK_LOLLIPOP_MR1;
Adam Lesinskie572c012014-09-19 15:10:04 -07004858
4859 Vector<sp<XMLNode> > nodesToVisit;
4860 nodesToVisit.push(root);
Tomasz Wasilczyk7e22cab2023-08-24 19:02:33 +00004861 while (!nodesToVisit.empty()) {
Adam Lesinskie572c012014-09-19 15:10:04 -07004862 sp<XMLNode> node = nodesToVisit.top();
4863 nodesToVisit.pop();
4864
Adam Lesinski6e460562015-04-21 14:20:15 -07004865 if (bundle->getNoVersionVectors() && (node->getElementName() == vector16 ||
ztenghui010df882017-03-07 15:50:03 -08004866 node->getElementName() == animatedVector16 ||
ztenghui20554852017-03-21 16:28:57 -07004867 node->getElementName() == objectAnimator16 ||
ztenghuiab2a38c2017-10-13 15:56:08 -07004868 node->getElementName() == pathInterpolator16 ||
Nick Butchere78a8162018-01-09 15:24:21 +00004869 node->getElementName() == gradient16 ||
4870 node->getElementName() == animatedSelector16)) {
Adam Lesinski6e460562015-04-21 14:20:15 -07004871 // We were told not to version vector tags, so skip the children here.
4872 continue;
4873 }
4874
Yuichi Araki4d35cca2017-01-18 20:42:17 +09004875 if (bundle->getNoVersionTransitions() && (IsTransitionElement(node->getElementName()))) {
4876 // We were told not to version transition tags, so skip the children here.
4877 continue;
4878 }
4879
Adam Lesinskie572c012014-09-19 15:10:04 -07004880 const Vector<XMLNode::attribute_entry>& attrs = node->getAttributes();
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004881 for (size_t i = 0; i < attrs.size(); i++) {
Adam Lesinskie572c012014-09-19 15:10:04 -07004882 const XMLNode::attribute_entry& attr = attrs[i];
Adam Lesinski28994d82015-01-13 13:42:41 -08004883 const int sdkLevel = getPublicAttributeSdkLevel(attr.nameResId);
4884 if (sdkLevel > 1 && sdkLevel > config.sdkVersion && sdkLevel > minSdk) {
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004885 if (newRoot == NULL) {
4886 newRoot = root->clone();
4887 }
4888
Adam Lesinski28994d82015-01-13 13:42:41 -08004889 // Find the smallest sdk version that we need to synthesize for
4890 // and do that one. Subsequent versions will be processed on
4891 // the next pass.
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004892 sdkVersionToGenerate = std::min(sdkLevel, sdkVersionToGenerate);
Adam Lesinski28994d82015-01-13 13:42:41 -08004893
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004894 if (bundle->getVerbose()) {
4895 SourcePos(node->getFilename(), node->getStartLineNumber()).printf(
4896 "removing attribute %s%s%s from <%s>",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004897 String8(attr.ns).c_str(),
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004898 (attr.ns.size() == 0 ? "" : ":"),
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004899 String8(attr.name).c_str(),
4900 String8(node->getElementName()).c_str());
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004901 }
4902 node->removeAttribute(i);
4903 i--;
Adam Lesinskie572c012014-09-19 15:10:04 -07004904 }
4905 }
4906
4907 // Schedule a visit to the children.
4908 const Vector<sp<XMLNode> >& children = node->getChildren();
4909 const size_t childCount = children.size();
4910 for (size_t i = 0; i < childCount; i++) {
4911 nodesToVisit.push(children[i]);
4912 }
4913 }
4914
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004915 if (newRoot == NULL) {
Adam Lesinskie572c012014-09-19 15:10:04 -07004916 return NO_ERROR;
4917 }
4918
Adam Lesinskie572c012014-09-19 15:10:04 -07004919 // Look to see if we already have an overriding v21 configuration.
4920 sp<ConfigList> cl = getConfigList(String16(mAssets->getPackage()),
4921 String16(target->getResourceType()), resourceName);
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004922 if (shouldGenerateVersionedResource(cl, config, sdkVersionToGenerate)) {
Adam Lesinskie572c012014-09-19 15:10:04 -07004923 // We don't have an overriding entry for v21, so we must duplicate this one.
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004924 ConfigDescription newConfig(config);
4925 newConfig.sdkVersion = sdkVersionToGenerate;
Adam Lesinskie572c012014-09-19 15:10:04 -07004926 sp<AaptFile> newFile = new AaptFile(target->getSourceFile(),
4927 AaptGroupEntry(newConfig), target->getResourceType());
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07004928 String8 resPath = String8::format("res/%s/%s.xml",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004929 newFile->getGroupEntry().toDirName(target->getResourceType()).c_str(),
4930 String8(resourceName).c_str());
Elliott Hughes338698e2021-07-13 17:15:19 -07004931 convertToResPath(resPath);
Adam Lesinskie572c012014-09-19 15:10:04 -07004932
4933 // Add a resource table entry.
Adam Lesinskif15de2e2014-10-03 14:57:28 -07004934 if (bundle->getVerbose()) {
4935 SourcePos(target->getSourceFile(), -1).printf(
4936 "using v%d attributes; synthesizing resource %s:%s/%s for configuration %s.",
Adam Lesinski28994d82015-01-13 13:42:41 -08004937 newConfig.sdkVersion,
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00004938 mAssets->getPackage().c_str(),
4939 newFile->getResourceType().c_str(),
4940 String8(resourceName).c_str(),
4941 newConfig.toString().c_str());
Adam Lesinskif15de2e2014-10-03 14:57:28 -07004942 }
Adam Lesinskie572c012014-09-19 15:10:04 -07004943
4944 addEntry(SourcePos(),
4945 String16(mAssets->getPackage()),
4946 String16(target->getResourceType()),
4947 resourceName,
4948 String16(resPath),
4949 NULL,
4950 &newConfig);
4951
4952 // Schedule this to be compiled.
4953 CompileResourceWorkItem item;
4954 item.resourceName = resourceName;
4955 item.resPath = resPath;
4956 item.file = newFile;
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07004957 item.xmlRoot = newRoot;
4958 item.needsCompiling = false; // This step occurs after we parse/assign, so we don't need
4959 // to do it again.
Adam Lesinskie572c012014-09-19 15:10:04 -07004960 mWorkQueue.push(item);
4961 }
Adam Lesinskie572c012014-09-19 15:10:04 -07004962 return NO_ERROR;
4963}
Adam Lesinskide7de472014-11-03 12:03:08 -08004964
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004965void ResourceTable::getDensityVaryingResources(
4966 KeyedVector<Symbol, Vector<SymbolDefinition> >& resources) {
Adam Lesinskide7de472014-11-03 12:03:08 -08004967 const ConfigDescription nullConfig;
4968
4969 const size_t packageCount = mOrderedPackages.size();
4970 for (size_t p = 0; p < packageCount; p++) {
4971 const Vector<sp<Type> >& types = mOrderedPackages[p]->getOrderedTypes();
4972 const size_t typeCount = types.size();
4973 for (size_t t = 0; t < typeCount; t++) {
Adam Lesinski081d1b42016-08-15 18:45:00 -07004974 const sp<Type>& type = types[t];
4975 if (type == NULL) {
4976 continue;
4977 }
4978
4979 const Vector<sp<ConfigList> >& configs = type->getOrderedConfigs();
Adam Lesinskide7de472014-11-03 12:03:08 -08004980 const size_t configCount = configs.size();
4981 for (size_t c = 0; c < configCount; c++) {
Adam Lesinski081d1b42016-08-15 18:45:00 -07004982 const sp<ConfigList>& configList = configs[c];
4983 if (configList == NULL) {
4984 continue;
4985 }
4986
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004987 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& configEntries
Adam Lesinski081d1b42016-08-15 18:45:00 -07004988 = configList->getEntries();
Adam Lesinskide7de472014-11-03 12:03:08 -08004989 const size_t configEntryCount = configEntries.size();
4990 for (size_t ce = 0; ce < configEntryCount; ce++) {
Adam Lesinski081d1b42016-08-15 18:45:00 -07004991 const sp<Entry>& entry = configEntries.valueAt(ce);
4992 if (entry == NULL) {
4993 continue;
4994 }
4995
Adam Lesinskide7de472014-11-03 12:03:08 -08004996 const ConfigDescription& config = configEntries.keyAt(ce);
4997 if (AaptConfig::isDensityOnly(config)) {
4998 // This configuration only varies with regards to density.
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004999 const Symbol symbol(
5000 mOrderedPackages[p]->getName(),
Adam Lesinski081d1b42016-08-15 18:45:00 -07005001 type->getName(),
5002 configList->getName(),
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07005003 getResId(mOrderedPackages[p], types[t],
Adam Lesinski081d1b42016-08-15 18:45:00 -07005004 configList->getEntryIndex()));
Adam Lesinskide7de472014-11-03 12:03:08 -08005005
Adam Lesinski081d1b42016-08-15 18:45:00 -07005006
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07005007 AaptUtil::appendValue(resources, symbol,
5008 SymbolDefinition(symbol, config, entry->getPos()));
Adam Lesinskide7de472014-11-03 12:03:08 -08005009 }
5010 }
5011 }
5012 }
5013 }
5014}
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07005015
5016static String16 buildNamespace(const String16& package) {
5017 return String16("http://schemas.android.com/apk/res/") + package;
5018}
5019
5020static sp<XMLNode> findOnlyChildElement(const sp<XMLNode>& parent) {
5021 const Vector<sp<XMLNode> >& children = parent->getChildren();
5022 sp<XMLNode> onlyChild;
5023 for (size_t i = 0; i < children.size(); i++) {
5024 if (children[i]->getType() != XMLNode::TYPE_CDATA) {
5025 if (onlyChild != NULL) {
5026 return NULL;
5027 }
5028 onlyChild = children[i];
5029 }
5030 }
5031 return onlyChild;
5032}
5033
5034/**
5035 * Detects use of the `bundle' format and extracts nested resources into their own top level
5036 * resources. The bundle format looks like this:
5037 *
5038 * <!-- res/drawable/bundle.xml -->
5039 * <animated-vector xmlns:aapt="http://schemas.android.com/aapt">
5040 * <aapt:attr name="android:drawable">
5041 * <vector android:width="60dp"
5042 * android:height="60dp">
5043 * <path android:name="v"
5044 * android:fillColor="#000000"
5045 * android:pathData="M300,70 l 0,-70 70,..." />
5046 * </vector>
5047 * </aapt:attr>
5048 * </animated-vector>
5049 *
5050 * When AAPT sees the <aapt:attr> tag, it will extract its single element and its children
5051 * into a new high-level resource, assigning it a name and ID. Then value of the `name`
5052 * attribute must be a resource attribute. That resource attribute is inserted into the parent
5053 * with the reference to the extracted resource as the value.
5054 *
5055 * <!-- res/drawable/bundle.xml -->
5056 * <animated-vector android:drawable="@drawable/bundle_1.xml">
5057 * </animated-vector>
5058 *
5059 * <!-- res/drawable/bundle_1.xml -->
5060 * <vector android:width="60dp"
5061 * android:height="60dp">
5062 * <path android:name="v"
5063 * android:fillColor="#000000"
5064 * android:pathData="M300,70 l 0,-70 70,..." />
5065 * </vector>
5066 */
5067status_t ResourceTable::processBundleFormat(const Bundle* bundle,
5068 const String16& resourceName,
5069 const sp<AaptFile>& target,
5070 const sp<XMLNode>& root) {
5071 Vector<sp<XMLNode> > namespaces;
5072 if (root->getType() == XMLNode::TYPE_NAMESPACE) {
5073 namespaces.push(root);
5074 }
5075 return processBundleFormatImpl(bundle, resourceName, target, root, &namespaces);
5076}
5077
5078status_t ResourceTable::processBundleFormatImpl(const Bundle* bundle,
5079 const String16& resourceName,
5080 const sp<AaptFile>& target,
5081 const sp<XMLNode>& parent,
5082 Vector<sp<XMLNode> >* namespaces) {
5083 const String16 kAaptNamespaceUri16("http://schemas.android.com/aapt");
5084 const String16 kName16("name");
5085 const String16 kAttr16("attr");
5086 const String16 kAssetPackage16(mAssets->getPackage());
5087
5088 Vector<sp<XMLNode> >& children = parent->getChildren();
5089 for (size_t i = 0; i < children.size(); i++) {
5090 const sp<XMLNode>& child = children[i];
5091
5092 if (child->getType() == XMLNode::TYPE_CDATA) {
5093 continue;
5094 } else if (child->getType() == XMLNode::TYPE_NAMESPACE) {
5095 namespaces->push(child);
5096 }
5097
5098 if (child->getElementNamespace() != kAaptNamespaceUri16 ||
5099 child->getElementName() != kAttr16) {
5100 status_t result = processBundleFormatImpl(bundle, resourceName, target, child,
5101 namespaces);
5102 if (result != NO_ERROR) {
5103 return result;
5104 }
5105
5106 if (child->getType() == XMLNode::TYPE_NAMESPACE) {
5107 namespaces->pop();
5108 }
5109 continue;
5110 }
5111
5112 // This is the <aapt:attr> tag. Look for the 'name' attribute.
5113 SourcePos source(child->getFilename(), child->getStartLineNumber());
5114
5115 sp<XMLNode> nestedRoot = findOnlyChildElement(child);
5116 if (nestedRoot == NULL) {
5117 source.error("<%s:%s> must have exactly one child element",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00005118 String8(child->getElementNamespace()).c_str(),
5119 String8(child->getElementName()).c_str());
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07005120 return UNKNOWN_ERROR;
5121 }
5122
5123 // Find the special attribute 'parent-attr'. This attribute's value contains
5124 // the resource attribute for which this element should be assigned in the parent.
5125 const XMLNode::attribute_entry* attr = child->getAttribute(String16(), kName16);
5126 if (attr == NULL) {
5127 source.error("inline resource definition must specify an attribute via 'name'");
5128 return UNKNOWN_ERROR;
5129 }
5130
5131 // Parse the attribute name.
5132 const char* errorMsg = NULL;
5133 String16 attrPackage, attrType, attrName;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00005134 bool result = ResTable::expandResourceRef(attr->string.c_str(),
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07005135 attr->string.size(),
5136 &attrPackage, &attrType, &attrName,
5137 &kAttr16, &kAssetPackage16,
5138 &errorMsg, NULL);
5139 if (!result) {
5140 source.error("invalid attribute name for 'name': %s", errorMsg);
5141 return UNKNOWN_ERROR;
5142 }
5143
5144 if (attrType != kAttr16) {
5145 // The value of the 'name' attribute must be an attribute reference.
5146 source.error("value of 'name' must be an attribute reference.");
5147 return UNKNOWN_ERROR;
5148 }
5149
5150 // Generate a name for this nested resource and try to add it to the table.
5151 // We do this in a loop because the name may be taken, in which case we will
5152 // increment a suffix until we succeed.
5153 String8 nestedResourceName;
5154 String8 nestedResourcePath;
5155 int suffix = 1;
5156 while (true) {
5157 // This child element will be extracted into its own resource file.
5158 // Generate a name and path for it from its parent.
5159 nestedResourceName = String8::format("%s_%d",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00005160 String8(resourceName).c_str(), suffix++);
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07005161 nestedResourcePath = String8::format("res/%s/%s.xml",
5162 target->getGroupEntry().toDirName(target->getResourceType())
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00005163 .c_str(),
5164 nestedResourceName.c_str());
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07005165
5166 // Lookup or create the entry for this name.
5167 sp<Entry> entry = getEntry(kAssetPackage16,
5168 String16(target->getResourceType()),
5169 String16(nestedResourceName),
5170 source,
5171 false,
5172 &target->getGroupEntry().toParams(),
5173 true);
5174 if (entry == NULL) {
5175 return UNKNOWN_ERROR;
5176 }
5177
5178 if (entry->getType() == Entry::TYPE_UNKNOWN) {
5179 // The value for this resource has never been set,
5180 // meaning we're good!
5181 entry->setItem(source, String16(nestedResourcePath));
5182 break;
5183 }
5184
5185 // We failed (name already exists), so try with a different name
5186 // (increment the suffix).
5187 }
5188
5189 if (bundle->getVerbose()) {
5190 source.printf("generating nested resource %s:%s/%s",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00005191 mAssets->getPackage().c_str(), target->getResourceType().c_str(),
5192 nestedResourceName.c_str());
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07005193 }
5194
5195 // Build the attribute reference and assign it to the parent.
5196 String16 nestedResourceRef = String16(String8::format("@%s:%s/%s",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00005197 mAssets->getPackage().c_str(), target->getResourceType().c_str(),
5198 nestedResourceName.c_str()));
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07005199
5200 String16 attrNs = buildNamespace(attrPackage);
5201 if (parent->getAttribute(attrNs, attrName) != NULL) {
5202 SourcePos(parent->getFilename(), parent->getStartLineNumber())
5203 .error("parent of nested resource already defines attribute '%s:%s'",
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +00005204 String8(attrPackage).c_str(), String8(attrName).c_str());
Adam Lesinski07dfd2d2015-10-28 15:44:27 -07005205 return UNKNOWN_ERROR;
5206 }
5207
5208 // Add the reference to the inline resource.
5209 parent->addAttribute(attrNs, attrName, nestedResourceRef);
5210
5211 // Remove the <aapt:attr> child element from here.
5212 children.removeAt(i);
5213 i--;
5214
5215 // Append all namespace declarations that we've seen on this branch in the XML tree
5216 // to this resource.
5217 // We do this because the order of namespace declarations and prefix usage is determined
5218 // by the developer and we do not want to override any decisions. Be conservative.
5219 for (size_t nsIndex = namespaces->size(); nsIndex > 0; nsIndex--) {
5220 const sp<XMLNode>& ns = namespaces->itemAt(nsIndex - 1);
5221 sp<XMLNode> newNs = XMLNode::newNamespace(ns->getFilename(), ns->getNamespacePrefix(),
5222 ns->getNamespaceUri());
5223 newNs->addChild(nestedRoot);
5224 nestedRoot = newNs;
5225 }
5226
5227 // Schedule compilation of the nested resource.
5228 CompileResourceWorkItem workItem;
5229 workItem.resPath = nestedResourcePath;
5230 workItem.resourceName = String16(nestedResourceName);
5231 workItem.xmlRoot = nestedRoot;
5232 workItem.file = new AaptFile(target->getSourceFile(), target->getGroupEntry(),
5233 target->getResourceType());
5234 mWorkQueue.push(workItem);
5235 }
5236 return NO_ERROR;
5237}