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