blob: 7d198282fc46de416a173bfd5b123a97f99da780 [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"
Adam Lesinski282e1812014-01-23 18:17:42 -080014
Adam Lesinski9b624c12014-11-19 17:49:26 -080015#include <algorithm>
Adam Lesinski282e1812014-01-23 18:17:42 -080016#include <androidfw/ResourceTypes.h>
17#include <utils/ByteOrder.h>
Adam Lesinski82a2dd82014-09-17 18:34:15 -070018#include <utils/TypeHelpers.h>
Adam Lesinski282e1812014-01-23 18:17:42 -080019#include <stdarg.h>
20
Andreas Gampe2412f842014-09-30 20:55:57 -070021// SSIZE: mingw does not have signed size_t == ssize_t.
22// 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 SSIZE(x) x
25# define STATUST(x) x
26#else
27# define SSIZE(x) (signed size_t)x
28# define STATUST(x) (status_t)x
29#endif
30
31// Set to true for noisy debug output.
32static const bool kIsDebug = false;
33
34#if PRINT_STRING_METRICS
35static const bool kPrintStringMetrics = true;
36#else
37static const bool kPrintStringMetrics = false;
38#endif
Adam Lesinski282e1812014-01-23 18:17:42 -080039
Adam Lesinski9b624c12014-11-19 17:49:26 -080040static const char* kAttrPrivateType = "^attr-private";
41
Adam Lesinskie572c012014-09-19 15:10:04 -070042status_t compileXmlFile(const Bundle* bundle,
43 const sp<AaptAssets>& assets,
44 const String16& resourceName,
Adam Lesinski282e1812014-01-23 18:17:42 -080045 const sp<AaptFile>& target,
46 ResourceTable* table,
47 int options)
48{
49 sp<XMLNode> root = XMLNode::parse(target);
50 if (root == NULL) {
51 return UNKNOWN_ERROR;
52 }
Anton Krumina2ef5c02014-03-12 14:46:44 -070053
Adam Lesinskie572c012014-09-19 15:10:04 -070054 return compileXmlFile(bundle, assets, resourceName, root, target, table, options);
Adam Lesinski282e1812014-01-23 18:17:42 -080055}
56
Adam Lesinskie572c012014-09-19 15:10:04 -070057status_t compileXmlFile(const Bundle* bundle,
58 const sp<AaptAssets>& assets,
59 const String16& resourceName,
Adam Lesinski282e1812014-01-23 18:17:42 -080060 const sp<AaptFile>& target,
61 const sp<AaptFile>& outTarget,
62 ResourceTable* table,
63 int options)
64{
65 sp<XMLNode> root = XMLNode::parse(target);
66 if (root == NULL) {
67 return UNKNOWN_ERROR;
68 }
69
Adam Lesinskie572c012014-09-19 15:10:04 -070070 return compileXmlFile(bundle, assets, resourceName, root, outTarget, table, options);
Adam Lesinski282e1812014-01-23 18:17:42 -080071}
72
Adam Lesinskie572c012014-09-19 15:10:04 -070073status_t compileXmlFile(const Bundle* bundle,
74 const sp<AaptAssets>& assets,
75 const String16& resourceName,
Adam Lesinski282e1812014-01-23 18:17:42 -080076 const sp<XMLNode>& root,
77 const sp<AaptFile>& target,
78 ResourceTable* table,
79 int options)
80{
81 if ((options&XML_COMPILE_STRIP_WHITESPACE) != 0) {
82 root->removeWhitespace(true, NULL);
83 } else if ((options&XML_COMPILE_COMPACT_WHITESPACE) != 0) {
84 root->removeWhitespace(false, NULL);
85 }
86
87 if ((options&XML_COMPILE_UTF8) != 0) {
88 root->setUTF8(true);
89 }
90
Adam Lesinski9d0f7d42015-10-28 15:44:27 -070091 if (table->processBundleFormat(bundle, resourceName, target, root) != NO_ERROR) {
92 return UNKNOWN_ERROR;
93 }
Adam Lesinski282e1812014-01-23 18:17:42 -080094
Adam Lesinski9d0f7d42015-10-28 15:44:27 -070095 bool hasErrors = false;
Adam Lesinski282e1812014-01-23 18:17:42 -080096 if ((options&XML_COMPILE_ASSIGN_ATTRIBUTE_IDS) != 0) {
97 status_t err = root->assignResourceIds(assets, table);
98 if (err != NO_ERROR) {
99 hasErrors = true;
100 }
101 }
102
103 status_t err = root->parseValues(assets, table);
104 if (err != NO_ERROR) {
105 hasErrors = true;
106 }
107
108 if (hasErrors) {
109 return UNKNOWN_ERROR;
110 }
Adam Lesinskie572c012014-09-19 15:10:04 -0700111
112 if (table->modifyForCompat(bundle, resourceName, target, root) != NO_ERROR) {
113 return UNKNOWN_ERROR;
114 }
Andreas Gampe87332a72014-10-01 22:03:58 -0700115
Andreas Gampe2412f842014-09-30 20:55:57 -0700116 if (kIsDebug) {
117 printf("Input XML Resource:\n");
118 root->print();
119 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800120 err = root->flatten(target,
121 (options&XML_COMPILE_STRIP_COMMENTS) != 0,
122 (options&XML_COMPILE_STRIP_RAW_VALUES) != 0);
123 if (err != NO_ERROR) {
124 return err;
125 }
126
Andreas Gampe2412f842014-09-30 20:55:57 -0700127 if (kIsDebug) {
128 printf("Output XML Resource:\n");
129 ResXMLTree tree;
Adam Lesinski282e1812014-01-23 18:17:42 -0800130 tree.setTo(target->getData(), target->getSize());
Andreas Gampe2412f842014-09-30 20:55:57 -0700131 printXMLBlock(&tree);
132 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800133
134 target->setCompressionMethod(ZipEntry::kCompressDeflated);
135
136 return err;
137}
138
Adam Lesinski282e1812014-01-23 18:17:42 -0800139struct flag_entry
140{
141 const char16_t* name;
142 size_t nameLen;
143 uint32_t value;
144 const char* description;
145};
146
147static const char16_t referenceArray[] =
148 { 'r', 'e', 'f', 'e', 'r', 'e', 'n', 'c', 'e' };
149static const char16_t stringArray[] =
150 { 's', 't', 'r', 'i', 'n', 'g' };
151static const char16_t integerArray[] =
152 { 'i', 'n', 't', 'e', 'g', 'e', 'r' };
153static const char16_t booleanArray[] =
154 { 'b', 'o', 'o', 'l', 'e', 'a', 'n' };
155static const char16_t colorArray[] =
156 { 'c', 'o', 'l', 'o', 'r' };
157static const char16_t floatArray[] =
158 { 'f', 'l', 'o', 'a', 't' };
159static const char16_t dimensionArray[] =
160 { 'd', 'i', 'm', 'e', 'n', 's', 'i', 'o', 'n' };
161static const char16_t fractionArray[] =
162 { 'f', 'r', 'a', 'c', 't', 'i', 'o', 'n' };
163static const char16_t enumArray[] =
164 { 'e', 'n', 'u', 'm' };
165static const char16_t flagsArray[] =
166 { 'f', 'l', 'a', 'g', 's' };
167
168static const flag_entry gFormatFlags[] = {
169 { referenceArray, sizeof(referenceArray)/2, ResTable_map::TYPE_REFERENCE,
170 "a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\n"
171 "or to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\"."},
172 { stringArray, sizeof(stringArray)/2, ResTable_map::TYPE_STRING,
173 "a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character." },
174 { integerArray, sizeof(integerArray)/2, ResTable_map::TYPE_INTEGER,
175 "an integer value, such as \"<code>100</code>\"." },
176 { booleanArray, sizeof(booleanArray)/2, ResTable_map::TYPE_BOOLEAN,
177 "a boolean value, either \"<code>true</code>\" or \"<code>false</code>\"." },
178 { colorArray, sizeof(colorArray)/2, ResTable_map::TYPE_COLOR,
179 "a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n"
180 "\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\"." },
181 { floatArray, sizeof(floatArray)/2, ResTable_map::TYPE_FLOAT,
182 "a floating point value, such as \"<code>1.2</code>\"."},
183 { dimensionArray, sizeof(dimensionArray)/2, ResTable_map::TYPE_DIMENSION,
184 "a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\n"
185 "Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\n"
186 "in (inches), mm (millimeters)." },
187 { fractionArray, sizeof(fractionArray)/2, ResTable_map::TYPE_FRACTION,
188 "a fractional value, which is a floating point number appended with either % or %p, such as \"<code>14.5%</code>\".\n"
189 "The % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to\n"
190 "some parent container." },
191 { enumArray, sizeof(enumArray)/2, ResTable_map::TYPE_ENUM, NULL },
192 { flagsArray, sizeof(flagsArray)/2, ResTable_map::TYPE_FLAGS, NULL },
193 { NULL, 0, 0, NULL }
194};
195
196static const char16_t suggestedArray[] = { 's', 'u', 'g', 'g', 'e', 's', 't', 'e', 'd' };
197
198static const flag_entry l10nRequiredFlags[] = {
199 { suggestedArray, sizeof(suggestedArray)/2, ResTable_map::L10N_SUGGESTED, NULL },
200 { NULL, 0, 0, NULL }
201};
202
203static const char16_t nulStr[] = { 0 };
204
205static uint32_t parse_flags(const char16_t* str, size_t len,
206 const flag_entry* flags, bool* outError = NULL)
207{
208 while (len > 0 && isspace(*str)) {
209 str++;
210 len--;
211 }
212 while (len > 0 && isspace(str[len-1])) {
213 len--;
214 }
215
216 const char16_t* const end = str + len;
217 uint32_t value = 0;
218
219 while (str < end) {
220 const char16_t* div = str;
221 while (div < end && *div != '|') {
222 div++;
223 }
224
225 const flag_entry* cur = flags;
226 while (cur->name) {
227 if (strzcmp16(cur->name, cur->nameLen, str, div-str) == 0) {
228 value |= cur->value;
229 break;
230 }
231 cur++;
232 }
233
234 if (!cur->name) {
235 if (outError) *outError = true;
236 return 0;
237 }
238
239 str = div < end ? div+1 : div;
240 }
241
242 if (outError) *outError = false;
243 return value;
244}
245
246static String16 mayOrMust(int type, int flags)
247{
248 if ((type&(~flags)) == 0) {
249 return String16("<p>Must");
250 }
251
252 return String16("<p>May");
253}
254
255static void appendTypeInfo(ResourceTable* outTable, const String16& pkg,
256 const String16& typeName, const String16& ident, int type,
257 const flag_entry* flags)
258{
259 bool hadType = false;
260 while (flags->name) {
261 if ((type&flags->value) != 0 && flags->description != NULL) {
262 String16 fullMsg(mayOrMust(type, flags->value));
263 fullMsg.append(String16(" be "));
264 fullMsg.append(String16(flags->description));
265 outTable->appendTypeComment(pkg, typeName, ident, fullMsg);
266 hadType = true;
267 }
268 flags++;
269 }
270 if (hadType && (type&ResTable_map::TYPE_REFERENCE) == 0) {
271 outTable->appendTypeComment(pkg, typeName, ident,
272 String16("<p>This may also be a reference to a resource (in the form\n"
273 "\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\n"
274 "theme attribute (in the form\n"
275 "\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\n"
276 "containing a value of this type."));
277 }
278}
279
280struct PendingAttribute
281{
282 const String16 myPackage;
283 const SourcePos sourcePos;
284 const bool appendComment;
285 int32_t type;
286 String16 ident;
287 String16 comment;
288 bool hasErrors;
289 bool added;
290
291 PendingAttribute(String16 _package, const sp<AaptFile>& in,
292 ResXMLTree& block, bool _appendComment)
293 : myPackage(_package)
294 , sourcePos(in->getPrintableSource(), block.getLineNumber())
295 , appendComment(_appendComment)
296 , type(ResTable_map::TYPE_ANY)
297 , hasErrors(false)
298 , added(false)
299 {
300 }
301
302 status_t createIfNeeded(ResourceTable* outTable)
303 {
304 if (added || hasErrors) {
305 return NO_ERROR;
306 }
307 added = true;
308
309 String16 attr16("attr");
310
311 if (outTable->hasBagOrEntry(myPackage, attr16, ident)) {
312 sourcePos.error("Attribute \"%s\" has already been defined\n",
313 String8(ident).string());
314 hasErrors = true;
315 return UNKNOWN_ERROR;
316 }
317
318 char numberStr[16];
319 sprintf(numberStr, "%d", type);
320 status_t err = outTable->addBag(sourcePos, myPackage,
321 attr16, ident, String16(""),
322 String16("^type"),
323 String16(numberStr), NULL, NULL);
324 if (err != NO_ERROR) {
325 hasErrors = true;
326 return err;
327 }
328 outTable->appendComment(myPackage, attr16, ident, comment, appendComment);
329 //printf("Attribute %s comment: %s\n", String8(ident).string(),
330 // String8(comment).string());
331 return err;
332 }
333};
334
335static status_t compileAttribute(const sp<AaptFile>& in,
336 ResXMLTree& block,
337 const String16& myPackage,
338 ResourceTable* outTable,
339 String16* outIdent = NULL,
340 bool inStyleable = false)
341{
342 PendingAttribute attr(myPackage, in, block, inStyleable);
343
344 const String16 attr16("attr");
345 const String16 id16("id");
346
347 // Attribute type constants.
348 const String16 enum16("enum");
349 const String16 flag16("flag");
350
351 ResXMLTree::event_code_t code;
352 size_t len;
353 status_t err;
354
355 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
356 if (identIdx >= 0) {
357 attr.ident = String16(block.getAttributeStringValue(identIdx, &len));
358 if (outIdent) {
359 *outIdent = attr.ident;
360 }
361 } else {
362 attr.sourcePos.error("A 'name' attribute is required for <attr>\n");
363 attr.hasErrors = true;
364 }
365
366 attr.comment = String16(
367 block.getComment(&len) ? block.getComment(&len) : nulStr);
368
369 ssize_t typeIdx = block.indexOfAttribute(NULL, "format");
370 if (typeIdx >= 0) {
371 String16 typeStr = String16(block.getAttributeStringValue(typeIdx, &len));
372 attr.type = parse_flags(typeStr.string(), typeStr.size(), gFormatFlags);
373 if (attr.type == 0) {
374 attr.sourcePos.error("Tag <attr> 'format' attribute value \"%s\" not valid\n",
375 String8(typeStr).string());
376 attr.hasErrors = true;
377 }
378 attr.createIfNeeded(outTable);
379 } else if (!inStyleable) {
380 // Attribute definitions outside of styleables always define the
381 // attribute as a generic value.
382 attr.createIfNeeded(outTable);
383 }
384
385 //printf("Attribute %s: type=0x%08x\n", String8(attr.ident).string(), attr.type);
386
387 ssize_t minIdx = block.indexOfAttribute(NULL, "min");
388 if (minIdx >= 0) {
389 String16 val = String16(block.getAttributeStringValue(minIdx, &len));
390 if (!ResTable::stringToInt(val.string(), val.size(), NULL)) {
391 attr.sourcePos.error("Tag <attr> 'min' attribute must be a number, not \"%s\"\n",
392 String8(val).string());
393 attr.hasErrors = true;
394 }
395 attr.createIfNeeded(outTable);
396 if (!attr.hasErrors) {
397 err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
398 String16(""), String16("^min"), String16(val), NULL, NULL);
399 if (err != NO_ERROR) {
400 attr.hasErrors = true;
401 }
402 }
403 }
404
405 ssize_t maxIdx = block.indexOfAttribute(NULL, "max");
406 if (maxIdx >= 0) {
407 String16 val = String16(block.getAttributeStringValue(maxIdx, &len));
408 if (!ResTable::stringToInt(val.string(), val.size(), NULL)) {
409 attr.sourcePos.error("Tag <attr> 'max' attribute must be a number, not \"%s\"\n",
410 String8(val).string());
411 attr.hasErrors = true;
412 }
413 attr.createIfNeeded(outTable);
414 if (!attr.hasErrors) {
415 err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
416 String16(""), String16("^max"), String16(val), NULL, NULL);
417 attr.hasErrors = true;
418 }
419 }
420
421 if ((minIdx >= 0 || maxIdx >= 0) && (attr.type&ResTable_map::TYPE_INTEGER) == 0) {
422 attr.sourcePos.error("Tag <attr> must have format=integer attribute if using max or min\n");
423 attr.hasErrors = true;
424 }
425
426 ssize_t l10nIdx = block.indexOfAttribute(NULL, "localization");
427 if (l10nIdx >= 0) {
Dan Albertf348c152014-09-08 18:28:00 -0700428 const char16_t* str = block.getAttributeStringValue(l10nIdx, &len);
Adam Lesinski282e1812014-01-23 18:17:42 -0800429 bool error;
430 uint32_t l10n_required = parse_flags(str, len, l10nRequiredFlags, &error);
431 if (error) {
432 attr.sourcePos.error("Tag <attr> 'localization' attribute value \"%s\" not valid\n",
433 String8(str).string());
434 attr.hasErrors = true;
435 }
436 attr.createIfNeeded(outTable);
437 if (!attr.hasErrors) {
438 char buf[11];
439 sprintf(buf, "%d", l10n_required);
440 err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
441 String16(""), String16("^l10n"), String16(buf), NULL, NULL);
442 if (err != NO_ERROR) {
443 attr.hasErrors = true;
444 }
445 }
446 }
447
448 String16 enumOrFlagsComment;
449
450 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
451 if (code == ResXMLTree::START_TAG) {
452 uint32_t localType = 0;
453 if (strcmp16(block.getElementName(&len), enum16.string()) == 0) {
454 localType = ResTable_map::TYPE_ENUM;
455 } else if (strcmp16(block.getElementName(&len), flag16.string()) == 0) {
456 localType = ResTable_map::TYPE_FLAGS;
457 } else {
458 SourcePos(in->getPrintableSource(), block.getLineNumber())
459 .error("Tag <%s> can not appear inside <attr>, only <enum> or <flag>\n",
460 String8(block.getElementName(&len)).string());
461 return UNKNOWN_ERROR;
462 }
463
464 attr.createIfNeeded(outTable);
465
466 if (attr.type == ResTable_map::TYPE_ANY) {
467 // No type was explicitly stated, so supplying enum tags
468 // implicitly creates an enum or flag.
469 attr.type = 0;
470 }
471
472 if ((attr.type&(ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS)) == 0) {
473 // Wasn't originally specified as an enum, so update its type.
474 attr.type |= localType;
475 if (!attr.hasErrors) {
476 char numberStr[16];
477 sprintf(numberStr, "%d", attr.type);
478 err = outTable->addBag(SourcePos(in->getPrintableSource(), block.getLineNumber()),
479 myPackage, attr16, attr.ident, String16(""),
480 String16("^type"), String16(numberStr), NULL, NULL, true);
481 if (err != NO_ERROR) {
482 attr.hasErrors = true;
483 }
484 }
485 } else if ((uint32_t)(attr.type&(ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS)) != localType) {
486 if (localType == ResTable_map::TYPE_ENUM) {
487 SourcePos(in->getPrintableSource(), block.getLineNumber())
488 .error("<enum> attribute can not be used inside a flags format\n");
489 attr.hasErrors = true;
490 } else {
491 SourcePos(in->getPrintableSource(), block.getLineNumber())
492 .error("<flag> attribute can not be used inside a enum format\n");
493 attr.hasErrors = true;
494 }
495 }
496
497 String16 itemIdent;
498 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "name");
499 if (itemIdentIdx >= 0) {
500 itemIdent = String16(block.getAttributeStringValue(itemIdentIdx, &len));
501 } else {
502 SourcePos(in->getPrintableSource(), block.getLineNumber())
503 .error("A 'name' attribute is required for <enum> or <flag>\n");
504 attr.hasErrors = true;
505 }
506
507 String16 value;
508 ssize_t valueIdx = block.indexOfAttribute(NULL, "value");
509 if (valueIdx >= 0) {
510 value = String16(block.getAttributeStringValue(valueIdx, &len));
511 } else {
512 SourcePos(in->getPrintableSource(), block.getLineNumber())
513 .error("A 'value' attribute is required for <enum> or <flag>\n");
514 attr.hasErrors = true;
515 }
516 if (!attr.hasErrors && !ResTable::stringToInt(value.string(), value.size(), NULL)) {
517 SourcePos(in->getPrintableSource(), block.getLineNumber())
518 .error("Tag <enum> or <flag> 'value' attribute must be a number,"
519 " not \"%s\"\n",
520 String8(value).string());
521 attr.hasErrors = true;
522 }
523
Adam Lesinski282e1812014-01-23 18:17:42 -0800524 if (!attr.hasErrors) {
525 if (enumOrFlagsComment.size() == 0) {
526 enumOrFlagsComment.append(mayOrMust(attr.type,
527 ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS));
528 enumOrFlagsComment.append((attr.type&ResTable_map::TYPE_ENUM)
529 ? String16(" be one of the following constant values.")
530 : String16(" be one or more (separated by '|') of the following constant values."));
531 enumOrFlagsComment.append(String16("</p>\n<table>\n"
532 "<colgroup align=\"left\" />\n"
533 "<colgroup align=\"left\" />\n"
534 "<colgroup align=\"left\" />\n"
535 "<tr><th>Constant</th><th>Value</th><th>Description</th></tr>"));
536 }
537
538 enumOrFlagsComment.append(String16("\n<tr><td><code>"));
539 enumOrFlagsComment.append(itemIdent);
540 enumOrFlagsComment.append(String16("</code></td><td>"));
541 enumOrFlagsComment.append(value);
542 enumOrFlagsComment.append(String16("</td><td>"));
543 if (block.getComment(&len)) {
544 enumOrFlagsComment.append(String16(block.getComment(&len)));
545 }
546 enumOrFlagsComment.append(String16("</td></tr>"));
547
548 err = outTable->addBag(SourcePos(in->getPrintableSource(), block.getLineNumber()),
549 myPackage,
550 attr16, attr.ident, String16(""),
551 itemIdent, value, NULL, NULL, false, true);
552 if (err != NO_ERROR) {
553 attr.hasErrors = true;
554 }
555 }
556 } else if (code == ResXMLTree::END_TAG) {
557 if (strcmp16(block.getElementName(&len), attr16.string()) == 0) {
558 break;
559 }
560 if ((attr.type&ResTable_map::TYPE_ENUM) != 0) {
561 if (strcmp16(block.getElementName(&len), enum16.string()) != 0) {
562 SourcePos(in->getPrintableSource(), block.getLineNumber())
563 .error("Found tag </%s> where </enum> is expected\n",
564 String8(block.getElementName(&len)).string());
565 return UNKNOWN_ERROR;
566 }
567 } else {
568 if (strcmp16(block.getElementName(&len), flag16.string()) != 0) {
569 SourcePos(in->getPrintableSource(), block.getLineNumber())
570 .error("Found tag </%s> where </flag> is expected\n",
571 String8(block.getElementName(&len)).string());
572 return UNKNOWN_ERROR;
573 }
574 }
575 }
576 }
577
578 if (!attr.hasErrors && attr.added) {
579 appendTypeInfo(outTable, myPackage, attr16, attr.ident, attr.type, gFormatFlags);
580 }
581
582 if (!attr.hasErrors && enumOrFlagsComment.size() > 0) {
583 enumOrFlagsComment.append(String16("\n</table>"));
584 outTable->appendTypeComment(myPackage, attr16, attr.ident, enumOrFlagsComment);
585 }
586
587
588 return NO_ERROR;
589}
590
591bool localeIsDefined(const ResTable_config& config)
592{
593 return config.locale == 0;
594}
595
596status_t parseAndAddBag(Bundle* bundle,
597 const sp<AaptFile>& in,
598 ResXMLTree* block,
599 const ResTable_config& config,
600 const String16& myPackage,
601 const String16& curType,
602 const String16& ident,
603 const String16& parentIdent,
604 const String16& itemIdent,
605 int32_t curFormat,
606 bool isFormatted,
Andreas Gampe2412f842014-09-30 20:55:57 -0700607 const String16& /* product */,
Anton Krumina2ef5c02014-03-12 14:46:44 -0700608 PseudolocalizationMethod pseudolocalize,
Adam Lesinski282e1812014-01-23 18:17:42 -0800609 const bool overwrite,
610 ResourceTable* outTable)
611{
612 status_t err;
613 const String16 item16("item");
Anton Krumina2ef5c02014-03-12 14:46:44 -0700614
Adam Lesinski282e1812014-01-23 18:17:42 -0800615 String16 str;
616 Vector<StringPool::entry_style_span> spans;
617 err = parseStyledString(bundle, in->getPrintableSource().string(),
618 block, item16, &str, &spans, isFormatted,
619 pseudolocalize);
620 if (err != NO_ERROR) {
621 return err;
622 }
Andreas Gampe2412f842014-09-30 20:55:57 -0700623
624 if (kIsDebug) {
625 printf("Adding resource bag entry l=%c%c c=%c%c orien=%d d=%d "
626 " pid=%s, bag=%s, id=%s: %s\n",
627 config.language[0], config.language[1],
628 config.country[0], config.country[1],
629 config.orientation, config.density,
630 String8(parentIdent).string(),
631 String8(ident).string(),
632 String8(itemIdent).string(),
633 String8(str).string());
634 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800635
636 err = outTable->addBag(SourcePos(in->getPrintableSource(), block->getLineNumber()),
637 myPackage, curType, ident, parentIdent, itemIdent, str,
638 &spans, &config, overwrite, false, curFormat);
639 return err;
640}
641
642/*
643 * Returns true if needle is one of the elements in the comma-separated list
644 * haystack, false otherwise.
645 */
646bool isInProductList(const String16& needle, const String16& haystack) {
647 const char16_t *needle2 = needle.string();
648 const char16_t *haystack2 = haystack.string();
649 size_t needlesize = needle.size();
650
651 while (*haystack2 != '\0') {
652 if (strncmp16(haystack2, needle2, needlesize) == 0) {
653 if (haystack2[needlesize] == '\0' || haystack2[needlesize] == ',') {
654 return true;
655 }
656 }
657
658 while (*haystack2 != '\0' && *haystack2 != ',') {
659 haystack2++;
660 }
661 if (*haystack2 == ',') {
662 haystack2++;
663 }
664 }
665
666 return false;
667}
668
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700669/*
670 * A simple container that holds a resource type and name. It is ordered first by type then
671 * by name.
672 */
673struct type_ident_pair_t {
674 String16 type;
675 String16 ident;
676
677 type_ident_pair_t() { };
678 type_ident_pair_t(const String16& t, const String16& i) : type(t), ident(i) { }
679 type_ident_pair_t(const type_ident_pair_t& o) : type(o.type), ident(o.ident) { }
680 inline bool operator < (const type_ident_pair_t& o) const {
681 int cmp = compare_type(type, o.type);
682 if (cmp < 0) {
683 return true;
684 } else if (cmp > 0) {
685 return false;
686 } else {
687 return strictly_order_type(ident, o.ident);
688 }
689 }
690};
691
692
Adam Lesinski282e1812014-01-23 18:17:42 -0800693status_t parseAndAddEntry(Bundle* bundle,
694 const sp<AaptFile>& in,
695 ResXMLTree* block,
696 const ResTable_config& config,
697 const String16& myPackage,
698 const String16& curType,
699 const String16& ident,
700 const String16& curTag,
701 bool curIsStyled,
702 int32_t curFormat,
703 bool isFormatted,
704 const String16& product,
Anton Krumina2ef5c02014-03-12 14:46:44 -0700705 PseudolocalizationMethod pseudolocalize,
Adam Lesinski282e1812014-01-23 18:17:42 -0800706 const bool overwrite,
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700707 KeyedVector<type_ident_pair_t, bool>* skippedResourceNames,
Adam Lesinski282e1812014-01-23 18:17:42 -0800708 ResourceTable* outTable)
709{
710 status_t err;
711
712 String16 str;
713 Vector<StringPool::entry_style_span> spans;
714 err = parseStyledString(bundle, in->getPrintableSource().string(), block,
715 curTag, &str, curIsStyled ? &spans : NULL,
716 isFormatted, pseudolocalize);
717
718 if (err < NO_ERROR) {
719 return err;
720 }
721
722 /*
723 * If a product type was specified on the command line
724 * and also in the string, and the two are not the same,
725 * return without adding the string.
726 */
727
728 const char *bundleProduct = bundle->getProduct();
729 if (bundleProduct == NULL) {
730 bundleProduct = "";
731 }
732
733 if (product.size() != 0) {
734 /*
735 * If the command-line-specified product is empty, only "default"
736 * matches. Other variants are skipped. This is so generation
737 * of the R.java file when the product is not known is predictable.
738 */
739
740 if (bundleProduct[0] == '\0') {
741 if (strcmp16(String16("default").string(), product.string()) != 0) {
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700742 /*
743 * This string has a product other than 'default'. Do not add it,
744 * but record it so that if we do not see the same string with
745 * product 'default' or no product, then report an error.
746 */
747 skippedResourceNames->replaceValueFor(
748 type_ident_pair_t(curType, ident), true);
Adam Lesinski282e1812014-01-23 18:17:42 -0800749 return NO_ERROR;
750 }
751 } else {
752 /*
753 * The command-line product is not empty.
754 * If the product for this string is on the command-line list,
755 * it matches. "default" also matches, but only if nothing
756 * else has matched already.
757 */
758
759 if (isInProductList(product, String16(bundleProduct))) {
760 ;
761 } else if (strcmp16(String16("default").string(), product.string()) == 0 &&
762 !outTable->hasBagOrEntry(myPackage, curType, ident, config)) {
763 ;
764 } else {
765 return NO_ERROR;
766 }
767 }
768 }
769
Andreas Gampe2412f842014-09-30 20:55:57 -0700770 if (kIsDebug) {
771 printf("Adding resource entry l=%c%c c=%c%c orien=%d d=%d id=%s: %s\n",
772 config.language[0], config.language[1],
773 config.country[0], config.country[1],
774 config.orientation, config.density,
775 String8(ident).string(), String8(str).string());
776 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800777
778 err = outTable->addEntry(SourcePos(in->getPrintableSource(), block->getLineNumber()),
779 myPackage, curType, ident, str, &spans, &config,
780 false, curFormat, overwrite);
781
782 return err;
783}
784
785status_t compileResourceFile(Bundle* bundle,
786 const sp<AaptAssets>& assets,
787 const sp<AaptFile>& in,
788 const ResTable_config& defParams,
789 const bool overwrite,
790 ResourceTable* outTable)
791{
792 ResXMLTree block;
793 status_t err = parseXMLResource(in, &block, false, true);
794 if (err != NO_ERROR) {
795 return err;
796 }
797
798 // Top-level tag.
799 const String16 resources16("resources");
800
801 // Identifier declaration tags.
802 const String16 declare_styleable16("declare-styleable");
803 const String16 attr16("attr");
804
805 // Data creation organizational tags.
806 const String16 string16("string");
807 const String16 drawable16("drawable");
808 const String16 color16("color");
809 const String16 bool16("bool");
810 const String16 integer16("integer");
811 const String16 dimen16("dimen");
812 const String16 fraction16("fraction");
813 const String16 style16("style");
814 const String16 plurals16("plurals");
815 const String16 array16("array");
816 const String16 string_array16("string-array");
817 const String16 integer_array16("integer-array");
818 const String16 public16("public");
819 const String16 public_padding16("public-padding");
820 const String16 private_symbols16("private-symbols");
821 const String16 java_symbol16("java-symbol");
822 const String16 add_resource16("add-resource");
823 const String16 skip16("skip");
824 const String16 eat_comment16("eat-comment");
825
826 // Data creation tags.
827 const String16 bag16("bag");
828 const String16 item16("item");
829
830 // Attribute type constants.
831 const String16 enum16("enum");
832
833 // plural values
834 const String16 other16("other");
835 const String16 quantityOther16("^other");
836 const String16 zero16("zero");
837 const String16 quantityZero16("^zero");
838 const String16 one16("one");
839 const String16 quantityOne16("^one");
840 const String16 two16("two");
841 const String16 quantityTwo16("^two");
842 const String16 few16("few");
843 const String16 quantityFew16("^few");
844 const String16 many16("many");
845 const String16 quantityMany16("^many");
846
847 // useful attribute names and special values
848 const String16 name16("name");
849 const String16 translatable16("translatable");
850 const String16 formatted16("formatted");
851 const String16 false16("false");
852
853 const String16 myPackage(assets->getPackage());
854
855 bool hasErrors = false;
856
857 bool fileIsTranslatable = true;
858 if (strstr(in->getPrintableSource().string(), "donottranslate") != NULL) {
859 fileIsTranslatable = false;
860 }
861
862 DefaultKeyedVector<String16, uint32_t> nextPublicId(0);
863
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700864 // Stores the resource names that were skipped. Typically this happens when
865 // AAPT is invoked without a product specified and a resource has no
866 // 'default' product attribute.
867 KeyedVector<type_ident_pair_t, bool> skippedResourceNames;
868
Adam Lesinski282e1812014-01-23 18:17:42 -0800869 ResXMLTree::event_code_t code;
870 do {
871 code = block.next();
872 } while (code == ResXMLTree::START_NAMESPACE);
873
874 size_t len;
875 if (code != ResXMLTree::START_TAG) {
876 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
877 "No start tag found\n");
878 return UNKNOWN_ERROR;
879 }
880 if (strcmp16(block.getElementName(&len), resources16.string()) != 0) {
881 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
882 "Invalid start tag %s\n", String8(block.getElementName(&len)).string());
883 return UNKNOWN_ERROR;
884 }
885
886 ResTable_config curParams(defParams);
887
888 ResTable_config pseudoParams(curParams);
Anton Krumina2ef5c02014-03-12 14:46:44 -0700889 pseudoParams.language[0] = 'e';
890 pseudoParams.language[1] = 'n';
891 pseudoParams.country[0] = 'X';
892 pseudoParams.country[1] = 'A';
893
894 ResTable_config pseudoBidiParams(curParams);
895 pseudoBidiParams.language[0] = 'a';
896 pseudoBidiParams.language[1] = 'r';
897 pseudoBidiParams.country[0] = 'X';
898 pseudoBidiParams.country[1] = 'B';
Adam Lesinski282e1812014-01-23 18:17:42 -0800899
Igor Viarheichyk47843df2014-05-01 17:04:39 -0700900 // We should skip resources for pseudolocales if they were
901 // already added automatically. This is a fix for a transition period when
902 // manually pseudolocalized resources may be expected.
903 // TODO: remove this check after next SDK version release.
904 if ((bundle->getPseudolocalize() & PSEUDO_ACCENTED &&
905 curParams.locale == pseudoParams.locale) ||
906 (bundle->getPseudolocalize() & PSEUDO_BIDI &&
907 curParams.locale == pseudoBidiParams.locale)) {
908 SourcePos(in->getPrintableSource(), 0).warning(
909 "Resource file %s is skipped as pseudolocalization"
910 " was done automatically.",
911 in->getPrintableSource().string());
912 return NO_ERROR;
913 }
914
Adam Lesinski282e1812014-01-23 18:17:42 -0800915 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
916 if (code == ResXMLTree::START_TAG) {
917 const String16* curTag = NULL;
918 String16 curType;
Adrian Roos58922482015-06-01 17:59:41 -0700919 String16 curName;
Adam Lesinski282e1812014-01-23 18:17:42 -0800920 int32_t curFormat = ResTable_map::TYPE_ANY;
921 bool curIsBag = false;
922 bool curIsBagReplaceOnOverwrite = false;
923 bool curIsStyled = false;
924 bool curIsPseudolocalizable = false;
925 bool curIsFormatted = fileIsTranslatable;
926 bool localHasErrors = false;
927
928 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
929 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
930 && code != ResXMLTree::BAD_DOCUMENT) {
931 if (code == ResXMLTree::END_TAG) {
932 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
933 break;
934 }
935 }
936 }
937 continue;
938
939 } else if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
940 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
941 && code != ResXMLTree::BAD_DOCUMENT) {
942 if (code == ResXMLTree::END_TAG) {
943 if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
944 break;
945 }
946 }
947 }
948 continue;
949
950 } else if (strcmp16(block.getElementName(&len), public16.string()) == 0) {
951 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
952
953 String16 type;
954 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
955 if (typeIdx < 0) {
956 srcPos.error("A 'type' attribute is required for <public>\n");
957 hasErrors = localHasErrors = true;
958 }
959 type = String16(block.getAttributeStringValue(typeIdx, &len));
960
961 String16 name;
962 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
963 if (nameIdx < 0) {
964 srcPos.error("A 'name' attribute is required for <public>\n");
965 hasErrors = localHasErrors = true;
966 }
967 name = String16(block.getAttributeStringValue(nameIdx, &len));
968
969 uint32_t ident = 0;
970 ssize_t identIdx = block.indexOfAttribute(NULL, "id");
971 if (identIdx >= 0) {
972 const char16_t* identStr = block.getAttributeStringValue(identIdx, &len);
973 Res_value identValue;
974 if (!ResTable::stringToInt(identStr, len, &identValue)) {
975 srcPos.error("Given 'id' attribute is not an integer: %s\n",
976 String8(block.getAttributeStringValue(identIdx, &len)).string());
977 hasErrors = localHasErrors = true;
978 } else {
979 ident = identValue.data;
980 nextPublicId.replaceValueFor(type, ident+1);
981 }
982 } else if (nextPublicId.indexOfKey(type) < 0) {
983 srcPos.error("No 'id' attribute supplied <public>,"
984 " and no previous id defined in this file.\n");
985 hasErrors = localHasErrors = true;
986 } else if (!localHasErrors) {
987 ident = nextPublicId.valueFor(type);
988 nextPublicId.replaceValueFor(type, ident+1);
989 }
990
991 if (!localHasErrors) {
992 err = outTable->addPublic(srcPos, myPackage, type, name, ident);
993 if (err < NO_ERROR) {
994 hasErrors = localHasErrors = true;
995 }
996 }
997 if (!localHasErrors) {
998 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
999 if (symbols != NULL) {
1000 symbols = symbols->addNestedSymbol(String8(type), srcPos);
1001 }
1002 if (symbols != NULL) {
1003 symbols->makeSymbolPublic(String8(name), srcPos);
1004 String16 comment(
1005 block.getComment(&len) ? block.getComment(&len) : nulStr);
1006 symbols->appendComment(String8(name), comment, srcPos);
1007 } else {
1008 srcPos.error("Unable to create symbols!\n");
1009 hasErrors = localHasErrors = true;
1010 }
1011 }
1012
1013 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1014 if (code == ResXMLTree::END_TAG) {
1015 if (strcmp16(block.getElementName(&len), public16.string()) == 0) {
1016 break;
1017 }
1018 }
1019 }
1020 continue;
1021
1022 } else if (strcmp16(block.getElementName(&len), public_padding16.string()) == 0) {
1023 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1024
1025 String16 type;
1026 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
1027 if (typeIdx < 0) {
1028 srcPos.error("A 'type' attribute is required for <public-padding>\n");
1029 hasErrors = localHasErrors = true;
1030 }
1031 type = String16(block.getAttributeStringValue(typeIdx, &len));
1032
1033 String16 name;
1034 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1035 if (nameIdx < 0) {
1036 srcPos.error("A 'name' attribute is required for <public-padding>\n");
1037 hasErrors = localHasErrors = true;
1038 }
1039 name = String16(block.getAttributeStringValue(nameIdx, &len));
1040
1041 uint32_t start = 0;
1042 ssize_t startIdx = block.indexOfAttribute(NULL, "start");
1043 if (startIdx >= 0) {
1044 const char16_t* startStr = block.getAttributeStringValue(startIdx, &len);
1045 Res_value startValue;
1046 if (!ResTable::stringToInt(startStr, len, &startValue)) {
1047 srcPos.error("Given 'start' attribute is not an integer: %s\n",
1048 String8(block.getAttributeStringValue(startIdx, &len)).string());
1049 hasErrors = localHasErrors = true;
1050 } else {
1051 start = startValue.data;
1052 }
1053 } else if (nextPublicId.indexOfKey(type) < 0) {
1054 srcPos.error("No 'start' attribute supplied <public-padding>,"
1055 " and no previous id defined in this file.\n");
1056 hasErrors = localHasErrors = true;
1057 } else if (!localHasErrors) {
1058 start = nextPublicId.valueFor(type);
1059 }
1060
1061 uint32_t end = 0;
1062 ssize_t endIdx = block.indexOfAttribute(NULL, "end");
1063 if (endIdx >= 0) {
1064 const char16_t* endStr = block.getAttributeStringValue(endIdx, &len);
1065 Res_value endValue;
1066 if (!ResTable::stringToInt(endStr, len, &endValue)) {
1067 srcPos.error("Given 'end' attribute is not an integer: %s\n",
1068 String8(block.getAttributeStringValue(endIdx, &len)).string());
1069 hasErrors = localHasErrors = true;
1070 } else {
1071 end = endValue.data;
1072 }
1073 } else {
1074 srcPos.error("No 'end' attribute supplied <public-padding>\n");
1075 hasErrors = localHasErrors = true;
1076 }
1077
1078 if (end >= start) {
1079 nextPublicId.replaceValueFor(type, end+1);
1080 } else {
1081 srcPos.error("Padding start '%ul' is after end '%ul'\n",
1082 start, end);
1083 hasErrors = localHasErrors = true;
1084 }
1085
1086 String16 comment(
1087 block.getComment(&len) ? block.getComment(&len) : nulStr);
1088 for (uint32_t curIdent=start; curIdent<=end; curIdent++) {
1089 if (localHasErrors) {
1090 break;
1091 }
1092 String16 curName(name);
1093 char buf[64];
1094 sprintf(buf, "%d", (int)(end-curIdent+1));
1095 curName.append(String16(buf));
1096
1097 err = outTable->addEntry(srcPos, myPackage, type, curName,
1098 String16("padding"), NULL, &curParams, false,
1099 ResTable_map::TYPE_STRING, overwrite);
1100 if (err < NO_ERROR) {
1101 hasErrors = localHasErrors = true;
1102 break;
1103 }
1104 err = outTable->addPublic(srcPos, myPackage, type,
1105 curName, curIdent);
1106 if (err < NO_ERROR) {
1107 hasErrors = localHasErrors = true;
1108 break;
1109 }
1110 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1111 if (symbols != NULL) {
1112 symbols = symbols->addNestedSymbol(String8(type), srcPos);
1113 }
1114 if (symbols != NULL) {
1115 symbols->makeSymbolPublic(String8(curName), srcPos);
1116 symbols->appendComment(String8(curName), comment, srcPos);
1117 } else {
1118 srcPos.error("Unable to create symbols!\n");
1119 hasErrors = localHasErrors = true;
1120 }
1121 }
1122
1123 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1124 if (code == ResXMLTree::END_TAG) {
1125 if (strcmp16(block.getElementName(&len), public_padding16.string()) == 0) {
1126 break;
1127 }
1128 }
1129 }
1130 continue;
1131
1132 } else if (strcmp16(block.getElementName(&len), private_symbols16.string()) == 0) {
1133 String16 pkg;
1134 ssize_t pkgIdx = block.indexOfAttribute(NULL, "package");
1135 if (pkgIdx < 0) {
1136 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1137 "A 'package' attribute is required for <private-symbols>\n");
1138 hasErrors = localHasErrors = true;
1139 }
1140 pkg = String16(block.getAttributeStringValue(pkgIdx, &len));
1141 if (!localHasErrors) {
1142 assets->setSymbolsPrivatePackage(String8(pkg));
1143 }
1144
1145 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1146 if (code == ResXMLTree::END_TAG) {
1147 if (strcmp16(block.getElementName(&len), private_symbols16.string()) == 0) {
1148 break;
1149 }
1150 }
1151 }
1152 continue;
1153
1154 } else if (strcmp16(block.getElementName(&len), java_symbol16.string()) == 0) {
1155 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1156
1157 String16 type;
1158 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
1159 if (typeIdx < 0) {
1160 srcPos.error("A 'type' attribute is required for <public>\n");
1161 hasErrors = localHasErrors = true;
1162 }
1163 type = String16(block.getAttributeStringValue(typeIdx, &len));
1164
1165 String16 name;
1166 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1167 if (nameIdx < 0) {
1168 srcPos.error("A 'name' attribute is required for <public>\n");
1169 hasErrors = localHasErrors = true;
1170 }
1171 name = String16(block.getAttributeStringValue(nameIdx, &len));
1172
1173 sp<AaptSymbols> symbols = assets->getJavaSymbolsFor(String8("R"));
1174 if (symbols != NULL) {
1175 symbols = symbols->addNestedSymbol(String8(type), srcPos);
1176 }
1177 if (symbols != NULL) {
1178 symbols->makeSymbolJavaSymbol(String8(name), srcPos);
1179 String16 comment(
1180 block.getComment(&len) ? block.getComment(&len) : nulStr);
1181 symbols->appendComment(String8(name), comment, srcPos);
1182 } else {
1183 srcPos.error("Unable to create symbols!\n");
1184 hasErrors = localHasErrors = true;
1185 }
1186
1187 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1188 if (code == ResXMLTree::END_TAG) {
1189 if (strcmp16(block.getElementName(&len), java_symbol16.string()) == 0) {
1190 break;
1191 }
1192 }
1193 }
1194 continue;
1195
1196
1197 } else if (strcmp16(block.getElementName(&len), add_resource16.string()) == 0) {
1198 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1199
1200 String16 typeName;
1201 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
1202 if (typeIdx < 0) {
1203 srcPos.error("A 'type' attribute is required for <add-resource>\n");
1204 hasErrors = localHasErrors = true;
1205 }
1206 typeName = String16(block.getAttributeStringValue(typeIdx, &len));
1207
1208 String16 name;
1209 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1210 if (nameIdx < 0) {
1211 srcPos.error("A 'name' attribute is required for <add-resource>\n");
1212 hasErrors = localHasErrors = true;
1213 }
1214 name = String16(block.getAttributeStringValue(nameIdx, &len));
1215
1216 outTable->canAddEntry(srcPos, myPackage, typeName, name);
1217
1218 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1219 if (code == ResXMLTree::END_TAG) {
1220 if (strcmp16(block.getElementName(&len), add_resource16.string()) == 0) {
1221 break;
1222 }
1223 }
1224 }
1225 continue;
1226
1227 } else if (strcmp16(block.getElementName(&len), declare_styleable16.string()) == 0) {
1228 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1229
1230 String16 ident;
1231 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
1232 if (identIdx < 0) {
1233 srcPos.error("A 'name' attribute is required for <declare-styleable>\n");
1234 hasErrors = localHasErrors = true;
1235 }
1236 ident = String16(block.getAttributeStringValue(identIdx, &len));
1237
1238 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1239 if (!localHasErrors) {
1240 if (symbols != NULL) {
1241 symbols = symbols->addNestedSymbol(String8("styleable"), srcPos);
1242 }
1243 sp<AaptSymbols> styleSymbols = symbols;
1244 if (symbols != NULL) {
1245 symbols = symbols->addNestedSymbol(String8(ident), srcPos);
1246 }
1247 if (symbols == NULL) {
1248 srcPos.error("Unable to create symbols!\n");
1249 return UNKNOWN_ERROR;
1250 }
1251
1252 String16 comment(
1253 block.getComment(&len) ? block.getComment(&len) : nulStr);
1254 styleSymbols->appendComment(String8(ident), comment, srcPos);
1255 } else {
1256 symbols = NULL;
1257 }
1258
1259 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1260 if (code == ResXMLTree::START_TAG) {
1261 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
1262 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1263 && code != ResXMLTree::BAD_DOCUMENT) {
1264 if (code == ResXMLTree::END_TAG) {
1265 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
1266 break;
1267 }
1268 }
1269 }
1270 continue;
1271 } else if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
1272 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1273 && code != ResXMLTree::BAD_DOCUMENT) {
1274 if (code == ResXMLTree::END_TAG) {
1275 if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
1276 break;
1277 }
1278 }
1279 }
1280 continue;
1281 } else if (strcmp16(block.getElementName(&len), attr16.string()) != 0) {
1282 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1283 "Tag <%s> can not appear inside <declare-styleable>, only <attr>\n",
1284 String8(block.getElementName(&len)).string());
1285 return UNKNOWN_ERROR;
1286 }
1287
1288 String16 comment(
1289 block.getComment(&len) ? block.getComment(&len) : nulStr);
1290 String16 itemIdent;
1291 err = compileAttribute(in, block, myPackage, outTable, &itemIdent, true);
1292 if (err != NO_ERROR) {
1293 hasErrors = localHasErrors = true;
1294 }
1295
1296 if (symbols != NULL) {
1297 SourcePos srcPos(String8(in->getPrintableSource()), block.getLineNumber());
1298 symbols->addSymbol(String8(itemIdent), 0, srcPos);
1299 symbols->appendComment(String8(itemIdent), comment, srcPos);
1300 //printf("Attribute %s comment: %s\n", String8(itemIdent).string(),
1301 // String8(comment).string());
1302 }
1303 } else if (code == ResXMLTree::END_TAG) {
1304 if (strcmp16(block.getElementName(&len), declare_styleable16.string()) == 0) {
1305 break;
1306 }
1307
1308 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1309 "Found tag </%s> where </attr> is expected\n",
1310 String8(block.getElementName(&len)).string());
1311 return UNKNOWN_ERROR;
1312 }
1313 }
1314 continue;
1315
1316 } else if (strcmp16(block.getElementName(&len), attr16.string()) == 0) {
1317 err = compileAttribute(in, block, myPackage, outTable, NULL);
1318 if (err != NO_ERROR) {
1319 hasErrors = true;
1320 }
1321 continue;
1322
1323 } else if (strcmp16(block.getElementName(&len), item16.string()) == 0) {
1324 curTag = &item16;
1325 ssize_t attri = block.indexOfAttribute(NULL, "type");
1326 if (attri >= 0) {
1327 curType = String16(block.getAttributeStringValue(attri, &len));
Adrian Roos58922482015-06-01 17:59:41 -07001328 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1329 if (nameIdx >= 0) {
1330 curName = String16(block.getAttributeStringValue(nameIdx, &len));
1331 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001332 ssize_t formatIdx = block.indexOfAttribute(NULL, "format");
1333 if (formatIdx >= 0) {
1334 String16 formatStr = String16(block.getAttributeStringValue(
1335 formatIdx, &len));
1336 curFormat = parse_flags(formatStr.string(), formatStr.size(),
1337 gFormatFlags);
1338 if (curFormat == 0) {
1339 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1340 "Tag <item> 'format' attribute value \"%s\" not valid\n",
1341 String8(formatStr).string());
1342 hasErrors = localHasErrors = true;
1343 }
1344 }
1345 } else {
1346 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1347 "A 'type' attribute is required for <item>\n");
1348 hasErrors = localHasErrors = true;
1349 }
1350 curIsStyled = true;
1351 } else if (strcmp16(block.getElementName(&len), string16.string()) == 0) {
1352 // Note the existence and locale of every string we process
Narayan Kamath91447d82014-01-21 15:32:36 +00001353 char rawLocale[RESTABLE_MAX_LOCALE_LEN];
1354 curParams.getBcp47Locale(rawLocale);
Adam Lesinski282e1812014-01-23 18:17:42 -08001355 String8 locale(rawLocale);
1356 String16 name;
1357 String16 translatable;
1358 String16 formatted;
1359
1360 size_t n = block.getAttributeCount();
1361 for (size_t i = 0; i < n; i++) {
1362 size_t length;
Dan Albertf348c152014-09-08 18:28:00 -07001363 const char16_t* attr = block.getAttributeName(i, &length);
Adam Lesinski282e1812014-01-23 18:17:42 -08001364 if (strcmp16(attr, name16.string()) == 0) {
1365 name.setTo(block.getAttributeStringValue(i, &length));
1366 } else if (strcmp16(attr, translatable16.string()) == 0) {
1367 translatable.setTo(block.getAttributeStringValue(i, &length));
1368 } else if (strcmp16(attr, formatted16.string()) == 0) {
1369 formatted.setTo(block.getAttributeStringValue(i, &length));
1370 }
1371 }
1372
1373 if (name.size() > 0) {
Adrian Roos58922482015-06-01 17:59:41 -07001374 if (locale.size() == 0) {
1375 outTable->addDefaultLocalization(name);
1376 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001377 if (translatable == false16) {
1378 curIsFormatted = false;
1379 // Untranslatable strings must only exist in the default [empty] locale
1380 if (locale.size() > 0) {
Adam Lesinskia01a9372014-03-20 18:04:57 -07001381 SourcePos(in->getPrintableSource(), block.getLineNumber()).warning(
1382 "string '%s' marked untranslatable but exists in locale '%s'\n",
1383 String8(name).string(),
Adam Lesinski282e1812014-01-23 18:17:42 -08001384 locale.string());
1385 // hasErrors = localHasErrors = true;
1386 } else {
1387 // Intentionally empty block:
1388 //
1389 // Don't add untranslatable strings to the localization table; that
1390 // way if we later see localizations of them, they'll be flagged as
1391 // having no default translation.
1392 }
1393 } else {
Adam Lesinskia01a9372014-03-20 18:04:57 -07001394 outTable->addLocalization(
1395 name,
1396 locale,
1397 SourcePos(in->getPrintableSource(), block.getLineNumber()));
Adam Lesinski282e1812014-01-23 18:17:42 -08001398 }
1399
1400 if (formatted == false16) {
1401 curIsFormatted = false;
1402 }
1403 }
1404
1405 curTag = &string16;
1406 curType = string16;
1407 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
1408 curIsStyled = true;
Igor Viarheichyk84410b02014-04-30 11:56:42 -07001409 curIsPseudolocalizable = fileIsTranslatable && (translatable != false16);
Adam Lesinski282e1812014-01-23 18:17:42 -08001410 } else if (strcmp16(block.getElementName(&len), drawable16.string()) == 0) {
1411 curTag = &drawable16;
1412 curType = drawable16;
1413 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
1414 } else if (strcmp16(block.getElementName(&len), color16.string()) == 0) {
1415 curTag = &color16;
1416 curType = color16;
1417 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
1418 } else if (strcmp16(block.getElementName(&len), bool16.string()) == 0) {
1419 curTag = &bool16;
1420 curType = bool16;
1421 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_BOOLEAN;
1422 } else if (strcmp16(block.getElementName(&len), integer16.string()) == 0) {
1423 curTag = &integer16;
1424 curType = integer16;
1425 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
1426 } else if (strcmp16(block.getElementName(&len), dimen16.string()) == 0) {
1427 curTag = &dimen16;
1428 curType = dimen16;
1429 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_DIMENSION;
1430 } else if (strcmp16(block.getElementName(&len), fraction16.string()) == 0) {
1431 curTag = &fraction16;
1432 curType = fraction16;
1433 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_FRACTION;
1434 } else if (strcmp16(block.getElementName(&len), bag16.string()) == 0) {
1435 curTag = &bag16;
1436 curIsBag = true;
1437 ssize_t attri = block.indexOfAttribute(NULL, "type");
1438 if (attri >= 0) {
1439 curType = String16(block.getAttributeStringValue(attri, &len));
1440 } else {
1441 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1442 "A 'type' attribute is required for <bag>\n");
1443 hasErrors = localHasErrors = true;
1444 }
1445 } else if (strcmp16(block.getElementName(&len), style16.string()) == 0) {
1446 curTag = &style16;
1447 curType = style16;
1448 curIsBag = true;
1449 } else if (strcmp16(block.getElementName(&len), plurals16.string()) == 0) {
1450 curTag = &plurals16;
1451 curType = plurals16;
1452 curIsBag = true;
Anton Krumina2ef5c02014-03-12 14:46:44 -07001453 curIsPseudolocalizable = fileIsTranslatable;
Adam Lesinski282e1812014-01-23 18:17:42 -08001454 } else if (strcmp16(block.getElementName(&len), array16.string()) == 0) {
1455 curTag = &array16;
1456 curType = array16;
1457 curIsBag = true;
1458 curIsBagReplaceOnOverwrite = true;
1459 ssize_t formatIdx = block.indexOfAttribute(NULL, "format");
1460 if (formatIdx >= 0) {
1461 String16 formatStr = String16(block.getAttributeStringValue(
1462 formatIdx, &len));
1463 curFormat = parse_flags(formatStr.string(), formatStr.size(),
1464 gFormatFlags);
1465 if (curFormat == 0) {
1466 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1467 "Tag <array> 'format' attribute value \"%s\" not valid\n",
1468 String8(formatStr).string());
1469 hasErrors = localHasErrors = true;
1470 }
1471 }
1472 } else if (strcmp16(block.getElementName(&len), string_array16.string()) == 0) {
1473 // Check whether these strings need valid formats.
1474 // (simplified form of what string16 does above)
Anton Krumina2ef5c02014-03-12 14:46:44 -07001475 bool isTranslatable = false;
Adam Lesinski282e1812014-01-23 18:17:42 -08001476 size_t n = block.getAttributeCount();
Narayan Kamath9a9fa162013-12-18 13:27:30 +00001477
1478 // Pseudolocalizable by default, unless this string array isn't
1479 // translatable.
Adam Lesinski282e1812014-01-23 18:17:42 -08001480 for (size_t i = 0; i < n; i++) {
1481 size_t length;
Dan Albertf348c152014-09-08 18:28:00 -07001482 const char16_t* attr = block.getAttributeName(i, &length);
Narayan Kamath9a9fa162013-12-18 13:27:30 +00001483 if (strcmp16(attr, formatted16.string()) == 0) {
Dan Albertf348c152014-09-08 18:28:00 -07001484 const char16_t* value = block.getAttributeStringValue(i, &length);
Adam Lesinski282e1812014-01-23 18:17:42 -08001485 if (strcmp16(value, false16.string()) == 0) {
1486 curIsFormatted = false;
Adam Lesinski282e1812014-01-23 18:17:42 -08001487 }
Anton Krumina2ef5c02014-03-12 14:46:44 -07001488 } else if (strcmp16(attr, translatable16.string()) == 0) {
Dan Albertf348c152014-09-08 18:28:00 -07001489 const char16_t* value = block.getAttributeStringValue(i, &length);
Anton Krumina2ef5c02014-03-12 14:46:44 -07001490 if (strcmp16(value, false16.string()) == 0) {
1491 isTranslatable = false;
1492 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001493 }
1494 }
1495
1496 curTag = &string_array16;
1497 curType = array16;
1498 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
1499 curIsBag = true;
1500 curIsBagReplaceOnOverwrite = true;
Anton Krumina2ef5c02014-03-12 14:46:44 -07001501 curIsPseudolocalizable = isTranslatable && fileIsTranslatable;
Adam Lesinski282e1812014-01-23 18:17:42 -08001502 } else if (strcmp16(block.getElementName(&len), integer_array16.string()) == 0) {
1503 curTag = &integer_array16;
1504 curType = array16;
1505 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
1506 curIsBag = true;
1507 curIsBagReplaceOnOverwrite = true;
1508 } else {
1509 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1510 "Found tag %s where item is expected\n",
1511 String8(block.getElementName(&len)).string());
1512 return UNKNOWN_ERROR;
1513 }
1514
1515 String16 ident;
1516 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
1517 if (identIdx >= 0) {
1518 ident = String16(block.getAttributeStringValue(identIdx, &len));
1519 } else {
1520 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1521 "A 'name' attribute is required for <%s>\n",
1522 String8(*curTag).string());
1523 hasErrors = localHasErrors = true;
1524 }
1525
1526 String16 product;
1527 identIdx = block.indexOfAttribute(NULL, "product");
1528 if (identIdx >= 0) {
1529 product = String16(block.getAttributeStringValue(identIdx, &len));
1530 }
1531
1532 String16 comment(block.getComment(&len) ? block.getComment(&len) : nulStr);
1533
1534 if (curIsBag) {
1535 // Figure out the parent of this bag...
1536 String16 parentIdent;
1537 ssize_t parentIdentIdx = block.indexOfAttribute(NULL, "parent");
1538 if (parentIdentIdx >= 0) {
1539 parentIdent = String16(block.getAttributeStringValue(parentIdentIdx, &len));
1540 } else {
1541 ssize_t sep = ident.findLast('.');
1542 if (sep >= 0) {
1543 parentIdent.setTo(ident, sep);
1544 }
1545 }
1546
1547 if (!localHasErrors) {
1548 err = outTable->startBag(SourcePos(in->getPrintableSource(),
1549 block.getLineNumber()), myPackage, curType, ident,
1550 parentIdent, &curParams,
1551 overwrite, curIsBagReplaceOnOverwrite);
1552 if (err != NO_ERROR) {
1553 hasErrors = localHasErrors = true;
1554 }
1555 }
1556
1557 ssize_t elmIndex = 0;
1558 char elmIndexStr[14];
1559 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1560 && code != ResXMLTree::BAD_DOCUMENT) {
1561
1562 if (code == ResXMLTree::START_TAG) {
1563 if (strcmp16(block.getElementName(&len), item16.string()) != 0) {
1564 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1565 "Tag <%s> can not appear inside <%s>, only <item>\n",
1566 String8(block.getElementName(&len)).string(),
1567 String8(*curTag).string());
1568 return UNKNOWN_ERROR;
1569 }
1570
1571 String16 itemIdent;
1572 if (curType == array16) {
1573 sprintf(elmIndexStr, "^index_%d", (int)elmIndex++);
1574 itemIdent = String16(elmIndexStr);
1575 } else if (curType == plurals16) {
1576 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "quantity");
1577 if (itemIdentIdx >= 0) {
1578 String16 quantity16(block.getAttributeStringValue(itemIdentIdx, &len));
1579 if (quantity16 == other16) {
1580 itemIdent = quantityOther16;
1581 }
1582 else if (quantity16 == zero16) {
1583 itemIdent = quantityZero16;
1584 }
1585 else if (quantity16 == one16) {
1586 itemIdent = quantityOne16;
1587 }
1588 else if (quantity16 == two16) {
1589 itemIdent = quantityTwo16;
1590 }
1591 else if (quantity16 == few16) {
1592 itemIdent = quantityFew16;
1593 }
1594 else if (quantity16 == many16) {
1595 itemIdent = quantityMany16;
1596 }
1597 else {
1598 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1599 "Illegal 'quantity' attribute is <item> inside <plurals>\n");
1600 hasErrors = localHasErrors = true;
1601 }
1602 } else {
1603 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1604 "A 'quantity' attribute is required for <item> inside <plurals>\n");
1605 hasErrors = localHasErrors = true;
1606 }
1607 } else {
1608 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "name");
1609 if (itemIdentIdx >= 0) {
1610 itemIdent = String16(block.getAttributeStringValue(itemIdentIdx, &len));
1611 } else {
1612 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1613 "A 'name' attribute is required for <item>\n");
1614 hasErrors = localHasErrors = true;
1615 }
1616 }
1617
1618 ResXMLParser::ResXMLPosition parserPosition;
1619 block.getPosition(&parserPosition);
1620
1621 err = parseAndAddBag(bundle, in, &block, curParams, myPackage, curType,
1622 ident, parentIdent, itemIdent, curFormat, curIsFormatted,
Anton Krumina2ef5c02014-03-12 14:46:44 -07001623 product, NO_PSEUDOLOCALIZATION, overwrite, outTable);
Adam Lesinski282e1812014-01-23 18:17:42 -08001624 if (err == NO_ERROR) {
1625 if (curIsPseudolocalizable && localeIsDefined(curParams)
Anton Krumina2ef5c02014-03-12 14:46:44 -07001626 && bundle->getPseudolocalize() > 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001627 // pseudolocalize here
Anton Krumina2ef5c02014-03-12 14:46:44 -07001628 if ((PSEUDO_ACCENTED & bundle->getPseudolocalize()) ==
1629 PSEUDO_ACCENTED) {
1630 block.setPosition(parserPosition);
1631 err = parseAndAddBag(bundle, in, &block, pseudoParams, myPackage,
1632 curType, ident, parentIdent, itemIdent, curFormat,
1633 curIsFormatted, product, PSEUDO_ACCENTED,
1634 overwrite, outTable);
1635 }
1636 if ((PSEUDO_BIDI & bundle->getPseudolocalize()) ==
1637 PSEUDO_BIDI) {
1638 block.setPosition(parserPosition);
1639 err = parseAndAddBag(bundle, in, &block, pseudoBidiParams, myPackage,
1640 curType, ident, parentIdent, itemIdent, curFormat,
1641 curIsFormatted, product, PSEUDO_BIDI,
1642 overwrite, outTable);
1643 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001644 }
Anton Krumina2ef5c02014-03-12 14:46:44 -07001645 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001646 if (err != NO_ERROR) {
1647 hasErrors = localHasErrors = true;
1648 }
1649 } else if (code == ResXMLTree::END_TAG) {
1650 if (strcmp16(block.getElementName(&len), curTag->string()) != 0) {
1651 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1652 "Found tag </%s> where </%s> is expected\n",
1653 String8(block.getElementName(&len)).string(),
1654 String8(*curTag).string());
1655 return UNKNOWN_ERROR;
1656 }
1657 break;
1658 }
1659 }
1660 } else {
1661 ResXMLParser::ResXMLPosition parserPosition;
1662 block.getPosition(&parserPosition);
1663
1664 err = parseAndAddEntry(bundle, in, &block, curParams, myPackage, curType, ident,
1665 *curTag, curIsStyled, curFormat, curIsFormatted,
Anton Krumina2ef5c02014-03-12 14:46:44 -07001666 product, NO_PSEUDOLOCALIZATION, overwrite, &skippedResourceNames, outTable);
Adam Lesinski282e1812014-01-23 18:17:42 -08001667
1668 if (err < NO_ERROR) { // Why err < NO_ERROR instead of err != NO_ERROR?
1669 hasErrors = localHasErrors = true;
1670 }
1671 else if (err == NO_ERROR) {
Adrian Roos58922482015-06-01 17:59:41 -07001672 if (curType == string16 && !curParams.language[0] && !curParams.country[0]) {
1673 outTable->addDefaultLocalization(curName);
1674 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001675 if (curIsPseudolocalizable && localeIsDefined(curParams)
Anton Krumina2ef5c02014-03-12 14:46:44 -07001676 && bundle->getPseudolocalize() > 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001677 // pseudolocalize here
Anton Krumina2ef5c02014-03-12 14:46:44 -07001678 if ((PSEUDO_ACCENTED & bundle->getPseudolocalize()) ==
1679 PSEUDO_ACCENTED) {
1680 block.setPosition(parserPosition);
1681 err = parseAndAddEntry(bundle, in, &block, pseudoParams, myPackage, curType,
1682 ident, *curTag, curIsStyled, curFormat,
1683 curIsFormatted, product,
1684 PSEUDO_ACCENTED, overwrite, &skippedResourceNames, outTable);
1685 }
1686 if ((PSEUDO_BIDI & bundle->getPseudolocalize()) ==
1687 PSEUDO_BIDI) {
1688 block.setPosition(parserPosition);
1689 err = parseAndAddEntry(bundle, in, &block, pseudoBidiParams,
1690 myPackage, curType, ident, *curTag, curIsStyled, curFormat,
1691 curIsFormatted, product,
1692 PSEUDO_BIDI, overwrite, &skippedResourceNames, outTable);
1693 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001694 if (err != NO_ERROR) {
1695 hasErrors = localHasErrors = true;
1696 }
1697 }
1698 }
1699 }
1700
1701#if 0
1702 if (comment.size() > 0) {
1703 printf("Comment for @%s:%s/%s: %s\n", String8(myPackage).string(),
1704 String8(curType).string(), String8(ident).string(),
1705 String8(comment).string());
1706 }
1707#endif
1708 if (!localHasErrors) {
1709 outTable->appendComment(myPackage, curType, ident, comment, false);
1710 }
1711 }
1712 else if (code == ResXMLTree::END_TAG) {
1713 if (strcmp16(block.getElementName(&len), resources16.string()) != 0) {
1714 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1715 "Unexpected end tag %s\n", String8(block.getElementName(&len)).string());
1716 return UNKNOWN_ERROR;
1717 }
1718 }
1719 else if (code == ResXMLTree::START_NAMESPACE || code == ResXMLTree::END_NAMESPACE) {
1720 }
1721 else if (code == ResXMLTree::TEXT) {
1722 if (isWhitespace(block.getText(&len))) {
1723 continue;
1724 }
1725 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1726 "Found text \"%s\" where item tag is expected\n",
1727 String8(block.getText(&len)).string());
1728 return UNKNOWN_ERROR;
1729 }
1730 }
1731
Adam Lesinski8ff15b42013-10-07 16:54:01 -07001732 // For every resource defined, there must be exist one variant with a product attribute
1733 // set to 'default' (or no product attribute at all).
1734 // We check to see that for every resource that was ignored because of a mismatched
1735 // product attribute, some product variant of that resource was processed.
1736 for (size_t i = 0; i < skippedResourceNames.size(); i++) {
1737 if (skippedResourceNames[i]) {
1738 const type_ident_pair_t& p = skippedResourceNames.keyAt(i);
1739 if (!outTable->hasBagOrEntry(myPackage, p.type, p.ident)) {
1740 const char* bundleProduct =
1741 (bundle->getProduct() == NULL) ? "" : bundle->getProduct();
1742 fprintf(stderr, "In resource file %s: %s\n",
1743 in->getPrintableSource().string(),
1744 curParams.toString().string());
1745
1746 fprintf(stderr, "\t%s '%s' does not match product %s.\n"
1747 "\tYou may have forgotten to include a 'default' product variant"
1748 " of the resource.\n",
1749 String8(p.type).string(), String8(p.ident).string(),
1750 bundleProduct[0] == 0 ? "default" : bundleProduct);
1751 return UNKNOWN_ERROR;
1752 }
1753 }
1754 }
1755
Andreas Gampe2412f842014-09-30 20:55:57 -07001756 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001757}
1758
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001759ResourceTable::ResourceTable(Bundle* bundle, const String16& assetsPackage, ResourceTable::PackageType type)
1760 : mAssetsPackage(assetsPackage)
1761 , mPackageType(type)
1762 , mTypeIdOffset(0)
1763 , mNumLocal(0)
1764 , mBundle(bundle)
Adam Lesinski282e1812014-01-23 18:17:42 -08001765{
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001766 ssize_t packageId = -1;
1767 switch (mPackageType) {
1768 case App:
1769 case AppFeature:
1770 packageId = 0x7f;
1771 break;
1772
1773 case System:
1774 packageId = 0x01;
1775 break;
1776
1777 case SharedLibrary:
1778 packageId = 0x00;
1779 break;
1780
1781 default:
1782 assert(0);
1783 break;
1784 }
1785 sp<Package> package = new Package(mAssetsPackage, packageId);
1786 mPackages.add(assetsPackage, package);
1787 mOrderedPackages.add(package);
1788
1789 // Every resource table always has one first entry, the bag attributes.
1790 const SourcePos unknown(String8("????"), 0);
1791 getType(mAssetsPackage, String16("attr"), unknown);
1792}
1793
1794static uint32_t findLargestTypeIdForPackage(const ResTable& table, const String16& packageName) {
1795 const size_t basePackageCount = table.getBasePackageCount();
1796 for (size_t i = 0; i < basePackageCount; i++) {
1797 if (packageName == table.getBasePackageName(i)) {
1798 return table.getLastTypeIdForPackage(i);
1799 }
1800 }
1801 return 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08001802}
1803
1804status_t ResourceTable::addIncludedResources(Bundle* bundle, const sp<AaptAssets>& assets)
1805{
1806 status_t err = assets->buildIncludedResources(bundle);
1807 if (err != NO_ERROR) {
1808 return err;
1809 }
1810
Adam Lesinski282e1812014-01-23 18:17:42 -08001811 mAssets = assets;
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001812 mTypeIdOffset = findLargestTypeIdForPackage(assets->getIncludedResources(), mAssetsPackage);
Adam Lesinski282e1812014-01-23 18:17:42 -08001813
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001814 const String8& featureAfter = bundle->getFeatureAfterPackage();
1815 if (!featureAfter.isEmpty()) {
1816 AssetManager featureAssetManager;
1817 if (!featureAssetManager.addAssetPath(featureAfter, NULL)) {
1818 fprintf(stderr, "ERROR: Feature package '%s' not found.\n",
1819 featureAfter.string());
1820 return UNKNOWN_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001821 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001822
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001823 const ResTable& featureTable = featureAssetManager.getResources(false);
Dan Albert030f5362015-03-04 13:54:20 -08001824 mTypeIdOffset = std::max(mTypeIdOffset,
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001825 findLargestTypeIdForPackage(featureTable, mAssetsPackage));
1826 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001827
1828 return NO_ERROR;
1829}
1830
1831status_t ResourceTable::addPublic(const SourcePos& sourcePos,
1832 const String16& package,
1833 const String16& type,
1834 const String16& name,
1835 const uint32_t ident)
1836{
1837 uint32_t rid = mAssets->getIncludedResources()
1838 .identifierForName(name.string(), name.size(),
1839 type.string(), type.size(),
1840 package.string(), package.size());
1841 if (rid != 0) {
1842 sourcePos.error("Error declaring public resource %s/%s for included package %s\n",
1843 String8(type).string(), String8(name).string(),
1844 String8(package).string());
1845 return UNKNOWN_ERROR;
1846 }
1847
1848 sp<Type> t = getType(package, type, sourcePos);
1849 if (t == NULL) {
1850 return UNKNOWN_ERROR;
1851 }
1852 return t->addPublic(sourcePos, name, ident);
1853}
1854
1855status_t ResourceTable::addEntry(const SourcePos& sourcePos,
1856 const String16& package,
1857 const String16& type,
1858 const String16& name,
1859 const String16& value,
1860 const Vector<StringPool::entry_style_span>* style,
1861 const ResTable_config* params,
1862 const bool doSetIndex,
1863 const int32_t format,
1864 const bool overwrite)
1865{
Adam Lesinski282e1812014-01-23 18:17:42 -08001866 uint32_t rid = mAssets->getIncludedResources()
1867 .identifierForName(name.string(), name.size(),
1868 type.string(), type.size(),
1869 package.string(), package.size());
1870 if (rid != 0) {
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001871 sourcePos.error("Resource entry %s/%s is already defined in package %s.",
1872 String8(type).string(), String8(name).string(), String8(package).string());
1873 return UNKNOWN_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001874 }
1875
Adam Lesinski282e1812014-01-23 18:17:42 -08001876 sp<Entry> e = getEntry(package, type, name, sourcePos, overwrite,
1877 params, doSetIndex);
1878 if (e == NULL) {
1879 return UNKNOWN_ERROR;
1880 }
1881 status_t err = e->setItem(sourcePos, value, style, format, overwrite);
1882 if (err == NO_ERROR) {
1883 mNumLocal++;
1884 }
1885 return err;
1886}
1887
1888status_t ResourceTable::startBag(const SourcePos& sourcePos,
1889 const String16& package,
1890 const String16& type,
1891 const String16& name,
1892 const String16& bagParent,
1893 const ResTable_config* params,
1894 bool overlay,
Andreas Gampe2412f842014-09-30 20:55:57 -07001895 bool replace, bool /* isId */)
Adam Lesinski282e1812014-01-23 18:17:42 -08001896{
1897 status_t result = NO_ERROR;
1898
1899 // Check for adding entries in other packages... for now we do
1900 // nothing. We need to do the right thing here to support skinning.
1901 uint32_t rid = mAssets->getIncludedResources()
1902 .identifierForName(name.string(), name.size(),
1903 type.string(), type.size(),
1904 package.string(), package.size());
1905 if (rid != 0) {
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001906 sourcePos.error("Resource entry %s/%s is already defined in package %s.",
1907 String8(type).string(), String8(name).string(), String8(package).string());
1908 return UNKNOWN_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001909 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001910
Adam Lesinski282e1812014-01-23 18:17:42 -08001911 if (overlay && !mBundle->getAutoAddOverlay() && !hasBagOrEntry(package, type, name)) {
1912 bool canAdd = false;
1913 sp<Package> p = mPackages.valueFor(package);
1914 if (p != NULL) {
1915 sp<Type> t = p->getTypes().valueFor(type);
1916 if (t != NULL) {
1917 if (t->getCanAddEntries().indexOf(name) >= 0) {
1918 canAdd = true;
1919 }
1920 }
1921 }
1922 if (!canAdd) {
1923 sourcePos.error("Resource does not already exist in overlay at '%s'; use <add-resource> to add.\n",
1924 String8(name).string());
1925 return UNKNOWN_ERROR;
1926 }
1927 }
1928 sp<Entry> e = getEntry(package, type, name, sourcePos, overlay, params);
1929 if (e == NULL) {
1930 return UNKNOWN_ERROR;
1931 }
1932
1933 // If a parent is explicitly specified, set it.
1934 if (bagParent.size() > 0) {
1935 e->setParent(bagParent);
1936 }
1937
1938 if ((result = e->makeItABag(sourcePos)) != NO_ERROR) {
1939 return result;
1940 }
1941
1942 if (overlay && replace) {
1943 return e->emptyBag(sourcePos);
1944 }
1945 return result;
1946}
1947
1948status_t ResourceTable::addBag(const SourcePos& sourcePos,
1949 const String16& package,
1950 const String16& type,
1951 const String16& name,
1952 const String16& bagParent,
1953 const String16& bagKey,
1954 const String16& value,
1955 const Vector<StringPool::entry_style_span>* style,
1956 const ResTable_config* params,
1957 bool replace, bool isId, const int32_t format)
1958{
1959 // Check for adding entries in other packages... for now we do
1960 // nothing. We need to do the right thing here to support skinning.
1961 uint32_t rid = mAssets->getIncludedResources()
1962 .identifierForName(name.string(), name.size(),
1963 type.string(), type.size(),
1964 package.string(), package.size());
1965 if (rid != 0) {
1966 return NO_ERROR;
1967 }
1968
1969#if 0
1970 if (name == String16("left")) {
1971 printf("Adding bag left: file=%s, line=%d, type=%s\n",
1972 sourcePos.file.striing(), sourcePos.line, String8(type).string());
1973 }
1974#endif
1975 sp<Entry> e = getEntry(package, type, name, sourcePos, replace, params);
1976 if (e == NULL) {
1977 return UNKNOWN_ERROR;
1978 }
1979
1980 // If a parent is explicitly specified, set it.
1981 if (bagParent.size() > 0) {
1982 e->setParent(bagParent);
1983 }
1984
1985 const bool first = e->getBag().indexOfKey(bagKey) < 0;
1986 status_t err = e->addToBag(sourcePos, bagKey, value, style, replace, isId, format);
1987 if (err == NO_ERROR && first) {
1988 mNumLocal++;
1989 }
1990 return err;
1991}
1992
1993bool ResourceTable::hasBagOrEntry(const String16& package,
1994 const String16& type,
1995 const String16& name) const
1996{
1997 // First look for this in the included resources...
1998 uint32_t rid = mAssets->getIncludedResources()
1999 .identifierForName(name.string(), name.size(),
2000 type.string(), type.size(),
2001 package.string(), package.size());
2002 if (rid != 0) {
2003 return true;
2004 }
2005
2006 sp<Package> p = mPackages.valueFor(package);
2007 if (p != NULL) {
2008 sp<Type> t = p->getTypes().valueFor(type);
2009 if (t != NULL) {
2010 sp<ConfigList> c = t->getConfigs().valueFor(name);
2011 if (c != NULL) return true;
2012 }
2013 }
2014
2015 return false;
2016}
2017
2018bool ResourceTable::hasBagOrEntry(const String16& package,
2019 const String16& type,
2020 const String16& name,
2021 const ResTable_config& config) const
2022{
2023 // First look for this in the included resources...
2024 uint32_t rid = mAssets->getIncludedResources()
2025 .identifierForName(name.string(), name.size(),
2026 type.string(), type.size(),
2027 package.string(), package.size());
2028 if (rid != 0) {
2029 return true;
2030 }
2031
2032 sp<Package> p = mPackages.valueFor(package);
2033 if (p != NULL) {
2034 sp<Type> t = p->getTypes().valueFor(type);
2035 if (t != NULL) {
2036 sp<ConfigList> c = t->getConfigs().valueFor(name);
2037 if (c != NULL) {
2038 sp<Entry> e = c->getEntries().valueFor(config);
2039 if (e != NULL) {
2040 return true;
2041 }
2042 }
2043 }
2044 }
2045
2046 return false;
2047}
2048
2049bool ResourceTable::hasBagOrEntry(const String16& ref,
2050 const String16* defType,
2051 const String16* defPackage)
2052{
2053 String16 package, type, name;
2054 if (!ResTable::expandResourceRef(ref.string(), ref.size(), &package, &type, &name,
2055 defType, defPackage ? defPackage:&mAssetsPackage, NULL)) {
2056 return false;
2057 }
2058 return hasBagOrEntry(package, type, name);
2059}
2060
2061bool ResourceTable::appendComment(const String16& package,
2062 const String16& type,
2063 const String16& name,
2064 const String16& comment,
2065 bool onlyIfEmpty)
2066{
2067 if (comment.size() <= 0) {
2068 return true;
2069 }
2070
2071 sp<Package> p = mPackages.valueFor(package);
2072 if (p != NULL) {
2073 sp<Type> t = p->getTypes().valueFor(type);
2074 if (t != NULL) {
2075 sp<ConfigList> c = t->getConfigs().valueFor(name);
2076 if (c != NULL) {
2077 c->appendComment(comment, onlyIfEmpty);
2078 return true;
2079 }
2080 }
2081 }
2082 return false;
2083}
2084
2085bool ResourceTable::appendTypeComment(const String16& package,
2086 const String16& type,
2087 const String16& name,
2088 const String16& comment)
2089{
2090 if (comment.size() <= 0) {
2091 return true;
2092 }
2093
2094 sp<Package> p = mPackages.valueFor(package);
2095 if (p != NULL) {
2096 sp<Type> t = p->getTypes().valueFor(type);
2097 if (t != NULL) {
2098 sp<ConfigList> c = t->getConfigs().valueFor(name);
2099 if (c != NULL) {
2100 c->appendTypeComment(comment);
2101 return true;
2102 }
2103 }
2104 }
2105 return false;
2106}
2107
2108void ResourceTable::canAddEntry(const SourcePos& pos,
2109 const String16& package, const String16& type, const String16& name)
2110{
2111 sp<Type> t = getType(package, type, pos);
2112 if (t != NULL) {
2113 t->canAddEntry(name);
2114 }
2115}
2116
2117size_t ResourceTable::size() const {
2118 return mPackages.size();
2119}
2120
2121size_t ResourceTable::numLocalResources() const {
2122 return mNumLocal;
2123}
2124
2125bool ResourceTable::hasResources() const {
2126 return mNumLocal > 0;
2127}
2128
Adam Lesinski27f69f42014-08-21 13:19:12 -07002129sp<AaptFile> ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& filter,
2130 const bool isBase)
Adam Lesinski282e1812014-01-23 18:17:42 -08002131{
2132 sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
Adam Lesinski27f69f42014-08-21 13:19:12 -07002133 status_t err = flatten(bundle, filter, data, isBase);
Adam Lesinski282e1812014-01-23 18:17:42 -08002134 return err == NO_ERROR ? data : NULL;
2135}
2136
2137inline uint32_t ResourceTable::getResId(const sp<Package>& p,
2138 const sp<Type>& t,
2139 uint32_t nameId)
2140{
2141 return makeResId(p->getAssignedId(), t->getIndex(), nameId);
2142}
2143
2144uint32_t ResourceTable::getResId(const String16& package,
2145 const String16& type,
2146 const String16& name,
2147 bool onlyPublic) const
2148{
2149 uint32_t id = ResourceIdCache::lookup(package, type, name, onlyPublic);
2150 if (id != 0) return id; // cache hit
2151
Adam Lesinski282e1812014-01-23 18:17:42 -08002152 // First look for this in the included resources...
2153 uint32_t specFlags = 0;
2154 uint32_t rid = mAssets->getIncludedResources()
2155 .identifierForName(name.string(), name.size(),
2156 type.string(), type.size(),
2157 package.string(), package.size(),
2158 &specFlags);
2159 if (rid != 0) {
2160 if (onlyPublic) {
2161 if ((specFlags & ResTable_typeSpec::SPEC_PUBLIC) == 0) {
2162 return 0;
2163 }
2164 }
2165
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002166 return ResourceIdCache::store(package, type, name, onlyPublic, rid);
Adam Lesinski282e1812014-01-23 18:17:42 -08002167 }
2168
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002169 sp<Package> p = mPackages.valueFor(package);
2170 if (p == NULL) return 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08002171 sp<Type> t = p->getTypes().valueFor(type);
2172 if (t == NULL) return 0;
Adam Lesinski9b624c12014-11-19 17:49:26 -08002173 sp<ConfigList> c = t->getConfigs().valueFor(name);
2174 if (c == NULL) {
2175 if (type != String16("attr")) {
2176 return 0;
2177 }
2178 t = p->getTypes().valueFor(String16(kAttrPrivateType));
2179 if (t == NULL) return 0;
2180 c = t->getConfigs().valueFor(name);
2181 if (c == NULL) return 0;
2182 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002183 int32_t ei = c->getEntryIndex();
2184 if (ei < 0) return 0;
2185
2186 return ResourceIdCache::store(package, type, name, onlyPublic,
2187 getResId(p, t, ei));
2188}
2189
2190uint32_t ResourceTable::getResId(const String16& ref,
2191 const String16* defType,
2192 const String16* defPackage,
2193 const char** outErrorMsg,
2194 bool onlyPublic) const
2195{
2196 String16 package, type, name;
2197 bool refOnlyPublic = true;
2198 if (!ResTable::expandResourceRef(
2199 ref.string(), ref.size(), &package, &type, &name,
2200 defType, defPackage ? defPackage:&mAssetsPackage,
2201 outErrorMsg, &refOnlyPublic)) {
Andreas Gampe2412f842014-09-30 20:55:57 -07002202 if (kIsDebug) {
2203 printf("Expanding resource: ref=%s\n", String8(ref).string());
2204 printf("Expanding resource: defType=%s\n",
2205 defType ? String8(*defType).string() : "NULL");
2206 printf("Expanding resource: defPackage=%s\n",
2207 defPackage ? String8(*defPackage).string() : "NULL");
2208 printf("Expanding resource: ref=%s\n", String8(ref).string());
2209 printf("Expanded resource: p=%s, t=%s, n=%s, res=0\n",
2210 String8(package).string(), String8(type).string(),
2211 String8(name).string());
2212 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002213 return 0;
2214 }
2215 uint32_t res = getResId(package, type, name, onlyPublic && refOnlyPublic);
Andreas Gampe2412f842014-09-30 20:55:57 -07002216 if (kIsDebug) {
2217 printf("Expanded resource: p=%s, t=%s, n=%s, res=%d\n",
2218 String8(package).string(), String8(type).string(),
2219 String8(name).string(), res);
2220 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002221 if (res == 0) {
2222 if (outErrorMsg)
2223 *outErrorMsg = "No resource found that matches the given name";
2224 }
2225 return res;
2226}
2227
2228bool ResourceTable::isValidResourceName(const String16& s)
2229{
2230 const char16_t* p = s.string();
2231 bool first = true;
2232 while (*p) {
2233 if ((*p >= 'a' && *p <= 'z')
2234 || (*p >= 'A' && *p <= 'Z')
2235 || *p == '_'
2236 || (!first && *p >= '0' && *p <= '9')) {
2237 first = false;
2238 p++;
2239 continue;
2240 }
2241 return false;
2242 }
2243 return true;
2244}
2245
2246bool ResourceTable::stringToValue(Res_value* outValue, StringPool* pool,
2247 const String16& str,
2248 bool preserveSpaces, bool coerceType,
2249 uint32_t attrID,
2250 const Vector<StringPool::entry_style_span>* style,
2251 String16* outStr, void* accessorCookie,
2252 uint32_t attrType, const String8* configTypeName,
2253 const ConfigDescription* config)
2254{
2255 String16 finalStr;
2256
2257 bool res = true;
2258 if (style == NULL || style->size() == 0) {
2259 // Text is not styled so it can be any type... let's figure it out.
2260 res = mAssets->getIncludedResources()
2261 .stringToValue(outValue, &finalStr, str.string(), str.size(), preserveSpaces,
2262 coerceType, attrID, NULL, &mAssetsPackage, this,
2263 accessorCookie, attrType);
2264 } else {
2265 // Styled text can only be a string, and while collecting the style
2266 // information we have already processed that string!
2267 outValue->size = sizeof(Res_value);
2268 outValue->res0 = 0;
2269 outValue->dataType = outValue->TYPE_STRING;
2270 outValue->data = 0;
2271 finalStr = str;
2272 }
2273
2274 if (!res) {
2275 return false;
2276 }
2277
2278 if (outValue->dataType == outValue->TYPE_STRING) {
2279 // Should do better merging styles.
2280 if (pool) {
2281 String8 configStr;
2282 if (config != NULL) {
2283 configStr = config->toString();
2284 } else {
2285 configStr = "(null)";
2286 }
Andreas Gampe2412f842014-09-30 20:55:57 -07002287 if (kIsDebug) {
2288 printf("Adding to pool string style #%zu config %s: %s\n",
2289 style != NULL ? style->size() : 0U,
2290 configStr.string(), String8(finalStr).string());
2291 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002292 if (style != NULL && style->size() > 0) {
2293 outValue->data = pool->add(finalStr, *style, configTypeName, config);
2294 } else {
2295 outValue->data = pool->add(finalStr, true, configTypeName, config);
2296 }
2297 } else {
2298 // Caller will fill this in later.
2299 outValue->data = 0;
2300 }
2301
2302 if (outStr) {
2303 *outStr = finalStr;
2304 }
2305
2306 }
2307
2308 return true;
2309}
2310
2311uint32_t ResourceTable::getCustomResource(
2312 const String16& package, const String16& type, const String16& name) const
2313{
2314 //printf("getCustomResource: %s %s %s\n", String8(package).string(),
2315 // String8(type).string(), String8(name).string());
2316 sp<Package> p = mPackages.valueFor(package);
2317 if (p == NULL) return 0;
2318 sp<Type> t = p->getTypes().valueFor(type);
2319 if (t == NULL) return 0;
2320 sp<ConfigList> c = t->getConfigs().valueFor(name);
Adam Lesinski9b624c12014-11-19 17:49:26 -08002321 if (c == NULL) {
2322 if (type != String16("attr")) {
2323 return 0;
2324 }
2325 t = p->getTypes().valueFor(String16(kAttrPrivateType));
2326 if (t == NULL) return 0;
2327 c = t->getConfigs().valueFor(name);
2328 if (c == NULL) return 0;
2329 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002330 int32_t ei = c->getEntryIndex();
2331 if (ei < 0) return 0;
2332 return getResId(p, t, ei);
2333}
2334
2335uint32_t ResourceTable::getCustomResourceWithCreation(
2336 const String16& package, const String16& type, const String16& name,
2337 const bool createIfNotFound)
2338{
2339 uint32_t resId = getCustomResource(package, type, name);
2340 if (resId != 0 || !createIfNotFound) {
2341 return resId;
2342 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002343
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002344 if (mAssetsPackage != package) {
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002345 mCurrentXmlPos.error("creating resource for external package %s: %s/%s.",
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002346 String8(package).string(), String8(type).string(), String8(name).string());
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002347 if (package == String16("android")) {
2348 mCurrentXmlPos.printf("did you mean to use @+id instead of @+android:id?");
2349 }
2350 return 0;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002351 }
2352
2353 String16 value("false");
Adam Lesinski282e1812014-01-23 18:17:42 -08002354 status_t status = addEntry(mCurrentXmlPos, package, type, name, value, NULL, NULL, true);
2355 if (status == NO_ERROR) {
2356 resId = getResId(package, type, name);
2357 return resId;
2358 }
2359 return 0;
2360}
2361
2362uint32_t ResourceTable::getRemappedPackage(uint32_t origPackage) const
2363{
2364 return origPackage;
2365}
2366
2367bool ResourceTable::getAttributeType(uint32_t attrID, uint32_t* outType)
2368{
2369 //printf("getAttributeType #%08x\n", attrID);
2370 Res_value value;
2371 if (getItemValue(attrID, ResTable_map::ATTR_TYPE, &value)) {
2372 //printf("getAttributeType #%08x (%s): #%08x\n", attrID,
2373 // String8(getEntry(attrID)->getName()).string(), value.data);
2374 *outType = value.data;
2375 return true;
2376 }
2377 return false;
2378}
2379
2380bool ResourceTable::getAttributeMin(uint32_t attrID, uint32_t* outMin)
2381{
2382 //printf("getAttributeMin #%08x\n", attrID);
2383 Res_value value;
2384 if (getItemValue(attrID, ResTable_map::ATTR_MIN, &value)) {
2385 *outMin = value.data;
2386 return true;
2387 }
2388 return false;
2389}
2390
2391bool ResourceTable::getAttributeMax(uint32_t attrID, uint32_t* outMax)
2392{
2393 //printf("getAttributeMax #%08x\n", attrID);
2394 Res_value value;
2395 if (getItemValue(attrID, ResTable_map::ATTR_MAX, &value)) {
2396 *outMax = value.data;
2397 return true;
2398 }
2399 return false;
2400}
2401
2402uint32_t ResourceTable::getAttributeL10N(uint32_t attrID)
2403{
2404 //printf("getAttributeL10N #%08x\n", attrID);
2405 Res_value value;
2406 if (getItemValue(attrID, ResTable_map::ATTR_L10N, &value)) {
2407 return value.data;
2408 }
2409 return ResTable_map::L10N_NOT_REQUIRED;
2410}
2411
2412bool ResourceTable::getLocalizationSetting()
2413{
2414 return mBundle->getRequireLocalization();
2415}
2416
2417void ResourceTable::reportError(void* accessorCookie, const char* fmt, ...)
2418{
2419 if (accessorCookie != NULL && fmt != NULL) {
2420 AccessorCookie* ac = (AccessorCookie*)accessorCookie;
2421 int retval=0;
2422 char buf[1024];
2423 va_list ap;
2424 va_start(ap, fmt);
2425 retval = vsnprintf(buf, sizeof(buf), fmt, ap);
2426 va_end(ap);
2427 ac->sourcePos.error("Error: %s (at '%s' with value '%s').\n",
2428 buf, ac->attr.string(), ac->value.string());
2429 }
2430}
2431
2432bool ResourceTable::getAttributeKeys(
2433 uint32_t attrID, Vector<String16>* outKeys)
2434{
2435 sp<const Entry> e = getEntry(attrID);
2436 if (e != NULL) {
2437 const size_t N = e->getBag().size();
2438 for (size_t i=0; i<N; i++) {
2439 const String16& key = e->getBag().keyAt(i);
2440 if (key.size() > 0 && key.string()[0] != '^') {
2441 outKeys->add(key);
2442 }
2443 }
2444 return true;
2445 }
2446 return false;
2447}
2448
2449bool ResourceTable::getAttributeEnum(
2450 uint32_t attrID, const char16_t* name, size_t nameLen,
2451 Res_value* outValue)
2452{
2453 //printf("getAttributeEnum #%08x %s\n", attrID, String8(name, nameLen).string());
2454 String16 nameStr(name, nameLen);
2455 sp<const Entry> e = getEntry(attrID);
2456 if (e != NULL) {
2457 const size_t N = e->getBag().size();
2458 for (size_t i=0; i<N; i++) {
2459 //printf("Comparing %s to %s\n", String8(name, nameLen).string(),
2460 // String8(e->getBag().keyAt(i)).string());
2461 if (e->getBag().keyAt(i) == nameStr) {
2462 return getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, outValue);
2463 }
2464 }
2465 }
2466 return false;
2467}
2468
2469bool ResourceTable::getAttributeFlags(
2470 uint32_t attrID, const char16_t* name, size_t nameLen,
2471 Res_value* outValue)
2472{
2473 outValue->dataType = Res_value::TYPE_INT_HEX;
2474 outValue->data = 0;
2475
2476 //printf("getAttributeFlags #%08x %s\n", attrID, String8(name, nameLen).string());
2477 String16 nameStr(name, nameLen);
2478 sp<const Entry> e = getEntry(attrID);
2479 if (e != NULL) {
2480 const size_t N = e->getBag().size();
2481
2482 const char16_t* end = name + nameLen;
2483 const char16_t* pos = name;
2484 while (pos < end) {
2485 const char16_t* start = pos;
2486 while (pos < end && *pos != '|') {
2487 pos++;
2488 }
2489
2490 String16 nameStr(start, pos-start);
2491 size_t i;
2492 for (i=0; i<N; i++) {
2493 //printf("Comparing \"%s\" to \"%s\"\n", String8(nameStr).string(),
2494 // String8(e->getBag().keyAt(i)).string());
2495 if (e->getBag().keyAt(i) == nameStr) {
2496 Res_value val;
2497 bool got = getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, &val);
2498 if (!got) {
2499 return false;
2500 }
2501 //printf("Got value: 0x%08x\n", val.data);
2502 outValue->data |= val.data;
2503 break;
2504 }
2505 }
2506
2507 if (i >= N) {
2508 // Didn't find this flag identifier.
2509 return false;
2510 }
2511 pos++;
2512 }
2513
2514 return true;
2515 }
2516 return false;
2517}
2518
2519status_t ResourceTable::assignResourceIds()
2520{
2521 const size_t N = mOrderedPackages.size();
2522 size_t pi;
2523 status_t firstError = NO_ERROR;
2524
2525 // First generate all bag attributes and assign indices.
2526 for (pi=0; pi<N; pi++) {
2527 sp<Package> p = mOrderedPackages.itemAt(pi);
2528 if (p == NULL || p->getTypes().size() == 0) {
2529 // Empty, skip!
2530 continue;
2531 }
2532
Adam Lesinski9b624c12014-11-19 17:49:26 -08002533 if (mPackageType == System) {
2534 p->movePrivateAttrs();
2535 }
2536
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002537 // This has no sense for packages being built as AppFeature (aka with a non-zero offset).
Adam Lesinski282e1812014-01-23 18:17:42 -08002538 status_t err = p->applyPublicTypeOrder();
2539 if (err != NO_ERROR && firstError == NO_ERROR) {
2540 firstError = err;
2541 }
2542
2543 // Generate attributes...
2544 const size_t N = p->getOrderedTypes().size();
2545 size_t ti;
2546 for (ti=0; ti<N; ti++) {
2547 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2548 if (t == NULL) {
2549 continue;
2550 }
2551 const size_t N = t->getOrderedConfigs().size();
2552 for (size_t ci=0; ci<N; ci++) {
2553 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2554 if (c == NULL) {
2555 continue;
2556 }
2557 const size_t N = c->getEntries().size();
2558 for (size_t ei=0; ei<N; ei++) {
2559 sp<Entry> e = c->getEntries().valueAt(ei);
2560 if (e == NULL) {
2561 continue;
2562 }
2563 status_t err = e->generateAttributes(this, p->getName());
2564 if (err != NO_ERROR && firstError == NO_ERROR) {
2565 firstError = err;
2566 }
2567 }
2568 }
2569 }
2570
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002571 uint32_t typeIdOffset = 0;
2572 if (mPackageType == AppFeature && p->getName() == mAssetsPackage) {
2573 typeIdOffset = mTypeIdOffset;
2574 }
2575
Adam Lesinski282e1812014-01-23 18:17:42 -08002576 const SourcePos unknown(String8("????"), 0);
2577 sp<Type> attr = p->getType(String16("attr"), unknown);
2578
2579 // Assign indices...
Adam Lesinski43a0df02014-08-18 17:14:57 -07002580 const size_t typeCount = p->getOrderedTypes().size();
2581 for (size_t ti = 0; ti < typeCount; ti++) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002582 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2583 if (t == NULL) {
2584 continue;
2585 }
Adam Lesinski43a0df02014-08-18 17:14:57 -07002586
Adam Lesinski282e1812014-01-23 18:17:42 -08002587 err = t->applyPublicEntryOrder();
2588 if (err != NO_ERROR && firstError == NO_ERROR) {
2589 firstError = err;
2590 }
2591
2592 const size_t N = t->getOrderedConfigs().size();
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002593 t->setIndex(ti + 1 + typeIdOffset);
Adam Lesinski282e1812014-01-23 18:17:42 -08002594
2595 LOG_ALWAYS_FATAL_IF(ti == 0 && attr != t,
2596 "First type is not attr!");
2597
2598 for (size_t ei=0; ei<N; ei++) {
2599 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ei);
2600 if (c == NULL) {
2601 continue;
2602 }
2603 c->setEntryIndex(ei);
2604 }
2605 }
2606
Adam Lesinski9b624c12014-11-19 17:49:26 -08002607
Adam Lesinski282e1812014-01-23 18:17:42 -08002608 // Assign resource IDs to keys in bags...
Adam Lesinski43a0df02014-08-18 17:14:57 -07002609 for (size_t ti = 0; ti < typeCount; ti++) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002610 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2611 if (t == NULL) {
2612 continue;
2613 }
Adam Lesinski9b624c12014-11-19 17:49:26 -08002614
Adam Lesinski282e1812014-01-23 18:17:42 -08002615 const size_t N = t->getOrderedConfigs().size();
2616 for (size_t ci=0; ci<N; ci++) {
2617 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
Adam Lesinski9b624c12014-11-19 17:49:26 -08002618 if (c == NULL) {
2619 continue;
2620 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002621 //printf("Ordered config #%d: %p\n", ci, c.get());
2622 const size_t N = c->getEntries().size();
2623 for (size_t ei=0; ei<N; ei++) {
2624 sp<Entry> e = c->getEntries().valueAt(ei);
2625 if (e == NULL) {
2626 continue;
2627 }
2628 status_t err = e->assignResourceIds(this, p->getName());
2629 if (err != NO_ERROR && firstError == NO_ERROR) {
2630 firstError = err;
2631 }
2632 }
2633 }
2634 }
2635 }
2636 return firstError;
2637}
2638
Adrian Roos58922482015-06-01 17:59:41 -07002639status_t ResourceTable::addSymbols(const sp<AaptSymbols>& outSymbols,
2640 bool skipSymbolsWithoutDefaultLocalization) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002641 const size_t N = mOrderedPackages.size();
Adrian Roos58922482015-06-01 17:59:41 -07002642 const String8 defaultLocale;
2643 const String16 stringType("string");
Adam Lesinski282e1812014-01-23 18:17:42 -08002644 size_t pi;
2645
2646 for (pi=0; pi<N; pi++) {
2647 sp<Package> p = mOrderedPackages.itemAt(pi);
2648 if (p->getTypes().size() == 0) {
2649 // Empty, skip!
2650 continue;
2651 }
2652
2653 const size_t N = p->getOrderedTypes().size();
2654 size_t ti;
2655
2656 for (ti=0; ti<N; ti++) {
2657 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2658 if (t == NULL) {
2659 continue;
2660 }
Adam Lesinski9b624c12014-11-19 17:49:26 -08002661
Adam Lesinski282e1812014-01-23 18:17:42 -08002662 const size_t N = t->getOrderedConfigs().size();
Adam Lesinski9b624c12014-11-19 17:49:26 -08002663 sp<AaptSymbols> typeSymbols;
2664 if (t->getName() == String16(kAttrPrivateType)) {
2665 typeSymbols = outSymbols->addNestedSymbol(String8("attr"), t->getPos());
2666 } else {
2667 typeSymbols = outSymbols->addNestedSymbol(String8(t->getName()), t->getPos());
2668 }
2669
Adam Lesinski3fb8c9b2014-09-09 16:05:10 -07002670 if (typeSymbols == NULL) {
2671 return UNKNOWN_ERROR;
2672 }
2673
Adam Lesinski282e1812014-01-23 18:17:42 -08002674 for (size_t ci=0; ci<N; ci++) {
2675 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2676 if (c == NULL) {
2677 continue;
2678 }
2679 uint32_t rid = getResId(p, t, ci);
2680 if (rid == 0) {
2681 return UNKNOWN_ERROR;
2682 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002683 if (Res_GETPACKAGE(rid) + 1 == p->getAssignedId()) {
Adrian Roos58922482015-06-01 17:59:41 -07002684
2685 if (skipSymbolsWithoutDefaultLocalization &&
2686 t->getName() == stringType) {
2687
2688 // Don't generate symbols for strings without a default localization.
2689 if (mHasDefaultLocalization.find(c->getName())
2690 == mHasDefaultLocalization.end()) {
2691 // printf("Skip symbol [%08x] %s\n", rid,
2692 // String8(c->getName()).string());
2693 continue;
2694 }
2695 }
2696
Adam Lesinski282e1812014-01-23 18:17:42 -08002697 typeSymbols->addSymbol(String8(c->getName()), rid, c->getPos());
2698
2699 String16 comment(c->getComment());
2700 typeSymbols->appendComment(String8(c->getName()), comment, c->getPos());
Adam Lesinski8ff15b42013-10-07 16:54:01 -07002701 //printf("Type symbol [%08x] %s comment: %s\n", rid,
2702 // String8(c->getName()).string(), String8(comment).string());
Adam Lesinski282e1812014-01-23 18:17:42 -08002703 comment = c->getTypeComment();
2704 typeSymbols->appendTypeComment(String8(c->getName()), comment);
Adam Lesinski282e1812014-01-23 18:17:42 -08002705 }
2706 }
2707 }
2708 }
2709 return NO_ERROR;
2710}
2711
2712
2713void
Adam Lesinskia01a9372014-03-20 18:04:57 -07002714ResourceTable::addLocalization(const String16& name, const String8& locale, const SourcePos& src)
Adam Lesinski282e1812014-01-23 18:17:42 -08002715{
Adam Lesinskia01a9372014-03-20 18:04:57 -07002716 mLocalizations[name][locale] = src;
Adam Lesinski282e1812014-01-23 18:17:42 -08002717}
2718
Adrian Roos58922482015-06-01 17:59:41 -07002719void
2720ResourceTable::addDefaultLocalization(const String16& name)
2721{
2722 mHasDefaultLocalization.insert(name);
2723}
2724
Adam Lesinski282e1812014-01-23 18:17:42 -08002725
2726/*!
2727 * Flag various sorts of localization problems. '+' indicates checks already implemented;
2728 * '-' indicates checks that will be implemented in the future.
2729 *
2730 * + A localized string for which no default-locale version exists => warning
2731 * + A string for which no version in an explicitly-requested locale exists => warning
2732 * + A localized translation of an translateable="false" string => warning
2733 * - A localized string not provided in every locale used by the table
2734 */
2735status_t
2736ResourceTable::validateLocalizations(void)
2737{
2738 status_t err = NO_ERROR;
2739 const String8 defaultLocale;
2740
2741 // For all strings...
Dan Albert030f5362015-03-04 13:54:20 -08002742 for (const auto& nameIter : mLocalizations) {
2743 const std::map<String8, SourcePos>& configSrcMap = nameIter.second;
Adam Lesinski282e1812014-01-23 18:17:42 -08002744
2745 // Look for strings with no default localization
Adam Lesinskia01a9372014-03-20 18:04:57 -07002746 if (configSrcMap.count(defaultLocale) == 0) {
2747 SourcePos().warning("string '%s' has no default translation.",
Dan Albert030f5362015-03-04 13:54:20 -08002748 String8(nameIter.first).string());
Adam Lesinskia01a9372014-03-20 18:04:57 -07002749 if (mBundle->getVerbose()) {
Dan Albert030f5362015-03-04 13:54:20 -08002750 for (const auto& locale : configSrcMap) {
2751 locale.second.printf("locale %s found", locale.first.string());
Adam Lesinskia01a9372014-03-20 18:04:57 -07002752 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002753 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002754 // !!! TODO: throw an error here in some circumstances
2755 }
2756
2757 // Check that all requested localizations are present for this string
Adam Lesinskifab50872014-04-16 14:40:42 -07002758 if (mBundle->getConfigurations().size() > 0 && mBundle->getRequireLocalization()) {
2759 const char* allConfigs = mBundle->getConfigurations().string();
Adam Lesinski282e1812014-01-23 18:17:42 -08002760 const char* start = allConfigs;
2761 const char* comma;
Dan Albert030f5362015-03-04 13:54:20 -08002762
2763 std::set<String8> missingConfigs;
Adam Lesinskia01a9372014-03-20 18:04:57 -07002764 AaptLocaleValue locale;
Adam Lesinski282e1812014-01-23 18:17:42 -08002765 do {
2766 String8 config;
2767 comma = strchr(start, ',');
2768 if (comma != NULL) {
2769 config.setTo(start, comma - start);
2770 start = comma + 1;
2771 } else {
2772 config.setTo(start);
2773 }
2774
Adam Lesinskia01a9372014-03-20 18:04:57 -07002775 if (!locale.initFromFilterString(config)) {
2776 continue;
2777 }
2778
Anton Krumina2ef5c02014-03-12 14:46:44 -07002779 // don't bother with the pseudolocale "en_XA" or "ar_XB"
2780 if (config != "en_XA" && config != "ar_XB") {
Adam Lesinskia01a9372014-03-20 18:04:57 -07002781 if (configSrcMap.find(config) == configSrcMap.end()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002782 // okay, no specific localization found. it's possible that we are
2783 // requiring a specific regional localization [e.g. de_DE] but there is an
2784 // available string in the generic language localization [e.g. de];
2785 // consider that string to have fulfilled the localization requirement.
2786 String8 region(config.string(), 2);
Adam Lesinskia01a9372014-03-20 18:04:57 -07002787 if (configSrcMap.find(region) == configSrcMap.end() &&
2788 configSrcMap.count(defaultLocale) == 0) {
2789 missingConfigs.insert(config);
Adam Lesinski282e1812014-01-23 18:17:42 -08002790 }
2791 }
2792 }
Adam Lesinskia01a9372014-03-20 18:04:57 -07002793 } while (comma != NULL);
2794
2795 if (!missingConfigs.empty()) {
2796 String8 configStr;
Dan Albert030f5362015-03-04 13:54:20 -08002797 for (const auto& iter : missingConfigs) {
2798 configStr.appendFormat(" %s", iter.string());
Adam Lesinskia01a9372014-03-20 18:04:57 -07002799 }
2800 SourcePos().warning("string '%s' is missing %u required localizations:%s",
Dan Albert030f5362015-03-04 13:54:20 -08002801 String8(nameIter.first).string(),
Adam Lesinskia01a9372014-03-20 18:04:57 -07002802 (unsigned int)missingConfigs.size(),
2803 configStr.string());
2804 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002805 }
2806 }
2807
2808 return err;
2809}
2810
Adam Lesinski27f69f42014-08-21 13:19:12 -07002811status_t ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& filter,
2812 const sp<AaptFile>& dest,
2813 const bool isBase)
Adam Lesinski282e1812014-01-23 18:17:42 -08002814{
Adam Lesinski282e1812014-01-23 18:17:42 -08002815 const ConfigDescription nullConfig;
2816
2817 const size_t N = mOrderedPackages.size();
2818 size_t pi;
2819
2820 const static String16 mipmap16("mipmap");
2821
2822 bool useUTF8 = !bundle->getUTF16StringsOption();
2823
Adam Lesinskide898ff2014-01-29 18:20:45 -08002824 // The libraries this table references.
2825 Vector<sp<Package> > libraryPackages;
Adam Lesinski6022deb2014-08-20 14:59:19 -07002826 const ResTable& table = mAssets->getIncludedResources();
2827 const size_t basePackageCount = table.getBasePackageCount();
2828 for (size_t i = 0; i < basePackageCount; i++) {
2829 size_t packageId = table.getBasePackageId(i);
2830 String16 packageName(table.getBasePackageName(i));
2831 if (packageId > 0x01 && packageId != 0x7f &&
2832 packageName != String16("android")) {
2833 libraryPackages.add(sp<Package>(new Package(packageName, packageId)));
2834 }
2835 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08002836
Adam Lesinski282e1812014-01-23 18:17:42 -08002837 // Iterate through all data, collecting all values (strings,
2838 // references, etc).
2839 StringPool valueStrings(useUTF8);
2840 Vector<sp<Entry> > allEntries;
2841 for (pi=0; pi<N; pi++) {
2842 sp<Package> p = mOrderedPackages.itemAt(pi);
2843 if (p->getTypes().size() == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002844 continue;
2845 }
2846
2847 StringPool typeStrings(useUTF8);
2848 StringPool keyStrings(useUTF8);
2849
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002850 ssize_t stringsAdded = 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08002851 const size_t N = p->getOrderedTypes().size();
2852 for (size_t ti=0; ti<N; ti++) {
2853 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2854 if (t == NULL) {
2855 typeStrings.add(String16("<empty>"), false);
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002856 stringsAdded++;
Adam Lesinski282e1812014-01-23 18:17:42 -08002857 continue;
2858 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002859
2860 while (stringsAdded < t->getIndex() - 1) {
2861 typeStrings.add(String16("<empty>"), false);
2862 stringsAdded++;
2863 }
2864
Adam Lesinski282e1812014-01-23 18:17:42 -08002865 const String16 typeName(t->getName());
2866 typeStrings.add(typeName, false);
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002867 stringsAdded++;
Adam Lesinski282e1812014-01-23 18:17:42 -08002868
2869 // This is a hack to tweak the sorting order of the final strings,
2870 // to put stuff that is generally not language-specific first.
2871 String8 configTypeName(typeName);
2872 if (configTypeName == "drawable" || configTypeName == "layout"
2873 || configTypeName == "color" || configTypeName == "anim"
2874 || configTypeName == "interpolator" || configTypeName == "animator"
2875 || configTypeName == "xml" || configTypeName == "menu"
2876 || configTypeName == "mipmap" || configTypeName == "raw") {
2877 configTypeName = "1complex";
2878 } else {
2879 configTypeName = "2value";
2880 }
2881
Adam Lesinski27f69f42014-08-21 13:19:12 -07002882 // mipmaps don't get filtered, so they will
2883 // allways end up in the base. Make sure they
2884 // don't end up in a split.
2885 if (typeName == mipmap16 && !isBase) {
2886 continue;
2887 }
2888
Adam Lesinski282e1812014-01-23 18:17:42 -08002889 const bool filterable = (typeName != mipmap16);
2890
2891 const size_t N = t->getOrderedConfigs().size();
2892 for (size_t ci=0; ci<N; ci++) {
2893 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2894 if (c == NULL) {
2895 continue;
2896 }
2897 const size_t N = c->getEntries().size();
2898 for (size_t ei=0; ei<N; ei++) {
2899 ConfigDescription config = c->getEntries().keyAt(ei);
Adam Lesinskifab50872014-04-16 14:40:42 -07002900 if (filterable && !filter->match(config)) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002901 continue;
2902 }
2903 sp<Entry> e = c->getEntries().valueAt(ei);
2904 if (e == NULL) {
2905 continue;
2906 }
2907 e->setNameIndex(keyStrings.add(e->getName(), true));
2908
2909 // If this entry has no values for other configs,
2910 // and is the default config, then it is special. Otherwise
2911 // we want to add it with the config info.
2912 ConfigDescription* valueConfig = NULL;
2913 if (N != 1 || config == nullConfig) {
2914 valueConfig = &config;
2915 }
2916
2917 status_t err = e->prepareFlatten(&valueStrings, this,
2918 &configTypeName, &config);
2919 if (err != NO_ERROR) {
2920 return err;
2921 }
2922 allEntries.add(e);
2923 }
2924 }
2925 }
2926
2927 p->setTypeStrings(typeStrings.createStringBlock());
2928 p->setKeyStrings(keyStrings.createStringBlock());
2929 }
2930
2931 if (bundle->getOutputAPKFile() != NULL) {
2932 // Now we want to sort the value strings for better locality. This will
2933 // cause the positions of the strings to change, so we need to go back
2934 // through out resource entries and update them accordingly. Only need
2935 // to do this if actually writing the output file.
2936 valueStrings.sortByConfig();
2937 for (pi=0; pi<allEntries.size(); pi++) {
2938 allEntries[pi]->remapStringValue(&valueStrings);
2939 }
2940 }
2941
2942 ssize_t strAmt = 0;
Adam Lesinskide898ff2014-01-29 18:20:45 -08002943
Adam Lesinski282e1812014-01-23 18:17:42 -08002944 // Now build the array of package chunks.
2945 Vector<sp<AaptFile> > flatPackages;
2946 for (pi=0; pi<N; pi++) {
2947 sp<Package> p = mOrderedPackages.itemAt(pi);
2948 if (p->getTypes().size() == 0) {
2949 // Empty, skip!
2950 continue;
2951 }
2952
2953 const size_t N = p->getTypeStrings().size();
2954
2955 const size_t baseSize = sizeof(ResTable_package);
2956
2957 // Start the package data.
2958 sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
2959 ResTable_package* header = (ResTable_package*)data->editData(baseSize);
2960 if (header == NULL) {
2961 fprintf(stderr, "ERROR: out of memory creating ResTable_package\n");
2962 return NO_MEMORY;
2963 }
2964 memset(header, 0, sizeof(*header));
2965 header->header.type = htods(RES_TABLE_PACKAGE_TYPE);
2966 header->header.headerSize = htods(sizeof(*header));
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002967 header->id = htodl(static_cast<uint32_t>(p->getAssignedId()));
Adam Lesinski282e1812014-01-23 18:17:42 -08002968 strcpy16_htod(header->name, p->getName().string());
2969
2970 // Write the string blocks.
2971 const size_t typeStringsStart = data->getSize();
2972 sp<AaptFile> strFile = p->getTypeStringsData();
2973 ssize_t amt = data->writeData(strFile->getData(), strFile->getSize());
Andreas Gampe2412f842014-09-30 20:55:57 -07002974 if (kPrintStringMetrics) {
2975 fprintf(stderr, "**** type strings: %zd\n", SSIZE(amt));
2976 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002977 strAmt += amt;
2978 if (amt < 0) {
2979 return amt;
2980 }
2981 const size_t keyStringsStart = data->getSize();
2982 strFile = p->getKeyStringsData();
2983 amt = data->writeData(strFile->getData(), strFile->getSize());
Andreas Gampe2412f842014-09-30 20:55:57 -07002984 if (kPrintStringMetrics) {
2985 fprintf(stderr, "**** key strings: %zd\n", SSIZE(amt));
2986 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002987 strAmt += amt;
2988 if (amt < 0) {
2989 return amt;
2990 }
2991
Adam Lesinski27f69f42014-08-21 13:19:12 -07002992 if (isBase) {
2993 status_t err = flattenLibraryTable(data, libraryPackages);
2994 if (err != NO_ERROR) {
2995 fprintf(stderr, "ERROR: failed to write library table\n");
2996 return err;
2997 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08002998 }
2999
Adam Lesinski282e1812014-01-23 18:17:42 -08003000 // Build the type chunks inside of this package.
3001 for (size_t ti=0; ti<N; ti++) {
3002 // Retrieve them in the same order as the type string block.
3003 size_t len;
3004 String16 typeName(p->getTypeStrings().stringAt(ti, &len));
3005 sp<Type> t = p->getTypes().valueFor(typeName);
3006 LOG_ALWAYS_FATAL_IF(t == NULL && typeName != String16("<empty>"),
3007 "Type name %s not found",
3008 String8(typeName).string());
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003009 if (t == NULL) {
3010 continue;
3011 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003012 const bool filterable = (typeName != mipmap16);
Adam Lesinski27f69f42014-08-21 13:19:12 -07003013 const bool skipEntireType = (typeName == mipmap16 && !isBase);
Adam Lesinski282e1812014-01-23 18:17:42 -08003014
3015 const size_t N = t != NULL ? t->getOrderedConfigs().size() : 0;
3016
3017 // Until a non-NO_ENTRY value has been written for a resource,
3018 // that resource is invalid; validResources[i] represents
3019 // the item at t->getOrderedConfigs().itemAt(i).
3020 Vector<bool> validResources;
3021 validResources.insertAt(false, 0, N);
3022
3023 // First write the typeSpec chunk, containing information about
3024 // each resource entry in this type.
3025 {
3026 const size_t typeSpecSize = sizeof(ResTable_typeSpec) + sizeof(uint32_t)*N;
3027 const size_t typeSpecStart = data->getSize();
3028 ResTable_typeSpec* tsHeader = (ResTable_typeSpec*)
3029 (((uint8_t*)data->editData(typeSpecStart+typeSpecSize)) + typeSpecStart);
3030 if (tsHeader == NULL) {
3031 fprintf(stderr, "ERROR: out of memory creating ResTable_typeSpec\n");
3032 return NO_MEMORY;
3033 }
3034 memset(tsHeader, 0, sizeof(*tsHeader));
3035 tsHeader->header.type = htods(RES_TABLE_TYPE_SPEC_TYPE);
3036 tsHeader->header.headerSize = htods(sizeof(*tsHeader));
3037 tsHeader->header.size = htodl(typeSpecSize);
3038 tsHeader->id = ti+1;
3039 tsHeader->entryCount = htodl(N);
3040
3041 uint32_t* typeSpecFlags = (uint32_t*)
3042 (((uint8_t*)data->editData())
3043 + typeSpecStart + sizeof(ResTable_typeSpec));
3044 memset(typeSpecFlags, 0, sizeof(uint32_t)*N);
3045
3046 for (size_t ei=0; ei<N; ei++) {
3047 sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
Adam Lesinski9b624c12014-11-19 17:49:26 -08003048 if (cl == NULL) {
3049 continue;
3050 }
3051
Adam Lesinski282e1812014-01-23 18:17:42 -08003052 if (cl->getPublic()) {
3053 typeSpecFlags[ei] |= htodl(ResTable_typeSpec::SPEC_PUBLIC);
3054 }
Adam Lesinski27f69f42014-08-21 13:19:12 -07003055
3056 if (skipEntireType) {
3057 continue;
3058 }
3059
Adam Lesinski282e1812014-01-23 18:17:42 -08003060 const size_t CN = cl->getEntries().size();
3061 for (size_t ci=0; ci<CN; ci++) {
Adam Lesinskifab50872014-04-16 14:40:42 -07003062 if (filterable && !filter->match(cl->getEntries().keyAt(ci))) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003063 continue;
3064 }
3065 for (size_t cj=ci+1; cj<CN; cj++) {
Adam Lesinskifab50872014-04-16 14:40:42 -07003066 if (filterable && !filter->match(cl->getEntries().keyAt(cj))) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003067 continue;
3068 }
3069 typeSpecFlags[ei] |= htodl(
3070 cl->getEntries().keyAt(ci).diff(cl->getEntries().keyAt(cj)));
3071 }
3072 }
3073 }
3074 }
3075
Adam Lesinski27f69f42014-08-21 13:19:12 -07003076 if (skipEntireType) {
3077 continue;
3078 }
3079
Adam Lesinski282e1812014-01-23 18:17:42 -08003080 // We need to write one type chunk for each configuration for
3081 // which we have entries in this type.
Adam Lesinskie97908d2014-12-05 11:06:21 -08003082 SortedVector<ConfigDescription> uniqueConfigs;
3083 if (t != NULL) {
3084 uniqueConfigs = t->getUniqueConfigs();
3085 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003086
3087 const size_t typeSize = sizeof(ResTable_type) + sizeof(uint32_t)*N;
3088
Adam Lesinskie97908d2014-12-05 11:06:21 -08003089 const size_t NC = uniqueConfigs.size();
Adam Lesinski282e1812014-01-23 18:17:42 -08003090 for (size_t ci=0; ci<NC; ci++) {
Adam Lesinski9b624c12014-11-19 17:49:26 -08003091 const ConfigDescription& config = uniqueConfigs[ci];
Adam Lesinski282e1812014-01-23 18:17:42 -08003092
Andreas Gampe2412f842014-09-30 20:55:57 -07003093 if (kIsDebug) {
3094 printf("Writing config %zu config: imsi:%d/%d lang:%c%c cnt:%c%c "
3095 "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
3096 "sw%ddp w%ddp h%ddp layout:%d\n",
3097 ti + 1,
3098 config.mcc, config.mnc,
3099 config.language[0] ? config.language[0] : '-',
3100 config.language[1] ? config.language[1] : '-',
3101 config.country[0] ? config.country[0] : '-',
3102 config.country[1] ? config.country[1] : '-',
3103 config.orientation,
3104 config.uiMode,
3105 config.touchscreen,
3106 config.density,
3107 config.keyboard,
3108 config.inputFlags,
3109 config.navigation,
3110 config.screenWidth,
3111 config.screenHeight,
3112 config.smallestScreenWidthDp,
3113 config.screenWidthDp,
3114 config.screenHeightDp,
3115 config.screenLayout);
3116 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003117
Adam Lesinskifab50872014-04-16 14:40:42 -07003118 if (filterable && !filter->match(config)) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003119 continue;
3120 }
3121
3122 const size_t typeStart = data->getSize();
3123
3124 ResTable_type* tHeader = (ResTable_type*)
3125 (((uint8_t*)data->editData(typeStart+typeSize)) + typeStart);
3126 if (tHeader == NULL) {
3127 fprintf(stderr, "ERROR: out of memory creating ResTable_type\n");
3128 return NO_MEMORY;
3129 }
3130
3131 memset(tHeader, 0, sizeof(*tHeader));
3132 tHeader->header.type = htods(RES_TABLE_TYPE_TYPE);
3133 tHeader->header.headerSize = htods(sizeof(*tHeader));
3134 tHeader->id = ti+1;
3135 tHeader->entryCount = htodl(N);
3136 tHeader->entriesStart = htodl(typeSize);
3137 tHeader->config = config;
Andreas Gampe2412f842014-09-30 20:55:57 -07003138 if (kIsDebug) {
3139 printf("Writing type %zu config: imsi:%d/%d lang:%c%c cnt:%c%c "
3140 "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
3141 "sw%ddp w%ddp h%ddp layout:%d\n",
3142 ti + 1,
3143 tHeader->config.mcc, tHeader->config.mnc,
3144 tHeader->config.language[0] ? tHeader->config.language[0] : '-',
3145 tHeader->config.language[1] ? tHeader->config.language[1] : '-',
3146 tHeader->config.country[0] ? tHeader->config.country[0] : '-',
3147 tHeader->config.country[1] ? tHeader->config.country[1] : '-',
3148 tHeader->config.orientation,
3149 tHeader->config.uiMode,
3150 tHeader->config.touchscreen,
3151 tHeader->config.density,
3152 tHeader->config.keyboard,
3153 tHeader->config.inputFlags,
3154 tHeader->config.navigation,
3155 tHeader->config.screenWidth,
3156 tHeader->config.screenHeight,
3157 tHeader->config.smallestScreenWidthDp,
3158 tHeader->config.screenWidthDp,
3159 tHeader->config.screenHeightDp,
3160 tHeader->config.screenLayout);
3161 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003162 tHeader->config.swapHtoD();
3163
3164 // Build the entries inside of this type.
3165 for (size_t ei=0; ei<N; ei++) {
3166 sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
Adam Lesinski9b624c12014-11-19 17:49:26 -08003167 sp<Entry> e = NULL;
3168 if (cl != NULL) {
3169 e = cl->getEntries().valueFor(config);
3170 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003171
3172 // Set the offset for this entry in its type.
3173 uint32_t* index = (uint32_t*)
3174 (((uint8_t*)data->editData())
3175 + typeStart + sizeof(ResTable_type));
3176 if (e != NULL) {
3177 index[ei] = htodl(data->getSize()-typeStart-typeSize);
3178
3179 // Create the entry.
3180 ssize_t amt = e->flatten(bundle, data, cl->getPublic());
3181 if (amt < 0) {
3182 return amt;
3183 }
3184 validResources.editItemAt(ei) = true;
3185 } else {
3186 index[ei] = htodl(ResTable_type::NO_ENTRY);
3187 }
3188 }
3189
3190 // Fill in the rest of the type information.
3191 tHeader = (ResTable_type*)
3192 (((uint8_t*)data->editData()) + typeStart);
3193 tHeader->header.size = htodl(data->getSize()-typeStart);
3194 }
3195
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003196 // If we're building splits, then each invocation of the flattening
3197 // step will have 'missing' entries. Don't warn/error for this case.
3198 if (bundle->getSplitConfigurations().isEmpty()) {
3199 bool missing_entry = false;
3200 const char* log_prefix = bundle->getErrorOnMissingConfigEntry() ?
3201 "error" : "warning";
3202 for (size_t i = 0; i < N; ++i) {
3203 if (!validResources[i]) {
3204 sp<ConfigList> c = t->getOrderedConfigs().itemAt(i);
Adam Lesinski9b624c12014-11-19 17:49:26 -08003205 if (c != NULL) {
Colin Cross01f18562015-04-08 17:29:00 -07003206 fprintf(stderr, "%s: no entries written for %s/%s (0x%08zx)\n", log_prefix,
Adam Lesinski9b624c12014-11-19 17:49:26 -08003207 String8(typeName).string(), String8(c->getName()).string(),
3208 Res_MAKEID(p->getAssignedId() - 1, ti, i));
3209 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003210 missing_entry = true;
3211 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003212 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003213 if (bundle->getErrorOnMissingConfigEntry() && missing_entry) {
3214 fprintf(stderr, "Error: Missing entries, quit!\n");
3215 return NOT_ENOUGH_DATA;
3216 }
Ying Wangcd28bd32013-11-14 17:12:10 -08003217 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003218 }
3219
3220 // Fill in the rest of the package information.
3221 header = (ResTable_package*)data->editData();
3222 header->header.size = htodl(data->getSize());
3223 header->typeStrings = htodl(typeStringsStart);
3224 header->lastPublicType = htodl(p->getTypeStrings().size());
3225 header->keyStrings = htodl(keyStringsStart);
3226 header->lastPublicKey = htodl(p->getKeyStrings().size());
3227
3228 flatPackages.add(data);
3229 }
3230
3231 // And now write out the final chunks.
3232 const size_t dataStart = dest->getSize();
3233
3234 {
3235 // blah
3236 ResTable_header header;
3237 memset(&header, 0, sizeof(header));
3238 header.header.type = htods(RES_TABLE_TYPE);
3239 header.header.headerSize = htods(sizeof(header));
3240 header.packageCount = htodl(flatPackages.size());
3241 status_t err = dest->writeData(&header, sizeof(header));
3242 if (err != NO_ERROR) {
3243 fprintf(stderr, "ERROR: out of memory creating ResTable_header\n");
3244 return err;
3245 }
3246 }
3247
3248 ssize_t strStart = dest->getSize();
Adam Lesinskifab50872014-04-16 14:40:42 -07003249 status_t err = valueStrings.writeStringBlock(dest);
Adam Lesinski282e1812014-01-23 18:17:42 -08003250 if (err != NO_ERROR) {
3251 return err;
3252 }
3253
3254 ssize_t amt = (dest->getSize()-strStart);
3255 strAmt += amt;
Andreas Gampe2412f842014-09-30 20:55:57 -07003256 if (kPrintStringMetrics) {
3257 fprintf(stderr, "**** value strings: %zd\n", SSIZE(amt));
3258 fprintf(stderr, "**** total strings: %zd\n", SSIZE(strAmt));
3259 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08003260
Adam Lesinski282e1812014-01-23 18:17:42 -08003261 for (pi=0; pi<flatPackages.size(); pi++) {
3262 err = dest->writeData(flatPackages[pi]->getData(),
3263 flatPackages[pi]->getSize());
3264 if (err != NO_ERROR) {
3265 fprintf(stderr, "ERROR: out of memory creating package chunk for ResTable_header\n");
3266 return err;
3267 }
3268 }
3269
3270 ResTable_header* header = (ResTable_header*)
3271 (((uint8_t*)dest->getData()) + dataStart);
3272 header->header.size = htodl(dest->getSize() - dataStart);
3273
Andreas Gampe2412f842014-09-30 20:55:57 -07003274 if (kPrintStringMetrics) {
3275 fprintf(stderr, "**** total resource table size: %zu / %zu%% strings\n",
3276 dest->getSize(), (size_t)(strAmt*100)/dest->getSize());
3277 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003278
3279 return NO_ERROR;
3280}
3281
Adam Lesinskide898ff2014-01-29 18:20:45 -08003282status_t ResourceTable::flattenLibraryTable(const sp<AaptFile>& dest, const Vector<sp<Package> >& libs) {
3283 // Write out the library table if necessary
3284 if (libs.size() > 0) {
Andreas Gampe87332a72014-10-01 22:03:58 -07003285 if (kIsDebug) {
3286 fprintf(stderr, "Writing library reference table\n");
3287 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08003288
3289 const size_t libStart = dest->getSize();
3290 const size_t count = libs.size();
Adam Lesinski6022deb2014-08-20 14:59:19 -07003291 ResTable_lib_header* libHeader = (ResTable_lib_header*) dest->editDataInRange(
3292 libStart, sizeof(ResTable_lib_header));
Adam Lesinskide898ff2014-01-29 18:20:45 -08003293
3294 memset(libHeader, 0, sizeof(*libHeader));
3295 libHeader->header.type = htods(RES_TABLE_LIBRARY_TYPE);
3296 libHeader->header.headerSize = htods(sizeof(*libHeader));
3297 libHeader->header.size = htodl(sizeof(*libHeader) + (sizeof(ResTable_lib_entry) * count));
3298 libHeader->count = htodl(count);
3299
3300 // Write the library entries
3301 for (size_t i = 0; i < count; i++) {
3302 const size_t entryStart = dest->getSize();
3303 sp<Package> libPackage = libs[i];
Andreas Gampe87332a72014-10-01 22:03:58 -07003304 if (kIsDebug) {
3305 fprintf(stderr, " Entry %s -> 0x%02x\n",
Adam Lesinskide898ff2014-01-29 18:20:45 -08003306 String8(libPackage->getName()).string(),
Andreas Gampe87332a72014-10-01 22:03:58 -07003307 (uint8_t)libPackage->getAssignedId());
3308 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08003309
Adam Lesinski6022deb2014-08-20 14:59:19 -07003310 ResTable_lib_entry* entry = (ResTable_lib_entry*) dest->editDataInRange(
3311 entryStart, sizeof(ResTable_lib_entry));
Adam Lesinskide898ff2014-01-29 18:20:45 -08003312 memset(entry, 0, sizeof(*entry));
3313 entry->packageId = htodl(libPackage->getAssignedId());
3314 strcpy16_htod(entry->packageName, libPackage->getName().string());
3315 }
3316 }
3317 return NO_ERROR;
3318}
3319
Adam Lesinski282e1812014-01-23 18:17:42 -08003320void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp)
3321{
3322 fprintf(fp,
3323 "<!-- This file contains <public> resource definitions for all\n"
3324 " resources that were generated from the source data. -->\n"
3325 "\n"
3326 "<resources>\n");
3327
3328 writePublicDefinitions(package, fp, true);
3329 writePublicDefinitions(package, fp, false);
3330
3331 fprintf(fp,
3332 "\n"
3333 "</resources>\n");
3334}
3335
3336void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp, bool pub)
3337{
3338 bool didHeader = false;
3339
3340 sp<Package> pkg = mPackages.valueFor(package);
3341 if (pkg != NULL) {
3342 const size_t NT = pkg->getOrderedTypes().size();
3343 for (size_t i=0; i<NT; i++) {
3344 sp<Type> t = pkg->getOrderedTypes().itemAt(i);
3345 if (t == NULL) {
3346 continue;
3347 }
3348
3349 bool didType = false;
3350
3351 const size_t NC = t->getOrderedConfigs().size();
3352 for (size_t j=0; j<NC; j++) {
3353 sp<ConfigList> c = t->getOrderedConfigs().itemAt(j);
3354 if (c == NULL) {
3355 continue;
3356 }
3357
3358 if (c->getPublic() != pub) {
3359 continue;
3360 }
3361
3362 if (!didType) {
3363 fprintf(fp, "\n");
3364 didType = true;
3365 }
3366 if (!didHeader) {
3367 if (pub) {
3368 fprintf(fp," <!-- PUBLIC SECTION. These resources have been declared public.\n");
3369 fprintf(fp," Changes to these definitions will break binary compatibility. -->\n\n");
3370 } else {
3371 fprintf(fp," <!-- PRIVATE SECTION. These resources have not been declared public.\n");
3372 fprintf(fp," You can make them public my moving these lines into a file in res/values. -->\n\n");
3373 }
3374 didHeader = true;
3375 }
3376 if (!pub) {
3377 const size_t NE = c->getEntries().size();
3378 for (size_t k=0; k<NE; k++) {
3379 const SourcePos& pos = c->getEntries().valueAt(k)->getPos();
3380 if (pos.file != "") {
3381 fprintf(fp," <!-- Declared at %s:%d -->\n",
3382 pos.file.string(), pos.line);
3383 }
3384 }
3385 }
3386 fprintf(fp, " <public type=\"%s\" name=\"%s\" id=\"0x%08x\" />\n",
3387 String8(t->getName()).string(),
3388 String8(c->getName()).string(),
3389 getResId(pkg, t, c->getEntryIndex()));
3390 }
3391 }
3392 }
3393}
3394
3395ResourceTable::Item::Item(const SourcePos& _sourcePos,
3396 bool _isId,
3397 const String16& _value,
3398 const Vector<StringPool::entry_style_span>* _style,
3399 int32_t _format)
3400 : sourcePos(_sourcePos)
3401 , isId(_isId)
3402 , value(_value)
3403 , format(_format)
3404 , bagKeyId(0)
3405 , evaluating(false)
3406{
3407 if (_style) {
3408 style = *_style;
3409 }
3410}
3411
Adam Lesinski82a2dd82014-09-17 18:34:15 -07003412ResourceTable::Entry::Entry(const Entry& entry)
3413 : RefBase()
3414 , mName(entry.mName)
3415 , mParent(entry.mParent)
3416 , mType(entry.mType)
3417 , mItem(entry.mItem)
3418 , mItemFormat(entry.mItemFormat)
3419 , mBag(entry.mBag)
3420 , mNameIndex(entry.mNameIndex)
3421 , mParentId(entry.mParentId)
3422 , mPos(entry.mPos) {}
3423
Adam Lesinski978ab9d2014-09-24 19:02:52 -07003424ResourceTable::Entry& ResourceTable::Entry::operator=(const Entry& entry) {
3425 mName = entry.mName;
3426 mParent = entry.mParent;
3427 mType = entry.mType;
3428 mItem = entry.mItem;
3429 mItemFormat = entry.mItemFormat;
3430 mBag = entry.mBag;
3431 mNameIndex = entry.mNameIndex;
3432 mParentId = entry.mParentId;
3433 mPos = entry.mPos;
3434 return *this;
3435}
3436
Adam Lesinski282e1812014-01-23 18:17:42 -08003437status_t ResourceTable::Entry::makeItABag(const SourcePos& sourcePos)
3438{
3439 if (mType == TYPE_BAG) {
3440 return NO_ERROR;
3441 }
3442 if (mType == TYPE_UNKNOWN) {
3443 mType = TYPE_BAG;
3444 return NO_ERROR;
3445 }
3446 sourcePos.error("Resource entry %s is already defined as a single item.\n"
3447 "%s:%d: Originally defined here.\n",
3448 String8(mName).string(),
3449 mItem.sourcePos.file.string(), mItem.sourcePos.line);
3450 return UNKNOWN_ERROR;
3451}
3452
3453status_t ResourceTable::Entry::setItem(const SourcePos& sourcePos,
3454 const String16& value,
3455 const Vector<StringPool::entry_style_span>* style,
3456 int32_t format,
3457 const bool overwrite)
3458{
3459 Item item(sourcePos, false, value, style);
3460
3461 if (mType == TYPE_BAG) {
Adam Lesinski43a0df02014-08-18 17:14:57 -07003462 if (mBag.size() == 0) {
3463 sourcePos.error("Resource entry %s is already defined as a bag.",
3464 String8(mName).string());
3465 } else {
3466 const Item& item(mBag.valueAt(0));
3467 sourcePos.error("Resource entry %s is already defined as a bag.\n"
3468 "%s:%d: Originally defined here.\n",
3469 String8(mName).string(),
3470 item.sourcePos.file.string(), item.sourcePos.line);
3471 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003472 return UNKNOWN_ERROR;
3473 }
3474 if ( (mType != TYPE_UNKNOWN) && (overwrite == false) ) {
3475 sourcePos.error("Resource entry %s is already defined.\n"
3476 "%s:%d: Originally defined here.\n",
3477 String8(mName).string(),
3478 mItem.sourcePos.file.string(), mItem.sourcePos.line);
3479 return UNKNOWN_ERROR;
3480 }
3481
3482 mType = TYPE_ITEM;
3483 mItem = item;
3484 mItemFormat = format;
3485 return NO_ERROR;
3486}
3487
3488status_t ResourceTable::Entry::addToBag(const SourcePos& sourcePos,
3489 const String16& key, const String16& value,
3490 const Vector<StringPool::entry_style_span>* style,
3491 bool replace, bool isId, int32_t format)
3492{
3493 status_t err = makeItABag(sourcePos);
3494 if (err != NO_ERROR) {
3495 return err;
3496 }
3497
3498 Item item(sourcePos, isId, value, style, format);
3499
3500 // XXX NOTE: there is an error if you try to have a bag with two keys,
3501 // one an attr and one an id, with the same name. Not something we
3502 // currently ever have to worry about.
3503 ssize_t origKey = mBag.indexOfKey(key);
3504 if (origKey >= 0) {
3505 if (!replace) {
3506 const Item& item(mBag.valueAt(origKey));
3507 sourcePos.error("Resource entry %s already has bag item %s.\n"
3508 "%s:%d: Originally defined here.\n",
3509 String8(mName).string(), String8(key).string(),
3510 item.sourcePos.file.string(), item.sourcePos.line);
3511 return UNKNOWN_ERROR;
3512 }
3513 //printf("Replacing %s with %s\n",
3514 // String8(mBag.valueFor(key).value).string(), String8(value).string());
3515 mBag.replaceValueFor(key, item);
3516 }
3517
3518 mBag.add(key, item);
3519 return NO_ERROR;
3520}
3521
Adam Lesinski82a2dd82014-09-17 18:34:15 -07003522status_t ResourceTable::Entry::removeFromBag(const String16& key) {
3523 if (mType != Entry::TYPE_BAG) {
3524 return NO_ERROR;
3525 }
3526
3527 if (mBag.removeItem(key) >= 0) {
3528 return NO_ERROR;
3529 }
3530 return UNKNOWN_ERROR;
3531}
3532
Adam Lesinski282e1812014-01-23 18:17:42 -08003533status_t ResourceTable::Entry::emptyBag(const SourcePos& sourcePos)
3534{
3535 status_t err = makeItABag(sourcePos);
3536 if (err != NO_ERROR) {
3537 return err;
3538 }
3539
3540 mBag.clear();
3541 return NO_ERROR;
3542}
3543
3544status_t ResourceTable::Entry::generateAttributes(ResourceTable* table,
3545 const String16& package)
3546{
3547 const String16 attr16("attr");
3548 const String16 id16("id");
3549 const size_t N = mBag.size();
3550 for (size_t i=0; i<N; i++) {
3551 const String16& key = mBag.keyAt(i);
3552 const Item& it = mBag.valueAt(i);
3553 if (it.isId) {
3554 if (!table->hasBagOrEntry(key, &id16, &package)) {
3555 String16 value("false");
Andreas Gampe87332a72014-10-01 22:03:58 -07003556 if (kIsDebug) {
3557 fprintf(stderr, "Generating %s:id/%s\n",
3558 String8(package).string(),
3559 String8(key).string());
3560 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003561 status_t err = table->addEntry(SourcePos(String8("<generated>"), 0), package,
3562 id16, key, value);
3563 if (err != NO_ERROR) {
3564 return err;
3565 }
3566 }
3567 } else if (!table->hasBagOrEntry(key, &attr16, &package)) {
3568
3569#if 1
3570// fprintf(stderr, "ERROR: Bag attribute '%s' has not been defined.\n",
3571// String8(key).string());
3572// const Item& item(mBag.valueAt(i));
3573// fprintf(stderr, "Referenced from file %s line %d\n",
3574// item.sourcePos.file.string(), item.sourcePos.line);
3575// return UNKNOWN_ERROR;
3576#else
3577 char numberStr[16];
3578 sprintf(numberStr, "%d", ResTable_map::TYPE_ANY);
3579 status_t err = table->addBag(SourcePos("<generated>", 0), package,
3580 attr16, key, String16(""),
3581 String16("^type"),
3582 String16(numberStr), NULL, NULL);
3583 if (err != NO_ERROR) {
3584 return err;
3585 }
3586#endif
3587 }
3588 }
3589 return NO_ERROR;
3590}
3591
3592status_t ResourceTable::Entry::assignResourceIds(ResourceTable* table,
Andreas Gampe2412f842014-09-30 20:55:57 -07003593 const String16& /* package */)
Adam Lesinski282e1812014-01-23 18:17:42 -08003594{
3595 bool hasErrors = false;
3596
3597 if (mType == TYPE_BAG) {
3598 const char* errorMsg;
3599 const String16 style16("style");
3600 const String16 attr16("attr");
3601 const String16 id16("id");
3602 mParentId = 0;
3603 if (mParent.size() > 0) {
3604 mParentId = table->getResId(mParent, &style16, NULL, &errorMsg);
3605 if (mParentId == 0) {
3606 mPos.error("Error retrieving parent for item: %s '%s'.\n",
3607 errorMsg, String8(mParent).string());
3608 hasErrors = true;
3609 }
3610 }
3611 const size_t N = mBag.size();
3612 for (size_t i=0; i<N; i++) {
3613 const String16& key = mBag.keyAt(i);
3614 Item& it = mBag.editValueAt(i);
3615 it.bagKeyId = table->getResId(key,
3616 it.isId ? &id16 : &attr16, NULL, &errorMsg);
3617 //printf("Bag key of %s: #%08x\n", String8(key).string(), it.bagKeyId);
3618 if (it.bagKeyId == 0) {
3619 it.sourcePos.error("Error: %s: %s '%s'.\n", errorMsg,
3620 String8(it.isId ? id16 : attr16).string(),
3621 String8(key).string());
3622 hasErrors = true;
3623 }
3624 }
3625 }
Andreas Gampe2412f842014-09-30 20:55:57 -07003626 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08003627}
3628
3629status_t ResourceTable::Entry::prepareFlatten(StringPool* strings, ResourceTable* table,
3630 const String8* configTypeName, const ConfigDescription* config)
3631{
3632 if (mType == TYPE_ITEM) {
3633 Item& it = mItem;
3634 AccessorCookie ac(it.sourcePos, String8(mName), String8(it.value));
3635 if (!table->stringToValue(&it.parsedValue, strings,
3636 it.value, false, true, 0,
3637 &it.style, NULL, &ac, mItemFormat,
3638 configTypeName, config)) {
3639 return UNKNOWN_ERROR;
3640 }
3641 } else if (mType == TYPE_BAG) {
3642 const size_t N = mBag.size();
3643 for (size_t i=0; i<N; i++) {
3644 const String16& key = mBag.keyAt(i);
3645 Item& it = mBag.editValueAt(i);
3646 AccessorCookie ac(it.sourcePos, String8(key), String8(it.value));
3647 if (!table->stringToValue(&it.parsedValue, strings,
3648 it.value, false, true, it.bagKeyId,
3649 &it.style, NULL, &ac, it.format,
3650 configTypeName, config)) {
3651 return UNKNOWN_ERROR;
3652 }
3653 }
3654 } else {
3655 mPos.error("Error: entry %s is not a single item or a bag.\n",
3656 String8(mName).string());
3657 return UNKNOWN_ERROR;
3658 }
3659 return NO_ERROR;
3660}
3661
3662status_t ResourceTable::Entry::remapStringValue(StringPool* strings)
3663{
3664 if (mType == TYPE_ITEM) {
3665 Item& it = mItem;
3666 if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3667 it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3668 }
3669 } else if (mType == TYPE_BAG) {
3670 const size_t N = mBag.size();
3671 for (size_t i=0; i<N; i++) {
3672 Item& it = mBag.editValueAt(i);
3673 if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3674 it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3675 }
3676 }
3677 } else {
3678 mPos.error("Error: entry %s is not a single item or a bag.\n",
3679 String8(mName).string());
3680 return UNKNOWN_ERROR;
3681 }
3682 return NO_ERROR;
3683}
3684
Andreas Gampe2412f842014-09-30 20:55:57 -07003685ssize_t ResourceTable::Entry::flatten(Bundle* /* bundle */, const sp<AaptFile>& data, bool isPublic)
Adam Lesinski282e1812014-01-23 18:17:42 -08003686{
3687 size_t amt = 0;
3688 ResTable_entry header;
3689 memset(&header, 0, sizeof(header));
3690 header.size = htods(sizeof(header));
Andreas Gampe2412f842014-09-30 20:55:57 -07003691 const type ty = mType;
3692 if (ty == TYPE_BAG) {
3693 header.flags |= htods(header.FLAG_COMPLEX);
Adam Lesinski282e1812014-01-23 18:17:42 -08003694 }
Andreas Gampe2412f842014-09-30 20:55:57 -07003695 if (isPublic) {
3696 header.flags |= htods(header.FLAG_PUBLIC);
3697 }
3698 header.key.index = htodl(mNameIndex);
Adam Lesinski282e1812014-01-23 18:17:42 -08003699 if (ty != TYPE_BAG) {
3700 status_t err = data->writeData(&header, sizeof(header));
3701 if (err != NO_ERROR) {
3702 fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3703 return err;
3704 }
3705
3706 const Item& it = mItem;
3707 Res_value par;
3708 memset(&par, 0, sizeof(par));
3709 par.size = htods(it.parsedValue.size);
3710 par.dataType = it.parsedValue.dataType;
3711 par.res0 = it.parsedValue.res0;
3712 par.data = htodl(it.parsedValue.data);
3713 #if 0
3714 printf("Writing item (%s): type=%d, data=0x%x, res0=0x%x\n",
3715 String8(mName).string(), it.parsedValue.dataType,
3716 it.parsedValue.data, par.res0);
3717 #endif
3718 err = data->writeData(&par, it.parsedValue.size);
3719 if (err != NO_ERROR) {
3720 fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3721 return err;
3722 }
3723 amt += it.parsedValue.size;
3724 } else {
3725 size_t N = mBag.size();
3726 size_t i;
3727 // Create correct ordering of items.
3728 KeyedVector<uint32_t, const Item*> items;
3729 for (i=0; i<N; i++) {
3730 const Item& it = mBag.valueAt(i);
3731 items.add(it.bagKeyId, &it);
3732 }
3733 N = items.size();
3734
3735 ResTable_map_entry mapHeader;
3736 memcpy(&mapHeader, &header, sizeof(header));
3737 mapHeader.size = htods(sizeof(mapHeader));
3738 mapHeader.parent.ident = htodl(mParentId);
3739 mapHeader.count = htodl(N);
3740 status_t err = data->writeData(&mapHeader, sizeof(mapHeader));
3741 if (err != NO_ERROR) {
3742 fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3743 return err;
3744 }
3745
3746 for (i=0; i<N; i++) {
3747 const Item& it = *items.valueAt(i);
3748 ResTable_map map;
3749 map.name.ident = htodl(it.bagKeyId);
3750 map.value.size = htods(it.parsedValue.size);
3751 map.value.dataType = it.parsedValue.dataType;
3752 map.value.res0 = it.parsedValue.res0;
3753 map.value.data = htodl(it.parsedValue.data);
3754 err = data->writeData(&map, sizeof(map));
3755 if (err != NO_ERROR) {
3756 fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3757 return err;
3758 }
3759 amt += sizeof(map);
3760 }
3761 }
3762 return amt;
3763}
3764
3765void ResourceTable::ConfigList::appendComment(const String16& comment,
3766 bool onlyIfEmpty)
3767{
3768 if (comment.size() <= 0) {
3769 return;
3770 }
3771 if (onlyIfEmpty && mComment.size() > 0) {
3772 return;
3773 }
3774 if (mComment.size() > 0) {
3775 mComment.append(String16("\n"));
3776 }
3777 mComment.append(comment);
3778}
3779
3780void ResourceTable::ConfigList::appendTypeComment(const String16& comment)
3781{
3782 if (comment.size() <= 0) {
3783 return;
3784 }
3785 if (mTypeComment.size() > 0) {
3786 mTypeComment.append(String16("\n"));
3787 }
3788 mTypeComment.append(comment);
3789}
3790
3791status_t ResourceTable::Type::addPublic(const SourcePos& sourcePos,
3792 const String16& name,
3793 const uint32_t ident)
3794{
3795 #if 0
3796 int32_t entryIdx = Res_GETENTRY(ident);
3797 if (entryIdx < 0) {
3798 sourcePos.error("Public resource %s/%s has an invalid 0 identifier (0x%08x).\n",
3799 String8(mName).string(), String8(name).string(), ident);
3800 return UNKNOWN_ERROR;
3801 }
3802 #endif
3803
3804 int32_t typeIdx = Res_GETTYPE(ident);
3805 if (typeIdx >= 0) {
3806 typeIdx++;
3807 if (mPublicIndex > 0 && mPublicIndex != typeIdx) {
3808 sourcePos.error("Public resource %s/%s has conflicting type codes for its"
3809 " public identifiers (0x%x vs 0x%x).\n",
3810 String8(mName).string(), String8(name).string(),
3811 mPublicIndex, typeIdx);
3812 return UNKNOWN_ERROR;
3813 }
3814 mPublicIndex = typeIdx;
3815 }
3816
3817 if (mFirstPublicSourcePos == NULL) {
3818 mFirstPublicSourcePos = new SourcePos(sourcePos);
3819 }
3820
3821 if (mPublic.indexOfKey(name) < 0) {
3822 mPublic.add(name, Public(sourcePos, String16(), ident));
3823 } else {
3824 Public& p = mPublic.editValueFor(name);
3825 if (p.ident != ident) {
3826 sourcePos.error("Public resource %s/%s has conflicting public identifiers"
3827 " (0x%08x vs 0x%08x).\n"
3828 "%s:%d: Originally defined here.\n",
3829 String8(mName).string(), String8(name).string(), p.ident, ident,
3830 p.sourcePos.file.string(), p.sourcePos.line);
3831 return UNKNOWN_ERROR;
3832 }
3833 }
3834
3835 return NO_ERROR;
3836}
3837
3838void ResourceTable::Type::canAddEntry(const String16& name)
3839{
3840 mCanAddEntries.add(name);
3841}
3842
3843sp<ResourceTable::Entry> ResourceTable::Type::getEntry(const String16& entry,
3844 const SourcePos& sourcePos,
3845 const ResTable_config* config,
3846 bool doSetIndex,
3847 bool overlay,
3848 bool autoAddOverlay)
3849{
3850 int pos = -1;
3851 sp<ConfigList> c = mConfigs.valueFor(entry);
3852 if (c == NULL) {
3853 if (overlay && !autoAddOverlay && mCanAddEntries.indexOf(entry) < 0) {
3854 sourcePos.error("Resource at %s appears in overlay but not"
3855 " in the base package; use <add-resource> to add.\n",
3856 String8(entry).string());
3857 return NULL;
3858 }
3859 c = new ConfigList(entry, sourcePos);
3860 mConfigs.add(entry, c);
3861 pos = (int)mOrderedConfigs.size();
3862 mOrderedConfigs.add(c);
3863 if (doSetIndex) {
3864 c->setEntryIndex(pos);
3865 }
3866 }
3867
3868 ConfigDescription cdesc;
3869 if (config) cdesc = *config;
3870
3871 sp<Entry> e = c->getEntries().valueFor(cdesc);
3872 if (e == NULL) {
Andreas Gampe2412f842014-09-30 20:55:57 -07003873 if (kIsDebug) {
3874 if (config != NULL) {
3875 printf("New entry at %s:%d: imsi:%d/%d lang:%c%c cnt:%c%c "
Adam Lesinski282e1812014-01-23 18:17:42 -08003876 "orien:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
Andreas Gampe2412f842014-09-30 20:55:57 -07003877 "sw%ddp w%ddp h%ddp layout:%d\n",
Adam Lesinski282e1812014-01-23 18:17:42 -08003878 sourcePos.file.string(), sourcePos.line,
3879 config->mcc, config->mnc,
3880 config->language[0] ? config->language[0] : '-',
3881 config->language[1] ? config->language[1] : '-',
3882 config->country[0] ? config->country[0] : '-',
3883 config->country[1] ? config->country[1] : '-',
3884 config->orientation,
3885 config->touchscreen,
3886 config->density,
3887 config->keyboard,
3888 config->inputFlags,
3889 config->navigation,
3890 config->screenWidth,
3891 config->screenHeight,
3892 config->smallestScreenWidthDp,
3893 config->screenWidthDp,
3894 config->screenHeightDp,
Andreas Gampe2412f842014-09-30 20:55:57 -07003895 config->screenLayout);
3896 } else {
3897 printf("New entry at %s:%d: NULL config\n",
3898 sourcePos.file.string(), sourcePos.line);
3899 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003900 }
3901 e = new Entry(entry, sourcePos);
3902 c->addEntry(cdesc, e);
3903 /*
3904 if (doSetIndex) {
3905 if (pos < 0) {
3906 for (pos=0; pos<(int)mOrderedConfigs.size(); pos++) {
3907 if (mOrderedConfigs[pos] == c) {
3908 break;
3909 }
3910 }
3911 if (pos >= (int)mOrderedConfigs.size()) {
3912 sourcePos.error("Internal error: config not found in mOrderedConfigs when adding entry");
3913 return NULL;
3914 }
3915 }
3916 e->setEntryIndex(pos);
3917 }
3918 */
3919 }
3920
Adam Lesinski282e1812014-01-23 18:17:42 -08003921 return e;
3922}
3923
Adam Lesinski9b624c12014-11-19 17:49:26 -08003924sp<ResourceTable::ConfigList> ResourceTable::Type::removeEntry(const String16& entry) {
3925 ssize_t idx = mConfigs.indexOfKey(entry);
3926 if (idx < 0) {
3927 return NULL;
3928 }
3929
3930 sp<ConfigList> removed = mConfigs.valueAt(idx);
3931 mConfigs.removeItemsAt(idx);
3932
3933 Vector<sp<ConfigList> >::iterator iter = std::find(
3934 mOrderedConfigs.begin(), mOrderedConfigs.end(), removed);
3935 if (iter != mOrderedConfigs.end()) {
3936 mOrderedConfigs.erase(iter);
3937 }
3938
3939 mPublic.removeItem(entry);
3940 return removed;
3941}
3942
3943SortedVector<ConfigDescription> ResourceTable::Type::getUniqueConfigs() const {
3944 SortedVector<ConfigDescription> unique;
3945 const size_t entryCount = mOrderedConfigs.size();
3946 for (size_t i = 0; i < entryCount; i++) {
3947 if (mOrderedConfigs[i] == NULL) {
3948 continue;
3949 }
3950 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& configs =
3951 mOrderedConfigs[i]->getEntries();
3952 const size_t configCount = configs.size();
3953 for (size_t j = 0; j < configCount; j++) {
3954 unique.add(configs.keyAt(j));
3955 }
3956 }
3957 return unique;
3958}
3959
Adam Lesinski282e1812014-01-23 18:17:42 -08003960status_t ResourceTable::Type::applyPublicEntryOrder()
3961{
3962 size_t N = mOrderedConfigs.size();
3963 Vector<sp<ConfigList> > origOrder(mOrderedConfigs);
3964 bool hasError = false;
3965
3966 size_t i;
3967 for (i=0; i<N; i++) {
3968 mOrderedConfigs.replaceAt(NULL, i);
3969 }
3970
3971 const size_t NP = mPublic.size();
3972 //printf("Ordering %d configs from %d public defs\n", N, NP);
3973 size_t j;
3974 for (j=0; j<NP; j++) {
3975 const String16& name = mPublic.keyAt(j);
3976 const Public& p = mPublic.valueAt(j);
3977 int32_t idx = Res_GETENTRY(p.ident);
3978 //printf("Looking for entry \"%s\"/\"%s\" (0x%08x) in %d...\n",
3979 // String8(mName).string(), String8(name).string(), p.ident, N);
3980 bool found = false;
3981 for (i=0; i<N; i++) {
3982 sp<ConfigList> e = origOrder.itemAt(i);
3983 //printf("#%d: \"%s\"\n", i, String8(e->getName()).string());
3984 if (e->getName() == name) {
3985 if (idx >= (int32_t)mOrderedConfigs.size()) {
Adam Lesinski9b624c12014-11-19 17:49:26 -08003986 mOrderedConfigs.resize(idx + 1);
3987 }
3988
3989 if (mOrderedConfigs.itemAt(idx) == NULL) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003990 e->setPublic(true);
3991 e->setPublicSourcePos(p.sourcePos);
3992 mOrderedConfigs.replaceAt(e, idx);
3993 origOrder.removeAt(i);
3994 N--;
3995 found = true;
3996 break;
3997 } else {
3998 sp<ConfigList> oe = mOrderedConfigs.itemAt(idx);
3999
4000 p.sourcePos.error("Multiple entry names declared for public entry"
4001 " identifier 0x%x in type %s (%s vs %s).\n"
4002 "%s:%d: Originally defined here.",
4003 idx+1, String8(mName).string(),
4004 String8(oe->getName()).string(),
4005 String8(name).string(),
4006 oe->getPublicSourcePos().file.string(),
4007 oe->getPublicSourcePos().line);
4008 hasError = true;
4009 }
4010 }
4011 }
4012
4013 if (!found) {
4014 p.sourcePos.error("Public symbol %s/%s declared here is not defined.",
4015 String8(mName).string(), String8(name).string());
4016 hasError = true;
4017 }
4018 }
4019
4020 //printf("Copying back in %d non-public configs, have %d\n", N, origOrder.size());
4021
4022 if (N != origOrder.size()) {
4023 printf("Internal error: remaining private symbol count mismatch\n");
4024 N = origOrder.size();
4025 }
4026
4027 j = 0;
4028 for (i=0; i<N; i++) {
4029 sp<ConfigList> e = origOrder.itemAt(i);
4030 // There will always be enough room for the remaining entries.
4031 while (mOrderedConfigs.itemAt(j) != NULL) {
4032 j++;
4033 }
4034 mOrderedConfigs.replaceAt(e, j);
4035 j++;
4036 }
4037
Andreas Gampe2412f842014-09-30 20:55:57 -07004038 return hasError ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08004039}
4040
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004041ResourceTable::Package::Package(const String16& name, size_t packageId)
4042 : mName(name), mPackageId(packageId),
Adam Lesinski282e1812014-01-23 18:17:42 -08004043 mTypeStringsMapping(0xffffffff),
4044 mKeyStringsMapping(0xffffffff)
4045{
4046}
4047
4048sp<ResourceTable::Type> ResourceTable::Package::getType(const String16& type,
4049 const SourcePos& sourcePos,
4050 bool doSetIndex)
4051{
4052 sp<Type> t = mTypes.valueFor(type);
4053 if (t == NULL) {
4054 t = new Type(type, sourcePos);
4055 mTypes.add(type, t);
4056 mOrderedTypes.add(t);
4057 if (doSetIndex) {
4058 // For some reason the type's index is set to one plus the index
4059 // in the mOrderedTypes list, rather than just the index.
4060 t->setIndex(mOrderedTypes.size());
4061 }
4062 }
4063 return t;
4064}
4065
4066status_t ResourceTable::Package::setTypeStrings(const sp<AaptFile>& data)
4067{
Adam Lesinski282e1812014-01-23 18:17:42 -08004068 status_t err = setStrings(data, &mTypeStrings, &mTypeStringsMapping);
4069 if (err != NO_ERROR) {
4070 fprintf(stderr, "ERROR: Type string data is corrupt!\n");
Adam Lesinski57079512014-07-29 11:51:35 -07004071 return err;
Adam Lesinski282e1812014-01-23 18:17:42 -08004072 }
Adam Lesinski57079512014-07-29 11:51:35 -07004073
4074 // Retain a reference to the new data after we've successfully replaced
4075 // all uses of the old reference (in setStrings() ).
4076 mTypeStringsData = data;
4077 return NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08004078}
4079
4080status_t ResourceTable::Package::setKeyStrings(const sp<AaptFile>& data)
4081{
Adam Lesinski282e1812014-01-23 18:17:42 -08004082 status_t err = setStrings(data, &mKeyStrings, &mKeyStringsMapping);
4083 if (err != NO_ERROR) {
4084 fprintf(stderr, "ERROR: Key string data is corrupt!\n");
Adam Lesinski57079512014-07-29 11:51:35 -07004085 return err;
Adam Lesinski282e1812014-01-23 18:17:42 -08004086 }
Adam Lesinski57079512014-07-29 11:51:35 -07004087
4088 // Retain a reference to the new data after we've successfully replaced
4089 // all uses of the old reference (in setStrings() ).
4090 mKeyStringsData = data;
4091 return NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08004092}
4093
4094status_t ResourceTable::Package::setStrings(const sp<AaptFile>& data,
4095 ResStringPool* strings,
4096 DefaultKeyedVector<String16, uint32_t>* mappings)
4097{
4098 if (data->getData() == NULL) {
4099 return UNKNOWN_ERROR;
4100 }
4101
Adam Lesinski282e1812014-01-23 18:17:42 -08004102 status_t err = strings->setTo(data->getData(), data->getSize());
4103 if (err == NO_ERROR) {
4104 const size_t N = strings->size();
4105 for (size_t i=0; i<N; i++) {
4106 size_t len;
4107 mappings->add(String16(strings->stringAt(i, &len)), i);
4108 }
4109 }
4110 return err;
4111}
4112
4113status_t ResourceTable::Package::applyPublicTypeOrder()
4114{
4115 size_t N = mOrderedTypes.size();
4116 Vector<sp<Type> > origOrder(mOrderedTypes);
4117
4118 size_t i;
4119 for (i=0; i<N; i++) {
4120 mOrderedTypes.replaceAt(NULL, i);
4121 }
4122
4123 for (i=0; i<N; i++) {
4124 sp<Type> t = origOrder.itemAt(i);
4125 int32_t idx = t->getPublicIndex();
4126 if (idx > 0) {
4127 idx--;
4128 while (idx >= (int32_t)mOrderedTypes.size()) {
4129 mOrderedTypes.add();
4130 }
4131 if (mOrderedTypes.itemAt(idx) != NULL) {
4132 sp<Type> ot = mOrderedTypes.itemAt(idx);
4133 t->getFirstPublicSourcePos().error("Multiple type names declared for public type"
4134 " identifier 0x%x (%s vs %s).\n"
4135 "%s:%d: Originally defined here.",
4136 idx, String8(ot->getName()).string(),
4137 String8(t->getName()).string(),
4138 ot->getFirstPublicSourcePos().file.string(),
4139 ot->getFirstPublicSourcePos().line);
4140 return UNKNOWN_ERROR;
4141 }
4142 mOrderedTypes.replaceAt(t, idx);
4143 origOrder.removeAt(i);
4144 i--;
4145 N--;
4146 }
4147 }
4148
4149 size_t j=0;
4150 for (i=0; i<N; i++) {
4151 sp<Type> t = origOrder.itemAt(i);
4152 // There will always be enough room for the remaining types.
4153 while (mOrderedTypes.itemAt(j) != NULL) {
4154 j++;
4155 }
4156 mOrderedTypes.replaceAt(t, j);
4157 }
4158
4159 return NO_ERROR;
4160}
4161
Adam Lesinski9b624c12014-11-19 17:49:26 -08004162void ResourceTable::Package::movePrivateAttrs() {
4163 sp<Type> attr = mTypes.valueFor(String16("attr"));
4164 if (attr == NULL) {
4165 // Nothing to do.
4166 return;
4167 }
4168
4169 Vector<sp<ConfigList> > privateAttrs;
4170
4171 bool hasPublic = false;
4172 const Vector<sp<ConfigList> >& configs = attr->getOrderedConfigs();
4173 const size_t configCount = configs.size();
4174 for (size_t i = 0; i < configCount; i++) {
4175 if (configs[i] == NULL) {
4176 continue;
4177 }
4178
4179 if (attr->isPublic(configs[i]->getName())) {
4180 hasPublic = true;
4181 } else {
4182 privateAttrs.add(configs[i]);
4183 }
4184 }
4185
4186 // Only if we have public attributes do we create a separate type for
4187 // private attributes.
4188 if (!hasPublic) {
4189 return;
4190 }
4191
4192 // Create a new type for private attributes.
4193 sp<Type> privateAttrType = getType(String16(kAttrPrivateType), SourcePos());
4194
4195 const size_t privateAttrCount = privateAttrs.size();
4196 for (size_t i = 0; i < privateAttrCount; i++) {
4197 const sp<ConfigList>& cl = privateAttrs[i];
4198
4199 // Remove the private attributes from their current type.
4200 attr->removeEntry(cl->getName());
4201
4202 // Add it to the new type.
4203 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& entries = cl->getEntries();
4204 const size_t entryCount = entries.size();
4205 for (size_t j = 0; j < entryCount; j++) {
4206 const sp<Entry>& oldEntry = entries[j];
4207 sp<Entry> entry = privateAttrType->getEntry(
4208 cl->getName(), oldEntry->getPos(), &entries.keyAt(j));
4209 *entry = *oldEntry;
4210 }
4211
4212 // Move the symbols to the new type.
4213
4214 }
4215}
4216
Adam Lesinski282e1812014-01-23 18:17:42 -08004217sp<ResourceTable::Package> ResourceTable::getPackage(const String16& package)
4218{
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004219 if (package != mAssetsPackage) {
4220 return NULL;
Adam Lesinski282e1812014-01-23 18:17:42 -08004221 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004222 return mPackages.valueFor(package);
Adam Lesinski282e1812014-01-23 18:17:42 -08004223}
4224
4225sp<ResourceTable::Type> ResourceTable::getType(const String16& package,
4226 const String16& type,
4227 const SourcePos& sourcePos,
4228 bool doSetIndex)
4229{
4230 sp<Package> p = getPackage(package);
4231 if (p == NULL) {
4232 return NULL;
4233 }
4234 return p->getType(type, sourcePos, doSetIndex);
4235}
4236
4237sp<ResourceTable::Entry> ResourceTable::getEntry(const String16& package,
4238 const String16& type,
4239 const String16& name,
4240 const SourcePos& sourcePos,
4241 bool overlay,
4242 const ResTable_config* config,
4243 bool doSetIndex)
4244{
4245 sp<Type> t = getType(package, type, sourcePos, doSetIndex);
4246 if (t == NULL) {
4247 return NULL;
4248 }
4249 return t->getEntry(name, sourcePos, config, doSetIndex, overlay, mBundle->getAutoAddOverlay());
4250}
4251
Adam Lesinskie572c012014-09-19 15:10:04 -07004252sp<ResourceTable::ConfigList> ResourceTable::getConfigList(const String16& package,
4253 const String16& type, const String16& name) const
4254{
4255 const size_t packageCount = mOrderedPackages.size();
4256 for (size_t pi = 0; pi < packageCount; pi++) {
4257 const sp<Package>& p = mOrderedPackages[pi];
4258 if (p == NULL || p->getName() != package) {
4259 continue;
4260 }
4261
4262 const Vector<sp<Type> >& types = p->getOrderedTypes();
4263 const size_t typeCount = types.size();
4264 for (size_t ti = 0; ti < typeCount; ti++) {
4265 const sp<Type>& t = types[ti];
4266 if (t == NULL || t->getName() != type) {
4267 continue;
4268 }
4269
4270 const Vector<sp<ConfigList> >& configs = t->getOrderedConfigs();
4271 const size_t configCount = configs.size();
4272 for (size_t ci = 0; ci < configCount; ci++) {
4273 const sp<ConfigList>& cl = configs[ci];
4274 if (cl == NULL || cl->getName() != name) {
4275 continue;
4276 }
4277
4278 return cl;
4279 }
4280 }
4281 }
4282 return NULL;
4283}
4284
Adam Lesinski282e1812014-01-23 18:17:42 -08004285sp<const ResourceTable::Entry> ResourceTable::getEntry(uint32_t resID,
4286 const ResTable_config* config) const
4287{
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004288 size_t pid = Res_GETPACKAGE(resID)+1;
Adam Lesinski282e1812014-01-23 18:17:42 -08004289 const size_t N = mOrderedPackages.size();
Adam Lesinski282e1812014-01-23 18:17:42 -08004290 sp<Package> p;
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004291 for (size_t i = 0; i < N; i++) {
Adam Lesinski282e1812014-01-23 18:17:42 -08004292 sp<Package> check = mOrderedPackages[i];
4293 if (check->getAssignedId() == pid) {
4294 p = check;
4295 break;
4296 }
4297
4298 }
4299 if (p == NULL) {
4300 fprintf(stderr, "warning: Package not found for resource #%08x\n", resID);
4301 return NULL;
4302 }
4303
4304 int tid = Res_GETTYPE(resID);
4305 if (tid < 0 || tid >= (int)p->getOrderedTypes().size()) {
4306 fprintf(stderr, "warning: Type not found for resource #%08x\n", resID);
4307 return NULL;
4308 }
4309 sp<Type> t = p->getOrderedTypes()[tid];
4310
4311 int eid = Res_GETENTRY(resID);
4312 if (eid < 0 || eid >= (int)t->getOrderedConfigs().size()) {
4313 fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
4314 return NULL;
4315 }
4316
4317 sp<ConfigList> c = t->getOrderedConfigs()[eid];
4318 if (c == NULL) {
4319 fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
4320 return NULL;
4321 }
4322
4323 ConfigDescription cdesc;
4324 if (config) cdesc = *config;
4325 sp<Entry> e = c->getEntries().valueFor(cdesc);
4326 if (c == NULL) {
4327 fprintf(stderr, "warning: Entry configuration not found for resource #%08x\n", resID);
4328 return NULL;
4329 }
4330
4331 return e;
4332}
4333
4334const ResourceTable::Item* ResourceTable::getItem(uint32_t resID, uint32_t attrID) const
4335{
4336 sp<const Entry> e = getEntry(resID);
4337 if (e == NULL) {
4338 return NULL;
4339 }
4340
4341 const size_t N = e->getBag().size();
4342 for (size_t i=0; i<N; i++) {
4343 const Item& it = e->getBag().valueAt(i);
4344 if (it.bagKeyId == 0) {
4345 fprintf(stderr, "warning: ID not yet assigned to '%s' in bag '%s'\n",
4346 String8(e->getName()).string(),
4347 String8(e->getBag().keyAt(i)).string());
4348 }
4349 if (it.bagKeyId == attrID) {
4350 return &it;
4351 }
4352 }
4353
4354 return NULL;
4355}
4356
4357bool ResourceTable::getItemValue(
4358 uint32_t resID, uint32_t attrID, Res_value* outValue)
4359{
4360 const Item* item = getItem(resID, attrID);
4361
4362 bool res = false;
4363 if (item != NULL) {
4364 if (item->evaluating) {
4365 sp<const Entry> e = getEntry(resID);
4366 const size_t N = e->getBag().size();
4367 size_t i;
4368 for (i=0; i<N; i++) {
4369 if (&e->getBag().valueAt(i) == item) {
4370 break;
4371 }
4372 }
4373 fprintf(stderr, "warning: Circular reference detected in key '%s' of bag '%s'\n",
4374 String8(e->getName()).string(),
4375 String8(e->getBag().keyAt(i)).string());
4376 return false;
4377 }
4378 item->evaluating = true;
4379 res = stringToValue(outValue, NULL, item->value, false, false, item->bagKeyId);
Andreas Gampe2412f842014-09-30 20:55:57 -07004380 if (kIsDebug) {
Adam Lesinski282e1812014-01-23 18:17:42 -08004381 if (res) {
4382 printf("getItemValue of #%08x[#%08x] (%s): type=#%08x, data=#%08x\n",
4383 resID, attrID, String8(getEntry(resID)->getName()).string(),
4384 outValue->dataType, outValue->data);
4385 } else {
4386 printf("getItemValue of #%08x[#%08x]: failed\n",
4387 resID, attrID);
4388 }
Andreas Gampe2412f842014-09-30 20:55:57 -07004389 }
Adam Lesinski282e1812014-01-23 18:17:42 -08004390 item->evaluating = false;
4391 }
4392 return res;
4393}
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004394
4395/**
Adam Lesinski28994d82015-01-13 13:42:41 -08004396 * Returns the SDK version at which the attribute was
4397 * made public, or -1 if the resource ID is not an attribute
4398 * or is not public.
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004399 */
Adam Lesinski28994d82015-01-13 13:42:41 -08004400int ResourceTable::getPublicAttributeSdkLevel(uint32_t attrId) const {
4401 if (Res_GETPACKAGE(attrId) + 1 != 0x01 || Res_GETTYPE(attrId) + 1 != 0x01) {
4402 return -1;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004403 }
4404
4405 uint32_t specFlags;
4406 if (!mAssets->getIncludedResources().getResourceFlags(attrId, &specFlags)) {
Adam Lesinski28994d82015-01-13 13:42:41 -08004407 return -1;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004408 }
4409
Adam Lesinski28994d82015-01-13 13:42:41 -08004410 if ((specFlags & ResTable_typeSpec::SPEC_PUBLIC) == 0) {
4411 return -1;
4412 }
4413
4414 const size_t entryId = Res_GETENTRY(attrId);
4415 if (entryId <= 0x021c) {
4416 return 1;
4417 } else if (entryId <= 0x021d) {
4418 return 2;
4419 } else if (entryId <= 0x0269) {
4420 return SDK_CUPCAKE;
4421 } else if (entryId <= 0x028d) {
4422 return SDK_DONUT;
4423 } else if (entryId <= 0x02ad) {
4424 return SDK_ECLAIR;
4425 } else if (entryId <= 0x02b3) {
4426 return SDK_ECLAIR_0_1;
4427 } else if (entryId <= 0x02b5) {
4428 return SDK_ECLAIR_MR1;
4429 } else if (entryId <= 0x02bd) {
4430 return SDK_FROYO;
4431 } else if (entryId <= 0x02cb) {
4432 return SDK_GINGERBREAD;
4433 } else if (entryId <= 0x0361) {
4434 return SDK_HONEYCOMB;
4435 } else if (entryId <= 0x0366) {
4436 return SDK_HONEYCOMB_MR1;
4437 } else if (entryId <= 0x03a6) {
4438 return SDK_HONEYCOMB_MR2;
4439 } else if (entryId <= 0x03ae) {
4440 return SDK_JELLY_BEAN;
4441 } else if (entryId <= 0x03cc) {
4442 return SDK_JELLY_BEAN_MR1;
4443 } else if (entryId <= 0x03da) {
4444 return SDK_JELLY_BEAN_MR2;
4445 } else if (entryId <= 0x03f1) {
4446 return SDK_KITKAT;
4447 } else if (entryId <= 0x03f6) {
4448 return SDK_KITKAT_WATCH;
4449 } else if (entryId <= 0x04ce) {
4450 return SDK_LOLLIPOP;
4451 } else {
4452 // Anything else is marked as defined in
4453 // SDK_LOLLIPOP_MR1 since after this
4454 // version no attribute compat work
4455 // needs to be done.
4456 return SDK_LOLLIPOP_MR1;
4457 }
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004458}
4459
Adam Lesinski28994d82015-01-13 13:42:41 -08004460/**
4461 * First check the Manifest, then check the command line flag.
4462 */
4463static int getMinSdkVersion(const Bundle* bundle) {
4464 if (bundle->getManifestMinSdkVersion() != NULL && strlen(bundle->getManifestMinSdkVersion()) > 0) {
4465 return atoi(bundle->getManifestMinSdkVersion());
4466 } else if (bundle->getMinSdkVersion() != NULL && strlen(bundle->getMinSdkVersion()) > 0) {
4467 return atoi(bundle->getMinSdkVersion());
Adam Lesinskie572c012014-09-19 15:10:04 -07004468 }
Adam Lesinski28994d82015-01-13 13:42:41 -08004469 return 0;
Adam Lesinskie572c012014-09-19 15:10:04 -07004470}
4471
Adam Lesinskibeb9e332015-08-14 13:16:18 -07004472bool ResourceTable::shouldGenerateVersionedResource(
4473 const sp<ResourceTable::ConfigList>& configList,
4474 const ConfigDescription& sourceConfig,
4475 const int sdkVersionToGenerate) {
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004476 assert(sdkVersionToGenerate > sourceConfig.sdkVersion);
4477 const DefaultKeyedVector<ConfigDescription, sp<ResourceTable::Entry>>& entries
4478 = configList->getEntries();
4479 ssize_t idx = entries.indexOfKey(sourceConfig);
4480
4481 // The source config came from this list, so it should be here.
4482 assert(idx >= 0);
4483
Adam Lesinskibeb9e332015-08-14 13:16:18 -07004484 // The next configuration either only varies in sdkVersion, or it is completely different
4485 // and therefore incompatible. If it is incompatible, we must generate the versioned resource.
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004486
Adam Lesinskibeb9e332015-08-14 13:16:18 -07004487 // NOTE: The ordering of configurations takes sdkVersion as higher precedence than other
4488 // qualifiers, so we need to iterate through the entire list to be sure there
4489 // are no higher sdk level versions of this resource.
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004490 ConfigDescription tempConfig(sourceConfig);
Adam Lesinskibeb9e332015-08-14 13:16:18 -07004491 for (size_t i = static_cast<size_t>(idx) + 1; i < entries.size(); i++) {
4492 const ConfigDescription& nextConfig = entries.keyAt(i);
4493 tempConfig.sdkVersion = nextConfig.sdkVersion;
4494 if (tempConfig == nextConfig) {
4495 // The two configs are the same, check the sdk version.
4496 return sdkVersionToGenerate < nextConfig.sdkVersion;
4497 }
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004498 }
Adam Lesinskibeb9e332015-08-14 13:16:18 -07004499
4500 // No match was found, so we should generate the versioned resource.
4501 return true;
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004502}
4503
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004504/**
4505 * Modifies the entries in the resource table to account for compatibility
4506 * issues with older versions of Android.
4507 *
4508 * This primarily handles the issue of private/public attribute clashes
4509 * in framework resources.
4510 *
4511 * AAPT has traditionally assigned resource IDs to public attributes,
4512 * and then followed those public definitions with private attributes.
4513 *
4514 * --- PUBLIC ---
4515 * | 0x01010234 | attr/color
4516 * | 0x01010235 | attr/background
4517 *
4518 * --- PRIVATE ---
4519 * | 0x01010236 | attr/secret
4520 * | 0x01010237 | attr/shhh
4521 *
4522 * Each release, when attributes are added, they take the place of the private
4523 * attributes and the private attributes are shifted down again.
4524 *
4525 * --- PUBLIC ---
4526 * | 0x01010234 | attr/color
4527 * | 0x01010235 | attr/background
4528 * | 0x01010236 | attr/shinyNewAttr
4529 * | 0x01010237 | attr/highlyValuedFeature
4530 *
4531 * --- PRIVATE ---
4532 * | 0x01010238 | attr/secret
4533 * | 0x01010239 | attr/shhh
4534 *
4535 * Platform code may look for private attributes set in a theme. If an app
4536 * compiled against a newer version of the platform uses a new public
4537 * attribute that happens to have the same ID as the private attribute
4538 * the older platform is expecting, then the behavior is undefined.
4539 *
4540 * We get around this by detecting any newly defined attributes (in L),
4541 * copy the resource into a -v21 qualified resource, and delete the
4542 * attribute from the original resource. This ensures that older platforms
4543 * don't see the new attribute, but when running on L+ platforms, the
4544 * attribute will be respected.
4545 */
4546status_t ResourceTable::modifyForCompat(const Bundle* bundle) {
Adam Lesinski28994d82015-01-13 13:42:41 -08004547 const int minSdk = getMinSdkVersion(bundle);
4548 if (minSdk >= SDK_LOLLIPOP_MR1) {
4549 // Lollipop MR1 and up handles public attributes differently, no
4550 // need to do any compat modifications.
Adam Lesinskie572c012014-09-19 15:10:04 -07004551 return NO_ERROR;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004552 }
4553
4554 const String16 attr16("attr");
4555
4556 const size_t packageCount = mOrderedPackages.size();
4557 for (size_t pi = 0; pi < packageCount; pi++) {
4558 sp<Package> p = mOrderedPackages.itemAt(pi);
4559 if (p == NULL || p->getTypes().size() == 0) {
4560 // Empty, skip!
4561 continue;
4562 }
4563
4564 const size_t typeCount = p->getOrderedTypes().size();
4565 for (size_t ti = 0; ti < typeCount; ti++) {
4566 sp<Type> t = p->getOrderedTypes().itemAt(ti);
4567 if (t == NULL) {
4568 continue;
4569 }
4570
4571 const size_t configCount = t->getOrderedConfigs().size();
4572 for (size_t ci = 0; ci < configCount; ci++) {
4573 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
4574 if (c == NULL) {
4575 continue;
4576 }
4577
4578 Vector<key_value_pair_t<ConfigDescription, sp<Entry> > > entriesToAdd;
4579 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& entries =
4580 c->getEntries();
4581 const size_t entryCount = entries.size();
4582 for (size_t ei = 0; ei < entryCount; ei++) {
4583 sp<Entry> e = entries.valueAt(ei);
4584 if (e == NULL || e->getType() != Entry::TYPE_BAG) {
4585 continue;
4586 }
4587
4588 const ConfigDescription& config = entries.keyAt(ei);
Adam Lesinski28994d82015-01-13 13:42:41 -08004589 if (config.sdkVersion >= SDK_LOLLIPOP_MR1) {
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004590 continue;
4591 }
4592
Adam Lesinski28994d82015-01-13 13:42:41 -08004593 KeyedVector<int, Vector<String16> > attributesToRemove;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004594 const KeyedVector<String16, Item>& bag = e->getBag();
4595 const size_t bagCount = bag.size();
4596 for (size_t bi = 0; bi < bagCount; bi++) {
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004597 const uint32_t attrId = getResId(bag.keyAt(bi), &attr16);
Adam Lesinski28994d82015-01-13 13:42:41 -08004598 const int sdkLevel = getPublicAttributeSdkLevel(attrId);
4599 if (sdkLevel > 1 && sdkLevel > config.sdkVersion && sdkLevel > minSdk) {
4600 AaptUtil::appendValue(attributesToRemove, sdkLevel, bag.keyAt(bi));
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004601 }
4602 }
4603
4604 if (attributesToRemove.isEmpty()) {
4605 continue;
4606 }
4607
Adam Lesinski28994d82015-01-13 13:42:41 -08004608 const size_t sdkCount = attributesToRemove.size();
4609 for (size_t i = 0; i < sdkCount; i++) {
4610 const int sdkLevel = attributesToRemove.keyAt(i);
4611
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004612 if (!shouldGenerateVersionedResource(c, config, sdkLevel)) {
4613 // There is a style that will override this generated one.
4614 continue;
4615 }
4616
Adam Lesinski28994d82015-01-13 13:42:41 -08004617 // Duplicate the entry under the same configuration
4618 // but with sdkVersion == sdkLevel.
4619 ConfigDescription newConfig(config);
4620 newConfig.sdkVersion = sdkLevel;
4621
4622 sp<Entry> newEntry = new Entry(*e);
4623
4624 // Remove all items that have a higher SDK level than
4625 // the one we are synthesizing.
4626 for (size_t j = 0; j < sdkCount; j++) {
4627 if (j == i) {
4628 continue;
4629 }
4630
4631 if (attributesToRemove.keyAt(j) > sdkLevel) {
4632 const size_t attrCount = attributesToRemove[j].size();
4633 for (size_t k = 0; k < attrCount; k++) {
4634 newEntry->removeFromBag(attributesToRemove[j][k]);
4635 }
4636 }
4637 }
4638
4639 entriesToAdd.add(key_value_pair_t<ConfigDescription, sp<Entry> >(
4640 newConfig, newEntry));
4641 }
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004642
4643 // Remove the attribute from the original.
4644 for (size_t i = 0; i < attributesToRemove.size(); i++) {
Adam Lesinski28994d82015-01-13 13:42:41 -08004645 for (size_t j = 0; j < attributesToRemove[i].size(); j++) {
4646 e->removeFromBag(attributesToRemove[i][j]);
4647 }
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004648 }
4649 }
4650
4651 const size_t entriesToAddCount = entriesToAdd.size();
4652 for (size_t i = 0; i < entriesToAddCount; i++) {
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004653 assert(entries.indexOfKey(entriesToAdd[i].key) < 0);
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004654
Adam Lesinskif15de2e2014-10-03 14:57:28 -07004655 if (bundle->getVerbose()) {
4656 entriesToAdd[i].value->getPos()
4657 .printf("using v%d attributes; synthesizing resource %s:%s/%s for configuration %s.",
Adam Lesinski28994d82015-01-13 13:42:41 -08004658 entriesToAdd[i].key.sdkVersion,
Adam Lesinskif15de2e2014-10-03 14:57:28 -07004659 String8(p->getName()).string(),
4660 String8(t->getName()).string(),
4661 String8(entriesToAdd[i].value->getName()).string(),
4662 entriesToAdd[i].key.toString().string());
4663 }
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004664
Adam Lesinski978ab9d2014-09-24 19:02:52 -07004665 sp<Entry> newEntry = t->getEntry(c->getName(),
4666 entriesToAdd[i].value->getPos(),
4667 &entriesToAdd[i].key);
4668
4669 *newEntry = *entriesToAdd[i].value;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004670 }
4671 }
4672 }
4673 }
4674 return NO_ERROR;
4675}
Adam Lesinskie572c012014-09-19 15:10:04 -07004676
4677status_t ResourceTable::modifyForCompat(const Bundle* bundle,
4678 const String16& resourceName,
4679 const sp<AaptFile>& target,
4680 const sp<XMLNode>& root) {
Adam Lesinski6e460562015-04-21 14:20:15 -07004681 const String16 vector16("vector");
4682 const String16 animatedVector16("animated-vector");
4683
Adam Lesinski28994d82015-01-13 13:42:41 -08004684 const int minSdk = getMinSdkVersion(bundle);
4685 if (minSdk >= SDK_LOLLIPOP_MR1) {
4686 // Lollipop MR1 and up handles public attributes differently, no
4687 // need to do any compat modifications.
Adam Lesinskie572c012014-09-19 15:10:04 -07004688 return NO_ERROR;
4689 }
4690
Adam Lesinski28994d82015-01-13 13:42:41 -08004691 const ConfigDescription config(target->getGroupEntry().toParams());
4692 if (target->getResourceType() == "" || config.sdkVersion >= SDK_LOLLIPOP_MR1) {
Adam Lesinski6e460562015-04-21 14:20:15 -07004693 // Skip resources that have no type (AndroidManifest.xml) or are already version qualified
4694 // with v21 or higher.
Adam Lesinskie572c012014-09-19 15:10:04 -07004695 return NO_ERROR;
4696 }
4697
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004698 sp<XMLNode> newRoot = NULL;
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004699 int sdkVersionToGenerate = SDK_LOLLIPOP_MR1;
Adam Lesinskie572c012014-09-19 15:10:04 -07004700
4701 Vector<sp<XMLNode> > nodesToVisit;
4702 nodesToVisit.push(root);
4703 while (!nodesToVisit.isEmpty()) {
4704 sp<XMLNode> node = nodesToVisit.top();
4705 nodesToVisit.pop();
4706
Adam Lesinski6e460562015-04-21 14:20:15 -07004707 if (bundle->getNoVersionVectors() && (node->getElementName() == vector16 ||
4708 node->getElementName() == animatedVector16)) {
4709 // We were told not to version vector tags, so skip the children here.
4710 continue;
4711 }
4712
Adam Lesinskie572c012014-09-19 15:10:04 -07004713 const Vector<XMLNode::attribute_entry>& attrs = node->getAttributes();
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004714 for (size_t i = 0; i < attrs.size(); i++) {
Adam Lesinskie572c012014-09-19 15:10:04 -07004715 const XMLNode::attribute_entry& attr = attrs[i];
Adam Lesinski28994d82015-01-13 13:42:41 -08004716 const int sdkLevel = getPublicAttributeSdkLevel(attr.nameResId);
4717 if (sdkLevel > 1 && sdkLevel > config.sdkVersion && sdkLevel > minSdk) {
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004718 if (newRoot == NULL) {
4719 newRoot = root->clone();
4720 }
4721
Adam Lesinski28994d82015-01-13 13:42:41 -08004722 // Find the smallest sdk version that we need to synthesize for
4723 // and do that one. Subsequent versions will be processed on
4724 // the next pass.
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004725 sdkVersionToGenerate = std::min(sdkLevel, sdkVersionToGenerate);
Adam Lesinski28994d82015-01-13 13:42:41 -08004726
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004727 if (bundle->getVerbose()) {
4728 SourcePos(node->getFilename(), node->getStartLineNumber()).printf(
4729 "removing attribute %s%s%s from <%s>",
4730 String8(attr.ns).string(),
4731 (attr.ns.size() == 0 ? "" : ":"),
4732 String8(attr.name).string(),
4733 String8(node->getElementName()).string());
4734 }
4735 node->removeAttribute(i);
4736 i--;
Adam Lesinskie572c012014-09-19 15:10:04 -07004737 }
4738 }
4739
4740 // Schedule a visit to the children.
4741 const Vector<sp<XMLNode> >& children = node->getChildren();
4742 const size_t childCount = children.size();
4743 for (size_t i = 0; i < childCount; i++) {
4744 nodesToVisit.push(children[i]);
4745 }
4746 }
4747
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004748 if (newRoot == NULL) {
Adam Lesinskie572c012014-09-19 15:10:04 -07004749 return NO_ERROR;
4750 }
4751
Adam Lesinskie572c012014-09-19 15:10:04 -07004752 // Look to see if we already have an overriding v21 configuration.
4753 sp<ConfigList> cl = getConfigList(String16(mAssets->getPackage()),
4754 String16(target->getResourceType()), resourceName);
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004755 if (shouldGenerateVersionedResource(cl, config, sdkVersionToGenerate)) {
Adam Lesinskie572c012014-09-19 15:10:04 -07004756 // We don't have an overriding entry for v21, so we must duplicate this one.
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004757 ConfigDescription newConfig(config);
4758 newConfig.sdkVersion = sdkVersionToGenerate;
Adam Lesinskie572c012014-09-19 15:10:04 -07004759 sp<AaptFile> newFile = new AaptFile(target->getSourceFile(),
4760 AaptGroupEntry(newConfig), target->getResourceType());
Adam Lesinski9d0f7d42015-10-28 15:44:27 -07004761 String8 resPath = String8::format("res/%s/%s.xml",
Adam Lesinskie572c012014-09-19 15:10:04 -07004762 newFile->getGroupEntry().toDirName(target->getResourceType()).string(),
Adam Lesinski9d0f7d42015-10-28 15:44:27 -07004763 String8(resourceName).string());
Adam Lesinskie572c012014-09-19 15:10:04 -07004764 resPath.convertToResPath();
4765
4766 // Add a resource table entry.
Adam Lesinskif15de2e2014-10-03 14:57:28 -07004767 if (bundle->getVerbose()) {
4768 SourcePos(target->getSourceFile(), -1).printf(
4769 "using v%d attributes; synthesizing resource %s:%s/%s for configuration %s.",
Adam Lesinski28994d82015-01-13 13:42:41 -08004770 newConfig.sdkVersion,
Adam Lesinskif15de2e2014-10-03 14:57:28 -07004771 mAssets->getPackage().string(),
4772 newFile->getResourceType().string(),
4773 String8(resourceName).string(),
4774 newConfig.toString().string());
4775 }
Adam Lesinskie572c012014-09-19 15:10:04 -07004776
4777 addEntry(SourcePos(),
4778 String16(mAssets->getPackage()),
4779 String16(target->getResourceType()),
4780 resourceName,
4781 String16(resPath),
4782 NULL,
4783 &newConfig);
4784
4785 // Schedule this to be compiled.
4786 CompileResourceWorkItem item;
4787 item.resourceName = resourceName;
4788 item.resPath = resPath;
4789 item.file = newFile;
Adam Lesinski9d0f7d42015-10-28 15:44:27 -07004790 item.xmlRoot = newRoot;
Adam Lesinskie572c012014-09-19 15:10:04 -07004791 mWorkQueue.push(item);
4792 }
4793
Adam Lesinskie572c012014-09-19 15:10:04 -07004794 return NO_ERROR;
4795}
Adam Lesinskide7de472014-11-03 12:03:08 -08004796
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004797void ResourceTable::getDensityVaryingResources(
4798 KeyedVector<Symbol, Vector<SymbolDefinition> >& resources) {
Adam Lesinskide7de472014-11-03 12:03:08 -08004799 const ConfigDescription nullConfig;
4800
4801 const size_t packageCount = mOrderedPackages.size();
4802 for (size_t p = 0; p < packageCount; p++) {
4803 const Vector<sp<Type> >& types = mOrderedPackages[p]->getOrderedTypes();
4804 const size_t typeCount = types.size();
4805 for (size_t t = 0; t < typeCount; t++) {
4806 const Vector<sp<ConfigList> >& configs = types[t]->getOrderedConfigs();
4807 const size_t configCount = configs.size();
4808 for (size_t c = 0; c < configCount; c++) {
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004809 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& configEntries
4810 = configs[c]->getEntries();
Adam Lesinskide7de472014-11-03 12:03:08 -08004811 const size_t configEntryCount = configEntries.size();
4812 for (size_t ce = 0; ce < configEntryCount; ce++) {
4813 const ConfigDescription& config = configEntries.keyAt(ce);
4814 if (AaptConfig::isDensityOnly(config)) {
4815 // This configuration only varies with regards to density.
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004816 const Symbol symbol(
4817 mOrderedPackages[p]->getName(),
Adam Lesinskide7de472014-11-03 12:03:08 -08004818 types[t]->getName(),
4819 configs[c]->getName(),
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004820 getResId(mOrderedPackages[p], types[t],
4821 configs[c]->getEntryIndex()));
Adam Lesinskide7de472014-11-03 12:03:08 -08004822
4823 const sp<Entry>& entry = configEntries.valueAt(ce);
Adam Lesinskif45d2fa2015-07-28 12:10:36 -07004824 AaptUtil::appendValue(resources, symbol,
4825 SymbolDefinition(symbol, config, entry->getPos()));
Adam Lesinskide7de472014-11-03 12:03:08 -08004826 }
4827 }
4828 }
4829 }
4830 }
4831}
Adam Lesinski9d0f7d42015-10-28 15:44:27 -07004832
4833static String16 buildNamespace(const String16& package) {
4834 return String16("http://schemas.android.com/apk/res/") + package;
4835}
4836
4837static sp<XMLNode> findOnlyChildElement(const sp<XMLNode>& parent) {
4838 const Vector<sp<XMLNode> >& children = parent->getChildren();
4839 sp<XMLNode> onlyChild;
4840 for (size_t i = 0; i < children.size(); i++) {
4841 if (children[i]->getType() != XMLNode::TYPE_CDATA) {
4842 if (onlyChild != NULL) {
4843 return NULL;
4844 }
4845 onlyChild = children[i];
4846 }
4847 }
4848 return onlyChild;
4849}
4850
4851/**
4852 * Detects use of the `bundle' format and extracts nested resources into their own top level
4853 * resources. The bundle format looks like this:
4854 *
4855 * <!-- res/drawable/bundle.xml -->
4856 * <animated-vector xmlns:aapt="http://schemas.android.com/aapt">
4857 * <aapt:attr name="android:drawable">
4858 * <vector android:width="60dp"
4859 * android:height="60dp">
4860 * <path android:name="v"
4861 * android:fillColor="#000000"
4862 * android:pathData="M300,70 l 0,-70 70,..." />
4863 * </vector>
4864 * </aapt:attr>
4865 * </animated-vector>
4866 *
4867 * When AAPT sees the <aapt:attr> tag, it will extract its single element and its children
4868 * into a new high-level resource, assigning it a name and ID. Then value of the `name`
4869 * attribute must be a resource attribute. That resource attribute is inserted into the parent
4870 * with the reference to the extracted resource as the value.
4871 *
4872 * <!-- res/drawable/bundle.xml -->
4873 * <animated-vector android:drawable="@drawable/bundle_1.xml">
4874 * </animated-vector>
4875 *
4876 * <!-- res/drawable/bundle_1.xml -->
4877 * <vector android:width="60dp"
4878 * android:height="60dp">
4879 * <path android:name="v"
4880 * android:fillColor="#000000"
4881 * android:pathData="M300,70 l 0,-70 70,..." />
4882 * </vector>
4883 */
4884status_t ResourceTable::processBundleFormat(const Bundle* bundle,
4885 const String16& resourceName,
4886 const sp<AaptFile>& target,
4887 const sp<XMLNode>& root) {
4888 Vector<sp<XMLNode> > namespaces;
4889 if (root->getType() == XMLNode::TYPE_NAMESPACE) {
4890 namespaces.push(root);
4891 }
4892 return processBundleFormatImpl(bundle, resourceName, target, root, &namespaces);
4893}
4894
4895status_t ResourceTable::processBundleFormatImpl(const Bundle* bundle,
4896 const String16& resourceName,
4897 const sp<AaptFile>& target,
4898 const sp<XMLNode>& parent,
4899 Vector<sp<XMLNode> >* namespaces) {
4900 const String16 kAaptNamespaceUri16("http://schemas.android.com/aapt");
4901 const String16 kName16("name");
4902 const String16 kAttr16("attr");
4903 const String16 kAssetPackage16(mAssets->getPackage());
4904
4905 Vector<sp<XMLNode> >& children = parent->getChildren();
4906 for (size_t i = 0; i < children.size(); i++) {
4907 const sp<XMLNode>& child = children[i];
4908
4909 if (child->getType() == XMLNode::TYPE_CDATA) {
4910 continue;
4911 } else if (child->getType() == XMLNode::TYPE_NAMESPACE) {
4912 namespaces->push(child);
4913 }
4914
4915 if (child->getElementNamespace() != kAaptNamespaceUri16 ||
4916 child->getElementName() != kAttr16) {
4917 status_t result = processBundleFormatImpl(bundle, resourceName, target, child,
4918 namespaces);
4919 if (result != NO_ERROR) {
4920 return result;
4921 }
4922
4923 if (child->getType() == XMLNode::TYPE_NAMESPACE) {
4924 namespaces->pop();
4925 }
4926 continue;
4927 }
4928
4929 // This is the <aapt:attr> tag. Look for the 'name' attribute.
4930 SourcePos source(child->getFilename(), child->getStartLineNumber());
4931
4932 sp<XMLNode> nestedRoot = findOnlyChildElement(child);
4933 if (nestedRoot == NULL) {
4934 source.error("<%s:%s> must have exactly one child element",
4935 String8(child->getElementNamespace()).string(),
4936 String8(child->getElementName()).string());
4937 return UNKNOWN_ERROR;
4938 }
4939
4940 // Find the special attribute 'parent-attr'. This attribute's value contains
4941 // the resource attribute for which this element should be assigned in the parent.
4942 const XMLNode::attribute_entry* attr = child->getAttribute(String16(), kName16);
4943 if (attr == NULL) {
4944 source.error("inline resource definition must specify an attribute via 'name'");
4945 return UNKNOWN_ERROR;
4946 }
4947
4948 // Parse the attribute name.
4949 const char* errorMsg = NULL;
4950 String16 attrPackage, attrType, attrName;
4951 bool result = ResTable::expandResourceRef(attr->string.string(),
4952 attr->string.size(),
4953 &attrPackage, &attrType, &attrName,
4954 &kAttr16, &kAssetPackage16,
4955 &errorMsg, NULL);
4956 if (!result) {
4957 source.error("invalid attribute name for 'name': %s", errorMsg);
4958 return UNKNOWN_ERROR;
4959 }
4960
4961 if (attrType != kAttr16) {
4962 // The value of the 'name' attribute must be an attribute reference.
4963 source.error("value of 'name' must be an attribute reference.");
4964 return UNKNOWN_ERROR;
4965 }
4966
4967 // Generate a name for this nested resource and try to add it to the table.
4968 // We do this in a loop because the name may be taken, in which case we will
4969 // increment a suffix until we succeed.
4970 String8 nestedResourceName;
4971 String8 nestedResourcePath;
4972 int suffix = 1;
4973 while (true) {
4974 // This child element will be extracted into its own resource file.
4975 // Generate a name and path for it from its parent.
4976 nestedResourceName = String8::format("%s_%d",
4977 String8(resourceName).string(), suffix++);
4978 nestedResourcePath = String8::format("res/%s/%s.xml",
4979 target->getGroupEntry().toDirName(target->getResourceType())
4980 .string(),
4981 nestedResourceName.string());
4982
4983 // Lookup or create the entry for this name.
4984 sp<Entry> entry = getEntry(kAssetPackage16,
4985 String16(target->getResourceType()),
4986 String16(nestedResourceName),
4987 source,
4988 false,
4989 &target->getGroupEntry().toParams(),
4990 true);
4991 if (entry == NULL) {
4992 return UNKNOWN_ERROR;
4993 }
4994
4995 if (entry->getType() == Entry::TYPE_UNKNOWN) {
4996 // The value for this resource has never been set,
4997 // meaning we're good!
4998 entry->setItem(source, String16(nestedResourcePath));
4999 break;
5000 }
5001
5002 // We failed (name already exists), so try with a different name
5003 // (increment the suffix).
5004 }
5005
5006 if (bundle->getVerbose()) {
5007 source.printf("generating nested resource %s:%s/%s",
5008 mAssets->getPackage().string(), target->getResourceType().string(),
5009 nestedResourceName.string());
5010 }
5011
5012 // Build the attribute reference and assign it to the parent.
5013 String16 nestedResourceRef = String16(String8::format("@%s:%s/%s",
5014 mAssets->getPackage().string(), target->getResourceType().string(),
5015 nestedResourceName.string()));
5016
5017 String16 attrNs = buildNamespace(attrPackage);
5018 if (parent->getAttribute(attrNs, attrName) != NULL) {
5019 SourcePos(parent->getFilename(), parent->getStartLineNumber())
5020 .error("parent of nested resource already defines attribute '%s:%s'",
5021 String8(attrPackage).string(), String8(attrName).string());
5022 return UNKNOWN_ERROR;
5023 }
5024
5025 // Add the reference to the inline resource.
5026 parent->addAttribute(attrNs, attrName, nestedResourceRef);
5027
5028 // Remove the <aapt:attr> child element from here.
5029 children.removeAt(i);
5030 i--;
5031
5032 // Append all namespace declarations that we've seen on this branch in the XML tree
5033 // to this resource.
5034 // We do this because the order of namespace declarations and prefix usage is determined
5035 // by the developer and we do not want to override any decisions. Be conservative.
5036 for (size_t nsIndex = namespaces->size(); nsIndex > 0; nsIndex--) {
5037 const sp<XMLNode>& ns = namespaces->itemAt(nsIndex - 1);
5038 sp<XMLNode> newNs = XMLNode::newNamespace(ns->getFilename(), ns->getNamespacePrefix(),
5039 ns->getNamespaceUri());
5040 newNs->addChild(nestedRoot);
5041 nestedRoot = newNs;
5042 }
5043
5044 // Schedule compilation of the nested resource.
5045 CompileResourceWorkItem workItem;
5046 workItem.resPath = nestedResourcePath;
5047 workItem.resourceName = String16(nestedResourceName);
5048 workItem.xmlRoot = nestedRoot;
5049 workItem.file = new AaptFile(target->getSourceFile(), target->getGroupEntry(),
5050 target->getResourceType());
5051 mWorkQueue.push(workItem);
5052 }
5053 return NO_ERROR;
5054}