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