blob: 69f1ec395ad7a41aea51a5d91306c0d9604776d4 [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
15#include <androidfw/ResourceTypes.h>
16#include <utils/ByteOrder.h>
Adam Lesinski82a2dd82014-09-17 18:34:15 -070017#include <utils/TypeHelpers.h>
Adam Lesinski282e1812014-01-23 18:17:42 -080018#include <stdarg.h>
19
Andreas Gampe2412f842014-09-30 20:55:57 -070020// SSIZE: mingw does not have signed size_t == ssize_t.
21// STATUST: mingw does seem to redefine UNKNOWN_ERROR from our enum value, so a cast is necessary.
22#if HAVE_PRINTF_ZD
23# define SSIZE(x) x
24# define STATUST(x) x
25#else
26# define SSIZE(x) (signed size_t)x
27# define STATUST(x) (status_t)x
28#endif
29
30// Set to true for noisy debug output.
31static const bool kIsDebug = false;
32
33#if PRINT_STRING_METRICS
34static const bool kPrintStringMetrics = true;
35#else
36static const bool kPrintStringMetrics = false;
37#endif
Adam Lesinski282e1812014-01-23 18:17:42 -080038
Adam Lesinskie572c012014-09-19 15:10:04 -070039status_t compileXmlFile(const Bundle* bundle,
40 const sp<AaptAssets>& assets,
41 const String16& resourceName,
Adam Lesinski282e1812014-01-23 18:17:42 -080042 const sp<AaptFile>& target,
43 ResourceTable* table,
44 int options)
45{
46 sp<XMLNode> root = XMLNode::parse(target);
47 if (root == NULL) {
48 return UNKNOWN_ERROR;
49 }
Anton Krumina2ef5c02014-03-12 14:46:44 -070050
Adam Lesinskie572c012014-09-19 15:10:04 -070051 return compileXmlFile(bundle, assets, resourceName, root, target, table, options);
Adam Lesinski282e1812014-01-23 18:17:42 -080052}
53
Adam Lesinskie572c012014-09-19 15:10:04 -070054status_t compileXmlFile(const Bundle* bundle,
55 const sp<AaptAssets>& assets,
56 const String16& resourceName,
Adam Lesinski282e1812014-01-23 18:17:42 -080057 const sp<AaptFile>& target,
58 const sp<AaptFile>& outTarget,
59 ResourceTable* table,
60 int options)
61{
62 sp<XMLNode> root = XMLNode::parse(target);
63 if (root == NULL) {
64 return UNKNOWN_ERROR;
65 }
66
Adam Lesinskie572c012014-09-19 15:10:04 -070067 return compileXmlFile(bundle, assets, resourceName, root, outTarget, table, options);
Adam Lesinski282e1812014-01-23 18:17:42 -080068}
69
Adam Lesinskie572c012014-09-19 15:10:04 -070070status_t compileXmlFile(const Bundle* bundle,
71 const sp<AaptAssets>& assets,
72 const String16& resourceName,
Adam Lesinski282e1812014-01-23 18:17:42 -080073 const sp<XMLNode>& root,
74 const sp<AaptFile>& target,
75 ResourceTable* table,
76 int options)
77{
78 if ((options&XML_COMPILE_STRIP_WHITESPACE) != 0) {
79 root->removeWhitespace(true, NULL);
80 } else if ((options&XML_COMPILE_COMPACT_WHITESPACE) != 0) {
81 root->removeWhitespace(false, NULL);
82 }
83
84 if ((options&XML_COMPILE_UTF8) != 0) {
85 root->setUTF8(true);
86 }
87
88 bool hasErrors = false;
89
90 if ((options&XML_COMPILE_ASSIGN_ATTRIBUTE_IDS) != 0) {
91 status_t err = root->assignResourceIds(assets, table);
92 if (err != NO_ERROR) {
93 hasErrors = true;
94 }
95 }
96
97 status_t err = root->parseValues(assets, table);
98 if (err != NO_ERROR) {
99 hasErrors = true;
100 }
101
102 if (hasErrors) {
103 return UNKNOWN_ERROR;
104 }
Adam Lesinskie572c012014-09-19 15:10:04 -0700105
106 if (table->modifyForCompat(bundle, resourceName, target, root) != NO_ERROR) {
107 return UNKNOWN_ERROR;
108 }
Andreas Gampe87332a72014-10-01 22:03:58 -0700109
Andreas Gampe2412f842014-09-30 20:55:57 -0700110 if (kIsDebug) {
111 printf("Input XML Resource:\n");
112 root->print();
113 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800114 err = root->flatten(target,
115 (options&XML_COMPILE_STRIP_COMMENTS) != 0,
116 (options&XML_COMPILE_STRIP_RAW_VALUES) != 0);
117 if (err != NO_ERROR) {
118 return err;
119 }
120
Andreas Gampe2412f842014-09-30 20:55:57 -0700121 if (kIsDebug) {
122 printf("Output XML Resource:\n");
123 ResXMLTree tree;
Adam Lesinski282e1812014-01-23 18:17:42 -0800124 tree.setTo(target->getData(), target->getSize());
Andreas Gampe2412f842014-09-30 20:55:57 -0700125 printXMLBlock(&tree);
126 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800127
128 target->setCompressionMethod(ZipEntry::kCompressDeflated);
129
130 return err;
131}
132
Adam Lesinski282e1812014-01-23 18:17:42 -0800133struct flag_entry
134{
135 const char16_t* name;
136 size_t nameLen;
137 uint32_t value;
138 const char* description;
139};
140
141static const char16_t referenceArray[] =
142 { 'r', 'e', 'f', 'e', 'r', 'e', 'n', 'c', 'e' };
143static const char16_t stringArray[] =
144 { 's', 't', 'r', 'i', 'n', 'g' };
145static const char16_t integerArray[] =
146 { 'i', 'n', 't', 'e', 'g', 'e', 'r' };
147static const char16_t booleanArray[] =
148 { 'b', 'o', 'o', 'l', 'e', 'a', 'n' };
149static const char16_t colorArray[] =
150 { 'c', 'o', 'l', 'o', 'r' };
151static const char16_t floatArray[] =
152 { 'f', 'l', 'o', 'a', 't' };
153static const char16_t dimensionArray[] =
154 { 'd', 'i', 'm', 'e', 'n', 's', 'i', 'o', 'n' };
155static const char16_t fractionArray[] =
156 { 'f', 'r', 'a', 'c', 't', 'i', 'o', 'n' };
157static const char16_t enumArray[] =
158 { 'e', 'n', 'u', 'm' };
159static const char16_t flagsArray[] =
160 { 'f', 'l', 'a', 'g', 's' };
161
162static const flag_entry gFormatFlags[] = {
163 { referenceArray, sizeof(referenceArray)/2, ResTable_map::TYPE_REFERENCE,
164 "a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\n"
165 "or to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\"."},
166 { stringArray, sizeof(stringArray)/2, ResTable_map::TYPE_STRING,
167 "a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character." },
168 { integerArray, sizeof(integerArray)/2, ResTable_map::TYPE_INTEGER,
169 "an integer value, such as \"<code>100</code>\"." },
170 { booleanArray, sizeof(booleanArray)/2, ResTable_map::TYPE_BOOLEAN,
171 "a boolean value, either \"<code>true</code>\" or \"<code>false</code>\"." },
172 { colorArray, sizeof(colorArray)/2, ResTable_map::TYPE_COLOR,
173 "a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n"
174 "\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\"." },
175 { floatArray, sizeof(floatArray)/2, ResTable_map::TYPE_FLOAT,
176 "a floating point value, such as \"<code>1.2</code>\"."},
177 { dimensionArray, sizeof(dimensionArray)/2, ResTable_map::TYPE_DIMENSION,
178 "a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\n"
179 "Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\n"
180 "in (inches), mm (millimeters)." },
181 { fractionArray, sizeof(fractionArray)/2, ResTable_map::TYPE_FRACTION,
182 "a fractional value, which is a floating point number appended with either % or %p, such as \"<code>14.5%</code>\".\n"
183 "The % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to\n"
184 "some parent container." },
185 { enumArray, sizeof(enumArray)/2, ResTable_map::TYPE_ENUM, NULL },
186 { flagsArray, sizeof(flagsArray)/2, ResTable_map::TYPE_FLAGS, NULL },
187 { NULL, 0, 0, NULL }
188};
189
190static const char16_t suggestedArray[] = { 's', 'u', 'g', 'g', 'e', 's', 't', 'e', 'd' };
191
192static const flag_entry l10nRequiredFlags[] = {
193 { suggestedArray, sizeof(suggestedArray)/2, ResTable_map::L10N_SUGGESTED, NULL },
194 { NULL, 0, 0, NULL }
195};
196
197static const char16_t nulStr[] = { 0 };
198
199static uint32_t parse_flags(const char16_t* str, size_t len,
200 const flag_entry* flags, bool* outError = NULL)
201{
202 while (len > 0 && isspace(*str)) {
203 str++;
204 len--;
205 }
206 while (len > 0 && isspace(str[len-1])) {
207 len--;
208 }
209
210 const char16_t* const end = str + len;
211 uint32_t value = 0;
212
213 while (str < end) {
214 const char16_t* div = str;
215 while (div < end && *div != '|') {
216 div++;
217 }
218
219 const flag_entry* cur = flags;
220 while (cur->name) {
221 if (strzcmp16(cur->name, cur->nameLen, str, div-str) == 0) {
222 value |= cur->value;
223 break;
224 }
225 cur++;
226 }
227
228 if (!cur->name) {
229 if (outError) *outError = true;
230 return 0;
231 }
232
233 str = div < end ? div+1 : div;
234 }
235
236 if (outError) *outError = false;
237 return value;
238}
239
240static String16 mayOrMust(int type, int flags)
241{
242 if ((type&(~flags)) == 0) {
243 return String16("<p>Must");
244 }
245
246 return String16("<p>May");
247}
248
249static void appendTypeInfo(ResourceTable* outTable, const String16& pkg,
250 const String16& typeName, const String16& ident, int type,
251 const flag_entry* flags)
252{
253 bool hadType = false;
254 while (flags->name) {
255 if ((type&flags->value) != 0 && flags->description != NULL) {
256 String16 fullMsg(mayOrMust(type, flags->value));
257 fullMsg.append(String16(" be "));
258 fullMsg.append(String16(flags->description));
259 outTable->appendTypeComment(pkg, typeName, ident, fullMsg);
260 hadType = true;
261 }
262 flags++;
263 }
264 if (hadType && (type&ResTable_map::TYPE_REFERENCE) == 0) {
265 outTable->appendTypeComment(pkg, typeName, ident,
266 String16("<p>This may also be a reference to a resource (in the form\n"
267 "\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\n"
268 "theme attribute (in the form\n"
269 "\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\n"
270 "containing a value of this type."));
271 }
272}
273
274struct PendingAttribute
275{
276 const String16 myPackage;
277 const SourcePos sourcePos;
278 const bool appendComment;
279 int32_t type;
280 String16 ident;
281 String16 comment;
282 bool hasErrors;
283 bool added;
284
285 PendingAttribute(String16 _package, const sp<AaptFile>& in,
286 ResXMLTree& block, bool _appendComment)
287 : myPackage(_package)
288 , sourcePos(in->getPrintableSource(), block.getLineNumber())
289 , appendComment(_appendComment)
290 , type(ResTable_map::TYPE_ANY)
291 , hasErrors(false)
292 , added(false)
293 {
294 }
295
296 status_t createIfNeeded(ResourceTable* outTable)
297 {
298 if (added || hasErrors) {
299 return NO_ERROR;
300 }
301 added = true;
302
303 String16 attr16("attr");
304
305 if (outTable->hasBagOrEntry(myPackage, attr16, ident)) {
306 sourcePos.error("Attribute \"%s\" has already been defined\n",
307 String8(ident).string());
308 hasErrors = true;
309 return UNKNOWN_ERROR;
310 }
311
312 char numberStr[16];
313 sprintf(numberStr, "%d", type);
314 status_t err = outTable->addBag(sourcePos, myPackage,
315 attr16, ident, String16(""),
316 String16("^type"),
317 String16(numberStr), NULL, NULL);
318 if (err != NO_ERROR) {
319 hasErrors = true;
320 return err;
321 }
322 outTable->appendComment(myPackage, attr16, ident, comment, appendComment);
323 //printf("Attribute %s comment: %s\n", String8(ident).string(),
324 // String8(comment).string());
325 return err;
326 }
327};
328
329static status_t compileAttribute(const sp<AaptFile>& in,
330 ResXMLTree& block,
331 const String16& myPackage,
332 ResourceTable* outTable,
333 String16* outIdent = NULL,
334 bool inStyleable = false)
335{
336 PendingAttribute attr(myPackage, in, block, inStyleable);
337
338 const String16 attr16("attr");
339 const String16 id16("id");
340
341 // Attribute type constants.
342 const String16 enum16("enum");
343 const String16 flag16("flag");
344
345 ResXMLTree::event_code_t code;
346 size_t len;
347 status_t err;
348
349 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
350 if (identIdx >= 0) {
351 attr.ident = String16(block.getAttributeStringValue(identIdx, &len));
352 if (outIdent) {
353 *outIdent = attr.ident;
354 }
355 } else {
356 attr.sourcePos.error("A 'name' attribute is required for <attr>\n");
357 attr.hasErrors = true;
358 }
359
360 attr.comment = String16(
361 block.getComment(&len) ? block.getComment(&len) : nulStr);
362
363 ssize_t typeIdx = block.indexOfAttribute(NULL, "format");
364 if (typeIdx >= 0) {
365 String16 typeStr = String16(block.getAttributeStringValue(typeIdx, &len));
366 attr.type = parse_flags(typeStr.string(), typeStr.size(), gFormatFlags);
367 if (attr.type == 0) {
368 attr.sourcePos.error("Tag <attr> 'format' attribute value \"%s\" not valid\n",
369 String8(typeStr).string());
370 attr.hasErrors = true;
371 }
372 attr.createIfNeeded(outTable);
373 } else if (!inStyleable) {
374 // Attribute definitions outside of styleables always define the
375 // attribute as a generic value.
376 attr.createIfNeeded(outTable);
377 }
378
379 //printf("Attribute %s: type=0x%08x\n", String8(attr.ident).string(), attr.type);
380
381 ssize_t minIdx = block.indexOfAttribute(NULL, "min");
382 if (minIdx >= 0) {
383 String16 val = String16(block.getAttributeStringValue(minIdx, &len));
384 if (!ResTable::stringToInt(val.string(), val.size(), NULL)) {
385 attr.sourcePos.error("Tag <attr> 'min' attribute must be a number, not \"%s\"\n",
386 String8(val).string());
387 attr.hasErrors = true;
388 }
389 attr.createIfNeeded(outTable);
390 if (!attr.hasErrors) {
391 err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
392 String16(""), String16("^min"), String16(val), NULL, NULL);
393 if (err != NO_ERROR) {
394 attr.hasErrors = true;
395 }
396 }
397 }
398
399 ssize_t maxIdx = block.indexOfAttribute(NULL, "max");
400 if (maxIdx >= 0) {
401 String16 val = String16(block.getAttributeStringValue(maxIdx, &len));
402 if (!ResTable::stringToInt(val.string(), val.size(), NULL)) {
403 attr.sourcePos.error("Tag <attr> 'max' attribute must be a number, not \"%s\"\n",
404 String8(val).string());
405 attr.hasErrors = true;
406 }
407 attr.createIfNeeded(outTable);
408 if (!attr.hasErrors) {
409 err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
410 String16(""), String16("^max"), String16(val), NULL, NULL);
411 attr.hasErrors = true;
412 }
413 }
414
415 if ((minIdx >= 0 || maxIdx >= 0) && (attr.type&ResTable_map::TYPE_INTEGER) == 0) {
416 attr.sourcePos.error("Tag <attr> must have format=integer attribute if using max or min\n");
417 attr.hasErrors = true;
418 }
419
420 ssize_t l10nIdx = block.indexOfAttribute(NULL, "localization");
421 if (l10nIdx >= 0) {
Dan Albertf348c152014-09-08 18:28:00 -0700422 const char16_t* str = block.getAttributeStringValue(l10nIdx, &len);
Adam Lesinski282e1812014-01-23 18:17:42 -0800423 bool error;
424 uint32_t l10n_required = parse_flags(str, len, l10nRequiredFlags, &error);
425 if (error) {
426 attr.sourcePos.error("Tag <attr> 'localization' attribute value \"%s\" not valid\n",
427 String8(str).string());
428 attr.hasErrors = true;
429 }
430 attr.createIfNeeded(outTable);
431 if (!attr.hasErrors) {
432 char buf[11];
433 sprintf(buf, "%d", l10n_required);
434 err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
435 String16(""), String16("^l10n"), String16(buf), NULL, NULL);
436 if (err != NO_ERROR) {
437 attr.hasErrors = true;
438 }
439 }
440 }
441
442 String16 enumOrFlagsComment;
443
444 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
445 if (code == ResXMLTree::START_TAG) {
446 uint32_t localType = 0;
447 if (strcmp16(block.getElementName(&len), enum16.string()) == 0) {
448 localType = ResTable_map::TYPE_ENUM;
449 } else if (strcmp16(block.getElementName(&len), flag16.string()) == 0) {
450 localType = ResTable_map::TYPE_FLAGS;
451 } else {
452 SourcePos(in->getPrintableSource(), block.getLineNumber())
453 .error("Tag <%s> can not appear inside <attr>, only <enum> or <flag>\n",
454 String8(block.getElementName(&len)).string());
455 return UNKNOWN_ERROR;
456 }
457
458 attr.createIfNeeded(outTable);
459
460 if (attr.type == ResTable_map::TYPE_ANY) {
461 // No type was explicitly stated, so supplying enum tags
462 // implicitly creates an enum or flag.
463 attr.type = 0;
464 }
465
466 if ((attr.type&(ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS)) == 0) {
467 // Wasn't originally specified as an enum, so update its type.
468 attr.type |= localType;
469 if (!attr.hasErrors) {
470 char numberStr[16];
471 sprintf(numberStr, "%d", attr.type);
472 err = outTable->addBag(SourcePos(in->getPrintableSource(), block.getLineNumber()),
473 myPackage, attr16, attr.ident, String16(""),
474 String16("^type"), String16(numberStr), NULL, NULL, true);
475 if (err != NO_ERROR) {
476 attr.hasErrors = true;
477 }
478 }
479 } else if ((uint32_t)(attr.type&(ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS)) != localType) {
480 if (localType == ResTable_map::TYPE_ENUM) {
481 SourcePos(in->getPrintableSource(), block.getLineNumber())
482 .error("<enum> attribute can not be used inside a flags format\n");
483 attr.hasErrors = true;
484 } else {
485 SourcePos(in->getPrintableSource(), block.getLineNumber())
486 .error("<flag> attribute can not be used inside a enum format\n");
487 attr.hasErrors = true;
488 }
489 }
490
491 String16 itemIdent;
492 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "name");
493 if (itemIdentIdx >= 0) {
494 itemIdent = String16(block.getAttributeStringValue(itemIdentIdx, &len));
495 } else {
496 SourcePos(in->getPrintableSource(), block.getLineNumber())
497 .error("A 'name' attribute is required for <enum> or <flag>\n");
498 attr.hasErrors = true;
499 }
500
501 String16 value;
502 ssize_t valueIdx = block.indexOfAttribute(NULL, "value");
503 if (valueIdx >= 0) {
504 value = String16(block.getAttributeStringValue(valueIdx, &len));
505 } else {
506 SourcePos(in->getPrintableSource(), block.getLineNumber())
507 .error("A 'value' attribute is required for <enum> or <flag>\n");
508 attr.hasErrors = true;
509 }
510 if (!attr.hasErrors && !ResTable::stringToInt(value.string(), value.size(), NULL)) {
511 SourcePos(in->getPrintableSource(), block.getLineNumber())
512 .error("Tag <enum> or <flag> 'value' attribute must be a number,"
513 " not \"%s\"\n",
514 String8(value).string());
515 attr.hasErrors = true;
516 }
517
Adam Lesinski282e1812014-01-23 18:17:42 -0800518 if (!attr.hasErrors) {
519 if (enumOrFlagsComment.size() == 0) {
520 enumOrFlagsComment.append(mayOrMust(attr.type,
521 ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS));
522 enumOrFlagsComment.append((attr.type&ResTable_map::TYPE_ENUM)
523 ? String16(" be one of the following constant values.")
524 : String16(" be one or more (separated by '|') of the following constant values."));
525 enumOrFlagsComment.append(String16("</p>\n<table>\n"
526 "<colgroup align=\"left\" />\n"
527 "<colgroup align=\"left\" />\n"
528 "<colgroup align=\"left\" />\n"
529 "<tr><th>Constant</th><th>Value</th><th>Description</th></tr>"));
530 }
531
532 enumOrFlagsComment.append(String16("\n<tr><td><code>"));
533 enumOrFlagsComment.append(itemIdent);
534 enumOrFlagsComment.append(String16("</code></td><td>"));
535 enumOrFlagsComment.append(value);
536 enumOrFlagsComment.append(String16("</td><td>"));
537 if (block.getComment(&len)) {
538 enumOrFlagsComment.append(String16(block.getComment(&len)));
539 }
540 enumOrFlagsComment.append(String16("</td></tr>"));
541
542 err = outTable->addBag(SourcePos(in->getPrintableSource(), block.getLineNumber()),
543 myPackage,
544 attr16, attr.ident, String16(""),
545 itemIdent, value, NULL, NULL, false, true);
546 if (err != NO_ERROR) {
547 attr.hasErrors = true;
548 }
549 }
550 } else if (code == ResXMLTree::END_TAG) {
551 if (strcmp16(block.getElementName(&len), attr16.string()) == 0) {
552 break;
553 }
554 if ((attr.type&ResTable_map::TYPE_ENUM) != 0) {
555 if (strcmp16(block.getElementName(&len), enum16.string()) != 0) {
556 SourcePos(in->getPrintableSource(), block.getLineNumber())
557 .error("Found tag </%s> where </enum> is expected\n",
558 String8(block.getElementName(&len)).string());
559 return UNKNOWN_ERROR;
560 }
561 } else {
562 if (strcmp16(block.getElementName(&len), flag16.string()) != 0) {
563 SourcePos(in->getPrintableSource(), block.getLineNumber())
564 .error("Found tag </%s> where </flag> is expected\n",
565 String8(block.getElementName(&len)).string());
566 return UNKNOWN_ERROR;
567 }
568 }
569 }
570 }
571
572 if (!attr.hasErrors && attr.added) {
573 appendTypeInfo(outTable, myPackage, attr16, attr.ident, attr.type, gFormatFlags);
574 }
575
576 if (!attr.hasErrors && enumOrFlagsComment.size() > 0) {
577 enumOrFlagsComment.append(String16("\n</table>"));
578 outTable->appendTypeComment(myPackage, attr16, attr.ident, enumOrFlagsComment);
579 }
580
581
582 return NO_ERROR;
583}
584
585bool localeIsDefined(const ResTable_config& config)
586{
587 return config.locale == 0;
588}
589
590status_t parseAndAddBag(Bundle* bundle,
591 const sp<AaptFile>& in,
592 ResXMLTree* block,
593 const ResTable_config& config,
594 const String16& myPackage,
595 const String16& curType,
596 const String16& ident,
597 const String16& parentIdent,
598 const String16& itemIdent,
599 int32_t curFormat,
600 bool isFormatted,
Andreas Gampe2412f842014-09-30 20:55:57 -0700601 const String16& /* product */,
Anton Krumina2ef5c02014-03-12 14:46:44 -0700602 PseudolocalizationMethod pseudolocalize,
Adam Lesinski282e1812014-01-23 18:17:42 -0800603 const bool overwrite,
604 ResourceTable* outTable)
605{
606 status_t err;
607 const String16 item16("item");
Anton Krumina2ef5c02014-03-12 14:46:44 -0700608
Adam Lesinski282e1812014-01-23 18:17:42 -0800609 String16 str;
610 Vector<StringPool::entry_style_span> spans;
611 err = parseStyledString(bundle, in->getPrintableSource().string(),
612 block, item16, &str, &spans, isFormatted,
613 pseudolocalize);
614 if (err != NO_ERROR) {
615 return err;
616 }
Andreas Gampe2412f842014-09-30 20:55:57 -0700617
618 if (kIsDebug) {
619 printf("Adding resource bag entry l=%c%c c=%c%c orien=%d d=%d "
620 " pid=%s, bag=%s, id=%s: %s\n",
621 config.language[0], config.language[1],
622 config.country[0], config.country[1],
623 config.orientation, config.density,
624 String8(parentIdent).string(),
625 String8(ident).string(),
626 String8(itemIdent).string(),
627 String8(str).string());
628 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800629
630 err = outTable->addBag(SourcePos(in->getPrintableSource(), block->getLineNumber()),
631 myPackage, curType, ident, parentIdent, itemIdent, str,
632 &spans, &config, overwrite, false, curFormat);
633 return err;
634}
635
636/*
637 * Returns true if needle is one of the elements in the comma-separated list
638 * haystack, false otherwise.
639 */
640bool isInProductList(const String16& needle, const String16& haystack) {
641 const char16_t *needle2 = needle.string();
642 const char16_t *haystack2 = haystack.string();
643 size_t needlesize = needle.size();
644
645 while (*haystack2 != '\0') {
646 if (strncmp16(haystack2, needle2, needlesize) == 0) {
647 if (haystack2[needlesize] == '\0' || haystack2[needlesize] == ',') {
648 return true;
649 }
650 }
651
652 while (*haystack2 != '\0' && *haystack2 != ',') {
653 haystack2++;
654 }
655 if (*haystack2 == ',') {
656 haystack2++;
657 }
658 }
659
660 return false;
661}
662
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700663/*
664 * A simple container that holds a resource type and name. It is ordered first by type then
665 * by name.
666 */
667struct type_ident_pair_t {
668 String16 type;
669 String16 ident;
670
671 type_ident_pair_t() { };
672 type_ident_pair_t(const String16& t, const String16& i) : type(t), ident(i) { }
673 type_ident_pair_t(const type_ident_pair_t& o) : type(o.type), ident(o.ident) { }
674 inline bool operator < (const type_ident_pair_t& o) const {
675 int cmp = compare_type(type, o.type);
676 if (cmp < 0) {
677 return true;
678 } else if (cmp > 0) {
679 return false;
680 } else {
681 return strictly_order_type(ident, o.ident);
682 }
683 }
684};
685
686
Adam Lesinski282e1812014-01-23 18:17:42 -0800687status_t parseAndAddEntry(Bundle* bundle,
688 const sp<AaptFile>& in,
689 ResXMLTree* block,
690 const ResTable_config& config,
691 const String16& myPackage,
692 const String16& curType,
693 const String16& ident,
694 const String16& curTag,
695 bool curIsStyled,
696 int32_t curFormat,
697 bool isFormatted,
698 const String16& product,
Anton Krumina2ef5c02014-03-12 14:46:44 -0700699 PseudolocalizationMethod pseudolocalize,
Adam Lesinski282e1812014-01-23 18:17:42 -0800700 const bool overwrite,
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700701 KeyedVector<type_ident_pair_t, bool>* skippedResourceNames,
Adam Lesinski282e1812014-01-23 18:17:42 -0800702 ResourceTable* outTable)
703{
704 status_t err;
705
706 String16 str;
707 Vector<StringPool::entry_style_span> spans;
708 err = parseStyledString(bundle, in->getPrintableSource().string(), block,
709 curTag, &str, curIsStyled ? &spans : NULL,
710 isFormatted, pseudolocalize);
711
712 if (err < NO_ERROR) {
713 return err;
714 }
715
716 /*
717 * If a product type was specified on the command line
718 * and also in the string, and the two are not the same,
719 * return without adding the string.
720 */
721
722 const char *bundleProduct = bundle->getProduct();
723 if (bundleProduct == NULL) {
724 bundleProduct = "";
725 }
726
727 if (product.size() != 0) {
728 /*
729 * If the command-line-specified product is empty, only "default"
730 * matches. Other variants are skipped. This is so generation
731 * of the R.java file when the product is not known is predictable.
732 */
733
734 if (bundleProduct[0] == '\0') {
735 if (strcmp16(String16("default").string(), product.string()) != 0) {
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700736 /*
737 * This string has a product other than 'default'. Do not add it,
738 * but record it so that if we do not see the same string with
739 * product 'default' or no product, then report an error.
740 */
741 skippedResourceNames->replaceValueFor(
742 type_ident_pair_t(curType, ident), true);
Adam Lesinski282e1812014-01-23 18:17:42 -0800743 return NO_ERROR;
744 }
745 } else {
746 /*
747 * The command-line product is not empty.
748 * If the product for this string is on the command-line list,
749 * it matches. "default" also matches, but only if nothing
750 * else has matched already.
751 */
752
753 if (isInProductList(product, String16(bundleProduct))) {
754 ;
755 } else if (strcmp16(String16("default").string(), product.string()) == 0 &&
756 !outTable->hasBagOrEntry(myPackage, curType, ident, config)) {
757 ;
758 } else {
759 return NO_ERROR;
760 }
761 }
762 }
763
Andreas Gampe2412f842014-09-30 20:55:57 -0700764 if (kIsDebug) {
765 printf("Adding resource entry l=%c%c c=%c%c orien=%d d=%d id=%s: %s\n",
766 config.language[0], config.language[1],
767 config.country[0], config.country[1],
768 config.orientation, config.density,
769 String8(ident).string(), String8(str).string());
770 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800771
772 err = outTable->addEntry(SourcePos(in->getPrintableSource(), block->getLineNumber()),
773 myPackage, curType, ident, str, &spans, &config,
774 false, curFormat, overwrite);
775
776 return err;
777}
778
779status_t compileResourceFile(Bundle* bundle,
780 const sp<AaptAssets>& assets,
781 const sp<AaptFile>& in,
782 const ResTable_config& defParams,
783 const bool overwrite,
784 ResourceTable* outTable)
785{
786 ResXMLTree block;
787 status_t err = parseXMLResource(in, &block, false, true);
788 if (err != NO_ERROR) {
789 return err;
790 }
791
792 // Top-level tag.
793 const String16 resources16("resources");
794
795 // Identifier declaration tags.
796 const String16 declare_styleable16("declare-styleable");
797 const String16 attr16("attr");
798
799 // Data creation organizational tags.
800 const String16 string16("string");
801 const String16 drawable16("drawable");
802 const String16 color16("color");
803 const String16 bool16("bool");
804 const String16 integer16("integer");
805 const String16 dimen16("dimen");
806 const String16 fraction16("fraction");
807 const String16 style16("style");
808 const String16 plurals16("plurals");
809 const String16 array16("array");
810 const String16 string_array16("string-array");
811 const String16 integer_array16("integer-array");
812 const String16 public16("public");
813 const String16 public_padding16("public-padding");
814 const String16 private_symbols16("private-symbols");
815 const String16 java_symbol16("java-symbol");
816 const String16 add_resource16("add-resource");
817 const String16 skip16("skip");
818 const String16 eat_comment16("eat-comment");
819
820 // Data creation tags.
821 const String16 bag16("bag");
822 const String16 item16("item");
823
824 // Attribute type constants.
825 const String16 enum16("enum");
826
827 // plural values
828 const String16 other16("other");
829 const String16 quantityOther16("^other");
830 const String16 zero16("zero");
831 const String16 quantityZero16("^zero");
832 const String16 one16("one");
833 const String16 quantityOne16("^one");
834 const String16 two16("two");
835 const String16 quantityTwo16("^two");
836 const String16 few16("few");
837 const String16 quantityFew16("^few");
838 const String16 many16("many");
839 const String16 quantityMany16("^many");
840
841 // useful attribute names and special values
842 const String16 name16("name");
843 const String16 translatable16("translatable");
844 const String16 formatted16("formatted");
845 const String16 false16("false");
846
847 const String16 myPackage(assets->getPackage());
848
849 bool hasErrors = false;
850
851 bool fileIsTranslatable = true;
852 if (strstr(in->getPrintableSource().string(), "donottranslate") != NULL) {
853 fileIsTranslatable = false;
854 }
855
856 DefaultKeyedVector<String16, uint32_t> nextPublicId(0);
857
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700858 // Stores the resource names that were skipped. Typically this happens when
859 // AAPT is invoked without a product specified and a resource has no
860 // 'default' product attribute.
861 KeyedVector<type_ident_pair_t, bool> skippedResourceNames;
862
Adam Lesinski282e1812014-01-23 18:17:42 -0800863 ResXMLTree::event_code_t code;
864 do {
865 code = block.next();
866 } while (code == ResXMLTree::START_NAMESPACE);
867
868 size_t len;
869 if (code != ResXMLTree::START_TAG) {
870 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
871 "No start tag found\n");
872 return UNKNOWN_ERROR;
873 }
874 if (strcmp16(block.getElementName(&len), resources16.string()) != 0) {
875 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
876 "Invalid start tag %s\n", String8(block.getElementName(&len)).string());
877 return UNKNOWN_ERROR;
878 }
879
880 ResTable_config curParams(defParams);
881
882 ResTable_config pseudoParams(curParams);
Anton Krumina2ef5c02014-03-12 14:46:44 -0700883 pseudoParams.language[0] = 'e';
884 pseudoParams.language[1] = 'n';
885 pseudoParams.country[0] = 'X';
886 pseudoParams.country[1] = 'A';
887
888 ResTable_config pseudoBidiParams(curParams);
889 pseudoBidiParams.language[0] = 'a';
890 pseudoBidiParams.language[1] = 'r';
891 pseudoBidiParams.country[0] = 'X';
892 pseudoBidiParams.country[1] = 'B';
Adam Lesinski282e1812014-01-23 18:17:42 -0800893
Igor Viarheichyk47843df2014-05-01 17:04:39 -0700894 // We should skip resources for pseudolocales if they were
895 // already added automatically. This is a fix for a transition period when
896 // manually pseudolocalized resources may be expected.
897 // TODO: remove this check after next SDK version release.
898 if ((bundle->getPseudolocalize() & PSEUDO_ACCENTED &&
899 curParams.locale == pseudoParams.locale) ||
900 (bundle->getPseudolocalize() & PSEUDO_BIDI &&
901 curParams.locale == pseudoBidiParams.locale)) {
902 SourcePos(in->getPrintableSource(), 0).warning(
903 "Resource file %s is skipped as pseudolocalization"
904 " was done automatically.",
905 in->getPrintableSource().string());
906 return NO_ERROR;
907 }
908
Adam Lesinski282e1812014-01-23 18:17:42 -0800909 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
910 if (code == ResXMLTree::START_TAG) {
911 const String16* curTag = NULL;
912 String16 curType;
913 int32_t curFormat = ResTable_map::TYPE_ANY;
914 bool curIsBag = false;
915 bool curIsBagReplaceOnOverwrite = false;
916 bool curIsStyled = false;
917 bool curIsPseudolocalizable = false;
918 bool curIsFormatted = fileIsTranslatable;
919 bool localHasErrors = false;
920
921 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
922 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
923 && code != ResXMLTree::BAD_DOCUMENT) {
924 if (code == ResXMLTree::END_TAG) {
925 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
926 break;
927 }
928 }
929 }
930 continue;
931
932 } else if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
933 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
934 && code != ResXMLTree::BAD_DOCUMENT) {
935 if (code == ResXMLTree::END_TAG) {
936 if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
937 break;
938 }
939 }
940 }
941 continue;
942
943 } else if (strcmp16(block.getElementName(&len), public16.string()) == 0) {
944 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
945
946 String16 type;
947 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
948 if (typeIdx < 0) {
949 srcPos.error("A 'type' attribute is required for <public>\n");
950 hasErrors = localHasErrors = true;
951 }
952 type = String16(block.getAttributeStringValue(typeIdx, &len));
953
954 String16 name;
955 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
956 if (nameIdx < 0) {
957 srcPos.error("A 'name' attribute is required for <public>\n");
958 hasErrors = localHasErrors = true;
959 }
960 name = String16(block.getAttributeStringValue(nameIdx, &len));
961
962 uint32_t ident = 0;
963 ssize_t identIdx = block.indexOfAttribute(NULL, "id");
964 if (identIdx >= 0) {
965 const char16_t* identStr = block.getAttributeStringValue(identIdx, &len);
966 Res_value identValue;
967 if (!ResTable::stringToInt(identStr, len, &identValue)) {
968 srcPos.error("Given 'id' attribute is not an integer: %s\n",
969 String8(block.getAttributeStringValue(identIdx, &len)).string());
970 hasErrors = localHasErrors = true;
971 } else {
972 ident = identValue.data;
973 nextPublicId.replaceValueFor(type, ident+1);
974 }
975 } else if (nextPublicId.indexOfKey(type) < 0) {
976 srcPos.error("No 'id' attribute supplied <public>,"
977 " and no previous id defined in this file.\n");
978 hasErrors = localHasErrors = true;
979 } else if (!localHasErrors) {
980 ident = nextPublicId.valueFor(type);
981 nextPublicId.replaceValueFor(type, ident+1);
982 }
983
984 if (!localHasErrors) {
985 err = outTable->addPublic(srcPos, myPackage, type, name, ident);
986 if (err < NO_ERROR) {
987 hasErrors = localHasErrors = true;
988 }
989 }
990 if (!localHasErrors) {
991 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
992 if (symbols != NULL) {
993 symbols = symbols->addNestedSymbol(String8(type), srcPos);
994 }
995 if (symbols != NULL) {
996 symbols->makeSymbolPublic(String8(name), srcPos);
997 String16 comment(
998 block.getComment(&len) ? block.getComment(&len) : nulStr);
999 symbols->appendComment(String8(name), comment, srcPos);
1000 } else {
1001 srcPos.error("Unable to create symbols!\n");
1002 hasErrors = localHasErrors = true;
1003 }
1004 }
1005
1006 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1007 if (code == ResXMLTree::END_TAG) {
1008 if (strcmp16(block.getElementName(&len), public16.string()) == 0) {
1009 break;
1010 }
1011 }
1012 }
1013 continue;
1014
1015 } else if (strcmp16(block.getElementName(&len), public_padding16.string()) == 0) {
1016 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1017
1018 String16 type;
1019 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
1020 if (typeIdx < 0) {
1021 srcPos.error("A 'type' attribute is required for <public-padding>\n");
1022 hasErrors = localHasErrors = true;
1023 }
1024 type = String16(block.getAttributeStringValue(typeIdx, &len));
1025
1026 String16 name;
1027 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1028 if (nameIdx < 0) {
1029 srcPos.error("A 'name' attribute is required for <public-padding>\n");
1030 hasErrors = localHasErrors = true;
1031 }
1032 name = String16(block.getAttributeStringValue(nameIdx, &len));
1033
1034 uint32_t start = 0;
1035 ssize_t startIdx = block.indexOfAttribute(NULL, "start");
1036 if (startIdx >= 0) {
1037 const char16_t* startStr = block.getAttributeStringValue(startIdx, &len);
1038 Res_value startValue;
1039 if (!ResTable::stringToInt(startStr, len, &startValue)) {
1040 srcPos.error("Given 'start' attribute is not an integer: %s\n",
1041 String8(block.getAttributeStringValue(startIdx, &len)).string());
1042 hasErrors = localHasErrors = true;
1043 } else {
1044 start = startValue.data;
1045 }
1046 } else if (nextPublicId.indexOfKey(type) < 0) {
1047 srcPos.error("No 'start' attribute supplied <public-padding>,"
1048 " and no previous id defined in this file.\n");
1049 hasErrors = localHasErrors = true;
1050 } else if (!localHasErrors) {
1051 start = nextPublicId.valueFor(type);
1052 }
1053
1054 uint32_t end = 0;
1055 ssize_t endIdx = block.indexOfAttribute(NULL, "end");
1056 if (endIdx >= 0) {
1057 const char16_t* endStr = block.getAttributeStringValue(endIdx, &len);
1058 Res_value endValue;
1059 if (!ResTable::stringToInt(endStr, len, &endValue)) {
1060 srcPos.error("Given 'end' attribute is not an integer: %s\n",
1061 String8(block.getAttributeStringValue(endIdx, &len)).string());
1062 hasErrors = localHasErrors = true;
1063 } else {
1064 end = endValue.data;
1065 }
1066 } else {
1067 srcPos.error("No 'end' attribute supplied <public-padding>\n");
1068 hasErrors = localHasErrors = true;
1069 }
1070
1071 if (end >= start) {
1072 nextPublicId.replaceValueFor(type, end+1);
1073 } else {
1074 srcPos.error("Padding start '%ul' is after end '%ul'\n",
1075 start, end);
1076 hasErrors = localHasErrors = true;
1077 }
1078
1079 String16 comment(
1080 block.getComment(&len) ? block.getComment(&len) : nulStr);
1081 for (uint32_t curIdent=start; curIdent<=end; curIdent++) {
1082 if (localHasErrors) {
1083 break;
1084 }
1085 String16 curName(name);
1086 char buf[64];
1087 sprintf(buf, "%d", (int)(end-curIdent+1));
1088 curName.append(String16(buf));
1089
1090 err = outTable->addEntry(srcPos, myPackage, type, curName,
1091 String16("padding"), NULL, &curParams, false,
1092 ResTable_map::TYPE_STRING, overwrite);
1093 if (err < NO_ERROR) {
1094 hasErrors = localHasErrors = true;
1095 break;
1096 }
1097 err = outTable->addPublic(srcPos, myPackage, type,
1098 curName, curIdent);
1099 if (err < NO_ERROR) {
1100 hasErrors = localHasErrors = true;
1101 break;
1102 }
1103 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1104 if (symbols != NULL) {
1105 symbols = symbols->addNestedSymbol(String8(type), srcPos);
1106 }
1107 if (symbols != NULL) {
1108 symbols->makeSymbolPublic(String8(curName), srcPos);
1109 symbols->appendComment(String8(curName), comment, srcPos);
1110 } else {
1111 srcPos.error("Unable to create symbols!\n");
1112 hasErrors = localHasErrors = true;
1113 }
1114 }
1115
1116 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1117 if (code == ResXMLTree::END_TAG) {
1118 if (strcmp16(block.getElementName(&len), public_padding16.string()) == 0) {
1119 break;
1120 }
1121 }
1122 }
1123 continue;
1124
1125 } else if (strcmp16(block.getElementName(&len), private_symbols16.string()) == 0) {
1126 String16 pkg;
1127 ssize_t pkgIdx = block.indexOfAttribute(NULL, "package");
1128 if (pkgIdx < 0) {
1129 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1130 "A 'package' attribute is required for <private-symbols>\n");
1131 hasErrors = localHasErrors = true;
1132 }
1133 pkg = String16(block.getAttributeStringValue(pkgIdx, &len));
1134 if (!localHasErrors) {
1135 assets->setSymbolsPrivatePackage(String8(pkg));
1136 }
1137
1138 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1139 if (code == ResXMLTree::END_TAG) {
1140 if (strcmp16(block.getElementName(&len), private_symbols16.string()) == 0) {
1141 break;
1142 }
1143 }
1144 }
1145 continue;
1146
1147 } else if (strcmp16(block.getElementName(&len), java_symbol16.string()) == 0) {
1148 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1149
1150 String16 type;
1151 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
1152 if (typeIdx < 0) {
1153 srcPos.error("A 'type' attribute is required for <public>\n");
1154 hasErrors = localHasErrors = true;
1155 }
1156 type = String16(block.getAttributeStringValue(typeIdx, &len));
1157
1158 String16 name;
1159 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1160 if (nameIdx < 0) {
1161 srcPos.error("A 'name' attribute is required for <public>\n");
1162 hasErrors = localHasErrors = true;
1163 }
1164 name = String16(block.getAttributeStringValue(nameIdx, &len));
1165
1166 sp<AaptSymbols> symbols = assets->getJavaSymbolsFor(String8("R"));
1167 if (symbols != NULL) {
1168 symbols = symbols->addNestedSymbol(String8(type), srcPos);
1169 }
1170 if (symbols != NULL) {
1171 symbols->makeSymbolJavaSymbol(String8(name), srcPos);
1172 String16 comment(
1173 block.getComment(&len) ? block.getComment(&len) : nulStr);
1174 symbols->appendComment(String8(name), comment, srcPos);
1175 } else {
1176 srcPos.error("Unable to create symbols!\n");
1177 hasErrors = localHasErrors = true;
1178 }
1179
1180 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1181 if (code == ResXMLTree::END_TAG) {
1182 if (strcmp16(block.getElementName(&len), java_symbol16.string()) == 0) {
1183 break;
1184 }
1185 }
1186 }
1187 continue;
1188
1189
1190 } else if (strcmp16(block.getElementName(&len), add_resource16.string()) == 0) {
1191 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1192
1193 String16 typeName;
1194 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
1195 if (typeIdx < 0) {
1196 srcPos.error("A 'type' attribute is required for <add-resource>\n");
1197 hasErrors = localHasErrors = true;
1198 }
1199 typeName = String16(block.getAttributeStringValue(typeIdx, &len));
1200
1201 String16 name;
1202 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1203 if (nameIdx < 0) {
1204 srcPos.error("A 'name' attribute is required for <add-resource>\n");
1205 hasErrors = localHasErrors = true;
1206 }
1207 name = String16(block.getAttributeStringValue(nameIdx, &len));
1208
1209 outTable->canAddEntry(srcPos, myPackage, typeName, name);
1210
1211 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1212 if (code == ResXMLTree::END_TAG) {
1213 if (strcmp16(block.getElementName(&len), add_resource16.string()) == 0) {
1214 break;
1215 }
1216 }
1217 }
1218 continue;
1219
1220 } else if (strcmp16(block.getElementName(&len), declare_styleable16.string()) == 0) {
1221 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1222
1223 String16 ident;
1224 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
1225 if (identIdx < 0) {
1226 srcPos.error("A 'name' attribute is required for <declare-styleable>\n");
1227 hasErrors = localHasErrors = true;
1228 }
1229 ident = String16(block.getAttributeStringValue(identIdx, &len));
1230
1231 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1232 if (!localHasErrors) {
1233 if (symbols != NULL) {
1234 symbols = symbols->addNestedSymbol(String8("styleable"), srcPos);
1235 }
1236 sp<AaptSymbols> styleSymbols = symbols;
1237 if (symbols != NULL) {
1238 symbols = symbols->addNestedSymbol(String8(ident), srcPos);
1239 }
1240 if (symbols == NULL) {
1241 srcPos.error("Unable to create symbols!\n");
1242 return UNKNOWN_ERROR;
1243 }
1244
1245 String16 comment(
1246 block.getComment(&len) ? block.getComment(&len) : nulStr);
1247 styleSymbols->appendComment(String8(ident), comment, srcPos);
1248 } else {
1249 symbols = NULL;
1250 }
1251
1252 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1253 if (code == ResXMLTree::START_TAG) {
1254 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
1255 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1256 && code != ResXMLTree::BAD_DOCUMENT) {
1257 if (code == ResXMLTree::END_TAG) {
1258 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
1259 break;
1260 }
1261 }
1262 }
1263 continue;
1264 } else if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
1265 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1266 && code != ResXMLTree::BAD_DOCUMENT) {
1267 if (code == ResXMLTree::END_TAG) {
1268 if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
1269 break;
1270 }
1271 }
1272 }
1273 continue;
1274 } else if (strcmp16(block.getElementName(&len), attr16.string()) != 0) {
1275 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1276 "Tag <%s> can not appear inside <declare-styleable>, only <attr>\n",
1277 String8(block.getElementName(&len)).string());
1278 return UNKNOWN_ERROR;
1279 }
1280
1281 String16 comment(
1282 block.getComment(&len) ? block.getComment(&len) : nulStr);
1283 String16 itemIdent;
1284 err = compileAttribute(in, block, myPackage, outTable, &itemIdent, true);
1285 if (err != NO_ERROR) {
1286 hasErrors = localHasErrors = true;
1287 }
1288
1289 if (symbols != NULL) {
1290 SourcePos srcPos(String8(in->getPrintableSource()), block.getLineNumber());
1291 symbols->addSymbol(String8(itemIdent), 0, srcPos);
1292 symbols->appendComment(String8(itemIdent), comment, srcPos);
1293 //printf("Attribute %s comment: %s\n", String8(itemIdent).string(),
1294 // String8(comment).string());
1295 }
1296 } else if (code == ResXMLTree::END_TAG) {
1297 if (strcmp16(block.getElementName(&len), declare_styleable16.string()) == 0) {
1298 break;
1299 }
1300
1301 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1302 "Found tag </%s> where </attr> is expected\n",
1303 String8(block.getElementName(&len)).string());
1304 return UNKNOWN_ERROR;
1305 }
1306 }
1307 continue;
1308
1309 } else if (strcmp16(block.getElementName(&len), attr16.string()) == 0) {
1310 err = compileAttribute(in, block, myPackage, outTable, NULL);
1311 if (err != NO_ERROR) {
1312 hasErrors = true;
1313 }
1314 continue;
1315
1316 } else if (strcmp16(block.getElementName(&len), item16.string()) == 0) {
1317 curTag = &item16;
1318 ssize_t attri = block.indexOfAttribute(NULL, "type");
1319 if (attri >= 0) {
1320 curType = String16(block.getAttributeStringValue(attri, &len));
1321 ssize_t formatIdx = block.indexOfAttribute(NULL, "format");
1322 if (formatIdx >= 0) {
1323 String16 formatStr = String16(block.getAttributeStringValue(
1324 formatIdx, &len));
1325 curFormat = parse_flags(formatStr.string(), formatStr.size(),
1326 gFormatFlags);
1327 if (curFormat == 0) {
1328 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1329 "Tag <item> 'format' attribute value \"%s\" not valid\n",
1330 String8(formatStr).string());
1331 hasErrors = localHasErrors = true;
1332 }
1333 }
1334 } else {
1335 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1336 "A 'type' attribute is required for <item>\n");
1337 hasErrors = localHasErrors = true;
1338 }
1339 curIsStyled = true;
1340 } else if (strcmp16(block.getElementName(&len), string16.string()) == 0) {
1341 // Note the existence and locale of every string we process
Narayan Kamath91447d82014-01-21 15:32:36 +00001342 char rawLocale[RESTABLE_MAX_LOCALE_LEN];
1343 curParams.getBcp47Locale(rawLocale);
Adam Lesinski282e1812014-01-23 18:17:42 -08001344 String8 locale(rawLocale);
1345 String16 name;
1346 String16 translatable;
1347 String16 formatted;
1348
1349 size_t n = block.getAttributeCount();
1350 for (size_t i = 0; i < n; i++) {
1351 size_t length;
Dan Albertf348c152014-09-08 18:28:00 -07001352 const char16_t* attr = block.getAttributeName(i, &length);
Adam Lesinski282e1812014-01-23 18:17:42 -08001353 if (strcmp16(attr, name16.string()) == 0) {
1354 name.setTo(block.getAttributeStringValue(i, &length));
1355 } else if (strcmp16(attr, translatable16.string()) == 0) {
1356 translatable.setTo(block.getAttributeStringValue(i, &length));
1357 } else if (strcmp16(attr, formatted16.string()) == 0) {
1358 formatted.setTo(block.getAttributeStringValue(i, &length));
1359 }
1360 }
1361
1362 if (name.size() > 0) {
1363 if (translatable == false16) {
1364 curIsFormatted = false;
1365 // Untranslatable strings must only exist in the default [empty] locale
1366 if (locale.size() > 0) {
Adam Lesinskia01a9372014-03-20 18:04:57 -07001367 SourcePos(in->getPrintableSource(), block.getLineNumber()).warning(
1368 "string '%s' marked untranslatable but exists in locale '%s'\n",
1369 String8(name).string(),
Adam Lesinski282e1812014-01-23 18:17:42 -08001370 locale.string());
1371 // hasErrors = localHasErrors = true;
1372 } else {
1373 // Intentionally empty block:
1374 //
1375 // Don't add untranslatable strings to the localization table; that
1376 // way if we later see localizations of them, they'll be flagged as
1377 // having no default translation.
1378 }
1379 } else {
Adam Lesinskia01a9372014-03-20 18:04:57 -07001380 outTable->addLocalization(
1381 name,
1382 locale,
1383 SourcePos(in->getPrintableSource(), block.getLineNumber()));
Adam Lesinski282e1812014-01-23 18:17:42 -08001384 }
1385
1386 if (formatted == false16) {
1387 curIsFormatted = false;
1388 }
1389 }
1390
1391 curTag = &string16;
1392 curType = string16;
1393 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
1394 curIsStyled = true;
Igor Viarheichyk84410b02014-04-30 11:56:42 -07001395 curIsPseudolocalizable = fileIsTranslatable && (translatable != false16);
Adam Lesinski282e1812014-01-23 18:17:42 -08001396 } else if (strcmp16(block.getElementName(&len), drawable16.string()) == 0) {
1397 curTag = &drawable16;
1398 curType = drawable16;
1399 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
1400 } else if (strcmp16(block.getElementName(&len), color16.string()) == 0) {
1401 curTag = &color16;
1402 curType = color16;
1403 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
1404 } else if (strcmp16(block.getElementName(&len), bool16.string()) == 0) {
1405 curTag = &bool16;
1406 curType = bool16;
1407 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_BOOLEAN;
1408 } else if (strcmp16(block.getElementName(&len), integer16.string()) == 0) {
1409 curTag = &integer16;
1410 curType = integer16;
1411 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
1412 } else if (strcmp16(block.getElementName(&len), dimen16.string()) == 0) {
1413 curTag = &dimen16;
1414 curType = dimen16;
1415 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_DIMENSION;
1416 } else if (strcmp16(block.getElementName(&len), fraction16.string()) == 0) {
1417 curTag = &fraction16;
1418 curType = fraction16;
1419 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_FRACTION;
1420 } else if (strcmp16(block.getElementName(&len), bag16.string()) == 0) {
1421 curTag = &bag16;
1422 curIsBag = true;
1423 ssize_t attri = block.indexOfAttribute(NULL, "type");
1424 if (attri >= 0) {
1425 curType = String16(block.getAttributeStringValue(attri, &len));
1426 } else {
1427 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1428 "A 'type' attribute is required for <bag>\n");
1429 hasErrors = localHasErrors = true;
1430 }
1431 } else if (strcmp16(block.getElementName(&len), style16.string()) == 0) {
1432 curTag = &style16;
1433 curType = style16;
1434 curIsBag = true;
1435 } else if (strcmp16(block.getElementName(&len), plurals16.string()) == 0) {
1436 curTag = &plurals16;
1437 curType = plurals16;
1438 curIsBag = true;
Anton Krumina2ef5c02014-03-12 14:46:44 -07001439 curIsPseudolocalizable = fileIsTranslatable;
Adam Lesinski282e1812014-01-23 18:17:42 -08001440 } else if (strcmp16(block.getElementName(&len), array16.string()) == 0) {
1441 curTag = &array16;
1442 curType = array16;
1443 curIsBag = true;
1444 curIsBagReplaceOnOverwrite = true;
1445 ssize_t formatIdx = block.indexOfAttribute(NULL, "format");
1446 if (formatIdx >= 0) {
1447 String16 formatStr = String16(block.getAttributeStringValue(
1448 formatIdx, &len));
1449 curFormat = parse_flags(formatStr.string(), formatStr.size(),
1450 gFormatFlags);
1451 if (curFormat == 0) {
1452 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1453 "Tag <array> 'format' attribute value \"%s\" not valid\n",
1454 String8(formatStr).string());
1455 hasErrors = localHasErrors = true;
1456 }
1457 }
1458 } else if (strcmp16(block.getElementName(&len), string_array16.string()) == 0) {
1459 // Check whether these strings need valid formats.
1460 // (simplified form of what string16 does above)
Anton Krumina2ef5c02014-03-12 14:46:44 -07001461 bool isTranslatable = false;
Adam Lesinski282e1812014-01-23 18:17:42 -08001462 size_t n = block.getAttributeCount();
Narayan Kamath9a9fa162013-12-18 13:27:30 +00001463
1464 // Pseudolocalizable by default, unless this string array isn't
1465 // translatable.
Adam Lesinski282e1812014-01-23 18:17:42 -08001466 for (size_t i = 0; i < n; i++) {
1467 size_t length;
Dan Albertf348c152014-09-08 18:28:00 -07001468 const char16_t* attr = block.getAttributeName(i, &length);
Narayan Kamath9a9fa162013-12-18 13:27:30 +00001469 if (strcmp16(attr, formatted16.string()) == 0) {
Dan Albertf348c152014-09-08 18:28:00 -07001470 const char16_t* value = block.getAttributeStringValue(i, &length);
Adam Lesinski282e1812014-01-23 18:17:42 -08001471 if (strcmp16(value, false16.string()) == 0) {
1472 curIsFormatted = false;
Adam Lesinski282e1812014-01-23 18:17:42 -08001473 }
Anton Krumina2ef5c02014-03-12 14:46:44 -07001474 } else if (strcmp16(attr, translatable16.string()) == 0) {
Dan Albertf348c152014-09-08 18:28:00 -07001475 const char16_t* value = block.getAttributeStringValue(i, &length);
Anton Krumina2ef5c02014-03-12 14:46:44 -07001476 if (strcmp16(value, false16.string()) == 0) {
1477 isTranslatable = false;
1478 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001479 }
1480 }
1481
1482 curTag = &string_array16;
1483 curType = array16;
1484 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
1485 curIsBag = true;
1486 curIsBagReplaceOnOverwrite = true;
Anton Krumina2ef5c02014-03-12 14:46:44 -07001487 curIsPseudolocalizable = isTranslatable && fileIsTranslatable;
Adam Lesinski282e1812014-01-23 18:17:42 -08001488 } else if (strcmp16(block.getElementName(&len), integer_array16.string()) == 0) {
1489 curTag = &integer_array16;
1490 curType = array16;
1491 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
1492 curIsBag = true;
1493 curIsBagReplaceOnOverwrite = true;
1494 } else {
1495 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1496 "Found tag %s where item is expected\n",
1497 String8(block.getElementName(&len)).string());
1498 return UNKNOWN_ERROR;
1499 }
1500
1501 String16 ident;
1502 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
1503 if (identIdx >= 0) {
1504 ident = String16(block.getAttributeStringValue(identIdx, &len));
1505 } else {
1506 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1507 "A 'name' attribute is required for <%s>\n",
1508 String8(*curTag).string());
1509 hasErrors = localHasErrors = true;
1510 }
1511
1512 String16 product;
1513 identIdx = block.indexOfAttribute(NULL, "product");
1514 if (identIdx >= 0) {
1515 product = String16(block.getAttributeStringValue(identIdx, &len));
1516 }
1517
1518 String16 comment(block.getComment(&len) ? block.getComment(&len) : nulStr);
1519
1520 if (curIsBag) {
1521 // Figure out the parent of this bag...
1522 String16 parentIdent;
1523 ssize_t parentIdentIdx = block.indexOfAttribute(NULL, "parent");
1524 if (parentIdentIdx >= 0) {
1525 parentIdent = String16(block.getAttributeStringValue(parentIdentIdx, &len));
1526 } else {
1527 ssize_t sep = ident.findLast('.');
1528 if (sep >= 0) {
1529 parentIdent.setTo(ident, sep);
1530 }
1531 }
1532
1533 if (!localHasErrors) {
1534 err = outTable->startBag(SourcePos(in->getPrintableSource(),
1535 block.getLineNumber()), myPackage, curType, ident,
1536 parentIdent, &curParams,
1537 overwrite, curIsBagReplaceOnOverwrite);
1538 if (err != NO_ERROR) {
1539 hasErrors = localHasErrors = true;
1540 }
1541 }
1542
1543 ssize_t elmIndex = 0;
1544 char elmIndexStr[14];
1545 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1546 && code != ResXMLTree::BAD_DOCUMENT) {
1547
1548 if (code == ResXMLTree::START_TAG) {
1549 if (strcmp16(block.getElementName(&len), item16.string()) != 0) {
1550 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1551 "Tag <%s> can not appear inside <%s>, only <item>\n",
1552 String8(block.getElementName(&len)).string(),
1553 String8(*curTag).string());
1554 return UNKNOWN_ERROR;
1555 }
1556
1557 String16 itemIdent;
1558 if (curType == array16) {
1559 sprintf(elmIndexStr, "^index_%d", (int)elmIndex++);
1560 itemIdent = String16(elmIndexStr);
1561 } else if (curType == plurals16) {
1562 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "quantity");
1563 if (itemIdentIdx >= 0) {
1564 String16 quantity16(block.getAttributeStringValue(itemIdentIdx, &len));
1565 if (quantity16 == other16) {
1566 itemIdent = quantityOther16;
1567 }
1568 else if (quantity16 == zero16) {
1569 itemIdent = quantityZero16;
1570 }
1571 else if (quantity16 == one16) {
1572 itemIdent = quantityOne16;
1573 }
1574 else if (quantity16 == two16) {
1575 itemIdent = quantityTwo16;
1576 }
1577 else if (quantity16 == few16) {
1578 itemIdent = quantityFew16;
1579 }
1580 else if (quantity16 == many16) {
1581 itemIdent = quantityMany16;
1582 }
1583 else {
1584 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1585 "Illegal 'quantity' attribute is <item> inside <plurals>\n");
1586 hasErrors = localHasErrors = true;
1587 }
1588 } else {
1589 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1590 "A 'quantity' attribute is required for <item> inside <plurals>\n");
1591 hasErrors = localHasErrors = true;
1592 }
1593 } else {
1594 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "name");
1595 if (itemIdentIdx >= 0) {
1596 itemIdent = String16(block.getAttributeStringValue(itemIdentIdx, &len));
1597 } else {
1598 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1599 "A 'name' attribute is required for <item>\n");
1600 hasErrors = localHasErrors = true;
1601 }
1602 }
1603
1604 ResXMLParser::ResXMLPosition parserPosition;
1605 block.getPosition(&parserPosition);
1606
1607 err = parseAndAddBag(bundle, in, &block, curParams, myPackage, curType,
1608 ident, parentIdent, itemIdent, curFormat, curIsFormatted,
Anton Krumina2ef5c02014-03-12 14:46:44 -07001609 product, NO_PSEUDOLOCALIZATION, overwrite, outTable);
Adam Lesinski282e1812014-01-23 18:17:42 -08001610 if (err == NO_ERROR) {
1611 if (curIsPseudolocalizable && localeIsDefined(curParams)
Anton Krumina2ef5c02014-03-12 14:46:44 -07001612 && bundle->getPseudolocalize() > 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001613 // pseudolocalize here
Anton Krumina2ef5c02014-03-12 14:46:44 -07001614 if ((PSEUDO_ACCENTED & bundle->getPseudolocalize()) ==
1615 PSEUDO_ACCENTED) {
1616 block.setPosition(parserPosition);
1617 err = parseAndAddBag(bundle, in, &block, pseudoParams, myPackage,
1618 curType, ident, parentIdent, itemIdent, curFormat,
1619 curIsFormatted, product, PSEUDO_ACCENTED,
1620 overwrite, outTable);
1621 }
1622 if ((PSEUDO_BIDI & bundle->getPseudolocalize()) ==
1623 PSEUDO_BIDI) {
1624 block.setPosition(parserPosition);
1625 err = parseAndAddBag(bundle, in, &block, pseudoBidiParams, myPackage,
1626 curType, ident, parentIdent, itemIdent, curFormat,
1627 curIsFormatted, product, PSEUDO_BIDI,
1628 overwrite, outTable);
1629 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001630 }
Anton Krumina2ef5c02014-03-12 14:46:44 -07001631 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001632 if (err != NO_ERROR) {
1633 hasErrors = localHasErrors = true;
1634 }
1635 } else if (code == ResXMLTree::END_TAG) {
1636 if (strcmp16(block.getElementName(&len), curTag->string()) != 0) {
1637 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1638 "Found tag </%s> where </%s> is expected\n",
1639 String8(block.getElementName(&len)).string(),
1640 String8(*curTag).string());
1641 return UNKNOWN_ERROR;
1642 }
1643 break;
1644 }
1645 }
1646 } else {
1647 ResXMLParser::ResXMLPosition parserPosition;
1648 block.getPosition(&parserPosition);
1649
1650 err = parseAndAddEntry(bundle, in, &block, curParams, myPackage, curType, ident,
1651 *curTag, curIsStyled, curFormat, curIsFormatted,
Anton Krumina2ef5c02014-03-12 14:46:44 -07001652 product, NO_PSEUDOLOCALIZATION, overwrite, &skippedResourceNames, outTable);
Adam Lesinski282e1812014-01-23 18:17:42 -08001653
1654 if (err < NO_ERROR) { // Why err < NO_ERROR instead of err != NO_ERROR?
1655 hasErrors = localHasErrors = true;
1656 }
1657 else if (err == NO_ERROR) {
1658 if (curIsPseudolocalizable && localeIsDefined(curParams)
Anton Krumina2ef5c02014-03-12 14:46:44 -07001659 && bundle->getPseudolocalize() > 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001660 // pseudolocalize here
Anton Krumina2ef5c02014-03-12 14:46:44 -07001661 if ((PSEUDO_ACCENTED & bundle->getPseudolocalize()) ==
1662 PSEUDO_ACCENTED) {
1663 block.setPosition(parserPosition);
1664 err = parseAndAddEntry(bundle, in, &block, pseudoParams, myPackage, curType,
1665 ident, *curTag, curIsStyled, curFormat,
1666 curIsFormatted, product,
1667 PSEUDO_ACCENTED, overwrite, &skippedResourceNames, outTable);
1668 }
1669 if ((PSEUDO_BIDI & bundle->getPseudolocalize()) ==
1670 PSEUDO_BIDI) {
1671 block.setPosition(parserPosition);
1672 err = parseAndAddEntry(bundle, in, &block, pseudoBidiParams,
1673 myPackage, curType, ident, *curTag, curIsStyled, curFormat,
1674 curIsFormatted, product,
1675 PSEUDO_BIDI, overwrite, &skippedResourceNames, outTable);
1676 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001677 if (err != NO_ERROR) {
1678 hasErrors = localHasErrors = true;
1679 }
1680 }
1681 }
1682 }
1683
1684#if 0
1685 if (comment.size() > 0) {
1686 printf("Comment for @%s:%s/%s: %s\n", String8(myPackage).string(),
1687 String8(curType).string(), String8(ident).string(),
1688 String8(comment).string());
1689 }
1690#endif
1691 if (!localHasErrors) {
1692 outTable->appendComment(myPackage, curType, ident, comment, false);
1693 }
1694 }
1695 else if (code == ResXMLTree::END_TAG) {
1696 if (strcmp16(block.getElementName(&len), resources16.string()) != 0) {
1697 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1698 "Unexpected end tag %s\n", String8(block.getElementName(&len)).string());
1699 return UNKNOWN_ERROR;
1700 }
1701 }
1702 else if (code == ResXMLTree::START_NAMESPACE || code == ResXMLTree::END_NAMESPACE) {
1703 }
1704 else if (code == ResXMLTree::TEXT) {
1705 if (isWhitespace(block.getText(&len))) {
1706 continue;
1707 }
1708 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1709 "Found text \"%s\" where item tag is expected\n",
1710 String8(block.getText(&len)).string());
1711 return UNKNOWN_ERROR;
1712 }
1713 }
1714
Adam Lesinski8ff15b42013-10-07 16:54:01 -07001715 // For every resource defined, there must be exist one variant with a product attribute
1716 // set to 'default' (or no product attribute at all).
1717 // We check to see that for every resource that was ignored because of a mismatched
1718 // product attribute, some product variant of that resource was processed.
1719 for (size_t i = 0; i < skippedResourceNames.size(); i++) {
1720 if (skippedResourceNames[i]) {
1721 const type_ident_pair_t& p = skippedResourceNames.keyAt(i);
1722 if (!outTable->hasBagOrEntry(myPackage, p.type, p.ident)) {
1723 const char* bundleProduct =
1724 (bundle->getProduct() == NULL) ? "" : bundle->getProduct();
1725 fprintf(stderr, "In resource file %s: %s\n",
1726 in->getPrintableSource().string(),
1727 curParams.toString().string());
1728
1729 fprintf(stderr, "\t%s '%s' does not match product %s.\n"
1730 "\tYou may have forgotten to include a 'default' product variant"
1731 " of the resource.\n",
1732 String8(p.type).string(), String8(p.ident).string(),
1733 bundleProduct[0] == 0 ? "default" : bundleProduct);
1734 return UNKNOWN_ERROR;
1735 }
1736 }
1737 }
1738
Andreas Gampe2412f842014-09-30 20:55:57 -07001739 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001740}
1741
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001742ResourceTable::ResourceTable(Bundle* bundle, const String16& assetsPackage, ResourceTable::PackageType type)
1743 : mAssetsPackage(assetsPackage)
1744 , mPackageType(type)
1745 , mTypeIdOffset(0)
1746 , mNumLocal(0)
1747 , mBundle(bundle)
Adam Lesinski282e1812014-01-23 18:17:42 -08001748{
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001749 ssize_t packageId = -1;
1750 switch (mPackageType) {
1751 case App:
1752 case AppFeature:
1753 packageId = 0x7f;
1754 break;
1755
1756 case System:
1757 packageId = 0x01;
1758 break;
1759
1760 case SharedLibrary:
1761 packageId = 0x00;
1762 break;
1763
1764 default:
1765 assert(0);
1766 break;
1767 }
1768 sp<Package> package = new Package(mAssetsPackage, packageId);
1769 mPackages.add(assetsPackage, package);
1770 mOrderedPackages.add(package);
1771
1772 // Every resource table always has one first entry, the bag attributes.
1773 const SourcePos unknown(String8("????"), 0);
1774 getType(mAssetsPackage, String16("attr"), unknown);
1775}
1776
1777static uint32_t findLargestTypeIdForPackage(const ResTable& table, const String16& packageName) {
1778 const size_t basePackageCount = table.getBasePackageCount();
1779 for (size_t i = 0; i < basePackageCount; i++) {
1780 if (packageName == table.getBasePackageName(i)) {
1781 return table.getLastTypeIdForPackage(i);
1782 }
1783 }
1784 return 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08001785}
1786
1787status_t ResourceTable::addIncludedResources(Bundle* bundle, const sp<AaptAssets>& assets)
1788{
1789 status_t err = assets->buildIncludedResources(bundle);
1790 if (err != NO_ERROR) {
1791 return err;
1792 }
1793
Adam Lesinski282e1812014-01-23 18:17:42 -08001794 mAssets = assets;
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001795 mTypeIdOffset = findLargestTypeIdForPackage(assets->getIncludedResources(), mAssetsPackage);
Adam Lesinski282e1812014-01-23 18:17:42 -08001796
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001797 const String8& featureAfter = bundle->getFeatureAfterPackage();
1798 if (!featureAfter.isEmpty()) {
1799 AssetManager featureAssetManager;
1800 if (!featureAssetManager.addAssetPath(featureAfter, NULL)) {
1801 fprintf(stderr, "ERROR: Feature package '%s' not found.\n",
1802 featureAfter.string());
1803 return UNKNOWN_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001804 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001805
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001806 const ResTable& featureTable = featureAssetManager.getResources(false);
1807 mTypeIdOffset = max(mTypeIdOffset,
1808 findLargestTypeIdForPackage(featureTable, mAssetsPackage));
1809 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001810
1811 return NO_ERROR;
1812}
1813
1814status_t ResourceTable::addPublic(const SourcePos& sourcePos,
1815 const String16& package,
1816 const String16& type,
1817 const String16& name,
1818 const uint32_t ident)
1819{
1820 uint32_t rid = mAssets->getIncludedResources()
1821 .identifierForName(name.string(), name.size(),
1822 type.string(), type.size(),
1823 package.string(), package.size());
1824 if (rid != 0) {
1825 sourcePos.error("Error declaring public resource %s/%s for included package %s\n",
1826 String8(type).string(), String8(name).string(),
1827 String8(package).string());
1828 return UNKNOWN_ERROR;
1829 }
1830
1831 sp<Type> t = getType(package, type, sourcePos);
1832 if (t == NULL) {
1833 return UNKNOWN_ERROR;
1834 }
1835 return t->addPublic(sourcePos, name, ident);
1836}
1837
1838status_t ResourceTable::addEntry(const SourcePos& sourcePos,
1839 const String16& package,
1840 const String16& type,
1841 const String16& name,
1842 const String16& value,
1843 const Vector<StringPool::entry_style_span>* style,
1844 const ResTable_config* params,
1845 const bool doSetIndex,
1846 const int32_t format,
1847 const bool overwrite)
1848{
Adam Lesinski282e1812014-01-23 18:17:42 -08001849 uint32_t rid = mAssets->getIncludedResources()
1850 .identifierForName(name.string(), name.size(),
1851 type.string(), type.size(),
1852 package.string(), package.size());
1853 if (rid != 0) {
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001854 sourcePos.error("Resource entry %s/%s is already defined in package %s.",
1855 String8(type).string(), String8(name).string(), String8(package).string());
1856 return UNKNOWN_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001857 }
1858
Adam Lesinski282e1812014-01-23 18:17:42 -08001859 sp<Entry> e = getEntry(package, type, name, sourcePos, overwrite,
1860 params, doSetIndex);
1861 if (e == NULL) {
1862 return UNKNOWN_ERROR;
1863 }
1864 status_t err = e->setItem(sourcePos, value, style, format, overwrite);
1865 if (err == NO_ERROR) {
1866 mNumLocal++;
1867 }
1868 return err;
1869}
1870
1871status_t ResourceTable::startBag(const SourcePos& sourcePos,
1872 const String16& package,
1873 const String16& type,
1874 const String16& name,
1875 const String16& bagParent,
1876 const ResTable_config* params,
1877 bool overlay,
Andreas Gampe2412f842014-09-30 20:55:57 -07001878 bool replace, bool /* isId */)
Adam Lesinski282e1812014-01-23 18:17:42 -08001879{
1880 status_t result = NO_ERROR;
1881
1882 // Check for adding entries in other packages... for now we do
1883 // nothing. We need to do the right thing here to support skinning.
1884 uint32_t rid = mAssets->getIncludedResources()
1885 .identifierForName(name.string(), name.size(),
1886 type.string(), type.size(),
1887 package.string(), package.size());
1888 if (rid != 0) {
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001889 sourcePos.error("Resource entry %s/%s is already defined in package %s.",
1890 String8(type).string(), String8(name).string(), String8(package).string());
1891 return UNKNOWN_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001892 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001893
Adam Lesinski282e1812014-01-23 18:17:42 -08001894 if (overlay && !mBundle->getAutoAddOverlay() && !hasBagOrEntry(package, type, name)) {
1895 bool canAdd = false;
1896 sp<Package> p = mPackages.valueFor(package);
1897 if (p != NULL) {
1898 sp<Type> t = p->getTypes().valueFor(type);
1899 if (t != NULL) {
1900 if (t->getCanAddEntries().indexOf(name) >= 0) {
1901 canAdd = true;
1902 }
1903 }
1904 }
1905 if (!canAdd) {
1906 sourcePos.error("Resource does not already exist in overlay at '%s'; use <add-resource> to add.\n",
1907 String8(name).string());
1908 return UNKNOWN_ERROR;
1909 }
1910 }
1911 sp<Entry> e = getEntry(package, type, name, sourcePos, overlay, params);
1912 if (e == NULL) {
1913 return UNKNOWN_ERROR;
1914 }
1915
1916 // If a parent is explicitly specified, set it.
1917 if (bagParent.size() > 0) {
1918 e->setParent(bagParent);
1919 }
1920
1921 if ((result = e->makeItABag(sourcePos)) != NO_ERROR) {
1922 return result;
1923 }
1924
1925 if (overlay && replace) {
1926 return e->emptyBag(sourcePos);
1927 }
1928 return result;
1929}
1930
1931status_t ResourceTable::addBag(const SourcePos& sourcePos,
1932 const String16& package,
1933 const String16& type,
1934 const String16& name,
1935 const String16& bagParent,
1936 const String16& bagKey,
1937 const String16& value,
1938 const Vector<StringPool::entry_style_span>* style,
1939 const ResTable_config* params,
1940 bool replace, bool isId, const int32_t format)
1941{
1942 // Check for adding entries in other packages... for now we do
1943 // nothing. We need to do the right thing here to support skinning.
1944 uint32_t rid = mAssets->getIncludedResources()
1945 .identifierForName(name.string(), name.size(),
1946 type.string(), type.size(),
1947 package.string(), package.size());
1948 if (rid != 0) {
1949 return NO_ERROR;
1950 }
1951
1952#if 0
1953 if (name == String16("left")) {
1954 printf("Adding bag left: file=%s, line=%d, type=%s\n",
1955 sourcePos.file.striing(), sourcePos.line, String8(type).string());
1956 }
1957#endif
1958 sp<Entry> e = getEntry(package, type, name, sourcePos, replace, params);
1959 if (e == NULL) {
1960 return UNKNOWN_ERROR;
1961 }
1962
1963 // If a parent is explicitly specified, set it.
1964 if (bagParent.size() > 0) {
1965 e->setParent(bagParent);
1966 }
1967
1968 const bool first = e->getBag().indexOfKey(bagKey) < 0;
1969 status_t err = e->addToBag(sourcePos, bagKey, value, style, replace, isId, format);
1970 if (err == NO_ERROR && first) {
1971 mNumLocal++;
1972 }
1973 return err;
1974}
1975
1976bool ResourceTable::hasBagOrEntry(const String16& package,
1977 const String16& type,
1978 const String16& name) const
1979{
1980 // First look for this in the included resources...
1981 uint32_t rid = mAssets->getIncludedResources()
1982 .identifierForName(name.string(), name.size(),
1983 type.string(), type.size(),
1984 package.string(), package.size());
1985 if (rid != 0) {
1986 return true;
1987 }
1988
1989 sp<Package> p = mPackages.valueFor(package);
1990 if (p != NULL) {
1991 sp<Type> t = p->getTypes().valueFor(type);
1992 if (t != NULL) {
1993 sp<ConfigList> c = t->getConfigs().valueFor(name);
1994 if (c != NULL) return true;
1995 }
1996 }
1997
1998 return false;
1999}
2000
2001bool ResourceTable::hasBagOrEntry(const String16& package,
2002 const String16& type,
2003 const String16& name,
2004 const ResTable_config& config) const
2005{
2006 // First look for this in the included resources...
2007 uint32_t rid = mAssets->getIncludedResources()
2008 .identifierForName(name.string(), name.size(),
2009 type.string(), type.size(),
2010 package.string(), package.size());
2011 if (rid != 0) {
2012 return true;
2013 }
2014
2015 sp<Package> p = mPackages.valueFor(package);
2016 if (p != NULL) {
2017 sp<Type> t = p->getTypes().valueFor(type);
2018 if (t != NULL) {
2019 sp<ConfigList> c = t->getConfigs().valueFor(name);
2020 if (c != NULL) {
2021 sp<Entry> e = c->getEntries().valueFor(config);
2022 if (e != NULL) {
2023 return true;
2024 }
2025 }
2026 }
2027 }
2028
2029 return false;
2030}
2031
2032bool ResourceTable::hasBagOrEntry(const String16& ref,
2033 const String16* defType,
2034 const String16* defPackage)
2035{
2036 String16 package, type, name;
2037 if (!ResTable::expandResourceRef(ref.string(), ref.size(), &package, &type, &name,
2038 defType, defPackage ? defPackage:&mAssetsPackage, NULL)) {
2039 return false;
2040 }
2041 return hasBagOrEntry(package, type, name);
2042}
2043
2044bool ResourceTable::appendComment(const String16& package,
2045 const String16& type,
2046 const String16& name,
2047 const String16& comment,
2048 bool onlyIfEmpty)
2049{
2050 if (comment.size() <= 0) {
2051 return true;
2052 }
2053
2054 sp<Package> p = mPackages.valueFor(package);
2055 if (p != NULL) {
2056 sp<Type> t = p->getTypes().valueFor(type);
2057 if (t != NULL) {
2058 sp<ConfigList> c = t->getConfigs().valueFor(name);
2059 if (c != NULL) {
2060 c->appendComment(comment, onlyIfEmpty);
2061 return true;
2062 }
2063 }
2064 }
2065 return false;
2066}
2067
2068bool ResourceTable::appendTypeComment(const String16& package,
2069 const String16& type,
2070 const String16& name,
2071 const String16& comment)
2072{
2073 if (comment.size() <= 0) {
2074 return true;
2075 }
2076
2077 sp<Package> p = mPackages.valueFor(package);
2078 if (p != NULL) {
2079 sp<Type> t = p->getTypes().valueFor(type);
2080 if (t != NULL) {
2081 sp<ConfigList> c = t->getConfigs().valueFor(name);
2082 if (c != NULL) {
2083 c->appendTypeComment(comment);
2084 return true;
2085 }
2086 }
2087 }
2088 return false;
2089}
2090
2091void ResourceTable::canAddEntry(const SourcePos& pos,
2092 const String16& package, const String16& type, const String16& name)
2093{
2094 sp<Type> t = getType(package, type, pos);
2095 if (t != NULL) {
2096 t->canAddEntry(name);
2097 }
2098}
2099
2100size_t ResourceTable::size() const {
2101 return mPackages.size();
2102}
2103
2104size_t ResourceTable::numLocalResources() const {
2105 return mNumLocal;
2106}
2107
2108bool ResourceTable::hasResources() const {
2109 return mNumLocal > 0;
2110}
2111
Adam Lesinski27f69f42014-08-21 13:19:12 -07002112sp<AaptFile> ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& filter,
2113 const bool isBase)
Adam Lesinski282e1812014-01-23 18:17:42 -08002114{
2115 sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
Adam Lesinski27f69f42014-08-21 13:19:12 -07002116 status_t err = flatten(bundle, filter, data, isBase);
Adam Lesinski282e1812014-01-23 18:17:42 -08002117 return err == NO_ERROR ? data : NULL;
2118}
2119
2120inline uint32_t ResourceTable::getResId(const sp<Package>& p,
2121 const sp<Type>& t,
2122 uint32_t nameId)
2123{
2124 return makeResId(p->getAssignedId(), t->getIndex(), nameId);
2125}
2126
2127uint32_t ResourceTable::getResId(const String16& package,
2128 const String16& type,
2129 const String16& name,
2130 bool onlyPublic) const
2131{
2132 uint32_t id = ResourceIdCache::lookup(package, type, name, onlyPublic);
2133 if (id != 0) return id; // cache hit
2134
Adam Lesinski282e1812014-01-23 18:17:42 -08002135 // First look for this in the included resources...
2136 uint32_t specFlags = 0;
2137 uint32_t rid = mAssets->getIncludedResources()
2138 .identifierForName(name.string(), name.size(),
2139 type.string(), type.size(),
2140 package.string(), package.size(),
2141 &specFlags);
2142 if (rid != 0) {
2143 if (onlyPublic) {
2144 if ((specFlags & ResTable_typeSpec::SPEC_PUBLIC) == 0) {
2145 return 0;
2146 }
2147 }
2148
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002149 return ResourceIdCache::store(package, type, name, onlyPublic, rid);
Adam Lesinski282e1812014-01-23 18:17:42 -08002150 }
2151
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002152 sp<Package> p = mPackages.valueFor(package);
2153 if (p == NULL) return 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08002154 sp<Type> t = p->getTypes().valueFor(type);
2155 if (t == NULL) return 0;
2156 sp<ConfigList> c = t->getConfigs().valueFor(name);
2157 if (c == NULL) return 0;
2158 int32_t ei = c->getEntryIndex();
2159 if (ei < 0) return 0;
2160
2161 return ResourceIdCache::store(package, type, name, onlyPublic,
2162 getResId(p, t, ei));
2163}
2164
2165uint32_t ResourceTable::getResId(const String16& ref,
2166 const String16* defType,
2167 const String16* defPackage,
2168 const char** outErrorMsg,
2169 bool onlyPublic) const
2170{
2171 String16 package, type, name;
2172 bool refOnlyPublic = true;
2173 if (!ResTable::expandResourceRef(
2174 ref.string(), ref.size(), &package, &type, &name,
2175 defType, defPackage ? defPackage:&mAssetsPackage,
2176 outErrorMsg, &refOnlyPublic)) {
Andreas Gampe2412f842014-09-30 20:55:57 -07002177 if (kIsDebug) {
2178 printf("Expanding resource: ref=%s\n", String8(ref).string());
2179 printf("Expanding resource: defType=%s\n",
2180 defType ? String8(*defType).string() : "NULL");
2181 printf("Expanding resource: defPackage=%s\n",
2182 defPackage ? String8(*defPackage).string() : "NULL");
2183 printf("Expanding resource: ref=%s\n", String8(ref).string());
2184 printf("Expanded resource: p=%s, t=%s, n=%s, res=0\n",
2185 String8(package).string(), String8(type).string(),
2186 String8(name).string());
2187 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002188 return 0;
2189 }
2190 uint32_t res = getResId(package, type, name, onlyPublic && refOnlyPublic);
Andreas Gampe2412f842014-09-30 20:55:57 -07002191 if (kIsDebug) {
2192 printf("Expanded resource: p=%s, t=%s, n=%s, res=%d\n",
2193 String8(package).string(), String8(type).string(),
2194 String8(name).string(), res);
2195 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002196 if (res == 0) {
2197 if (outErrorMsg)
2198 *outErrorMsg = "No resource found that matches the given name";
2199 }
2200 return res;
2201}
2202
2203bool ResourceTable::isValidResourceName(const String16& s)
2204{
2205 const char16_t* p = s.string();
2206 bool first = true;
2207 while (*p) {
2208 if ((*p >= 'a' && *p <= 'z')
2209 || (*p >= 'A' && *p <= 'Z')
2210 || *p == '_'
2211 || (!first && *p >= '0' && *p <= '9')) {
2212 first = false;
2213 p++;
2214 continue;
2215 }
2216 return false;
2217 }
2218 return true;
2219}
2220
2221bool ResourceTable::stringToValue(Res_value* outValue, StringPool* pool,
2222 const String16& str,
2223 bool preserveSpaces, bool coerceType,
2224 uint32_t attrID,
2225 const Vector<StringPool::entry_style_span>* style,
2226 String16* outStr, void* accessorCookie,
2227 uint32_t attrType, const String8* configTypeName,
2228 const ConfigDescription* config)
2229{
2230 String16 finalStr;
2231
2232 bool res = true;
2233 if (style == NULL || style->size() == 0) {
2234 // Text is not styled so it can be any type... let's figure it out.
2235 res = mAssets->getIncludedResources()
2236 .stringToValue(outValue, &finalStr, str.string(), str.size(), preserveSpaces,
2237 coerceType, attrID, NULL, &mAssetsPackage, this,
2238 accessorCookie, attrType);
2239 } else {
2240 // Styled text can only be a string, and while collecting the style
2241 // information we have already processed that string!
2242 outValue->size = sizeof(Res_value);
2243 outValue->res0 = 0;
2244 outValue->dataType = outValue->TYPE_STRING;
2245 outValue->data = 0;
2246 finalStr = str;
2247 }
2248
2249 if (!res) {
2250 return false;
2251 }
2252
2253 if (outValue->dataType == outValue->TYPE_STRING) {
2254 // Should do better merging styles.
2255 if (pool) {
2256 String8 configStr;
2257 if (config != NULL) {
2258 configStr = config->toString();
2259 } else {
2260 configStr = "(null)";
2261 }
Andreas Gampe2412f842014-09-30 20:55:57 -07002262 if (kIsDebug) {
2263 printf("Adding to pool string style #%zu config %s: %s\n",
2264 style != NULL ? style->size() : 0U,
2265 configStr.string(), String8(finalStr).string());
2266 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002267 if (style != NULL && style->size() > 0) {
2268 outValue->data = pool->add(finalStr, *style, configTypeName, config);
2269 } else {
2270 outValue->data = pool->add(finalStr, true, configTypeName, config);
2271 }
2272 } else {
2273 // Caller will fill this in later.
2274 outValue->data = 0;
2275 }
2276
2277 if (outStr) {
2278 *outStr = finalStr;
2279 }
2280
2281 }
2282
2283 return true;
2284}
2285
2286uint32_t ResourceTable::getCustomResource(
2287 const String16& package, const String16& type, const String16& name) const
2288{
2289 //printf("getCustomResource: %s %s %s\n", String8(package).string(),
2290 // String8(type).string(), String8(name).string());
2291 sp<Package> p = mPackages.valueFor(package);
2292 if (p == NULL) return 0;
2293 sp<Type> t = p->getTypes().valueFor(type);
2294 if (t == NULL) return 0;
2295 sp<ConfigList> c = t->getConfigs().valueFor(name);
2296 if (c == NULL) return 0;
2297 int32_t ei = c->getEntryIndex();
2298 if (ei < 0) return 0;
2299 return getResId(p, t, ei);
2300}
2301
2302uint32_t ResourceTable::getCustomResourceWithCreation(
2303 const String16& package, const String16& type, const String16& name,
2304 const bool createIfNotFound)
2305{
2306 uint32_t resId = getCustomResource(package, type, name);
2307 if (resId != 0 || !createIfNotFound) {
2308 return resId;
2309 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002310
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002311 if (mAssetsPackage != package) {
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002312 mCurrentXmlPos.error("creating resource for external package %s: %s/%s.",
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002313 String8(package).string(), String8(type).string(), String8(name).string());
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002314 if (package == String16("android")) {
2315 mCurrentXmlPos.printf("did you mean to use @+id instead of @+android:id?");
2316 }
2317 return 0;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002318 }
2319
2320 String16 value("false");
Adam Lesinski282e1812014-01-23 18:17:42 -08002321 status_t status = addEntry(mCurrentXmlPos, package, type, name, value, NULL, NULL, true);
2322 if (status == NO_ERROR) {
2323 resId = getResId(package, type, name);
2324 return resId;
2325 }
2326 return 0;
2327}
2328
2329uint32_t ResourceTable::getRemappedPackage(uint32_t origPackage) const
2330{
2331 return origPackage;
2332}
2333
2334bool ResourceTable::getAttributeType(uint32_t attrID, uint32_t* outType)
2335{
2336 //printf("getAttributeType #%08x\n", attrID);
2337 Res_value value;
2338 if (getItemValue(attrID, ResTable_map::ATTR_TYPE, &value)) {
2339 //printf("getAttributeType #%08x (%s): #%08x\n", attrID,
2340 // String8(getEntry(attrID)->getName()).string(), value.data);
2341 *outType = value.data;
2342 return true;
2343 }
2344 return false;
2345}
2346
2347bool ResourceTable::getAttributeMin(uint32_t attrID, uint32_t* outMin)
2348{
2349 //printf("getAttributeMin #%08x\n", attrID);
2350 Res_value value;
2351 if (getItemValue(attrID, ResTable_map::ATTR_MIN, &value)) {
2352 *outMin = value.data;
2353 return true;
2354 }
2355 return false;
2356}
2357
2358bool ResourceTable::getAttributeMax(uint32_t attrID, uint32_t* outMax)
2359{
2360 //printf("getAttributeMax #%08x\n", attrID);
2361 Res_value value;
2362 if (getItemValue(attrID, ResTable_map::ATTR_MAX, &value)) {
2363 *outMax = value.data;
2364 return true;
2365 }
2366 return false;
2367}
2368
2369uint32_t ResourceTable::getAttributeL10N(uint32_t attrID)
2370{
2371 //printf("getAttributeL10N #%08x\n", attrID);
2372 Res_value value;
2373 if (getItemValue(attrID, ResTable_map::ATTR_L10N, &value)) {
2374 return value.data;
2375 }
2376 return ResTable_map::L10N_NOT_REQUIRED;
2377}
2378
2379bool ResourceTable::getLocalizationSetting()
2380{
2381 return mBundle->getRequireLocalization();
2382}
2383
2384void ResourceTable::reportError(void* accessorCookie, const char* fmt, ...)
2385{
2386 if (accessorCookie != NULL && fmt != NULL) {
2387 AccessorCookie* ac = (AccessorCookie*)accessorCookie;
2388 int retval=0;
2389 char buf[1024];
2390 va_list ap;
2391 va_start(ap, fmt);
2392 retval = vsnprintf(buf, sizeof(buf), fmt, ap);
2393 va_end(ap);
2394 ac->sourcePos.error("Error: %s (at '%s' with value '%s').\n",
2395 buf, ac->attr.string(), ac->value.string());
2396 }
2397}
2398
2399bool ResourceTable::getAttributeKeys(
2400 uint32_t attrID, Vector<String16>* outKeys)
2401{
2402 sp<const Entry> e = getEntry(attrID);
2403 if (e != NULL) {
2404 const size_t N = e->getBag().size();
2405 for (size_t i=0; i<N; i++) {
2406 const String16& key = e->getBag().keyAt(i);
2407 if (key.size() > 0 && key.string()[0] != '^') {
2408 outKeys->add(key);
2409 }
2410 }
2411 return true;
2412 }
2413 return false;
2414}
2415
2416bool ResourceTable::getAttributeEnum(
2417 uint32_t attrID, const char16_t* name, size_t nameLen,
2418 Res_value* outValue)
2419{
2420 //printf("getAttributeEnum #%08x %s\n", attrID, String8(name, nameLen).string());
2421 String16 nameStr(name, nameLen);
2422 sp<const Entry> e = getEntry(attrID);
2423 if (e != NULL) {
2424 const size_t N = e->getBag().size();
2425 for (size_t i=0; i<N; i++) {
2426 //printf("Comparing %s to %s\n", String8(name, nameLen).string(),
2427 // String8(e->getBag().keyAt(i)).string());
2428 if (e->getBag().keyAt(i) == nameStr) {
2429 return getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, outValue);
2430 }
2431 }
2432 }
2433 return false;
2434}
2435
2436bool ResourceTable::getAttributeFlags(
2437 uint32_t attrID, const char16_t* name, size_t nameLen,
2438 Res_value* outValue)
2439{
2440 outValue->dataType = Res_value::TYPE_INT_HEX;
2441 outValue->data = 0;
2442
2443 //printf("getAttributeFlags #%08x %s\n", attrID, String8(name, nameLen).string());
2444 String16 nameStr(name, nameLen);
2445 sp<const Entry> e = getEntry(attrID);
2446 if (e != NULL) {
2447 const size_t N = e->getBag().size();
2448
2449 const char16_t* end = name + nameLen;
2450 const char16_t* pos = name;
2451 while (pos < end) {
2452 const char16_t* start = pos;
2453 while (pos < end && *pos != '|') {
2454 pos++;
2455 }
2456
2457 String16 nameStr(start, pos-start);
2458 size_t i;
2459 for (i=0; i<N; i++) {
2460 //printf("Comparing \"%s\" to \"%s\"\n", String8(nameStr).string(),
2461 // String8(e->getBag().keyAt(i)).string());
2462 if (e->getBag().keyAt(i) == nameStr) {
2463 Res_value val;
2464 bool got = getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, &val);
2465 if (!got) {
2466 return false;
2467 }
2468 //printf("Got value: 0x%08x\n", val.data);
2469 outValue->data |= val.data;
2470 break;
2471 }
2472 }
2473
2474 if (i >= N) {
2475 // Didn't find this flag identifier.
2476 return false;
2477 }
2478 pos++;
2479 }
2480
2481 return true;
2482 }
2483 return false;
2484}
2485
2486status_t ResourceTable::assignResourceIds()
2487{
2488 const size_t N = mOrderedPackages.size();
2489 size_t pi;
2490 status_t firstError = NO_ERROR;
2491
2492 // First generate all bag attributes and assign indices.
2493 for (pi=0; pi<N; pi++) {
2494 sp<Package> p = mOrderedPackages.itemAt(pi);
2495 if (p == NULL || p->getTypes().size() == 0) {
2496 // Empty, skip!
2497 continue;
2498 }
2499
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002500 // This has no sense for packages being built as AppFeature (aka with a non-zero offset).
Adam Lesinski282e1812014-01-23 18:17:42 -08002501 status_t err = p->applyPublicTypeOrder();
2502 if (err != NO_ERROR && firstError == NO_ERROR) {
2503 firstError = err;
2504 }
2505
2506 // Generate attributes...
2507 const size_t N = p->getOrderedTypes().size();
2508 size_t ti;
2509 for (ti=0; ti<N; ti++) {
2510 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2511 if (t == NULL) {
2512 continue;
2513 }
2514 const size_t N = t->getOrderedConfigs().size();
2515 for (size_t ci=0; ci<N; ci++) {
2516 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2517 if (c == NULL) {
2518 continue;
2519 }
2520 const size_t N = c->getEntries().size();
2521 for (size_t ei=0; ei<N; ei++) {
2522 sp<Entry> e = c->getEntries().valueAt(ei);
2523 if (e == NULL) {
2524 continue;
2525 }
2526 status_t err = e->generateAttributes(this, p->getName());
2527 if (err != NO_ERROR && firstError == NO_ERROR) {
2528 firstError = err;
2529 }
2530 }
2531 }
2532 }
2533
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002534 uint32_t typeIdOffset = 0;
2535 if (mPackageType == AppFeature && p->getName() == mAssetsPackage) {
2536 typeIdOffset = mTypeIdOffset;
2537 }
2538
Adam Lesinski282e1812014-01-23 18:17:42 -08002539 const SourcePos unknown(String8("????"), 0);
2540 sp<Type> attr = p->getType(String16("attr"), unknown);
2541
2542 // Assign indices...
Adam Lesinski43a0df02014-08-18 17:14:57 -07002543 const size_t typeCount = p->getOrderedTypes().size();
2544 for (size_t ti = 0; ti < typeCount; ti++) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002545 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2546 if (t == NULL) {
2547 continue;
2548 }
Adam Lesinski43a0df02014-08-18 17:14:57 -07002549
Adam Lesinski282e1812014-01-23 18:17:42 -08002550 err = t->applyPublicEntryOrder();
2551 if (err != NO_ERROR && firstError == NO_ERROR) {
2552 firstError = err;
2553 }
2554
2555 const size_t N = t->getOrderedConfigs().size();
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002556 t->setIndex(ti + 1 + typeIdOffset);
Adam Lesinski282e1812014-01-23 18:17:42 -08002557
2558 LOG_ALWAYS_FATAL_IF(ti == 0 && attr != t,
2559 "First type is not attr!");
2560
2561 for (size_t ei=0; ei<N; ei++) {
2562 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ei);
2563 if (c == NULL) {
2564 continue;
2565 }
2566 c->setEntryIndex(ei);
2567 }
2568 }
2569
2570 // Assign resource IDs to keys in bags...
Adam Lesinski43a0df02014-08-18 17:14:57 -07002571 for (size_t ti = 0; ti < typeCount; ti++) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002572 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2573 if (t == NULL) {
2574 continue;
2575 }
2576 const size_t N = t->getOrderedConfigs().size();
2577 for (size_t ci=0; ci<N; ci++) {
2578 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2579 //printf("Ordered config #%d: %p\n", ci, c.get());
2580 const size_t N = c->getEntries().size();
2581 for (size_t ei=0; ei<N; ei++) {
2582 sp<Entry> e = c->getEntries().valueAt(ei);
2583 if (e == NULL) {
2584 continue;
2585 }
2586 status_t err = e->assignResourceIds(this, p->getName());
2587 if (err != NO_ERROR && firstError == NO_ERROR) {
2588 firstError = err;
2589 }
2590 }
2591 }
2592 }
2593 }
2594 return firstError;
2595}
2596
2597status_t ResourceTable::addSymbols(const sp<AaptSymbols>& outSymbols) {
2598 const size_t N = mOrderedPackages.size();
2599 size_t pi;
2600
2601 for (pi=0; pi<N; pi++) {
2602 sp<Package> p = mOrderedPackages.itemAt(pi);
2603 if (p->getTypes().size() == 0) {
2604 // Empty, skip!
2605 continue;
2606 }
2607
2608 const size_t N = p->getOrderedTypes().size();
2609 size_t ti;
2610
2611 for (ti=0; ti<N; ti++) {
2612 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2613 if (t == NULL) {
2614 continue;
2615 }
2616 const size_t N = t->getOrderedConfigs().size();
Adam Lesinski3fb8c9b2014-09-09 16:05:10 -07002617 sp<AaptSymbols> typeSymbols =
2618 outSymbols->addNestedSymbol(String8(t->getName()), t->getPos());
2619 if (typeSymbols == NULL) {
2620 return UNKNOWN_ERROR;
2621 }
2622
Adam Lesinski282e1812014-01-23 18:17:42 -08002623 for (size_t ci=0; ci<N; ci++) {
2624 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2625 if (c == NULL) {
2626 continue;
2627 }
2628 uint32_t rid = getResId(p, t, ci);
2629 if (rid == 0) {
2630 return UNKNOWN_ERROR;
2631 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002632 if (Res_GETPACKAGE(rid) + 1 == p->getAssignedId()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002633 typeSymbols->addSymbol(String8(c->getName()), rid, c->getPos());
2634
2635 String16 comment(c->getComment());
2636 typeSymbols->appendComment(String8(c->getName()), comment, c->getPos());
Adam Lesinski8ff15b42013-10-07 16:54:01 -07002637 //printf("Type symbol [%08x] %s comment: %s\n", rid,
2638 // String8(c->getName()).string(), String8(comment).string());
Adam Lesinski282e1812014-01-23 18:17:42 -08002639 comment = c->getTypeComment();
2640 typeSymbols->appendTypeComment(String8(c->getName()), comment);
Adam Lesinski282e1812014-01-23 18:17:42 -08002641 }
2642 }
2643 }
2644 }
2645 return NO_ERROR;
2646}
2647
2648
2649void
Adam Lesinskia01a9372014-03-20 18:04:57 -07002650ResourceTable::addLocalization(const String16& name, const String8& locale, const SourcePos& src)
Adam Lesinski282e1812014-01-23 18:17:42 -08002651{
Adam Lesinskia01a9372014-03-20 18:04:57 -07002652 mLocalizations[name][locale] = src;
Adam Lesinski282e1812014-01-23 18:17:42 -08002653}
2654
2655
2656/*!
2657 * Flag various sorts of localization problems. '+' indicates checks already implemented;
2658 * '-' indicates checks that will be implemented in the future.
2659 *
2660 * + A localized string for which no default-locale version exists => warning
2661 * + A string for which no version in an explicitly-requested locale exists => warning
2662 * + A localized translation of an translateable="false" string => warning
2663 * - A localized string not provided in every locale used by the table
2664 */
2665status_t
2666ResourceTable::validateLocalizations(void)
2667{
2668 status_t err = NO_ERROR;
2669 const String8 defaultLocale;
2670
2671 // For all strings...
Adam Lesinskia01a9372014-03-20 18:04:57 -07002672 for (map<String16, map<String8, SourcePos> >::iterator nameIter = mLocalizations.begin();
Adam Lesinski282e1812014-01-23 18:17:42 -08002673 nameIter != mLocalizations.end();
2674 nameIter++) {
Adam Lesinskia01a9372014-03-20 18:04:57 -07002675 const map<String8, SourcePos>& configSrcMap = nameIter->second;
Adam Lesinski282e1812014-01-23 18:17:42 -08002676
2677 // Look for strings with no default localization
Adam Lesinskia01a9372014-03-20 18:04:57 -07002678 if (configSrcMap.count(defaultLocale) == 0) {
2679 SourcePos().warning("string '%s' has no default translation.",
2680 String8(nameIter->first).string());
2681 if (mBundle->getVerbose()) {
2682 for (map<String8, SourcePos>::const_iterator locales = configSrcMap.begin();
2683 locales != configSrcMap.end();
2684 locales++) {
2685 locales->second.printf("locale %s found", locales->first.string());
2686 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002687 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002688 // !!! TODO: throw an error here in some circumstances
2689 }
2690
2691 // Check that all requested localizations are present for this string
Adam Lesinskifab50872014-04-16 14:40:42 -07002692 if (mBundle->getConfigurations().size() > 0 && mBundle->getRequireLocalization()) {
2693 const char* allConfigs = mBundle->getConfigurations().string();
Adam Lesinski282e1812014-01-23 18:17:42 -08002694 const char* start = allConfigs;
2695 const char* comma;
2696
Adam Lesinskia01a9372014-03-20 18:04:57 -07002697 set<String8> missingConfigs;
2698 AaptLocaleValue locale;
Adam Lesinski282e1812014-01-23 18:17:42 -08002699 do {
2700 String8 config;
2701 comma = strchr(start, ',');
2702 if (comma != NULL) {
2703 config.setTo(start, comma - start);
2704 start = comma + 1;
2705 } else {
2706 config.setTo(start);
2707 }
2708
Adam Lesinskia01a9372014-03-20 18:04:57 -07002709 if (!locale.initFromFilterString(config)) {
2710 continue;
2711 }
2712
Anton Krumina2ef5c02014-03-12 14:46:44 -07002713 // don't bother with the pseudolocale "en_XA" or "ar_XB"
2714 if (config != "en_XA" && config != "ar_XB") {
Adam Lesinskia01a9372014-03-20 18:04:57 -07002715 if (configSrcMap.find(config) == configSrcMap.end()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002716 // okay, no specific localization found. it's possible that we are
2717 // requiring a specific regional localization [e.g. de_DE] but there is an
2718 // available string in the generic language localization [e.g. de];
2719 // consider that string to have fulfilled the localization requirement.
2720 String8 region(config.string(), 2);
Adam Lesinskia01a9372014-03-20 18:04:57 -07002721 if (configSrcMap.find(region) == configSrcMap.end() &&
2722 configSrcMap.count(defaultLocale) == 0) {
2723 missingConfigs.insert(config);
Adam Lesinski282e1812014-01-23 18:17:42 -08002724 }
2725 }
2726 }
Adam Lesinskia01a9372014-03-20 18:04:57 -07002727 } while (comma != NULL);
2728
2729 if (!missingConfigs.empty()) {
2730 String8 configStr;
2731 for (set<String8>::iterator iter = missingConfigs.begin();
2732 iter != missingConfigs.end();
2733 iter++) {
2734 configStr.appendFormat(" %s", iter->string());
2735 }
2736 SourcePos().warning("string '%s' is missing %u required localizations:%s",
2737 String8(nameIter->first).string(),
2738 (unsigned int)missingConfigs.size(),
2739 configStr.string());
2740 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002741 }
2742 }
2743
2744 return err;
2745}
2746
Adam Lesinski27f69f42014-08-21 13:19:12 -07002747status_t ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& filter,
2748 const sp<AaptFile>& dest,
2749 const bool isBase)
Adam Lesinski282e1812014-01-23 18:17:42 -08002750{
Adam Lesinski282e1812014-01-23 18:17:42 -08002751 const ConfigDescription nullConfig;
2752
2753 const size_t N = mOrderedPackages.size();
2754 size_t pi;
2755
2756 const static String16 mipmap16("mipmap");
2757
2758 bool useUTF8 = !bundle->getUTF16StringsOption();
2759
Adam Lesinskide898ff2014-01-29 18:20:45 -08002760 // The libraries this table references.
2761 Vector<sp<Package> > libraryPackages;
Adam Lesinski6022deb2014-08-20 14:59:19 -07002762 const ResTable& table = mAssets->getIncludedResources();
2763 const size_t basePackageCount = table.getBasePackageCount();
2764 for (size_t i = 0; i < basePackageCount; i++) {
2765 size_t packageId = table.getBasePackageId(i);
2766 String16 packageName(table.getBasePackageName(i));
2767 if (packageId > 0x01 && packageId != 0x7f &&
2768 packageName != String16("android")) {
2769 libraryPackages.add(sp<Package>(new Package(packageName, packageId)));
2770 }
2771 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08002772
Adam Lesinski282e1812014-01-23 18:17:42 -08002773 // Iterate through all data, collecting all values (strings,
2774 // references, etc).
2775 StringPool valueStrings(useUTF8);
2776 Vector<sp<Entry> > allEntries;
2777 for (pi=0; pi<N; pi++) {
2778 sp<Package> p = mOrderedPackages.itemAt(pi);
2779 if (p->getTypes().size() == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002780 continue;
2781 }
2782
2783 StringPool typeStrings(useUTF8);
2784 StringPool keyStrings(useUTF8);
2785
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002786 ssize_t stringsAdded = 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08002787 const size_t N = p->getOrderedTypes().size();
2788 for (size_t ti=0; ti<N; ti++) {
2789 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2790 if (t == NULL) {
2791 typeStrings.add(String16("<empty>"), false);
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002792 stringsAdded++;
Adam Lesinski282e1812014-01-23 18:17:42 -08002793 continue;
2794 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002795
2796 while (stringsAdded < t->getIndex() - 1) {
2797 typeStrings.add(String16("<empty>"), false);
2798 stringsAdded++;
2799 }
2800
Adam Lesinski282e1812014-01-23 18:17:42 -08002801 const String16 typeName(t->getName());
2802 typeStrings.add(typeName, false);
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002803 stringsAdded++;
Adam Lesinski282e1812014-01-23 18:17:42 -08002804
2805 // This is a hack to tweak the sorting order of the final strings,
2806 // to put stuff that is generally not language-specific first.
2807 String8 configTypeName(typeName);
2808 if (configTypeName == "drawable" || configTypeName == "layout"
2809 || configTypeName == "color" || configTypeName == "anim"
2810 || configTypeName == "interpolator" || configTypeName == "animator"
2811 || configTypeName == "xml" || configTypeName == "menu"
2812 || configTypeName == "mipmap" || configTypeName == "raw") {
2813 configTypeName = "1complex";
2814 } else {
2815 configTypeName = "2value";
2816 }
2817
Adam Lesinski27f69f42014-08-21 13:19:12 -07002818 // mipmaps don't get filtered, so they will
2819 // allways end up in the base. Make sure they
2820 // don't end up in a split.
2821 if (typeName == mipmap16 && !isBase) {
2822 continue;
2823 }
2824
Adam Lesinski282e1812014-01-23 18:17:42 -08002825 const bool filterable = (typeName != mipmap16);
2826
2827 const size_t N = t->getOrderedConfigs().size();
2828 for (size_t ci=0; ci<N; ci++) {
2829 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2830 if (c == NULL) {
2831 continue;
2832 }
2833 const size_t N = c->getEntries().size();
2834 for (size_t ei=0; ei<N; ei++) {
2835 ConfigDescription config = c->getEntries().keyAt(ei);
Adam Lesinskifab50872014-04-16 14:40:42 -07002836 if (filterable && !filter->match(config)) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002837 continue;
2838 }
2839 sp<Entry> e = c->getEntries().valueAt(ei);
2840 if (e == NULL) {
2841 continue;
2842 }
2843 e->setNameIndex(keyStrings.add(e->getName(), true));
2844
2845 // If this entry has no values for other configs,
2846 // and is the default config, then it is special. Otherwise
2847 // we want to add it with the config info.
2848 ConfigDescription* valueConfig = NULL;
2849 if (N != 1 || config == nullConfig) {
2850 valueConfig = &config;
2851 }
2852
2853 status_t err = e->prepareFlatten(&valueStrings, this,
2854 &configTypeName, &config);
2855 if (err != NO_ERROR) {
2856 return err;
2857 }
2858 allEntries.add(e);
2859 }
2860 }
2861 }
2862
2863 p->setTypeStrings(typeStrings.createStringBlock());
2864 p->setKeyStrings(keyStrings.createStringBlock());
2865 }
2866
2867 if (bundle->getOutputAPKFile() != NULL) {
2868 // Now we want to sort the value strings for better locality. This will
2869 // cause the positions of the strings to change, so we need to go back
2870 // through out resource entries and update them accordingly. Only need
2871 // to do this if actually writing the output file.
2872 valueStrings.sortByConfig();
2873 for (pi=0; pi<allEntries.size(); pi++) {
2874 allEntries[pi]->remapStringValue(&valueStrings);
2875 }
2876 }
2877
2878 ssize_t strAmt = 0;
Adam Lesinskide898ff2014-01-29 18:20:45 -08002879
Adam Lesinski282e1812014-01-23 18:17:42 -08002880 // Now build the array of package chunks.
2881 Vector<sp<AaptFile> > flatPackages;
2882 for (pi=0; pi<N; pi++) {
2883 sp<Package> p = mOrderedPackages.itemAt(pi);
2884 if (p->getTypes().size() == 0) {
2885 // Empty, skip!
2886 continue;
2887 }
2888
2889 const size_t N = p->getTypeStrings().size();
2890
2891 const size_t baseSize = sizeof(ResTable_package);
2892
2893 // Start the package data.
2894 sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
2895 ResTable_package* header = (ResTable_package*)data->editData(baseSize);
2896 if (header == NULL) {
2897 fprintf(stderr, "ERROR: out of memory creating ResTable_package\n");
2898 return NO_MEMORY;
2899 }
2900 memset(header, 0, sizeof(*header));
2901 header->header.type = htods(RES_TABLE_PACKAGE_TYPE);
2902 header->header.headerSize = htods(sizeof(*header));
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002903 header->id = htodl(static_cast<uint32_t>(p->getAssignedId()));
Adam Lesinski282e1812014-01-23 18:17:42 -08002904 strcpy16_htod(header->name, p->getName().string());
2905
2906 // Write the string blocks.
2907 const size_t typeStringsStart = data->getSize();
2908 sp<AaptFile> strFile = p->getTypeStringsData();
2909 ssize_t amt = data->writeData(strFile->getData(), strFile->getSize());
Andreas Gampe2412f842014-09-30 20:55:57 -07002910 if (kPrintStringMetrics) {
2911 fprintf(stderr, "**** type strings: %zd\n", SSIZE(amt));
2912 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002913 strAmt += amt;
2914 if (amt < 0) {
2915 return amt;
2916 }
2917 const size_t keyStringsStart = data->getSize();
2918 strFile = p->getKeyStringsData();
2919 amt = data->writeData(strFile->getData(), strFile->getSize());
Andreas Gampe2412f842014-09-30 20:55:57 -07002920 if (kPrintStringMetrics) {
2921 fprintf(stderr, "**** key strings: %zd\n", SSIZE(amt));
2922 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002923 strAmt += amt;
2924 if (amt < 0) {
2925 return amt;
2926 }
2927
Adam Lesinski27f69f42014-08-21 13:19:12 -07002928 if (isBase) {
2929 status_t err = flattenLibraryTable(data, libraryPackages);
2930 if (err != NO_ERROR) {
2931 fprintf(stderr, "ERROR: failed to write library table\n");
2932 return err;
2933 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08002934 }
2935
Adam Lesinski282e1812014-01-23 18:17:42 -08002936 // Build the type chunks inside of this package.
2937 for (size_t ti=0; ti<N; ti++) {
2938 // Retrieve them in the same order as the type string block.
2939 size_t len;
2940 String16 typeName(p->getTypeStrings().stringAt(ti, &len));
2941 sp<Type> t = p->getTypes().valueFor(typeName);
2942 LOG_ALWAYS_FATAL_IF(t == NULL && typeName != String16("<empty>"),
2943 "Type name %s not found",
2944 String8(typeName).string());
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002945 if (t == NULL) {
2946 continue;
2947 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002948 const bool filterable = (typeName != mipmap16);
Adam Lesinski27f69f42014-08-21 13:19:12 -07002949 const bool skipEntireType = (typeName == mipmap16 && !isBase);
Adam Lesinski282e1812014-01-23 18:17:42 -08002950
2951 const size_t N = t != NULL ? t->getOrderedConfigs().size() : 0;
2952
2953 // Until a non-NO_ENTRY value has been written for a resource,
2954 // that resource is invalid; validResources[i] represents
2955 // the item at t->getOrderedConfigs().itemAt(i).
2956 Vector<bool> validResources;
2957 validResources.insertAt(false, 0, N);
2958
2959 // First write the typeSpec chunk, containing information about
2960 // each resource entry in this type.
2961 {
2962 const size_t typeSpecSize = sizeof(ResTable_typeSpec) + sizeof(uint32_t)*N;
2963 const size_t typeSpecStart = data->getSize();
2964 ResTable_typeSpec* tsHeader = (ResTable_typeSpec*)
2965 (((uint8_t*)data->editData(typeSpecStart+typeSpecSize)) + typeSpecStart);
2966 if (tsHeader == NULL) {
2967 fprintf(stderr, "ERROR: out of memory creating ResTable_typeSpec\n");
2968 return NO_MEMORY;
2969 }
2970 memset(tsHeader, 0, sizeof(*tsHeader));
2971 tsHeader->header.type = htods(RES_TABLE_TYPE_SPEC_TYPE);
2972 tsHeader->header.headerSize = htods(sizeof(*tsHeader));
2973 tsHeader->header.size = htodl(typeSpecSize);
2974 tsHeader->id = ti+1;
2975 tsHeader->entryCount = htodl(N);
2976
2977 uint32_t* typeSpecFlags = (uint32_t*)
2978 (((uint8_t*)data->editData())
2979 + typeSpecStart + sizeof(ResTable_typeSpec));
2980 memset(typeSpecFlags, 0, sizeof(uint32_t)*N);
2981
2982 for (size_t ei=0; ei<N; ei++) {
2983 sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
2984 if (cl->getPublic()) {
2985 typeSpecFlags[ei] |= htodl(ResTable_typeSpec::SPEC_PUBLIC);
2986 }
Adam Lesinski27f69f42014-08-21 13:19:12 -07002987
2988 if (skipEntireType) {
2989 continue;
2990 }
2991
Adam Lesinski282e1812014-01-23 18:17:42 -08002992 const size_t CN = cl->getEntries().size();
2993 for (size_t ci=0; ci<CN; ci++) {
Adam Lesinskifab50872014-04-16 14:40:42 -07002994 if (filterable && !filter->match(cl->getEntries().keyAt(ci))) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002995 continue;
2996 }
2997 for (size_t cj=ci+1; cj<CN; cj++) {
Adam Lesinskifab50872014-04-16 14:40:42 -07002998 if (filterable && !filter->match(cl->getEntries().keyAt(cj))) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002999 continue;
3000 }
3001 typeSpecFlags[ei] |= htodl(
3002 cl->getEntries().keyAt(ci).diff(cl->getEntries().keyAt(cj)));
3003 }
3004 }
3005 }
3006 }
3007
Adam Lesinski27f69f42014-08-21 13:19:12 -07003008 if (skipEntireType) {
3009 continue;
3010 }
3011
Adam Lesinski282e1812014-01-23 18:17:42 -08003012 // We need to write one type chunk for each configuration for
3013 // which we have entries in this type.
Jörgen Ekströmda44fe02011-03-24 15:09:42 +01003014 const size_t NC = t != NULL ? t->getUniqueConfigs().size() : 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08003015
3016 const size_t typeSize = sizeof(ResTable_type) + sizeof(uint32_t)*N;
3017
3018 for (size_t ci=0; ci<NC; ci++) {
3019 ConfigDescription config = t->getUniqueConfigs().itemAt(ci);
3020
Andreas Gampe2412f842014-09-30 20:55:57 -07003021 if (kIsDebug) {
3022 printf("Writing config %zu config: imsi:%d/%d lang:%c%c cnt:%c%c "
3023 "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
3024 "sw%ddp w%ddp h%ddp layout:%d\n",
3025 ti + 1,
3026 config.mcc, config.mnc,
3027 config.language[0] ? config.language[0] : '-',
3028 config.language[1] ? config.language[1] : '-',
3029 config.country[0] ? config.country[0] : '-',
3030 config.country[1] ? config.country[1] : '-',
3031 config.orientation,
3032 config.uiMode,
3033 config.touchscreen,
3034 config.density,
3035 config.keyboard,
3036 config.inputFlags,
3037 config.navigation,
3038 config.screenWidth,
3039 config.screenHeight,
3040 config.smallestScreenWidthDp,
3041 config.screenWidthDp,
3042 config.screenHeightDp,
3043 config.screenLayout);
3044 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003045
Adam Lesinskifab50872014-04-16 14:40:42 -07003046 if (filterable && !filter->match(config)) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003047 continue;
3048 }
3049
3050 const size_t typeStart = data->getSize();
3051
3052 ResTable_type* tHeader = (ResTable_type*)
3053 (((uint8_t*)data->editData(typeStart+typeSize)) + typeStart);
3054 if (tHeader == NULL) {
3055 fprintf(stderr, "ERROR: out of memory creating ResTable_type\n");
3056 return NO_MEMORY;
3057 }
3058
3059 memset(tHeader, 0, sizeof(*tHeader));
3060 tHeader->header.type = htods(RES_TABLE_TYPE_TYPE);
3061 tHeader->header.headerSize = htods(sizeof(*tHeader));
3062 tHeader->id = ti+1;
3063 tHeader->entryCount = htodl(N);
3064 tHeader->entriesStart = htodl(typeSize);
3065 tHeader->config = config;
Andreas Gampe2412f842014-09-30 20:55:57 -07003066 if (kIsDebug) {
3067 printf("Writing type %zu config: imsi:%d/%d lang:%c%c cnt:%c%c "
3068 "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
3069 "sw%ddp w%ddp h%ddp layout:%d\n",
3070 ti + 1,
3071 tHeader->config.mcc, tHeader->config.mnc,
3072 tHeader->config.language[0] ? tHeader->config.language[0] : '-',
3073 tHeader->config.language[1] ? tHeader->config.language[1] : '-',
3074 tHeader->config.country[0] ? tHeader->config.country[0] : '-',
3075 tHeader->config.country[1] ? tHeader->config.country[1] : '-',
3076 tHeader->config.orientation,
3077 tHeader->config.uiMode,
3078 tHeader->config.touchscreen,
3079 tHeader->config.density,
3080 tHeader->config.keyboard,
3081 tHeader->config.inputFlags,
3082 tHeader->config.navigation,
3083 tHeader->config.screenWidth,
3084 tHeader->config.screenHeight,
3085 tHeader->config.smallestScreenWidthDp,
3086 tHeader->config.screenWidthDp,
3087 tHeader->config.screenHeightDp,
3088 tHeader->config.screenLayout);
3089 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003090 tHeader->config.swapHtoD();
3091
3092 // Build the entries inside of this type.
3093 for (size_t ei=0; ei<N; ei++) {
3094 sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
3095 sp<Entry> e = cl->getEntries().valueFor(config);
3096
3097 // Set the offset for this entry in its type.
3098 uint32_t* index = (uint32_t*)
3099 (((uint8_t*)data->editData())
3100 + typeStart + sizeof(ResTable_type));
3101 if (e != NULL) {
3102 index[ei] = htodl(data->getSize()-typeStart-typeSize);
3103
3104 // Create the entry.
3105 ssize_t amt = e->flatten(bundle, data, cl->getPublic());
3106 if (amt < 0) {
3107 return amt;
3108 }
3109 validResources.editItemAt(ei) = true;
3110 } else {
3111 index[ei] = htodl(ResTable_type::NO_ENTRY);
3112 }
3113 }
3114
3115 // Fill in the rest of the type information.
3116 tHeader = (ResTable_type*)
3117 (((uint8_t*)data->editData()) + typeStart);
3118 tHeader->header.size = htodl(data->getSize()-typeStart);
3119 }
3120
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003121 // If we're building splits, then each invocation of the flattening
3122 // step will have 'missing' entries. Don't warn/error for this case.
3123 if (bundle->getSplitConfigurations().isEmpty()) {
3124 bool missing_entry = false;
3125 const char* log_prefix = bundle->getErrorOnMissingConfigEntry() ?
3126 "error" : "warning";
3127 for (size_t i = 0; i < N; ++i) {
3128 if (!validResources[i]) {
3129 sp<ConfigList> c = t->getOrderedConfigs().itemAt(i);
3130 fprintf(stderr, "%s: no entries written for %s/%s (0x%08x)\n", log_prefix,
3131 String8(typeName).string(), String8(c->getName()).string(),
3132 Res_MAKEID(p->getAssignedId() - 1, ti, i));
3133 missing_entry = true;
3134 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003135 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003136 if (bundle->getErrorOnMissingConfigEntry() && missing_entry) {
3137 fprintf(stderr, "Error: Missing entries, quit!\n");
3138 return NOT_ENOUGH_DATA;
3139 }
Ying Wangcd28bd32013-11-14 17:12:10 -08003140 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003141 }
3142
3143 // Fill in the rest of the package information.
3144 header = (ResTable_package*)data->editData();
3145 header->header.size = htodl(data->getSize());
3146 header->typeStrings = htodl(typeStringsStart);
3147 header->lastPublicType = htodl(p->getTypeStrings().size());
3148 header->keyStrings = htodl(keyStringsStart);
3149 header->lastPublicKey = htodl(p->getKeyStrings().size());
3150
3151 flatPackages.add(data);
3152 }
3153
3154 // And now write out the final chunks.
3155 const size_t dataStart = dest->getSize();
3156
3157 {
3158 // blah
3159 ResTable_header header;
3160 memset(&header, 0, sizeof(header));
3161 header.header.type = htods(RES_TABLE_TYPE);
3162 header.header.headerSize = htods(sizeof(header));
3163 header.packageCount = htodl(flatPackages.size());
3164 status_t err = dest->writeData(&header, sizeof(header));
3165 if (err != NO_ERROR) {
3166 fprintf(stderr, "ERROR: out of memory creating ResTable_header\n");
3167 return err;
3168 }
3169 }
3170
3171 ssize_t strStart = dest->getSize();
Adam Lesinskifab50872014-04-16 14:40:42 -07003172 status_t err = valueStrings.writeStringBlock(dest);
Adam Lesinski282e1812014-01-23 18:17:42 -08003173 if (err != NO_ERROR) {
3174 return err;
3175 }
3176
3177 ssize_t amt = (dest->getSize()-strStart);
3178 strAmt += amt;
Andreas Gampe2412f842014-09-30 20:55:57 -07003179 if (kPrintStringMetrics) {
3180 fprintf(stderr, "**** value strings: %zd\n", SSIZE(amt));
3181 fprintf(stderr, "**** total strings: %zd\n", SSIZE(strAmt));
3182 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08003183
Adam Lesinski282e1812014-01-23 18:17:42 -08003184 for (pi=0; pi<flatPackages.size(); pi++) {
3185 err = dest->writeData(flatPackages[pi]->getData(),
3186 flatPackages[pi]->getSize());
3187 if (err != NO_ERROR) {
3188 fprintf(stderr, "ERROR: out of memory creating package chunk for ResTable_header\n");
3189 return err;
3190 }
3191 }
3192
3193 ResTable_header* header = (ResTable_header*)
3194 (((uint8_t*)dest->getData()) + dataStart);
3195 header->header.size = htodl(dest->getSize() - dataStart);
3196
Andreas Gampe2412f842014-09-30 20:55:57 -07003197 if (kPrintStringMetrics) {
3198 fprintf(stderr, "**** total resource table size: %zu / %zu%% strings\n",
3199 dest->getSize(), (size_t)(strAmt*100)/dest->getSize());
3200 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003201
3202 return NO_ERROR;
3203}
3204
Adam Lesinskide898ff2014-01-29 18:20:45 -08003205status_t ResourceTable::flattenLibraryTable(const sp<AaptFile>& dest, const Vector<sp<Package> >& libs) {
3206 // Write out the library table if necessary
3207 if (libs.size() > 0) {
Andreas Gampe87332a72014-10-01 22:03:58 -07003208 if (kIsDebug) {
3209 fprintf(stderr, "Writing library reference table\n");
3210 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08003211
3212 const size_t libStart = dest->getSize();
3213 const size_t count = libs.size();
Adam Lesinski6022deb2014-08-20 14:59:19 -07003214 ResTable_lib_header* libHeader = (ResTable_lib_header*) dest->editDataInRange(
3215 libStart, sizeof(ResTable_lib_header));
Adam Lesinskide898ff2014-01-29 18:20:45 -08003216
3217 memset(libHeader, 0, sizeof(*libHeader));
3218 libHeader->header.type = htods(RES_TABLE_LIBRARY_TYPE);
3219 libHeader->header.headerSize = htods(sizeof(*libHeader));
3220 libHeader->header.size = htodl(sizeof(*libHeader) + (sizeof(ResTable_lib_entry) * count));
3221 libHeader->count = htodl(count);
3222
3223 // Write the library entries
3224 for (size_t i = 0; i < count; i++) {
3225 const size_t entryStart = dest->getSize();
3226 sp<Package> libPackage = libs[i];
Andreas Gampe87332a72014-10-01 22:03:58 -07003227 if (kIsDebug) {
3228 fprintf(stderr, " Entry %s -> 0x%02x\n",
Adam Lesinskide898ff2014-01-29 18:20:45 -08003229 String8(libPackage->getName()).string(),
Andreas Gampe87332a72014-10-01 22:03:58 -07003230 (uint8_t)libPackage->getAssignedId());
3231 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08003232
Adam Lesinski6022deb2014-08-20 14:59:19 -07003233 ResTable_lib_entry* entry = (ResTable_lib_entry*) dest->editDataInRange(
3234 entryStart, sizeof(ResTable_lib_entry));
Adam Lesinskide898ff2014-01-29 18:20:45 -08003235 memset(entry, 0, sizeof(*entry));
3236 entry->packageId = htodl(libPackage->getAssignedId());
3237 strcpy16_htod(entry->packageName, libPackage->getName().string());
3238 }
3239 }
3240 return NO_ERROR;
3241}
3242
Adam Lesinski282e1812014-01-23 18:17:42 -08003243void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp)
3244{
3245 fprintf(fp,
3246 "<!-- This file contains <public> resource definitions for all\n"
3247 " resources that were generated from the source data. -->\n"
3248 "\n"
3249 "<resources>\n");
3250
3251 writePublicDefinitions(package, fp, true);
3252 writePublicDefinitions(package, fp, false);
3253
3254 fprintf(fp,
3255 "\n"
3256 "</resources>\n");
3257}
3258
3259void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp, bool pub)
3260{
3261 bool didHeader = false;
3262
3263 sp<Package> pkg = mPackages.valueFor(package);
3264 if (pkg != NULL) {
3265 const size_t NT = pkg->getOrderedTypes().size();
3266 for (size_t i=0; i<NT; i++) {
3267 sp<Type> t = pkg->getOrderedTypes().itemAt(i);
3268 if (t == NULL) {
3269 continue;
3270 }
3271
3272 bool didType = false;
3273
3274 const size_t NC = t->getOrderedConfigs().size();
3275 for (size_t j=0; j<NC; j++) {
3276 sp<ConfigList> c = t->getOrderedConfigs().itemAt(j);
3277 if (c == NULL) {
3278 continue;
3279 }
3280
3281 if (c->getPublic() != pub) {
3282 continue;
3283 }
3284
3285 if (!didType) {
3286 fprintf(fp, "\n");
3287 didType = true;
3288 }
3289 if (!didHeader) {
3290 if (pub) {
3291 fprintf(fp," <!-- PUBLIC SECTION. These resources have been declared public.\n");
3292 fprintf(fp," Changes to these definitions will break binary compatibility. -->\n\n");
3293 } else {
3294 fprintf(fp," <!-- PRIVATE SECTION. These resources have not been declared public.\n");
3295 fprintf(fp," You can make them public my moving these lines into a file in res/values. -->\n\n");
3296 }
3297 didHeader = true;
3298 }
3299 if (!pub) {
3300 const size_t NE = c->getEntries().size();
3301 for (size_t k=0; k<NE; k++) {
3302 const SourcePos& pos = c->getEntries().valueAt(k)->getPos();
3303 if (pos.file != "") {
3304 fprintf(fp," <!-- Declared at %s:%d -->\n",
3305 pos.file.string(), pos.line);
3306 }
3307 }
3308 }
3309 fprintf(fp, " <public type=\"%s\" name=\"%s\" id=\"0x%08x\" />\n",
3310 String8(t->getName()).string(),
3311 String8(c->getName()).string(),
3312 getResId(pkg, t, c->getEntryIndex()));
3313 }
3314 }
3315 }
3316}
3317
3318ResourceTable::Item::Item(const SourcePos& _sourcePos,
3319 bool _isId,
3320 const String16& _value,
3321 const Vector<StringPool::entry_style_span>* _style,
3322 int32_t _format)
3323 : sourcePos(_sourcePos)
3324 , isId(_isId)
3325 , value(_value)
3326 , format(_format)
3327 , bagKeyId(0)
3328 , evaluating(false)
3329{
3330 if (_style) {
3331 style = *_style;
3332 }
3333}
3334
Adam Lesinski82a2dd82014-09-17 18:34:15 -07003335ResourceTable::Entry::Entry(const Entry& entry)
3336 : RefBase()
3337 , mName(entry.mName)
3338 , mParent(entry.mParent)
3339 , mType(entry.mType)
3340 , mItem(entry.mItem)
3341 , mItemFormat(entry.mItemFormat)
3342 , mBag(entry.mBag)
3343 , mNameIndex(entry.mNameIndex)
3344 , mParentId(entry.mParentId)
3345 , mPos(entry.mPos) {}
3346
Adam Lesinski978ab9d2014-09-24 19:02:52 -07003347ResourceTable::Entry& ResourceTable::Entry::operator=(const Entry& entry) {
3348 mName = entry.mName;
3349 mParent = entry.mParent;
3350 mType = entry.mType;
3351 mItem = entry.mItem;
3352 mItemFormat = entry.mItemFormat;
3353 mBag = entry.mBag;
3354 mNameIndex = entry.mNameIndex;
3355 mParentId = entry.mParentId;
3356 mPos = entry.mPos;
3357 return *this;
3358}
3359
Adam Lesinski282e1812014-01-23 18:17:42 -08003360status_t ResourceTable::Entry::makeItABag(const SourcePos& sourcePos)
3361{
3362 if (mType == TYPE_BAG) {
3363 return NO_ERROR;
3364 }
3365 if (mType == TYPE_UNKNOWN) {
3366 mType = TYPE_BAG;
3367 return NO_ERROR;
3368 }
3369 sourcePos.error("Resource entry %s is already defined as a single item.\n"
3370 "%s:%d: Originally defined here.\n",
3371 String8(mName).string(),
3372 mItem.sourcePos.file.string(), mItem.sourcePos.line);
3373 return UNKNOWN_ERROR;
3374}
3375
3376status_t ResourceTable::Entry::setItem(const SourcePos& sourcePos,
3377 const String16& value,
3378 const Vector<StringPool::entry_style_span>* style,
3379 int32_t format,
3380 const bool overwrite)
3381{
3382 Item item(sourcePos, false, value, style);
3383
3384 if (mType == TYPE_BAG) {
Adam Lesinski43a0df02014-08-18 17:14:57 -07003385 if (mBag.size() == 0) {
3386 sourcePos.error("Resource entry %s is already defined as a bag.",
3387 String8(mName).string());
3388 } else {
3389 const Item& item(mBag.valueAt(0));
3390 sourcePos.error("Resource entry %s is already defined as a bag.\n"
3391 "%s:%d: Originally defined here.\n",
3392 String8(mName).string(),
3393 item.sourcePos.file.string(), item.sourcePos.line);
3394 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003395 return UNKNOWN_ERROR;
3396 }
3397 if ( (mType != TYPE_UNKNOWN) && (overwrite == false) ) {
3398 sourcePos.error("Resource entry %s is already defined.\n"
3399 "%s:%d: Originally defined here.\n",
3400 String8(mName).string(),
3401 mItem.sourcePos.file.string(), mItem.sourcePos.line);
3402 return UNKNOWN_ERROR;
3403 }
3404
3405 mType = TYPE_ITEM;
3406 mItem = item;
3407 mItemFormat = format;
3408 return NO_ERROR;
3409}
3410
3411status_t ResourceTable::Entry::addToBag(const SourcePos& sourcePos,
3412 const String16& key, const String16& value,
3413 const Vector<StringPool::entry_style_span>* style,
3414 bool replace, bool isId, int32_t format)
3415{
3416 status_t err = makeItABag(sourcePos);
3417 if (err != NO_ERROR) {
3418 return err;
3419 }
3420
3421 Item item(sourcePos, isId, value, style, format);
3422
3423 // XXX NOTE: there is an error if you try to have a bag with two keys,
3424 // one an attr and one an id, with the same name. Not something we
3425 // currently ever have to worry about.
3426 ssize_t origKey = mBag.indexOfKey(key);
3427 if (origKey >= 0) {
3428 if (!replace) {
3429 const Item& item(mBag.valueAt(origKey));
3430 sourcePos.error("Resource entry %s already has bag item %s.\n"
3431 "%s:%d: Originally defined here.\n",
3432 String8(mName).string(), String8(key).string(),
3433 item.sourcePos.file.string(), item.sourcePos.line);
3434 return UNKNOWN_ERROR;
3435 }
3436 //printf("Replacing %s with %s\n",
3437 // String8(mBag.valueFor(key).value).string(), String8(value).string());
3438 mBag.replaceValueFor(key, item);
3439 }
3440
3441 mBag.add(key, item);
3442 return NO_ERROR;
3443}
3444
Adam Lesinski82a2dd82014-09-17 18:34:15 -07003445status_t ResourceTable::Entry::removeFromBag(const String16& key) {
3446 if (mType != Entry::TYPE_BAG) {
3447 return NO_ERROR;
3448 }
3449
3450 if (mBag.removeItem(key) >= 0) {
3451 return NO_ERROR;
3452 }
3453 return UNKNOWN_ERROR;
3454}
3455
Adam Lesinski282e1812014-01-23 18:17:42 -08003456status_t ResourceTable::Entry::emptyBag(const SourcePos& sourcePos)
3457{
3458 status_t err = makeItABag(sourcePos);
3459 if (err != NO_ERROR) {
3460 return err;
3461 }
3462
3463 mBag.clear();
3464 return NO_ERROR;
3465}
3466
3467status_t ResourceTable::Entry::generateAttributes(ResourceTable* table,
3468 const String16& package)
3469{
3470 const String16 attr16("attr");
3471 const String16 id16("id");
3472 const size_t N = mBag.size();
3473 for (size_t i=0; i<N; i++) {
3474 const String16& key = mBag.keyAt(i);
3475 const Item& it = mBag.valueAt(i);
3476 if (it.isId) {
3477 if (!table->hasBagOrEntry(key, &id16, &package)) {
3478 String16 value("false");
Andreas Gampe87332a72014-10-01 22:03:58 -07003479 if (kIsDebug) {
3480 fprintf(stderr, "Generating %s:id/%s\n",
3481 String8(package).string(),
3482 String8(key).string());
3483 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003484 status_t err = table->addEntry(SourcePos(String8("<generated>"), 0), package,
3485 id16, key, value);
3486 if (err != NO_ERROR) {
3487 return err;
3488 }
3489 }
3490 } else if (!table->hasBagOrEntry(key, &attr16, &package)) {
3491
3492#if 1
3493// fprintf(stderr, "ERROR: Bag attribute '%s' has not been defined.\n",
3494// String8(key).string());
3495// const Item& item(mBag.valueAt(i));
3496// fprintf(stderr, "Referenced from file %s line %d\n",
3497// item.sourcePos.file.string(), item.sourcePos.line);
3498// return UNKNOWN_ERROR;
3499#else
3500 char numberStr[16];
3501 sprintf(numberStr, "%d", ResTable_map::TYPE_ANY);
3502 status_t err = table->addBag(SourcePos("<generated>", 0), package,
3503 attr16, key, String16(""),
3504 String16("^type"),
3505 String16(numberStr), NULL, NULL);
3506 if (err != NO_ERROR) {
3507 return err;
3508 }
3509#endif
3510 }
3511 }
3512 return NO_ERROR;
3513}
3514
3515status_t ResourceTable::Entry::assignResourceIds(ResourceTable* table,
Andreas Gampe2412f842014-09-30 20:55:57 -07003516 const String16& /* package */)
Adam Lesinski282e1812014-01-23 18:17:42 -08003517{
3518 bool hasErrors = false;
3519
3520 if (mType == TYPE_BAG) {
3521 const char* errorMsg;
3522 const String16 style16("style");
3523 const String16 attr16("attr");
3524 const String16 id16("id");
3525 mParentId = 0;
3526 if (mParent.size() > 0) {
3527 mParentId = table->getResId(mParent, &style16, NULL, &errorMsg);
3528 if (mParentId == 0) {
3529 mPos.error("Error retrieving parent for item: %s '%s'.\n",
3530 errorMsg, String8(mParent).string());
3531 hasErrors = true;
3532 }
3533 }
3534 const size_t N = mBag.size();
3535 for (size_t i=0; i<N; i++) {
3536 const String16& key = mBag.keyAt(i);
3537 Item& it = mBag.editValueAt(i);
3538 it.bagKeyId = table->getResId(key,
3539 it.isId ? &id16 : &attr16, NULL, &errorMsg);
3540 //printf("Bag key of %s: #%08x\n", String8(key).string(), it.bagKeyId);
3541 if (it.bagKeyId == 0) {
3542 it.sourcePos.error("Error: %s: %s '%s'.\n", errorMsg,
3543 String8(it.isId ? id16 : attr16).string(),
3544 String8(key).string());
3545 hasErrors = true;
3546 }
3547 }
3548 }
Andreas Gampe2412f842014-09-30 20:55:57 -07003549 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08003550}
3551
3552status_t ResourceTable::Entry::prepareFlatten(StringPool* strings, ResourceTable* table,
3553 const String8* configTypeName, const ConfigDescription* config)
3554{
3555 if (mType == TYPE_ITEM) {
3556 Item& it = mItem;
3557 AccessorCookie ac(it.sourcePos, String8(mName), String8(it.value));
3558 if (!table->stringToValue(&it.parsedValue, strings,
3559 it.value, false, true, 0,
3560 &it.style, NULL, &ac, mItemFormat,
3561 configTypeName, config)) {
3562 return UNKNOWN_ERROR;
3563 }
3564 } else if (mType == TYPE_BAG) {
3565 const size_t N = mBag.size();
3566 for (size_t i=0; i<N; i++) {
3567 const String16& key = mBag.keyAt(i);
3568 Item& it = mBag.editValueAt(i);
3569 AccessorCookie ac(it.sourcePos, String8(key), String8(it.value));
3570 if (!table->stringToValue(&it.parsedValue, strings,
3571 it.value, false, true, it.bagKeyId,
3572 &it.style, NULL, &ac, it.format,
3573 configTypeName, config)) {
3574 return UNKNOWN_ERROR;
3575 }
3576 }
3577 } else {
3578 mPos.error("Error: entry %s is not a single item or a bag.\n",
3579 String8(mName).string());
3580 return UNKNOWN_ERROR;
3581 }
3582 return NO_ERROR;
3583}
3584
3585status_t ResourceTable::Entry::remapStringValue(StringPool* strings)
3586{
3587 if (mType == TYPE_ITEM) {
3588 Item& it = mItem;
3589 if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3590 it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3591 }
3592 } else if (mType == TYPE_BAG) {
3593 const size_t N = mBag.size();
3594 for (size_t i=0; i<N; i++) {
3595 Item& it = mBag.editValueAt(i);
3596 if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3597 it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3598 }
3599 }
3600 } else {
3601 mPos.error("Error: entry %s is not a single item or a bag.\n",
3602 String8(mName).string());
3603 return UNKNOWN_ERROR;
3604 }
3605 return NO_ERROR;
3606}
3607
Andreas Gampe2412f842014-09-30 20:55:57 -07003608ssize_t ResourceTable::Entry::flatten(Bundle* /* bundle */, const sp<AaptFile>& data, bool isPublic)
Adam Lesinski282e1812014-01-23 18:17:42 -08003609{
3610 size_t amt = 0;
3611 ResTable_entry header;
3612 memset(&header, 0, sizeof(header));
3613 header.size = htods(sizeof(header));
Andreas Gampe2412f842014-09-30 20:55:57 -07003614 const type ty = mType;
3615 if (ty == TYPE_BAG) {
3616 header.flags |= htods(header.FLAG_COMPLEX);
Adam Lesinski282e1812014-01-23 18:17:42 -08003617 }
Andreas Gampe2412f842014-09-30 20:55:57 -07003618 if (isPublic) {
3619 header.flags |= htods(header.FLAG_PUBLIC);
3620 }
3621 header.key.index = htodl(mNameIndex);
Adam Lesinski282e1812014-01-23 18:17:42 -08003622 if (ty != TYPE_BAG) {
3623 status_t err = data->writeData(&header, sizeof(header));
3624 if (err != NO_ERROR) {
3625 fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3626 return err;
3627 }
3628
3629 const Item& it = mItem;
3630 Res_value par;
3631 memset(&par, 0, sizeof(par));
3632 par.size = htods(it.parsedValue.size);
3633 par.dataType = it.parsedValue.dataType;
3634 par.res0 = it.parsedValue.res0;
3635 par.data = htodl(it.parsedValue.data);
3636 #if 0
3637 printf("Writing item (%s): type=%d, data=0x%x, res0=0x%x\n",
3638 String8(mName).string(), it.parsedValue.dataType,
3639 it.parsedValue.data, par.res0);
3640 #endif
3641 err = data->writeData(&par, it.parsedValue.size);
3642 if (err != NO_ERROR) {
3643 fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3644 return err;
3645 }
3646 amt += it.parsedValue.size;
3647 } else {
3648 size_t N = mBag.size();
3649 size_t i;
3650 // Create correct ordering of items.
3651 KeyedVector<uint32_t, const Item*> items;
3652 for (i=0; i<N; i++) {
3653 const Item& it = mBag.valueAt(i);
3654 items.add(it.bagKeyId, &it);
3655 }
3656 N = items.size();
3657
3658 ResTable_map_entry mapHeader;
3659 memcpy(&mapHeader, &header, sizeof(header));
3660 mapHeader.size = htods(sizeof(mapHeader));
3661 mapHeader.parent.ident = htodl(mParentId);
3662 mapHeader.count = htodl(N);
3663 status_t err = data->writeData(&mapHeader, sizeof(mapHeader));
3664 if (err != NO_ERROR) {
3665 fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3666 return err;
3667 }
3668
3669 for (i=0; i<N; i++) {
3670 const Item& it = *items.valueAt(i);
3671 ResTable_map map;
3672 map.name.ident = htodl(it.bagKeyId);
3673 map.value.size = htods(it.parsedValue.size);
3674 map.value.dataType = it.parsedValue.dataType;
3675 map.value.res0 = it.parsedValue.res0;
3676 map.value.data = htodl(it.parsedValue.data);
3677 err = data->writeData(&map, sizeof(map));
3678 if (err != NO_ERROR) {
3679 fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3680 return err;
3681 }
3682 amt += sizeof(map);
3683 }
3684 }
3685 return amt;
3686}
3687
3688void ResourceTable::ConfigList::appendComment(const String16& comment,
3689 bool onlyIfEmpty)
3690{
3691 if (comment.size() <= 0) {
3692 return;
3693 }
3694 if (onlyIfEmpty && mComment.size() > 0) {
3695 return;
3696 }
3697 if (mComment.size() > 0) {
3698 mComment.append(String16("\n"));
3699 }
3700 mComment.append(comment);
3701}
3702
3703void ResourceTable::ConfigList::appendTypeComment(const String16& comment)
3704{
3705 if (comment.size() <= 0) {
3706 return;
3707 }
3708 if (mTypeComment.size() > 0) {
3709 mTypeComment.append(String16("\n"));
3710 }
3711 mTypeComment.append(comment);
3712}
3713
3714status_t ResourceTable::Type::addPublic(const SourcePos& sourcePos,
3715 const String16& name,
3716 const uint32_t ident)
3717{
3718 #if 0
3719 int32_t entryIdx = Res_GETENTRY(ident);
3720 if (entryIdx < 0) {
3721 sourcePos.error("Public resource %s/%s has an invalid 0 identifier (0x%08x).\n",
3722 String8(mName).string(), String8(name).string(), ident);
3723 return UNKNOWN_ERROR;
3724 }
3725 #endif
3726
3727 int32_t typeIdx = Res_GETTYPE(ident);
3728 if (typeIdx >= 0) {
3729 typeIdx++;
3730 if (mPublicIndex > 0 && mPublicIndex != typeIdx) {
3731 sourcePos.error("Public resource %s/%s has conflicting type codes for its"
3732 " public identifiers (0x%x vs 0x%x).\n",
3733 String8(mName).string(), String8(name).string(),
3734 mPublicIndex, typeIdx);
3735 return UNKNOWN_ERROR;
3736 }
3737 mPublicIndex = typeIdx;
3738 }
3739
3740 if (mFirstPublicSourcePos == NULL) {
3741 mFirstPublicSourcePos = new SourcePos(sourcePos);
3742 }
3743
3744 if (mPublic.indexOfKey(name) < 0) {
3745 mPublic.add(name, Public(sourcePos, String16(), ident));
3746 } else {
3747 Public& p = mPublic.editValueFor(name);
3748 if (p.ident != ident) {
3749 sourcePos.error("Public resource %s/%s has conflicting public identifiers"
3750 " (0x%08x vs 0x%08x).\n"
3751 "%s:%d: Originally defined here.\n",
3752 String8(mName).string(), String8(name).string(), p.ident, ident,
3753 p.sourcePos.file.string(), p.sourcePos.line);
3754 return UNKNOWN_ERROR;
3755 }
3756 }
3757
3758 return NO_ERROR;
3759}
3760
3761void ResourceTable::Type::canAddEntry(const String16& name)
3762{
3763 mCanAddEntries.add(name);
3764}
3765
3766sp<ResourceTable::Entry> ResourceTable::Type::getEntry(const String16& entry,
3767 const SourcePos& sourcePos,
3768 const ResTable_config* config,
3769 bool doSetIndex,
3770 bool overlay,
3771 bool autoAddOverlay)
3772{
3773 int pos = -1;
3774 sp<ConfigList> c = mConfigs.valueFor(entry);
3775 if (c == NULL) {
3776 if (overlay && !autoAddOverlay && mCanAddEntries.indexOf(entry) < 0) {
3777 sourcePos.error("Resource at %s appears in overlay but not"
3778 " in the base package; use <add-resource> to add.\n",
3779 String8(entry).string());
3780 return NULL;
3781 }
3782 c = new ConfigList(entry, sourcePos);
3783 mConfigs.add(entry, c);
3784 pos = (int)mOrderedConfigs.size();
3785 mOrderedConfigs.add(c);
3786 if (doSetIndex) {
3787 c->setEntryIndex(pos);
3788 }
3789 }
3790
3791 ConfigDescription cdesc;
3792 if (config) cdesc = *config;
3793
3794 sp<Entry> e = c->getEntries().valueFor(cdesc);
3795 if (e == NULL) {
Andreas Gampe2412f842014-09-30 20:55:57 -07003796 if (kIsDebug) {
3797 if (config != NULL) {
3798 printf("New entry at %s:%d: imsi:%d/%d lang:%c%c cnt:%c%c "
Adam Lesinski282e1812014-01-23 18:17:42 -08003799 "orien:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
Andreas Gampe2412f842014-09-30 20:55:57 -07003800 "sw%ddp w%ddp h%ddp layout:%d\n",
Adam Lesinski282e1812014-01-23 18:17:42 -08003801 sourcePos.file.string(), sourcePos.line,
3802 config->mcc, config->mnc,
3803 config->language[0] ? config->language[0] : '-',
3804 config->language[1] ? config->language[1] : '-',
3805 config->country[0] ? config->country[0] : '-',
3806 config->country[1] ? config->country[1] : '-',
3807 config->orientation,
3808 config->touchscreen,
3809 config->density,
3810 config->keyboard,
3811 config->inputFlags,
3812 config->navigation,
3813 config->screenWidth,
3814 config->screenHeight,
3815 config->smallestScreenWidthDp,
3816 config->screenWidthDp,
3817 config->screenHeightDp,
Andreas Gampe2412f842014-09-30 20:55:57 -07003818 config->screenLayout);
3819 } else {
3820 printf("New entry at %s:%d: NULL config\n",
3821 sourcePos.file.string(), sourcePos.line);
3822 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003823 }
3824 e = new Entry(entry, sourcePos);
3825 c->addEntry(cdesc, e);
3826 /*
3827 if (doSetIndex) {
3828 if (pos < 0) {
3829 for (pos=0; pos<(int)mOrderedConfigs.size(); pos++) {
3830 if (mOrderedConfigs[pos] == c) {
3831 break;
3832 }
3833 }
3834 if (pos >= (int)mOrderedConfigs.size()) {
3835 sourcePos.error("Internal error: config not found in mOrderedConfigs when adding entry");
3836 return NULL;
3837 }
3838 }
3839 e->setEntryIndex(pos);
3840 }
3841 */
3842 }
3843
3844 mUniqueConfigs.add(cdesc);
3845
3846 return e;
3847}
3848
3849status_t ResourceTable::Type::applyPublicEntryOrder()
3850{
3851 size_t N = mOrderedConfigs.size();
3852 Vector<sp<ConfigList> > origOrder(mOrderedConfigs);
3853 bool hasError = false;
3854
3855 size_t i;
3856 for (i=0; i<N; i++) {
3857 mOrderedConfigs.replaceAt(NULL, i);
3858 }
3859
3860 const size_t NP = mPublic.size();
3861 //printf("Ordering %d configs from %d public defs\n", N, NP);
3862 size_t j;
3863 for (j=0; j<NP; j++) {
3864 const String16& name = mPublic.keyAt(j);
3865 const Public& p = mPublic.valueAt(j);
3866 int32_t idx = Res_GETENTRY(p.ident);
3867 //printf("Looking for entry \"%s\"/\"%s\" (0x%08x) in %d...\n",
3868 // String8(mName).string(), String8(name).string(), p.ident, N);
3869 bool found = false;
3870 for (i=0; i<N; i++) {
3871 sp<ConfigList> e = origOrder.itemAt(i);
3872 //printf("#%d: \"%s\"\n", i, String8(e->getName()).string());
3873 if (e->getName() == name) {
3874 if (idx >= (int32_t)mOrderedConfigs.size()) {
3875 p.sourcePos.error("Public entry identifier 0x%x entry index "
3876 "is larger than available symbols (index %d, total symbols %d).\n",
3877 p.ident, idx, mOrderedConfigs.size());
3878 hasError = true;
3879 } else if (mOrderedConfigs.itemAt(idx) == NULL) {
3880 e->setPublic(true);
3881 e->setPublicSourcePos(p.sourcePos);
3882 mOrderedConfigs.replaceAt(e, idx);
3883 origOrder.removeAt(i);
3884 N--;
3885 found = true;
3886 break;
3887 } else {
3888 sp<ConfigList> oe = mOrderedConfigs.itemAt(idx);
3889
3890 p.sourcePos.error("Multiple entry names declared for public entry"
3891 " identifier 0x%x in type %s (%s vs %s).\n"
3892 "%s:%d: Originally defined here.",
3893 idx+1, String8(mName).string(),
3894 String8(oe->getName()).string(),
3895 String8(name).string(),
3896 oe->getPublicSourcePos().file.string(),
3897 oe->getPublicSourcePos().line);
3898 hasError = true;
3899 }
3900 }
3901 }
3902
3903 if (!found) {
3904 p.sourcePos.error("Public symbol %s/%s declared here is not defined.",
3905 String8(mName).string(), String8(name).string());
3906 hasError = true;
3907 }
3908 }
3909
3910 //printf("Copying back in %d non-public configs, have %d\n", N, origOrder.size());
3911
3912 if (N != origOrder.size()) {
3913 printf("Internal error: remaining private symbol count mismatch\n");
3914 N = origOrder.size();
3915 }
3916
3917 j = 0;
3918 for (i=0; i<N; i++) {
3919 sp<ConfigList> e = origOrder.itemAt(i);
3920 // There will always be enough room for the remaining entries.
3921 while (mOrderedConfigs.itemAt(j) != NULL) {
3922 j++;
3923 }
3924 mOrderedConfigs.replaceAt(e, j);
3925 j++;
3926 }
3927
Andreas Gampe2412f842014-09-30 20:55:57 -07003928 return hasError ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08003929}
3930
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003931ResourceTable::Package::Package(const String16& name, size_t packageId)
3932 : mName(name), mPackageId(packageId),
Adam Lesinski282e1812014-01-23 18:17:42 -08003933 mTypeStringsMapping(0xffffffff),
3934 mKeyStringsMapping(0xffffffff)
3935{
3936}
3937
3938sp<ResourceTable::Type> ResourceTable::Package::getType(const String16& type,
3939 const SourcePos& sourcePos,
3940 bool doSetIndex)
3941{
3942 sp<Type> t = mTypes.valueFor(type);
3943 if (t == NULL) {
3944 t = new Type(type, sourcePos);
3945 mTypes.add(type, t);
3946 mOrderedTypes.add(t);
3947 if (doSetIndex) {
3948 // For some reason the type's index is set to one plus the index
3949 // in the mOrderedTypes list, rather than just the index.
3950 t->setIndex(mOrderedTypes.size());
3951 }
3952 }
3953 return t;
3954}
3955
3956status_t ResourceTable::Package::setTypeStrings(const sp<AaptFile>& data)
3957{
Adam Lesinski282e1812014-01-23 18:17:42 -08003958 status_t err = setStrings(data, &mTypeStrings, &mTypeStringsMapping);
3959 if (err != NO_ERROR) {
3960 fprintf(stderr, "ERROR: Type string data is corrupt!\n");
Adam Lesinski57079512014-07-29 11:51:35 -07003961 return err;
Adam Lesinski282e1812014-01-23 18:17:42 -08003962 }
Adam Lesinski57079512014-07-29 11:51:35 -07003963
3964 // Retain a reference to the new data after we've successfully replaced
3965 // all uses of the old reference (in setStrings() ).
3966 mTypeStringsData = data;
3967 return NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08003968}
3969
3970status_t ResourceTable::Package::setKeyStrings(const sp<AaptFile>& data)
3971{
Adam Lesinski282e1812014-01-23 18:17:42 -08003972 status_t err = setStrings(data, &mKeyStrings, &mKeyStringsMapping);
3973 if (err != NO_ERROR) {
3974 fprintf(stderr, "ERROR: Key string data is corrupt!\n");
Adam Lesinski57079512014-07-29 11:51:35 -07003975 return err;
Adam Lesinski282e1812014-01-23 18:17:42 -08003976 }
Adam Lesinski57079512014-07-29 11:51:35 -07003977
3978 // Retain a reference to the new data after we've successfully replaced
3979 // all uses of the old reference (in setStrings() ).
3980 mKeyStringsData = data;
3981 return NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08003982}
3983
3984status_t ResourceTable::Package::setStrings(const sp<AaptFile>& data,
3985 ResStringPool* strings,
3986 DefaultKeyedVector<String16, uint32_t>* mappings)
3987{
3988 if (data->getData() == NULL) {
3989 return UNKNOWN_ERROR;
3990 }
3991
Adam Lesinski282e1812014-01-23 18:17:42 -08003992 status_t err = strings->setTo(data->getData(), data->getSize());
3993 if (err == NO_ERROR) {
3994 const size_t N = strings->size();
3995 for (size_t i=0; i<N; i++) {
3996 size_t len;
3997 mappings->add(String16(strings->stringAt(i, &len)), i);
3998 }
3999 }
4000 return err;
4001}
4002
4003status_t ResourceTable::Package::applyPublicTypeOrder()
4004{
4005 size_t N = mOrderedTypes.size();
4006 Vector<sp<Type> > origOrder(mOrderedTypes);
4007
4008 size_t i;
4009 for (i=0; i<N; i++) {
4010 mOrderedTypes.replaceAt(NULL, i);
4011 }
4012
4013 for (i=0; i<N; i++) {
4014 sp<Type> t = origOrder.itemAt(i);
4015 int32_t idx = t->getPublicIndex();
4016 if (idx > 0) {
4017 idx--;
4018 while (idx >= (int32_t)mOrderedTypes.size()) {
4019 mOrderedTypes.add();
4020 }
4021 if (mOrderedTypes.itemAt(idx) != NULL) {
4022 sp<Type> ot = mOrderedTypes.itemAt(idx);
4023 t->getFirstPublicSourcePos().error("Multiple type names declared for public type"
4024 " identifier 0x%x (%s vs %s).\n"
4025 "%s:%d: Originally defined here.",
4026 idx, String8(ot->getName()).string(),
4027 String8(t->getName()).string(),
4028 ot->getFirstPublicSourcePos().file.string(),
4029 ot->getFirstPublicSourcePos().line);
4030 return UNKNOWN_ERROR;
4031 }
4032 mOrderedTypes.replaceAt(t, idx);
4033 origOrder.removeAt(i);
4034 i--;
4035 N--;
4036 }
4037 }
4038
4039 size_t j=0;
4040 for (i=0; i<N; i++) {
4041 sp<Type> t = origOrder.itemAt(i);
4042 // There will always be enough room for the remaining types.
4043 while (mOrderedTypes.itemAt(j) != NULL) {
4044 j++;
4045 }
4046 mOrderedTypes.replaceAt(t, j);
4047 }
4048
4049 return NO_ERROR;
4050}
4051
4052sp<ResourceTable::Package> ResourceTable::getPackage(const String16& package)
4053{
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004054 if (package != mAssetsPackage) {
4055 return NULL;
Adam Lesinski282e1812014-01-23 18:17:42 -08004056 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004057 return mPackages.valueFor(package);
Adam Lesinski282e1812014-01-23 18:17:42 -08004058}
4059
4060sp<ResourceTable::Type> ResourceTable::getType(const String16& package,
4061 const String16& type,
4062 const SourcePos& sourcePos,
4063 bool doSetIndex)
4064{
4065 sp<Package> p = getPackage(package);
4066 if (p == NULL) {
4067 return NULL;
4068 }
4069 return p->getType(type, sourcePos, doSetIndex);
4070}
4071
4072sp<ResourceTable::Entry> ResourceTable::getEntry(const String16& package,
4073 const String16& type,
4074 const String16& name,
4075 const SourcePos& sourcePos,
4076 bool overlay,
4077 const ResTable_config* config,
4078 bool doSetIndex)
4079{
4080 sp<Type> t = getType(package, type, sourcePos, doSetIndex);
4081 if (t == NULL) {
4082 return NULL;
4083 }
4084 return t->getEntry(name, sourcePos, config, doSetIndex, overlay, mBundle->getAutoAddOverlay());
4085}
4086
Adam Lesinskie572c012014-09-19 15:10:04 -07004087sp<ResourceTable::ConfigList> ResourceTable::getConfigList(const String16& package,
4088 const String16& type, const String16& name) const
4089{
4090 const size_t packageCount = mOrderedPackages.size();
4091 for (size_t pi = 0; pi < packageCount; pi++) {
4092 const sp<Package>& p = mOrderedPackages[pi];
4093 if (p == NULL || p->getName() != package) {
4094 continue;
4095 }
4096
4097 const Vector<sp<Type> >& types = p->getOrderedTypes();
4098 const size_t typeCount = types.size();
4099 for (size_t ti = 0; ti < typeCount; ti++) {
4100 const sp<Type>& t = types[ti];
4101 if (t == NULL || t->getName() != type) {
4102 continue;
4103 }
4104
4105 const Vector<sp<ConfigList> >& configs = t->getOrderedConfigs();
4106 const size_t configCount = configs.size();
4107 for (size_t ci = 0; ci < configCount; ci++) {
4108 const sp<ConfigList>& cl = configs[ci];
4109 if (cl == NULL || cl->getName() != name) {
4110 continue;
4111 }
4112
4113 return cl;
4114 }
4115 }
4116 }
4117 return NULL;
4118}
4119
Adam Lesinski282e1812014-01-23 18:17:42 -08004120sp<const ResourceTable::Entry> ResourceTable::getEntry(uint32_t resID,
4121 const ResTable_config* config) const
4122{
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004123 size_t pid = Res_GETPACKAGE(resID)+1;
Adam Lesinski282e1812014-01-23 18:17:42 -08004124 const size_t N = mOrderedPackages.size();
Adam Lesinski282e1812014-01-23 18:17:42 -08004125 sp<Package> p;
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004126 for (size_t i = 0; i < N; i++) {
Adam Lesinski282e1812014-01-23 18:17:42 -08004127 sp<Package> check = mOrderedPackages[i];
4128 if (check->getAssignedId() == pid) {
4129 p = check;
4130 break;
4131 }
4132
4133 }
4134 if (p == NULL) {
4135 fprintf(stderr, "warning: Package not found for resource #%08x\n", resID);
4136 return NULL;
4137 }
4138
4139 int tid = Res_GETTYPE(resID);
4140 if (tid < 0 || tid >= (int)p->getOrderedTypes().size()) {
4141 fprintf(stderr, "warning: Type not found for resource #%08x\n", resID);
4142 return NULL;
4143 }
4144 sp<Type> t = p->getOrderedTypes()[tid];
4145
4146 int eid = Res_GETENTRY(resID);
4147 if (eid < 0 || eid >= (int)t->getOrderedConfigs().size()) {
4148 fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
4149 return NULL;
4150 }
4151
4152 sp<ConfigList> c = t->getOrderedConfigs()[eid];
4153 if (c == NULL) {
4154 fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
4155 return NULL;
4156 }
4157
4158 ConfigDescription cdesc;
4159 if (config) cdesc = *config;
4160 sp<Entry> e = c->getEntries().valueFor(cdesc);
4161 if (c == NULL) {
4162 fprintf(stderr, "warning: Entry configuration not found for resource #%08x\n", resID);
4163 return NULL;
4164 }
4165
4166 return e;
4167}
4168
4169const ResourceTable::Item* ResourceTable::getItem(uint32_t resID, uint32_t attrID) const
4170{
4171 sp<const Entry> e = getEntry(resID);
4172 if (e == NULL) {
4173 return NULL;
4174 }
4175
4176 const size_t N = e->getBag().size();
4177 for (size_t i=0; i<N; i++) {
4178 const Item& it = e->getBag().valueAt(i);
4179 if (it.bagKeyId == 0) {
4180 fprintf(stderr, "warning: ID not yet assigned to '%s' in bag '%s'\n",
4181 String8(e->getName()).string(),
4182 String8(e->getBag().keyAt(i)).string());
4183 }
4184 if (it.bagKeyId == attrID) {
4185 return &it;
4186 }
4187 }
4188
4189 return NULL;
4190}
4191
4192bool ResourceTable::getItemValue(
4193 uint32_t resID, uint32_t attrID, Res_value* outValue)
4194{
4195 const Item* item = getItem(resID, attrID);
4196
4197 bool res = false;
4198 if (item != NULL) {
4199 if (item->evaluating) {
4200 sp<const Entry> e = getEntry(resID);
4201 const size_t N = e->getBag().size();
4202 size_t i;
4203 for (i=0; i<N; i++) {
4204 if (&e->getBag().valueAt(i) == item) {
4205 break;
4206 }
4207 }
4208 fprintf(stderr, "warning: Circular reference detected in key '%s' of bag '%s'\n",
4209 String8(e->getName()).string(),
4210 String8(e->getBag().keyAt(i)).string());
4211 return false;
4212 }
4213 item->evaluating = true;
4214 res = stringToValue(outValue, NULL, item->value, false, false, item->bagKeyId);
Andreas Gampe2412f842014-09-30 20:55:57 -07004215 if (kIsDebug) {
Adam Lesinski282e1812014-01-23 18:17:42 -08004216 if (res) {
4217 printf("getItemValue of #%08x[#%08x] (%s): type=#%08x, data=#%08x\n",
4218 resID, attrID, String8(getEntry(resID)->getName()).string(),
4219 outValue->dataType, outValue->data);
4220 } else {
4221 printf("getItemValue of #%08x[#%08x]: failed\n",
4222 resID, attrID);
4223 }
Andreas Gampe2412f842014-09-30 20:55:57 -07004224 }
Adam Lesinski282e1812014-01-23 18:17:42 -08004225 item->evaluating = false;
4226 }
4227 return res;
4228}
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004229
4230/**
4231 * Returns true if the given attribute ID comes from
4232 * a platform version from or after L.
4233 */
4234bool ResourceTable::isAttributeFromL(uint32_t attrId) {
4235 const uint32_t baseAttrId = 0x010103f7;
4236 if ((attrId & 0xffff0000) != (baseAttrId & 0xffff0000)) {
4237 return false;
4238 }
4239
4240 uint32_t specFlags;
4241 if (!mAssets->getIncludedResources().getResourceFlags(attrId, &specFlags)) {
4242 return false;
4243 }
4244
4245 return (specFlags & ResTable_typeSpec::SPEC_PUBLIC) != 0 &&
4246 (attrId & 0x0000ffff) >= (baseAttrId & 0x0000ffff);
4247}
4248
Adam Lesinskie572c012014-09-19 15:10:04 -07004249static bool isMinSdkVersionLOrAbove(const Bundle* bundle) {
4250 if (bundle->getMinSdkVersion() != NULL && strlen(bundle->getMinSdkVersion()) > 0) {
4251 const char firstChar = bundle->getMinSdkVersion()[0];
4252 if (firstChar >= 'L' && firstChar <= 'Z') {
4253 // L is the code-name for the v21 release.
4254 return true;
4255 }
4256
4257 const int minSdk = atoi(bundle->getMinSdkVersion());
Adam Lesinskidcdfe9f2014-11-06 12:54:36 -08004258 if (minSdk >= SDK_LOLLIPOP) {
Adam Lesinskie572c012014-09-19 15:10:04 -07004259 return true;
4260 }
4261 }
4262 return false;
4263}
4264
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004265/**
4266 * Modifies the entries in the resource table to account for compatibility
4267 * issues with older versions of Android.
4268 *
4269 * This primarily handles the issue of private/public attribute clashes
4270 * in framework resources.
4271 *
4272 * AAPT has traditionally assigned resource IDs to public attributes,
4273 * and then followed those public definitions with private attributes.
4274 *
4275 * --- PUBLIC ---
4276 * | 0x01010234 | attr/color
4277 * | 0x01010235 | attr/background
4278 *
4279 * --- PRIVATE ---
4280 * | 0x01010236 | attr/secret
4281 * | 0x01010237 | attr/shhh
4282 *
4283 * Each release, when attributes are added, they take the place of the private
4284 * attributes and the private attributes are shifted down again.
4285 *
4286 * --- PUBLIC ---
4287 * | 0x01010234 | attr/color
4288 * | 0x01010235 | attr/background
4289 * | 0x01010236 | attr/shinyNewAttr
4290 * | 0x01010237 | attr/highlyValuedFeature
4291 *
4292 * --- PRIVATE ---
4293 * | 0x01010238 | attr/secret
4294 * | 0x01010239 | attr/shhh
4295 *
4296 * Platform code may look for private attributes set in a theme. If an app
4297 * compiled against a newer version of the platform uses a new public
4298 * attribute that happens to have the same ID as the private attribute
4299 * the older platform is expecting, then the behavior is undefined.
4300 *
4301 * We get around this by detecting any newly defined attributes (in L),
4302 * copy the resource into a -v21 qualified resource, and delete the
4303 * attribute from the original resource. This ensures that older platforms
4304 * don't see the new attribute, but when running on L+ platforms, the
4305 * attribute will be respected.
4306 */
4307status_t ResourceTable::modifyForCompat(const Bundle* bundle) {
Adam Lesinskie572c012014-09-19 15:10:04 -07004308 if (isMinSdkVersionLOrAbove(bundle)) {
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004309 // If this app will only ever run on L+ devices,
4310 // we don't need to do any compatibility work.
Adam Lesinskie572c012014-09-19 15:10:04 -07004311 return NO_ERROR;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004312 }
4313
4314 const String16 attr16("attr");
4315
4316 const size_t packageCount = mOrderedPackages.size();
4317 for (size_t pi = 0; pi < packageCount; pi++) {
4318 sp<Package> p = mOrderedPackages.itemAt(pi);
4319 if (p == NULL || p->getTypes().size() == 0) {
4320 // Empty, skip!
4321 continue;
4322 }
4323
4324 const size_t typeCount = p->getOrderedTypes().size();
4325 for (size_t ti = 0; ti < typeCount; ti++) {
4326 sp<Type> t = p->getOrderedTypes().itemAt(ti);
4327 if (t == NULL) {
4328 continue;
4329 }
4330
4331 const size_t configCount = t->getOrderedConfigs().size();
4332 for (size_t ci = 0; ci < configCount; ci++) {
4333 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
4334 if (c == NULL) {
4335 continue;
4336 }
4337
4338 Vector<key_value_pair_t<ConfigDescription, sp<Entry> > > entriesToAdd;
4339 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& entries =
4340 c->getEntries();
4341 const size_t entryCount = entries.size();
4342 for (size_t ei = 0; ei < entryCount; ei++) {
4343 sp<Entry> e = entries.valueAt(ei);
4344 if (e == NULL || e->getType() != Entry::TYPE_BAG) {
4345 continue;
4346 }
4347
4348 const ConfigDescription& config = entries.keyAt(ei);
Adam Lesinskidcdfe9f2014-11-06 12:54:36 -08004349 if (config.sdkVersion >= SDK_LOLLIPOP) {
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004350 // We don't need to do anything if the resource is
4351 // already qualified for version 21 or higher.
4352 continue;
4353 }
4354
4355 Vector<String16> attributesToRemove;
4356 const KeyedVector<String16, Item>& bag = e->getBag();
4357 const size_t bagCount = bag.size();
4358 for (size_t bi = 0; bi < bagCount; bi++) {
4359 const Item& item = bag.valueAt(bi);
4360 const uint32_t attrId = getResId(bag.keyAt(bi), &attr16);
4361 if (isAttributeFromL(attrId)) {
4362 attributesToRemove.add(bag.keyAt(bi));
4363 }
4364 }
4365
4366 if (attributesToRemove.isEmpty()) {
4367 continue;
4368 }
4369
4370 // Duplicate the entry under the same configuration
Adam Lesinskidcdfe9f2014-11-06 12:54:36 -08004371 // but with sdkVersion == SDK_LOLLIPOP.
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004372 ConfigDescription newConfig(config);
Adam Lesinskidcdfe9f2014-11-06 12:54:36 -08004373 newConfig.sdkVersion = SDK_LOLLIPOP;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004374 entriesToAdd.add(key_value_pair_t<ConfigDescription, sp<Entry> >(
4375 newConfig, new Entry(*e)));
4376
4377 // Remove the attribute from the original.
4378 for (size_t i = 0; i < attributesToRemove.size(); i++) {
4379 e->removeFromBag(attributesToRemove[i]);
4380 }
4381 }
4382
4383 const size_t entriesToAddCount = entriesToAdd.size();
4384 for (size_t i = 0; i < entriesToAddCount; i++) {
4385 if (entries.indexOfKey(entriesToAdd[i].key) >= 0) {
4386 // An entry already exists for this config.
4387 // That means that any attributes that were
4388 // defined in L in the original bag will be overriden
4389 // anyways on L devices, so we do nothing.
4390 continue;
4391 }
4392
Adam Lesinskif15de2e2014-10-03 14:57:28 -07004393 if (bundle->getVerbose()) {
4394 entriesToAdd[i].value->getPos()
4395 .printf("using v%d attributes; synthesizing resource %s:%s/%s for configuration %s.",
Adam Lesinskidcdfe9f2014-11-06 12:54:36 -08004396 SDK_LOLLIPOP,
Adam Lesinskif15de2e2014-10-03 14:57:28 -07004397 String8(p->getName()).string(),
4398 String8(t->getName()).string(),
4399 String8(entriesToAdd[i].value->getName()).string(),
4400 entriesToAdd[i].key.toString().string());
4401 }
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004402
Adam Lesinski978ab9d2014-09-24 19:02:52 -07004403 sp<Entry> newEntry = t->getEntry(c->getName(),
4404 entriesToAdd[i].value->getPos(),
4405 &entriesToAdd[i].key);
4406
4407 *newEntry = *entriesToAdd[i].value;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004408 }
4409 }
4410 }
4411 }
4412 return NO_ERROR;
4413}
Adam Lesinskie572c012014-09-19 15:10:04 -07004414
4415status_t ResourceTable::modifyForCompat(const Bundle* bundle,
4416 const String16& resourceName,
4417 const sp<AaptFile>& target,
4418 const sp<XMLNode>& root) {
4419 if (isMinSdkVersionLOrAbove(bundle)) {
4420 return NO_ERROR;
4421 }
4422
Adam Lesinskidcdfe9f2014-11-06 12:54:36 -08004423 if (target->getResourceType() == "" || target->getGroupEntry().toParams().sdkVersion >= SDK_LOLLIPOP) {
Adam Lesinskie572c012014-09-19 15:10:04 -07004424 // Skip resources that have no type (AndroidManifest.xml) or are already version qualified with v21
4425 // or higher.
4426 return NO_ERROR;
4427 }
4428
4429 Vector<key_value_pair_t<sp<XMLNode>, size_t> > attrsToRemove;
4430
4431 Vector<sp<XMLNode> > nodesToVisit;
4432 nodesToVisit.push(root);
4433 while (!nodesToVisit.isEmpty()) {
4434 sp<XMLNode> node = nodesToVisit.top();
4435 nodesToVisit.pop();
4436
4437 const Vector<XMLNode::attribute_entry>& attrs = node->getAttributes();
4438 const size_t attrCount = attrs.size();
4439 for (size_t i = 0; i < attrCount; i++) {
4440 const XMLNode::attribute_entry& attr = attrs[i];
4441 if (isAttributeFromL(attr.nameResId)) {
4442 attrsToRemove.add(key_value_pair_t<sp<XMLNode>, size_t>(node, i));
4443 }
4444 }
4445
4446 // Schedule a visit to the children.
4447 const Vector<sp<XMLNode> >& children = node->getChildren();
4448 const size_t childCount = children.size();
4449 for (size_t i = 0; i < childCount; i++) {
4450 nodesToVisit.push(children[i]);
4451 }
4452 }
4453
4454 if (attrsToRemove.isEmpty()) {
4455 return NO_ERROR;
4456 }
4457
4458 ConfigDescription newConfig(target->getGroupEntry().toParams());
Adam Lesinskidcdfe9f2014-11-06 12:54:36 -08004459 newConfig.sdkVersion = SDK_LOLLIPOP;
Adam Lesinskie572c012014-09-19 15:10:04 -07004460
4461 // Look to see if we already have an overriding v21 configuration.
4462 sp<ConfigList> cl = getConfigList(String16(mAssets->getPackage()),
4463 String16(target->getResourceType()), resourceName);
Adam Lesinskiaff7c242014-10-20 12:15:25 -07004464 //if (cl == NULL) {
4465 // fprintf(stderr, "fuuuuck\n");
4466 //}
Adam Lesinskie572c012014-09-19 15:10:04 -07004467 if (cl->getEntries().indexOfKey(newConfig) < 0) {
4468 // We don't have an overriding entry for v21, so we must duplicate this one.
4469 sp<XMLNode> newRoot = root->clone();
4470 sp<AaptFile> newFile = new AaptFile(target->getSourceFile(),
4471 AaptGroupEntry(newConfig), target->getResourceType());
4472 String8 resPath = String8::format("res/%s/%s",
4473 newFile->getGroupEntry().toDirName(target->getResourceType()).string(),
Adam Lesinskiaff7c242014-10-20 12:15:25 -07004474 target->getSourceFile().getPathLeaf().string());
Adam Lesinskie572c012014-09-19 15:10:04 -07004475 resPath.convertToResPath();
4476
4477 // Add a resource table entry.
Adam Lesinskif15de2e2014-10-03 14:57:28 -07004478 if (bundle->getVerbose()) {
4479 SourcePos(target->getSourceFile(), -1).printf(
4480 "using v%d attributes; synthesizing resource %s:%s/%s for configuration %s.",
Adam Lesinskidcdfe9f2014-11-06 12:54:36 -08004481 SDK_LOLLIPOP,
Adam Lesinskif15de2e2014-10-03 14:57:28 -07004482 mAssets->getPackage().string(),
4483 newFile->getResourceType().string(),
4484 String8(resourceName).string(),
4485 newConfig.toString().string());
4486 }
Adam Lesinskie572c012014-09-19 15:10:04 -07004487
4488 addEntry(SourcePos(),
4489 String16(mAssets->getPackage()),
4490 String16(target->getResourceType()),
4491 resourceName,
4492 String16(resPath),
4493 NULL,
4494 &newConfig);
4495
4496 // Schedule this to be compiled.
4497 CompileResourceWorkItem item;
4498 item.resourceName = resourceName;
4499 item.resPath = resPath;
4500 item.file = newFile;
4501 mWorkQueue.push(item);
4502 }
4503
4504 const size_t removeCount = attrsToRemove.size();
4505 for (size_t i = 0; i < removeCount; i++) {
4506 sp<XMLNode> node = attrsToRemove[i].key;
4507 size_t attrIndex = attrsToRemove[i].value;
4508 const XMLNode::attribute_entry& ae = node->getAttributes()[attrIndex];
Adam Lesinskif15de2e2014-10-03 14:57:28 -07004509 if (bundle->getVerbose()) {
4510 SourcePos(node->getFilename(), node->getStartLineNumber()).printf(
4511 "removing attribute %s%s%s from <%s>",
4512 String8(ae.ns).string(),
4513 (ae.ns.size() == 0 ? "" : ":"),
4514 String8(ae.name).string(),
4515 String8(node->getElementName()).string());
4516 }
Adam Lesinskie572c012014-09-19 15:10:04 -07004517 node->removeAttribute(attrIndex);
4518 }
4519
4520 return NO_ERROR;
4521}
Adam Lesinskide7de472014-11-03 12:03:08 -08004522
4523void ResourceTable::getDensityVaryingResources(KeyedVector<Symbol, Vector<SymbolDefinition> >& resources) {
4524 const ConfigDescription nullConfig;
4525
4526 const size_t packageCount = mOrderedPackages.size();
4527 for (size_t p = 0; p < packageCount; p++) {
4528 const Vector<sp<Type> >& types = mOrderedPackages[p]->getOrderedTypes();
4529 const size_t typeCount = types.size();
4530 for (size_t t = 0; t < typeCount; t++) {
4531 const Vector<sp<ConfigList> >& configs = types[t]->getOrderedConfigs();
4532 const size_t configCount = configs.size();
4533 for (size_t c = 0; c < configCount; c++) {
4534 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& configEntries = configs[c]->getEntries();
4535 const size_t configEntryCount = configEntries.size();
4536 for (size_t ce = 0; ce < configEntryCount; ce++) {
4537 const ConfigDescription& config = configEntries.keyAt(ce);
4538 if (AaptConfig::isDensityOnly(config)) {
4539 // This configuration only varies with regards to density.
4540 const Symbol symbol(mOrderedPackages[p]->getName(),
4541 types[t]->getName(),
4542 configs[c]->getName(),
4543 getResId(mOrderedPackages[p], types[t], configs[c]->getEntryIndex()));
4544
4545 const sp<Entry>& entry = configEntries.valueAt(ce);
4546 AaptUtil::appendValue(resources, symbol, SymbolDefinition(symbol, config, entry->getPos()));
4547 }
4548 }
4549 }
4550 }
4551 }
4552}