blob: efbba40f950db73567d72f1fb576404f081e3ea8 [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
487 // Make sure an id is defined for this enum/flag identifier...
488 if (!attr.hasErrors && !outTable->hasBagOrEntry(itemIdent, &id16, &myPackage)) {
489 err = outTable->startBag(SourcePos(in->getPrintableSource(), block.getLineNumber()),
490 myPackage, id16, itemIdent, String16(), NULL);
491 if (err != NO_ERROR) {
492 attr.hasErrors = true;
493 }
494 }
495
496 if (!attr.hasErrors) {
497 if (enumOrFlagsComment.size() == 0) {
498 enumOrFlagsComment.append(mayOrMust(attr.type,
499 ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS));
500 enumOrFlagsComment.append((attr.type&ResTable_map::TYPE_ENUM)
501 ? String16(" be one of the following constant values.")
502 : String16(" be one or more (separated by '|') of the following constant values."));
503 enumOrFlagsComment.append(String16("</p>\n<table>\n"
504 "<colgroup align=\"left\" />\n"
505 "<colgroup align=\"left\" />\n"
506 "<colgroup align=\"left\" />\n"
507 "<tr><th>Constant</th><th>Value</th><th>Description</th></tr>"));
508 }
509
510 enumOrFlagsComment.append(String16("\n<tr><td><code>"));
511 enumOrFlagsComment.append(itemIdent);
512 enumOrFlagsComment.append(String16("</code></td><td>"));
513 enumOrFlagsComment.append(value);
514 enumOrFlagsComment.append(String16("</td><td>"));
515 if (block.getComment(&len)) {
516 enumOrFlagsComment.append(String16(block.getComment(&len)));
517 }
518 enumOrFlagsComment.append(String16("</td></tr>"));
519
520 err = outTable->addBag(SourcePos(in->getPrintableSource(), block.getLineNumber()),
521 myPackage,
522 attr16, attr.ident, String16(""),
523 itemIdent, value, NULL, NULL, false, true);
524 if (err != NO_ERROR) {
525 attr.hasErrors = true;
526 }
527 }
528 } else if (code == ResXMLTree::END_TAG) {
529 if (strcmp16(block.getElementName(&len), attr16.string()) == 0) {
530 break;
531 }
532 if ((attr.type&ResTable_map::TYPE_ENUM) != 0) {
533 if (strcmp16(block.getElementName(&len), enum16.string()) != 0) {
534 SourcePos(in->getPrintableSource(), block.getLineNumber())
535 .error("Found tag </%s> where </enum> is expected\n",
536 String8(block.getElementName(&len)).string());
537 return UNKNOWN_ERROR;
538 }
539 } else {
540 if (strcmp16(block.getElementName(&len), flag16.string()) != 0) {
541 SourcePos(in->getPrintableSource(), block.getLineNumber())
542 .error("Found tag </%s> where </flag> is expected\n",
543 String8(block.getElementName(&len)).string());
544 return UNKNOWN_ERROR;
545 }
546 }
547 }
548 }
549
550 if (!attr.hasErrors && attr.added) {
551 appendTypeInfo(outTable, myPackage, attr16, attr.ident, attr.type, gFormatFlags);
552 }
553
554 if (!attr.hasErrors && enumOrFlagsComment.size() > 0) {
555 enumOrFlagsComment.append(String16("\n</table>"));
556 outTable->appendTypeComment(myPackage, attr16, attr.ident, enumOrFlagsComment);
557 }
558
559
560 return NO_ERROR;
561}
562
563bool localeIsDefined(const ResTable_config& config)
564{
565 return config.locale == 0;
566}
567
568status_t parseAndAddBag(Bundle* bundle,
569 const sp<AaptFile>& in,
570 ResXMLTree* block,
571 const ResTable_config& config,
572 const String16& myPackage,
573 const String16& curType,
574 const String16& ident,
575 const String16& parentIdent,
576 const String16& itemIdent,
577 int32_t curFormat,
578 bool isFormatted,
579 const String16& product,
Anton Krumina2ef5c02014-03-12 14:46:44 -0700580 PseudolocalizationMethod pseudolocalize,
Adam Lesinski282e1812014-01-23 18:17:42 -0800581 const bool overwrite,
582 ResourceTable* outTable)
583{
584 status_t err;
585 const String16 item16("item");
Anton Krumina2ef5c02014-03-12 14:46:44 -0700586
Adam Lesinski282e1812014-01-23 18:17:42 -0800587 String16 str;
588 Vector<StringPool::entry_style_span> spans;
589 err = parseStyledString(bundle, in->getPrintableSource().string(),
590 block, item16, &str, &spans, isFormatted,
591 pseudolocalize);
592 if (err != NO_ERROR) {
593 return err;
594 }
595
596 NOISY(printf("Adding resource bag entry l=%c%c c=%c%c orien=%d d=%d "
597 " pid=%s, bag=%s, id=%s: %s\n",
598 config.language[0], config.language[1],
599 config.country[0], config.country[1],
600 config.orientation, config.density,
601 String8(parentIdent).string(),
602 String8(ident).string(),
603 String8(itemIdent).string(),
604 String8(str).string()));
605
606 err = outTable->addBag(SourcePos(in->getPrintableSource(), block->getLineNumber()),
607 myPackage, curType, ident, parentIdent, itemIdent, str,
608 &spans, &config, overwrite, false, curFormat);
609 return err;
610}
611
612/*
613 * Returns true if needle is one of the elements in the comma-separated list
614 * haystack, false otherwise.
615 */
616bool isInProductList(const String16& needle, const String16& haystack) {
617 const char16_t *needle2 = needle.string();
618 const char16_t *haystack2 = haystack.string();
619 size_t needlesize = needle.size();
620
621 while (*haystack2 != '\0') {
622 if (strncmp16(haystack2, needle2, needlesize) == 0) {
623 if (haystack2[needlesize] == '\0' || haystack2[needlesize] == ',') {
624 return true;
625 }
626 }
627
628 while (*haystack2 != '\0' && *haystack2 != ',') {
629 haystack2++;
630 }
631 if (*haystack2 == ',') {
632 haystack2++;
633 }
634 }
635
636 return false;
637}
638
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700639/*
640 * A simple container that holds a resource type and name. It is ordered first by type then
641 * by name.
642 */
643struct type_ident_pair_t {
644 String16 type;
645 String16 ident;
646
647 type_ident_pair_t() { };
648 type_ident_pair_t(const String16& t, const String16& i) : type(t), ident(i) { }
649 type_ident_pair_t(const type_ident_pair_t& o) : type(o.type), ident(o.ident) { }
650 inline bool operator < (const type_ident_pair_t& o) const {
651 int cmp = compare_type(type, o.type);
652 if (cmp < 0) {
653 return true;
654 } else if (cmp > 0) {
655 return false;
656 } else {
657 return strictly_order_type(ident, o.ident);
658 }
659 }
660};
661
662
Adam Lesinski282e1812014-01-23 18:17:42 -0800663status_t parseAndAddEntry(Bundle* bundle,
664 const sp<AaptFile>& in,
665 ResXMLTree* block,
666 const ResTable_config& config,
667 const String16& myPackage,
668 const String16& curType,
669 const String16& ident,
670 const String16& curTag,
671 bool curIsStyled,
672 int32_t curFormat,
673 bool isFormatted,
674 const String16& product,
Anton Krumina2ef5c02014-03-12 14:46:44 -0700675 PseudolocalizationMethod pseudolocalize,
Adam Lesinski282e1812014-01-23 18:17:42 -0800676 const bool overwrite,
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700677 KeyedVector<type_ident_pair_t, bool>* skippedResourceNames,
Adam Lesinski282e1812014-01-23 18:17:42 -0800678 ResourceTable* outTable)
679{
680 status_t err;
681
682 String16 str;
683 Vector<StringPool::entry_style_span> spans;
684 err = parseStyledString(bundle, in->getPrintableSource().string(), block,
685 curTag, &str, curIsStyled ? &spans : NULL,
686 isFormatted, pseudolocalize);
687
688 if (err < NO_ERROR) {
689 return err;
690 }
691
692 /*
693 * If a product type was specified on the command line
694 * and also in the string, and the two are not the same,
695 * return without adding the string.
696 */
697
698 const char *bundleProduct = bundle->getProduct();
699 if (bundleProduct == NULL) {
700 bundleProduct = "";
701 }
702
703 if (product.size() != 0) {
704 /*
705 * If the command-line-specified product is empty, only "default"
706 * matches. Other variants are skipped. This is so generation
707 * of the R.java file when the product is not known is predictable.
708 */
709
710 if (bundleProduct[0] == '\0') {
711 if (strcmp16(String16("default").string(), product.string()) != 0) {
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700712 /*
713 * This string has a product other than 'default'. Do not add it,
714 * but record it so that if we do not see the same string with
715 * product 'default' or no product, then report an error.
716 */
717 skippedResourceNames->replaceValueFor(
718 type_ident_pair_t(curType, ident), true);
Adam Lesinski282e1812014-01-23 18:17:42 -0800719 return NO_ERROR;
720 }
721 } else {
722 /*
723 * The command-line product is not empty.
724 * If the product for this string is on the command-line list,
725 * it matches. "default" also matches, but only if nothing
726 * else has matched already.
727 */
728
729 if (isInProductList(product, String16(bundleProduct))) {
730 ;
731 } else if (strcmp16(String16("default").string(), product.string()) == 0 &&
732 !outTable->hasBagOrEntry(myPackage, curType, ident, config)) {
733 ;
734 } else {
735 return NO_ERROR;
736 }
737 }
738 }
739
740 NOISY(printf("Adding resource entry l=%c%c c=%c%c orien=%d d=%d id=%s: %s\n",
741 config.language[0], config.language[1],
742 config.country[0], config.country[1],
743 config.orientation, config.density,
744 String8(ident).string(), String8(str).string()));
745
746 err = outTable->addEntry(SourcePos(in->getPrintableSource(), block->getLineNumber()),
747 myPackage, curType, ident, str, &spans, &config,
748 false, curFormat, overwrite);
749
750 return err;
751}
752
753status_t compileResourceFile(Bundle* bundle,
754 const sp<AaptAssets>& assets,
755 const sp<AaptFile>& in,
756 const ResTable_config& defParams,
757 const bool overwrite,
758 ResourceTable* outTable)
759{
760 ResXMLTree block;
761 status_t err = parseXMLResource(in, &block, false, true);
762 if (err != NO_ERROR) {
763 return err;
764 }
765
766 // Top-level tag.
767 const String16 resources16("resources");
768
769 // Identifier declaration tags.
770 const String16 declare_styleable16("declare-styleable");
771 const String16 attr16("attr");
772
773 // Data creation organizational tags.
774 const String16 string16("string");
775 const String16 drawable16("drawable");
776 const String16 color16("color");
777 const String16 bool16("bool");
778 const String16 integer16("integer");
779 const String16 dimen16("dimen");
780 const String16 fraction16("fraction");
781 const String16 style16("style");
782 const String16 plurals16("plurals");
783 const String16 array16("array");
784 const String16 string_array16("string-array");
785 const String16 integer_array16("integer-array");
786 const String16 public16("public");
787 const String16 public_padding16("public-padding");
788 const String16 private_symbols16("private-symbols");
789 const String16 java_symbol16("java-symbol");
790 const String16 add_resource16("add-resource");
791 const String16 skip16("skip");
792 const String16 eat_comment16("eat-comment");
793
794 // Data creation tags.
795 const String16 bag16("bag");
796 const String16 item16("item");
797
798 // Attribute type constants.
799 const String16 enum16("enum");
800
801 // plural values
802 const String16 other16("other");
803 const String16 quantityOther16("^other");
804 const String16 zero16("zero");
805 const String16 quantityZero16("^zero");
806 const String16 one16("one");
807 const String16 quantityOne16("^one");
808 const String16 two16("two");
809 const String16 quantityTwo16("^two");
810 const String16 few16("few");
811 const String16 quantityFew16("^few");
812 const String16 many16("many");
813 const String16 quantityMany16("^many");
814
815 // useful attribute names and special values
816 const String16 name16("name");
817 const String16 translatable16("translatable");
818 const String16 formatted16("formatted");
819 const String16 false16("false");
820
821 const String16 myPackage(assets->getPackage());
822
823 bool hasErrors = false;
824
825 bool fileIsTranslatable = true;
826 if (strstr(in->getPrintableSource().string(), "donottranslate") != NULL) {
827 fileIsTranslatable = false;
828 }
829
830 DefaultKeyedVector<String16, uint32_t> nextPublicId(0);
831
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700832 // Stores the resource names that were skipped. Typically this happens when
833 // AAPT is invoked without a product specified and a resource has no
834 // 'default' product attribute.
835 KeyedVector<type_ident_pair_t, bool> skippedResourceNames;
836
Adam Lesinski282e1812014-01-23 18:17:42 -0800837 ResXMLTree::event_code_t code;
838 do {
839 code = block.next();
840 } while (code == ResXMLTree::START_NAMESPACE);
841
842 size_t len;
843 if (code != ResXMLTree::START_TAG) {
844 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
845 "No start tag found\n");
846 return UNKNOWN_ERROR;
847 }
848 if (strcmp16(block.getElementName(&len), resources16.string()) != 0) {
849 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
850 "Invalid start tag %s\n", String8(block.getElementName(&len)).string());
851 return UNKNOWN_ERROR;
852 }
853
854 ResTable_config curParams(defParams);
855
856 ResTable_config pseudoParams(curParams);
Anton Krumina2ef5c02014-03-12 14:46:44 -0700857 pseudoParams.language[0] = 'e';
858 pseudoParams.language[1] = 'n';
859 pseudoParams.country[0] = 'X';
860 pseudoParams.country[1] = 'A';
861
862 ResTable_config pseudoBidiParams(curParams);
863 pseudoBidiParams.language[0] = 'a';
864 pseudoBidiParams.language[1] = 'r';
865 pseudoBidiParams.country[0] = 'X';
866 pseudoBidiParams.country[1] = 'B';
Adam Lesinski282e1812014-01-23 18:17:42 -0800867
Igor Viarheichyk47843df2014-05-01 17:04:39 -0700868 // We should skip resources for pseudolocales if they were
869 // already added automatically. This is a fix for a transition period when
870 // manually pseudolocalized resources may be expected.
871 // TODO: remove this check after next SDK version release.
872 if ((bundle->getPseudolocalize() & PSEUDO_ACCENTED &&
873 curParams.locale == pseudoParams.locale) ||
874 (bundle->getPseudolocalize() & PSEUDO_BIDI &&
875 curParams.locale == pseudoBidiParams.locale)) {
876 SourcePos(in->getPrintableSource(), 0).warning(
877 "Resource file %s is skipped as pseudolocalization"
878 " was done automatically.",
879 in->getPrintableSource().string());
880 return NO_ERROR;
881 }
882
Adam Lesinski282e1812014-01-23 18:17:42 -0800883 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
884 if (code == ResXMLTree::START_TAG) {
885 const String16* curTag = NULL;
886 String16 curType;
887 int32_t curFormat = ResTable_map::TYPE_ANY;
888 bool curIsBag = false;
889 bool curIsBagReplaceOnOverwrite = false;
890 bool curIsStyled = false;
891 bool curIsPseudolocalizable = false;
892 bool curIsFormatted = fileIsTranslatable;
893 bool localHasErrors = false;
894
895 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
896 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
897 && code != ResXMLTree::BAD_DOCUMENT) {
898 if (code == ResXMLTree::END_TAG) {
899 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
900 break;
901 }
902 }
903 }
904 continue;
905
906 } else if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
907 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
908 && code != ResXMLTree::BAD_DOCUMENT) {
909 if (code == ResXMLTree::END_TAG) {
910 if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
911 break;
912 }
913 }
914 }
915 continue;
916
917 } else if (strcmp16(block.getElementName(&len), public16.string()) == 0) {
918 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
919
920 String16 type;
921 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
922 if (typeIdx < 0) {
923 srcPos.error("A 'type' attribute is required for <public>\n");
924 hasErrors = localHasErrors = true;
925 }
926 type = String16(block.getAttributeStringValue(typeIdx, &len));
927
928 String16 name;
929 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
930 if (nameIdx < 0) {
931 srcPos.error("A 'name' attribute is required for <public>\n");
932 hasErrors = localHasErrors = true;
933 }
934 name = String16(block.getAttributeStringValue(nameIdx, &len));
935
936 uint32_t ident = 0;
937 ssize_t identIdx = block.indexOfAttribute(NULL, "id");
938 if (identIdx >= 0) {
939 const char16_t* identStr = block.getAttributeStringValue(identIdx, &len);
940 Res_value identValue;
941 if (!ResTable::stringToInt(identStr, len, &identValue)) {
942 srcPos.error("Given 'id' attribute is not an integer: %s\n",
943 String8(block.getAttributeStringValue(identIdx, &len)).string());
944 hasErrors = localHasErrors = true;
945 } else {
946 ident = identValue.data;
947 nextPublicId.replaceValueFor(type, ident+1);
948 }
949 } else if (nextPublicId.indexOfKey(type) < 0) {
950 srcPos.error("No 'id' attribute supplied <public>,"
951 " and no previous id defined in this file.\n");
952 hasErrors = localHasErrors = true;
953 } else if (!localHasErrors) {
954 ident = nextPublicId.valueFor(type);
955 nextPublicId.replaceValueFor(type, ident+1);
956 }
957
958 if (!localHasErrors) {
959 err = outTable->addPublic(srcPos, myPackage, type, name, ident);
960 if (err < NO_ERROR) {
961 hasErrors = localHasErrors = true;
962 }
963 }
964 if (!localHasErrors) {
965 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
966 if (symbols != NULL) {
967 symbols = symbols->addNestedSymbol(String8(type), srcPos);
968 }
969 if (symbols != NULL) {
970 symbols->makeSymbolPublic(String8(name), srcPos);
971 String16 comment(
972 block.getComment(&len) ? block.getComment(&len) : nulStr);
973 symbols->appendComment(String8(name), comment, srcPos);
974 } else {
975 srcPos.error("Unable to create symbols!\n");
976 hasErrors = localHasErrors = true;
977 }
978 }
979
980 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
981 if (code == ResXMLTree::END_TAG) {
982 if (strcmp16(block.getElementName(&len), public16.string()) == 0) {
983 break;
984 }
985 }
986 }
987 continue;
988
989 } else if (strcmp16(block.getElementName(&len), public_padding16.string()) == 0) {
990 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
991
992 String16 type;
993 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
994 if (typeIdx < 0) {
995 srcPos.error("A 'type' attribute is required for <public-padding>\n");
996 hasErrors = localHasErrors = true;
997 }
998 type = String16(block.getAttributeStringValue(typeIdx, &len));
999
1000 String16 name;
1001 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1002 if (nameIdx < 0) {
1003 srcPos.error("A 'name' attribute is required for <public-padding>\n");
1004 hasErrors = localHasErrors = true;
1005 }
1006 name = String16(block.getAttributeStringValue(nameIdx, &len));
1007
1008 uint32_t start = 0;
1009 ssize_t startIdx = block.indexOfAttribute(NULL, "start");
1010 if (startIdx >= 0) {
1011 const char16_t* startStr = block.getAttributeStringValue(startIdx, &len);
1012 Res_value startValue;
1013 if (!ResTable::stringToInt(startStr, len, &startValue)) {
1014 srcPos.error("Given 'start' attribute is not an integer: %s\n",
1015 String8(block.getAttributeStringValue(startIdx, &len)).string());
1016 hasErrors = localHasErrors = true;
1017 } else {
1018 start = startValue.data;
1019 }
1020 } else if (nextPublicId.indexOfKey(type) < 0) {
1021 srcPos.error("No 'start' attribute supplied <public-padding>,"
1022 " and no previous id defined in this file.\n");
1023 hasErrors = localHasErrors = true;
1024 } else if (!localHasErrors) {
1025 start = nextPublicId.valueFor(type);
1026 }
1027
1028 uint32_t end = 0;
1029 ssize_t endIdx = block.indexOfAttribute(NULL, "end");
1030 if (endIdx >= 0) {
1031 const char16_t* endStr = block.getAttributeStringValue(endIdx, &len);
1032 Res_value endValue;
1033 if (!ResTable::stringToInt(endStr, len, &endValue)) {
1034 srcPos.error("Given 'end' attribute is not an integer: %s\n",
1035 String8(block.getAttributeStringValue(endIdx, &len)).string());
1036 hasErrors = localHasErrors = true;
1037 } else {
1038 end = endValue.data;
1039 }
1040 } else {
1041 srcPos.error("No 'end' attribute supplied <public-padding>\n");
1042 hasErrors = localHasErrors = true;
1043 }
1044
1045 if (end >= start) {
1046 nextPublicId.replaceValueFor(type, end+1);
1047 } else {
1048 srcPos.error("Padding start '%ul' is after end '%ul'\n",
1049 start, end);
1050 hasErrors = localHasErrors = true;
1051 }
1052
1053 String16 comment(
1054 block.getComment(&len) ? block.getComment(&len) : nulStr);
1055 for (uint32_t curIdent=start; curIdent<=end; curIdent++) {
1056 if (localHasErrors) {
1057 break;
1058 }
1059 String16 curName(name);
1060 char buf[64];
1061 sprintf(buf, "%d", (int)(end-curIdent+1));
1062 curName.append(String16(buf));
1063
1064 err = outTable->addEntry(srcPos, myPackage, type, curName,
1065 String16("padding"), NULL, &curParams, false,
1066 ResTable_map::TYPE_STRING, overwrite);
1067 if (err < NO_ERROR) {
1068 hasErrors = localHasErrors = true;
1069 break;
1070 }
1071 err = outTable->addPublic(srcPos, myPackage, type,
1072 curName, curIdent);
1073 if (err < NO_ERROR) {
1074 hasErrors = localHasErrors = true;
1075 break;
1076 }
1077 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1078 if (symbols != NULL) {
1079 symbols = symbols->addNestedSymbol(String8(type), srcPos);
1080 }
1081 if (symbols != NULL) {
1082 symbols->makeSymbolPublic(String8(curName), srcPos);
1083 symbols->appendComment(String8(curName), comment, srcPos);
1084 } else {
1085 srcPos.error("Unable to create symbols!\n");
1086 hasErrors = localHasErrors = true;
1087 }
1088 }
1089
1090 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1091 if (code == ResXMLTree::END_TAG) {
1092 if (strcmp16(block.getElementName(&len), public_padding16.string()) == 0) {
1093 break;
1094 }
1095 }
1096 }
1097 continue;
1098
1099 } else if (strcmp16(block.getElementName(&len), private_symbols16.string()) == 0) {
1100 String16 pkg;
1101 ssize_t pkgIdx = block.indexOfAttribute(NULL, "package");
1102 if (pkgIdx < 0) {
1103 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1104 "A 'package' attribute is required for <private-symbols>\n");
1105 hasErrors = localHasErrors = true;
1106 }
1107 pkg = String16(block.getAttributeStringValue(pkgIdx, &len));
1108 if (!localHasErrors) {
1109 assets->setSymbolsPrivatePackage(String8(pkg));
1110 }
1111
1112 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1113 if (code == ResXMLTree::END_TAG) {
1114 if (strcmp16(block.getElementName(&len), private_symbols16.string()) == 0) {
1115 break;
1116 }
1117 }
1118 }
1119 continue;
1120
1121 } else if (strcmp16(block.getElementName(&len), java_symbol16.string()) == 0) {
1122 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1123
1124 String16 type;
1125 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
1126 if (typeIdx < 0) {
1127 srcPos.error("A 'type' attribute is required for <public>\n");
1128 hasErrors = localHasErrors = true;
1129 }
1130 type = String16(block.getAttributeStringValue(typeIdx, &len));
1131
1132 String16 name;
1133 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1134 if (nameIdx < 0) {
1135 srcPos.error("A 'name' attribute is required for <public>\n");
1136 hasErrors = localHasErrors = true;
1137 }
1138 name = String16(block.getAttributeStringValue(nameIdx, &len));
1139
1140 sp<AaptSymbols> symbols = assets->getJavaSymbolsFor(String8("R"));
1141 if (symbols != NULL) {
1142 symbols = symbols->addNestedSymbol(String8(type), srcPos);
1143 }
1144 if (symbols != NULL) {
1145 symbols->makeSymbolJavaSymbol(String8(name), srcPos);
1146 String16 comment(
1147 block.getComment(&len) ? block.getComment(&len) : nulStr);
1148 symbols->appendComment(String8(name), comment, srcPos);
1149 } else {
1150 srcPos.error("Unable to create symbols!\n");
1151 hasErrors = localHasErrors = true;
1152 }
1153
1154 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1155 if (code == ResXMLTree::END_TAG) {
1156 if (strcmp16(block.getElementName(&len), java_symbol16.string()) == 0) {
1157 break;
1158 }
1159 }
1160 }
1161 continue;
1162
1163
1164 } else if (strcmp16(block.getElementName(&len), add_resource16.string()) == 0) {
1165 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1166
1167 String16 typeName;
1168 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
1169 if (typeIdx < 0) {
1170 srcPos.error("A 'type' attribute is required for <add-resource>\n");
1171 hasErrors = localHasErrors = true;
1172 }
1173 typeName = String16(block.getAttributeStringValue(typeIdx, &len));
1174
1175 String16 name;
1176 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1177 if (nameIdx < 0) {
1178 srcPos.error("A 'name' attribute is required for <add-resource>\n");
1179 hasErrors = localHasErrors = true;
1180 }
1181 name = String16(block.getAttributeStringValue(nameIdx, &len));
1182
1183 outTable->canAddEntry(srcPos, myPackage, typeName, name);
1184
1185 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1186 if (code == ResXMLTree::END_TAG) {
1187 if (strcmp16(block.getElementName(&len), add_resource16.string()) == 0) {
1188 break;
1189 }
1190 }
1191 }
1192 continue;
1193
1194 } else if (strcmp16(block.getElementName(&len), declare_styleable16.string()) == 0) {
1195 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1196
1197 String16 ident;
1198 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
1199 if (identIdx < 0) {
1200 srcPos.error("A 'name' attribute is required for <declare-styleable>\n");
1201 hasErrors = localHasErrors = true;
1202 }
1203 ident = String16(block.getAttributeStringValue(identIdx, &len));
1204
1205 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1206 if (!localHasErrors) {
1207 if (symbols != NULL) {
1208 symbols = symbols->addNestedSymbol(String8("styleable"), srcPos);
1209 }
1210 sp<AaptSymbols> styleSymbols = symbols;
1211 if (symbols != NULL) {
1212 symbols = symbols->addNestedSymbol(String8(ident), srcPos);
1213 }
1214 if (symbols == NULL) {
1215 srcPos.error("Unable to create symbols!\n");
1216 return UNKNOWN_ERROR;
1217 }
1218
1219 String16 comment(
1220 block.getComment(&len) ? block.getComment(&len) : nulStr);
1221 styleSymbols->appendComment(String8(ident), comment, srcPos);
1222 } else {
1223 symbols = NULL;
1224 }
1225
1226 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1227 if (code == ResXMLTree::START_TAG) {
1228 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
1229 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1230 && code != ResXMLTree::BAD_DOCUMENT) {
1231 if (code == ResXMLTree::END_TAG) {
1232 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
1233 break;
1234 }
1235 }
1236 }
1237 continue;
1238 } else if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
1239 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1240 && code != ResXMLTree::BAD_DOCUMENT) {
1241 if (code == ResXMLTree::END_TAG) {
1242 if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
1243 break;
1244 }
1245 }
1246 }
1247 continue;
1248 } else if (strcmp16(block.getElementName(&len), attr16.string()) != 0) {
1249 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1250 "Tag <%s> can not appear inside <declare-styleable>, only <attr>\n",
1251 String8(block.getElementName(&len)).string());
1252 return UNKNOWN_ERROR;
1253 }
1254
1255 String16 comment(
1256 block.getComment(&len) ? block.getComment(&len) : nulStr);
1257 String16 itemIdent;
1258 err = compileAttribute(in, block, myPackage, outTable, &itemIdent, true);
1259 if (err != NO_ERROR) {
1260 hasErrors = localHasErrors = true;
1261 }
1262
1263 if (symbols != NULL) {
1264 SourcePos srcPos(String8(in->getPrintableSource()), block.getLineNumber());
1265 symbols->addSymbol(String8(itemIdent), 0, srcPos);
1266 symbols->appendComment(String8(itemIdent), comment, srcPos);
1267 //printf("Attribute %s comment: %s\n", String8(itemIdent).string(),
1268 // String8(comment).string());
1269 }
1270 } else if (code == ResXMLTree::END_TAG) {
1271 if (strcmp16(block.getElementName(&len), declare_styleable16.string()) == 0) {
1272 break;
1273 }
1274
1275 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1276 "Found tag </%s> where </attr> is expected\n",
1277 String8(block.getElementName(&len)).string());
1278 return UNKNOWN_ERROR;
1279 }
1280 }
1281 continue;
1282
1283 } else if (strcmp16(block.getElementName(&len), attr16.string()) == 0) {
1284 err = compileAttribute(in, block, myPackage, outTable, NULL);
1285 if (err != NO_ERROR) {
1286 hasErrors = true;
1287 }
1288 continue;
1289
1290 } else if (strcmp16(block.getElementName(&len), item16.string()) == 0) {
1291 curTag = &item16;
1292 ssize_t attri = block.indexOfAttribute(NULL, "type");
1293 if (attri >= 0) {
1294 curType = String16(block.getAttributeStringValue(attri, &len));
1295 ssize_t formatIdx = block.indexOfAttribute(NULL, "format");
1296 if (formatIdx >= 0) {
1297 String16 formatStr = String16(block.getAttributeStringValue(
1298 formatIdx, &len));
1299 curFormat = parse_flags(formatStr.string(), formatStr.size(),
1300 gFormatFlags);
1301 if (curFormat == 0) {
1302 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1303 "Tag <item> 'format' attribute value \"%s\" not valid\n",
1304 String8(formatStr).string());
1305 hasErrors = localHasErrors = true;
1306 }
1307 }
1308 } else {
1309 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1310 "A 'type' attribute is required for <item>\n");
1311 hasErrors = localHasErrors = true;
1312 }
1313 curIsStyled = true;
1314 } else if (strcmp16(block.getElementName(&len), string16.string()) == 0) {
1315 // Note the existence and locale of every string we process
Narayan Kamath91447d82014-01-21 15:32:36 +00001316 char rawLocale[RESTABLE_MAX_LOCALE_LEN];
1317 curParams.getBcp47Locale(rawLocale);
Adam Lesinski282e1812014-01-23 18:17:42 -08001318 String8 locale(rawLocale);
1319 String16 name;
1320 String16 translatable;
1321 String16 formatted;
1322
1323 size_t n = block.getAttributeCount();
1324 for (size_t i = 0; i < n; i++) {
1325 size_t length;
1326 const uint16_t* attr = block.getAttributeName(i, &length);
1327 if (strcmp16(attr, name16.string()) == 0) {
1328 name.setTo(block.getAttributeStringValue(i, &length));
1329 } else if (strcmp16(attr, translatable16.string()) == 0) {
1330 translatable.setTo(block.getAttributeStringValue(i, &length));
1331 } else if (strcmp16(attr, formatted16.string()) == 0) {
1332 formatted.setTo(block.getAttributeStringValue(i, &length));
1333 }
1334 }
1335
1336 if (name.size() > 0) {
1337 if (translatable == false16) {
1338 curIsFormatted = false;
1339 // Untranslatable strings must only exist in the default [empty] locale
1340 if (locale.size() > 0) {
Adam Lesinskia01a9372014-03-20 18:04:57 -07001341 SourcePos(in->getPrintableSource(), block.getLineNumber()).warning(
1342 "string '%s' marked untranslatable but exists in locale '%s'\n",
1343 String8(name).string(),
Adam Lesinski282e1812014-01-23 18:17:42 -08001344 locale.string());
1345 // hasErrors = localHasErrors = true;
1346 } else {
1347 // Intentionally empty block:
1348 //
1349 // Don't add untranslatable strings to the localization table; that
1350 // way if we later see localizations of them, they'll be flagged as
1351 // having no default translation.
1352 }
1353 } else {
Adam Lesinskia01a9372014-03-20 18:04:57 -07001354 outTable->addLocalization(
1355 name,
1356 locale,
1357 SourcePos(in->getPrintableSource(), block.getLineNumber()));
Adam Lesinski282e1812014-01-23 18:17:42 -08001358 }
1359
1360 if (formatted == false16) {
1361 curIsFormatted = false;
1362 }
1363 }
1364
1365 curTag = &string16;
1366 curType = string16;
1367 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
1368 curIsStyled = true;
Igor Viarheichyk84410b02014-04-30 11:56:42 -07001369 curIsPseudolocalizable = fileIsTranslatable && (translatable != false16);
Adam Lesinski282e1812014-01-23 18:17:42 -08001370 } else if (strcmp16(block.getElementName(&len), drawable16.string()) == 0) {
1371 curTag = &drawable16;
1372 curType = drawable16;
1373 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
1374 } else if (strcmp16(block.getElementName(&len), color16.string()) == 0) {
1375 curTag = &color16;
1376 curType = color16;
1377 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
1378 } else if (strcmp16(block.getElementName(&len), bool16.string()) == 0) {
1379 curTag = &bool16;
1380 curType = bool16;
1381 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_BOOLEAN;
1382 } else if (strcmp16(block.getElementName(&len), integer16.string()) == 0) {
1383 curTag = &integer16;
1384 curType = integer16;
1385 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
1386 } else if (strcmp16(block.getElementName(&len), dimen16.string()) == 0) {
1387 curTag = &dimen16;
1388 curType = dimen16;
1389 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_DIMENSION;
1390 } else if (strcmp16(block.getElementName(&len), fraction16.string()) == 0) {
1391 curTag = &fraction16;
1392 curType = fraction16;
1393 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_FRACTION;
1394 } else if (strcmp16(block.getElementName(&len), bag16.string()) == 0) {
1395 curTag = &bag16;
1396 curIsBag = true;
1397 ssize_t attri = block.indexOfAttribute(NULL, "type");
1398 if (attri >= 0) {
1399 curType = String16(block.getAttributeStringValue(attri, &len));
1400 } else {
1401 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1402 "A 'type' attribute is required for <bag>\n");
1403 hasErrors = localHasErrors = true;
1404 }
1405 } else if (strcmp16(block.getElementName(&len), style16.string()) == 0) {
1406 curTag = &style16;
1407 curType = style16;
1408 curIsBag = true;
1409 } else if (strcmp16(block.getElementName(&len), plurals16.string()) == 0) {
1410 curTag = &plurals16;
1411 curType = plurals16;
1412 curIsBag = true;
Anton Krumina2ef5c02014-03-12 14:46:44 -07001413 curIsPseudolocalizable = fileIsTranslatable;
Adam Lesinski282e1812014-01-23 18:17:42 -08001414 } else if (strcmp16(block.getElementName(&len), array16.string()) == 0) {
1415 curTag = &array16;
1416 curType = array16;
1417 curIsBag = true;
1418 curIsBagReplaceOnOverwrite = true;
1419 ssize_t formatIdx = block.indexOfAttribute(NULL, "format");
1420 if (formatIdx >= 0) {
1421 String16 formatStr = String16(block.getAttributeStringValue(
1422 formatIdx, &len));
1423 curFormat = parse_flags(formatStr.string(), formatStr.size(),
1424 gFormatFlags);
1425 if (curFormat == 0) {
1426 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1427 "Tag <array> 'format' attribute value \"%s\" not valid\n",
1428 String8(formatStr).string());
1429 hasErrors = localHasErrors = true;
1430 }
1431 }
1432 } else if (strcmp16(block.getElementName(&len), string_array16.string()) == 0) {
1433 // Check whether these strings need valid formats.
1434 // (simplified form of what string16 does above)
Anton Krumina2ef5c02014-03-12 14:46:44 -07001435 bool isTranslatable = false;
Adam Lesinski282e1812014-01-23 18:17:42 -08001436 size_t n = block.getAttributeCount();
Narayan Kamath9a9fa162013-12-18 13:27:30 +00001437
1438 // Pseudolocalizable by default, unless this string array isn't
1439 // translatable.
Adam Lesinski282e1812014-01-23 18:17:42 -08001440 for (size_t i = 0; i < n; i++) {
1441 size_t length;
1442 const uint16_t* attr = block.getAttributeName(i, &length);
Narayan Kamath9a9fa162013-12-18 13:27:30 +00001443 if (strcmp16(attr, formatted16.string()) == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001444 const uint16_t* value = block.getAttributeStringValue(i, &length);
1445 if (strcmp16(value, false16.string()) == 0) {
1446 curIsFormatted = false;
Adam Lesinski282e1812014-01-23 18:17:42 -08001447 }
Anton Krumina2ef5c02014-03-12 14:46:44 -07001448 } else if (strcmp16(attr, translatable16.string()) == 0) {
1449 const uint16_t* value = block.getAttributeStringValue(i, &length);
1450 if (strcmp16(value, false16.string()) == 0) {
1451 isTranslatable = false;
1452 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001453 }
1454 }
1455
1456 curTag = &string_array16;
1457 curType = array16;
1458 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
1459 curIsBag = true;
1460 curIsBagReplaceOnOverwrite = true;
Anton Krumina2ef5c02014-03-12 14:46:44 -07001461 curIsPseudolocalizable = isTranslatable && fileIsTranslatable;
Adam Lesinski282e1812014-01-23 18:17:42 -08001462 } else if (strcmp16(block.getElementName(&len), integer_array16.string()) == 0) {
1463 curTag = &integer_array16;
1464 curType = array16;
1465 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
1466 curIsBag = true;
1467 curIsBagReplaceOnOverwrite = true;
1468 } else {
1469 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1470 "Found tag %s where item is expected\n",
1471 String8(block.getElementName(&len)).string());
1472 return UNKNOWN_ERROR;
1473 }
1474
1475 String16 ident;
1476 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
1477 if (identIdx >= 0) {
1478 ident = String16(block.getAttributeStringValue(identIdx, &len));
1479 } else {
1480 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1481 "A 'name' attribute is required for <%s>\n",
1482 String8(*curTag).string());
1483 hasErrors = localHasErrors = true;
1484 }
1485
1486 String16 product;
1487 identIdx = block.indexOfAttribute(NULL, "product");
1488 if (identIdx >= 0) {
1489 product = String16(block.getAttributeStringValue(identIdx, &len));
1490 }
1491
1492 String16 comment(block.getComment(&len) ? block.getComment(&len) : nulStr);
1493
1494 if (curIsBag) {
1495 // Figure out the parent of this bag...
1496 String16 parentIdent;
1497 ssize_t parentIdentIdx = block.indexOfAttribute(NULL, "parent");
1498 if (parentIdentIdx >= 0) {
1499 parentIdent = String16(block.getAttributeStringValue(parentIdentIdx, &len));
1500 } else {
1501 ssize_t sep = ident.findLast('.');
1502 if (sep >= 0) {
1503 parentIdent.setTo(ident, sep);
1504 }
1505 }
1506
1507 if (!localHasErrors) {
1508 err = outTable->startBag(SourcePos(in->getPrintableSource(),
1509 block.getLineNumber()), myPackage, curType, ident,
1510 parentIdent, &curParams,
1511 overwrite, curIsBagReplaceOnOverwrite);
1512 if (err != NO_ERROR) {
1513 hasErrors = localHasErrors = true;
1514 }
1515 }
1516
1517 ssize_t elmIndex = 0;
1518 char elmIndexStr[14];
1519 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1520 && code != ResXMLTree::BAD_DOCUMENT) {
1521
1522 if (code == ResXMLTree::START_TAG) {
1523 if (strcmp16(block.getElementName(&len), item16.string()) != 0) {
1524 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1525 "Tag <%s> can not appear inside <%s>, only <item>\n",
1526 String8(block.getElementName(&len)).string(),
1527 String8(*curTag).string());
1528 return UNKNOWN_ERROR;
1529 }
1530
1531 String16 itemIdent;
1532 if (curType == array16) {
1533 sprintf(elmIndexStr, "^index_%d", (int)elmIndex++);
1534 itemIdent = String16(elmIndexStr);
1535 } else if (curType == plurals16) {
1536 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "quantity");
1537 if (itemIdentIdx >= 0) {
1538 String16 quantity16(block.getAttributeStringValue(itemIdentIdx, &len));
1539 if (quantity16 == other16) {
1540 itemIdent = quantityOther16;
1541 }
1542 else if (quantity16 == zero16) {
1543 itemIdent = quantityZero16;
1544 }
1545 else if (quantity16 == one16) {
1546 itemIdent = quantityOne16;
1547 }
1548 else if (quantity16 == two16) {
1549 itemIdent = quantityTwo16;
1550 }
1551 else if (quantity16 == few16) {
1552 itemIdent = quantityFew16;
1553 }
1554 else if (quantity16 == many16) {
1555 itemIdent = quantityMany16;
1556 }
1557 else {
1558 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1559 "Illegal 'quantity' attribute is <item> inside <plurals>\n");
1560 hasErrors = localHasErrors = true;
1561 }
1562 } else {
1563 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1564 "A 'quantity' attribute is required for <item> inside <plurals>\n");
1565 hasErrors = localHasErrors = true;
1566 }
1567 } else {
1568 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "name");
1569 if (itemIdentIdx >= 0) {
1570 itemIdent = String16(block.getAttributeStringValue(itemIdentIdx, &len));
1571 } else {
1572 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1573 "A 'name' attribute is required for <item>\n");
1574 hasErrors = localHasErrors = true;
1575 }
1576 }
1577
1578 ResXMLParser::ResXMLPosition parserPosition;
1579 block.getPosition(&parserPosition);
1580
1581 err = parseAndAddBag(bundle, in, &block, curParams, myPackage, curType,
1582 ident, parentIdent, itemIdent, curFormat, curIsFormatted,
Anton Krumina2ef5c02014-03-12 14:46:44 -07001583 product, NO_PSEUDOLOCALIZATION, overwrite, outTable);
Adam Lesinski282e1812014-01-23 18:17:42 -08001584 if (err == NO_ERROR) {
1585 if (curIsPseudolocalizable && localeIsDefined(curParams)
Anton Krumina2ef5c02014-03-12 14:46:44 -07001586 && bundle->getPseudolocalize() > 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001587 // pseudolocalize here
Anton Krumina2ef5c02014-03-12 14:46:44 -07001588 if ((PSEUDO_ACCENTED & bundle->getPseudolocalize()) ==
1589 PSEUDO_ACCENTED) {
1590 block.setPosition(parserPosition);
1591 err = parseAndAddBag(bundle, in, &block, pseudoParams, myPackage,
1592 curType, ident, parentIdent, itemIdent, curFormat,
1593 curIsFormatted, product, PSEUDO_ACCENTED,
1594 overwrite, outTable);
1595 }
1596 if ((PSEUDO_BIDI & bundle->getPseudolocalize()) ==
1597 PSEUDO_BIDI) {
1598 block.setPosition(parserPosition);
1599 err = parseAndAddBag(bundle, in, &block, pseudoBidiParams, myPackage,
1600 curType, ident, parentIdent, itemIdent, curFormat,
1601 curIsFormatted, product, PSEUDO_BIDI,
1602 overwrite, outTable);
1603 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001604 }
Anton Krumina2ef5c02014-03-12 14:46:44 -07001605 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001606 if (err != NO_ERROR) {
1607 hasErrors = localHasErrors = true;
1608 }
1609 } else if (code == ResXMLTree::END_TAG) {
1610 if (strcmp16(block.getElementName(&len), curTag->string()) != 0) {
1611 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1612 "Found tag </%s> where </%s> is expected\n",
1613 String8(block.getElementName(&len)).string(),
1614 String8(*curTag).string());
1615 return UNKNOWN_ERROR;
1616 }
1617 break;
1618 }
1619 }
1620 } else {
1621 ResXMLParser::ResXMLPosition parserPosition;
1622 block.getPosition(&parserPosition);
1623
1624 err = parseAndAddEntry(bundle, in, &block, curParams, myPackage, curType, ident,
1625 *curTag, curIsStyled, curFormat, curIsFormatted,
Anton Krumina2ef5c02014-03-12 14:46:44 -07001626 product, NO_PSEUDOLOCALIZATION, overwrite, &skippedResourceNames, outTable);
Adam Lesinski282e1812014-01-23 18:17:42 -08001627
1628 if (err < NO_ERROR) { // Why err < NO_ERROR instead of err != NO_ERROR?
1629 hasErrors = localHasErrors = true;
1630 }
1631 else if (err == NO_ERROR) {
1632 if (curIsPseudolocalizable && localeIsDefined(curParams)
Anton Krumina2ef5c02014-03-12 14:46:44 -07001633 && bundle->getPseudolocalize() > 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001634 // pseudolocalize here
Anton Krumina2ef5c02014-03-12 14:46:44 -07001635 if ((PSEUDO_ACCENTED & bundle->getPseudolocalize()) ==
1636 PSEUDO_ACCENTED) {
1637 block.setPosition(parserPosition);
1638 err = parseAndAddEntry(bundle, in, &block, pseudoParams, myPackage, curType,
1639 ident, *curTag, curIsStyled, curFormat,
1640 curIsFormatted, product,
1641 PSEUDO_ACCENTED, overwrite, &skippedResourceNames, outTable);
1642 }
1643 if ((PSEUDO_BIDI & bundle->getPseudolocalize()) ==
1644 PSEUDO_BIDI) {
1645 block.setPosition(parserPosition);
1646 err = parseAndAddEntry(bundle, in, &block, pseudoBidiParams,
1647 myPackage, curType, ident, *curTag, curIsStyled, curFormat,
1648 curIsFormatted, product,
1649 PSEUDO_BIDI, overwrite, &skippedResourceNames, outTable);
1650 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001651 if (err != NO_ERROR) {
1652 hasErrors = localHasErrors = true;
1653 }
1654 }
1655 }
1656 }
1657
1658#if 0
1659 if (comment.size() > 0) {
1660 printf("Comment for @%s:%s/%s: %s\n", String8(myPackage).string(),
1661 String8(curType).string(), String8(ident).string(),
1662 String8(comment).string());
1663 }
1664#endif
1665 if (!localHasErrors) {
1666 outTable->appendComment(myPackage, curType, ident, comment, false);
1667 }
1668 }
1669 else if (code == ResXMLTree::END_TAG) {
1670 if (strcmp16(block.getElementName(&len), resources16.string()) != 0) {
1671 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1672 "Unexpected end tag %s\n", String8(block.getElementName(&len)).string());
1673 return UNKNOWN_ERROR;
1674 }
1675 }
1676 else if (code == ResXMLTree::START_NAMESPACE || code == ResXMLTree::END_NAMESPACE) {
1677 }
1678 else if (code == ResXMLTree::TEXT) {
1679 if (isWhitespace(block.getText(&len))) {
1680 continue;
1681 }
1682 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1683 "Found text \"%s\" where item tag is expected\n",
1684 String8(block.getText(&len)).string());
1685 return UNKNOWN_ERROR;
1686 }
1687 }
1688
Adam Lesinski8ff15b42013-10-07 16:54:01 -07001689 // For every resource defined, there must be exist one variant with a product attribute
1690 // set to 'default' (or no product attribute at all).
1691 // We check to see that for every resource that was ignored because of a mismatched
1692 // product attribute, some product variant of that resource was processed.
1693 for (size_t i = 0; i < skippedResourceNames.size(); i++) {
1694 if (skippedResourceNames[i]) {
1695 const type_ident_pair_t& p = skippedResourceNames.keyAt(i);
1696 if (!outTable->hasBagOrEntry(myPackage, p.type, p.ident)) {
1697 const char* bundleProduct =
1698 (bundle->getProduct() == NULL) ? "" : bundle->getProduct();
1699 fprintf(stderr, "In resource file %s: %s\n",
1700 in->getPrintableSource().string(),
1701 curParams.toString().string());
1702
1703 fprintf(stderr, "\t%s '%s' does not match product %s.\n"
1704 "\tYou may have forgotten to include a 'default' product variant"
1705 " of the resource.\n",
1706 String8(p.type).string(), String8(p.ident).string(),
1707 bundleProduct[0] == 0 ? "default" : bundleProduct);
1708 return UNKNOWN_ERROR;
1709 }
1710 }
1711 }
1712
Adam Lesinski282e1812014-01-23 18:17:42 -08001713 return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
1714}
1715
1716ResourceTable::ResourceTable(Bundle* bundle, const String16& assetsPackage)
1717 : mAssetsPackage(assetsPackage), mNextPackageId(1), mHaveAppPackage(false),
Adam Lesinskide898ff2014-01-29 18:20:45 -08001718 mIsAppPackage(!bundle->getExtending()), mIsSharedLibrary(bundle->getBuildSharedLibrary()),
Adam Lesinski282e1812014-01-23 18:17:42 -08001719 mNumLocal(0),
1720 mBundle(bundle)
1721{
1722}
1723
1724status_t ResourceTable::addIncludedResources(Bundle* bundle, const sp<AaptAssets>& assets)
1725{
1726 status_t err = assets->buildIncludedResources(bundle);
1727 if (err != NO_ERROR) {
1728 return err;
1729 }
1730
1731 // For future reference to included resources.
1732 mAssets = assets;
1733
1734 const ResTable& incl = assets->getIncludedResources();
1735
1736 // Retrieve all the packages.
1737 const size_t N = incl.getBasePackageCount();
1738 for (size_t phase=0; phase<2; phase++) {
1739 for (size_t i=0; i<N; i++) {
Adam Lesinskide898ff2014-01-29 18:20:45 -08001740 const String16 name = incl.getBasePackageName(i);
Adam Lesinski282e1812014-01-23 18:17:42 -08001741 uint32_t id = incl.getBasePackageId(i);
Adam Lesinskide898ff2014-01-29 18:20:45 -08001742
Adam Lesinski282e1812014-01-23 18:17:42 -08001743 // First time through: only add base packages (id
1744 // is not 0); second time through add the other
1745 // packages.
1746 if (phase != 0) {
1747 if (id != 0) {
1748 // Skip base packages -- already one.
1749 id = 0;
1750 } else {
1751 // Assign a dynamic id.
1752 id = mNextPackageId;
1753 }
1754 } else if (id != 0) {
1755 if (id == 127) {
1756 if (mHaveAppPackage) {
1757 fprintf(stderr, "Included resources have two application packages!\n");
1758 return UNKNOWN_ERROR;
1759 }
1760 mHaveAppPackage = true;
1761 }
1762 if (mNextPackageId > id) {
1763 fprintf(stderr, "Included base package ID %d already in use!\n", id);
1764 return UNKNOWN_ERROR;
1765 }
1766 }
1767 if (id != 0) {
Adam Lesinskide898ff2014-01-29 18:20:45 -08001768 NOISY(fprintf(stderr, "Including package %s with ID=%d\n",
Adam Lesinski282e1812014-01-23 18:17:42 -08001769 String8(name).string(), id));
1770 sp<Package> p = new Package(name, id);
1771 mPackages.add(name, p);
1772 mOrderedPackages.add(p);
1773
1774 if (id >= mNextPackageId) {
1775 mNextPackageId = id+1;
1776 }
1777 }
1778 }
1779 }
1780
1781 // Every resource table always has one first entry, the bag attributes.
1782 const SourcePos unknown(String8("????"), 0);
1783 sp<Type> attr = getType(mAssetsPackage, String16("attr"), unknown);
1784
1785 return NO_ERROR;
1786}
1787
1788status_t ResourceTable::addPublic(const SourcePos& sourcePos,
1789 const String16& package,
1790 const String16& type,
1791 const String16& name,
1792 const uint32_t ident)
1793{
1794 uint32_t rid = mAssets->getIncludedResources()
1795 .identifierForName(name.string(), name.size(),
1796 type.string(), type.size(),
1797 package.string(), package.size());
1798 if (rid != 0) {
1799 sourcePos.error("Error declaring public resource %s/%s for included package %s\n",
1800 String8(type).string(), String8(name).string(),
1801 String8(package).string());
1802 return UNKNOWN_ERROR;
1803 }
1804
1805 sp<Type> t = getType(package, type, sourcePos);
1806 if (t == NULL) {
1807 return UNKNOWN_ERROR;
1808 }
1809 return t->addPublic(sourcePos, name, ident);
1810}
1811
1812status_t ResourceTable::addEntry(const SourcePos& sourcePos,
1813 const String16& package,
1814 const String16& type,
1815 const String16& name,
1816 const String16& value,
1817 const Vector<StringPool::entry_style_span>* style,
1818 const ResTable_config* params,
1819 const bool doSetIndex,
1820 const int32_t format,
1821 const bool overwrite)
1822{
1823 // Check for adding entries in other packages... for now we do
1824 // nothing. We need to do the right thing here to support skinning.
1825 uint32_t rid = mAssets->getIncludedResources()
1826 .identifierForName(name.string(), name.size(),
1827 type.string(), type.size(),
1828 package.string(), package.size());
1829 if (rid != 0) {
1830 return NO_ERROR;
1831 }
1832
1833#if 0
1834 if (name == String16("left")) {
1835 printf("Adding entry left: file=%s, line=%d, type=%s, value=%s\n",
1836 sourcePos.file.string(), sourcePos.line, String8(type).string(),
1837 String8(value).string());
1838 }
1839#endif
1840
1841 sp<Entry> e = getEntry(package, type, name, sourcePos, overwrite,
1842 params, doSetIndex);
1843 if (e == NULL) {
1844 return UNKNOWN_ERROR;
1845 }
1846 status_t err = e->setItem(sourcePos, value, style, format, overwrite);
1847 if (err == NO_ERROR) {
1848 mNumLocal++;
1849 }
1850 return err;
1851}
1852
1853status_t ResourceTable::startBag(const SourcePos& sourcePos,
1854 const String16& package,
1855 const String16& type,
1856 const String16& name,
1857 const String16& bagParent,
1858 const ResTable_config* params,
1859 bool overlay,
1860 bool replace, bool isId)
1861{
1862 status_t result = NO_ERROR;
1863
1864 // Check for adding entries in other packages... for now we do
1865 // nothing. We need to do the right thing here to support skinning.
1866 uint32_t rid = mAssets->getIncludedResources()
1867 .identifierForName(name.string(), name.size(),
1868 type.string(), type.size(),
1869 package.string(), package.size());
1870 if (rid != 0) {
1871 return NO_ERROR;
1872 }
1873
1874#if 0
1875 if (name == String16("left")) {
1876 printf("Adding bag left: file=%s, line=%d, type=%s\n",
1877 sourcePos.file.striing(), sourcePos.line, String8(type).string());
1878 }
1879#endif
1880 if (overlay && !mBundle->getAutoAddOverlay() && !hasBagOrEntry(package, type, name)) {
1881 bool canAdd = false;
1882 sp<Package> p = mPackages.valueFor(package);
1883 if (p != NULL) {
1884 sp<Type> t = p->getTypes().valueFor(type);
1885 if (t != NULL) {
1886 if (t->getCanAddEntries().indexOf(name) >= 0) {
1887 canAdd = true;
1888 }
1889 }
1890 }
1891 if (!canAdd) {
1892 sourcePos.error("Resource does not already exist in overlay at '%s'; use <add-resource> to add.\n",
1893 String8(name).string());
1894 return UNKNOWN_ERROR;
1895 }
1896 }
1897 sp<Entry> e = getEntry(package, type, name, sourcePos, overlay, params);
1898 if (e == NULL) {
1899 return UNKNOWN_ERROR;
1900 }
1901
1902 // If a parent is explicitly specified, set it.
1903 if (bagParent.size() > 0) {
1904 e->setParent(bagParent);
1905 }
1906
1907 if ((result = e->makeItABag(sourcePos)) != NO_ERROR) {
1908 return result;
1909 }
1910
1911 if (overlay && replace) {
1912 return e->emptyBag(sourcePos);
1913 }
1914 return result;
1915}
1916
1917status_t ResourceTable::addBag(const SourcePos& sourcePos,
1918 const String16& package,
1919 const String16& type,
1920 const String16& name,
1921 const String16& bagParent,
1922 const String16& bagKey,
1923 const String16& value,
1924 const Vector<StringPool::entry_style_span>* style,
1925 const ResTable_config* params,
1926 bool replace, bool isId, const int32_t format)
1927{
1928 // Check for adding entries in other packages... for now we do
1929 // nothing. We need to do the right thing here to support skinning.
1930 uint32_t rid = mAssets->getIncludedResources()
1931 .identifierForName(name.string(), name.size(),
1932 type.string(), type.size(),
1933 package.string(), package.size());
1934 if (rid != 0) {
1935 return NO_ERROR;
1936 }
1937
1938#if 0
1939 if (name == String16("left")) {
1940 printf("Adding bag left: file=%s, line=%d, type=%s\n",
1941 sourcePos.file.striing(), sourcePos.line, String8(type).string());
1942 }
1943#endif
1944 sp<Entry> e = getEntry(package, type, name, sourcePos, replace, params);
1945 if (e == NULL) {
1946 return UNKNOWN_ERROR;
1947 }
1948
1949 // If a parent is explicitly specified, set it.
1950 if (bagParent.size() > 0) {
1951 e->setParent(bagParent);
1952 }
1953
1954 const bool first = e->getBag().indexOfKey(bagKey) < 0;
1955 status_t err = e->addToBag(sourcePos, bagKey, value, style, replace, isId, format);
1956 if (err == NO_ERROR && first) {
1957 mNumLocal++;
1958 }
1959 return err;
1960}
1961
1962bool ResourceTable::hasBagOrEntry(const String16& package,
1963 const String16& type,
1964 const String16& name) const
1965{
1966 // First look for this in the included resources...
1967 uint32_t rid = mAssets->getIncludedResources()
1968 .identifierForName(name.string(), name.size(),
1969 type.string(), type.size(),
1970 package.string(), package.size());
1971 if (rid != 0) {
1972 return true;
1973 }
1974
1975 sp<Package> p = mPackages.valueFor(package);
1976 if (p != NULL) {
1977 sp<Type> t = p->getTypes().valueFor(type);
1978 if (t != NULL) {
1979 sp<ConfigList> c = t->getConfigs().valueFor(name);
1980 if (c != NULL) return true;
1981 }
1982 }
1983
1984 return false;
1985}
1986
1987bool ResourceTable::hasBagOrEntry(const String16& package,
1988 const String16& type,
1989 const String16& name,
1990 const ResTable_config& config) const
1991{
1992 // First look for this in the included resources...
1993 uint32_t rid = mAssets->getIncludedResources()
1994 .identifierForName(name.string(), name.size(),
1995 type.string(), type.size(),
1996 package.string(), package.size());
1997 if (rid != 0) {
1998 return true;
1999 }
2000
2001 sp<Package> p = mPackages.valueFor(package);
2002 if (p != NULL) {
2003 sp<Type> t = p->getTypes().valueFor(type);
2004 if (t != NULL) {
2005 sp<ConfigList> c = t->getConfigs().valueFor(name);
2006 if (c != NULL) {
2007 sp<Entry> e = c->getEntries().valueFor(config);
2008 if (e != NULL) {
2009 return true;
2010 }
2011 }
2012 }
2013 }
2014
2015 return false;
2016}
2017
2018bool ResourceTable::hasBagOrEntry(const String16& ref,
2019 const String16* defType,
2020 const String16* defPackage)
2021{
2022 String16 package, type, name;
2023 if (!ResTable::expandResourceRef(ref.string(), ref.size(), &package, &type, &name,
2024 defType, defPackage ? defPackage:&mAssetsPackage, NULL)) {
2025 return false;
2026 }
2027 return hasBagOrEntry(package, type, name);
2028}
2029
2030bool ResourceTable::appendComment(const String16& package,
2031 const String16& type,
2032 const String16& name,
2033 const String16& comment,
2034 bool onlyIfEmpty)
2035{
2036 if (comment.size() <= 0) {
2037 return true;
2038 }
2039
2040 sp<Package> p = mPackages.valueFor(package);
2041 if (p != NULL) {
2042 sp<Type> t = p->getTypes().valueFor(type);
2043 if (t != NULL) {
2044 sp<ConfigList> c = t->getConfigs().valueFor(name);
2045 if (c != NULL) {
2046 c->appendComment(comment, onlyIfEmpty);
2047 return true;
2048 }
2049 }
2050 }
2051 return false;
2052}
2053
2054bool ResourceTable::appendTypeComment(const String16& package,
2055 const String16& type,
2056 const String16& name,
2057 const String16& comment)
2058{
2059 if (comment.size() <= 0) {
2060 return true;
2061 }
2062
2063 sp<Package> p = mPackages.valueFor(package);
2064 if (p != NULL) {
2065 sp<Type> t = p->getTypes().valueFor(type);
2066 if (t != NULL) {
2067 sp<ConfigList> c = t->getConfigs().valueFor(name);
2068 if (c != NULL) {
2069 c->appendTypeComment(comment);
2070 return true;
2071 }
2072 }
2073 }
2074 return false;
2075}
2076
2077void ResourceTable::canAddEntry(const SourcePos& pos,
2078 const String16& package, const String16& type, const String16& name)
2079{
2080 sp<Type> t = getType(package, type, pos);
2081 if (t != NULL) {
2082 t->canAddEntry(name);
2083 }
2084}
2085
2086size_t ResourceTable::size() const {
2087 return mPackages.size();
2088}
2089
2090size_t ResourceTable::numLocalResources() const {
2091 return mNumLocal;
2092}
2093
2094bool ResourceTable::hasResources() const {
2095 return mNumLocal > 0;
2096}
2097
Adam Lesinskifab50872014-04-16 14:40:42 -07002098sp<AaptFile> ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& filter)
Adam Lesinski282e1812014-01-23 18:17:42 -08002099{
2100 sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
Adam Lesinskifab50872014-04-16 14:40:42 -07002101 status_t err = flatten(bundle, filter, data);
Adam Lesinski282e1812014-01-23 18:17:42 -08002102 return err == NO_ERROR ? data : NULL;
2103}
2104
2105inline uint32_t ResourceTable::getResId(const sp<Package>& p,
2106 const sp<Type>& t,
2107 uint32_t nameId)
2108{
2109 return makeResId(p->getAssignedId(), t->getIndex(), nameId);
2110}
2111
2112uint32_t ResourceTable::getResId(const String16& package,
2113 const String16& type,
2114 const String16& name,
2115 bool onlyPublic) const
2116{
2117 uint32_t id = ResourceIdCache::lookup(package, type, name, onlyPublic);
2118 if (id != 0) return id; // cache hit
2119
2120 sp<Package> p = mPackages.valueFor(package);
2121 if (p == NULL) return 0;
2122
2123 // First look for this in the included resources...
2124 uint32_t specFlags = 0;
2125 uint32_t rid = mAssets->getIncludedResources()
2126 .identifierForName(name.string(), name.size(),
2127 type.string(), type.size(),
2128 package.string(), package.size(),
2129 &specFlags);
2130 if (rid != 0) {
2131 if (onlyPublic) {
2132 if ((specFlags & ResTable_typeSpec::SPEC_PUBLIC) == 0) {
2133 return 0;
2134 }
2135 }
2136
2137 if (Res_INTERNALID(rid)) {
2138 return ResourceIdCache::store(package, type, name, onlyPublic, rid);
2139 }
2140 return ResourceIdCache::store(package, type, name, onlyPublic,
2141 Res_MAKEID(p->getAssignedId()-1, Res_GETTYPE(rid), Res_GETENTRY(rid)));
2142 }
2143
2144 sp<Type> t = p->getTypes().valueFor(type);
2145 if (t == NULL) return 0;
2146 sp<ConfigList> c = t->getConfigs().valueFor(name);
2147 if (c == NULL) return 0;
2148 int32_t ei = c->getEntryIndex();
2149 if (ei < 0) return 0;
2150
2151 return ResourceIdCache::store(package, type, name, onlyPublic,
2152 getResId(p, t, ei));
2153}
2154
2155uint32_t ResourceTable::getResId(const String16& ref,
2156 const String16* defType,
2157 const String16* defPackage,
2158 const char** outErrorMsg,
2159 bool onlyPublic) const
2160{
2161 String16 package, type, name;
2162 bool refOnlyPublic = true;
2163 if (!ResTable::expandResourceRef(
2164 ref.string(), ref.size(), &package, &type, &name,
2165 defType, defPackage ? defPackage:&mAssetsPackage,
2166 outErrorMsg, &refOnlyPublic)) {
2167 NOISY(printf("Expanding resource: ref=%s\n",
2168 String8(ref).string()));
2169 NOISY(printf("Expanding resource: defType=%s\n",
2170 defType ? String8(*defType).string() : "NULL"));
2171 NOISY(printf("Expanding resource: defPackage=%s\n",
2172 defPackage ? String8(*defPackage).string() : "NULL"));
2173 NOISY(printf("Expanding resource: ref=%s\n", String8(ref).string()));
2174 NOISY(printf("Expanded resource: p=%s, t=%s, n=%s, res=0\n",
2175 String8(package).string(), String8(type).string(),
2176 String8(name).string()));
2177 return 0;
2178 }
2179 uint32_t res = getResId(package, type, name, onlyPublic && refOnlyPublic);
2180 NOISY(printf("Expanded resource: p=%s, t=%s, n=%s, res=%d\n",
2181 String8(package).string(), String8(type).string(),
2182 String8(name).string(), res));
2183 if (res == 0) {
2184 if (outErrorMsg)
2185 *outErrorMsg = "No resource found that matches the given name";
2186 }
2187 return res;
2188}
2189
2190bool ResourceTable::isValidResourceName(const String16& s)
2191{
2192 const char16_t* p = s.string();
2193 bool first = true;
2194 while (*p) {
2195 if ((*p >= 'a' && *p <= 'z')
2196 || (*p >= 'A' && *p <= 'Z')
2197 || *p == '_'
2198 || (!first && *p >= '0' && *p <= '9')) {
2199 first = false;
2200 p++;
2201 continue;
2202 }
2203 return false;
2204 }
2205 return true;
2206}
2207
2208bool ResourceTable::stringToValue(Res_value* outValue, StringPool* pool,
2209 const String16& str,
2210 bool preserveSpaces, bool coerceType,
2211 uint32_t attrID,
2212 const Vector<StringPool::entry_style_span>* style,
2213 String16* outStr, void* accessorCookie,
2214 uint32_t attrType, const String8* configTypeName,
2215 const ConfigDescription* config)
2216{
2217 String16 finalStr;
2218
2219 bool res = true;
2220 if (style == NULL || style->size() == 0) {
2221 // Text is not styled so it can be any type... let's figure it out.
2222 res = mAssets->getIncludedResources()
2223 .stringToValue(outValue, &finalStr, str.string(), str.size(), preserveSpaces,
2224 coerceType, attrID, NULL, &mAssetsPackage, this,
2225 accessorCookie, attrType);
2226 } else {
2227 // Styled text can only be a string, and while collecting the style
2228 // information we have already processed that string!
2229 outValue->size = sizeof(Res_value);
2230 outValue->res0 = 0;
2231 outValue->dataType = outValue->TYPE_STRING;
2232 outValue->data = 0;
2233 finalStr = str;
2234 }
2235
2236 if (!res) {
2237 return false;
2238 }
2239
2240 if (outValue->dataType == outValue->TYPE_STRING) {
2241 // Should do better merging styles.
2242 if (pool) {
2243 String8 configStr;
2244 if (config != NULL) {
2245 configStr = config->toString();
2246 } else {
2247 configStr = "(null)";
2248 }
2249 NOISY(printf("Adding to pool string style #%d config %s: %s\n",
2250 style != NULL ? style->size() : 0,
2251 configStr.string(), String8(finalStr).string()));
2252 if (style != NULL && style->size() > 0) {
2253 outValue->data = pool->add(finalStr, *style, configTypeName, config);
2254 } else {
2255 outValue->data = pool->add(finalStr, true, configTypeName, config);
2256 }
2257 } else {
2258 // Caller will fill this in later.
2259 outValue->data = 0;
2260 }
2261
2262 if (outStr) {
2263 *outStr = finalStr;
2264 }
2265
2266 }
2267
2268 return true;
2269}
2270
2271uint32_t ResourceTable::getCustomResource(
2272 const String16& package, const String16& type, const String16& name) const
2273{
2274 //printf("getCustomResource: %s %s %s\n", String8(package).string(),
2275 // String8(type).string(), String8(name).string());
2276 sp<Package> p = mPackages.valueFor(package);
2277 if (p == NULL) return 0;
2278 sp<Type> t = p->getTypes().valueFor(type);
2279 if (t == NULL) return 0;
2280 sp<ConfigList> c = t->getConfigs().valueFor(name);
2281 if (c == NULL) return 0;
2282 int32_t ei = c->getEntryIndex();
2283 if (ei < 0) return 0;
2284 return getResId(p, t, ei);
2285}
2286
2287uint32_t ResourceTable::getCustomResourceWithCreation(
2288 const String16& package, const String16& type, const String16& name,
2289 const bool createIfNotFound)
2290{
2291 uint32_t resId = getCustomResource(package, type, name);
2292 if (resId != 0 || !createIfNotFound) {
2293 return resId;
2294 }
2295 String16 value("false");
2296
2297 status_t status = addEntry(mCurrentXmlPos, package, type, name, value, NULL, NULL, true);
2298 if (status == NO_ERROR) {
2299 resId = getResId(package, type, name);
2300 return resId;
2301 }
2302 return 0;
2303}
2304
2305uint32_t ResourceTable::getRemappedPackage(uint32_t origPackage) const
2306{
2307 return origPackage;
2308}
2309
2310bool ResourceTable::getAttributeType(uint32_t attrID, uint32_t* outType)
2311{
2312 //printf("getAttributeType #%08x\n", attrID);
2313 Res_value value;
2314 if (getItemValue(attrID, ResTable_map::ATTR_TYPE, &value)) {
2315 //printf("getAttributeType #%08x (%s): #%08x\n", attrID,
2316 // String8(getEntry(attrID)->getName()).string(), value.data);
2317 *outType = value.data;
2318 return true;
2319 }
2320 return false;
2321}
2322
2323bool ResourceTable::getAttributeMin(uint32_t attrID, uint32_t* outMin)
2324{
2325 //printf("getAttributeMin #%08x\n", attrID);
2326 Res_value value;
2327 if (getItemValue(attrID, ResTable_map::ATTR_MIN, &value)) {
2328 *outMin = value.data;
2329 return true;
2330 }
2331 return false;
2332}
2333
2334bool ResourceTable::getAttributeMax(uint32_t attrID, uint32_t* outMax)
2335{
2336 //printf("getAttributeMax #%08x\n", attrID);
2337 Res_value value;
2338 if (getItemValue(attrID, ResTable_map::ATTR_MAX, &value)) {
2339 *outMax = value.data;
2340 return true;
2341 }
2342 return false;
2343}
2344
2345uint32_t ResourceTable::getAttributeL10N(uint32_t attrID)
2346{
2347 //printf("getAttributeL10N #%08x\n", attrID);
2348 Res_value value;
2349 if (getItemValue(attrID, ResTable_map::ATTR_L10N, &value)) {
2350 return value.data;
2351 }
2352 return ResTable_map::L10N_NOT_REQUIRED;
2353}
2354
2355bool ResourceTable::getLocalizationSetting()
2356{
2357 return mBundle->getRequireLocalization();
2358}
2359
2360void ResourceTable::reportError(void* accessorCookie, const char* fmt, ...)
2361{
2362 if (accessorCookie != NULL && fmt != NULL) {
2363 AccessorCookie* ac = (AccessorCookie*)accessorCookie;
2364 int retval=0;
2365 char buf[1024];
2366 va_list ap;
2367 va_start(ap, fmt);
2368 retval = vsnprintf(buf, sizeof(buf), fmt, ap);
2369 va_end(ap);
2370 ac->sourcePos.error("Error: %s (at '%s' with value '%s').\n",
2371 buf, ac->attr.string(), ac->value.string());
2372 }
2373}
2374
2375bool ResourceTable::getAttributeKeys(
2376 uint32_t attrID, Vector<String16>* outKeys)
2377{
2378 sp<const Entry> e = getEntry(attrID);
2379 if (e != NULL) {
2380 const size_t N = e->getBag().size();
2381 for (size_t i=0; i<N; i++) {
2382 const String16& key = e->getBag().keyAt(i);
2383 if (key.size() > 0 && key.string()[0] != '^') {
2384 outKeys->add(key);
2385 }
2386 }
2387 return true;
2388 }
2389 return false;
2390}
2391
2392bool ResourceTable::getAttributeEnum(
2393 uint32_t attrID, const char16_t* name, size_t nameLen,
2394 Res_value* outValue)
2395{
2396 //printf("getAttributeEnum #%08x %s\n", attrID, String8(name, nameLen).string());
2397 String16 nameStr(name, nameLen);
2398 sp<const Entry> e = getEntry(attrID);
2399 if (e != NULL) {
2400 const size_t N = e->getBag().size();
2401 for (size_t i=0; i<N; i++) {
2402 //printf("Comparing %s to %s\n", String8(name, nameLen).string(),
2403 // String8(e->getBag().keyAt(i)).string());
2404 if (e->getBag().keyAt(i) == nameStr) {
2405 return getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, outValue);
2406 }
2407 }
2408 }
2409 return false;
2410}
2411
2412bool ResourceTable::getAttributeFlags(
2413 uint32_t attrID, const char16_t* name, size_t nameLen,
2414 Res_value* outValue)
2415{
2416 outValue->dataType = Res_value::TYPE_INT_HEX;
2417 outValue->data = 0;
2418
2419 //printf("getAttributeFlags #%08x %s\n", attrID, String8(name, nameLen).string());
2420 String16 nameStr(name, nameLen);
2421 sp<const Entry> e = getEntry(attrID);
2422 if (e != NULL) {
2423 const size_t N = e->getBag().size();
2424
2425 const char16_t* end = name + nameLen;
2426 const char16_t* pos = name;
2427 while (pos < end) {
2428 const char16_t* start = pos;
2429 while (pos < end && *pos != '|') {
2430 pos++;
2431 }
2432
2433 String16 nameStr(start, pos-start);
2434 size_t i;
2435 for (i=0; i<N; i++) {
2436 //printf("Comparing \"%s\" to \"%s\"\n", String8(nameStr).string(),
2437 // String8(e->getBag().keyAt(i)).string());
2438 if (e->getBag().keyAt(i) == nameStr) {
2439 Res_value val;
2440 bool got = getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, &val);
2441 if (!got) {
2442 return false;
2443 }
2444 //printf("Got value: 0x%08x\n", val.data);
2445 outValue->data |= val.data;
2446 break;
2447 }
2448 }
2449
2450 if (i >= N) {
2451 // Didn't find this flag identifier.
2452 return false;
2453 }
2454 pos++;
2455 }
2456
2457 return true;
2458 }
2459 return false;
2460}
2461
2462status_t ResourceTable::assignResourceIds()
2463{
2464 const size_t N = mOrderedPackages.size();
2465 size_t pi;
2466 status_t firstError = NO_ERROR;
2467
2468 // First generate all bag attributes and assign indices.
2469 for (pi=0; pi<N; pi++) {
2470 sp<Package> p = mOrderedPackages.itemAt(pi);
2471 if (p == NULL || p->getTypes().size() == 0) {
2472 // Empty, skip!
2473 continue;
2474 }
2475
2476 status_t err = p->applyPublicTypeOrder();
2477 if (err != NO_ERROR && firstError == NO_ERROR) {
2478 firstError = err;
2479 }
2480
2481 // Generate attributes...
2482 const size_t N = p->getOrderedTypes().size();
2483 size_t ti;
2484 for (ti=0; ti<N; ti++) {
2485 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2486 if (t == NULL) {
2487 continue;
2488 }
2489 const size_t N = t->getOrderedConfigs().size();
2490 for (size_t ci=0; ci<N; ci++) {
2491 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2492 if (c == NULL) {
2493 continue;
2494 }
2495 const size_t N = c->getEntries().size();
2496 for (size_t ei=0; ei<N; ei++) {
2497 sp<Entry> e = c->getEntries().valueAt(ei);
2498 if (e == NULL) {
2499 continue;
2500 }
2501 status_t err = e->generateAttributes(this, p->getName());
2502 if (err != NO_ERROR && firstError == NO_ERROR) {
2503 firstError = err;
2504 }
2505 }
2506 }
2507 }
2508
2509 const SourcePos unknown(String8("????"), 0);
2510 sp<Type> attr = p->getType(String16("attr"), unknown);
2511
2512 // Assign indices...
2513 for (ti=0; ti<N; ti++) {
2514 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2515 if (t == NULL) {
2516 continue;
2517 }
2518 err = t->applyPublicEntryOrder();
2519 if (err != NO_ERROR && firstError == NO_ERROR) {
2520 firstError = err;
2521 }
2522
2523 const size_t N = t->getOrderedConfigs().size();
2524 t->setIndex(ti+1);
2525
2526 LOG_ALWAYS_FATAL_IF(ti == 0 && attr != t,
2527 "First type is not attr!");
2528
2529 for (size_t ei=0; ei<N; ei++) {
2530 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ei);
2531 if (c == NULL) {
2532 continue;
2533 }
2534 c->setEntryIndex(ei);
2535 }
2536 }
2537
2538 // Assign resource IDs to keys in bags...
2539 for (ti=0; ti<N; ti++) {
2540 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2541 if (t == NULL) {
2542 continue;
2543 }
2544 const size_t N = t->getOrderedConfigs().size();
2545 for (size_t ci=0; ci<N; ci++) {
2546 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2547 //printf("Ordered config #%d: %p\n", ci, c.get());
2548 const size_t N = c->getEntries().size();
2549 for (size_t ei=0; ei<N; ei++) {
2550 sp<Entry> e = c->getEntries().valueAt(ei);
2551 if (e == NULL) {
2552 continue;
2553 }
2554 status_t err = e->assignResourceIds(this, p->getName());
2555 if (err != NO_ERROR && firstError == NO_ERROR) {
2556 firstError = err;
2557 }
2558 }
2559 }
2560 }
2561 }
2562 return firstError;
2563}
2564
2565status_t ResourceTable::addSymbols(const sp<AaptSymbols>& outSymbols) {
2566 const size_t N = mOrderedPackages.size();
2567 size_t pi;
2568
2569 for (pi=0; pi<N; pi++) {
2570 sp<Package> p = mOrderedPackages.itemAt(pi);
2571 if (p->getTypes().size() == 0) {
2572 // Empty, skip!
2573 continue;
2574 }
2575
2576 const size_t N = p->getOrderedTypes().size();
2577 size_t ti;
2578
2579 for (ti=0; ti<N; ti++) {
2580 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2581 if (t == NULL) {
2582 continue;
2583 }
2584 const size_t N = t->getOrderedConfigs().size();
2585 sp<AaptSymbols> typeSymbols;
2586 typeSymbols = outSymbols->addNestedSymbol(String8(t->getName()), t->getPos());
2587 for (size_t ci=0; ci<N; ci++) {
2588 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2589 if (c == NULL) {
2590 continue;
2591 }
2592 uint32_t rid = getResId(p, t, ci);
2593 if (rid == 0) {
2594 return UNKNOWN_ERROR;
2595 }
2596 if (Res_GETPACKAGE(rid) == (size_t)(p->getAssignedId()-1)) {
2597 typeSymbols->addSymbol(String8(c->getName()), rid, c->getPos());
2598
2599 String16 comment(c->getComment());
2600 typeSymbols->appendComment(String8(c->getName()), comment, c->getPos());
Adam Lesinski8ff15b42013-10-07 16:54:01 -07002601 //printf("Type symbol [%08x] %s comment: %s\n", rid,
2602 // String8(c->getName()).string(), String8(comment).string());
Adam Lesinski282e1812014-01-23 18:17:42 -08002603 comment = c->getTypeComment();
2604 typeSymbols->appendTypeComment(String8(c->getName()), comment);
2605 } else {
2606#if 0
2607 printf("**** NO MATCH: 0x%08x vs 0x%08x\n",
2608 Res_GETPACKAGE(rid), p->getAssignedId());
2609#endif
2610 }
2611 }
2612 }
2613 }
2614 return NO_ERROR;
2615}
2616
2617
2618void
Adam Lesinskia01a9372014-03-20 18:04:57 -07002619ResourceTable::addLocalization(const String16& name, const String8& locale, const SourcePos& src)
Adam Lesinski282e1812014-01-23 18:17:42 -08002620{
Adam Lesinskia01a9372014-03-20 18:04:57 -07002621 mLocalizations[name][locale] = src;
Adam Lesinski282e1812014-01-23 18:17:42 -08002622}
2623
2624
2625/*!
2626 * Flag various sorts of localization problems. '+' indicates checks already implemented;
2627 * '-' indicates checks that will be implemented in the future.
2628 *
2629 * + A localized string for which no default-locale version exists => warning
2630 * + A string for which no version in an explicitly-requested locale exists => warning
2631 * + A localized translation of an translateable="false" string => warning
2632 * - A localized string not provided in every locale used by the table
2633 */
2634status_t
2635ResourceTable::validateLocalizations(void)
2636{
2637 status_t err = NO_ERROR;
2638 const String8 defaultLocale;
2639
2640 // For all strings...
Adam Lesinskia01a9372014-03-20 18:04:57 -07002641 for (map<String16, map<String8, SourcePos> >::iterator nameIter = mLocalizations.begin();
Adam Lesinski282e1812014-01-23 18:17:42 -08002642 nameIter != mLocalizations.end();
2643 nameIter++) {
Adam Lesinskia01a9372014-03-20 18:04:57 -07002644 const map<String8, SourcePos>& configSrcMap = nameIter->second;
Adam Lesinski282e1812014-01-23 18:17:42 -08002645
2646 // Look for strings with no default localization
Adam Lesinskia01a9372014-03-20 18:04:57 -07002647 if (configSrcMap.count(defaultLocale) == 0) {
2648 SourcePos().warning("string '%s' has no default translation.",
2649 String8(nameIter->first).string());
2650 if (mBundle->getVerbose()) {
2651 for (map<String8, SourcePos>::const_iterator locales = configSrcMap.begin();
2652 locales != configSrcMap.end();
2653 locales++) {
2654 locales->second.printf("locale %s found", locales->first.string());
2655 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002656 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002657 // !!! TODO: throw an error here in some circumstances
2658 }
2659
2660 // Check that all requested localizations are present for this string
Adam Lesinskifab50872014-04-16 14:40:42 -07002661 if (mBundle->getConfigurations().size() > 0 && mBundle->getRequireLocalization()) {
2662 const char* allConfigs = mBundle->getConfigurations().string();
Adam Lesinski282e1812014-01-23 18:17:42 -08002663 const char* start = allConfigs;
2664 const char* comma;
2665
Adam Lesinskia01a9372014-03-20 18:04:57 -07002666 set<String8> missingConfigs;
2667 AaptLocaleValue locale;
Adam Lesinski282e1812014-01-23 18:17:42 -08002668 do {
2669 String8 config;
2670 comma = strchr(start, ',');
2671 if (comma != NULL) {
2672 config.setTo(start, comma - start);
2673 start = comma + 1;
2674 } else {
2675 config.setTo(start);
2676 }
2677
Adam Lesinskia01a9372014-03-20 18:04:57 -07002678 if (!locale.initFromFilterString(config)) {
2679 continue;
2680 }
2681
Anton Krumina2ef5c02014-03-12 14:46:44 -07002682 // don't bother with the pseudolocale "en_XA" or "ar_XB"
2683 if (config != "en_XA" && config != "ar_XB") {
Adam Lesinskia01a9372014-03-20 18:04:57 -07002684 if (configSrcMap.find(config) == configSrcMap.end()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002685 // okay, no specific localization found. it's possible that we are
2686 // requiring a specific regional localization [e.g. de_DE] but there is an
2687 // available string in the generic language localization [e.g. de];
2688 // consider that string to have fulfilled the localization requirement.
2689 String8 region(config.string(), 2);
Adam Lesinskia01a9372014-03-20 18:04:57 -07002690 if (configSrcMap.find(region) == configSrcMap.end() &&
2691 configSrcMap.count(defaultLocale) == 0) {
2692 missingConfigs.insert(config);
Adam Lesinski282e1812014-01-23 18:17:42 -08002693 }
2694 }
2695 }
Adam Lesinskia01a9372014-03-20 18:04:57 -07002696 } while (comma != NULL);
2697
2698 if (!missingConfigs.empty()) {
2699 String8 configStr;
2700 for (set<String8>::iterator iter = missingConfigs.begin();
2701 iter != missingConfigs.end();
2702 iter++) {
2703 configStr.appendFormat(" %s", iter->string());
2704 }
2705 SourcePos().warning("string '%s' is missing %u required localizations:%s",
2706 String8(nameIter->first).string(),
2707 (unsigned int)missingConfigs.size(),
2708 configStr.string());
2709 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002710 }
2711 }
2712
2713 return err;
2714}
2715
Adam Lesinskifab50872014-04-16 14:40:42 -07002716status_t ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& filter, const sp<AaptFile>& dest)
Adam Lesinski282e1812014-01-23 18:17:42 -08002717{
Adam Lesinski282e1812014-01-23 18:17:42 -08002718 const ConfigDescription nullConfig;
2719
2720 const size_t N = mOrderedPackages.size();
2721 size_t pi;
2722
2723 const static String16 mipmap16("mipmap");
2724
2725 bool useUTF8 = !bundle->getUTF16StringsOption();
2726
Adam Lesinskide898ff2014-01-29 18:20:45 -08002727 // The libraries this table references.
2728 Vector<sp<Package> > libraryPackages;
2729
Adam Lesinski282e1812014-01-23 18:17:42 -08002730 // Iterate through all data, collecting all values (strings,
2731 // references, etc).
2732 StringPool valueStrings(useUTF8);
2733 Vector<sp<Entry> > allEntries;
2734 for (pi=0; pi<N; pi++) {
2735 sp<Package> p = mOrderedPackages.itemAt(pi);
2736 if (p->getTypes().size() == 0) {
Adam Lesinskide898ff2014-01-29 18:20:45 -08002737 // Empty, this is an imported package being used as
2738 // a shared library. We do not flatten this package.
2739 if (p->getAssignedId() != 0x01 && p->getName() != String16("android")) {
2740 // This is not the base Android package, and it is a library
2741 // so we must add a reference to the library when flattening.
2742 libraryPackages.add(p);
2743 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002744 continue;
Adam Lesinskide898ff2014-01-29 18:20:45 -08002745 } else if (p->getAssignedId() == 0x00) {
2746 if (!bundle->getBuildSharedLibrary()) {
2747 fprintf(stderr, "ERROR: Package %s can not have ID=0x00 unless building a shared library.",
2748 String8(p->getName()).string());
2749 return UNKNOWN_ERROR;
2750 }
2751 // If this is a shared library, we also include ourselves as an entry.
2752 libraryPackages.add(p);
Adam Lesinski282e1812014-01-23 18:17:42 -08002753 }
2754
2755 StringPool typeStrings(useUTF8);
2756 StringPool keyStrings(useUTF8);
2757
2758 const size_t N = p->getOrderedTypes().size();
2759 for (size_t ti=0; ti<N; ti++) {
2760 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2761 if (t == NULL) {
2762 typeStrings.add(String16("<empty>"), false);
2763 continue;
2764 }
2765 const String16 typeName(t->getName());
2766 typeStrings.add(typeName, false);
2767
2768 // This is a hack to tweak the sorting order of the final strings,
2769 // to put stuff that is generally not language-specific first.
2770 String8 configTypeName(typeName);
2771 if (configTypeName == "drawable" || configTypeName == "layout"
2772 || configTypeName == "color" || configTypeName == "anim"
2773 || configTypeName == "interpolator" || configTypeName == "animator"
2774 || configTypeName == "xml" || configTypeName == "menu"
2775 || configTypeName == "mipmap" || configTypeName == "raw") {
2776 configTypeName = "1complex";
2777 } else {
2778 configTypeName = "2value";
2779 }
2780
2781 const bool filterable = (typeName != mipmap16);
2782
2783 const size_t N = t->getOrderedConfigs().size();
2784 for (size_t ci=0; ci<N; ci++) {
2785 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2786 if (c == NULL) {
2787 continue;
2788 }
2789 const size_t N = c->getEntries().size();
2790 for (size_t ei=0; ei<N; ei++) {
2791 ConfigDescription config = c->getEntries().keyAt(ei);
Adam Lesinskifab50872014-04-16 14:40:42 -07002792 if (filterable && !filter->match(config)) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002793 continue;
2794 }
2795 sp<Entry> e = c->getEntries().valueAt(ei);
2796 if (e == NULL) {
2797 continue;
2798 }
2799 e->setNameIndex(keyStrings.add(e->getName(), true));
2800
2801 // If this entry has no values for other configs,
2802 // and is the default config, then it is special. Otherwise
2803 // we want to add it with the config info.
2804 ConfigDescription* valueConfig = NULL;
2805 if (N != 1 || config == nullConfig) {
2806 valueConfig = &config;
2807 }
2808
2809 status_t err = e->prepareFlatten(&valueStrings, this,
2810 &configTypeName, &config);
2811 if (err != NO_ERROR) {
2812 return err;
2813 }
2814 allEntries.add(e);
2815 }
2816 }
2817 }
2818
2819 p->setTypeStrings(typeStrings.createStringBlock());
2820 p->setKeyStrings(keyStrings.createStringBlock());
2821 }
2822
2823 if (bundle->getOutputAPKFile() != NULL) {
2824 // Now we want to sort the value strings for better locality. This will
2825 // cause the positions of the strings to change, so we need to go back
2826 // through out resource entries and update them accordingly. Only need
2827 // to do this if actually writing the output file.
2828 valueStrings.sortByConfig();
2829 for (pi=0; pi<allEntries.size(); pi++) {
2830 allEntries[pi]->remapStringValue(&valueStrings);
2831 }
2832 }
2833
2834 ssize_t strAmt = 0;
Adam Lesinskide898ff2014-01-29 18:20:45 -08002835
Adam Lesinski282e1812014-01-23 18:17:42 -08002836 // Now build the array of package chunks.
2837 Vector<sp<AaptFile> > flatPackages;
2838 for (pi=0; pi<N; pi++) {
2839 sp<Package> p = mOrderedPackages.itemAt(pi);
2840 if (p->getTypes().size() == 0) {
2841 // Empty, skip!
2842 continue;
2843 }
2844
2845 const size_t N = p->getTypeStrings().size();
2846
2847 const size_t baseSize = sizeof(ResTable_package);
2848
2849 // Start the package data.
2850 sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
2851 ResTable_package* header = (ResTable_package*)data->editData(baseSize);
2852 if (header == NULL) {
2853 fprintf(stderr, "ERROR: out of memory creating ResTable_package\n");
2854 return NO_MEMORY;
2855 }
2856 memset(header, 0, sizeof(*header));
2857 header->header.type = htods(RES_TABLE_PACKAGE_TYPE);
2858 header->header.headerSize = htods(sizeof(*header));
2859 header->id = htodl(p->getAssignedId());
2860 strcpy16_htod(header->name, p->getName().string());
2861
2862 // Write the string blocks.
2863 const size_t typeStringsStart = data->getSize();
2864 sp<AaptFile> strFile = p->getTypeStringsData();
2865 ssize_t amt = data->writeData(strFile->getData(), strFile->getSize());
2866 #if PRINT_STRING_METRICS
2867 fprintf(stderr, "**** type strings: %d\n", amt);
2868 #endif
2869 strAmt += amt;
2870 if (amt < 0) {
2871 return amt;
2872 }
2873 const size_t keyStringsStart = data->getSize();
2874 strFile = p->getKeyStringsData();
2875 amt = data->writeData(strFile->getData(), strFile->getSize());
2876 #if PRINT_STRING_METRICS
2877 fprintf(stderr, "**** key strings: %d\n", amt);
2878 #endif
2879 strAmt += amt;
2880 if (amt < 0) {
2881 return amt;
2882 }
2883
Adam Lesinskifab50872014-04-16 14:40:42 -07002884 status_t err = flattenLibraryTable(data, libraryPackages);
Adam Lesinskide898ff2014-01-29 18:20:45 -08002885 if (err != NO_ERROR) {
2886 fprintf(stderr, "ERROR: failed to write library table\n");
2887 return err;
2888 }
2889
Adam Lesinski282e1812014-01-23 18:17:42 -08002890 // Build the type chunks inside of this package.
2891 for (size_t ti=0; ti<N; ti++) {
2892 // Retrieve them in the same order as the type string block.
2893 size_t len;
2894 String16 typeName(p->getTypeStrings().stringAt(ti, &len));
2895 sp<Type> t = p->getTypes().valueFor(typeName);
2896 LOG_ALWAYS_FATAL_IF(t == NULL && typeName != String16("<empty>"),
2897 "Type name %s not found",
2898 String8(typeName).string());
2899
2900 const bool filterable = (typeName != mipmap16);
2901
2902 const size_t N = t != NULL ? t->getOrderedConfigs().size() : 0;
2903
2904 // Until a non-NO_ENTRY value has been written for a resource,
2905 // that resource is invalid; validResources[i] represents
2906 // the item at t->getOrderedConfigs().itemAt(i).
2907 Vector<bool> validResources;
2908 validResources.insertAt(false, 0, N);
2909
2910 // First write the typeSpec chunk, containing information about
2911 // each resource entry in this type.
2912 {
2913 const size_t typeSpecSize = sizeof(ResTable_typeSpec) + sizeof(uint32_t)*N;
2914 const size_t typeSpecStart = data->getSize();
2915 ResTable_typeSpec* tsHeader = (ResTable_typeSpec*)
2916 (((uint8_t*)data->editData(typeSpecStart+typeSpecSize)) + typeSpecStart);
2917 if (tsHeader == NULL) {
2918 fprintf(stderr, "ERROR: out of memory creating ResTable_typeSpec\n");
2919 return NO_MEMORY;
2920 }
2921 memset(tsHeader, 0, sizeof(*tsHeader));
2922 tsHeader->header.type = htods(RES_TABLE_TYPE_SPEC_TYPE);
2923 tsHeader->header.headerSize = htods(sizeof(*tsHeader));
2924 tsHeader->header.size = htodl(typeSpecSize);
2925 tsHeader->id = ti+1;
2926 tsHeader->entryCount = htodl(N);
2927
2928 uint32_t* typeSpecFlags = (uint32_t*)
2929 (((uint8_t*)data->editData())
2930 + typeSpecStart + sizeof(ResTable_typeSpec));
2931 memset(typeSpecFlags, 0, sizeof(uint32_t)*N);
2932
2933 for (size_t ei=0; ei<N; ei++) {
2934 sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
2935 if (cl->getPublic()) {
2936 typeSpecFlags[ei] |= htodl(ResTable_typeSpec::SPEC_PUBLIC);
2937 }
2938 const size_t CN = cl->getEntries().size();
2939 for (size_t ci=0; ci<CN; ci++) {
Adam Lesinskifab50872014-04-16 14:40:42 -07002940 if (filterable && !filter->match(cl->getEntries().keyAt(ci))) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002941 continue;
2942 }
2943 for (size_t cj=ci+1; cj<CN; cj++) {
Adam Lesinskifab50872014-04-16 14:40:42 -07002944 if (filterable && !filter->match(cl->getEntries().keyAt(cj))) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002945 continue;
2946 }
2947 typeSpecFlags[ei] |= htodl(
2948 cl->getEntries().keyAt(ci).diff(cl->getEntries().keyAt(cj)));
2949 }
2950 }
2951 }
2952 }
2953
2954 // We need to write one type chunk for each configuration for
2955 // which we have entries in this type.
2956 const size_t NC = t->getUniqueConfigs().size();
2957
2958 const size_t typeSize = sizeof(ResTable_type) + sizeof(uint32_t)*N;
2959
2960 for (size_t ci=0; ci<NC; ci++) {
2961 ConfigDescription config = t->getUniqueConfigs().itemAt(ci);
2962
2963 NOISY(printf("Writing config %d config: imsi:%d/%d lang:%c%c cnt:%c%c "
2964 "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
2965 "sw%ddp w%ddp h%ddp dir:%d\n",
2966 ti+1,
2967 config.mcc, config.mnc,
2968 config.language[0] ? config.language[0] : '-',
2969 config.language[1] ? config.language[1] : '-',
2970 config.country[0] ? config.country[0] : '-',
2971 config.country[1] ? config.country[1] : '-',
2972 config.orientation,
2973 config.uiMode,
2974 config.touchscreen,
2975 config.density,
2976 config.keyboard,
2977 config.inputFlags,
2978 config.navigation,
2979 config.screenWidth,
2980 config.screenHeight,
2981 config.smallestScreenWidthDp,
2982 config.screenWidthDp,
2983 config.screenHeightDp,
2984 config.layoutDirection));
2985
Adam Lesinskifab50872014-04-16 14:40:42 -07002986 if (filterable && !filter->match(config)) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002987 continue;
2988 }
2989
2990 const size_t typeStart = data->getSize();
2991
2992 ResTable_type* tHeader = (ResTable_type*)
2993 (((uint8_t*)data->editData(typeStart+typeSize)) + typeStart);
2994 if (tHeader == NULL) {
2995 fprintf(stderr, "ERROR: out of memory creating ResTable_type\n");
2996 return NO_MEMORY;
2997 }
2998
2999 memset(tHeader, 0, sizeof(*tHeader));
3000 tHeader->header.type = htods(RES_TABLE_TYPE_TYPE);
3001 tHeader->header.headerSize = htods(sizeof(*tHeader));
3002 tHeader->id = ti+1;
3003 tHeader->entryCount = htodl(N);
3004 tHeader->entriesStart = htodl(typeSize);
3005 tHeader->config = config;
3006 NOISY(printf("Writing type %d config: imsi:%d/%d lang:%c%c cnt:%c%c "
3007 "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
3008 "sw%ddp w%ddp h%ddp dir:%d\n",
3009 ti+1,
3010 tHeader->config.mcc, tHeader->config.mnc,
3011 tHeader->config.language[0] ? tHeader->config.language[0] : '-',
3012 tHeader->config.language[1] ? tHeader->config.language[1] : '-',
3013 tHeader->config.country[0] ? tHeader->config.country[0] : '-',
3014 tHeader->config.country[1] ? tHeader->config.country[1] : '-',
3015 tHeader->config.orientation,
3016 tHeader->config.uiMode,
3017 tHeader->config.touchscreen,
3018 tHeader->config.density,
3019 tHeader->config.keyboard,
3020 tHeader->config.inputFlags,
3021 tHeader->config.navigation,
3022 tHeader->config.screenWidth,
3023 tHeader->config.screenHeight,
3024 tHeader->config.smallestScreenWidthDp,
3025 tHeader->config.screenWidthDp,
3026 tHeader->config.screenHeightDp,
3027 tHeader->config.layoutDirection));
3028 tHeader->config.swapHtoD();
3029
3030 // Build the entries inside of this type.
3031 for (size_t ei=0; ei<N; ei++) {
3032 sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
3033 sp<Entry> e = cl->getEntries().valueFor(config);
3034
3035 // Set the offset for this entry in its type.
3036 uint32_t* index = (uint32_t*)
3037 (((uint8_t*)data->editData())
3038 + typeStart + sizeof(ResTable_type));
3039 if (e != NULL) {
3040 index[ei] = htodl(data->getSize()-typeStart-typeSize);
3041
3042 // Create the entry.
3043 ssize_t amt = e->flatten(bundle, data, cl->getPublic());
3044 if (amt < 0) {
3045 return amt;
3046 }
3047 validResources.editItemAt(ei) = true;
3048 } else {
3049 index[ei] = htodl(ResTable_type::NO_ENTRY);
3050 }
3051 }
3052
3053 // Fill in the rest of the type information.
3054 tHeader = (ResTable_type*)
3055 (((uint8_t*)data->editData()) + typeStart);
3056 tHeader->header.size = htodl(data->getSize()-typeStart);
3057 }
3058
Ying Wangcd28bd32013-11-14 17:12:10 -08003059 bool missing_entry = false;
3060 const char* log_prefix = bundle->getErrorOnMissingConfigEntry() ?
3061 "error" : "warning";
Adam Lesinski282e1812014-01-23 18:17:42 -08003062 for (size_t i = 0; i < N; ++i) {
3063 if (!validResources[i]) {
3064 sp<ConfigList> c = t->getOrderedConfigs().itemAt(i);
Ying Wangcd28bd32013-11-14 17:12:10 -08003065 fprintf(stderr, "%s: no entries written for %s/%s\n", log_prefix,
Adam Lesinski282e1812014-01-23 18:17:42 -08003066 String8(typeName).string(), String8(c->getName()).string());
Ying Wangcd28bd32013-11-14 17:12:10 -08003067 missing_entry = true;
Adam Lesinski282e1812014-01-23 18:17:42 -08003068 }
3069 }
Ying Wangcd28bd32013-11-14 17:12:10 -08003070 if (bundle->getErrorOnMissingConfigEntry() && missing_entry) {
3071 fprintf(stderr, "Error: Missing entries, quit!\n");
3072 return NOT_ENOUGH_DATA;
3073 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003074 }
3075
3076 // Fill in the rest of the package information.
3077 header = (ResTable_package*)data->editData();
3078 header->header.size = htodl(data->getSize());
3079 header->typeStrings = htodl(typeStringsStart);
3080 header->lastPublicType = htodl(p->getTypeStrings().size());
3081 header->keyStrings = htodl(keyStringsStart);
3082 header->lastPublicKey = htodl(p->getKeyStrings().size());
3083
3084 flatPackages.add(data);
3085 }
3086
3087 // And now write out the final chunks.
3088 const size_t dataStart = dest->getSize();
3089
3090 {
3091 // blah
3092 ResTable_header header;
3093 memset(&header, 0, sizeof(header));
3094 header.header.type = htods(RES_TABLE_TYPE);
3095 header.header.headerSize = htods(sizeof(header));
3096 header.packageCount = htodl(flatPackages.size());
3097 status_t err = dest->writeData(&header, sizeof(header));
3098 if (err != NO_ERROR) {
3099 fprintf(stderr, "ERROR: out of memory creating ResTable_header\n");
3100 return err;
3101 }
3102 }
3103
3104 ssize_t strStart = dest->getSize();
Adam Lesinskifab50872014-04-16 14:40:42 -07003105 status_t err = valueStrings.writeStringBlock(dest);
Adam Lesinski282e1812014-01-23 18:17:42 -08003106 if (err != NO_ERROR) {
3107 return err;
3108 }
3109
3110 ssize_t amt = (dest->getSize()-strStart);
3111 strAmt += amt;
3112 #if PRINT_STRING_METRICS
3113 fprintf(stderr, "**** value strings: %d\n", amt);
3114 fprintf(stderr, "**** total strings: %d\n", strAmt);
3115 #endif
Adam Lesinskide898ff2014-01-29 18:20:45 -08003116
Adam Lesinski282e1812014-01-23 18:17:42 -08003117 for (pi=0; pi<flatPackages.size(); pi++) {
3118 err = dest->writeData(flatPackages[pi]->getData(),
3119 flatPackages[pi]->getSize());
3120 if (err != NO_ERROR) {
3121 fprintf(stderr, "ERROR: out of memory creating package chunk for ResTable_header\n");
3122 return err;
3123 }
3124 }
3125
3126 ResTable_header* header = (ResTable_header*)
3127 (((uint8_t*)dest->getData()) + dataStart);
3128 header->header.size = htodl(dest->getSize() - dataStart);
3129
3130 NOISY(aout << "Resource table:"
3131 << HexDump(dest->getData(), dest->getSize()) << endl);
3132
3133 #if PRINT_STRING_METRICS
3134 fprintf(stderr, "**** total resource table size: %d / %d%% strings\n",
3135 dest->getSize(), (strAmt*100)/dest->getSize());
3136 #endif
3137
3138 return NO_ERROR;
3139}
3140
Adam Lesinskide898ff2014-01-29 18:20:45 -08003141status_t ResourceTable::flattenLibraryTable(const sp<AaptFile>& dest, const Vector<sp<Package> >& libs) {
3142 // Write out the library table if necessary
3143 if (libs.size() > 0) {
3144 NOISY(fprintf(stderr, "Writing library reference table\n"));
3145
3146 const size_t libStart = dest->getSize();
3147 const size_t count = libs.size();
3148 ResTable_lib_header* libHeader = (ResTable_lib_header*) dest->editDataInRange(libStart, sizeof(ResTable_lib_header));
3149
3150 memset(libHeader, 0, sizeof(*libHeader));
3151 libHeader->header.type = htods(RES_TABLE_LIBRARY_TYPE);
3152 libHeader->header.headerSize = htods(sizeof(*libHeader));
3153 libHeader->header.size = htodl(sizeof(*libHeader) + (sizeof(ResTable_lib_entry) * count));
3154 libHeader->count = htodl(count);
3155
3156 // Write the library entries
3157 for (size_t i = 0; i < count; i++) {
3158 const size_t entryStart = dest->getSize();
3159 sp<Package> libPackage = libs[i];
3160 NOISY(fprintf(stderr, " Entry %s -> 0x%02x\n",
3161 String8(libPackage->getName()).string(),
3162 (uint8_t)libPackage->getAssignedId()));
3163
3164 ResTable_lib_entry* entry = (ResTable_lib_entry*) dest->editDataInRange(entryStart, sizeof(ResTable_lib_entry));
3165 memset(entry, 0, sizeof(*entry));
3166 entry->packageId = htodl(libPackage->getAssignedId());
3167 strcpy16_htod(entry->packageName, libPackage->getName().string());
3168 }
3169 }
3170 return NO_ERROR;
3171}
3172
Adam Lesinski282e1812014-01-23 18:17:42 -08003173void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp)
3174{
3175 fprintf(fp,
3176 "<!-- This file contains <public> resource definitions for all\n"
3177 " resources that were generated from the source data. -->\n"
3178 "\n"
3179 "<resources>\n");
3180
3181 writePublicDefinitions(package, fp, true);
3182 writePublicDefinitions(package, fp, false);
3183
3184 fprintf(fp,
3185 "\n"
3186 "</resources>\n");
3187}
3188
3189void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp, bool pub)
3190{
3191 bool didHeader = false;
3192
3193 sp<Package> pkg = mPackages.valueFor(package);
3194 if (pkg != NULL) {
3195 const size_t NT = pkg->getOrderedTypes().size();
3196 for (size_t i=0; i<NT; i++) {
3197 sp<Type> t = pkg->getOrderedTypes().itemAt(i);
3198 if (t == NULL) {
3199 continue;
3200 }
3201
3202 bool didType = false;
3203
3204 const size_t NC = t->getOrderedConfigs().size();
3205 for (size_t j=0; j<NC; j++) {
3206 sp<ConfigList> c = t->getOrderedConfigs().itemAt(j);
3207 if (c == NULL) {
3208 continue;
3209 }
3210
3211 if (c->getPublic() != pub) {
3212 continue;
3213 }
3214
3215 if (!didType) {
3216 fprintf(fp, "\n");
3217 didType = true;
3218 }
3219 if (!didHeader) {
3220 if (pub) {
3221 fprintf(fp," <!-- PUBLIC SECTION. These resources have been declared public.\n");
3222 fprintf(fp," Changes to these definitions will break binary compatibility. -->\n\n");
3223 } else {
3224 fprintf(fp," <!-- PRIVATE SECTION. These resources have not been declared public.\n");
3225 fprintf(fp," You can make them public my moving these lines into a file in res/values. -->\n\n");
3226 }
3227 didHeader = true;
3228 }
3229 if (!pub) {
3230 const size_t NE = c->getEntries().size();
3231 for (size_t k=0; k<NE; k++) {
3232 const SourcePos& pos = c->getEntries().valueAt(k)->getPos();
3233 if (pos.file != "") {
3234 fprintf(fp," <!-- Declared at %s:%d -->\n",
3235 pos.file.string(), pos.line);
3236 }
3237 }
3238 }
3239 fprintf(fp, " <public type=\"%s\" name=\"%s\" id=\"0x%08x\" />\n",
3240 String8(t->getName()).string(),
3241 String8(c->getName()).string(),
3242 getResId(pkg, t, c->getEntryIndex()));
3243 }
3244 }
3245 }
3246}
3247
3248ResourceTable::Item::Item(const SourcePos& _sourcePos,
3249 bool _isId,
3250 const String16& _value,
3251 const Vector<StringPool::entry_style_span>* _style,
3252 int32_t _format)
3253 : sourcePos(_sourcePos)
3254 , isId(_isId)
3255 , value(_value)
3256 , format(_format)
3257 , bagKeyId(0)
3258 , evaluating(false)
3259{
3260 if (_style) {
3261 style = *_style;
3262 }
3263}
3264
3265status_t ResourceTable::Entry::makeItABag(const SourcePos& sourcePos)
3266{
3267 if (mType == TYPE_BAG) {
3268 return NO_ERROR;
3269 }
3270 if (mType == TYPE_UNKNOWN) {
3271 mType = TYPE_BAG;
3272 return NO_ERROR;
3273 }
3274 sourcePos.error("Resource entry %s is already defined as a single item.\n"
3275 "%s:%d: Originally defined here.\n",
3276 String8(mName).string(),
3277 mItem.sourcePos.file.string(), mItem.sourcePos.line);
3278 return UNKNOWN_ERROR;
3279}
3280
3281status_t ResourceTable::Entry::setItem(const SourcePos& sourcePos,
3282 const String16& value,
3283 const Vector<StringPool::entry_style_span>* style,
3284 int32_t format,
3285 const bool overwrite)
3286{
3287 Item item(sourcePos, false, value, style);
3288
3289 if (mType == TYPE_BAG) {
3290 const Item& item(mBag.valueAt(0));
3291 sourcePos.error("Resource entry %s is already defined as a bag.\n"
3292 "%s:%d: Originally defined here.\n",
3293 String8(mName).string(),
3294 item.sourcePos.file.string(), item.sourcePos.line);
3295 return UNKNOWN_ERROR;
3296 }
3297 if ( (mType != TYPE_UNKNOWN) && (overwrite == false) ) {
3298 sourcePos.error("Resource entry %s is already defined.\n"
3299 "%s:%d: Originally defined here.\n",
3300 String8(mName).string(),
3301 mItem.sourcePos.file.string(), mItem.sourcePos.line);
3302 return UNKNOWN_ERROR;
3303 }
3304
3305 mType = TYPE_ITEM;
3306 mItem = item;
3307 mItemFormat = format;
3308 return NO_ERROR;
3309}
3310
3311status_t ResourceTable::Entry::addToBag(const SourcePos& sourcePos,
3312 const String16& key, const String16& value,
3313 const Vector<StringPool::entry_style_span>* style,
3314 bool replace, bool isId, int32_t format)
3315{
3316 status_t err = makeItABag(sourcePos);
3317 if (err != NO_ERROR) {
3318 return err;
3319 }
3320
3321 Item item(sourcePos, isId, value, style, format);
3322
3323 // XXX NOTE: there is an error if you try to have a bag with two keys,
3324 // one an attr and one an id, with the same name. Not something we
3325 // currently ever have to worry about.
3326 ssize_t origKey = mBag.indexOfKey(key);
3327 if (origKey >= 0) {
3328 if (!replace) {
3329 const Item& item(mBag.valueAt(origKey));
3330 sourcePos.error("Resource entry %s already has bag item %s.\n"
3331 "%s:%d: Originally defined here.\n",
3332 String8(mName).string(), String8(key).string(),
3333 item.sourcePos.file.string(), item.sourcePos.line);
3334 return UNKNOWN_ERROR;
3335 }
3336 //printf("Replacing %s with %s\n",
3337 // String8(mBag.valueFor(key).value).string(), String8(value).string());
3338 mBag.replaceValueFor(key, item);
3339 }
3340
3341 mBag.add(key, item);
3342 return NO_ERROR;
3343}
3344
3345status_t ResourceTable::Entry::emptyBag(const SourcePos& sourcePos)
3346{
3347 status_t err = makeItABag(sourcePos);
3348 if (err != NO_ERROR) {
3349 return err;
3350 }
3351
3352 mBag.clear();
3353 return NO_ERROR;
3354}
3355
3356status_t ResourceTable::Entry::generateAttributes(ResourceTable* table,
3357 const String16& package)
3358{
3359 const String16 attr16("attr");
3360 const String16 id16("id");
3361 const size_t N = mBag.size();
3362 for (size_t i=0; i<N; i++) {
3363 const String16& key = mBag.keyAt(i);
3364 const Item& it = mBag.valueAt(i);
3365 if (it.isId) {
3366 if (!table->hasBagOrEntry(key, &id16, &package)) {
3367 String16 value("false");
3368 status_t err = table->addEntry(SourcePos(String8("<generated>"), 0), package,
3369 id16, key, value);
3370 if (err != NO_ERROR) {
3371 return err;
3372 }
3373 }
3374 } else if (!table->hasBagOrEntry(key, &attr16, &package)) {
3375
3376#if 1
3377// fprintf(stderr, "ERROR: Bag attribute '%s' has not been defined.\n",
3378// String8(key).string());
3379// const Item& item(mBag.valueAt(i));
3380// fprintf(stderr, "Referenced from file %s line %d\n",
3381// item.sourcePos.file.string(), item.sourcePos.line);
3382// return UNKNOWN_ERROR;
3383#else
3384 char numberStr[16];
3385 sprintf(numberStr, "%d", ResTable_map::TYPE_ANY);
3386 status_t err = table->addBag(SourcePos("<generated>", 0), package,
3387 attr16, key, String16(""),
3388 String16("^type"),
3389 String16(numberStr), NULL, NULL);
3390 if (err != NO_ERROR) {
3391 return err;
3392 }
3393#endif
3394 }
3395 }
3396 return NO_ERROR;
3397}
3398
3399status_t ResourceTable::Entry::assignResourceIds(ResourceTable* table,
3400 const String16& package)
3401{
3402 bool hasErrors = false;
3403
3404 if (mType == TYPE_BAG) {
3405 const char* errorMsg;
3406 const String16 style16("style");
3407 const String16 attr16("attr");
3408 const String16 id16("id");
3409 mParentId = 0;
3410 if (mParent.size() > 0) {
3411 mParentId = table->getResId(mParent, &style16, NULL, &errorMsg);
3412 if (mParentId == 0) {
3413 mPos.error("Error retrieving parent for item: %s '%s'.\n",
3414 errorMsg, String8(mParent).string());
3415 hasErrors = true;
3416 }
3417 }
3418 const size_t N = mBag.size();
3419 for (size_t i=0; i<N; i++) {
3420 const String16& key = mBag.keyAt(i);
3421 Item& it = mBag.editValueAt(i);
3422 it.bagKeyId = table->getResId(key,
3423 it.isId ? &id16 : &attr16, NULL, &errorMsg);
3424 //printf("Bag key of %s: #%08x\n", String8(key).string(), it.bagKeyId);
3425 if (it.bagKeyId == 0) {
3426 it.sourcePos.error("Error: %s: %s '%s'.\n", errorMsg,
3427 String8(it.isId ? id16 : attr16).string(),
3428 String8(key).string());
3429 hasErrors = true;
3430 }
3431 }
3432 }
3433 return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
3434}
3435
3436status_t ResourceTable::Entry::prepareFlatten(StringPool* strings, ResourceTable* table,
3437 const String8* configTypeName, const ConfigDescription* config)
3438{
3439 if (mType == TYPE_ITEM) {
3440 Item& it = mItem;
3441 AccessorCookie ac(it.sourcePos, String8(mName), String8(it.value));
3442 if (!table->stringToValue(&it.parsedValue, strings,
3443 it.value, false, true, 0,
3444 &it.style, NULL, &ac, mItemFormat,
3445 configTypeName, config)) {
3446 return UNKNOWN_ERROR;
3447 }
3448 } else if (mType == TYPE_BAG) {
3449 const size_t N = mBag.size();
3450 for (size_t i=0; i<N; i++) {
3451 const String16& key = mBag.keyAt(i);
3452 Item& it = mBag.editValueAt(i);
3453 AccessorCookie ac(it.sourcePos, String8(key), String8(it.value));
3454 if (!table->stringToValue(&it.parsedValue, strings,
3455 it.value, false, true, it.bagKeyId,
3456 &it.style, NULL, &ac, it.format,
3457 configTypeName, config)) {
3458 return UNKNOWN_ERROR;
3459 }
3460 }
3461 } else {
3462 mPos.error("Error: entry %s is not a single item or a bag.\n",
3463 String8(mName).string());
3464 return UNKNOWN_ERROR;
3465 }
3466 return NO_ERROR;
3467}
3468
3469status_t ResourceTable::Entry::remapStringValue(StringPool* strings)
3470{
3471 if (mType == TYPE_ITEM) {
3472 Item& it = mItem;
3473 if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3474 it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3475 }
3476 } else if (mType == TYPE_BAG) {
3477 const size_t N = mBag.size();
3478 for (size_t i=0; i<N; i++) {
3479 Item& it = mBag.editValueAt(i);
3480 if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3481 it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3482 }
3483 }
3484 } else {
3485 mPos.error("Error: entry %s is not a single item or a bag.\n",
3486 String8(mName).string());
3487 return UNKNOWN_ERROR;
3488 }
3489 return NO_ERROR;
3490}
3491
3492ssize_t ResourceTable::Entry::flatten(Bundle* bundle, const sp<AaptFile>& data, bool isPublic)
3493{
3494 size_t amt = 0;
3495 ResTable_entry header;
3496 memset(&header, 0, sizeof(header));
3497 header.size = htods(sizeof(header));
3498 const type ty = this != NULL ? mType : TYPE_ITEM;
3499 if (this != NULL) {
3500 if (ty == TYPE_BAG) {
3501 header.flags |= htods(header.FLAG_COMPLEX);
3502 }
3503 if (isPublic) {
3504 header.flags |= htods(header.FLAG_PUBLIC);
3505 }
3506 header.key.index = htodl(mNameIndex);
3507 }
3508 if (ty != TYPE_BAG) {
3509 status_t err = data->writeData(&header, sizeof(header));
3510 if (err != NO_ERROR) {
3511 fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3512 return err;
3513 }
3514
3515 const Item& it = mItem;
3516 Res_value par;
3517 memset(&par, 0, sizeof(par));
3518 par.size = htods(it.parsedValue.size);
3519 par.dataType = it.parsedValue.dataType;
3520 par.res0 = it.parsedValue.res0;
3521 par.data = htodl(it.parsedValue.data);
3522 #if 0
3523 printf("Writing item (%s): type=%d, data=0x%x, res0=0x%x\n",
3524 String8(mName).string(), it.parsedValue.dataType,
3525 it.parsedValue.data, par.res0);
3526 #endif
3527 err = data->writeData(&par, it.parsedValue.size);
3528 if (err != NO_ERROR) {
3529 fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3530 return err;
3531 }
3532 amt += it.parsedValue.size;
3533 } else {
3534 size_t N = mBag.size();
3535 size_t i;
3536 // Create correct ordering of items.
3537 KeyedVector<uint32_t, const Item*> items;
3538 for (i=0; i<N; i++) {
3539 const Item& it = mBag.valueAt(i);
3540 items.add(it.bagKeyId, &it);
3541 }
3542 N = items.size();
3543
3544 ResTable_map_entry mapHeader;
3545 memcpy(&mapHeader, &header, sizeof(header));
3546 mapHeader.size = htods(sizeof(mapHeader));
3547 mapHeader.parent.ident = htodl(mParentId);
3548 mapHeader.count = htodl(N);
3549 status_t err = data->writeData(&mapHeader, sizeof(mapHeader));
3550 if (err != NO_ERROR) {
3551 fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3552 return err;
3553 }
3554
3555 for (i=0; i<N; i++) {
3556 const Item& it = *items.valueAt(i);
3557 ResTable_map map;
3558 map.name.ident = htodl(it.bagKeyId);
3559 map.value.size = htods(it.parsedValue.size);
3560 map.value.dataType = it.parsedValue.dataType;
3561 map.value.res0 = it.parsedValue.res0;
3562 map.value.data = htodl(it.parsedValue.data);
3563 err = data->writeData(&map, sizeof(map));
3564 if (err != NO_ERROR) {
3565 fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3566 return err;
3567 }
3568 amt += sizeof(map);
3569 }
3570 }
3571 return amt;
3572}
3573
3574void ResourceTable::ConfigList::appendComment(const String16& comment,
3575 bool onlyIfEmpty)
3576{
3577 if (comment.size() <= 0) {
3578 return;
3579 }
3580 if (onlyIfEmpty && mComment.size() > 0) {
3581 return;
3582 }
3583 if (mComment.size() > 0) {
3584 mComment.append(String16("\n"));
3585 }
3586 mComment.append(comment);
3587}
3588
3589void ResourceTable::ConfigList::appendTypeComment(const String16& comment)
3590{
3591 if (comment.size() <= 0) {
3592 return;
3593 }
3594 if (mTypeComment.size() > 0) {
3595 mTypeComment.append(String16("\n"));
3596 }
3597 mTypeComment.append(comment);
3598}
3599
3600status_t ResourceTable::Type::addPublic(const SourcePos& sourcePos,
3601 const String16& name,
3602 const uint32_t ident)
3603{
3604 #if 0
3605 int32_t entryIdx = Res_GETENTRY(ident);
3606 if (entryIdx < 0) {
3607 sourcePos.error("Public resource %s/%s has an invalid 0 identifier (0x%08x).\n",
3608 String8(mName).string(), String8(name).string(), ident);
3609 return UNKNOWN_ERROR;
3610 }
3611 #endif
3612
3613 int32_t typeIdx = Res_GETTYPE(ident);
3614 if (typeIdx >= 0) {
3615 typeIdx++;
3616 if (mPublicIndex > 0 && mPublicIndex != typeIdx) {
3617 sourcePos.error("Public resource %s/%s has conflicting type codes for its"
3618 " public identifiers (0x%x vs 0x%x).\n",
3619 String8(mName).string(), String8(name).string(),
3620 mPublicIndex, typeIdx);
3621 return UNKNOWN_ERROR;
3622 }
3623 mPublicIndex = typeIdx;
3624 }
3625
3626 if (mFirstPublicSourcePos == NULL) {
3627 mFirstPublicSourcePos = new SourcePos(sourcePos);
3628 }
3629
3630 if (mPublic.indexOfKey(name) < 0) {
3631 mPublic.add(name, Public(sourcePos, String16(), ident));
3632 } else {
3633 Public& p = mPublic.editValueFor(name);
3634 if (p.ident != ident) {
3635 sourcePos.error("Public resource %s/%s has conflicting public identifiers"
3636 " (0x%08x vs 0x%08x).\n"
3637 "%s:%d: Originally defined here.\n",
3638 String8(mName).string(), String8(name).string(), p.ident, ident,
3639 p.sourcePos.file.string(), p.sourcePos.line);
3640 return UNKNOWN_ERROR;
3641 }
3642 }
3643
3644 return NO_ERROR;
3645}
3646
3647void ResourceTable::Type::canAddEntry(const String16& name)
3648{
3649 mCanAddEntries.add(name);
3650}
3651
3652sp<ResourceTable::Entry> ResourceTable::Type::getEntry(const String16& entry,
3653 const SourcePos& sourcePos,
3654 const ResTable_config* config,
3655 bool doSetIndex,
3656 bool overlay,
3657 bool autoAddOverlay)
3658{
3659 int pos = -1;
3660 sp<ConfigList> c = mConfigs.valueFor(entry);
3661 if (c == NULL) {
3662 if (overlay && !autoAddOverlay && mCanAddEntries.indexOf(entry) < 0) {
3663 sourcePos.error("Resource at %s appears in overlay but not"
3664 " in the base package; use <add-resource> to add.\n",
3665 String8(entry).string());
3666 return NULL;
3667 }
3668 c = new ConfigList(entry, sourcePos);
3669 mConfigs.add(entry, c);
3670 pos = (int)mOrderedConfigs.size();
3671 mOrderedConfigs.add(c);
3672 if (doSetIndex) {
3673 c->setEntryIndex(pos);
3674 }
3675 }
3676
3677 ConfigDescription cdesc;
3678 if (config) cdesc = *config;
3679
3680 sp<Entry> e = c->getEntries().valueFor(cdesc);
3681 if (e == NULL) {
3682 if (config != NULL) {
3683 NOISY(printf("New entry at %s:%d: imsi:%d/%d lang:%c%c cnt:%c%c "
3684 "orien:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
3685 "sw%ddp w%ddp h%ddp dir:%d\n",
3686 sourcePos.file.string(), sourcePos.line,
3687 config->mcc, config->mnc,
3688 config->language[0] ? config->language[0] : '-',
3689 config->language[1] ? config->language[1] : '-',
3690 config->country[0] ? config->country[0] : '-',
3691 config->country[1] ? config->country[1] : '-',
3692 config->orientation,
3693 config->touchscreen,
3694 config->density,
3695 config->keyboard,
3696 config->inputFlags,
3697 config->navigation,
3698 config->screenWidth,
3699 config->screenHeight,
3700 config->smallestScreenWidthDp,
3701 config->screenWidthDp,
3702 config->screenHeightDp,
3703 config->layoutDirection));
3704 } else {
3705 NOISY(printf("New entry at %s:%d: NULL config\n",
3706 sourcePos.file.string(), sourcePos.line));
3707 }
3708 e = new Entry(entry, sourcePos);
3709 c->addEntry(cdesc, e);
3710 /*
3711 if (doSetIndex) {
3712 if (pos < 0) {
3713 for (pos=0; pos<(int)mOrderedConfigs.size(); pos++) {
3714 if (mOrderedConfigs[pos] == c) {
3715 break;
3716 }
3717 }
3718 if (pos >= (int)mOrderedConfigs.size()) {
3719 sourcePos.error("Internal error: config not found in mOrderedConfigs when adding entry");
3720 return NULL;
3721 }
3722 }
3723 e->setEntryIndex(pos);
3724 }
3725 */
3726 }
3727
3728 mUniqueConfigs.add(cdesc);
3729
3730 return e;
3731}
3732
3733status_t ResourceTable::Type::applyPublicEntryOrder()
3734{
3735 size_t N = mOrderedConfigs.size();
3736 Vector<sp<ConfigList> > origOrder(mOrderedConfigs);
3737 bool hasError = false;
3738
3739 size_t i;
3740 for (i=0; i<N; i++) {
3741 mOrderedConfigs.replaceAt(NULL, i);
3742 }
3743
3744 const size_t NP = mPublic.size();
3745 //printf("Ordering %d configs from %d public defs\n", N, NP);
3746 size_t j;
3747 for (j=0; j<NP; j++) {
3748 const String16& name = mPublic.keyAt(j);
3749 const Public& p = mPublic.valueAt(j);
3750 int32_t idx = Res_GETENTRY(p.ident);
3751 //printf("Looking for entry \"%s\"/\"%s\" (0x%08x) in %d...\n",
3752 // String8(mName).string(), String8(name).string(), p.ident, N);
3753 bool found = false;
3754 for (i=0; i<N; i++) {
3755 sp<ConfigList> e = origOrder.itemAt(i);
3756 //printf("#%d: \"%s\"\n", i, String8(e->getName()).string());
3757 if (e->getName() == name) {
3758 if (idx >= (int32_t)mOrderedConfigs.size()) {
3759 p.sourcePos.error("Public entry identifier 0x%x entry index "
3760 "is larger than available symbols (index %d, total symbols %d).\n",
3761 p.ident, idx, mOrderedConfigs.size());
3762 hasError = true;
3763 } else if (mOrderedConfigs.itemAt(idx) == NULL) {
3764 e->setPublic(true);
3765 e->setPublicSourcePos(p.sourcePos);
3766 mOrderedConfigs.replaceAt(e, idx);
3767 origOrder.removeAt(i);
3768 N--;
3769 found = true;
3770 break;
3771 } else {
3772 sp<ConfigList> oe = mOrderedConfigs.itemAt(idx);
3773
3774 p.sourcePos.error("Multiple entry names declared for public entry"
3775 " identifier 0x%x in type %s (%s vs %s).\n"
3776 "%s:%d: Originally defined here.",
3777 idx+1, String8(mName).string(),
3778 String8(oe->getName()).string(),
3779 String8(name).string(),
3780 oe->getPublicSourcePos().file.string(),
3781 oe->getPublicSourcePos().line);
3782 hasError = true;
3783 }
3784 }
3785 }
3786
3787 if (!found) {
3788 p.sourcePos.error("Public symbol %s/%s declared here is not defined.",
3789 String8(mName).string(), String8(name).string());
3790 hasError = true;
3791 }
3792 }
3793
3794 //printf("Copying back in %d non-public configs, have %d\n", N, origOrder.size());
3795
3796 if (N != origOrder.size()) {
3797 printf("Internal error: remaining private symbol count mismatch\n");
3798 N = origOrder.size();
3799 }
3800
3801 j = 0;
3802 for (i=0; i<N; i++) {
3803 sp<ConfigList> e = origOrder.itemAt(i);
3804 // There will always be enough room for the remaining entries.
3805 while (mOrderedConfigs.itemAt(j) != NULL) {
3806 j++;
3807 }
3808 mOrderedConfigs.replaceAt(e, j);
3809 j++;
3810 }
3811
3812 return hasError ? UNKNOWN_ERROR : NO_ERROR;
3813}
3814
3815ResourceTable::Package::Package(const String16& name, ssize_t includedId)
3816 : mName(name), mIncludedId(includedId),
3817 mTypeStringsMapping(0xffffffff),
3818 mKeyStringsMapping(0xffffffff)
3819{
3820}
3821
3822sp<ResourceTable::Type> ResourceTable::Package::getType(const String16& type,
3823 const SourcePos& sourcePos,
3824 bool doSetIndex)
3825{
3826 sp<Type> t = mTypes.valueFor(type);
3827 if (t == NULL) {
3828 t = new Type(type, sourcePos);
3829 mTypes.add(type, t);
3830 mOrderedTypes.add(t);
3831 if (doSetIndex) {
3832 // For some reason the type's index is set to one plus the index
3833 // in the mOrderedTypes list, rather than just the index.
3834 t->setIndex(mOrderedTypes.size());
3835 }
3836 }
3837 return t;
3838}
3839
3840status_t ResourceTable::Package::setTypeStrings(const sp<AaptFile>& data)
3841{
3842 mTypeStringsData = data;
3843 status_t err = setStrings(data, &mTypeStrings, &mTypeStringsMapping);
3844 if (err != NO_ERROR) {
3845 fprintf(stderr, "ERROR: Type string data is corrupt!\n");
3846 }
3847 return err;
3848}
3849
3850status_t ResourceTable::Package::setKeyStrings(const sp<AaptFile>& data)
3851{
3852 mKeyStringsData = data;
3853 status_t err = setStrings(data, &mKeyStrings, &mKeyStringsMapping);
3854 if (err != NO_ERROR) {
3855 fprintf(stderr, "ERROR: Key string data is corrupt!\n");
3856 }
3857 return err;
3858}
3859
3860status_t ResourceTable::Package::setStrings(const sp<AaptFile>& data,
3861 ResStringPool* strings,
3862 DefaultKeyedVector<String16, uint32_t>* mappings)
3863{
3864 if (data->getData() == NULL) {
3865 return UNKNOWN_ERROR;
3866 }
3867
3868 NOISY(aout << "Setting restable string pool: "
3869 << HexDump(data->getData(), data->getSize()) << endl);
3870
3871 status_t err = strings->setTo(data->getData(), data->getSize());
3872 if (err == NO_ERROR) {
3873 const size_t N = strings->size();
3874 for (size_t i=0; i<N; i++) {
3875 size_t len;
3876 mappings->add(String16(strings->stringAt(i, &len)), i);
3877 }
3878 }
3879 return err;
3880}
3881
3882status_t ResourceTable::Package::applyPublicTypeOrder()
3883{
3884 size_t N = mOrderedTypes.size();
3885 Vector<sp<Type> > origOrder(mOrderedTypes);
3886
3887 size_t i;
3888 for (i=0; i<N; i++) {
3889 mOrderedTypes.replaceAt(NULL, i);
3890 }
3891
3892 for (i=0; i<N; i++) {
3893 sp<Type> t = origOrder.itemAt(i);
3894 int32_t idx = t->getPublicIndex();
3895 if (idx > 0) {
3896 idx--;
3897 while (idx >= (int32_t)mOrderedTypes.size()) {
3898 mOrderedTypes.add();
3899 }
3900 if (mOrderedTypes.itemAt(idx) != NULL) {
3901 sp<Type> ot = mOrderedTypes.itemAt(idx);
3902 t->getFirstPublicSourcePos().error("Multiple type names declared for public type"
3903 " identifier 0x%x (%s vs %s).\n"
3904 "%s:%d: Originally defined here.",
3905 idx, String8(ot->getName()).string(),
3906 String8(t->getName()).string(),
3907 ot->getFirstPublicSourcePos().file.string(),
3908 ot->getFirstPublicSourcePos().line);
3909 return UNKNOWN_ERROR;
3910 }
3911 mOrderedTypes.replaceAt(t, idx);
3912 origOrder.removeAt(i);
3913 i--;
3914 N--;
3915 }
3916 }
3917
3918 size_t j=0;
3919 for (i=0; i<N; i++) {
3920 sp<Type> t = origOrder.itemAt(i);
3921 // There will always be enough room for the remaining types.
3922 while (mOrderedTypes.itemAt(j) != NULL) {
3923 j++;
3924 }
3925 mOrderedTypes.replaceAt(t, j);
3926 }
3927
3928 return NO_ERROR;
3929}
3930
3931sp<ResourceTable::Package> ResourceTable::getPackage(const String16& package)
3932{
3933 sp<Package> p = mPackages.valueFor(package);
3934 if (p == NULL) {
3935 if (mIsAppPackage) {
3936 if (mHaveAppPackage) {
3937 fprintf(stderr, "Adding multiple application package resources; only one is allowed.\n"
3938 "Use -x to create extended resources.\n");
3939 return NULL;
3940 }
3941 mHaveAppPackage = true;
Adam Lesinskide898ff2014-01-29 18:20:45 -08003942 p = new Package(package, mIsSharedLibrary ? 0 : 127);
Adam Lesinski282e1812014-01-23 18:17:42 -08003943 } else {
3944 p = new Package(package, mNextPackageId);
3945 }
3946 //printf("*** NEW PACKAGE: \"%s\" id=%d\n",
3947 // String8(package).string(), p->getAssignedId());
3948 mPackages.add(package, p);
3949 mOrderedPackages.add(p);
3950 mNextPackageId++;
3951 }
3952 return p;
3953}
3954
3955sp<ResourceTable::Type> ResourceTable::getType(const String16& package,
3956 const String16& type,
3957 const SourcePos& sourcePos,
3958 bool doSetIndex)
3959{
3960 sp<Package> p = getPackage(package);
3961 if (p == NULL) {
3962 return NULL;
3963 }
3964 return p->getType(type, sourcePos, doSetIndex);
3965}
3966
3967sp<ResourceTable::Entry> ResourceTable::getEntry(const String16& package,
3968 const String16& type,
3969 const String16& name,
3970 const SourcePos& sourcePos,
3971 bool overlay,
3972 const ResTable_config* config,
3973 bool doSetIndex)
3974{
3975 sp<Type> t = getType(package, type, sourcePos, doSetIndex);
3976 if (t == NULL) {
3977 return NULL;
3978 }
3979 return t->getEntry(name, sourcePos, config, doSetIndex, overlay, mBundle->getAutoAddOverlay());
3980}
3981
3982sp<const ResourceTable::Entry> ResourceTable::getEntry(uint32_t resID,
3983 const ResTable_config* config) const
3984{
3985 int pid = Res_GETPACKAGE(resID)+1;
3986 const size_t N = mOrderedPackages.size();
3987 size_t i;
3988 sp<Package> p;
3989 for (i=0; i<N; i++) {
3990 sp<Package> check = mOrderedPackages[i];
3991 if (check->getAssignedId() == pid) {
3992 p = check;
3993 break;
3994 }
3995
3996 }
3997 if (p == NULL) {
3998 fprintf(stderr, "warning: Package not found for resource #%08x\n", resID);
3999 return NULL;
4000 }
4001
4002 int tid = Res_GETTYPE(resID);
4003 if (tid < 0 || tid >= (int)p->getOrderedTypes().size()) {
4004 fprintf(stderr, "warning: Type not found for resource #%08x\n", resID);
4005 return NULL;
4006 }
4007 sp<Type> t = p->getOrderedTypes()[tid];
4008
4009 int eid = Res_GETENTRY(resID);
4010 if (eid < 0 || eid >= (int)t->getOrderedConfigs().size()) {
4011 fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
4012 return NULL;
4013 }
4014
4015 sp<ConfigList> c = t->getOrderedConfigs()[eid];
4016 if (c == NULL) {
4017 fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
4018 return NULL;
4019 }
4020
4021 ConfigDescription cdesc;
4022 if (config) cdesc = *config;
4023 sp<Entry> e = c->getEntries().valueFor(cdesc);
4024 if (c == NULL) {
4025 fprintf(stderr, "warning: Entry configuration not found for resource #%08x\n", resID);
4026 return NULL;
4027 }
4028
4029 return e;
4030}
4031
4032const ResourceTable::Item* ResourceTable::getItem(uint32_t resID, uint32_t attrID) const
4033{
4034 sp<const Entry> e = getEntry(resID);
4035 if (e == NULL) {
4036 return NULL;
4037 }
4038
4039 const size_t N = e->getBag().size();
4040 for (size_t i=0; i<N; i++) {
4041 const Item& it = e->getBag().valueAt(i);
4042 if (it.bagKeyId == 0) {
4043 fprintf(stderr, "warning: ID not yet assigned to '%s' in bag '%s'\n",
4044 String8(e->getName()).string(),
4045 String8(e->getBag().keyAt(i)).string());
4046 }
4047 if (it.bagKeyId == attrID) {
4048 return &it;
4049 }
4050 }
4051
4052 return NULL;
4053}
4054
4055bool ResourceTable::getItemValue(
4056 uint32_t resID, uint32_t attrID, Res_value* outValue)
4057{
4058 const Item* item = getItem(resID, attrID);
4059
4060 bool res = false;
4061 if (item != NULL) {
4062 if (item->evaluating) {
4063 sp<const Entry> e = getEntry(resID);
4064 const size_t N = e->getBag().size();
4065 size_t i;
4066 for (i=0; i<N; i++) {
4067 if (&e->getBag().valueAt(i) == item) {
4068 break;
4069 }
4070 }
4071 fprintf(stderr, "warning: Circular reference detected in key '%s' of bag '%s'\n",
4072 String8(e->getName()).string(),
4073 String8(e->getBag().keyAt(i)).string());
4074 return false;
4075 }
4076 item->evaluating = true;
4077 res = stringToValue(outValue, NULL, item->value, false, false, item->bagKeyId);
4078 NOISY(
4079 if (res) {
4080 printf("getItemValue of #%08x[#%08x] (%s): type=#%08x, data=#%08x\n",
4081 resID, attrID, String8(getEntry(resID)->getName()).string(),
4082 outValue->dataType, outValue->data);
4083 } else {
4084 printf("getItemValue of #%08x[#%08x]: failed\n",
4085 resID, attrID);
4086 }
4087 );
4088 item->evaluating = false;
4089 }
4090 return res;
4091}