blob: 1a9f1b95dada1454fc51111acab9569973876f1e [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 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002295
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002296 if (mAssetsPackage != package) {
2297 mCurrentXmlPos.warning("creating resource for external package %s: %s/%s.",
2298 String8(package).string(), String8(type).string(), String8(name).string());
2299 mCurrentXmlPos.printf("This will be an error in a future version of AAPT.");
2300 }
2301
2302 String16 value("false");
Adam Lesinski282e1812014-01-23 18:17:42 -08002303 status_t status = addEntry(mCurrentXmlPos, package, type, name, value, NULL, NULL, true);
2304 if (status == NO_ERROR) {
2305 resId = getResId(package, type, name);
2306 return resId;
2307 }
2308 return 0;
2309}
2310
2311uint32_t ResourceTable::getRemappedPackage(uint32_t origPackage) const
2312{
2313 return origPackage;
2314}
2315
2316bool ResourceTable::getAttributeType(uint32_t attrID, uint32_t* outType)
2317{
2318 //printf("getAttributeType #%08x\n", attrID);
2319 Res_value value;
2320 if (getItemValue(attrID, ResTable_map::ATTR_TYPE, &value)) {
2321 //printf("getAttributeType #%08x (%s): #%08x\n", attrID,
2322 // String8(getEntry(attrID)->getName()).string(), value.data);
2323 *outType = value.data;
2324 return true;
2325 }
2326 return false;
2327}
2328
2329bool ResourceTable::getAttributeMin(uint32_t attrID, uint32_t* outMin)
2330{
2331 //printf("getAttributeMin #%08x\n", attrID);
2332 Res_value value;
2333 if (getItemValue(attrID, ResTable_map::ATTR_MIN, &value)) {
2334 *outMin = value.data;
2335 return true;
2336 }
2337 return false;
2338}
2339
2340bool ResourceTable::getAttributeMax(uint32_t attrID, uint32_t* outMax)
2341{
2342 //printf("getAttributeMax #%08x\n", attrID);
2343 Res_value value;
2344 if (getItemValue(attrID, ResTable_map::ATTR_MAX, &value)) {
2345 *outMax = value.data;
2346 return true;
2347 }
2348 return false;
2349}
2350
2351uint32_t ResourceTable::getAttributeL10N(uint32_t attrID)
2352{
2353 //printf("getAttributeL10N #%08x\n", attrID);
2354 Res_value value;
2355 if (getItemValue(attrID, ResTable_map::ATTR_L10N, &value)) {
2356 return value.data;
2357 }
2358 return ResTable_map::L10N_NOT_REQUIRED;
2359}
2360
2361bool ResourceTable::getLocalizationSetting()
2362{
2363 return mBundle->getRequireLocalization();
2364}
2365
2366void ResourceTable::reportError(void* accessorCookie, const char* fmt, ...)
2367{
2368 if (accessorCookie != NULL && fmt != NULL) {
2369 AccessorCookie* ac = (AccessorCookie*)accessorCookie;
2370 int retval=0;
2371 char buf[1024];
2372 va_list ap;
2373 va_start(ap, fmt);
2374 retval = vsnprintf(buf, sizeof(buf), fmt, ap);
2375 va_end(ap);
2376 ac->sourcePos.error("Error: %s (at '%s' with value '%s').\n",
2377 buf, ac->attr.string(), ac->value.string());
2378 }
2379}
2380
2381bool ResourceTable::getAttributeKeys(
2382 uint32_t attrID, Vector<String16>* outKeys)
2383{
2384 sp<const Entry> e = getEntry(attrID);
2385 if (e != NULL) {
2386 const size_t N = e->getBag().size();
2387 for (size_t i=0; i<N; i++) {
2388 const String16& key = e->getBag().keyAt(i);
2389 if (key.size() > 0 && key.string()[0] != '^') {
2390 outKeys->add(key);
2391 }
2392 }
2393 return true;
2394 }
2395 return false;
2396}
2397
2398bool ResourceTable::getAttributeEnum(
2399 uint32_t attrID, const char16_t* name, size_t nameLen,
2400 Res_value* outValue)
2401{
2402 //printf("getAttributeEnum #%08x %s\n", attrID, String8(name, nameLen).string());
2403 String16 nameStr(name, nameLen);
2404 sp<const Entry> e = getEntry(attrID);
2405 if (e != NULL) {
2406 const size_t N = e->getBag().size();
2407 for (size_t i=0; i<N; i++) {
2408 //printf("Comparing %s to %s\n", String8(name, nameLen).string(),
2409 // String8(e->getBag().keyAt(i)).string());
2410 if (e->getBag().keyAt(i) == nameStr) {
2411 return getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, outValue);
2412 }
2413 }
2414 }
2415 return false;
2416}
2417
2418bool ResourceTable::getAttributeFlags(
2419 uint32_t attrID, const char16_t* name, size_t nameLen,
2420 Res_value* outValue)
2421{
2422 outValue->dataType = Res_value::TYPE_INT_HEX;
2423 outValue->data = 0;
2424
2425 //printf("getAttributeFlags #%08x %s\n", attrID, String8(name, nameLen).string());
2426 String16 nameStr(name, nameLen);
2427 sp<const Entry> e = getEntry(attrID);
2428 if (e != NULL) {
2429 const size_t N = e->getBag().size();
2430
2431 const char16_t* end = name + nameLen;
2432 const char16_t* pos = name;
2433 while (pos < end) {
2434 const char16_t* start = pos;
2435 while (pos < end && *pos != '|') {
2436 pos++;
2437 }
2438
2439 String16 nameStr(start, pos-start);
2440 size_t i;
2441 for (i=0; i<N; i++) {
2442 //printf("Comparing \"%s\" to \"%s\"\n", String8(nameStr).string(),
2443 // String8(e->getBag().keyAt(i)).string());
2444 if (e->getBag().keyAt(i) == nameStr) {
2445 Res_value val;
2446 bool got = getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, &val);
2447 if (!got) {
2448 return false;
2449 }
2450 //printf("Got value: 0x%08x\n", val.data);
2451 outValue->data |= val.data;
2452 break;
2453 }
2454 }
2455
2456 if (i >= N) {
2457 // Didn't find this flag identifier.
2458 return false;
2459 }
2460 pos++;
2461 }
2462
2463 return true;
2464 }
2465 return false;
2466}
2467
2468status_t ResourceTable::assignResourceIds()
2469{
2470 const size_t N = mOrderedPackages.size();
2471 size_t pi;
2472 status_t firstError = NO_ERROR;
2473
2474 // First generate all bag attributes and assign indices.
2475 for (pi=0; pi<N; pi++) {
2476 sp<Package> p = mOrderedPackages.itemAt(pi);
2477 if (p == NULL || p->getTypes().size() == 0) {
2478 // Empty, skip!
2479 continue;
2480 }
2481
2482 status_t err = p->applyPublicTypeOrder();
2483 if (err != NO_ERROR && firstError == NO_ERROR) {
2484 firstError = err;
2485 }
2486
2487 // Generate attributes...
2488 const size_t N = p->getOrderedTypes().size();
2489 size_t ti;
2490 for (ti=0; ti<N; ti++) {
2491 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2492 if (t == NULL) {
2493 continue;
2494 }
2495 const size_t N = t->getOrderedConfigs().size();
2496 for (size_t ci=0; ci<N; ci++) {
2497 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2498 if (c == NULL) {
2499 continue;
2500 }
2501 const size_t N = c->getEntries().size();
2502 for (size_t ei=0; ei<N; ei++) {
2503 sp<Entry> e = c->getEntries().valueAt(ei);
2504 if (e == NULL) {
2505 continue;
2506 }
2507 status_t err = e->generateAttributes(this, p->getName());
2508 if (err != NO_ERROR && firstError == NO_ERROR) {
2509 firstError = err;
2510 }
2511 }
2512 }
2513 }
2514
2515 const SourcePos unknown(String8("????"), 0);
2516 sp<Type> attr = p->getType(String16("attr"), unknown);
2517
2518 // Assign indices...
2519 for (ti=0; ti<N; ti++) {
2520 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2521 if (t == NULL) {
2522 continue;
2523 }
2524 err = t->applyPublicEntryOrder();
2525 if (err != NO_ERROR && firstError == NO_ERROR) {
2526 firstError = err;
2527 }
2528
2529 const size_t N = t->getOrderedConfigs().size();
2530 t->setIndex(ti+1);
2531
2532 LOG_ALWAYS_FATAL_IF(ti == 0 && attr != t,
2533 "First type is not attr!");
2534
2535 for (size_t ei=0; ei<N; ei++) {
2536 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ei);
2537 if (c == NULL) {
2538 continue;
2539 }
2540 c->setEntryIndex(ei);
2541 }
2542 }
2543
2544 // Assign resource IDs to keys in bags...
2545 for (ti=0; ti<N; ti++) {
2546 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2547 if (t == NULL) {
2548 continue;
2549 }
2550 const size_t N = t->getOrderedConfigs().size();
2551 for (size_t ci=0; ci<N; ci++) {
2552 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2553 //printf("Ordered config #%d: %p\n", ci, c.get());
2554 const size_t N = c->getEntries().size();
2555 for (size_t ei=0; ei<N; ei++) {
2556 sp<Entry> e = c->getEntries().valueAt(ei);
2557 if (e == NULL) {
2558 continue;
2559 }
2560 status_t err = e->assignResourceIds(this, p->getName());
2561 if (err != NO_ERROR && firstError == NO_ERROR) {
2562 firstError = err;
2563 }
2564 }
2565 }
2566 }
2567 }
2568 return firstError;
2569}
2570
2571status_t ResourceTable::addSymbols(const sp<AaptSymbols>& outSymbols) {
2572 const size_t N = mOrderedPackages.size();
2573 size_t pi;
2574
2575 for (pi=0; pi<N; pi++) {
2576 sp<Package> p = mOrderedPackages.itemAt(pi);
2577 if (p->getTypes().size() == 0) {
2578 // Empty, skip!
2579 continue;
2580 }
2581
2582 const size_t N = p->getOrderedTypes().size();
2583 size_t ti;
2584
2585 for (ti=0; ti<N; ti++) {
2586 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2587 if (t == NULL) {
2588 continue;
2589 }
2590 const size_t N = t->getOrderedConfigs().size();
2591 sp<AaptSymbols> typeSymbols;
2592 typeSymbols = outSymbols->addNestedSymbol(String8(t->getName()), t->getPos());
2593 for (size_t ci=0; ci<N; ci++) {
2594 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2595 if (c == NULL) {
2596 continue;
2597 }
2598 uint32_t rid = getResId(p, t, ci);
2599 if (rid == 0) {
2600 return UNKNOWN_ERROR;
2601 }
2602 if (Res_GETPACKAGE(rid) == (size_t)(p->getAssignedId()-1)) {
2603 typeSymbols->addSymbol(String8(c->getName()), rid, c->getPos());
2604
2605 String16 comment(c->getComment());
2606 typeSymbols->appendComment(String8(c->getName()), comment, c->getPos());
Adam Lesinski8ff15b42013-10-07 16:54:01 -07002607 //printf("Type symbol [%08x] %s comment: %s\n", rid,
2608 // String8(c->getName()).string(), String8(comment).string());
Adam Lesinski282e1812014-01-23 18:17:42 -08002609 comment = c->getTypeComment();
2610 typeSymbols->appendTypeComment(String8(c->getName()), comment);
2611 } else {
2612#if 0
2613 printf("**** NO MATCH: 0x%08x vs 0x%08x\n",
2614 Res_GETPACKAGE(rid), p->getAssignedId());
2615#endif
2616 }
2617 }
2618 }
2619 }
2620 return NO_ERROR;
2621}
2622
2623
2624void
Adam Lesinskia01a9372014-03-20 18:04:57 -07002625ResourceTable::addLocalization(const String16& name, const String8& locale, const SourcePos& src)
Adam Lesinski282e1812014-01-23 18:17:42 -08002626{
Adam Lesinskia01a9372014-03-20 18:04:57 -07002627 mLocalizations[name][locale] = src;
Adam Lesinski282e1812014-01-23 18:17:42 -08002628}
2629
2630
2631/*!
2632 * Flag various sorts of localization problems. '+' indicates checks already implemented;
2633 * '-' indicates checks that will be implemented in the future.
2634 *
2635 * + A localized string for which no default-locale version exists => warning
2636 * + A string for which no version in an explicitly-requested locale exists => warning
2637 * + A localized translation of an translateable="false" string => warning
2638 * - A localized string not provided in every locale used by the table
2639 */
2640status_t
2641ResourceTable::validateLocalizations(void)
2642{
2643 status_t err = NO_ERROR;
2644 const String8 defaultLocale;
2645
2646 // For all strings...
Adam Lesinskia01a9372014-03-20 18:04:57 -07002647 for (map<String16, map<String8, SourcePos> >::iterator nameIter = mLocalizations.begin();
Adam Lesinski282e1812014-01-23 18:17:42 -08002648 nameIter != mLocalizations.end();
2649 nameIter++) {
Adam Lesinskia01a9372014-03-20 18:04:57 -07002650 const map<String8, SourcePos>& configSrcMap = nameIter->second;
Adam Lesinski282e1812014-01-23 18:17:42 -08002651
2652 // Look for strings with no default localization
Adam Lesinskia01a9372014-03-20 18:04:57 -07002653 if (configSrcMap.count(defaultLocale) == 0) {
2654 SourcePos().warning("string '%s' has no default translation.",
2655 String8(nameIter->first).string());
2656 if (mBundle->getVerbose()) {
2657 for (map<String8, SourcePos>::const_iterator locales = configSrcMap.begin();
2658 locales != configSrcMap.end();
2659 locales++) {
2660 locales->second.printf("locale %s found", locales->first.string());
2661 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002662 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002663 // !!! TODO: throw an error here in some circumstances
2664 }
2665
2666 // Check that all requested localizations are present for this string
Adam Lesinskifab50872014-04-16 14:40:42 -07002667 if (mBundle->getConfigurations().size() > 0 && mBundle->getRequireLocalization()) {
2668 const char* allConfigs = mBundle->getConfigurations().string();
Adam Lesinski282e1812014-01-23 18:17:42 -08002669 const char* start = allConfigs;
2670 const char* comma;
2671
Adam Lesinskia01a9372014-03-20 18:04:57 -07002672 set<String8> missingConfigs;
2673 AaptLocaleValue locale;
Adam Lesinski282e1812014-01-23 18:17:42 -08002674 do {
2675 String8 config;
2676 comma = strchr(start, ',');
2677 if (comma != NULL) {
2678 config.setTo(start, comma - start);
2679 start = comma + 1;
2680 } else {
2681 config.setTo(start);
2682 }
2683
Adam Lesinskia01a9372014-03-20 18:04:57 -07002684 if (!locale.initFromFilterString(config)) {
2685 continue;
2686 }
2687
Anton Krumina2ef5c02014-03-12 14:46:44 -07002688 // don't bother with the pseudolocale "en_XA" or "ar_XB"
2689 if (config != "en_XA" && config != "ar_XB") {
Adam Lesinskia01a9372014-03-20 18:04:57 -07002690 if (configSrcMap.find(config) == configSrcMap.end()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002691 // okay, no specific localization found. it's possible that we are
2692 // requiring a specific regional localization [e.g. de_DE] but there is an
2693 // available string in the generic language localization [e.g. de];
2694 // consider that string to have fulfilled the localization requirement.
2695 String8 region(config.string(), 2);
Adam Lesinskia01a9372014-03-20 18:04:57 -07002696 if (configSrcMap.find(region) == configSrcMap.end() &&
2697 configSrcMap.count(defaultLocale) == 0) {
2698 missingConfigs.insert(config);
Adam Lesinski282e1812014-01-23 18:17:42 -08002699 }
2700 }
2701 }
Adam Lesinskia01a9372014-03-20 18:04:57 -07002702 } while (comma != NULL);
2703
2704 if (!missingConfigs.empty()) {
2705 String8 configStr;
2706 for (set<String8>::iterator iter = missingConfigs.begin();
2707 iter != missingConfigs.end();
2708 iter++) {
2709 configStr.appendFormat(" %s", iter->string());
2710 }
2711 SourcePos().warning("string '%s' is missing %u required localizations:%s",
2712 String8(nameIter->first).string(),
2713 (unsigned int)missingConfigs.size(),
2714 configStr.string());
2715 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002716 }
2717 }
2718
2719 return err;
2720}
2721
Adam Lesinskifab50872014-04-16 14:40:42 -07002722status_t ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& filter, const sp<AaptFile>& dest)
Adam Lesinski282e1812014-01-23 18:17:42 -08002723{
Adam Lesinski282e1812014-01-23 18:17:42 -08002724 const ConfigDescription nullConfig;
2725
2726 const size_t N = mOrderedPackages.size();
2727 size_t pi;
2728
2729 const static String16 mipmap16("mipmap");
2730
2731 bool useUTF8 = !bundle->getUTF16StringsOption();
2732
Adam Lesinskide898ff2014-01-29 18:20:45 -08002733 // The libraries this table references.
2734 Vector<sp<Package> > libraryPackages;
2735
Adam Lesinski282e1812014-01-23 18:17:42 -08002736 // Iterate through all data, collecting all values (strings,
2737 // references, etc).
2738 StringPool valueStrings(useUTF8);
2739 Vector<sp<Entry> > allEntries;
2740 for (pi=0; pi<N; pi++) {
2741 sp<Package> p = mOrderedPackages.itemAt(pi);
2742 if (p->getTypes().size() == 0) {
Adam Lesinskide898ff2014-01-29 18:20:45 -08002743 // Empty, this is an imported package being used as
2744 // a shared library. We do not flatten this package.
2745 if (p->getAssignedId() != 0x01 && p->getName() != String16("android")) {
2746 // This is not the base Android package, and it is a library
2747 // so we must add a reference to the library when flattening.
2748 libraryPackages.add(p);
2749 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002750 continue;
Adam Lesinskide898ff2014-01-29 18:20:45 -08002751 } else if (p->getAssignedId() == 0x00) {
2752 if (!bundle->getBuildSharedLibrary()) {
2753 fprintf(stderr, "ERROR: Package %s can not have ID=0x00 unless building a shared library.",
2754 String8(p->getName()).string());
2755 return UNKNOWN_ERROR;
2756 }
2757 // If this is a shared library, we also include ourselves as an entry.
2758 libraryPackages.add(p);
Adam Lesinski282e1812014-01-23 18:17:42 -08002759 }
2760
2761 StringPool typeStrings(useUTF8);
2762 StringPool keyStrings(useUTF8);
2763
2764 const size_t N = p->getOrderedTypes().size();
2765 for (size_t ti=0; ti<N; ti++) {
2766 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2767 if (t == NULL) {
2768 typeStrings.add(String16("<empty>"), false);
2769 continue;
2770 }
2771 const String16 typeName(t->getName());
2772 typeStrings.add(typeName, false);
2773
2774 // This is a hack to tweak the sorting order of the final strings,
2775 // to put stuff that is generally not language-specific first.
2776 String8 configTypeName(typeName);
2777 if (configTypeName == "drawable" || configTypeName == "layout"
2778 || configTypeName == "color" || configTypeName == "anim"
2779 || configTypeName == "interpolator" || configTypeName == "animator"
2780 || configTypeName == "xml" || configTypeName == "menu"
2781 || configTypeName == "mipmap" || configTypeName == "raw") {
2782 configTypeName = "1complex";
2783 } else {
2784 configTypeName = "2value";
2785 }
2786
2787 const bool filterable = (typeName != mipmap16);
2788
2789 const size_t N = t->getOrderedConfigs().size();
2790 for (size_t ci=0; ci<N; ci++) {
2791 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2792 if (c == NULL) {
2793 continue;
2794 }
2795 const size_t N = c->getEntries().size();
2796 for (size_t ei=0; ei<N; ei++) {
2797 ConfigDescription config = c->getEntries().keyAt(ei);
Adam Lesinskifab50872014-04-16 14:40:42 -07002798 if (filterable && !filter->match(config)) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002799 continue;
2800 }
2801 sp<Entry> e = c->getEntries().valueAt(ei);
2802 if (e == NULL) {
2803 continue;
2804 }
2805 e->setNameIndex(keyStrings.add(e->getName(), true));
2806
2807 // If this entry has no values for other configs,
2808 // and is the default config, then it is special. Otherwise
2809 // we want to add it with the config info.
2810 ConfigDescription* valueConfig = NULL;
2811 if (N != 1 || config == nullConfig) {
2812 valueConfig = &config;
2813 }
2814
2815 status_t err = e->prepareFlatten(&valueStrings, this,
2816 &configTypeName, &config);
2817 if (err != NO_ERROR) {
2818 return err;
2819 }
2820 allEntries.add(e);
2821 }
2822 }
2823 }
2824
2825 p->setTypeStrings(typeStrings.createStringBlock());
2826 p->setKeyStrings(keyStrings.createStringBlock());
2827 }
2828
2829 if (bundle->getOutputAPKFile() != NULL) {
2830 // Now we want to sort the value strings for better locality. This will
2831 // cause the positions of the strings to change, so we need to go back
2832 // through out resource entries and update them accordingly. Only need
2833 // to do this if actually writing the output file.
2834 valueStrings.sortByConfig();
2835 for (pi=0; pi<allEntries.size(); pi++) {
2836 allEntries[pi]->remapStringValue(&valueStrings);
2837 }
2838 }
2839
2840 ssize_t strAmt = 0;
Adam Lesinskide898ff2014-01-29 18:20:45 -08002841
Adam Lesinski282e1812014-01-23 18:17:42 -08002842 // Now build the array of package chunks.
2843 Vector<sp<AaptFile> > flatPackages;
2844 for (pi=0; pi<N; pi++) {
2845 sp<Package> p = mOrderedPackages.itemAt(pi);
2846 if (p->getTypes().size() == 0) {
2847 // Empty, skip!
2848 continue;
2849 }
2850
2851 const size_t N = p->getTypeStrings().size();
2852
2853 const size_t baseSize = sizeof(ResTable_package);
2854
2855 // Start the package data.
2856 sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
2857 ResTable_package* header = (ResTable_package*)data->editData(baseSize);
2858 if (header == NULL) {
2859 fprintf(stderr, "ERROR: out of memory creating ResTable_package\n");
2860 return NO_MEMORY;
2861 }
2862 memset(header, 0, sizeof(*header));
2863 header->header.type = htods(RES_TABLE_PACKAGE_TYPE);
2864 header->header.headerSize = htods(sizeof(*header));
2865 header->id = htodl(p->getAssignedId());
2866 strcpy16_htod(header->name, p->getName().string());
2867
2868 // Write the string blocks.
2869 const size_t typeStringsStart = data->getSize();
2870 sp<AaptFile> strFile = p->getTypeStringsData();
2871 ssize_t amt = data->writeData(strFile->getData(), strFile->getSize());
2872 #if PRINT_STRING_METRICS
2873 fprintf(stderr, "**** type strings: %d\n", amt);
2874 #endif
2875 strAmt += amt;
2876 if (amt < 0) {
2877 return amt;
2878 }
2879 const size_t keyStringsStart = data->getSize();
2880 strFile = p->getKeyStringsData();
2881 amt = data->writeData(strFile->getData(), strFile->getSize());
2882 #if PRINT_STRING_METRICS
2883 fprintf(stderr, "**** key strings: %d\n", amt);
2884 #endif
2885 strAmt += amt;
2886 if (amt < 0) {
2887 return amt;
2888 }
2889
Adam Lesinskifab50872014-04-16 14:40:42 -07002890 status_t err = flattenLibraryTable(data, libraryPackages);
Adam Lesinskide898ff2014-01-29 18:20:45 -08002891 if (err != NO_ERROR) {
2892 fprintf(stderr, "ERROR: failed to write library table\n");
2893 return err;
2894 }
2895
Adam Lesinski282e1812014-01-23 18:17:42 -08002896 // Build the type chunks inside of this package.
2897 for (size_t ti=0; ti<N; ti++) {
2898 // Retrieve them in the same order as the type string block.
2899 size_t len;
2900 String16 typeName(p->getTypeStrings().stringAt(ti, &len));
2901 sp<Type> t = p->getTypes().valueFor(typeName);
2902 LOG_ALWAYS_FATAL_IF(t == NULL && typeName != String16("<empty>"),
2903 "Type name %s not found",
2904 String8(typeName).string());
2905
2906 const bool filterable = (typeName != mipmap16);
2907
2908 const size_t N = t != NULL ? t->getOrderedConfigs().size() : 0;
2909
2910 // Until a non-NO_ENTRY value has been written for a resource,
2911 // that resource is invalid; validResources[i] represents
2912 // the item at t->getOrderedConfigs().itemAt(i).
2913 Vector<bool> validResources;
2914 validResources.insertAt(false, 0, N);
2915
2916 // First write the typeSpec chunk, containing information about
2917 // each resource entry in this type.
2918 {
2919 const size_t typeSpecSize = sizeof(ResTable_typeSpec) + sizeof(uint32_t)*N;
2920 const size_t typeSpecStart = data->getSize();
2921 ResTable_typeSpec* tsHeader = (ResTable_typeSpec*)
2922 (((uint8_t*)data->editData(typeSpecStart+typeSpecSize)) + typeSpecStart);
2923 if (tsHeader == NULL) {
2924 fprintf(stderr, "ERROR: out of memory creating ResTable_typeSpec\n");
2925 return NO_MEMORY;
2926 }
2927 memset(tsHeader, 0, sizeof(*tsHeader));
2928 tsHeader->header.type = htods(RES_TABLE_TYPE_SPEC_TYPE);
2929 tsHeader->header.headerSize = htods(sizeof(*tsHeader));
2930 tsHeader->header.size = htodl(typeSpecSize);
2931 tsHeader->id = ti+1;
2932 tsHeader->entryCount = htodl(N);
2933
2934 uint32_t* typeSpecFlags = (uint32_t*)
2935 (((uint8_t*)data->editData())
2936 + typeSpecStart + sizeof(ResTable_typeSpec));
2937 memset(typeSpecFlags, 0, sizeof(uint32_t)*N);
2938
2939 for (size_t ei=0; ei<N; ei++) {
2940 sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
2941 if (cl->getPublic()) {
2942 typeSpecFlags[ei] |= htodl(ResTable_typeSpec::SPEC_PUBLIC);
2943 }
2944 const size_t CN = cl->getEntries().size();
2945 for (size_t ci=0; ci<CN; ci++) {
Adam Lesinskifab50872014-04-16 14:40:42 -07002946 if (filterable && !filter->match(cl->getEntries().keyAt(ci))) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002947 continue;
2948 }
2949 for (size_t cj=ci+1; cj<CN; cj++) {
Adam Lesinskifab50872014-04-16 14:40:42 -07002950 if (filterable && !filter->match(cl->getEntries().keyAt(cj))) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002951 continue;
2952 }
2953 typeSpecFlags[ei] |= htodl(
2954 cl->getEntries().keyAt(ci).diff(cl->getEntries().keyAt(cj)));
2955 }
2956 }
2957 }
2958 }
2959
2960 // We need to write one type chunk for each configuration for
2961 // which we have entries in this type.
2962 const size_t NC = t->getUniqueConfigs().size();
2963
2964 const size_t typeSize = sizeof(ResTable_type) + sizeof(uint32_t)*N;
2965
2966 for (size_t ci=0; ci<NC; ci++) {
2967 ConfigDescription config = t->getUniqueConfigs().itemAt(ci);
2968
2969 NOISY(printf("Writing config %d config: imsi:%d/%d lang:%c%c cnt:%c%c "
2970 "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
2971 "sw%ddp w%ddp h%ddp dir:%d\n",
2972 ti+1,
2973 config.mcc, config.mnc,
2974 config.language[0] ? config.language[0] : '-',
2975 config.language[1] ? config.language[1] : '-',
2976 config.country[0] ? config.country[0] : '-',
2977 config.country[1] ? config.country[1] : '-',
2978 config.orientation,
2979 config.uiMode,
2980 config.touchscreen,
2981 config.density,
2982 config.keyboard,
2983 config.inputFlags,
2984 config.navigation,
2985 config.screenWidth,
2986 config.screenHeight,
2987 config.smallestScreenWidthDp,
2988 config.screenWidthDp,
2989 config.screenHeightDp,
2990 config.layoutDirection));
2991
Adam Lesinskifab50872014-04-16 14:40:42 -07002992 if (filterable && !filter->match(config)) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002993 continue;
2994 }
2995
2996 const size_t typeStart = data->getSize();
2997
2998 ResTable_type* tHeader = (ResTable_type*)
2999 (((uint8_t*)data->editData(typeStart+typeSize)) + typeStart);
3000 if (tHeader == NULL) {
3001 fprintf(stderr, "ERROR: out of memory creating ResTable_type\n");
3002 return NO_MEMORY;
3003 }
3004
3005 memset(tHeader, 0, sizeof(*tHeader));
3006 tHeader->header.type = htods(RES_TABLE_TYPE_TYPE);
3007 tHeader->header.headerSize = htods(sizeof(*tHeader));
3008 tHeader->id = ti+1;
3009 tHeader->entryCount = htodl(N);
3010 tHeader->entriesStart = htodl(typeSize);
3011 tHeader->config = config;
3012 NOISY(printf("Writing type %d config: imsi:%d/%d lang:%c%c cnt:%c%c "
3013 "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
3014 "sw%ddp w%ddp h%ddp dir:%d\n",
3015 ti+1,
3016 tHeader->config.mcc, tHeader->config.mnc,
3017 tHeader->config.language[0] ? tHeader->config.language[0] : '-',
3018 tHeader->config.language[1] ? tHeader->config.language[1] : '-',
3019 tHeader->config.country[0] ? tHeader->config.country[0] : '-',
3020 tHeader->config.country[1] ? tHeader->config.country[1] : '-',
3021 tHeader->config.orientation,
3022 tHeader->config.uiMode,
3023 tHeader->config.touchscreen,
3024 tHeader->config.density,
3025 tHeader->config.keyboard,
3026 tHeader->config.inputFlags,
3027 tHeader->config.navigation,
3028 tHeader->config.screenWidth,
3029 tHeader->config.screenHeight,
3030 tHeader->config.smallestScreenWidthDp,
3031 tHeader->config.screenWidthDp,
3032 tHeader->config.screenHeightDp,
3033 tHeader->config.layoutDirection));
3034 tHeader->config.swapHtoD();
3035
3036 // Build the entries inside of this type.
3037 for (size_t ei=0; ei<N; ei++) {
3038 sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
3039 sp<Entry> e = cl->getEntries().valueFor(config);
3040
3041 // Set the offset for this entry in its type.
3042 uint32_t* index = (uint32_t*)
3043 (((uint8_t*)data->editData())
3044 + typeStart + sizeof(ResTable_type));
3045 if (e != NULL) {
3046 index[ei] = htodl(data->getSize()-typeStart-typeSize);
3047
3048 // Create the entry.
3049 ssize_t amt = e->flatten(bundle, data, cl->getPublic());
3050 if (amt < 0) {
3051 return amt;
3052 }
3053 validResources.editItemAt(ei) = true;
3054 } else {
3055 index[ei] = htodl(ResTable_type::NO_ENTRY);
3056 }
3057 }
3058
3059 // Fill in the rest of the type information.
3060 tHeader = (ResTable_type*)
3061 (((uint8_t*)data->editData()) + typeStart);
3062 tHeader->header.size = htodl(data->getSize()-typeStart);
3063 }
3064
Ying Wangcd28bd32013-11-14 17:12:10 -08003065 bool missing_entry = false;
3066 const char* log_prefix = bundle->getErrorOnMissingConfigEntry() ?
3067 "error" : "warning";
Adam Lesinski282e1812014-01-23 18:17:42 -08003068 for (size_t i = 0; i < N; ++i) {
3069 if (!validResources[i]) {
3070 sp<ConfigList> c = t->getOrderedConfigs().itemAt(i);
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07003071 fprintf(stderr, "%s: no entries written for %s/%s (0x%08x)\n", log_prefix,
3072 String8(typeName).string(), String8(c->getName()).string(),
3073 Res_MAKEID(p->getAssignedId() - 1, ti, i));
Ying Wangcd28bd32013-11-14 17:12:10 -08003074 missing_entry = true;
Adam Lesinski282e1812014-01-23 18:17:42 -08003075 }
3076 }
Ying Wangcd28bd32013-11-14 17:12:10 -08003077 if (bundle->getErrorOnMissingConfigEntry() && missing_entry) {
3078 fprintf(stderr, "Error: Missing entries, quit!\n");
3079 return NOT_ENOUGH_DATA;
3080 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003081 }
3082
3083 // Fill in the rest of the package information.
3084 header = (ResTable_package*)data->editData();
3085 header->header.size = htodl(data->getSize());
3086 header->typeStrings = htodl(typeStringsStart);
3087 header->lastPublicType = htodl(p->getTypeStrings().size());
3088 header->keyStrings = htodl(keyStringsStart);
3089 header->lastPublicKey = htodl(p->getKeyStrings().size());
3090
3091 flatPackages.add(data);
3092 }
3093
3094 // And now write out the final chunks.
3095 const size_t dataStart = dest->getSize();
3096
3097 {
3098 // blah
3099 ResTable_header header;
3100 memset(&header, 0, sizeof(header));
3101 header.header.type = htods(RES_TABLE_TYPE);
3102 header.header.headerSize = htods(sizeof(header));
3103 header.packageCount = htodl(flatPackages.size());
3104 status_t err = dest->writeData(&header, sizeof(header));
3105 if (err != NO_ERROR) {
3106 fprintf(stderr, "ERROR: out of memory creating ResTable_header\n");
3107 return err;
3108 }
3109 }
3110
3111 ssize_t strStart = dest->getSize();
Adam Lesinskifab50872014-04-16 14:40:42 -07003112 status_t err = valueStrings.writeStringBlock(dest);
Adam Lesinski282e1812014-01-23 18:17:42 -08003113 if (err != NO_ERROR) {
3114 return err;
3115 }
3116
3117 ssize_t amt = (dest->getSize()-strStart);
3118 strAmt += amt;
3119 #if PRINT_STRING_METRICS
3120 fprintf(stderr, "**** value strings: %d\n", amt);
3121 fprintf(stderr, "**** total strings: %d\n", strAmt);
3122 #endif
Adam Lesinskide898ff2014-01-29 18:20:45 -08003123
Adam Lesinski282e1812014-01-23 18:17:42 -08003124 for (pi=0; pi<flatPackages.size(); pi++) {
3125 err = dest->writeData(flatPackages[pi]->getData(),
3126 flatPackages[pi]->getSize());
3127 if (err != NO_ERROR) {
3128 fprintf(stderr, "ERROR: out of memory creating package chunk for ResTable_header\n");
3129 return err;
3130 }
3131 }
3132
3133 ResTable_header* header = (ResTable_header*)
3134 (((uint8_t*)dest->getData()) + dataStart);
3135 header->header.size = htodl(dest->getSize() - dataStart);
3136
3137 NOISY(aout << "Resource table:"
3138 << HexDump(dest->getData(), dest->getSize()) << endl);
3139
3140 #if PRINT_STRING_METRICS
3141 fprintf(stderr, "**** total resource table size: %d / %d%% strings\n",
3142 dest->getSize(), (strAmt*100)/dest->getSize());
3143 #endif
3144
3145 return NO_ERROR;
3146}
3147
Adam Lesinskide898ff2014-01-29 18:20:45 -08003148status_t ResourceTable::flattenLibraryTable(const sp<AaptFile>& dest, const Vector<sp<Package> >& libs) {
3149 // Write out the library table if necessary
3150 if (libs.size() > 0) {
3151 NOISY(fprintf(stderr, "Writing library reference table\n"));
3152
3153 const size_t libStart = dest->getSize();
3154 const size_t count = libs.size();
3155 ResTable_lib_header* libHeader = (ResTable_lib_header*) dest->editDataInRange(libStart, sizeof(ResTable_lib_header));
3156
3157 memset(libHeader, 0, sizeof(*libHeader));
3158 libHeader->header.type = htods(RES_TABLE_LIBRARY_TYPE);
3159 libHeader->header.headerSize = htods(sizeof(*libHeader));
3160 libHeader->header.size = htodl(sizeof(*libHeader) + (sizeof(ResTable_lib_entry) * count));
3161 libHeader->count = htodl(count);
3162
3163 // Write the library entries
3164 for (size_t i = 0; i < count; i++) {
3165 const size_t entryStart = dest->getSize();
3166 sp<Package> libPackage = libs[i];
3167 NOISY(fprintf(stderr, " Entry %s -> 0x%02x\n",
3168 String8(libPackage->getName()).string(),
3169 (uint8_t)libPackage->getAssignedId()));
3170
3171 ResTable_lib_entry* entry = (ResTable_lib_entry*) dest->editDataInRange(entryStart, sizeof(ResTable_lib_entry));
3172 memset(entry, 0, sizeof(*entry));
3173 entry->packageId = htodl(libPackage->getAssignedId());
3174 strcpy16_htod(entry->packageName, libPackage->getName().string());
3175 }
3176 }
3177 return NO_ERROR;
3178}
3179
Adam Lesinski282e1812014-01-23 18:17:42 -08003180void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp)
3181{
3182 fprintf(fp,
3183 "<!-- This file contains <public> resource definitions for all\n"
3184 " resources that were generated from the source data. -->\n"
3185 "\n"
3186 "<resources>\n");
3187
3188 writePublicDefinitions(package, fp, true);
3189 writePublicDefinitions(package, fp, false);
3190
3191 fprintf(fp,
3192 "\n"
3193 "</resources>\n");
3194}
3195
3196void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp, bool pub)
3197{
3198 bool didHeader = false;
3199
3200 sp<Package> pkg = mPackages.valueFor(package);
3201 if (pkg != NULL) {
3202 const size_t NT = pkg->getOrderedTypes().size();
3203 for (size_t i=0; i<NT; i++) {
3204 sp<Type> t = pkg->getOrderedTypes().itemAt(i);
3205 if (t == NULL) {
3206 continue;
3207 }
3208
3209 bool didType = false;
3210
3211 const size_t NC = t->getOrderedConfigs().size();
3212 for (size_t j=0; j<NC; j++) {
3213 sp<ConfigList> c = t->getOrderedConfigs().itemAt(j);
3214 if (c == NULL) {
3215 continue;
3216 }
3217
3218 if (c->getPublic() != pub) {
3219 continue;
3220 }
3221
3222 if (!didType) {
3223 fprintf(fp, "\n");
3224 didType = true;
3225 }
3226 if (!didHeader) {
3227 if (pub) {
3228 fprintf(fp," <!-- PUBLIC SECTION. These resources have been declared public.\n");
3229 fprintf(fp," Changes to these definitions will break binary compatibility. -->\n\n");
3230 } else {
3231 fprintf(fp," <!-- PRIVATE SECTION. These resources have not been declared public.\n");
3232 fprintf(fp," You can make them public my moving these lines into a file in res/values. -->\n\n");
3233 }
3234 didHeader = true;
3235 }
3236 if (!pub) {
3237 const size_t NE = c->getEntries().size();
3238 for (size_t k=0; k<NE; k++) {
3239 const SourcePos& pos = c->getEntries().valueAt(k)->getPos();
3240 if (pos.file != "") {
3241 fprintf(fp," <!-- Declared at %s:%d -->\n",
3242 pos.file.string(), pos.line);
3243 }
3244 }
3245 }
3246 fprintf(fp, " <public type=\"%s\" name=\"%s\" id=\"0x%08x\" />\n",
3247 String8(t->getName()).string(),
3248 String8(c->getName()).string(),
3249 getResId(pkg, t, c->getEntryIndex()));
3250 }
3251 }
3252 }
3253}
3254
3255ResourceTable::Item::Item(const SourcePos& _sourcePos,
3256 bool _isId,
3257 const String16& _value,
3258 const Vector<StringPool::entry_style_span>* _style,
3259 int32_t _format)
3260 : sourcePos(_sourcePos)
3261 , isId(_isId)
3262 , value(_value)
3263 , format(_format)
3264 , bagKeyId(0)
3265 , evaluating(false)
3266{
3267 if (_style) {
3268 style = *_style;
3269 }
3270}
3271
3272status_t ResourceTable::Entry::makeItABag(const SourcePos& sourcePos)
3273{
3274 if (mType == TYPE_BAG) {
3275 return NO_ERROR;
3276 }
3277 if (mType == TYPE_UNKNOWN) {
3278 mType = TYPE_BAG;
3279 return NO_ERROR;
3280 }
3281 sourcePos.error("Resource entry %s is already defined as a single item.\n"
3282 "%s:%d: Originally defined here.\n",
3283 String8(mName).string(),
3284 mItem.sourcePos.file.string(), mItem.sourcePos.line);
3285 return UNKNOWN_ERROR;
3286}
3287
3288status_t ResourceTable::Entry::setItem(const SourcePos& sourcePos,
3289 const String16& value,
3290 const Vector<StringPool::entry_style_span>* style,
3291 int32_t format,
3292 const bool overwrite)
3293{
3294 Item item(sourcePos, false, value, style);
3295
3296 if (mType == TYPE_BAG) {
3297 const Item& item(mBag.valueAt(0));
3298 sourcePos.error("Resource entry %s is already defined as a bag.\n"
3299 "%s:%d: Originally defined here.\n",
3300 String8(mName).string(),
3301 item.sourcePos.file.string(), item.sourcePos.line);
3302 return UNKNOWN_ERROR;
3303 }
3304 if ( (mType != TYPE_UNKNOWN) && (overwrite == false) ) {
3305 sourcePos.error("Resource entry %s is already defined.\n"
3306 "%s:%d: Originally defined here.\n",
3307 String8(mName).string(),
3308 mItem.sourcePos.file.string(), mItem.sourcePos.line);
3309 return UNKNOWN_ERROR;
3310 }
3311
3312 mType = TYPE_ITEM;
3313 mItem = item;
3314 mItemFormat = format;
3315 return NO_ERROR;
3316}
3317
3318status_t ResourceTable::Entry::addToBag(const SourcePos& sourcePos,
3319 const String16& key, const String16& value,
3320 const Vector<StringPool::entry_style_span>* style,
3321 bool replace, bool isId, int32_t format)
3322{
3323 status_t err = makeItABag(sourcePos);
3324 if (err != NO_ERROR) {
3325 return err;
3326 }
3327
3328 Item item(sourcePos, isId, value, style, format);
3329
3330 // XXX NOTE: there is an error if you try to have a bag with two keys,
3331 // one an attr and one an id, with the same name. Not something we
3332 // currently ever have to worry about.
3333 ssize_t origKey = mBag.indexOfKey(key);
3334 if (origKey >= 0) {
3335 if (!replace) {
3336 const Item& item(mBag.valueAt(origKey));
3337 sourcePos.error("Resource entry %s already has bag item %s.\n"
3338 "%s:%d: Originally defined here.\n",
3339 String8(mName).string(), String8(key).string(),
3340 item.sourcePos.file.string(), item.sourcePos.line);
3341 return UNKNOWN_ERROR;
3342 }
3343 //printf("Replacing %s with %s\n",
3344 // String8(mBag.valueFor(key).value).string(), String8(value).string());
3345 mBag.replaceValueFor(key, item);
3346 }
3347
3348 mBag.add(key, item);
3349 return NO_ERROR;
3350}
3351
3352status_t ResourceTable::Entry::emptyBag(const SourcePos& sourcePos)
3353{
3354 status_t err = makeItABag(sourcePos);
3355 if (err != NO_ERROR) {
3356 return err;
3357 }
3358
3359 mBag.clear();
3360 return NO_ERROR;
3361}
3362
3363status_t ResourceTable::Entry::generateAttributes(ResourceTable* table,
3364 const String16& package)
3365{
3366 const String16 attr16("attr");
3367 const String16 id16("id");
3368 const size_t N = mBag.size();
3369 for (size_t i=0; i<N; i++) {
3370 const String16& key = mBag.keyAt(i);
3371 const Item& it = mBag.valueAt(i);
3372 if (it.isId) {
3373 if (!table->hasBagOrEntry(key, &id16, &package)) {
3374 String16 value("false");
3375 status_t err = table->addEntry(SourcePos(String8("<generated>"), 0), package,
3376 id16, key, value);
3377 if (err != NO_ERROR) {
3378 return err;
3379 }
3380 }
3381 } else if (!table->hasBagOrEntry(key, &attr16, &package)) {
3382
3383#if 1
3384// fprintf(stderr, "ERROR: Bag attribute '%s' has not been defined.\n",
3385// String8(key).string());
3386// const Item& item(mBag.valueAt(i));
3387// fprintf(stderr, "Referenced from file %s line %d\n",
3388// item.sourcePos.file.string(), item.sourcePos.line);
3389// return UNKNOWN_ERROR;
3390#else
3391 char numberStr[16];
3392 sprintf(numberStr, "%d", ResTable_map::TYPE_ANY);
3393 status_t err = table->addBag(SourcePos("<generated>", 0), package,
3394 attr16, key, String16(""),
3395 String16("^type"),
3396 String16(numberStr), NULL, NULL);
3397 if (err != NO_ERROR) {
3398 return err;
3399 }
3400#endif
3401 }
3402 }
3403 return NO_ERROR;
3404}
3405
3406status_t ResourceTable::Entry::assignResourceIds(ResourceTable* table,
3407 const String16& package)
3408{
3409 bool hasErrors = false;
3410
3411 if (mType == TYPE_BAG) {
3412 const char* errorMsg;
3413 const String16 style16("style");
3414 const String16 attr16("attr");
3415 const String16 id16("id");
3416 mParentId = 0;
3417 if (mParent.size() > 0) {
3418 mParentId = table->getResId(mParent, &style16, NULL, &errorMsg);
3419 if (mParentId == 0) {
3420 mPos.error("Error retrieving parent for item: %s '%s'.\n",
3421 errorMsg, String8(mParent).string());
3422 hasErrors = true;
3423 }
3424 }
3425 const size_t N = mBag.size();
3426 for (size_t i=0; i<N; i++) {
3427 const String16& key = mBag.keyAt(i);
3428 Item& it = mBag.editValueAt(i);
3429 it.bagKeyId = table->getResId(key,
3430 it.isId ? &id16 : &attr16, NULL, &errorMsg);
3431 //printf("Bag key of %s: #%08x\n", String8(key).string(), it.bagKeyId);
3432 if (it.bagKeyId == 0) {
3433 it.sourcePos.error("Error: %s: %s '%s'.\n", errorMsg,
3434 String8(it.isId ? id16 : attr16).string(),
3435 String8(key).string());
3436 hasErrors = true;
3437 }
3438 }
3439 }
3440 return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
3441}
3442
3443status_t ResourceTable::Entry::prepareFlatten(StringPool* strings, ResourceTable* table,
3444 const String8* configTypeName, const ConfigDescription* config)
3445{
3446 if (mType == TYPE_ITEM) {
3447 Item& it = mItem;
3448 AccessorCookie ac(it.sourcePos, String8(mName), String8(it.value));
3449 if (!table->stringToValue(&it.parsedValue, strings,
3450 it.value, false, true, 0,
3451 &it.style, NULL, &ac, mItemFormat,
3452 configTypeName, config)) {
3453 return UNKNOWN_ERROR;
3454 }
3455 } else if (mType == TYPE_BAG) {
3456 const size_t N = mBag.size();
3457 for (size_t i=0; i<N; i++) {
3458 const String16& key = mBag.keyAt(i);
3459 Item& it = mBag.editValueAt(i);
3460 AccessorCookie ac(it.sourcePos, String8(key), String8(it.value));
3461 if (!table->stringToValue(&it.parsedValue, strings,
3462 it.value, false, true, it.bagKeyId,
3463 &it.style, NULL, &ac, it.format,
3464 configTypeName, config)) {
3465 return UNKNOWN_ERROR;
3466 }
3467 }
3468 } else {
3469 mPos.error("Error: entry %s is not a single item or a bag.\n",
3470 String8(mName).string());
3471 return UNKNOWN_ERROR;
3472 }
3473 return NO_ERROR;
3474}
3475
3476status_t ResourceTable::Entry::remapStringValue(StringPool* strings)
3477{
3478 if (mType == TYPE_ITEM) {
3479 Item& it = mItem;
3480 if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3481 it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3482 }
3483 } else if (mType == TYPE_BAG) {
3484 const size_t N = mBag.size();
3485 for (size_t i=0; i<N; i++) {
3486 Item& it = mBag.editValueAt(i);
3487 if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3488 it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3489 }
3490 }
3491 } else {
3492 mPos.error("Error: entry %s is not a single item or a bag.\n",
3493 String8(mName).string());
3494 return UNKNOWN_ERROR;
3495 }
3496 return NO_ERROR;
3497}
3498
3499ssize_t ResourceTable::Entry::flatten(Bundle* bundle, const sp<AaptFile>& data, bool isPublic)
3500{
3501 size_t amt = 0;
3502 ResTable_entry header;
3503 memset(&header, 0, sizeof(header));
3504 header.size = htods(sizeof(header));
3505 const type ty = this != NULL ? mType : TYPE_ITEM;
3506 if (this != NULL) {
3507 if (ty == TYPE_BAG) {
3508 header.flags |= htods(header.FLAG_COMPLEX);
3509 }
3510 if (isPublic) {
3511 header.flags |= htods(header.FLAG_PUBLIC);
3512 }
3513 header.key.index = htodl(mNameIndex);
3514 }
3515 if (ty != TYPE_BAG) {
3516 status_t err = data->writeData(&header, sizeof(header));
3517 if (err != NO_ERROR) {
3518 fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3519 return err;
3520 }
3521
3522 const Item& it = mItem;
3523 Res_value par;
3524 memset(&par, 0, sizeof(par));
3525 par.size = htods(it.parsedValue.size);
3526 par.dataType = it.parsedValue.dataType;
3527 par.res0 = it.parsedValue.res0;
3528 par.data = htodl(it.parsedValue.data);
3529 #if 0
3530 printf("Writing item (%s): type=%d, data=0x%x, res0=0x%x\n",
3531 String8(mName).string(), it.parsedValue.dataType,
3532 it.parsedValue.data, par.res0);
3533 #endif
3534 err = data->writeData(&par, it.parsedValue.size);
3535 if (err != NO_ERROR) {
3536 fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3537 return err;
3538 }
3539 amt += it.parsedValue.size;
3540 } else {
3541 size_t N = mBag.size();
3542 size_t i;
3543 // Create correct ordering of items.
3544 KeyedVector<uint32_t, const Item*> items;
3545 for (i=0; i<N; i++) {
3546 const Item& it = mBag.valueAt(i);
3547 items.add(it.bagKeyId, &it);
3548 }
3549 N = items.size();
3550
3551 ResTable_map_entry mapHeader;
3552 memcpy(&mapHeader, &header, sizeof(header));
3553 mapHeader.size = htods(sizeof(mapHeader));
3554 mapHeader.parent.ident = htodl(mParentId);
3555 mapHeader.count = htodl(N);
3556 status_t err = data->writeData(&mapHeader, sizeof(mapHeader));
3557 if (err != NO_ERROR) {
3558 fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3559 return err;
3560 }
3561
3562 for (i=0; i<N; i++) {
3563 const Item& it = *items.valueAt(i);
3564 ResTable_map map;
3565 map.name.ident = htodl(it.bagKeyId);
3566 map.value.size = htods(it.parsedValue.size);
3567 map.value.dataType = it.parsedValue.dataType;
3568 map.value.res0 = it.parsedValue.res0;
3569 map.value.data = htodl(it.parsedValue.data);
3570 err = data->writeData(&map, sizeof(map));
3571 if (err != NO_ERROR) {
3572 fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3573 return err;
3574 }
3575 amt += sizeof(map);
3576 }
3577 }
3578 return amt;
3579}
3580
3581void ResourceTable::ConfigList::appendComment(const String16& comment,
3582 bool onlyIfEmpty)
3583{
3584 if (comment.size() <= 0) {
3585 return;
3586 }
3587 if (onlyIfEmpty && mComment.size() > 0) {
3588 return;
3589 }
3590 if (mComment.size() > 0) {
3591 mComment.append(String16("\n"));
3592 }
3593 mComment.append(comment);
3594}
3595
3596void ResourceTable::ConfigList::appendTypeComment(const String16& comment)
3597{
3598 if (comment.size() <= 0) {
3599 return;
3600 }
3601 if (mTypeComment.size() > 0) {
3602 mTypeComment.append(String16("\n"));
3603 }
3604 mTypeComment.append(comment);
3605}
3606
3607status_t ResourceTable::Type::addPublic(const SourcePos& sourcePos,
3608 const String16& name,
3609 const uint32_t ident)
3610{
3611 #if 0
3612 int32_t entryIdx = Res_GETENTRY(ident);
3613 if (entryIdx < 0) {
3614 sourcePos.error("Public resource %s/%s has an invalid 0 identifier (0x%08x).\n",
3615 String8(mName).string(), String8(name).string(), ident);
3616 return UNKNOWN_ERROR;
3617 }
3618 #endif
3619
3620 int32_t typeIdx = Res_GETTYPE(ident);
3621 if (typeIdx >= 0) {
3622 typeIdx++;
3623 if (mPublicIndex > 0 && mPublicIndex != typeIdx) {
3624 sourcePos.error("Public resource %s/%s has conflicting type codes for its"
3625 " public identifiers (0x%x vs 0x%x).\n",
3626 String8(mName).string(), String8(name).string(),
3627 mPublicIndex, typeIdx);
3628 return UNKNOWN_ERROR;
3629 }
3630 mPublicIndex = typeIdx;
3631 }
3632
3633 if (mFirstPublicSourcePos == NULL) {
3634 mFirstPublicSourcePos = new SourcePos(sourcePos);
3635 }
3636
3637 if (mPublic.indexOfKey(name) < 0) {
3638 mPublic.add(name, Public(sourcePos, String16(), ident));
3639 } else {
3640 Public& p = mPublic.editValueFor(name);
3641 if (p.ident != ident) {
3642 sourcePos.error("Public resource %s/%s has conflicting public identifiers"
3643 " (0x%08x vs 0x%08x).\n"
3644 "%s:%d: Originally defined here.\n",
3645 String8(mName).string(), String8(name).string(), p.ident, ident,
3646 p.sourcePos.file.string(), p.sourcePos.line);
3647 return UNKNOWN_ERROR;
3648 }
3649 }
3650
3651 return NO_ERROR;
3652}
3653
3654void ResourceTable::Type::canAddEntry(const String16& name)
3655{
3656 mCanAddEntries.add(name);
3657}
3658
3659sp<ResourceTable::Entry> ResourceTable::Type::getEntry(const String16& entry,
3660 const SourcePos& sourcePos,
3661 const ResTable_config* config,
3662 bool doSetIndex,
3663 bool overlay,
3664 bool autoAddOverlay)
3665{
3666 int pos = -1;
3667 sp<ConfigList> c = mConfigs.valueFor(entry);
3668 if (c == NULL) {
3669 if (overlay && !autoAddOverlay && mCanAddEntries.indexOf(entry) < 0) {
3670 sourcePos.error("Resource at %s appears in overlay but not"
3671 " in the base package; use <add-resource> to add.\n",
3672 String8(entry).string());
3673 return NULL;
3674 }
3675 c = new ConfigList(entry, sourcePos);
3676 mConfigs.add(entry, c);
3677 pos = (int)mOrderedConfigs.size();
3678 mOrderedConfigs.add(c);
3679 if (doSetIndex) {
3680 c->setEntryIndex(pos);
3681 }
3682 }
3683
3684 ConfigDescription cdesc;
3685 if (config) cdesc = *config;
3686
3687 sp<Entry> e = c->getEntries().valueFor(cdesc);
3688 if (e == NULL) {
3689 if (config != NULL) {
3690 NOISY(printf("New entry at %s:%d: imsi:%d/%d lang:%c%c cnt:%c%c "
3691 "orien:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
3692 "sw%ddp w%ddp h%ddp dir:%d\n",
3693 sourcePos.file.string(), sourcePos.line,
3694 config->mcc, config->mnc,
3695 config->language[0] ? config->language[0] : '-',
3696 config->language[1] ? config->language[1] : '-',
3697 config->country[0] ? config->country[0] : '-',
3698 config->country[1] ? config->country[1] : '-',
3699 config->orientation,
3700 config->touchscreen,
3701 config->density,
3702 config->keyboard,
3703 config->inputFlags,
3704 config->navigation,
3705 config->screenWidth,
3706 config->screenHeight,
3707 config->smallestScreenWidthDp,
3708 config->screenWidthDp,
3709 config->screenHeightDp,
3710 config->layoutDirection));
3711 } else {
3712 NOISY(printf("New entry at %s:%d: NULL config\n",
3713 sourcePos.file.string(), sourcePos.line));
3714 }
3715 e = new Entry(entry, sourcePos);
3716 c->addEntry(cdesc, e);
3717 /*
3718 if (doSetIndex) {
3719 if (pos < 0) {
3720 for (pos=0; pos<(int)mOrderedConfigs.size(); pos++) {
3721 if (mOrderedConfigs[pos] == c) {
3722 break;
3723 }
3724 }
3725 if (pos >= (int)mOrderedConfigs.size()) {
3726 sourcePos.error("Internal error: config not found in mOrderedConfigs when adding entry");
3727 return NULL;
3728 }
3729 }
3730 e->setEntryIndex(pos);
3731 }
3732 */
3733 }
3734
3735 mUniqueConfigs.add(cdesc);
3736
3737 return e;
3738}
3739
3740status_t ResourceTable::Type::applyPublicEntryOrder()
3741{
3742 size_t N = mOrderedConfigs.size();
3743 Vector<sp<ConfigList> > origOrder(mOrderedConfigs);
3744 bool hasError = false;
3745
3746 size_t i;
3747 for (i=0; i<N; i++) {
3748 mOrderedConfigs.replaceAt(NULL, i);
3749 }
3750
3751 const size_t NP = mPublic.size();
3752 //printf("Ordering %d configs from %d public defs\n", N, NP);
3753 size_t j;
3754 for (j=0; j<NP; j++) {
3755 const String16& name = mPublic.keyAt(j);
3756 const Public& p = mPublic.valueAt(j);
3757 int32_t idx = Res_GETENTRY(p.ident);
3758 //printf("Looking for entry \"%s\"/\"%s\" (0x%08x) in %d...\n",
3759 // String8(mName).string(), String8(name).string(), p.ident, N);
3760 bool found = false;
3761 for (i=0; i<N; i++) {
3762 sp<ConfigList> e = origOrder.itemAt(i);
3763 //printf("#%d: \"%s\"\n", i, String8(e->getName()).string());
3764 if (e->getName() == name) {
3765 if (idx >= (int32_t)mOrderedConfigs.size()) {
3766 p.sourcePos.error("Public entry identifier 0x%x entry index "
3767 "is larger than available symbols (index %d, total symbols %d).\n",
3768 p.ident, idx, mOrderedConfigs.size());
3769 hasError = true;
3770 } else if (mOrderedConfigs.itemAt(idx) == NULL) {
3771 e->setPublic(true);
3772 e->setPublicSourcePos(p.sourcePos);
3773 mOrderedConfigs.replaceAt(e, idx);
3774 origOrder.removeAt(i);
3775 N--;
3776 found = true;
3777 break;
3778 } else {
3779 sp<ConfigList> oe = mOrderedConfigs.itemAt(idx);
3780
3781 p.sourcePos.error("Multiple entry names declared for public entry"
3782 " identifier 0x%x in type %s (%s vs %s).\n"
3783 "%s:%d: Originally defined here.",
3784 idx+1, String8(mName).string(),
3785 String8(oe->getName()).string(),
3786 String8(name).string(),
3787 oe->getPublicSourcePos().file.string(),
3788 oe->getPublicSourcePos().line);
3789 hasError = true;
3790 }
3791 }
3792 }
3793
3794 if (!found) {
3795 p.sourcePos.error("Public symbol %s/%s declared here is not defined.",
3796 String8(mName).string(), String8(name).string());
3797 hasError = true;
3798 }
3799 }
3800
3801 //printf("Copying back in %d non-public configs, have %d\n", N, origOrder.size());
3802
3803 if (N != origOrder.size()) {
3804 printf("Internal error: remaining private symbol count mismatch\n");
3805 N = origOrder.size();
3806 }
3807
3808 j = 0;
3809 for (i=0; i<N; i++) {
3810 sp<ConfigList> e = origOrder.itemAt(i);
3811 // There will always be enough room for the remaining entries.
3812 while (mOrderedConfigs.itemAt(j) != NULL) {
3813 j++;
3814 }
3815 mOrderedConfigs.replaceAt(e, j);
3816 j++;
3817 }
3818
3819 return hasError ? UNKNOWN_ERROR : NO_ERROR;
3820}
3821
3822ResourceTable::Package::Package(const String16& name, ssize_t includedId)
3823 : mName(name), mIncludedId(includedId),
3824 mTypeStringsMapping(0xffffffff),
3825 mKeyStringsMapping(0xffffffff)
3826{
3827}
3828
3829sp<ResourceTable::Type> ResourceTable::Package::getType(const String16& type,
3830 const SourcePos& sourcePos,
3831 bool doSetIndex)
3832{
3833 sp<Type> t = mTypes.valueFor(type);
3834 if (t == NULL) {
3835 t = new Type(type, sourcePos);
3836 mTypes.add(type, t);
3837 mOrderedTypes.add(t);
3838 if (doSetIndex) {
3839 // For some reason the type's index is set to one plus the index
3840 // in the mOrderedTypes list, rather than just the index.
3841 t->setIndex(mOrderedTypes.size());
3842 }
3843 }
3844 return t;
3845}
3846
3847status_t ResourceTable::Package::setTypeStrings(const sp<AaptFile>& data)
3848{
3849 mTypeStringsData = data;
3850 status_t err = setStrings(data, &mTypeStrings, &mTypeStringsMapping);
3851 if (err != NO_ERROR) {
3852 fprintf(stderr, "ERROR: Type string data is corrupt!\n");
3853 }
3854 return err;
3855}
3856
3857status_t ResourceTable::Package::setKeyStrings(const sp<AaptFile>& data)
3858{
3859 mKeyStringsData = data;
3860 status_t err = setStrings(data, &mKeyStrings, &mKeyStringsMapping);
3861 if (err != NO_ERROR) {
3862 fprintf(stderr, "ERROR: Key string data is corrupt!\n");
3863 }
3864 return err;
3865}
3866
3867status_t ResourceTable::Package::setStrings(const sp<AaptFile>& data,
3868 ResStringPool* strings,
3869 DefaultKeyedVector<String16, uint32_t>* mappings)
3870{
3871 if (data->getData() == NULL) {
3872 return UNKNOWN_ERROR;
3873 }
3874
3875 NOISY(aout << "Setting restable string pool: "
3876 << HexDump(data->getData(), data->getSize()) << endl);
3877
3878 status_t err = strings->setTo(data->getData(), data->getSize());
3879 if (err == NO_ERROR) {
3880 const size_t N = strings->size();
3881 for (size_t i=0; i<N; i++) {
3882 size_t len;
3883 mappings->add(String16(strings->stringAt(i, &len)), i);
3884 }
3885 }
3886 return err;
3887}
3888
3889status_t ResourceTable::Package::applyPublicTypeOrder()
3890{
3891 size_t N = mOrderedTypes.size();
3892 Vector<sp<Type> > origOrder(mOrderedTypes);
3893
3894 size_t i;
3895 for (i=0; i<N; i++) {
3896 mOrderedTypes.replaceAt(NULL, i);
3897 }
3898
3899 for (i=0; i<N; i++) {
3900 sp<Type> t = origOrder.itemAt(i);
3901 int32_t idx = t->getPublicIndex();
3902 if (idx > 0) {
3903 idx--;
3904 while (idx >= (int32_t)mOrderedTypes.size()) {
3905 mOrderedTypes.add();
3906 }
3907 if (mOrderedTypes.itemAt(idx) != NULL) {
3908 sp<Type> ot = mOrderedTypes.itemAt(idx);
3909 t->getFirstPublicSourcePos().error("Multiple type names declared for public type"
3910 " identifier 0x%x (%s vs %s).\n"
3911 "%s:%d: Originally defined here.",
3912 idx, String8(ot->getName()).string(),
3913 String8(t->getName()).string(),
3914 ot->getFirstPublicSourcePos().file.string(),
3915 ot->getFirstPublicSourcePos().line);
3916 return UNKNOWN_ERROR;
3917 }
3918 mOrderedTypes.replaceAt(t, idx);
3919 origOrder.removeAt(i);
3920 i--;
3921 N--;
3922 }
3923 }
3924
3925 size_t j=0;
3926 for (i=0; i<N; i++) {
3927 sp<Type> t = origOrder.itemAt(i);
3928 // There will always be enough room for the remaining types.
3929 while (mOrderedTypes.itemAt(j) != NULL) {
3930 j++;
3931 }
3932 mOrderedTypes.replaceAt(t, j);
3933 }
3934
3935 return NO_ERROR;
3936}
3937
3938sp<ResourceTable::Package> ResourceTable::getPackage(const String16& package)
3939{
3940 sp<Package> p = mPackages.valueFor(package);
3941 if (p == NULL) {
3942 if (mIsAppPackage) {
3943 if (mHaveAppPackage) {
3944 fprintf(stderr, "Adding multiple application package resources; only one is allowed.\n"
3945 "Use -x to create extended resources.\n");
3946 return NULL;
3947 }
3948 mHaveAppPackage = true;
Adam Lesinskide898ff2014-01-29 18:20:45 -08003949 p = new Package(package, mIsSharedLibrary ? 0 : 127);
Adam Lesinski282e1812014-01-23 18:17:42 -08003950 } else {
3951 p = new Package(package, mNextPackageId);
3952 }
3953 //printf("*** NEW PACKAGE: \"%s\" id=%d\n",
3954 // String8(package).string(), p->getAssignedId());
3955 mPackages.add(package, p);
3956 mOrderedPackages.add(p);
3957 mNextPackageId++;
3958 }
3959 return p;
3960}
3961
3962sp<ResourceTable::Type> ResourceTable::getType(const String16& package,
3963 const String16& type,
3964 const SourcePos& sourcePos,
3965 bool doSetIndex)
3966{
3967 sp<Package> p = getPackage(package);
3968 if (p == NULL) {
3969 return NULL;
3970 }
3971 return p->getType(type, sourcePos, doSetIndex);
3972}
3973
3974sp<ResourceTable::Entry> ResourceTable::getEntry(const String16& package,
3975 const String16& type,
3976 const String16& name,
3977 const SourcePos& sourcePos,
3978 bool overlay,
3979 const ResTable_config* config,
3980 bool doSetIndex)
3981{
3982 sp<Type> t = getType(package, type, sourcePos, doSetIndex);
3983 if (t == NULL) {
3984 return NULL;
3985 }
3986 return t->getEntry(name, sourcePos, config, doSetIndex, overlay, mBundle->getAutoAddOverlay());
3987}
3988
3989sp<const ResourceTable::Entry> ResourceTable::getEntry(uint32_t resID,
3990 const ResTable_config* config) const
3991{
3992 int pid = Res_GETPACKAGE(resID)+1;
3993 const size_t N = mOrderedPackages.size();
3994 size_t i;
3995 sp<Package> p;
3996 for (i=0; i<N; i++) {
3997 sp<Package> check = mOrderedPackages[i];
3998 if (check->getAssignedId() == pid) {
3999 p = check;
4000 break;
4001 }
4002
4003 }
4004 if (p == NULL) {
4005 fprintf(stderr, "warning: Package not found for resource #%08x\n", resID);
4006 return NULL;
4007 }
4008
4009 int tid = Res_GETTYPE(resID);
4010 if (tid < 0 || tid >= (int)p->getOrderedTypes().size()) {
4011 fprintf(stderr, "warning: Type not found for resource #%08x\n", resID);
4012 return NULL;
4013 }
4014 sp<Type> t = p->getOrderedTypes()[tid];
4015
4016 int eid = Res_GETENTRY(resID);
4017 if (eid < 0 || eid >= (int)t->getOrderedConfigs().size()) {
4018 fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
4019 return NULL;
4020 }
4021
4022 sp<ConfigList> c = t->getOrderedConfigs()[eid];
4023 if (c == NULL) {
4024 fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
4025 return NULL;
4026 }
4027
4028 ConfigDescription cdesc;
4029 if (config) cdesc = *config;
4030 sp<Entry> e = c->getEntries().valueFor(cdesc);
4031 if (c == NULL) {
4032 fprintf(stderr, "warning: Entry configuration not found for resource #%08x\n", resID);
4033 return NULL;
4034 }
4035
4036 return e;
4037}
4038
4039const ResourceTable::Item* ResourceTable::getItem(uint32_t resID, uint32_t attrID) const
4040{
4041 sp<const Entry> e = getEntry(resID);
4042 if (e == NULL) {
4043 return NULL;
4044 }
4045
4046 const size_t N = e->getBag().size();
4047 for (size_t i=0; i<N; i++) {
4048 const Item& it = e->getBag().valueAt(i);
4049 if (it.bagKeyId == 0) {
4050 fprintf(stderr, "warning: ID not yet assigned to '%s' in bag '%s'\n",
4051 String8(e->getName()).string(),
4052 String8(e->getBag().keyAt(i)).string());
4053 }
4054 if (it.bagKeyId == attrID) {
4055 return &it;
4056 }
4057 }
4058
4059 return NULL;
4060}
4061
4062bool ResourceTable::getItemValue(
4063 uint32_t resID, uint32_t attrID, Res_value* outValue)
4064{
4065 const Item* item = getItem(resID, attrID);
4066
4067 bool res = false;
4068 if (item != NULL) {
4069 if (item->evaluating) {
4070 sp<const Entry> e = getEntry(resID);
4071 const size_t N = e->getBag().size();
4072 size_t i;
4073 for (i=0; i<N; i++) {
4074 if (&e->getBag().valueAt(i) == item) {
4075 break;
4076 }
4077 }
4078 fprintf(stderr, "warning: Circular reference detected in key '%s' of bag '%s'\n",
4079 String8(e->getName()).string(),
4080 String8(e->getBag().keyAt(i)).string());
4081 return false;
4082 }
4083 item->evaluating = true;
4084 res = stringToValue(outValue, NULL, item->value, false, false, item->bagKeyId);
4085 NOISY(
4086 if (res) {
4087 printf("getItemValue of #%08x[#%08x] (%s): type=#%08x, data=#%08x\n",
4088 resID, attrID, String8(getEntry(resID)->getName()).string(),
4089 outValue->dataType, outValue->data);
4090 } else {
4091 printf("getItemValue of #%08x[#%08x]: failed\n",
4092 resID, attrID);
4093 }
4094 );
4095 item->evaluating = false;
4096 }
4097 return res;
4098}