blob: 8341de6c4ba5fe5ae7f295b7f51d37315159a91e [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
9#include "XMLNode.h"
10#include "ResourceFilter.h"
11#include "ResourceIdCache.h"
12
13#include <androidfw/ResourceTypes.h>
14#include <utils/ByteOrder.h>
15#include <stdarg.h>
16
17#define NOISY(x) //x
18
19status_t compileXmlFile(const sp<AaptAssets>& assets,
20 const sp<AaptFile>& target,
21 ResourceTable* table,
22 int options)
23{
24 sp<XMLNode> root = XMLNode::parse(target);
25 if (root == NULL) {
26 return UNKNOWN_ERROR;
27 }
Anton Krumina2ef5c02014-03-12 14:46:44 -070028
Adam Lesinski282e1812014-01-23 18:17:42 -080029 return compileXmlFile(assets, root, target, table, options);
30}
31
32status_t compileXmlFile(const sp<AaptAssets>& assets,
33 const sp<AaptFile>& target,
34 const sp<AaptFile>& outTarget,
35 ResourceTable* table,
36 int options)
37{
38 sp<XMLNode> root = XMLNode::parse(target);
39 if (root == NULL) {
40 return UNKNOWN_ERROR;
41 }
42
43 return compileXmlFile(assets, root, outTarget, table, options);
44}
45
46status_t compileXmlFile(const sp<AaptAssets>& assets,
47 const sp<XMLNode>& root,
48 const sp<AaptFile>& target,
49 ResourceTable* table,
50 int options)
51{
52 if ((options&XML_COMPILE_STRIP_WHITESPACE) != 0) {
53 root->removeWhitespace(true, NULL);
54 } else if ((options&XML_COMPILE_COMPACT_WHITESPACE) != 0) {
55 root->removeWhitespace(false, NULL);
56 }
57
58 if ((options&XML_COMPILE_UTF8) != 0) {
59 root->setUTF8(true);
60 }
61
62 bool hasErrors = false;
63
64 if ((options&XML_COMPILE_ASSIGN_ATTRIBUTE_IDS) != 0) {
65 status_t err = root->assignResourceIds(assets, table);
66 if (err != NO_ERROR) {
67 hasErrors = true;
68 }
69 }
70
71 status_t err = root->parseValues(assets, table);
72 if (err != NO_ERROR) {
73 hasErrors = true;
74 }
75
76 if (hasErrors) {
77 return UNKNOWN_ERROR;
78 }
79
80 NOISY(printf("Input XML Resource:\n"));
81 NOISY(root->print());
82 err = root->flatten(target,
83 (options&XML_COMPILE_STRIP_COMMENTS) != 0,
84 (options&XML_COMPILE_STRIP_RAW_VALUES) != 0);
85 if (err != NO_ERROR) {
86 return err;
87 }
88
89 NOISY(printf("Output XML Resource:\n"));
90 NOISY(ResXMLTree tree;
91 tree.setTo(target->getData(), target->getSize());
92 printXMLBlock(&tree));
93
94 target->setCompressionMethod(ZipEntry::kCompressDeflated);
95
96 return err;
97}
98
99#undef NOISY
100#define NOISY(x) //x
101
102struct flag_entry
103{
104 const char16_t* name;
105 size_t nameLen;
106 uint32_t value;
107 const char* description;
108};
109
110static const char16_t referenceArray[] =
111 { 'r', 'e', 'f', 'e', 'r', 'e', 'n', 'c', 'e' };
112static const char16_t stringArray[] =
113 { 's', 't', 'r', 'i', 'n', 'g' };
114static const char16_t integerArray[] =
115 { 'i', 'n', 't', 'e', 'g', 'e', 'r' };
116static const char16_t booleanArray[] =
117 { 'b', 'o', 'o', 'l', 'e', 'a', 'n' };
118static const char16_t colorArray[] =
119 { 'c', 'o', 'l', 'o', 'r' };
120static const char16_t floatArray[] =
121 { 'f', 'l', 'o', 'a', 't' };
122static const char16_t dimensionArray[] =
123 { 'd', 'i', 'm', 'e', 'n', 's', 'i', 'o', 'n' };
124static const char16_t fractionArray[] =
125 { 'f', 'r', 'a', 'c', 't', 'i', 'o', 'n' };
126static const char16_t enumArray[] =
127 { 'e', 'n', 'u', 'm' };
128static const char16_t flagsArray[] =
129 { 'f', 'l', 'a', 'g', 's' };
130
131static const flag_entry gFormatFlags[] = {
132 { referenceArray, sizeof(referenceArray)/2, ResTable_map::TYPE_REFERENCE,
133 "a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\n"
134 "or to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\"."},
135 { stringArray, sizeof(stringArray)/2, ResTable_map::TYPE_STRING,
136 "a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character." },
137 { integerArray, sizeof(integerArray)/2, ResTable_map::TYPE_INTEGER,
138 "an integer value, such as \"<code>100</code>\"." },
139 { booleanArray, sizeof(booleanArray)/2, ResTable_map::TYPE_BOOLEAN,
140 "a boolean value, either \"<code>true</code>\" or \"<code>false</code>\"." },
141 { colorArray, sizeof(colorArray)/2, ResTable_map::TYPE_COLOR,
142 "a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n"
143 "\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\"." },
144 { floatArray, sizeof(floatArray)/2, ResTable_map::TYPE_FLOAT,
145 "a floating point value, such as \"<code>1.2</code>\"."},
146 { dimensionArray, sizeof(dimensionArray)/2, ResTable_map::TYPE_DIMENSION,
147 "a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\n"
148 "Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\n"
149 "in (inches), mm (millimeters)." },
150 { fractionArray, sizeof(fractionArray)/2, ResTable_map::TYPE_FRACTION,
151 "a fractional value, which is a floating point number appended with either % or %p, such as \"<code>14.5%</code>\".\n"
152 "The % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to\n"
153 "some parent container." },
154 { enumArray, sizeof(enumArray)/2, ResTable_map::TYPE_ENUM, NULL },
155 { flagsArray, sizeof(flagsArray)/2, ResTable_map::TYPE_FLAGS, NULL },
156 { NULL, 0, 0, NULL }
157};
158
159static const char16_t suggestedArray[] = { 's', 'u', 'g', 'g', 'e', 's', 't', 'e', 'd' };
160
161static const flag_entry l10nRequiredFlags[] = {
162 { suggestedArray, sizeof(suggestedArray)/2, ResTable_map::L10N_SUGGESTED, NULL },
163 { NULL, 0, 0, NULL }
164};
165
166static const char16_t nulStr[] = { 0 };
167
168static uint32_t parse_flags(const char16_t* str, size_t len,
169 const flag_entry* flags, bool* outError = NULL)
170{
171 while (len > 0 && isspace(*str)) {
172 str++;
173 len--;
174 }
175 while (len > 0 && isspace(str[len-1])) {
176 len--;
177 }
178
179 const char16_t* const end = str + len;
180 uint32_t value = 0;
181
182 while (str < end) {
183 const char16_t* div = str;
184 while (div < end && *div != '|') {
185 div++;
186 }
187
188 const flag_entry* cur = flags;
189 while (cur->name) {
190 if (strzcmp16(cur->name, cur->nameLen, str, div-str) == 0) {
191 value |= cur->value;
192 break;
193 }
194 cur++;
195 }
196
197 if (!cur->name) {
198 if (outError) *outError = true;
199 return 0;
200 }
201
202 str = div < end ? div+1 : div;
203 }
204
205 if (outError) *outError = false;
206 return value;
207}
208
209static String16 mayOrMust(int type, int flags)
210{
211 if ((type&(~flags)) == 0) {
212 return String16("<p>Must");
213 }
214
215 return String16("<p>May");
216}
217
218static void appendTypeInfo(ResourceTable* outTable, const String16& pkg,
219 const String16& typeName, const String16& ident, int type,
220 const flag_entry* flags)
221{
222 bool hadType = false;
223 while (flags->name) {
224 if ((type&flags->value) != 0 && flags->description != NULL) {
225 String16 fullMsg(mayOrMust(type, flags->value));
226 fullMsg.append(String16(" be "));
227 fullMsg.append(String16(flags->description));
228 outTable->appendTypeComment(pkg, typeName, ident, fullMsg);
229 hadType = true;
230 }
231 flags++;
232 }
233 if (hadType && (type&ResTable_map::TYPE_REFERENCE) == 0) {
234 outTable->appendTypeComment(pkg, typeName, ident,
235 String16("<p>This may also be a reference to a resource (in the form\n"
236 "\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\n"
237 "theme attribute (in the form\n"
238 "\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\n"
239 "containing a value of this type."));
240 }
241}
242
243struct PendingAttribute
244{
245 const String16 myPackage;
246 const SourcePos sourcePos;
247 const bool appendComment;
248 int32_t type;
249 String16 ident;
250 String16 comment;
251 bool hasErrors;
252 bool added;
253
254 PendingAttribute(String16 _package, const sp<AaptFile>& in,
255 ResXMLTree& block, bool _appendComment)
256 : myPackage(_package)
257 , sourcePos(in->getPrintableSource(), block.getLineNumber())
258 , appendComment(_appendComment)
259 , type(ResTable_map::TYPE_ANY)
260 , hasErrors(false)
261 , added(false)
262 {
263 }
264
265 status_t createIfNeeded(ResourceTable* outTable)
266 {
267 if (added || hasErrors) {
268 return NO_ERROR;
269 }
270 added = true;
271
272 String16 attr16("attr");
273
274 if (outTable->hasBagOrEntry(myPackage, attr16, ident)) {
275 sourcePos.error("Attribute \"%s\" has already been defined\n",
276 String8(ident).string());
277 hasErrors = true;
278 return UNKNOWN_ERROR;
279 }
280
281 char numberStr[16];
282 sprintf(numberStr, "%d", type);
283 status_t err = outTable->addBag(sourcePos, myPackage,
284 attr16, ident, String16(""),
285 String16("^type"),
286 String16(numberStr), NULL, NULL);
287 if (err != NO_ERROR) {
288 hasErrors = true;
289 return err;
290 }
291 outTable->appendComment(myPackage, attr16, ident, comment, appendComment);
292 //printf("Attribute %s comment: %s\n", String8(ident).string(),
293 // String8(comment).string());
294 return err;
295 }
296};
297
298static status_t compileAttribute(const sp<AaptFile>& in,
299 ResXMLTree& block,
300 const String16& myPackage,
301 ResourceTable* outTable,
302 String16* outIdent = NULL,
303 bool inStyleable = false)
304{
305 PendingAttribute attr(myPackage, in, block, inStyleable);
306
307 const String16 attr16("attr");
308 const String16 id16("id");
309
310 // Attribute type constants.
311 const String16 enum16("enum");
312 const String16 flag16("flag");
313
314 ResXMLTree::event_code_t code;
315 size_t len;
316 status_t err;
317
318 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
319 if (identIdx >= 0) {
320 attr.ident = String16(block.getAttributeStringValue(identIdx, &len));
321 if (outIdent) {
322 *outIdent = attr.ident;
323 }
324 } else {
325 attr.sourcePos.error("A 'name' attribute is required for <attr>\n");
326 attr.hasErrors = true;
327 }
328
329 attr.comment = String16(
330 block.getComment(&len) ? block.getComment(&len) : nulStr);
331
332 ssize_t typeIdx = block.indexOfAttribute(NULL, "format");
333 if (typeIdx >= 0) {
334 String16 typeStr = String16(block.getAttributeStringValue(typeIdx, &len));
335 attr.type = parse_flags(typeStr.string(), typeStr.size(), gFormatFlags);
336 if (attr.type == 0) {
337 attr.sourcePos.error("Tag <attr> 'format' attribute value \"%s\" not valid\n",
338 String8(typeStr).string());
339 attr.hasErrors = true;
340 }
341 attr.createIfNeeded(outTable);
342 } else if (!inStyleable) {
343 // Attribute definitions outside of styleables always define the
344 // attribute as a generic value.
345 attr.createIfNeeded(outTable);
346 }
347
348 //printf("Attribute %s: type=0x%08x\n", String8(attr.ident).string(), attr.type);
349
350 ssize_t minIdx = block.indexOfAttribute(NULL, "min");
351 if (minIdx >= 0) {
352 String16 val = String16(block.getAttributeStringValue(minIdx, &len));
353 if (!ResTable::stringToInt(val.string(), val.size(), NULL)) {
354 attr.sourcePos.error("Tag <attr> 'min' attribute must be a number, not \"%s\"\n",
355 String8(val).string());
356 attr.hasErrors = true;
357 }
358 attr.createIfNeeded(outTable);
359 if (!attr.hasErrors) {
360 err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
361 String16(""), String16("^min"), String16(val), NULL, NULL);
362 if (err != NO_ERROR) {
363 attr.hasErrors = true;
364 }
365 }
366 }
367
368 ssize_t maxIdx = block.indexOfAttribute(NULL, "max");
369 if (maxIdx >= 0) {
370 String16 val = String16(block.getAttributeStringValue(maxIdx, &len));
371 if (!ResTable::stringToInt(val.string(), val.size(), NULL)) {
372 attr.sourcePos.error("Tag <attr> 'max' attribute must be a number, not \"%s\"\n",
373 String8(val).string());
374 attr.hasErrors = true;
375 }
376 attr.createIfNeeded(outTable);
377 if (!attr.hasErrors) {
378 err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
379 String16(""), String16("^max"), String16(val), NULL, NULL);
380 attr.hasErrors = true;
381 }
382 }
383
384 if ((minIdx >= 0 || maxIdx >= 0) && (attr.type&ResTable_map::TYPE_INTEGER) == 0) {
385 attr.sourcePos.error("Tag <attr> must have format=integer attribute if using max or min\n");
386 attr.hasErrors = true;
387 }
388
389 ssize_t l10nIdx = block.indexOfAttribute(NULL, "localization");
390 if (l10nIdx >= 0) {
391 const uint16_t* str = block.getAttributeStringValue(l10nIdx, &len);
392 bool error;
393 uint32_t l10n_required = parse_flags(str, len, l10nRequiredFlags, &error);
394 if (error) {
395 attr.sourcePos.error("Tag <attr> 'localization' attribute value \"%s\" not valid\n",
396 String8(str).string());
397 attr.hasErrors = true;
398 }
399 attr.createIfNeeded(outTable);
400 if (!attr.hasErrors) {
401 char buf[11];
402 sprintf(buf, "%d", l10n_required);
403 err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
404 String16(""), String16("^l10n"), String16(buf), NULL, NULL);
405 if (err != NO_ERROR) {
406 attr.hasErrors = true;
407 }
408 }
409 }
410
411 String16 enumOrFlagsComment;
412
413 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
414 if (code == ResXMLTree::START_TAG) {
415 uint32_t localType = 0;
416 if (strcmp16(block.getElementName(&len), enum16.string()) == 0) {
417 localType = ResTable_map::TYPE_ENUM;
418 } else if (strcmp16(block.getElementName(&len), flag16.string()) == 0) {
419 localType = ResTable_map::TYPE_FLAGS;
420 } else {
421 SourcePos(in->getPrintableSource(), block.getLineNumber())
422 .error("Tag <%s> can not appear inside <attr>, only <enum> or <flag>\n",
423 String8(block.getElementName(&len)).string());
424 return UNKNOWN_ERROR;
425 }
426
427 attr.createIfNeeded(outTable);
428
429 if (attr.type == ResTable_map::TYPE_ANY) {
430 // No type was explicitly stated, so supplying enum tags
431 // implicitly creates an enum or flag.
432 attr.type = 0;
433 }
434
435 if ((attr.type&(ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS)) == 0) {
436 // Wasn't originally specified as an enum, so update its type.
437 attr.type |= localType;
438 if (!attr.hasErrors) {
439 char numberStr[16];
440 sprintf(numberStr, "%d", attr.type);
441 err = outTable->addBag(SourcePos(in->getPrintableSource(), block.getLineNumber()),
442 myPackage, attr16, attr.ident, String16(""),
443 String16("^type"), String16(numberStr), NULL, NULL, true);
444 if (err != NO_ERROR) {
445 attr.hasErrors = true;
446 }
447 }
448 } else if ((uint32_t)(attr.type&(ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS)) != localType) {
449 if (localType == ResTable_map::TYPE_ENUM) {
450 SourcePos(in->getPrintableSource(), block.getLineNumber())
451 .error("<enum> attribute can not be used inside a flags format\n");
452 attr.hasErrors = true;
453 } else {
454 SourcePos(in->getPrintableSource(), block.getLineNumber())
455 .error("<flag> attribute can not be used inside a enum format\n");
456 attr.hasErrors = true;
457 }
458 }
459
460 String16 itemIdent;
461 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "name");
462 if (itemIdentIdx >= 0) {
463 itemIdent = String16(block.getAttributeStringValue(itemIdentIdx, &len));
464 } else {
465 SourcePos(in->getPrintableSource(), block.getLineNumber())
466 .error("A 'name' attribute is required for <enum> or <flag>\n");
467 attr.hasErrors = true;
468 }
469
470 String16 value;
471 ssize_t valueIdx = block.indexOfAttribute(NULL, "value");
472 if (valueIdx >= 0) {
473 value = String16(block.getAttributeStringValue(valueIdx, &len));
474 } else {
475 SourcePos(in->getPrintableSource(), block.getLineNumber())
476 .error("A 'value' attribute is required for <enum> or <flag>\n");
477 attr.hasErrors = true;
478 }
479 if (!attr.hasErrors && !ResTable::stringToInt(value.string(), value.size(), NULL)) {
480 SourcePos(in->getPrintableSource(), block.getLineNumber())
481 .error("Tag <enum> or <flag> 'value' attribute must be a number,"
482 " not \"%s\"\n",
483 String8(value).string());
484 attr.hasErrors = true;
485 }
486
Adam Lesinski282e1812014-01-23 18:17:42 -0800487 if (!attr.hasErrors) {
488 if (enumOrFlagsComment.size() == 0) {
489 enumOrFlagsComment.append(mayOrMust(attr.type,
490 ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS));
491 enumOrFlagsComment.append((attr.type&ResTable_map::TYPE_ENUM)
492 ? String16(" be one of the following constant values.")
493 : String16(" be one or more (separated by '|') of the following constant values."));
494 enumOrFlagsComment.append(String16("</p>\n<table>\n"
495 "<colgroup align=\"left\" />\n"
496 "<colgroup align=\"left\" />\n"
497 "<colgroup align=\"left\" />\n"
498 "<tr><th>Constant</th><th>Value</th><th>Description</th></tr>"));
499 }
500
501 enumOrFlagsComment.append(String16("\n<tr><td><code>"));
502 enumOrFlagsComment.append(itemIdent);
503 enumOrFlagsComment.append(String16("</code></td><td>"));
504 enumOrFlagsComment.append(value);
505 enumOrFlagsComment.append(String16("</td><td>"));
506 if (block.getComment(&len)) {
507 enumOrFlagsComment.append(String16(block.getComment(&len)));
508 }
509 enumOrFlagsComment.append(String16("</td></tr>"));
510
511 err = outTable->addBag(SourcePos(in->getPrintableSource(), block.getLineNumber()),
512 myPackage,
513 attr16, attr.ident, String16(""),
514 itemIdent, value, NULL, NULL, false, true);
515 if (err != NO_ERROR) {
516 attr.hasErrors = true;
517 }
518 }
519 } else if (code == ResXMLTree::END_TAG) {
520 if (strcmp16(block.getElementName(&len), attr16.string()) == 0) {
521 break;
522 }
523 if ((attr.type&ResTable_map::TYPE_ENUM) != 0) {
524 if (strcmp16(block.getElementName(&len), enum16.string()) != 0) {
525 SourcePos(in->getPrintableSource(), block.getLineNumber())
526 .error("Found tag </%s> where </enum> is expected\n",
527 String8(block.getElementName(&len)).string());
528 return UNKNOWN_ERROR;
529 }
530 } else {
531 if (strcmp16(block.getElementName(&len), flag16.string()) != 0) {
532 SourcePos(in->getPrintableSource(), block.getLineNumber())
533 .error("Found tag </%s> where </flag> is expected\n",
534 String8(block.getElementName(&len)).string());
535 return UNKNOWN_ERROR;
536 }
537 }
538 }
539 }
540
541 if (!attr.hasErrors && attr.added) {
542 appendTypeInfo(outTable, myPackage, attr16, attr.ident, attr.type, gFormatFlags);
543 }
544
545 if (!attr.hasErrors && enumOrFlagsComment.size() > 0) {
546 enumOrFlagsComment.append(String16("\n</table>"));
547 outTable->appendTypeComment(myPackage, attr16, attr.ident, enumOrFlagsComment);
548 }
549
550
551 return NO_ERROR;
552}
553
554bool localeIsDefined(const ResTable_config& config)
555{
556 return config.locale == 0;
557}
558
559status_t parseAndAddBag(Bundle* bundle,
560 const sp<AaptFile>& in,
561 ResXMLTree* block,
562 const ResTable_config& config,
563 const String16& myPackage,
564 const String16& curType,
565 const String16& ident,
566 const String16& parentIdent,
567 const String16& itemIdent,
568 int32_t curFormat,
569 bool isFormatted,
570 const String16& product,
Anton Krumina2ef5c02014-03-12 14:46:44 -0700571 PseudolocalizationMethod pseudolocalize,
Adam Lesinski282e1812014-01-23 18:17:42 -0800572 const bool overwrite,
573 ResourceTable* outTable)
574{
575 status_t err;
576 const String16 item16("item");
Anton Krumina2ef5c02014-03-12 14:46:44 -0700577
Adam Lesinski282e1812014-01-23 18:17:42 -0800578 String16 str;
579 Vector<StringPool::entry_style_span> spans;
580 err = parseStyledString(bundle, in->getPrintableSource().string(),
581 block, item16, &str, &spans, isFormatted,
582 pseudolocalize);
583 if (err != NO_ERROR) {
584 return err;
585 }
586
587 NOISY(printf("Adding resource bag entry l=%c%c c=%c%c orien=%d d=%d "
588 " pid=%s, bag=%s, id=%s: %s\n",
589 config.language[0], config.language[1],
590 config.country[0], config.country[1],
591 config.orientation, config.density,
592 String8(parentIdent).string(),
593 String8(ident).string(),
594 String8(itemIdent).string(),
595 String8(str).string()));
596
597 err = outTable->addBag(SourcePos(in->getPrintableSource(), block->getLineNumber()),
598 myPackage, curType, ident, parentIdent, itemIdent, str,
599 &spans, &config, overwrite, false, curFormat);
600 return err;
601}
602
603/*
604 * Returns true if needle is one of the elements in the comma-separated list
605 * haystack, false otherwise.
606 */
607bool isInProductList(const String16& needle, const String16& haystack) {
608 const char16_t *needle2 = needle.string();
609 const char16_t *haystack2 = haystack.string();
610 size_t needlesize = needle.size();
611
612 while (*haystack2 != '\0') {
613 if (strncmp16(haystack2, needle2, needlesize) == 0) {
614 if (haystack2[needlesize] == '\0' || haystack2[needlesize] == ',') {
615 return true;
616 }
617 }
618
619 while (*haystack2 != '\0' && *haystack2 != ',') {
620 haystack2++;
621 }
622 if (*haystack2 == ',') {
623 haystack2++;
624 }
625 }
626
627 return false;
628}
629
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700630/*
631 * A simple container that holds a resource type and name. It is ordered first by type then
632 * by name.
633 */
634struct type_ident_pair_t {
635 String16 type;
636 String16 ident;
637
638 type_ident_pair_t() { };
639 type_ident_pair_t(const String16& t, const String16& i) : type(t), ident(i) { }
640 type_ident_pair_t(const type_ident_pair_t& o) : type(o.type), ident(o.ident) { }
641 inline bool operator < (const type_ident_pair_t& o) const {
642 int cmp = compare_type(type, o.type);
643 if (cmp < 0) {
644 return true;
645 } else if (cmp > 0) {
646 return false;
647 } else {
648 return strictly_order_type(ident, o.ident);
649 }
650 }
651};
652
653
Adam Lesinski282e1812014-01-23 18:17:42 -0800654status_t parseAndAddEntry(Bundle* bundle,
655 const sp<AaptFile>& in,
656 ResXMLTree* block,
657 const ResTable_config& config,
658 const String16& myPackage,
659 const String16& curType,
660 const String16& ident,
661 const String16& curTag,
662 bool curIsStyled,
663 int32_t curFormat,
664 bool isFormatted,
665 const String16& product,
Anton Krumina2ef5c02014-03-12 14:46:44 -0700666 PseudolocalizationMethod pseudolocalize,
Adam Lesinski282e1812014-01-23 18:17:42 -0800667 const bool overwrite,
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700668 KeyedVector<type_ident_pair_t, bool>* skippedResourceNames,
Adam Lesinski282e1812014-01-23 18:17:42 -0800669 ResourceTable* outTable)
670{
671 status_t err;
672
673 String16 str;
674 Vector<StringPool::entry_style_span> spans;
675 err = parseStyledString(bundle, in->getPrintableSource().string(), block,
676 curTag, &str, curIsStyled ? &spans : NULL,
677 isFormatted, pseudolocalize);
678
679 if (err < NO_ERROR) {
680 return err;
681 }
682
683 /*
684 * If a product type was specified on the command line
685 * and also in the string, and the two are not the same,
686 * return without adding the string.
687 */
688
689 const char *bundleProduct = bundle->getProduct();
690 if (bundleProduct == NULL) {
691 bundleProduct = "";
692 }
693
694 if (product.size() != 0) {
695 /*
696 * If the command-line-specified product is empty, only "default"
697 * matches. Other variants are skipped. This is so generation
698 * of the R.java file when the product is not known is predictable.
699 */
700
701 if (bundleProduct[0] == '\0') {
702 if (strcmp16(String16("default").string(), product.string()) != 0) {
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700703 /*
704 * This string has a product other than 'default'. Do not add it,
705 * but record it so that if we do not see the same string with
706 * product 'default' or no product, then report an error.
707 */
708 skippedResourceNames->replaceValueFor(
709 type_ident_pair_t(curType, ident), true);
Adam Lesinski282e1812014-01-23 18:17:42 -0800710 return NO_ERROR;
711 }
712 } else {
713 /*
714 * The command-line product is not empty.
715 * If the product for this string is on the command-line list,
716 * it matches. "default" also matches, but only if nothing
717 * else has matched already.
718 */
719
720 if (isInProductList(product, String16(bundleProduct))) {
721 ;
722 } else if (strcmp16(String16("default").string(), product.string()) == 0 &&
723 !outTable->hasBagOrEntry(myPackage, curType, ident, config)) {
724 ;
725 } else {
726 return NO_ERROR;
727 }
728 }
729 }
730
731 NOISY(printf("Adding resource entry l=%c%c c=%c%c orien=%d d=%d id=%s: %s\n",
732 config.language[0], config.language[1],
733 config.country[0], config.country[1],
734 config.orientation, config.density,
735 String8(ident).string(), String8(str).string()));
736
737 err = outTable->addEntry(SourcePos(in->getPrintableSource(), block->getLineNumber()),
738 myPackage, curType, ident, str, &spans, &config,
739 false, curFormat, overwrite);
740
741 return err;
742}
743
744status_t compileResourceFile(Bundle* bundle,
745 const sp<AaptAssets>& assets,
746 const sp<AaptFile>& in,
747 const ResTable_config& defParams,
748 const bool overwrite,
749 ResourceTable* outTable)
750{
751 ResXMLTree block;
752 status_t err = parseXMLResource(in, &block, false, true);
753 if (err != NO_ERROR) {
754 return err;
755 }
756
757 // Top-level tag.
758 const String16 resources16("resources");
759
760 // Identifier declaration tags.
761 const String16 declare_styleable16("declare-styleable");
762 const String16 attr16("attr");
763
764 // Data creation organizational tags.
765 const String16 string16("string");
766 const String16 drawable16("drawable");
767 const String16 color16("color");
768 const String16 bool16("bool");
769 const String16 integer16("integer");
770 const String16 dimen16("dimen");
771 const String16 fraction16("fraction");
772 const String16 style16("style");
773 const String16 plurals16("plurals");
774 const String16 array16("array");
775 const String16 string_array16("string-array");
776 const String16 integer_array16("integer-array");
777 const String16 public16("public");
778 const String16 public_padding16("public-padding");
779 const String16 private_symbols16("private-symbols");
780 const String16 java_symbol16("java-symbol");
781 const String16 add_resource16("add-resource");
782 const String16 skip16("skip");
783 const String16 eat_comment16("eat-comment");
784
785 // Data creation tags.
786 const String16 bag16("bag");
787 const String16 item16("item");
788
789 // Attribute type constants.
790 const String16 enum16("enum");
791
792 // plural values
793 const String16 other16("other");
794 const String16 quantityOther16("^other");
795 const String16 zero16("zero");
796 const String16 quantityZero16("^zero");
797 const String16 one16("one");
798 const String16 quantityOne16("^one");
799 const String16 two16("two");
800 const String16 quantityTwo16("^two");
801 const String16 few16("few");
802 const String16 quantityFew16("^few");
803 const String16 many16("many");
804 const String16 quantityMany16("^many");
805
806 // useful attribute names and special values
807 const String16 name16("name");
808 const String16 translatable16("translatable");
809 const String16 formatted16("formatted");
810 const String16 false16("false");
811
812 const String16 myPackage(assets->getPackage());
813
814 bool hasErrors = false;
815
816 bool fileIsTranslatable = true;
817 if (strstr(in->getPrintableSource().string(), "donottranslate") != NULL) {
818 fileIsTranslatable = false;
819 }
820
821 DefaultKeyedVector<String16, uint32_t> nextPublicId(0);
822
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700823 // Stores the resource names that were skipped. Typically this happens when
824 // AAPT is invoked without a product specified and a resource has no
825 // 'default' product attribute.
826 KeyedVector<type_ident_pair_t, bool> skippedResourceNames;
827
Adam Lesinski282e1812014-01-23 18:17:42 -0800828 ResXMLTree::event_code_t code;
829 do {
830 code = block.next();
831 } while (code == ResXMLTree::START_NAMESPACE);
832
833 size_t len;
834 if (code != ResXMLTree::START_TAG) {
835 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
836 "No start tag found\n");
837 return UNKNOWN_ERROR;
838 }
839 if (strcmp16(block.getElementName(&len), resources16.string()) != 0) {
840 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
841 "Invalid start tag %s\n", String8(block.getElementName(&len)).string());
842 return UNKNOWN_ERROR;
843 }
844
845 ResTable_config curParams(defParams);
846
847 ResTable_config pseudoParams(curParams);
Anton Krumina2ef5c02014-03-12 14:46:44 -0700848 pseudoParams.language[0] = 'e';
849 pseudoParams.language[1] = 'n';
850 pseudoParams.country[0] = 'X';
851 pseudoParams.country[1] = 'A';
852
853 ResTable_config pseudoBidiParams(curParams);
854 pseudoBidiParams.language[0] = 'a';
855 pseudoBidiParams.language[1] = 'r';
856 pseudoBidiParams.country[0] = 'X';
857 pseudoBidiParams.country[1] = 'B';
Adam Lesinski282e1812014-01-23 18:17:42 -0800858
Igor Viarheichyk47843df2014-05-01 17:04:39 -0700859 // We should skip resources for pseudolocales if they were
860 // already added automatically. This is a fix for a transition period when
861 // manually pseudolocalized resources may be expected.
862 // TODO: remove this check after next SDK version release.
863 if ((bundle->getPseudolocalize() & PSEUDO_ACCENTED &&
864 curParams.locale == pseudoParams.locale) ||
865 (bundle->getPseudolocalize() & PSEUDO_BIDI &&
866 curParams.locale == pseudoBidiParams.locale)) {
867 SourcePos(in->getPrintableSource(), 0).warning(
868 "Resource file %s is skipped as pseudolocalization"
869 " was done automatically.",
870 in->getPrintableSource().string());
871 return NO_ERROR;
872 }
873
Adam Lesinski282e1812014-01-23 18:17:42 -0800874 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
875 if (code == ResXMLTree::START_TAG) {
876 const String16* curTag = NULL;
877 String16 curType;
878 int32_t curFormat = ResTable_map::TYPE_ANY;
879 bool curIsBag = false;
880 bool curIsBagReplaceOnOverwrite = false;
881 bool curIsStyled = false;
882 bool curIsPseudolocalizable = false;
883 bool curIsFormatted = fileIsTranslatable;
884 bool localHasErrors = false;
885
886 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
887 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
888 && code != ResXMLTree::BAD_DOCUMENT) {
889 if (code == ResXMLTree::END_TAG) {
890 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
891 break;
892 }
893 }
894 }
895 continue;
896
897 } else if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
898 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
899 && code != ResXMLTree::BAD_DOCUMENT) {
900 if (code == ResXMLTree::END_TAG) {
901 if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
902 break;
903 }
904 }
905 }
906 continue;
907
908 } else if (strcmp16(block.getElementName(&len), public16.string()) == 0) {
909 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
910
911 String16 type;
912 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
913 if (typeIdx < 0) {
914 srcPos.error("A 'type' attribute is required for <public>\n");
915 hasErrors = localHasErrors = true;
916 }
917 type = String16(block.getAttributeStringValue(typeIdx, &len));
918
919 String16 name;
920 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
921 if (nameIdx < 0) {
922 srcPos.error("A 'name' attribute is required for <public>\n");
923 hasErrors = localHasErrors = true;
924 }
925 name = String16(block.getAttributeStringValue(nameIdx, &len));
926
927 uint32_t ident = 0;
928 ssize_t identIdx = block.indexOfAttribute(NULL, "id");
929 if (identIdx >= 0) {
930 const char16_t* identStr = block.getAttributeStringValue(identIdx, &len);
931 Res_value identValue;
932 if (!ResTable::stringToInt(identStr, len, &identValue)) {
933 srcPos.error("Given 'id' attribute is not an integer: %s\n",
934 String8(block.getAttributeStringValue(identIdx, &len)).string());
935 hasErrors = localHasErrors = true;
936 } else {
937 ident = identValue.data;
938 nextPublicId.replaceValueFor(type, ident+1);
939 }
940 } else if (nextPublicId.indexOfKey(type) < 0) {
941 srcPos.error("No 'id' attribute supplied <public>,"
942 " and no previous id defined in this file.\n");
943 hasErrors = localHasErrors = true;
944 } else if (!localHasErrors) {
945 ident = nextPublicId.valueFor(type);
946 nextPublicId.replaceValueFor(type, ident+1);
947 }
948
949 if (!localHasErrors) {
950 err = outTable->addPublic(srcPos, myPackage, type, name, ident);
951 if (err < NO_ERROR) {
952 hasErrors = localHasErrors = true;
953 }
954 }
955 if (!localHasErrors) {
956 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
957 if (symbols != NULL) {
958 symbols = symbols->addNestedSymbol(String8(type), srcPos);
959 }
960 if (symbols != NULL) {
961 symbols->makeSymbolPublic(String8(name), srcPos);
962 String16 comment(
963 block.getComment(&len) ? block.getComment(&len) : nulStr);
964 symbols->appendComment(String8(name), comment, srcPos);
965 } else {
966 srcPos.error("Unable to create symbols!\n");
967 hasErrors = localHasErrors = true;
968 }
969 }
970
971 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
972 if (code == ResXMLTree::END_TAG) {
973 if (strcmp16(block.getElementName(&len), public16.string()) == 0) {
974 break;
975 }
976 }
977 }
978 continue;
979
980 } else if (strcmp16(block.getElementName(&len), public_padding16.string()) == 0) {
981 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
982
983 String16 type;
984 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
985 if (typeIdx < 0) {
986 srcPos.error("A 'type' attribute is required for <public-padding>\n");
987 hasErrors = localHasErrors = true;
988 }
989 type = String16(block.getAttributeStringValue(typeIdx, &len));
990
991 String16 name;
992 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
993 if (nameIdx < 0) {
994 srcPos.error("A 'name' attribute is required for <public-padding>\n");
995 hasErrors = localHasErrors = true;
996 }
997 name = String16(block.getAttributeStringValue(nameIdx, &len));
998
999 uint32_t start = 0;
1000 ssize_t startIdx = block.indexOfAttribute(NULL, "start");
1001 if (startIdx >= 0) {
1002 const char16_t* startStr = block.getAttributeStringValue(startIdx, &len);
1003 Res_value startValue;
1004 if (!ResTable::stringToInt(startStr, len, &startValue)) {
1005 srcPos.error("Given 'start' attribute is not an integer: %s\n",
1006 String8(block.getAttributeStringValue(startIdx, &len)).string());
1007 hasErrors = localHasErrors = true;
1008 } else {
1009 start = startValue.data;
1010 }
1011 } else if (nextPublicId.indexOfKey(type) < 0) {
1012 srcPos.error("No 'start' attribute supplied <public-padding>,"
1013 " and no previous id defined in this file.\n");
1014 hasErrors = localHasErrors = true;
1015 } else if (!localHasErrors) {
1016 start = nextPublicId.valueFor(type);
1017 }
1018
1019 uint32_t end = 0;
1020 ssize_t endIdx = block.indexOfAttribute(NULL, "end");
1021 if (endIdx >= 0) {
1022 const char16_t* endStr = block.getAttributeStringValue(endIdx, &len);
1023 Res_value endValue;
1024 if (!ResTable::stringToInt(endStr, len, &endValue)) {
1025 srcPos.error("Given 'end' attribute is not an integer: %s\n",
1026 String8(block.getAttributeStringValue(endIdx, &len)).string());
1027 hasErrors = localHasErrors = true;
1028 } else {
1029 end = endValue.data;
1030 }
1031 } else {
1032 srcPos.error("No 'end' attribute supplied <public-padding>\n");
1033 hasErrors = localHasErrors = true;
1034 }
1035
1036 if (end >= start) {
1037 nextPublicId.replaceValueFor(type, end+1);
1038 } else {
1039 srcPos.error("Padding start '%ul' is after end '%ul'\n",
1040 start, end);
1041 hasErrors = localHasErrors = true;
1042 }
1043
1044 String16 comment(
1045 block.getComment(&len) ? block.getComment(&len) : nulStr);
1046 for (uint32_t curIdent=start; curIdent<=end; curIdent++) {
1047 if (localHasErrors) {
1048 break;
1049 }
1050 String16 curName(name);
1051 char buf[64];
1052 sprintf(buf, "%d", (int)(end-curIdent+1));
1053 curName.append(String16(buf));
1054
1055 err = outTable->addEntry(srcPos, myPackage, type, curName,
1056 String16("padding"), NULL, &curParams, false,
1057 ResTable_map::TYPE_STRING, overwrite);
1058 if (err < NO_ERROR) {
1059 hasErrors = localHasErrors = true;
1060 break;
1061 }
1062 err = outTable->addPublic(srcPos, myPackage, type,
1063 curName, curIdent);
1064 if (err < NO_ERROR) {
1065 hasErrors = localHasErrors = true;
1066 break;
1067 }
1068 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1069 if (symbols != NULL) {
1070 symbols = symbols->addNestedSymbol(String8(type), srcPos);
1071 }
1072 if (symbols != NULL) {
1073 symbols->makeSymbolPublic(String8(curName), srcPos);
1074 symbols->appendComment(String8(curName), comment, srcPos);
1075 } else {
1076 srcPos.error("Unable to create symbols!\n");
1077 hasErrors = localHasErrors = true;
1078 }
1079 }
1080
1081 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1082 if (code == ResXMLTree::END_TAG) {
1083 if (strcmp16(block.getElementName(&len), public_padding16.string()) == 0) {
1084 break;
1085 }
1086 }
1087 }
1088 continue;
1089
1090 } else if (strcmp16(block.getElementName(&len), private_symbols16.string()) == 0) {
1091 String16 pkg;
1092 ssize_t pkgIdx = block.indexOfAttribute(NULL, "package");
1093 if (pkgIdx < 0) {
1094 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1095 "A 'package' attribute is required for <private-symbols>\n");
1096 hasErrors = localHasErrors = true;
1097 }
1098 pkg = String16(block.getAttributeStringValue(pkgIdx, &len));
1099 if (!localHasErrors) {
1100 assets->setSymbolsPrivatePackage(String8(pkg));
1101 }
1102
1103 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1104 if (code == ResXMLTree::END_TAG) {
1105 if (strcmp16(block.getElementName(&len), private_symbols16.string()) == 0) {
1106 break;
1107 }
1108 }
1109 }
1110 continue;
1111
1112 } else if (strcmp16(block.getElementName(&len), java_symbol16.string()) == 0) {
1113 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1114
1115 String16 type;
1116 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
1117 if (typeIdx < 0) {
1118 srcPos.error("A 'type' attribute is required for <public>\n");
1119 hasErrors = localHasErrors = true;
1120 }
1121 type = String16(block.getAttributeStringValue(typeIdx, &len));
1122
1123 String16 name;
1124 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1125 if (nameIdx < 0) {
1126 srcPos.error("A 'name' attribute is required for <public>\n");
1127 hasErrors = localHasErrors = true;
1128 }
1129 name = String16(block.getAttributeStringValue(nameIdx, &len));
1130
1131 sp<AaptSymbols> symbols = assets->getJavaSymbolsFor(String8("R"));
1132 if (symbols != NULL) {
1133 symbols = symbols->addNestedSymbol(String8(type), srcPos);
1134 }
1135 if (symbols != NULL) {
1136 symbols->makeSymbolJavaSymbol(String8(name), srcPos);
1137 String16 comment(
1138 block.getComment(&len) ? block.getComment(&len) : nulStr);
1139 symbols->appendComment(String8(name), comment, srcPos);
1140 } else {
1141 srcPos.error("Unable to create symbols!\n");
1142 hasErrors = localHasErrors = true;
1143 }
1144
1145 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1146 if (code == ResXMLTree::END_TAG) {
1147 if (strcmp16(block.getElementName(&len), java_symbol16.string()) == 0) {
1148 break;
1149 }
1150 }
1151 }
1152 continue;
1153
1154
1155 } else if (strcmp16(block.getElementName(&len), add_resource16.string()) == 0) {
1156 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1157
1158 String16 typeName;
1159 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
1160 if (typeIdx < 0) {
1161 srcPos.error("A 'type' attribute is required for <add-resource>\n");
1162 hasErrors = localHasErrors = true;
1163 }
1164 typeName = String16(block.getAttributeStringValue(typeIdx, &len));
1165
1166 String16 name;
1167 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1168 if (nameIdx < 0) {
1169 srcPos.error("A 'name' attribute is required for <add-resource>\n");
1170 hasErrors = localHasErrors = true;
1171 }
1172 name = String16(block.getAttributeStringValue(nameIdx, &len));
1173
1174 outTable->canAddEntry(srcPos, myPackage, typeName, name);
1175
1176 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1177 if (code == ResXMLTree::END_TAG) {
1178 if (strcmp16(block.getElementName(&len), add_resource16.string()) == 0) {
1179 break;
1180 }
1181 }
1182 }
1183 continue;
1184
1185 } else if (strcmp16(block.getElementName(&len), declare_styleable16.string()) == 0) {
1186 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1187
1188 String16 ident;
1189 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
1190 if (identIdx < 0) {
1191 srcPos.error("A 'name' attribute is required for <declare-styleable>\n");
1192 hasErrors = localHasErrors = true;
1193 }
1194 ident = String16(block.getAttributeStringValue(identIdx, &len));
1195
1196 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1197 if (!localHasErrors) {
1198 if (symbols != NULL) {
1199 symbols = symbols->addNestedSymbol(String8("styleable"), srcPos);
1200 }
1201 sp<AaptSymbols> styleSymbols = symbols;
1202 if (symbols != NULL) {
1203 symbols = symbols->addNestedSymbol(String8(ident), srcPos);
1204 }
1205 if (symbols == NULL) {
1206 srcPos.error("Unable to create symbols!\n");
1207 return UNKNOWN_ERROR;
1208 }
1209
1210 String16 comment(
1211 block.getComment(&len) ? block.getComment(&len) : nulStr);
1212 styleSymbols->appendComment(String8(ident), comment, srcPos);
1213 } else {
1214 symbols = NULL;
1215 }
1216
1217 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1218 if (code == ResXMLTree::START_TAG) {
1219 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
1220 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1221 && code != ResXMLTree::BAD_DOCUMENT) {
1222 if (code == ResXMLTree::END_TAG) {
1223 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
1224 break;
1225 }
1226 }
1227 }
1228 continue;
1229 } else if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
1230 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1231 && code != ResXMLTree::BAD_DOCUMENT) {
1232 if (code == ResXMLTree::END_TAG) {
1233 if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
1234 break;
1235 }
1236 }
1237 }
1238 continue;
1239 } else if (strcmp16(block.getElementName(&len), attr16.string()) != 0) {
1240 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1241 "Tag <%s> can not appear inside <declare-styleable>, only <attr>\n",
1242 String8(block.getElementName(&len)).string());
1243 return UNKNOWN_ERROR;
1244 }
1245
1246 String16 comment(
1247 block.getComment(&len) ? block.getComment(&len) : nulStr);
1248 String16 itemIdent;
1249 err = compileAttribute(in, block, myPackage, outTable, &itemIdent, true);
1250 if (err != NO_ERROR) {
1251 hasErrors = localHasErrors = true;
1252 }
1253
1254 if (symbols != NULL) {
1255 SourcePos srcPos(String8(in->getPrintableSource()), block.getLineNumber());
1256 symbols->addSymbol(String8(itemIdent), 0, srcPos);
1257 symbols->appendComment(String8(itemIdent), comment, srcPos);
1258 //printf("Attribute %s comment: %s\n", String8(itemIdent).string(),
1259 // String8(comment).string());
1260 }
1261 } else if (code == ResXMLTree::END_TAG) {
1262 if (strcmp16(block.getElementName(&len), declare_styleable16.string()) == 0) {
1263 break;
1264 }
1265
1266 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1267 "Found tag </%s> where </attr> is expected\n",
1268 String8(block.getElementName(&len)).string());
1269 return UNKNOWN_ERROR;
1270 }
1271 }
1272 continue;
1273
1274 } else if (strcmp16(block.getElementName(&len), attr16.string()) == 0) {
1275 err = compileAttribute(in, block, myPackage, outTable, NULL);
1276 if (err != NO_ERROR) {
1277 hasErrors = true;
1278 }
1279 continue;
1280
1281 } else if (strcmp16(block.getElementName(&len), item16.string()) == 0) {
1282 curTag = &item16;
1283 ssize_t attri = block.indexOfAttribute(NULL, "type");
1284 if (attri >= 0) {
1285 curType = String16(block.getAttributeStringValue(attri, &len));
1286 ssize_t formatIdx = block.indexOfAttribute(NULL, "format");
1287 if (formatIdx >= 0) {
1288 String16 formatStr = String16(block.getAttributeStringValue(
1289 formatIdx, &len));
1290 curFormat = parse_flags(formatStr.string(), formatStr.size(),
1291 gFormatFlags);
1292 if (curFormat == 0) {
1293 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1294 "Tag <item> 'format' attribute value \"%s\" not valid\n",
1295 String8(formatStr).string());
1296 hasErrors = localHasErrors = true;
1297 }
1298 }
1299 } else {
1300 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1301 "A 'type' attribute is required for <item>\n");
1302 hasErrors = localHasErrors = true;
1303 }
1304 curIsStyled = true;
1305 } else if (strcmp16(block.getElementName(&len), string16.string()) == 0) {
1306 // Note the existence and locale of every string we process
Narayan Kamath91447d82014-01-21 15:32:36 +00001307 char rawLocale[RESTABLE_MAX_LOCALE_LEN];
1308 curParams.getBcp47Locale(rawLocale);
Adam Lesinski282e1812014-01-23 18:17:42 -08001309 String8 locale(rawLocale);
1310 String16 name;
1311 String16 translatable;
1312 String16 formatted;
1313
1314 size_t n = block.getAttributeCount();
1315 for (size_t i = 0; i < n; i++) {
1316 size_t length;
1317 const uint16_t* attr = block.getAttributeName(i, &length);
1318 if (strcmp16(attr, name16.string()) == 0) {
1319 name.setTo(block.getAttributeStringValue(i, &length));
1320 } else if (strcmp16(attr, translatable16.string()) == 0) {
1321 translatable.setTo(block.getAttributeStringValue(i, &length));
1322 } else if (strcmp16(attr, formatted16.string()) == 0) {
1323 formatted.setTo(block.getAttributeStringValue(i, &length));
1324 }
1325 }
1326
1327 if (name.size() > 0) {
1328 if (translatable == false16) {
1329 curIsFormatted = false;
1330 // Untranslatable strings must only exist in the default [empty] locale
1331 if (locale.size() > 0) {
Adam Lesinskia01a9372014-03-20 18:04:57 -07001332 SourcePos(in->getPrintableSource(), block.getLineNumber()).warning(
1333 "string '%s' marked untranslatable but exists in locale '%s'\n",
1334 String8(name).string(),
Adam Lesinski282e1812014-01-23 18:17:42 -08001335 locale.string());
1336 // hasErrors = localHasErrors = true;
1337 } else {
1338 // Intentionally empty block:
1339 //
1340 // Don't add untranslatable strings to the localization table; that
1341 // way if we later see localizations of them, they'll be flagged as
1342 // having no default translation.
1343 }
1344 } else {
Adam Lesinskia01a9372014-03-20 18:04:57 -07001345 outTable->addLocalization(
1346 name,
1347 locale,
1348 SourcePos(in->getPrintableSource(), block.getLineNumber()));
Adam Lesinski282e1812014-01-23 18:17:42 -08001349 }
1350
1351 if (formatted == false16) {
1352 curIsFormatted = false;
1353 }
1354 }
1355
1356 curTag = &string16;
1357 curType = string16;
1358 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
1359 curIsStyled = true;
Igor Viarheichyk84410b02014-04-30 11:56:42 -07001360 curIsPseudolocalizable = fileIsTranslatable && (translatable != false16);
Adam Lesinski282e1812014-01-23 18:17:42 -08001361 } else if (strcmp16(block.getElementName(&len), drawable16.string()) == 0) {
1362 curTag = &drawable16;
1363 curType = drawable16;
1364 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
1365 } else if (strcmp16(block.getElementName(&len), color16.string()) == 0) {
1366 curTag = &color16;
1367 curType = color16;
1368 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
1369 } else if (strcmp16(block.getElementName(&len), bool16.string()) == 0) {
1370 curTag = &bool16;
1371 curType = bool16;
1372 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_BOOLEAN;
1373 } else if (strcmp16(block.getElementName(&len), integer16.string()) == 0) {
1374 curTag = &integer16;
1375 curType = integer16;
1376 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
1377 } else if (strcmp16(block.getElementName(&len), dimen16.string()) == 0) {
1378 curTag = &dimen16;
1379 curType = dimen16;
1380 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_DIMENSION;
1381 } else if (strcmp16(block.getElementName(&len), fraction16.string()) == 0) {
1382 curTag = &fraction16;
1383 curType = fraction16;
1384 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_FRACTION;
1385 } else if (strcmp16(block.getElementName(&len), bag16.string()) == 0) {
1386 curTag = &bag16;
1387 curIsBag = true;
1388 ssize_t attri = block.indexOfAttribute(NULL, "type");
1389 if (attri >= 0) {
1390 curType = String16(block.getAttributeStringValue(attri, &len));
1391 } else {
1392 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1393 "A 'type' attribute is required for <bag>\n");
1394 hasErrors = localHasErrors = true;
1395 }
1396 } else if (strcmp16(block.getElementName(&len), style16.string()) == 0) {
1397 curTag = &style16;
1398 curType = style16;
1399 curIsBag = true;
1400 } else if (strcmp16(block.getElementName(&len), plurals16.string()) == 0) {
1401 curTag = &plurals16;
1402 curType = plurals16;
1403 curIsBag = true;
Anton Krumina2ef5c02014-03-12 14:46:44 -07001404 curIsPseudolocalizable = fileIsTranslatable;
Adam Lesinski282e1812014-01-23 18:17:42 -08001405 } else if (strcmp16(block.getElementName(&len), array16.string()) == 0) {
1406 curTag = &array16;
1407 curType = array16;
1408 curIsBag = true;
1409 curIsBagReplaceOnOverwrite = true;
1410 ssize_t formatIdx = block.indexOfAttribute(NULL, "format");
1411 if (formatIdx >= 0) {
1412 String16 formatStr = String16(block.getAttributeStringValue(
1413 formatIdx, &len));
1414 curFormat = parse_flags(formatStr.string(), formatStr.size(),
1415 gFormatFlags);
1416 if (curFormat == 0) {
1417 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1418 "Tag <array> 'format' attribute value \"%s\" not valid\n",
1419 String8(formatStr).string());
1420 hasErrors = localHasErrors = true;
1421 }
1422 }
1423 } else if (strcmp16(block.getElementName(&len), string_array16.string()) == 0) {
1424 // Check whether these strings need valid formats.
1425 // (simplified form of what string16 does above)
Anton Krumina2ef5c02014-03-12 14:46:44 -07001426 bool isTranslatable = false;
Adam Lesinski282e1812014-01-23 18:17:42 -08001427 size_t n = block.getAttributeCount();
Narayan Kamath9a9fa162013-12-18 13:27:30 +00001428
1429 // Pseudolocalizable by default, unless this string array isn't
1430 // translatable.
Adam Lesinski282e1812014-01-23 18:17:42 -08001431 for (size_t i = 0; i < n; i++) {
1432 size_t length;
1433 const uint16_t* attr = block.getAttributeName(i, &length);
Narayan Kamath9a9fa162013-12-18 13:27:30 +00001434 if (strcmp16(attr, formatted16.string()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001435 const uint16_t* value = block.getAttributeStringValue(i, &length);
1436 if (strcmp16(value, false16.string()) == 0) {
1437 curIsFormatted = false;
Adam Lesinski282e1812014-01-23 18:17:42 -08001438 }
Anton Krumina2ef5c02014-03-12 14:46:44 -07001439 } else if (strcmp16(attr, translatable16.string()) == 0) {
1440 const uint16_t* value = block.getAttributeStringValue(i, &length);
1441 if (strcmp16(value, false16.string()) == 0) {
1442 isTranslatable = false;
1443 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001444 }
1445 }
1446
1447 curTag = &string_array16;
1448 curType = array16;
1449 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
1450 curIsBag = true;
1451 curIsBagReplaceOnOverwrite = true;
Anton Krumina2ef5c02014-03-12 14:46:44 -07001452 curIsPseudolocalizable = isTranslatable && fileIsTranslatable;
Adam Lesinski282e1812014-01-23 18:17:42 -08001453 } else if (strcmp16(block.getElementName(&len), integer_array16.string()) == 0) {
1454 curTag = &integer_array16;
1455 curType = array16;
1456 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
1457 curIsBag = true;
1458 curIsBagReplaceOnOverwrite = true;
1459 } else {
1460 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1461 "Found tag %s where item is expected\n",
1462 String8(block.getElementName(&len)).string());
1463 return UNKNOWN_ERROR;
1464 }
1465
1466 String16 ident;
1467 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
1468 if (identIdx >= 0) {
1469 ident = String16(block.getAttributeStringValue(identIdx, &len));
1470 } else {
1471 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1472 "A 'name' attribute is required for <%s>\n",
1473 String8(*curTag).string());
1474 hasErrors = localHasErrors = true;
1475 }
1476
1477 String16 product;
1478 identIdx = block.indexOfAttribute(NULL, "product");
1479 if (identIdx >= 0) {
1480 product = String16(block.getAttributeStringValue(identIdx, &len));
1481 }
1482
1483 String16 comment(block.getComment(&len) ? block.getComment(&len) : nulStr);
1484
1485 if (curIsBag) {
1486 // Figure out the parent of this bag...
1487 String16 parentIdent;
1488 ssize_t parentIdentIdx = block.indexOfAttribute(NULL, "parent");
1489 if (parentIdentIdx >= 0) {
1490 parentIdent = String16(block.getAttributeStringValue(parentIdentIdx, &len));
1491 } else {
1492 ssize_t sep = ident.findLast('.');
1493 if (sep >= 0) {
1494 parentIdent.setTo(ident, sep);
1495 }
1496 }
1497
1498 if (!localHasErrors) {
1499 err = outTable->startBag(SourcePos(in->getPrintableSource(),
1500 block.getLineNumber()), myPackage, curType, ident,
1501 parentIdent, &curParams,
1502 overwrite, curIsBagReplaceOnOverwrite);
1503 if (err != NO_ERROR) {
1504 hasErrors = localHasErrors = true;
1505 }
1506 }
1507
1508 ssize_t elmIndex = 0;
1509 char elmIndexStr[14];
1510 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1511 && code != ResXMLTree::BAD_DOCUMENT) {
1512
1513 if (code == ResXMLTree::START_TAG) {
1514 if (strcmp16(block.getElementName(&len), item16.string()) != 0) {
1515 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1516 "Tag <%s> can not appear inside <%s>, only <item>\n",
1517 String8(block.getElementName(&len)).string(),
1518 String8(*curTag).string());
1519 return UNKNOWN_ERROR;
1520 }
1521
1522 String16 itemIdent;
1523 if (curType == array16) {
1524 sprintf(elmIndexStr, "^index_%d", (int)elmIndex++);
1525 itemIdent = String16(elmIndexStr);
1526 } else if (curType == plurals16) {
1527 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "quantity");
1528 if (itemIdentIdx >= 0) {
1529 String16 quantity16(block.getAttributeStringValue(itemIdentIdx, &len));
1530 if (quantity16 == other16) {
1531 itemIdent = quantityOther16;
1532 }
1533 else if (quantity16 == zero16) {
1534 itemIdent = quantityZero16;
1535 }
1536 else if (quantity16 == one16) {
1537 itemIdent = quantityOne16;
1538 }
1539 else if (quantity16 == two16) {
1540 itemIdent = quantityTwo16;
1541 }
1542 else if (quantity16 == few16) {
1543 itemIdent = quantityFew16;
1544 }
1545 else if (quantity16 == many16) {
1546 itemIdent = quantityMany16;
1547 }
1548 else {
1549 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1550 "Illegal 'quantity' attribute is <item> inside <plurals>\n");
1551 hasErrors = localHasErrors = true;
1552 }
1553 } else {
1554 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1555 "A 'quantity' attribute is required for <item> inside <plurals>\n");
1556 hasErrors = localHasErrors = true;
1557 }
1558 } else {
1559 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "name");
1560 if (itemIdentIdx >= 0) {
1561 itemIdent = String16(block.getAttributeStringValue(itemIdentIdx, &len));
1562 } else {
1563 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1564 "A 'name' attribute is required for <item>\n");
1565 hasErrors = localHasErrors = true;
1566 }
1567 }
1568
1569 ResXMLParser::ResXMLPosition parserPosition;
1570 block.getPosition(&parserPosition);
1571
1572 err = parseAndAddBag(bundle, in, &block, curParams, myPackage, curType,
1573 ident, parentIdent, itemIdent, curFormat, curIsFormatted,
Anton Krumina2ef5c02014-03-12 14:46:44 -07001574 product, NO_PSEUDOLOCALIZATION, overwrite, outTable);
Adam Lesinski282e1812014-01-23 18:17:42 -08001575 if (err == NO_ERROR) {
1576 if (curIsPseudolocalizable && localeIsDefined(curParams)
Anton Krumina2ef5c02014-03-12 14:46:44 -07001577 && bundle->getPseudolocalize() > 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001578 // pseudolocalize here
Anton Krumina2ef5c02014-03-12 14:46:44 -07001579 if ((PSEUDO_ACCENTED & bundle->getPseudolocalize()) ==
1580 PSEUDO_ACCENTED) {
1581 block.setPosition(parserPosition);
1582 err = parseAndAddBag(bundle, in, &block, pseudoParams, myPackage,
1583 curType, ident, parentIdent, itemIdent, curFormat,
1584 curIsFormatted, product, PSEUDO_ACCENTED,
1585 overwrite, outTable);
1586 }
1587 if ((PSEUDO_BIDI & bundle->getPseudolocalize()) ==
1588 PSEUDO_BIDI) {
1589 block.setPosition(parserPosition);
1590 err = parseAndAddBag(bundle, in, &block, pseudoBidiParams, myPackage,
1591 curType, ident, parentIdent, itemIdent, curFormat,
1592 curIsFormatted, product, PSEUDO_BIDI,
1593 overwrite, outTable);
1594 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001595 }
Anton Krumina2ef5c02014-03-12 14:46:44 -07001596 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001597 if (err != NO_ERROR) {
1598 hasErrors = localHasErrors = true;
1599 }
1600 } else if (code == ResXMLTree::END_TAG) {
1601 if (strcmp16(block.getElementName(&len), curTag->string()) != 0) {
1602 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1603 "Found tag </%s> where </%s> is expected\n",
1604 String8(block.getElementName(&len)).string(),
1605 String8(*curTag).string());
1606 return UNKNOWN_ERROR;
1607 }
1608 break;
1609 }
1610 }
1611 } else {
1612 ResXMLParser::ResXMLPosition parserPosition;
1613 block.getPosition(&parserPosition);
1614
1615 err = parseAndAddEntry(bundle, in, &block, curParams, myPackage, curType, ident,
1616 *curTag, curIsStyled, curFormat, curIsFormatted,
Anton Krumina2ef5c02014-03-12 14:46:44 -07001617 product, NO_PSEUDOLOCALIZATION, overwrite, &skippedResourceNames, outTable);
Adam Lesinski282e1812014-01-23 18:17:42 -08001618
1619 if (err < NO_ERROR) { // Why err < NO_ERROR instead of err != NO_ERROR?
1620 hasErrors = localHasErrors = true;
1621 }
1622 else if (err == NO_ERROR) {
1623 if (curIsPseudolocalizable && localeIsDefined(curParams)
Anton Krumina2ef5c02014-03-12 14:46:44 -07001624 && bundle->getPseudolocalize() > 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001625 // pseudolocalize here
Anton Krumina2ef5c02014-03-12 14:46:44 -07001626 if ((PSEUDO_ACCENTED & bundle->getPseudolocalize()) ==
1627 PSEUDO_ACCENTED) {
1628 block.setPosition(parserPosition);
1629 err = parseAndAddEntry(bundle, in, &block, pseudoParams, myPackage, curType,
1630 ident, *curTag, curIsStyled, curFormat,
1631 curIsFormatted, product,
1632 PSEUDO_ACCENTED, overwrite, &skippedResourceNames, outTable);
1633 }
1634 if ((PSEUDO_BIDI & bundle->getPseudolocalize()) ==
1635 PSEUDO_BIDI) {
1636 block.setPosition(parserPosition);
1637 err = parseAndAddEntry(bundle, in, &block, pseudoBidiParams,
1638 myPackage, curType, ident, *curTag, curIsStyled, curFormat,
1639 curIsFormatted, product,
1640 PSEUDO_BIDI, overwrite, &skippedResourceNames, outTable);
1641 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001642 if (err != NO_ERROR) {
1643 hasErrors = localHasErrors = true;
1644 }
1645 }
1646 }
1647 }
1648
1649#if 0
1650 if (comment.size() > 0) {
1651 printf("Comment for @%s:%s/%s: %s\n", String8(myPackage).string(),
1652 String8(curType).string(), String8(ident).string(),
1653 String8(comment).string());
1654 }
1655#endif
1656 if (!localHasErrors) {
1657 outTable->appendComment(myPackage, curType, ident, comment, false);
1658 }
1659 }
1660 else if (code == ResXMLTree::END_TAG) {
1661 if (strcmp16(block.getElementName(&len), resources16.string()) != 0) {
1662 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1663 "Unexpected end tag %s\n", String8(block.getElementName(&len)).string());
1664 return UNKNOWN_ERROR;
1665 }
1666 }
1667 else if (code == ResXMLTree::START_NAMESPACE || code == ResXMLTree::END_NAMESPACE) {
1668 }
1669 else if (code == ResXMLTree::TEXT) {
1670 if (isWhitespace(block.getText(&len))) {
1671 continue;
1672 }
1673 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1674 "Found text \"%s\" where item tag is expected\n",
1675 String8(block.getText(&len)).string());
1676 return UNKNOWN_ERROR;
1677 }
1678 }
1679
Adam Lesinski8ff15b42013-10-07 16:54:01 -07001680 // For every resource defined, there must be exist one variant with a product attribute
1681 // set to 'default' (or no product attribute at all).
1682 // We check to see that for every resource that was ignored because of a mismatched
1683 // product attribute, some product variant of that resource was processed.
1684 for (size_t i = 0; i < skippedResourceNames.size(); i++) {
1685 if (skippedResourceNames[i]) {
1686 const type_ident_pair_t& p = skippedResourceNames.keyAt(i);
1687 if (!outTable->hasBagOrEntry(myPackage, p.type, p.ident)) {
1688 const char* bundleProduct =
1689 (bundle->getProduct() == NULL) ? "" : bundle->getProduct();
1690 fprintf(stderr, "In resource file %s: %s\n",
1691 in->getPrintableSource().string(),
1692 curParams.toString().string());
1693
1694 fprintf(stderr, "\t%s '%s' does not match product %s.\n"
1695 "\tYou may have forgotten to include a 'default' product variant"
1696 " of the resource.\n",
1697 String8(p.type).string(), String8(p.ident).string(),
1698 bundleProduct[0] == 0 ? "default" : bundleProduct);
1699 return UNKNOWN_ERROR;
1700 }
1701 }
1702 }
1703
Adam Lesinski282e1812014-01-23 18:17:42 -08001704 return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
1705}
1706
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001707ResourceTable::ResourceTable(Bundle* bundle, const String16& assetsPackage, ResourceTable::PackageType type)
1708 : mAssetsPackage(assetsPackage)
1709 , mPackageType(type)
1710 , mTypeIdOffset(0)
1711 , mNumLocal(0)
1712 , mBundle(bundle)
Adam Lesinski282e1812014-01-23 18:17:42 -08001713{
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001714 ssize_t packageId = -1;
1715 switch (mPackageType) {
1716 case App:
1717 case AppFeature:
1718 packageId = 0x7f;
1719 break;
1720
1721 case System:
1722 packageId = 0x01;
1723 break;
1724
1725 case SharedLibrary:
1726 packageId = 0x00;
1727 break;
1728
1729 default:
1730 assert(0);
1731 break;
1732 }
1733 sp<Package> package = new Package(mAssetsPackage, packageId);
1734 mPackages.add(assetsPackage, package);
1735 mOrderedPackages.add(package);
1736
1737 // Every resource table always has one first entry, the bag attributes.
1738 const SourcePos unknown(String8("????"), 0);
1739 getType(mAssetsPackage, String16("attr"), unknown);
1740}
1741
1742static uint32_t findLargestTypeIdForPackage(const ResTable& table, const String16& packageName) {
1743 const size_t basePackageCount = table.getBasePackageCount();
1744 for (size_t i = 0; i < basePackageCount; i++) {
1745 if (packageName == table.getBasePackageName(i)) {
1746 return table.getLastTypeIdForPackage(i);
1747 }
1748 }
1749 return 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08001750}
1751
1752status_t ResourceTable::addIncludedResources(Bundle* bundle, const sp<AaptAssets>& assets)
1753{
1754 status_t err = assets->buildIncludedResources(bundle);
1755 if (err != NO_ERROR) {
1756 return err;
1757 }
1758
Adam Lesinski282e1812014-01-23 18:17:42 -08001759 mAssets = assets;
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001760 mTypeIdOffset = findLargestTypeIdForPackage(assets->getIncludedResources(), mAssetsPackage);
Adam Lesinski282e1812014-01-23 18:17:42 -08001761
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001762 const String8& featureAfter = bundle->getFeatureAfterPackage();
1763 if (!featureAfter.isEmpty()) {
1764 AssetManager featureAssetManager;
1765 if (!featureAssetManager.addAssetPath(featureAfter, NULL)) {
1766 fprintf(stderr, "ERROR: Feature package '%s' not found.\n",
1767 featureAfter.string());
1768 return UNKNOWN_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001769 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001770
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001771 const ResTable& featureTable = featureAssetManager.getResources(false);
1772 mTypeIdOffset = max(mTypeIdOffset,
1773 findLargestTypeIdForPackage(featureTable, mAssetsPackage));
1774 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001775
1776 return NO_ERROR;
1777}
1778
1779status_t ResourceTable::addPublic(const SourcePos& sourcePos,
1780 const String16& package,
1781 const String16& type,
1782 const String16& name,
1783 const uint32_t ident)
1784{
1785 uint32_t rid = mAssets->getIncludedResources()
1786 .identifierForName(name.string(), name.size(),
1787 type.string(), type.size(),
1788 package.string(), package.size());
1789 if (rid != 0) {
1790 sourcePos.error("Error declaring public resource %s/%s for included package %s\n",
1791 String8(type).string(), String8(name).string(),
1792 String8(package).string());
1793 return UNKNOWN_ERROR;
1794 }
1795
1796 sp<Type> t = getType(package, type, sourcePos);
1797 if (t == NULL) {
1798 return UNKNOWN_ERROR;
1799 }
1800 return t->addPublic(sourcePos, name, ident);
1801}
1802
1803status_t ResourceTable::addEntry(const SourcePos& sourcePos,
1804 const String16& package,
1805 const String16& type,
1806 const String16& name,
1807 const String16& value,
1808 const Vector<StringPool::entry_style_span>* style,
1809 const ResTable_config* params,
1810 const bool doSetIndex,
1811 const int32_t format,
1812 const bool overwrite)
1813{
Adam Lesinski282e1812014-01-23 18:17:42 -08001814 uint32_t rid = mAssets->getIncludedResources()
1815 .identifierForName(name.string(), name.size(),
1816 type.string(), type.size(),
1817 package.string(), package.size());
1818 if (rid != 0) {
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001819 sourcePos.error("Resource entry %s/%s is already defined in package %s.",
1820 String8(type).string(), String8(name).string(), String8(package).string());
1821 return UNKNOWN_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001822 }
1823
Adam Lesinski282e1812014-01-23 18:17:42 -08001824 sp<Entry> e = getEntry(package, type, name, sourcePos, overwrite,
1825 params, doSetIndex);
1826 if (e == NULL) {
1827 return UNKNOWN_ERROR;
1828 }
1829 status_t err = e->setItem(sourcePos, value, style, format, overwrite);
1830 if (err == NO_ERROR) {
1831 mNumLocal++;
1832 }
1833 return err;
1834}
1835
1836status_t ResourceTable::startBag(const SourcePos& sourcePos,
1837 const String16& package,
1838 const String16& type,
1839 const String16& name,
1840 const String16& bagParent,
1841 const ResTable_config* params,
1842 bool overlay,
1843 bool replace, bool isId)
1844{
1845 status_t result = NO_ERROR;
1846
1847 // Check for adding entries in other packages... for now we do
1848 // nothing. We need to do the right thing here to support skinning.
1849 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 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001858
Adam Lesinski282e1812014-01-23 18:17:42 -08001859 if (overlay && !mBundle->getAutoAddOverlay() && !hasBagOrEntry(package, type, name)) {
1860 bool canAdd = false;
1861 sp<Package> p = mPackages.valueFor(package);
1862 if (p != NULL) {
1863 sp<Type> t = p->getTypes().valueFor(type);
1864 if (t != NULL) {
1865 if (t->getCanAddEntries().indexOf(name) >= 0) {
1866 canAdd = true;
1867 }
1868 }
1869 }
1870 if (!canAdd) {
1871 sourcePos.error("Resource does not already exist in overlay at '%s'; use <add-resource> to add.\n",
1872 String8(name).string());
1873 return UNKNOWN_ERROR;
1874 }
1875 }
1876 sp<Entry> e = getEntry(package, type, name, sourcePos, overlay, params);
1877 if (e == NULL) {
1878 return UNKNOWN_ERROR;
1879 }
1880
1881 // If a parent is explicitly specified, set it.
1882 if (bagParent.size() > 0) {
1883 e->setParent(bagParent);
1884 }
1885
1886 if ((result = e->makeItABag(sourcePos)) != NO_ERROR) {
1887 return result;
1888 }
1889
1890 if (overlay && replace) {
1891 return e->emptyBag(sourcePos);
1892 }
1893 return result;
1894}
1895
1896status_t ResourceTable::addBag(const SourcePos& sourcePos,
1897 const String16& package,
1898 const String16& type,
1899 const String16& name,
1900 const String16& bagParent,
1901 const String16& bagKey,
1902 const String16& value,
1903 const Vector<StringPool::entry_style_span>* style,
1904 const ResTable_config* params,
1905 bool replace, bool isId, const int32_t format)
1906{
1907 // Check for adding entries in other packages... for now we do
1908 // nothing. We need to do the right thing here to support skinning.
1909 uint32_t rid = mAssets->getIncludedResources()
1910 .identifierForName(name.string(), name.size(),
1911 type.string(), type.size(),
1912 package.string(), package.size());
1913 if (rid != 0) {
1914 return NO_ERROR;
1915 }
1916
1917#if 0
1918 if (name == String16("left")) {
1919 printf("Adding bag left: file=%s, line=%d, type=%s\n",
1920 sourcePos.file.striing(), sourcePos.line, String8(type).string());
1921 }
1922#endif
1923 sp<Entry> e = getEntry(package, type, name, sourcePos, replace, params);
1924 if (e == NULL) {
1925 return UNKNOWN_ERROR;
1926 }
1927
1928 // If a parent is explicitly specified, set it.
1929 if (bagParent.size() > 0) {
1930 e->setParent(bagParent);
1931 }
1932
1933 const bool first = e->getBag().indexOfKey(bagKey) < 0;
1934 status_t err = e->addToBag(sourcePos, bagKey, value, style, replace, isId, format);
1935 if (err == NO_ERROR && first) {
1936 mNumLocal++;
1937 }
1938 return err;
1939}
1940
1941bool ResourceTable::hasBagOrEntry(const String16& package,
1942 const String16& type,
1943 const String16& name) const
1944{
1945 // First look for this in the included resources...
1946 uint32_t rid = mAssets->getIncludedResources()
1947 .identifierForName(name.string(), name.size(),
1948 type.string(), type.size(),
1949 package.string(), package.size());
1950 if (rid != 0) {
1951 return true;
1952 }
1953
1954 sp<Package> p = mPackages.valueFor(package);
1955 if (p != NULL) {
1956 sp<Type> t = p->getTypes().valueFor(type);
1957 if (t != NULL) {
1958 sp<ConfigList> c = t->getConfigs().valueFor(name);
1959 if (c != NULL) return true;
1960 }
1961 }
1962
1963 return false;
1964}
1965
1966bool ResourceTable::hasBagOrEntry(const String16& package,
1967 const String16& type,
1968 const String16& name,
1969 const ResTable_config& config) const
1970{
1971 // First look for this in the included resources...
1972 uint32_t rid = mAssets->getIncludedResources()
1973 .identifierForName(name.string(), name.size(),
1974 type.string(), type.size(),
1975 package.string(), package.size());
1976 if (rid != 0) {
1977 return true;
1978 }
1979
1980 sp<Package> p = mPackages.valueFor(package);
1981 if (p != NULL) {
1982 sp<Type> t = p->getTypes().valueFor(type);
1983 if (t != NULL) {
1984 sp<ConfigList> c = t->getConfigs().valueFor(name);
1985 if (c != NULL) {
1986 sp<Entry> e = c->getEntries().valueFor(config);
1987 if (e != NULL) {
1988 return true;
1989 }
1990 }
1991 }
1992 }
1993
1994 return false;
1995}
1996
1997bool ResourceTable::hasBagOrEntry(const String16& ref,
1998 const String16* defType,
1999 const String16* defPackage)
2000{
2001 String16 package, type, name;
2002 if (!ResTable::expandResourceRef(ref.string(), ref.size(), &package, &type, &name,
2003 defType, defPackage ? defPackage:&mAssetsPackage, NULL)) {
2004 return false;
2005 }
2006 return hasBagOrEntry(package, type, name);
2007}
2008
2009bool ResourceTable::appendComment(const String16& package,
2010 const String16& type,
2011 const String16& name,
2012 const String16& comment,
2013 bool onlyIfEmpty)
2014{
2015 if (comment.size() <= 0) {
2016 return true;
2017 }
2018
2019 sp<Package> p = mPackages.valueFor(package);
2020 if (p != NULL) {
2021 sp<Type> t = p->getTypes().valueFor(type);
2022 if (t != NULL) {
2023 sp<ConfigList> c = t->getConfigs().valueFor(name);
2024 if (c != NULL) {
2025 c->appendComment(comment, onlyIfEmpty);
2026 return true;
2027 }
2028 }
2029 }
2030 return false;
2031}
2032
2033bool ResourceTable::appendTypeComment(const String16& package,
2034 const String16& type,
2035 const String16& name,
2036 const String16& comment)
2037{
2038 if (comment.size() <= 0) {
2039 return true;
2040 }
2041
2042 sp<Package> p = mPackages.valueFor(package);
2043 if (p != NULL) {
2044 sp<Type> t = p->getTypes().valueFor(type);
2045 if (t != NULL) {
2046 sp<ConfigList> c = t->getConfigs().valueFor(name);
2047 if (c != NULL) {
2048 c->appendTypeComment(comment);
2049 return true;
2050 }
2051 }
2052 }
2053 return false;
2054}
2055
2056void ResourceTable::canAddEntry(const SourcePos& pos,
2057 const String16& package, const String16& type, const String16& name)
2058{
2059 sp<Type> t = getType(package, type, pos);
2060 if (t != NULL) {
2061 t->canAddEntry(name);
2062 }
2063}
2064
2065size_t ResourceTable::size() const {
2066 return mPackages.size();
2067}
2068
2069size_t ResourceTable::numLocalResources() const {
2070 return mNumLocal;
2071}
2072
2073bool ResourceTable::hasResources() const {
2074 return mNumLocal > 0;
2075}
2076
Adam Lesinski27f69f42014-08-21 13:19:12 -07002077sp<AaptFile> ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& filter,
2078 const bool isBase)
Adam Lesinski282e1812014-01-23 18:17:42 -08002079{
2080 sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
Adam Lesinski27f69f42014-08-21 13:19:12 -07002081 status_t err = flatten(bundle, filter, data, isBase);
Adam Lesinski282e1812014-01-23 18:17:42 -08002082 return err == NO_ERROR ? data : NULL;
2083}
2084
2085inline uint32_t ResourceTable::getResId(const sp<Package>& p,
2086 const sp<Type>& t,
2087 uint32_t nameId)
2088{
2089 return makeResId(p->getAssignedId(), t->getIndex(), nameId);
2090}
2091
2092uint32_t ResourceTable::getResId(const String16& package,
2093 const String16& type,
2094 const String16& name,
2095 bool onlyPublic) const
2096{
2097 uint32_t id = ResourceIdCache::lookup(package, type, name, onlyPublic);
2098 if (id != 0) return id; // cache hit
2099
Adam Lesinski282e1812014-01-23 18:17:42 -08002100 // First look for this in the included resources...
2101 uint32_t specFlags = 0;
2102 uint32_t rid = mAssets->getIncludedResources()
2103 .identifierForName(name.string(), name.size(),
2104 type.string(), type.size(),
2105 package.string(), package.size(),
2106 &specFlags);
2107 if (rid != 0) {
2108 if (onlyPublic) {
2109 if ((specFlags & ResTable_typeSpec::SPEC_PUBLIC) == 0) {
2110 return 0;
2111 }
2112 }
2113
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002114 return ResourceIdCache::store(package, type, name, onlyPublic, rid);
Adam Lesinski282e1812014-01-23 18:17:42 -08002115 }
2116
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002117 sp<Package> p = mPackages.valueFor(package);
2118 if (p == NULL) return 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08002119 sp<Type> t = p->getTypes().valueFor(type);
2120 if (t == NULL) return 0;
2121 sp<ConfigList> c = t->getConfigs().valueFor(name);
2122 if (c == NULL) return 0;
2123 int32_t ei = c->getEntryIndex();
2124 if (ei < 0) return 0;
2125
2126 return ResourceIdCache::store(package, type, name, onlyPublic,
2127 getResId(p, t, ei));
2128}
2129
2130uint32_t ResourceTable::getResId(const String16& ref,
2131 const String16* defType,
2132 const String16* defPackage,
2133 const char** outErrorMsg,
2134 bool onlyPublic) const
2135{
2136 String16 package, type, name;
2137 bool refOnlyPublic = true;
2138 if (!ResTable::expandResourceRef(
2139 ref.string(), ref.size(), &package, &type, &name,
2140 defType, defPackage ? defPackage:&mAssetsPackage,
2141 outErrorMsg, &refOnlyPublic)) {
2142 NOISY(printf("Expanding resource: ref=%s\n",
2143 String8(ref).string()));
2144 NOISY(printf("Expanding resource: defType=%s\n",
2145 defType ? String8(*defType).string() : "NULL"));
2146 NOISY(printf("Expanding resource: defPackage=%s\n",
2147 defPackage ? String8(*defPackage).string() : "NULL"));
2148 NOISY(printf("Expanding resource: ref=%s\n", String8(ref).string()));
2149 NOISY(printf("Expanded resource: p=%s, t=%s, n=%s, res=0\n",
2150 String8(package).string(), String8(type).string(),
2151 String8(name).string()));
2152 return 0;
2153 }
2154 uint32_t res = getResId(package, type, name, onlyPublic && refOnlyPublic);
2155 NOISY(printf("Expanded resource: p=%s, t=%s, n=%s, res=%d\n",
2156 String8(package).string(), String8(type).string(),
2157 String8(name).string(), res));
2158 if (res == 0) {
2159 if (outErrorMsg)
2160 *outErrorMsg = "No resource found that matches the given name";
2161 }
2162 return res;
2163}
2164
2165bool ResourceTable::isValidResourceName(const String16& s)
2166{
2167 const char16_t* p = s.string();
2168 bool first = true;
2169 while (*p) {
2170 if ((*p >= 'a' && *p <= 'z')
2171 || (*p >= 'A' && *p <= 'Z')
2172 || *p == '_'
2173 || (!first && *p >= '0' && *p <= '9')) {
2174 first = false;
2175 p++;
2176 continue;
2177 }
2178 return false;
2179 }
2180 return true;
2181}
2182
2183bool ResourceTable::stringToValue(Res_value* outValue, StringPool* pool,
2184 const String16& str,
2185 bool preserveSpaces, bool coerceType,
2186 uint32_t attrID,
2187 const Vector<StringPool::entry_style_span>* style,
2188 String16* outStr, void* accessorCookie,
2189 uint32_t attrType, const String8* configTypeName,
2190 const ConfigDescription* config)
2191{
2192 String16 finalStr;
2193
2194 bool res = true;
2195 if (style == NULL || style->size() == 0) {
2196 // Text is not styled so it can be any type... let's figure it out.
2197 res = mAssets->getIncludedResources()
2198 .stringToValue(outValue, &finalStr, str.string(), str.size(), preserveSpaces,
2199 coerceType, attrID, NULL, &mAssetsPackage, this,
2200 accessorCookie, attrType);
2201 } else {
2202 // Styled text can only be a string, and while collecting the style
2203 // information we have already processed that string!
2204 outValue->size = sizeof(Res_value);
2205 outValue->res0 = 0;
2206 outValue->dataType = outValue->TYPE_STRING;
2207 outValue->data = 0;
2208 finalStr = str;
2209 }
2210
2211 if (!res) {
2212 return false;
2213 }
2214
2215 if (outValue->dataType == outValue->TYPE_STRING) {
2216 // Should do better merging styles.
2217 if (pool) {
2218 String8 configStr;
2219 if (config != NULL) {
2220 configStr = config->toString();
2221 } else {
2222 configStr = "(null)";
2223 }
2224 NOISY(printf("Adding to pool string style #%d config %s: %s\n",
2225 style != NULL ? style->size() : 0,
2226 configStr.string(), String8(finalStr).string()));
2227 if (style != NULL && style->size() > 0) {
2228 outValue->data = pool->add(finalStr, *style, configTypeName, config);
2229 } else {
2230 outValue->data = pool->add(finalStr, true, configTypeName, config);
2231 }
2232 } else {
2233 // Caller will fill this in later.
2234 outValue->data = 0;
2235 }
2236
2237 if (outStr) {
2238 *outStr = finalStr;
2239 }
2240
2241 }
2242
2243 return true;
2244}
2245
2246uint32_t ResourceTable::getCustomResource(
2247 const String16& package, const String16& type, const String16& name) const
2248{
2249 //printf("getCustomResource: %s %s %s\n", String8(package).string(),
2250 // String8(type).string(), String8(name).string());
2251 sp<Package> p = mPackages.valueFor(package);
2252 if (p == NULL) return 0;
2253 sp<Type> t = p->getTypes().valueFor(type);
2254 if (t == NULL) return 0;
2255 sp<ConfigList> c = t->getConfigs().valueFor(name);
2256 if (c == NULL) return 0;
2257 int32_t ei = c->getEntryIndex();
2258 if (ei < 0) return 0;
2259 return getResId(p, t, ei);
2260}
2261
2262uint32_t ResourceTable::getCustomResourceWithCreation(
2263 const String16& package, const String16& type, const String16& name,
2264 const bool createIfNotFound)
2265{
2266 uint32_t resId = getCustomResource(package, type, name);
2267 if (resId != 0 || !createIfNotFound) {
2268 return resId;
2269 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002270
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002271 if (mAssetsPackage != package) {
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002272 mCurrentXmlPos.error("creating resource for external package %s: %s/%s.",
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002273 String8(package).string(), String8(type).string(), String8(name).string());
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002274 if (package == String16("android")) {
2275 mCurrentXmlPos.printf("did you mean to use @+id instead of @+android:id?");
2276 }
2277 return 0;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002278 }
2279
2280 String16 value("false");
Adam Lesinski282e1812014-01-23 18:17:42 -08002281 status_t status = addEntry(mCurrentXmlPos, package, type, name, value, NULL, NULL, true);
2282 if (status == NO_ERROR) {
2283 resId = getResId(package, type, name);
2284 return resId;
2285 }
2286 return 0;
2287}
2288
2289uint32_t ResourceTable::getRemappedPackage(uint32_t origPackage) const
2290{
2291 return origPackage;
2292}
2293
2294bool ResourceTable::getAttributeType(uint32_t attrID, uint32_t* outType)
2295{
2296 //printf("getAttributeType #%08x\n", attrID);
2297 Res_value value;
2298 if (getItemValue(attrID, ResTable_map::ATTR_TYPE, &value)) {
2299 //printf("getAttributeType #%08x (%s): #%08x\n", attrID,
2300 // String8(getEntry(attrID)->getName()).string(), value.data);
2301 *outType = value.data;
2302 return true;
2303 }
2304 return false;
2305}
2306
2307bool ResourceTable::getAttributeMin(uint32_t attrID, uint32_t* outMin)
2308{
2309 //printf("getAttributeMin #%08x\n", attrID);
2310 Res_value value;
2311 if (getItemValue(attrID, ResTable_map::ATTR_MIN, &value)) {
2312 *outMin = value.data;
2313 return true;
2314 }
2315 return false;
2316}
2317
2318bool ResourceTable::getAttributeMax(uint32_t attrID, uint32_t* outMax)
2319{
2320 //printf("getAttributeMax #%08x\n", attrID);
2321 Res_value value;
2322 if (getItemValue(attrID, ResTable_map::ATTR_MAX, &value)) {
2323 *outMax = value.data;
2324 return true;
2325 }
2326 return false;
2327}
2328
2329uint32_t ResourceTable::getAttributeL10N(uint32_t attrID)
2330{
2331 //printf("getAttributeL10N #%08x\n", attrID);
2332 Res_value value;
2333 if (getItemValue(attrID, ResTable_map::ATTR_L10N, &value)) {
2334 return value.data;
2335 }
2336 return ResTable_map::L10N_NOT_REQUIRED;
2337}
2338
2339bool ResourceTable::getLocalizationSetting()
2340{
2341 return mBundle->getRequireLocalization();
2342}
2343
2344void ResourceTable::reportError(void* accessorCookie, const char* fmt, ...)
2345{
2346 if (accessorCookie != NULL && fmt != NULL) {
2347 AccessorCookie* ac = (AccessorCookie*)accessorCookie;
2348 int retval=0;
2349 char buf[1024];
2350 va_list ap;
2351 va_start(ap, fmt);
2352 retval = vsnprintf(buf, sizeof(buf), fmt, ap);
2353 va_end(ap);
2354 ac->sourcePos.error("Error: %s (at '%s' with value '%s').\n",
2355 buf, ac->attr.string(), ac->value.string());
2356 }
2357}
2358
2359bool ResourceTable::getAttributeKeys(
2360 uint32_t attrID, Vector<String16>* outKeys)
2361{
2362 sp<const Entry> e = getEntry(attrID);
2363 if (e != NULL) {
2364 const size_t N = e->getBag().size();
2365 for (size_t i=0; i<N; i++) {
2366 const String16& key = e->getBag().keyAt(i);
2367 if (key.size() > 0 && key.string()[0] != '^') {
2368 outKeys->add(key);
2369 }
2370 }
2371 return true;
2372 }
2373 return false;
2374}
2375
2376bool ResourceTable::getAttributeEnum(
2377 uint32_t attrID, const char16_t* name, size_t nameLen,
2378 Res_value* outValue)
2379{
2380 //printf("getAttributeEnum #%08x %s\n", attrID, String8(name, nameLen).string());
2381 String16 nameStr(name, nameLen);
2382 sp<const Entry> e = getEntry(attrID);
2383 if (e != NULL) {
2384 const size_t N = e->getBag().size();
2385 for (size_t i=0; i<N; i++) {
2386 //printf("Comparing %s to %s\n", String8(name, nameLen).string(),
2387 // String8(e->getBag().keyAt(i)).string());
2388 if (e->getBag().keyAt(i) == nameStr) {
2389 return getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, outValue);
2390 }
2391 }
2392 }
2393 return false;
2394}
2395
2396bool ResourceTable::getAttributeFlags(
2397 uint32_t attrID, const char16_t* name, size_t nameLen,
2398 Res_value* outValue)
2399{
2400 outValue->dataType = Res_value::TYPE_INT_HEX;
2401 outValue->data = 0;
2402
2403 //printf("getAttributeFlags #%08x %s\n", attrID, String8(name, nameLen).string());
2404 String16 nameStr(name, nameLen);
2405 sp<const Entry> e = getEntry(attrID);
2406 if (e != NULL) {
2407 const size_t N = e->getBag().size();
2408
2409 const char16_t* end = name + nameLen;
2410 const char16_t* pos = name;
2411 while (pos < end) {
2412 const char16_t* start = pos;
2413 while (pos < end && *pos != '|') {
2414 pos++;
2415 }
2416
2417 String16 nameStr(start, pos-start);
2418 size_t i;
2419 for (i=0; i<N; i++) {
2420 //printf("Comparing \"%s\" to \"%s\"\n", String8(nameStr).string(),
2421 // String8(e->getBag().keyAt(i)).string());
2422 if (e->getBag().keyAt(i) == nameStr) {
2423 Res_value val;
2424 bool got = getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, &val);
2425 if (!got) {
2426 return false;
2427 }
2428 //printf("Got value: 0x%08x\n", val.data);
2429 outValue->data |= val.data;
2430 break;
2431 }
2432 }
2433
2434 if (i >= N) {
2435 // Didn't find this flag identifier.
2436 return false;
2437 }
2438 pos++;
2439 }
2440
2441 return true;
2442 }
2443 return false;
2444}
2445
2446status_t ResourceTable::assignResourceIds()
2447{
2448 const size_t N = mOrderedPackages.size();
2449 size_t pi;
2450 status_t firstError = NO_ERROR;
2451
2452 // First generate all bag attributes and assign indices.
2453 for (pi=0; pi<N; pi++) {
2454 sp<Package> p = mOrderedPackages.itemAt(pi);
2455 if (p == NULL || p->getTypes().size() == 0) {
2456 // Empty, skip!
2457 continue;
2458 }
2459
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002460 // This has no sense for packages being built as AppFeature (aka with a non-zero offset).
Adam Lesinski282e1812014-01-23 18:17:42 -08002461 status_t err = p->applyPublicTypeOrder();
2462 if (err != NO_ERROR && firstError == NO_ERROR) {
2463 firstError = err;
2464 }
2465
2466 // Generate attributes...
2467 const size_t N = p->getOrderedTypes().size();
2468 size_t ti;
2469 for (ti=0; ti<N; ti++) {
2470 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2471 if (t == NULL) {
2472 continue;
2473 }
2474 const size_t N = t->getOrderedConfigs().size();
2475 for (size_t ci=0; ci<N; ci++) {
2476 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2477 if (c == NULL) {
2478 continue;
2479 }
2480 const size_t N = c->getEntries().size();
2481 for (size_t ei=0; ei<N; ei++) {
2482 sp<Entry> e = c->getEntries().valueAt(ei);
2483 if (e == NULL) {
2484 continue;
2485 }
2486 status_t err = e->generateAttributes(this, p->getName());
2487 if (err != NO_ERROR && firstError == NO_ERROR) {
2488 firstError = err;
2489 }
2490 }
2491 }
2492 }
2493
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002494 uint32_t typeIdOffset = 0;
2495 if (mPackageType == AppFeature && p->getName() == mAssetsPackage) {
2496 typeIdOffset = mTypeIdOffset;
2497 }
2498
Adam Lesinski282e1812014-01-23 18:17:42 -08002499 const SourcePos unknown(String8("????"), 0);
2500 sp<Type> attr = p->getType(String16("attr"), unknown);
2501
2502 // Assign indices...
Adam Lesinski43a0df02014-08-18 17:14:57 -07002503 const size_t typeCount = p->getOrderedTypes().size();
2504 for (size_t ti = 0; ti < typeCount; ti++) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002505 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2506 if (t == NULL) {
2507 continue;
2508 }
Adam Lesinski43a0df02014-08-18 17:14:57 -07002509
Adam Lesinski282e1812014-01-23 18:17:42 -08002510 err = t->applyPublicEntryOrder();
2511 if (err != NO_ERROR && firstError == NO_ERROR) {
2512 firstError = err;
2513 }
2514
2515 const size_t N = t->getOrderedConfigs().size();
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002516 t->setIndex(ti + 1 + typeIdOffset);
Adam Lesinski282e1812014-01-23 18:17:42 -08002517
2518 LOG_ALWAYS_FATAL_IF(ti == 0 && attr != t,
2519 "First type is not attr!");
2520
2521 for (size_t ei=0; ei<N; ei++) {
2522 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ei);
2523 if (c == NULL) {
2524 continue;
2525 }
2526 c->setEntryIndex(ei);
2527 }
2528 }
2529
2530 // Assign resource IDs to keys in bags...
Adam Lesinski43a0df02014-08-18 17:14:57 -07002531 for (size_t ti = 0; ti < typeCount; ti++) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002532 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2533 if (t == NULL) {
2534 continue;
2535 }
2536 const size_t N = t->getOrderedConfigs().size();
2537 for (size_t ci=0; ci<N; ci++) {
2538 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2539 //printf("Ordered config #%d: %p\n", ci, c.get());
2540 const size_t N = c->getEntries().size();
2541 for (size_t ei=0; ei<N; ei++) {
2542 sp<Entry> e = c->getEntries().valueAt(ei);
2543 if (e == NULL) {
2544 continue;
2545 }
2546 status_t err = e->assignResourceIds(this, p->getName());
2547 if (err != NO_ERROR && firstError == NO_ERROR) {
2548 firstError = err;
2549 }
2550 }
2551 }
2552 }
2553 }
2554 return firstError;
2555}
2556
2557status_t ResourceTable::addSymbols(const sp<AaptSymbols>& outSymbols) {
2558 const size_t N = mOrderedPackages.size();
2559 size_t pi;
2560
2561 for (pi=0; pi<N; pi++) {
2562 sp<Package> p = mOrderedPackages.itemAt(pi);
2563 if (p->getTypes().size() == 0) {
2564 // Empty, skip!
2565 continue;
2566 }
2567
2568 const size_t N = p->getOrderedTypes().size();
2569 size_t ti;
2570
2571 for (ti=0; ti<N; ti++) {
2572 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2573 if (t == NULL) {
2574 continue;
2575 }
2576 const size_t N = t->getOrderedConfigs().size();
Adam Lesinski3fb8c9b2014-09-09 16:05:10 -07002577 sp<AaptSymbols> typeSymbols =
2578 outSymbols->addNestedSymbol(String8(t->getName()), t->getPos());
2579 if (typeSymbols == NULL) {
2580 return UNKNOWN_ERROR;
2581 }
2582
Adam Lesinski282e1812014-01-23 18:17:42 -08002583 for (size_t ci=0; ci<N; ci++) {
2584 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2585 if (c == NULL) {
2586 continue;
2587 }
2588 uint32_t rid = getResId(p, t, ci);
2589 if (rid == 0) {
2590 return UNKNOWN_ERROR;
2591 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002592 if (Res_GETPACKAGE(rid) + 1 == p->getAssignedId()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002593 typeSymbols->addSymbol(String8(c->getName()), rid, c->getPos());
2594
2595 String16 comment(c->getComment());
2596 typeSymbols->appendComment(String8(c->getName()), comment, c->getPos());
Adam Lesinski8ff15b42013-10-07 16:54:01 -07002597 //printf("Type symbol [%08x] %s comment: %s\n", rid,
2598 // String8(c->getName()).string(), String8(comment).string());
Adam Lesinski282e1812014-01-23 18:17:42 -08002599 comment = c->getTypeComment();
2600 typeSymbols->appendTypeComment(String8(c->getName()), comment);
Adam Lesinski282e1812014-01-23 18:17:42 -08002601 }
2602 }
2603 }
2604 }
2605 return NO_ERROR;
2606}
2607
2608
2609void
Adam Lesinskia01a9372014-03-20 18:04:57 -07002610ResourceTable::addLocalization(const String16& name, const String8& locale, const SourcePos& src)
Adam Lesinski282e1812014-01-23 18:17:42 -08002611{
Adam Lesinskia01a9372014-03-20 18:04:57 -07002612 mLocalizations[name][locale] = src;
Adam Lesinski282e1812014-01-23 18:17:42 -08002613}
2614
2615
2616/*!
2617 * Flag various sorts of localization problems. '+' indicates checks already implemented;
2618 * '-' indicates checks that will be implemented in the future.
2619 *
2620 * + A localized string for which no default-locale version exists => warning
2621 * + A string for which no version in an explicitly-requested locale exists => warning
2622 * + A localized translation of an translateable="false" string => warning
2623 * - A localized string not provided in every locale used by the table
2624 */
2625status_t
2626ResourceTable::validateLocalizations(void)
2627{
2628 status_t err = NO_ERROR;
2629 const String8 defaultLocale;
2630
2631 // For all strings...
Adam Lesinskia01a9372014-03-20 18:04:57 -07002632 for (map<String16, map<String8, SourcePos> >::iterator nameIter = mLocalizations.begin();
Adam Lesinski282e1812014-01-23 18:17:42 -08002633 nameIter != mLocalizations.end();
2634 nameIter++) {
Adam Lesinskia01a9372014-03-20 18:04:57 -07002635 const map<String8, SourcePos>& configSrcMap = nameIter->second;
Adam Lesinski282e1812014-01-23 18:17:42 -08002636
2637 // Look for strings with no default localization
Adam Lesinskia01a9372014-03-20 18:04:57 -07002638 if (configSrcMap.count(defaultLocale) == 0) {
2639 SourcePos().warning("string '%s' has no default translation.",
2640 String8(nameIter->first).string());
2641 if (mBundle->getVerbose()) {
2642 for (map<String8, SourcePos>::const_iterator locales = configSrcMap.begin();
2643 locales != configSrcMap.end();
2644 locales++) {
2645 locales->second.printf("locale %s found", locales->first.string());
2646 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002647 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002648 // !!! TODO: throw an error here in some circumstances
2649 }
2650
2651 // Check that all requested localizations are present for this string
Adam Lesinskifab50872014-04-16 14:40:42 -07002652 if (mBundle->getConfigurations().size() > 0 && mBundle->getRequireLocalization()) {
2653 const char* allConfigs = mBundle->getConfigurations().string();
Adam Lesinski282e1812014-01-23 18:17:42 -08002654 const char* start = allConfigs;
2655 const char* comma;
2656
Adam Lesinskia01a9372014-03-20 18:04:57 -07002657 set<String8> missingConfigs;
2658 AaptLocaleValue locale;
Adam Lesinski282e1812014-01-23 18:17:42 -08002659 do {
2660 String8 config;
2661 comma = strchr(start, ',');
2662 if (comma != NULL) {
2663 config.setTo(start, comma - start);
2664 start = comma + 1;
2665 } else {
2666 config.setTo(start);
2667 }
2668
Adam Lesinskia01a9372014-03-20 18:04:57 -07002669 if (!locale.initFromFilterString(config)) {
2670 continue;
2671 }
2672
Anton Krumina2ef5c02014-03-12 14:46:44 -07002673 // don't bother with the pseudolocale "en_XA" or "ar_XB"
2674 if (config != "en_XA" && config != "ar_XB") {
Adam Lesinskia01a9372014-03-20 18:04:57 -07002675 if (configSrcMap.find(config) == configSrcMap.end()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002676 // okay, no specific localization found. it's possible that we are
2677 // requiring a specific regional localization [e.g. de_DE] but there is an
2678 // available string in the generic language localization [e.g. de];
2679 // consider that string to have fulfilled the localization requirement.
2680 String8 region(config.string(), 2);
Adam Lesinskia01a9372014-03-20 18:04:57 -07002681 if (configSrcMap.find(region) == configSrcMap.end() &&
2682 configSrcMap.count(defaultLocale) == 0) {
2683 missingConfigs.insert(config);
Adam Lesinski282e1812014-01-23 18:17:42 -08002684 }
2685 }
2686 }
Adam Lesinskia01a9372014-03-20 18:04:57 -07002687 } while (comma != NULL);
2688
2689 if (!missingConfigs.empty()) {
2690 String8 configStr;
2691 for (set<String8>::iterator iter = missingConfigs.begin();
2692 iter != missingConfigs.end();
2693 iter++) {
2694 configStr.appendFormat(" %s", iter->string());
2695 }
2696 SourcePos().warning("string '%s' is missing %u required localizations:%s",
2697 String8(nameIter->first).string(),
2698 (unsigned int)missingConfigs.size(),
2699 configStr.string());
2700 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002701 }
2702 }
2703
2704 return err;
2705}
2706
Adam Lesinski27f69f42014-08-21 13:19:12 -07002707status_t ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& filter,
2708 const sp<AaptFile>& dest,
2709 const bool isBase)
Adam Lesinski282e1812014-01-23 18:17:42 -08002710{
Adam Lesinski282e1812014-01-23 18:17:42 -08002711 const ConfigDescription nullConfig;
2712
2713 const size_t N = mOrderedPackages.size();
2714 size_t pi;
2715
2716 const static String16 mipmap16("mipmap");
2717
2718 bool useUTF8 = !bundle->getUTF16StringsOption();
2719
Adam Lesinskide898ff2014-01-29 18:20:45 -08002720 // The libraries this table references.
2721 Vector<sp<Package> > libraryPackages;
Adam Lesinski6022deb2014-08-20 14:59:19 -07002722 const ResTable& table = mAssets->getIncludedResources();
2723 const size_t basePackageCount = table.getBasePackageCount();
2724 for (size_t i = 0; i < basePackageCount; i++) {
2725 size_t packageId = table.getBasePackageId(i);
2726 String16 packageName(table.getBasePackageName(i));
2727 if (packageId > 0x01 && packageId != 0x7f &&
2728 packageName != String16("android")) {
2729 libraryPackages.add(sp<Package>(new Package(packageName, packageId)));
2730 }
2731 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08002732
Adam Lesinski282e1812014-01-23 18:17:42 -08002733 // Iterate through all data, collecting all values (strings,
2734 // references, etc).
2735 StringPool valueStrings(useUTF8);
2736 Vector<sp<Entry> > allEntries;
2737 for (pi=0; pi<N; pi++) {
2738 sp<Package> p = mOrderedPackages.itemAt(pi);
2739 if (p->getTypes().size() == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002740 continue;
2741 }
2742
2743 StringPool typeStrings(useUTF8);
2744 StringPool keyStrings(useUTF8);
2745
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002746 ssize_t stringsAdded = 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08002747 const size_t N = p->getOrderedTypes().size();
2748 for (size_t ti=0; ti<N; ti++) {
2749 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2750 if (t == NULL) {
2751 typeStrings.add(String16("<empty>"), false);
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002752 stringsAdded++;
Adam Lesinski282e1812014-01-23 18:17:42 -08002753 continue;
2754 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002755
2756 while (stringsAdded < t->getIndex() - 1) {
2757 typeStrings.add(String16("<empty>"), false);
2758 stringsAdded++;
2759 }
2760
Adam Lesinski282e1812014-01-23 18:17:42 -08002761 const String16 typeName(t->getName());
2762 typeStrings.add(typeName, false);
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002763 stringsAdded++;
Adam Lesinski282e1812014-01-23 18:17:42 -08002764
2765 // This is a hack to tweak the sorting order of the final strings,
2766 // to put stuff that is generally not language-specific first.
2767 String8 configTypeName(typeName);
2768 if (configTypeName == "drawable" || configTypeName == "layout"
2769 || configTypeName == "color" || configTypeName == "anim"
2770 || configTypeName == "interpolator" || configTypeName == "animator"
2771 || configTypeName == "xml" || configTypeName == "menu"
2772 || configTypeName == "mipmap" || configTypeName == "raw") {
2773 configTypeName = "1complex";
2774 } else {
2775 configTypeName = "2value";
2776 }
2777
Adam Lesinski27f69f42014-08-21 13:19:12 -07002778 // mipmaps don't get filtered, so they will
2779 // allways end up in the base. Make sure they
2780 // don't end up in a split.
2781 if (typeName == mipmap16 && !isBase) {
2782 continue;
2783 }
2784
Adam Lesinski282e1812014-01-23 18:17:42 -08002785 const bool filterable = (typeName != mipmap16);
2786
2787 const size_t N = t->getOrderedConfigs().size();
2788 for (size_t ci=0; ci<N; ci++) {
2789 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2790 if (c == NULL) {
2791 continue;
2792 }
2793 const size_t N = c->getEntries().size();
2794 for (size_t ei=0; ei<N; ei++) {
2795 ConfigDescription config = c->getEntries().keyAt(ei);
Adam Lesinskifab50872014-04-16 14:40:42 -07002796 if (filterable && !filter->match(config)) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002797 continue;
2798 }
2799 sp<Entry> e = c->getEntries().valueAt(ei);
2800 if (e == NULL) {
2801 continue;
2802 }
2803 e->setNameIndex(keyStrings.add(e->getName(), true));
2804
2805 // If this entry has no values for other configs,
2806 // and is the default config, then it is special. Otherwise
2807 // we want to add it with the config info.
2808 ConfigDescription* valueConfig = NULL;
2809 if (N != 1 || config == nullConfig) {
2810 valueConfig = &config;
2811 }
2812
2813 status_t err = e->prepareFlatten(&valueStrings, this,
2814 &configTypeName, &config);
2815 if (err != NO_ERROR) {
2816 return err;
2817 }
2818 allEntries.add(e);
2819 }
2820 }
2821 }
2822
2823 p->setTypeStrings(typeStrings.createStringBlock());
2824 p->setKeyStrings(keyStrings.createStringBlock());
2825 }
2826
2827 if (bundle->getOutputAPKFile() != NULL) {
2828 // Now we want to sort the value strings for better locality. This will
2829 // cause the positions of the strings to change, so we need to go back
2830 // through out resource entries and update them accordingly. Only need
2831 // to do this if actually writing the output file.
2832 valueStrings.sortByConfig();
2833 for (pi=0; pi<allEntries.size(); pi++) {
2834 allEntries[pi]->remapStringValue(&valueStrings);
2835 }
2836 }
2837
2838 ssize_t strAmt = 0;
Adam Lesinskide898ff2014-01-29 18:20:45 -08002839
Adam Lesinski282e1812014-01-23 18:17:42 -08002840 // Now build the array of package chunks.
2841 Vector<sp<AaptFile> > flatPackages;
2842 for (pi=0; pi<N; pi++) {
2843 sp<Package> p = mOrderedPackages.itemAt(pi);
2844 if (p->getTypes().size() == 0) {
2845 // Empty, skip!
2846 continue;
2847 }
2848
2849 const size_t N = p->getTypeStrings().size();
2850
2851 const size_t baseSize = sizeof(ResTable_package);
2852
2853 // Start the package data.
2854 sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
2855 ResTable_package* header = (ResTable_package*)data->editData(baseSize);
2856 if (header == NULL) {
2857 fprintf(stderr, "ERROR: out of memory creating ResTable_package\n");
2858 return NO_MEMORY;
2859 }
2860 memset(header, 0, sizeof(*header));
2861 header->header.type = htods(RES_TABLE_PACKAGE_TYPE);
2862 header->header.headerSize = htods(sizeof(*header));
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002863 header->id = htodl(static_cast<uint32_t>(p->getAssignedId()));
Adam Lesinski282e1812014-01-23 18:17:42 -08002864 strcpy16_htod(header->name, p->getName().string());
2865
2866 // Write the string blocks.
2867 const size_t typeStringsStart = data->getSize();
2868 sp<AaptFile> strFile = p->getTypeStringsData();
2869 ssize_t amt = data->writeData(strFile->getData(), strFile->getSize());
2870 #if PRINT_STRING_METRICS
2871 fprintf(stderr, "**** type strings: %d\n", amt);
2872 #endif
2873 strAmt += amt;
2874 if (amt < 0) {
2875 return amt;
2876 }
2877 const size_t keyStringsStart = data->getSize();
2878 strFile = p->getKeyStringsData();
2879 amt = data->writeData(strFile->getData(), strFile->getSize());
2880 #if PRINT_STRING_METRICS
2881 fprintf(stderr, "**** key strings: %d\n", amt);
2882 #endif
2883 strAmt += amt;
2884 if (amt < 0) {
2885 return amt;
2886 }
2887
Adam Lesinski27f69f42014-08-21 13:19:12 -07002888 if (isBase) {
2889 status_t err = flattenLibraryTable(data, libraryPackages);
2890 if (err != NO_ERROR) {
2891 fprintf(stderr, "ERROR: failed to write library table\n");
2892 return err;
2893 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08002894 }
2895
Adam Lesinski282e1812014-01-23 18:17:42 -08002896 // Build the type chunks inside of this package.
2897 for (size_t ti=0; ti<N; ti++) {
2898 // Retrieve them in the same order as the type string block.
2899 size_t len;
2900 String16 typeName(p->getTypeStrings().stringAt(ti, &len));
2901 sp<Type> t = p->getTypes().valueFor(typeName);
2902 LOG_ALWAYS_FATAL_IF(t == NULL && typeName != String16("<empty>"),
2903 "Type name %s not found",
2904 String8(typeName).string());
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002905 if (t == NULL) {
2906 continue;
2907 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002908 const bool filterable = (typeName != mipmap16);
Adam Lesinski27f69f42014-08-21 13:19:12 -07002909 const bool skipEntireType = (typeName == mipmap16 && !isBase);
Adam Lesinski282e1812014-01-23 18:17:42 -08002910
2911 const size_t N = t != NULL ? t->getOrderedConfigs().size() : 0;
2912
2913 // Until a non-NO_ENTRY value has been written for a resource,
2914 // that resource is invalid; validResources[i] represents
2915 // the item at t->getOrderedConfigs().itemAt(i).
2916 Vector<bool> validResources;
2917 validResources.insertAt(false, 0, N);
2918
2919 // First write the typeSpec chunk, containing information about
2920 // each resource entry in this type.
2921 {
2922 const size_t typeSpecSize = sizeof(ResTable_typeSpec) + sizeof(uint32_t)*N;
2923 const size_t typeSpecStart = data->getSize();
2924 ResTable_typeSpec* tsHeader = (ResTable_typeSpec*)
2925 (((uint8_t*)data->editData(typeSpecStart+typeSpecSize)) + typeSpecStart);
2926 if (tsHeader == NULL) {
2927 fprintf(stderr, "ERROR: out of memory creating ResTable_typeSpec\n");
2928 return NO_MEMORY;
2929 }
2930 memset(tsHeader, 0, sizeof(*tsHeader));
2931 tsHeader->header.type = htods(RES_TABLE_TYPE_SPEC_TYPE);
2932 tsHeader->header.headerSize = htods(sizeof(*tsHeader));
2933 tsHeader->header.size = htodl(typeSpecSize);
2934 tsHeader->id = ti+1;
2935 tsHeader->entryCount = htodl(N);
2936
2937 uint32_t* typeSpecFlags = (uint32_t*)
2938 (((uint8_t*)data->editData())
2939 + typeSpecStart + sizeof(ResTable_typeSpec));
2940 memset(typeSpecFlags, 0, sizeof(uint32_t)*N);
2941
2942 for (size_t ei=0; ei<N; ei++) {
2943 sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
2944 if (cl->getPublic()) {
2945 typeSpecFlags[ei] |= htodl(ResTable_typeSpec::SPEC_PUBLIC);
2946 }
Adam Lesinski27f69f42014-08-21 13:19:12 -07002947
2948 if (skipEntireType) {
2949 continue;
2950 }
2951
Adam Lesinski282e1812014-01-23 18:17:42 -08002952 const size_t CN = cl->getEntries().size();
2953 for (size_t ci=0; ci<CN; ci++) {
Adam Lesinskifab50872014-04-16 14:40:42 -07002954 if (filterable && !filter->match(cl->getEntries().keyAt(ci))) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002955 continue;
2956 }
2957 for (size_t cj=ci+1; cj<CN; cj++) {
Adam Lesinskifab50872014-04-16 14:40:42 -07002958 if (filterable && !filter->match(cl->getEntries().keyAt(cj))) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002959 continue;
2960 }
2961 typeSpecFlags[ei] |= htodl(
2962 cl->getEntries().keyAt(ci).diff(cl->getEntries().keyAt(cj)));
2963 }
2964 }
2965 }
2966 }
2967
Adam Lesinski27f69f42014-08-21 13:19:12 -07002968 if (skipEntireType) {
2969 continue;
2970 }
2971
Adam Lesinski282e1812014-01-23 18:17:42 -08002972 // We need to write one type chunk for each configuration for
2973 // which we have entries in this type.
2974 const size_t NC = t->getUniqueConfigs().size();
2975
2976 const size_t typeSize = sizeof(ResTable_type) + sizeof(uint32_t)*N;
2977
2978 for (size_t ci=0; ci<NC; ci++) {
2979 ConfigDescription config = t->getUniqueConfigs().itemAt(ci);
2980
2981 NOISY(printf("Writing config %d config: imsi:%d/%d lang:%c%c cnt:%c%c "
2982 "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
2983 "sw%ddp w%ddp h%ddp dir:%d\n",
2984 ti+1,
2985 config.mcc, config.mnc,
2986 config.language[0] ? config.language[0] : '-',
2987 config.language[1] ? config.language[1] : '-',
2988 config.country[0] ? config.country[0] : '-',
2989 config.country[1] ? config.country[1] : '-',
2990 config.orientation,
2991 config.uiMode,
2992 config.touchscreen,
2993 config.density,
2994 config.keyboard,
2995 config.inputFlags,
2996 config.navigation,
2997 config.screenWidth,
2998 config.screenHeight,
2999 config.smallestScreenWidthDp,
3000 config.screenWidthDp,
3001 config.screenHeightDp,
3002 config.layoutDirection));
3003
Adam Lesinskifab50872014-04-16 14:40:42 -07003004 if (filterable && !filter->match(config)) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003005 continue;
3006 }
3007
3008 const size_t typeStart = data->getSize();
3009
3010 ResTable_type* tHeader = (ResTable_type*)
3011 (((uint8_t*)data->editData(typeStart+typeSize)) + typeStart);
3012 if (tHeader == NULL) {
3013 fprintf(stderr, "ERROR: out of memory creating ResTable_type\n");
3014 return NO_MEMORY;
3015 }
3016
3017 memset(tHeader, 0, sizeof(*tHeader));
3018 tHeader->header.type = htods(RES_TABLE_TYPE_TYPE);
3019 tHeader->header.headerSize = htods(sizeof(*tHeader));
3020 tHeader->id = ti+1;
3021 tHeader->entryCount = htodl(N);
3022 tHeader->entriesStart = htodl(typeSize);
3023 tHeader->config = config;
3024 NOISY(printf("Writing type %d config: imsi:%d/%d lang:%c%c cnt:%c%c "
3025 "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
3026 "sw%ddp w%ddp h%ddp dir:%d\n",
3027 ti+1,
3028 tHeader->config.mcc, tHeader->config.mnc,
3029 tHeader->config.language[0] ? tHeader->config.language[0] : '-',
3030 tHeader->config.language[1] ? tHeader->config.language[1] : '-',
3031 tHeader->config.country[0] ? tHeader->config.country[0] : '-',
3032 tHeader->config.country[1] ? tHeader->config.country[1] : '-',
3033 tHeader->config.orientation,
3034 tHeader->config.uiMode,
3035 tHeader->config.touchscreen,
3036 tHeader->config.density,
3037 tHeader->config.keyboard,
3038 tHeader->config.inputFlags,
3039 tHeader->config.navigation,
3040 tHeader->config.screenWidth,
3041 tHeader->config.screenHeight,
3042 tHeader->config.smallestScreenWidthDp,
3043 tHeader->config.screenWidthDp,
3044 tHeader->config.screenHeightDp,
3045 tHeader->config.layoutDirection));
3046 tHeader->config.swapHtoD();
3047
3048 // Build the entries inside of this type.
3049 for (size_t ei=0; ei<N; ei++) {
3050 sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
3051 sp<Entry> e = cl->getEntries().valueFor(config);
3052
3053 // Set the offset for this entry in its type.
3054 uint32_t* index = (uint32_t*)
3055 (((uint8_t*)data->editData())
3056 + typeStart + sizeof(ResTable_type));
3057 if (e != NULL) {
3058 index[ei] = htodl(data->getSize()-typeStart-typeSize);
3059
3060 // Create the entry.
3061 ssize_t amt = e->flatten(bundle, data, cl->getPublic());
3062 if (amt < 0) {
3063 return amt;
3064 }
3065 validResources.editItemAt(ei) = true;
3066 } else {
3067 index[ei] = htodl(ResTable_type::NO_ENTRY);
3068 }
3069 }
3070
3071 // Fill in the rest of the type information.
3072 tHeader = (ResTable_type*)
3073 (((uint8_t*)data->editData()) + typeStart);
3074 tHeader->header.size = htodl(data->getSize()-typeStart);
3075 }
3076
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003077 // If we're building splits, then each invocation of the flattening
3078 // step will have 'missing' entries. Don't warn/error for this case.
3079 if (bundle->getSplitConfigurations().isEmpty()) {
3080 bool missing_entry = false;
3081 const char* log_prefix = bundle->getErrorOnMissingConfigEntry() ?
3082 "error" : "warning";
3083 for (size_t i = 0; i < N; ++i) {
3084 if (!validResources[i]) {
3085 sp<ConfigList> c = t->getOrderedConfigs().itemAt(i);
3086 fprintf(stderr, "%s: no entries written for %s/%s (0x%08x)\n", log_prefix,
3087 String8(typeName).string(), String8(c->getName()).string(),
3088 Res_MAKEID(p->getAssignedId() - 1, ti, i));
3089 missing_entry = true;
3090 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003091 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003092 if (bundle->getErrorOnMissingConfigEntry() && missing_entry) {
3093 fprintf(stderr, "Error: Missing entries, quit!\n");
3094 return NOT_ENOUGH_DATA;
3095 }
Ying Wangcd28bd32013-11-14 17:12:10 -08003096 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003097 }
3098
3099 // Fill in the rest of the package information.
3100 header = (ResTable_package*)data->editData();
3101 header->header.size = htodl(data->getSize());
3102 header->typeStrings = htodl(typeStringsStart);
3103 header->lastPublicType = htodl(p->getTypeStrings().size());
3104 header->keyStrings = htodl(keyStringsStart);
3105 header->lastPublicKey = htodl(p->getKeyStrings().size());
3106
3107 flatPackages.add(data);
3108 }
3109
3110 // And now write out the final chunks.
3111 const size_t dataStart = dest->getSize();
3112
3113 {
3114 // blah
3115 ResTable_header header;
3116 memset(&header, 0, sizeof(header));
3117 header.header.type = htods(RES_TABLE_TYPE);
3118 header.header.headerSize = htods(sizeof(header));
3119 header.packageCount = htodl(flatPackages.size());
3120 status_t err = dest->writeData(&header, sizeof(header));
3121 if (err != NO_ERROR) {
3122 fprintf(stderr, "ERROR: out of memory creating ResTable_header\n");
3123 return err;
3124 }
3125 }
3126
3127 ssize_t strStart = dest->getSize();
Adam Lesinskifab50872014-04-16 14:40:42 -07003128 status_t err = valueStrings.writeStringBlock(dest);
Adam Lesinski282e1812014-01-23 18:17:42 -08003129 if (err != NO_ERROR) {
3130 return err;
3131 }
3132
3133 ssize_t amt = (dest->getSize()-strStart);
3134 strAmt += amt;
3135 #if PRINT_STRING_METRICS
3136 fprintf(stderr, "**** value strings: %d\n", amt);
3137 fprintf(stderr, "**** total strings: %d\n", strAmt);
3138 #endif
Adam Lesinskide898ff2014-01-29 18:20:45 -08003139
Adam Lesinski282e1812014-01-23 18:17:42 -08003140 for (pi=0; pi<flatPackages.size(); pi++) {
3141 err = dest->writeData(flatPackages[pi]->getData(),
3142 flatPackages[pi]->getSize());
3143 if (err != NO_ERROR) {
3144 fprintf(stderr, "ERROR: out of memory creating package chunk for ResTable_header\n");
3145 return err;
3146 }
3147 }
3148
3149 ResTable_header* header = (ResTable_header*)
3150 (((uint8_t*)dest->getData()) + dataStart);
3151 header->header.size = htodl(dest->getSize() - dataStart);
3152
3153 NOISY(aout << "Resource table:"
3154 << HexDump(dest->getData(), dest->getSize()) << endl);
3155
3156 #if PRINT_STRING_METRICS
3157 fprintf(stderr, "**** total resource table size: %d / %d%% strings\n",
3158 dest->getSize(), (strAmt*100)/dest->getSize());
3159 #endif
3160
3161 return NO_ERROR;
3162}
3163
Adam Lesinskide898ff2014-01-29 18:20:45 -08003164status_t ResourceTable::flattenLibraryTable(const sp<AaptFile>& dest, const Vector<sp<Package> >& libs) {
3165 // Write out the library table if necessary
3166 if (libs.size() > 0) {
3167 NOISY(fprintf(stderr, "Writing library reference table\n"));
3168
3169 const size_t libStart = dest->getSize();
3170 const size_t count = libs.size();
Adam Lesinski6022deb2014-08-20 14:59:19 -07003171 ResTable_lib_header* libHeader = (ResTable_lib_header*) dest->editDataInRange(
3172 libStart, sizeof(ResTable_lib_header));
Adam Lesinskide898ff2014-01-29 18:20:45 -08003173
3174 memset(libHeader, 0, sizeof(*libHeader));
3175 libHeader->header.type = htods(RES_TABLE_LIBRARY_TYPE);
3176 libHeader->header.headerSize = htods(sizeof(*libHeader));
3177 libHeader->header.size = htodl(sizeof(*libHeader) + (sizeof(ResTable_lib_entry) * count));
3178 libHeader->count = htodl(count);
3179
3180 // Write the library entries
3181 for (size_t i = 0; i < count; i++) {
3182 const size_t entryStart = dest->getSize();
3183 sp<Package> libPackage = libs[i];
3184 NOISY(fprintf(stderr, " Entry %s -> 0x%02x\n",
3185 String8(libPackage->getName()).string(),
3186 (uint8_t)libPackage->getAssignedId()));
3187
Adam Lesinski6022deb2014-08-20 14:59:19 -07003188 ResTable_lib_entry* entry = (ResTable_lib_entry*) dest->editDataInRange(
3189 entryStart, sizeof(ResTable_lib_entry));
Adam Lesinskide898ff2014-01-29 18:20:45 -08003190 memset(entry, 0, sizeof(*entry));
3191 entry->packageId = htodl(libPackage->getAssignedId());
3192 strcpy16_htod(entry->packageName, libPackage->getName().string());
3193 }
3194 }
3195 return NO_ERROR;
3196}
3197
Adam Lesinski282e1812014-01-23 18:17:42 -08003198void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp)
3199{
3200 fprintf(fp,
3201 "<!-- This file contains <public> resource definitions for all\n"
3202 " resources that were generated from the source data. -->\n"
3203 "\n"
3204 "<resources>\n");
3205
3206 writePublicDefinitions(package, fp, true);
3207 writePublicDefinitions(package, fp, false);
3208
3209 fprintf(fp,
3210 "\n"
3211 "</resources>\n");
3212}
3213
3214void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp, bool pub)
3215{
3216 bool didHeader = false;
3217
3218 sp<Package> pkg = mPackages.valueFor(package);
3219 if (pkg != NULL) {
3220 const size_t NT = pkg->getOrderedTypes().size();
3221 for (size_t i=0; i<NT; i++) {
3222 sp<Type> t = pkg->getOrderedTypes().itemAt(i);
3223 if (t == NULL) {
3224 continue;
3225 }
3226
3227 bool didType = false;
3228
3229 const size_t NC = t->getOrderedConfigs().size();
3230 for (size_t j=0; j<NC; j++) {
3231 sp<ConfigList> c = t->getOrderedConfigs().itemAt(j);
3232 if (c == NULL) {
3233 continue;
3234 }
3235
3236 if (c->getPublic() != pub) {
3237 continue;
3238 }
3239
3240 if (!didType) {
3241 fprintf(fp, "\n");
3242 didType = true;
3243 }
3244 if (!didHeader) {
3245 if (pub) {
3246 fprintf(fp," <!-- PUBLIC SECTION. These resources have been declared public.\n");
3247 fprintf(fp," Changes to these definitions will break binary compatibility. -->\n\n");
3248 } else {
3249 fprintf(fp," <!-- PRIVATE SECTION. These resources have not been declared public.\n");
3250 fprintf(fp," You can make them public my moving these lines into a file in res/values. -->\n\n");
3251 }
3252 didHeader = true;
3253 }
3254 if (!pub) {
3255 const size_t NE = c->getEntries().size();
3256 for (size_t k=0; k<NE; k++) {
3257 const SourcePos& pos = c->getEntries().valueAt(k)->getPos();
3258 if (pos.file != "") {
3259 fprintf(fp," <!-- Declared at %s:%d -->\n",
3260 pos.file.string(), pos.line);
3261 }
3262 }
3263 }
3264 fprintf(fp, " <public type=\"%s\" name=\"%s\" id=\"0x%08x\" />\n",
3265 String8(t->getName()).string(),
3266 String8(c->getName()).string(),
3267 getResId(pkg, t, c->getEntryIndex()));
3268 }
3269 }
3270 }
3271}
3272
3273ResourceTable::Item::Item(const SourcePos& _sourcePos,
3274 bool _isId,
3275 const String16& _value,
3276 const Vector<StringPool::entry_style_span>* _style,
3277 int32_t _format)
3278 : sourcePos(_sourcePos)
3279 , isId(_isId)
3280 , value(_value)
3281 , format(_format)
3282 , bagKeyId(0)
3283 , evaluating(false)
3284{
3285 if (_style) {
3286 style = *_style;
3287 }
3288}
3289
3290status_t ResourceTable::Entry::makeItABag(const SourcePos& sourcePos)
3291{
3292 if (mType == TYPE_BAG) {
3293 return NO_ERROR;
3294 }
3295 if (mType == TYPE_UNKNOWN) {
3296 mType = TYPE_BAG;
3297 return NO_ERROR;
3298 }
3299 sourcePos.error("Resource entry %s is already defined as a single item.\n"
3300 "%s:%d: Originally defined here.\n",
3301 String8(mName).string(),
3302 mItem.sourcePos.file.string(), mItem.sourcePos.line);
3303 return UNKNOWN_ERROR;
3304}
3305
3306status_t ResourceTable::Entry::setItem(const SourcePos& sourcePos,
3307 const String16& value,
3308 const Vector<StringPool::entry_style_span>* style,
3309 int32_t format,
3310 const bool overwrite)
3311{
3312 Item item(sourcePos, false, value, style);
3313
3314 if (mType == TYPE_BAG) {
Adam Lesinski43a0df02014-08-18 17:14:57 -07003315 if (mBag.size() == 0) {
3316 sourcePos.error("Resource entry %s is already defined as a bag.",
3317 String8(mName).string());
3318 } else {
3319 const Item& item(mBag.valueAt(0));
3320 sourcePos.error("Resource entry %s is already defined as a bag.\n"
3321 "%s:%d: Originally defined here.\n",
3322 String8(mName).string(),
3323 item.sourcePos.file.string(), item.sourcePos.line);
3324 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003325 return UNKNOWN_ERROR;
3326 }
3327 if ( (mType != TYPE_UNKNOWN) && (overwrite == false) ) {
3328 sourcePos.error("Resource entry %s is already defined.\n"
3329 "%s:%d: Originally defined here.\n",
3330 String8(mName).string(),
3331 mItem.sourcePos.file.string(), mItem.sourcePos.line);
3332 return UNKNOWN_ERROR;
3333 }
3334
3335 mType = TYPE_ITEM;
3336 mItem = item;
3337 mItemFormat = format;
3338 return NO_ERROR;
3339}
3340
3341status_t ResourceTable::Entry::addToBag(const SourcePos& sourcePos,
3342 const String16& key, const String16& value,
3343 const Vector<StringPool::entry_style_span>* style,
3344 bool replace, bool isId, int32_t format)
3345{
3346 status_t err = makeItABag(sourcePos);
3347 if (err != NO_ERROR) {
3348 return err;
3349 }
3350
3351 Item item(sourcePos, isId, value, style, format);
3352
3353 // XXX NOTE: there is an error if you try to have a bag with two keys,
3354 // one an attr and one an id, with the same name. Not something we
3355 // currently ever have to worry about.
3356 ssize_t origKey = mBag.indexOfKey(key);
3357 if (origKey >= 0) {
3358 if (!replace) {
3359 const Item& item(mBag.valueAt(origKey));
3360 sourcePos.error("Resource entry %s already has bag item %s.\n"
3361 "%s:%d: Originally defined here.\n",
3362 String8(mName).string(), String8(key).string(),
3363 item.sourcePos.file.string(), item.sourcePos.line);
3364 return UNKNOWN_ERROR;
3365 }
3366 //printf("Replacing %s with %s\n",
3367 // String8(mBag.valueFor(key).value).string(), String8(value).string());
3368 mBag.replaceValueFor(key, item);
3369 }
3370
3371 mBag.add(key, item);
3372 return NO_ERROR;
3373}
3374
3375status_t ResourceTable::Entry::emptyBag(const SourcePos& sourcePos)
3376{
3377 status_t err = makeItABag(sourcePos);
3378 if (err != NO_ERROR) {
3379 return err;
3380 }
3381
3382 mBag.clear();
3383 return NO_ERROR;
3384}
3385
3386status_t ResourceTable::Entry::generateAttributes(ResourceTable* table,
3387 const String16& package)
3388{
3389 const String16 attr16("attr");
3390 const String16 id16("id");
3391 const size_t N = mBag.size();
3392 for (size_t i=0; i<N; i++) {
3393 const String16& key = mBag.keyAt(i);
3394 const Item& it = mBag.valueAt(i);
3395 if (it.isId) {
3396 if (!table->hasBagOrEntry(key, &id16, &package)) {
3397 String16 value("false");
Adam Lesinski43a0df02014-08-18 17:14:57 -07003398 NOISY(fprintf(stderr, "Generating %s:id/%s\n",
3399 String8(package).string(),
3400 String8(key).string()));
Adam Lesinski282e1812014-01-23 18:17:42 -08003401 status_t err = table->addEntry(SourcePos(String8("<generated>"), 0), package,
3402 id16, key, value);
3403 if (err != NO_ERROR) {
3404 return err;
3405 }
3406 }
3407 } else if (!table->hasBagOrEntry(key, &attr16, &package)) {
3408
3409#if 1
3410// fprintf(stderr, "ERROR: Bag attribute '%s' has not been defined.\n",
3411// String8(key).string());
3412// const Item& item(mBag.valueAt(i));
3413// fprintf(stderr, "Referenced from file %s line %d\n",
3414// item.sourcePos.file.string(), item.sourcePos.line);
3415// return UNKNOWN_ERROR;
3416#else
3417 char numberStr[16];
3418 sprintf(numberStr, "%d", ResTable_map::TYPE_ANY);
3419 status_t err = table->addBag(SourcePos("<generated>", 0), package,
3420 attr16, key, String16(""),
3421 String16("^type"),
3422 String16(numberStr), NULL, NULL);
3423 if (err != NO_ERROR) {
3424 return err;
3425 }
3426#endif
3427 }
3428 }
3429 return NO_ERROR;
3430}
3431
3432status_t ResourceTable::Entry::assignResourceIds(ResourceTable* table,
3433 const String16& package)
3434{
3435 bool hasErrors = false;
3436
3437 if (mType == TYPE_BAG) {
3438 const char* errorMsg;
3439 const String16 style16("style");
3440 const String16 attr16("attr");
3441 const String16 id16("id");
3442 mParentId = 0;
3443 if (mParent.size() > 0) {
3444 mParentId = table->getResId(mParent, &style16, NULL, &errorMsg);
3445 if (mParentId == 0) {
3446 mPos.error("Error retrieving parent for item: %s '%s'.\n",
3447 errorMsg, String8(mParent).string());
3448 hasErrors = true;
3449 }
3450 }
3451 const size_t N = mBag.size();
3452 for (size_t i=0; i<N; i++) {
3453 const String16& key = mBag.keyAt(i);
3454 Item& it = mBag.editValueAt(i);
3455 it.bagKeyId = table->getResId(key,
3456 it.isId ? &id16 : &attr16, NULL, &errorMsg);
3457 //printf("Bag key of %s: #%08x\n", String8(key).string(), it.bagKeyId);
3458 if (it.bagKeyId == 0) {
3459 it.sourcePos.error("Error: %s: %s '%s'.\n", errorMsg,
3460 String8(it.isId ? id16 : attr16).string(),
3461 String8(key).string());
3462 hasErrors = true;
3463 }
3464 }
3465 }
3466 return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
3467}
3468
3469status_t ResourceTable::Entry::prepareFlatten(StringPool* strings, ResourceTable* table,
3470 const String8* configTypeName, const ConfigDescription* config)
3471{
3472 if (mType == TYPE_ITEM) {
3473 Item& it = mItem;
3474 AccessorCookie ac(it.sourcePos, String8(mName), String8(it.value));
3475 if (!table->stringToValue(&it.parsedValue, strings,
3476 it.value, false, true, 0,
3477 &it.style, NULL, &ac, mItemFormat,
3478 configTypeName, config)) {
3479 return UNKNOWN_ERROR;
3480 }
3481 } else if (mType == TYPE_BAG) {
3482 const size_t N = mBag.size();
3483 for (size_t i=0; i<N; i++) {
3484 const String16& key = mBag.keyAt(i);
3485 Item& it = mBag.editValueAt(i);
3486 AccessorCookie ac(it.sourcePos, String8(key), String8(it.value));
3487 if (!table->stringToValue(&it.parsedValue, strings,
3488 it.value, false, true, it.bagKeyId,
3489 &it.style, NULL, &ac, it.format,
3490 configTypeName, config)) {
3491 return UNKNOWN_ERROR;
3492 }
3493 }
3494 } else {
3495 mPos.error("Error: entry %s is not a single item or a bag.\n",
3496 String8(mName).string());
3497 return UNKNOWN_ERROR;
3498 }
3499 return NO_ERROR;
3500}
3501
3502status_t ResourceTable::Entry::remapStringValue(StringPool* strings)
3503{
3504 if (mType == TYPE_ITEM) {
3505 Item& it = mItem;
3506 if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3507 it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3508 }
3509 } else if (mType == TYPE_BAG) {
3510 const size_t N = mBag.size();
3511 for (size_t i=0; i<N; i++) {
3512 Item& it = mBag.editValueAt(i);
3513 if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3514 it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3515 }
3516 }
3517 } else {
3518 mPos.error("Error: entry %s is not a single item or a bag.\n",
3519 String8(mName).string());
3520 return UNKNOWN_ERROR;
3521 }
3522 return NO_ERROR;
3523}
3524
3525ssize_t ResourceTable::Entry::flatten(Bundle* bundle, const sp<AaptFile>& data, bool isPublic)
3526{
3527 size_t amt = 0;
3528 ResTable_entry header;
3529 memset(&header, 0, sizeof(header));
3530 header.size = htods(sizeof(header));
3531 const type ty = this != NULL ? mType : TYPE_ITEM;
3532 if (this != NULL) {
3533 if (ty == TYPE_BAG) {
3534 header.flags |= htods(header.FLAG_COMPLEX);
3535 }
3536 if (isPublic) {
3537 header.flags |= htods(header.FLAG_PUBLIC);
3538 }
3539 header.key.index = htodl(mNameIndex);
3540 }
3541 if (ty != TYPE_BAG) {
3542 status_t err = data->writeData(&header, sizeof(header));
3543 if (err != NO_ERROR) {
3544 fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3545 return err;
3546 }
3547
3548 const Item& it = mItem;
3549 Res_value par;
3550 memset(&par, 0, sizeof(par));
3551 par.size = htods(it.parsedValue.size);
3552 par.dataType = it.parsedValue.dataType;
3553 par.res0 = it.parsedValue.res0;
3554 par.data = htodl(it.parsedValue.data);
3555 #if 0
3556 printf("Writing item (%s): type=%d, data=0x%x, res0=0x%x\n",
3557 String8(mName).string(), it.parsedValue.dataType,
3558 it.parsedValue.data, par.res0);
3559 #endif
3560 err = data->writeData(&par, it.parsedValue.size);
3561 if (err != NO_ERROR) {
3562 fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3563 return err;
3564 }
3565 amt += it.parsedValue.size;
3566 } else {
3567 size_t N = mBag.size();
3568 size_t i;
3569 // Create correct ordering of items.
3570 KeyedVector<uint32_t, const Item*> items;
3571 for (i=0; i<N; i++) {
3572 const Item& it = mBag.valueAt(i);
3573 items.add(it.bagKeyId, &it);
3574 }
3575 N = items.size();
3576
3577 ResTable_map_entry mapHeader;
3578 memcpy(&mapHeader, &header, sizeof(header));
3579 mapHeader.size = htods(sizeof(mapHeader));
3580 mapHeader.parent.ident = htodl(mParentId);
3581 mapHeader.count = htodl(N);
3582 status_t err = data->writeData(&mapHeader, sizeof(mapHeader));
3583 if (err != NO_ERROR) {
3584 fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3585 return err;
3586 }
3587
3588 for (i=0; i<N; i++) {
3589 const Item& it = *items.valueAt(i);
3590 ResTable_map map;
3591 map.name.ident = htodl(it.bagKeyId);
3592 map.value.size = htods(it.parsedValue.size);
3593 map.value.dataType = it.parsedValue.dataType;
3594 map.value.res0 = it.parsedValue.res0;
3595 map.value.data = htodl(it.parsedValue.data);
3596 err = data->writeData(&map, sizeof(map));
3597 if (err != NO_ERROR) {
3598 fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3599 return err;
3600 }
3601 amt += sizeof(map);
3602 }
3603 }
3604 return amt;
3605}
3606
3607void ResourceTable::ConfigList::appendComment(const String16& comment,
3608 bool onlyIfEmpty)
3609{
3610 if (comment.size() <= 0) {
3611 return;
3612 }
3613 if (onlyIfEmpty && mComment.size() > 0) {
3614 return;
3615 }
3616 if (mComment.size() > 0) {
3617 mComment.append(String16("\n"));
3618 }
3619 mComment.append(comment);
3620}
3621
3622void ResourceTable::ConfigList::appendTypeComment(const String16& comment)
3623{
3624 if (comment.size() <= 0) {
3625 return;
3626 }
3627 if (mTypeComment.size() > 0) {
3628 mTypeComment.append(String16("\n"));
3629 }
3630 mTypeComment.append(comment);
3631}
3632
3633status_t ResourceTable::Type::addPublic(const SourcePos& sourcePos,
3634 const String16& name,
3635 const uint32_t ident)
3636{
3637 #if 0
3638 int32_t entryIdx = Res_GETENTRY(ident);
3639 if (entryIdx < 0) {
3640 sourcePos.error("Public resource %s/%s has an invalid 0 identifier (0x%08x).\n",
3641 String8(mName).string(), String8(name).string(), ident);
3642 return UNKNOWN_ERROR;
3643 }
3644 #endif
3645
3646 int32_t typeIdx = Res_GETTYPE(ident);
3647 if (typeIdx >= 0) {
3648 typeIdx++;
3649 if (mPublicIndex > 0 && mPublicIndex != typeIdx) {
3650 sourcePos.error("Public resource %s/%s has conflicting type codes for its"
3651 " public identifiers (0x%x vs 0x%x).\n",
3652 String8(mName).string(), String8(name).string(),
3653 mPublicIndex, typeIdx);
3654 return UNKNOWN_ERROR;
3655 }
3656 mPublicIndex = typeIdx;
3657 }
3658
3659 if (mFirstPublicSourcePos == NULL) {
3660 mFirstPublicSourcePos = new SourcePos(sourcePos);
3661 }
3662
3663 if (mPublic.indexOfKey(name) < 0) {
3664 mPublic.add(name, Public(sourcePos, String16(), ident));
3665 } else {
3666 Public& p = mPublic.editValueFor(name);
3667 if (p.ident != ident) {
3668 sourcePos.error("Public resource %s/%s has conflicting public identifiers"
3669 " (0x%08x vs 0x%08x).\n"
3670 "%s:%d: Originally defined here.\n",
3671 String8(mName).string(), String8(name).string(), p.ident, ident,
3672 p.sourcePos.file.string(), p.sourcePos.line);
3673 return UNKNOWN_ERROR;
3674 }
3675 }
3676
3677 return NO_ERROR;
3678}
3679
3680void ResourceTable::Type::canAddEntry(const String16& name)
3681{
3682 mCanAddEntries.add(name);
3683}
3684
3685sp<ResourceTable::Entry> ResourceTable::Type::getEntry(const String16& entry,
3686 const SourcePos& sourcePos,
3687 const ResTable_config* config,
3688 bool doSetIndex,
3689 bool overlay,
3690 bool autoAddOverlay)
3691{
3692 int pos = -1;
3693 sp<ConfigList> c = mConfigs.valueFor(entry);
3694 if (c == NULL) {
3695 if (overlay && !autoAddOverlay && mCanAddEntries.indexOf(entry) < 0) {
3696 sourcePos.error("Resource at %s appears in overlay but not"
3697 " in the base package; use <add-resource> to add.\n",
3698 String8(entry).string());
3699 return NULL;
3700 }
3701 c = new ConfigList(entry, sourcePos);
3702 mConfigs.add(entry, c);
3703 pos = (int)mOrderedConfigs.size();
3704 mOrderedConfigs.add(c);
3705 if (doSetIndex) {
3706 c->setEntryIndex(pos);
3707 }
3708 }
3709
3710 ConfigDescription cdesc;
3711 if (config) cdesc = *config;
3712
3713 sp<Entry> e = c->getEntries().valueFor(cdesc);
3714 if (e == NULL) {
3715 if (config != NULL) {
3716 NOISY(printf("New entry at %s:%d: imsi:%d/%d lang:%c%c cnt:%c%c "
3717 "orien:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
3718 "sw%ddp w%ddp h%ddp dir:%d\n",
3719 sourcePos.file.string(), sourcePos.line,
3720 config->mcc, config->mnc,
3721 config->language[0] ? config->language[0] : '-',
3722 config->language[1] ? config->language[1] : '-',
3723 config->country[0] ? config->country[0] : '-',
3724 config->country[1] ? config->country[1] : '-',
3725 config->orientation,
3726 config->touchscreen,
3727 config->density,
3728 config->keyboard,
3729 config->inputFlags,
3730 config->navigation,
3731 config->screenWidth,
3732 config->screenHeight,
3733 config->smallestScreenWidthDp,
3734 config->screenWidthDp,
3735 config->screenHeightDp,
3736 config->layoutDirection));
3737 } else {
3738 NOISY(printf("New entry at %s:%d: NULL config\n",
3739 sourcePos.file.string(), sourcePos.line));
3740 }
3741 e = new Entry(entry, sourcePos);
3742 c->addEntry(cdesc, e);
3743 /*
3744 if (doSetIndex) {
3745 if (pos < 0) {
3746 for (pos=0; pos<(int)mOrderedConfigs.size(); pos++) {
3747 if (mOrderedConfigs[pos] == c) {
3748 break;
3749 }
3750 }
3751 if (pos >= (int)mOrderedConfigs.size()) {
3752 sourcePos.error("Internal error: config not found in mOrderedConfigs when adding entry");
3753 return NULL;
3754 }
3755 }
3756 e->setEntryIndex(pos);
3757 }
3758 */
3759 }
3760
3761 mUniqueConfigs.add(cdesc);
3762
3763 return e;
3764}
3765
3766status_t ResourceTable::Type::applyPublicEntryOrder()
3767{
3768 size_t N = mOrderedConfigs.size();
3769 Vector<sp<ConfigList> > origOrder(mOrderedConfigs);
3770 bool hasError = false;
3771
3772 size_t i;
3773 for (i=0; i<N; i++) {
3774 mOrderedConfigs.replaceAt(NULL, i);
3775 }
3776
3777 const size_t NP = mPublic.size();
3778 //printf("Ordering %d configs from %d public defs\n", N, NP);
3779 size_t j;
3780 for (j=0; j<NP; j++) {
3781 const String16& name = mPublic.keyAt(j);
3782 const Public& p = mPublic.valueAt(j);
3783 int32_t idx = Res_GETENTRY(p.ident);
3784 //printf("Looking for entry \"%s\"/\"%s\" (0x%08x) in %d...\n",
3785 // String8(mName).string(), String8(name).string(), p.ident, N);
3786 bool found = false;
3787 for (i=0; i<N; i++) {
3788 sp<ConfigList> e = origOrder.itemAt(i);
3789 //printf("#%d: \"%s\"\n", i, String8(e->getName()).string());
3790 if (e->getName() == name) {
3791 if (idx >= (int32_t)mOrderedConfigs.size()) {
3792 p.sourcePos.error("Public entry identifier 0x%x entry index "
3793 "is larger than available symbols (index %d, total symbols %d).\n",
3794 p.ident, idx, mOrderedConfigs.size());
3795 hasError = true;
3796 } else if (mOrderedConfigs.itemAt(idx) == NULL) {
3797 e->setPublic(true);
3798 e->setPublicSourcePos(p.sourcePos);
3799 mOrderedConfigs.replaceAt(e, idx);
3800 origOrder.removeAt(i);
3801 N--;
3802 found = true;
3803 break;
3804 } else {
3805 sp<ConfigList> oe = mOrderedConfigs.itemAt(idx);
3806
3807 p.sourcePos.error("Multiple entry names declared for public entry"
3808 " identifier 0x%x in type %s (%s vs %s).\n"
3809 "%s:%d: Originally defined here.",
3810 idx+1, String8(mName).string(),
3811 String8(oe->getName()).string(),
3812 String8(name).string(),
3813 oe->getPublicSourcePos().file.string(),
3814 oe->getPublicSourcePos().line);
3815 hasError = true;
3816 }
3817 }
3818 }
3819
3820 if (!found) {
3821 p.sourcePos.error("Public symbol %s/%s declared here is not defined.",
3822 String8(mName).string(), String8(name).string());
3823 hasError = true;
3824 }
3825 }
3826
3827 //printf("Copying back in %d non-public configs, have %d\n", N, origOrder.size());
3828
3829 if (N != origOrder.size()) {
3830 printf("Internal error: remaining private symbol count mismatch\n");
3831 N = origOrder.size();
3832 }
3833
3834 j = 0;
3835 for (i=0; i<N; i++) {
3836 sp<ConfigList> e = origOrder.itemAt(i);
3837 // There will always be enough room for the remaining entries.
3838 while (mOrderedConfigs.itemAt(j) != NULL) {
3839 j++;
3840 }
3841 mOrderedConfigs.replaceAt(e, j);
3842 j++;
3843 }
3844
3845 return hasError ? UNKNOWN_ERROR : NO_ERROR;
3846}
3847
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003848ResourceTable::Package::Package(const String16& name, size_t packageId)
3849 : mName(name), mPackageId(packageId),
Adam Lesinski282e1812014-01-23 18:17:42 -08003850 mTypeStringsMapping(0xffffffff),
3851 mKeyStringsMapping(0xffffffff)
3852{
3853}
3854
3855sp<ResourceTable::Type> ResourceTable::Package::getType(const String16& type,
3856 const SourcePos& sourcePos,
3857 bool doSetIndex)
3858{
3859 sp<Type> t = mTypes.valueFor(type);
3860 if (t == NULL) {
3861 t = new Type(type, sourcePos);
3862 mTypes.add(type, t);
3863 mOrderedTypes.add(t);
3864 if (doSetIndex) {
3865 // For some reason the type's index is set to one plus the index
3866 // in the mOrderedTypes list, rather than just the index.
3867 t->setIndex(mOrderedTypes.size());
3868 }
3869 }
3870 return t;
3871}
3872
3873status_t ResourceTable::Package::setTypeStrings(const sp<AaptFile>& data)
3874{
Adam Lesinski282e1812014-01-23 18:17:42 -08003875 status_t err = setStrings(data, &mTypeStrings, &mTypeStringsMapping);
3876 if (err != NO_ERROR) {
3877 fprintf(stderr, "ERROR: Type string data is corrupt!\n");
Adam Lesinski57079512014-07-29 11:51:35 -07003878 return err;
Adam Lesinski282e1812014-01-23 18:17:42 -08003879 }
Adam Lesinski57079512014-07-29 11:51:35 -07003880
3881 // Retain a reference to the new data after we've successfully replaced
3882 // all uses of the old reference (in setStrings() ).
3883 mTypeStringsData = data;
3884 return NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08003885}
3886
3887status_t ResourceTable::Package::setKeyStrings(const sp<AaptFile>& data)
3888{
Adam Lesinski282e1812014-01-23 18:17:42 -08003889 status_t err = setStrings(data, &mKeyStrings, &mKeyStringsMapping);
3890 if (err != NO_ERROR) {
3891 fprintf(stderr, "ERROR: Key string data is corrupt!\n");
Adam Lesinski57079512014-07-29 11:51:35 -07003892 return err;
Adam Lesinski282e1812014-01-23 18:17:42 -08003893 }
Adam Lesinski57079512014-07-29 11:51:35 -07003894
3895 // Retain a reference to the new data after we've successfully replaced
3896 // all uses of the old reference (in setStrings() ).
3897 mKeyStringsData = data;
3898 return NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08003899}
3900
3901status_t ResourceTable::Package::setStrings(const sp<AaptFile>& data,
3902 ResStringPool* strings,
3903 DefaultKeyedVector<String16, uint32_t>* mappings)
3904{
3905 if (data->getData() == NULL) {
3906 return UNKNOWN_ERROR;
3907 }
3908
3909 NOISY(aout << "Setting restable string pool: "
3910 << HexDump(data->getData(), data->getSize()) << endl);
3911
3912 status_t err = strings->setTo(data->getData(), data->getSize());
3913 if (err == NO_ERROR) {
3914 const size_t N = strings->size();
3915 for (size_t i=0; i<N; i++) {
3916 size_t len;
3917 mappings->add(String16(strings->stringAt(i, &len)), i);
3918 }
3919 }
3920 return err;
3921}
3922
3923status_t ResourceTable::Package::applyPublicTypeOrder()
3924{
3925 size_t N = mOrderedTypes.size();
3926 Vector<sp<Type> > origOrder(mOrderedTypes);
3927
3928 size_t i;
3929 for (i=0; i<N; i++) {
3930 mOrderedTypes.replaceAt(NULL, i);
3931 }
3932
3933 for (i=0; i<N; i++) {
3934 sp<Type> t = origOrder.itemAt(i);
3935 int32_t idx = t->getPublicIndex();
3936 if (idx > 0) {
3937 idx--;
3938 while (idx >= (int32_t)mOrderedTypes.size()) {
3939 mOrderedTypes.add();
3940 }
3941 if (mOrderedTypes.itemAt(idx) != NULL) {
3942 sp<Type> ot = mOrderedTypes.itemAt(idx);
3943 t->getFirstPublicSourcePos().error("Multiple type names declared for public type"
3944 " identifier 0x%x (%s vs %s).\n"
3945 "%s:%d: Originally defined here.",
3946 idx, String8(ot->getName()).string(),
3947 String8(t->getName()).string(),
3948 ot->getFirstPublicSourcePos().file.string(),
3949 ot->getFirstPublicSourcePos().line);
3950 return UNKNOWN_ERROR;
3951 }
3952 mOrderedTypes.replaceAt(t, idx);
3953 origOrder.removeAt(i);
3954 i--;
3955 N--;
3956 }
3957 }
3958
3959 size_t j=0;
3960 for (i=0; i<N; i++) {
3961 sp<Type> t = origOrder.itemAt(i);
3962 // There will always be enough room for the remaining types.
3963 while (mOrderedTypes.itemAt(j) != NULL) {
3964 j++;
3965 }
3966 mOrderedTypes.replaceAt(t, j);
3967 }
3968
3969 return NO_ERROR;
3970}
3971
3972sp<ResourceTable::Package> ResourceTable::getPackage(const String16& package)
3973{
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003974 if (package != mAssetsPackage) {
3975 return NULL;
Adam Lesinski282e1812014-01-23 18:17:42 -08003976 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003977 return mPackages.valueFor(package);
Adam Lesinski282e1812014-01-23 18:17:42 -08003978}
3979
3980sp<ResourceTable::Type> ResourceTable::getType(const String16& package,
3981 const String16& type,
3982 const SourcePos& sourcePos,
3983 bool doSetIndex)
3984{
3985 sp<Package> p = getPackage(package);
3986 if (p == NULL) {
3987 return NULL;
3988 }
3989 return p->getType(type, sourcePos, doSetIndex);
3990}
3991
3992sp<ResourceTable::Entry> ResourceTable::getEntry(const String16& package,
3993 const String16& type,
3994 const String16& name,
3995 const SourcePos& sourcePos,
3996 bool overlay,
3997 const ResTable_config* config,
3998 bool doSetIndex)
3999{
4000 sp<Type> t = getType(package, type, sourcePos, doSetIndex);
4001 if (t == NULL) {
4002 return NULL;
4003 }
4004 return t->getEntry(name, sourcePos, config, doSetIndex, overlay, mBundle->getAutoAddOverlay());
4005}
4006
4007sp<const ResourceTable::Entry> ResourceTable::getEntry(uint32_t resID,
4008 const ResTable_config* config) const
4009{
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004010 size_t pid = Res_GETPACKAGE(resID)+1;
Adam Lesinski282e1812014-01-23 18:17:42 -08004011 const size_t N = mOrderedPackages.size();
Adam Lesinski282e1812014-01-23 18:17:42 -08004012 sp<Package> p;
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004013 for (size_t i = 0; i < N; i++) {
Adam Lesinski282e1812014-01-23 18:17:42 -08004014 sp<Package> check = mOrderedPackages[i];
4015 if (check->getAssignedId() == pid) {
4016 p = check;
4017 break;
4018 }
4019
4020 }
4021 if (p == NULL) {
4022 fprintf(stderr, "warning: Package not found for resource #%08x\n", resID);
4023 return NULL;
4024 }
4025
4026 int tid = Res_GETTYPE(resID);
4027 if (tid < 0 || tid >= (int)p->getOrderedTypes().size()) {
4028 fprintf(stderr, "warning: Type not found for resource #%08x\n", resID);
4029 return NULL;
4030 }
4031 sp<Type> t = p->getOrderedTypes()[tid];
4032
4033 int eid = Res_GETENTRY(resID);
4034 if (eid < 0 || eid >= (int)t->getOrderedConfigs().size()) {
4035 fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
4036 return NULL;
4037 }
4038
4039 sp<ConfigList> c = t->getOrderedConfigs()[eid];
4040 if (c == NULL) {
4041 fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
4042 return NULL;
4043 }
4044
4045 ConfigDescription cdesc;
4046 if (config) cdesc = *config;
4047 sp<Entry> e = c->getEntries().valueFor(cdesc);
4048 if (c == NULL) {
4049 fprintf(stderr, "warning: Entry configuration not found for resource #%08x\n", resID);
4050 return NULL;
4051 }
4052
4053 return e;
4054}
4055
4056const ResourceTable::Item* ResourceTable::getItem(uint32_t resID, uint32_t attrID) const
4057{
4058 sp<const Entry> e = getEntry(resID);
4059 if (e == NULL) {
4060 return NULL;
4061 }
4062
4063 const size_t N = e->getBag().size();
4064 for (size_t i=0; i<N; i++) {
4065 const Item& it = e->getBag().valueAt(i);
4066 if (it.bagKeyId == 0) {
4067 fprintf(stderr, "warning: ID not yet assigned to '%s' in bag '%s'\n",
4068 String8(e->getName()).string(),
4069 String8(e->getBag().keyAt(i)).string());
4070 }
4071 if (it.bagKeyId == attrID) {
4072 return &it;
4073 }
4074 }
4075
4076 return NULL;
4077}
4078
4079bool ResourceTable::getItemValue(
4080 uint32_t resID, uint32_t attrID, Res_value* outValue)
4081{
4082 const Item* item = getItem(resID, attrID);
4083
4084 bool res = false;
4085 if (item != NULL) {
4086 if (item->evaluating) {
4087 sp<const Entry> e = getEntry(resID);
4088 const size_t N = e->getBag().size();
4089 size_t i;
4090 for (i=0; i<N; i++) {
4091 if (&e->getBag().valueAt(i) == item) {
4092 break;
4093 }
4094 }
4095 fprintf(stderr, "warning: Circular reference detected in key '%s' of bag '%s'\n",
4096 String8(e->getName()).string(),
4097 String8(e->getBag().keyAt(i)).string());
4098 return false;
4099 }
4100 item->evaluating = true;
4101 res = stringToValue(outValue, NULL, item->value, false, false, item->bagKeyId);
4102 NOISY(
4103 if (res) {
4104 printf("getItemValue of #%08x[#%08x] (%s): type=#%08x, data=#%08x\n",
4105 resID, attrID, String8(getEntry(resID)->getName()).string(),
4106 outValue->dataType, outValue->data);
4107 } else {
4108 printf("getItemValue of #%08x[#%08x]: failed\n",
4109 resID, attrID);
4110 }
4111 );
4112 item->evaluating = false;
4113 }
4114 return res;
4115}