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