blob: 6fbc17cabda9c36b50548d6a0bc9970977dcbdb0 [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
Adam Lesinskide7de472014-11-03 12:03:08 -08009#include "AaptUtil.h"
Adam Lesinski282e1812014-01-23 18:17:42 -080010#include "XMLNode.h"
11#include "ResourceFilter.h"
12#include "ResourceIdCache.h"
Adam Lesinskidcdfe9f2014-11-06 12:54:36 -080013#include "SdkConstants.h"
Adam Lesinski282e1812014-01-23 18:17:42 -080014
Adam Lesinski9b624c12014-11-19 17:49:26 -080015#include <algorithm>
Adam Lesinski282e1812014-01-23 18:17:42 -080016#include <androidfw/ResourceTypes.h>
17#include <utils/ByteOrder.h>
Adam Lesinski82a2dd82014-09-17 18:34:15 -070018#include <utils/TypeHelpers.h>
Adam Lesinski282e1812014-01-23 18:17:42 -080019#include <stdarg.h>
20
Andreas Gampe2412f842014-09-30 20:55:57 -070021// SSIZE: mingw does not have signed size_t == ssize_t.
22// STATUST: mingw does seem to redefine UNKNOWN_ERROR from our enum value, so a cast is necessary.
23#if HAVE_PRINTF_ZD
24# define SSIZE(x) x
25# define STATUST(x) x
26#else
27# define SSIZE(x) (signed size_t)x
28# define STATUST(x) (status_t)x
29#endif
30
31// Set to true for noisy debug output.
32static const bool kIsDebug = false;
33
34#if PRINT_STRING_METRICS
35static const bool kPrintStringMetrics = true;
36#else
37static const bool kPrintStringMetrics = false;
38#endif
Adam Lesinski282e1812014-01-23 18:17:42 -080039
Adam Lesinski9b624c12014-11-19 17:49:26 -080040static const char* kAttrPrivateType = "^attr-private";
41
Adam Lesinskie572c012014-09-19 15:10:04 -070042status_t compileXmlFile(const Bundle* bundle,
43 const sp<AaptAssets>& assets,
44 const String16& resourceName,
Adam Lesinski282e1812014-01-23 18:17:42 -080045 const sp<AaptFile>& target,
46 ResourceTable* table,
47 int options)
48{
49 sp<XMLNode> root = XMLNode::parse(target);
50 if (root == NULL) {
51 return UNKNOWN_ERROR;
52 }
Anton Krumina2ef5c02014-03-12 14:46:44 -070053
Adam Lesinskie572c012014-09-19 15:10:04 -070054 return compileXmlFile(bundle, assets, resourceName, root, target, table, options);
Adam Lesinski282e1812014-01-23 18:17:42 -080055}
56
Adam Lesinskie572c012014-09-19 15:10:04 -070057status_t compileXmlFile(const Bundle* bundle,
58 const sp<AaptAssets>& assets,
59 const String16& resourceName,
Adam Lesinski282e1812014-01-23 18:17:42 -080060 const sp<AaptFile>& target,
61 const sp<AaptFile>& outTarget,
62 ResourceTable* table,
63 int options)
64{
65 sp<XMLNode> root = XMLNode::parse(target);
66 if (root == NULL) {
67 return UNKNOWN_ERROR;
68 }
69
Adam Lesinskie572c012014-09-19 15:10:04 -070070 return compileXmlFile(bundle, assets, resourceName, root, outTarget, table, options);
Adam Lesinski282e1812014-01-23 18:17:42 -080071}
72
Adam Lesinskie572c012014-09-19 15:10:04 -070073status_t compileXmlFile(const Bundle* bundle,
74 const sp<AaptAssets>& assets,
75 const String16& resourceName,
Adam Lesinski282e1812014-01-23 18:17:42 -080076 const sp<XMLNode>& root,
77 const sp<AaptFile>& target,
78 ResourceTable* table,
79 int options)
80{
81 if ((options&XML_COMPILE_STRIP_WHITESPACE) != 0) {
82 root->removeWhitespace(true, NULL);
83 } else if ((options&XML_COMPILE_COMPACT_WHITESPACE) != 0) {
84 root->removeWhitespace(false, NULL);
85 }
86
87 if ((options&XML_COMPILE_UTF8) != 0) {
88 root->setUTF8(true);
89 }
90
91 bool hasErrors = false;
92
93 if ((options&XML_COMPILE_ASSIGN_ATTRIBUTE_IDS) != 0) {
94 status_t err = root->assignResourceIds(assets, table);
95 if (err != NO_ERROR) {
96 hasErrors = true;
97 }
98 }
99
100 status_t err = root->parseValues(assets, table);
101 if (err != NO_ERROR) {
102 hasErrors = true;
103 }
104
105 if (hasErrors) {
106 return UNKNOWN_ERROR;
107 }
Adam Lesinskie572c012014-09-19 15:10:04 -0700108
109 if (table->modifyForCompat(bundle, resourceName, target, root) != NO_ERROR) {
110 return UNKNOWN_ERROR;
111 }
Andreas Gampe87332a72014-10-01 22:03:58 -0700112
Andreas Gampe2412f842014-09-30 20:55:57 -0700113 if (kIsDebug) {
114 printf("Input XML Resource:\n");
115 root->print();
116 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800117 err = root->flatten(target,
118 (options&XML_COMPILE_STRIP_COMMENTS) != 0,
119 (options&XML_COMPILE_STRIP_RAW_VALUES) != 0);
120 if (err != NO_ERROR) {
121 return err;
122 }
123
Andreas Gampe2412f842014-09-30 20:55:57 -0700124 if (kIsDebug) {
125 printf("Output XML Resource:\n");
126 ResXMLTree tree;
Adam Lesinski282e1812014-01-23 18:17:42 -0800127 tree.setTo(target->getData(), target->getSize());
Andreas Gampe2412f842014-09-30 20:55:57 -0700128 printXMLBlock(&tree);
129 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800130
131 target->setCompressionMethod(ZipEntry::kCompressDeflated);
132
133 return err;
134}
135
Adam Lesinski282e1812014-01-23 18:17:42 -0800136struct flag_entry
137{
138 const char16_t* name;
139 size_t nameLen;
140 uint32_t value;
141 const char* description;
142};
143
144static const char16_t referenceArray[] =
145 { 'r', 'e', 'f', 'e', 'r', 'e', 'n', 'c', 'e' };
146static const char16_t stringArray[] =
147 { 's', 't', 'r', 'i', 'n', 'g' };
148static const char16_t integerArray[] =
149 { 'i', 'n', 't', 'e', 'g', 'e', 'r' };
150static const char16_t booleanArray[] =
151 { 'b', 'o', 'o', 'l', 'e', 'a', 'n' };
152static const char16_t colorArray[] =
153 { 'c', 'o', 'l', 'o', 'r' };
154static const char16_t floatArray[] =
155 { 'f', 'l', 'o', 'a', 't' };
156static const char16_t dimensionArray[] =
157 { 'd', 'i', 'm', 'e', 'n', 's', 'i', 'o', 'n' };
158static const char16_t fractionArray[] =
159 { 'f', 'r', 'a', 'c', 't', 'i', 'o', 'n' };
160static const char16_t enumArray[] =
161 { 'e', 'n', 'u', 'm' };
162static const char16_t flagsArray[] =
163 { 'f', 'l', 'a', 'g', 's' };
164
165static const flag_entry gFormatFlags[] = {
166 { referenceArray, sizeof(referenceArray)/2, ResTable_map::TYPE_REFERENCE,
167 "a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\n"
168 "or to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\"."},
169 { stringArray, sizeof(stringArray)/2, ResTable_map::TYPE_STRING,
170 "a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character." },
171 { integerArray, sizeof(integerArray)/2, ResTable_map::TYPE_INTEGER,
172 "an integer value, such as \"<code>100</code>\"." },
173 { booleanArray, sizeof(booleanArray)/2, ResTable_map::TYPE_BOOLEAN,
174 "a boolean value, either \"<code>true</code>\" or \"<code>false</code>\"." },
175 { colorArray, sizeof(colorArray)/2, ResTable_map::TYPE_COLOR,
176 "a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n"
177 "\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\"." },
178 { floatArray, sizeof(floatArray)/2, ResTable_map::TYPE_FLOAT,
179 "a floating point value, such as \"<code>1.2</code>\"."},
180 { dimensionArray, sizeof(dimensionArray)/2, ResTable_map::TYPE_DIMENSION,
181 "a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\n"
182 "Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\n"
183 "in (inches), mm (millimeters)." },
184 { fractionArray, sizeof(fractionArray)/2, ResTable_map::TYPE_FRACTION,
185 "a fractional value, which is a floating point number appended with either % or %p, such as \"<code>14.5%</code>\".\n"
186 "The % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to\n"
187 "some parent container." },
188 { enumArray, sizeof(enumArray)/2, ResTable_map::TYPE_ENUM, NULL },
189 { flagsArray, sizeof(flagsArray)/2, ResTable_map::TYPE_FLAGS, NULL },
190 { NULL, 0, 0, NULL }
191};
192
193static const char16_t suggestedArray[] = { 's', 'u', 'g', 'g', 'e', 's', 't', 'e', 'd' };
194
195static const flag_entry l10nRequiredFlags[] = {
196 { suggestedArray, sizeof(suggestedArray)/2, ResTable_map::L10N_SUGGESTED, NULL },
197 { NULL, 0, 0, NULL }
198};
199
200static const char16_t nulStr[] = { 0 };
201
202static uint32_t parse_flags(const char16_t* str, size_t len,
203 const flag_entry* flags, bool* outError = NULL)
204{
205 while (len > 0 && isspace(*str)) {
206 str++;
207 len--;
208 }
209 while (len > 0 && isspace(str[len-1])) {
210 len--;
211 }
212
213 const char16_t* const end = str + len;
214 uint32_t value = 0;
215
216 while (str < end) {
217 const char16_t* div = str;
218 while (div < end && *div != '|') {
219 div++;
220 }
221
222 const flag_entry* cur = flags;
223 while (cur->name) {
224 if (strzcmp16(cur->name, cur->nameLen, str, div-str) == 0) {
225 value |= cur->value;
226 break;
227 }
228 cur++;
229 }
230
231 if (!cur->name) {
232 if (outError) *outError = true;
233 return 0;
234 }
235
236 str = div < end ? div+1 : div;
237 }
238
239 if (outError) *outError = false;
240 return value;
241}
242
243static String16 mayOrMust(int type, int flags)
244{
245 if ((type&(~flags)) == 0) {
246 return String16("<p>Must");
247 }
248
249 return String16("<p>May");
250}
251
252static void appendTypeInfo(ResourceTable* outTable, const String16& pkg,
253 const String16& typeName, const String16& ident, int type,
254 const flag_entry* flags)
255{
256 bool hadType = false;
257 while (flags->name) {
258 if ((type&flags->value) != 0 && flags->description != NULL) {
259 String16 fullMsg(mayOrMust(type, flags->value));
260 fullMsg.append(String16(" be "));
261 fullMsg.append(String16(flags->description));
262 outTable->appendTypeComment(pkg, typeName, ident, fullMsg);
263 hadType = true;
264 }
265 flags++;
266 }
267 if (hadType && (type&ResTable_map::TYPE_REFERENCE) == 0) {
268 outTable->appendTypeComment(pkg, typeName, ident,
269 String16("<p>This may also be a reference to a resource (in the form\n"
270 "\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\n"
271 "theme attribute (in the form\n"
272 "\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\n"
273 "containing a value of this type."));
274 }
275}
276
277struct PendingAttribute
278{
279 const String16 myPackage;
280 const SourcePos sourcePos;
281 const bool appendComment;
282 int32_t type;
283 String16 ident;
284 String16 comment;
285 bool hasErrors;
286 bool added;
287
288 PendingAttribute(String16 _package, const sp<AaptFile>& in,
289 ResXMLTree& block, bool _appendComment)
290 : myPackage(_package)
291 , sourcePos(in->getPrintableSource(), block.getLineNumber())
292 , appendComment(_appendComment)
293 , type(ResTable_map::TYPE_ANY)
294 , hasErrors(false)
295 , added(false)
296 {
297 }
298
299 status_t createIfNeeded(ResourceTable* outTable)
300 {
301 if (added || hasErrors) {
302 return NO_ERROR;
303 }
304 added = true;
305
306 String16 attr16("attr");
307
308 if (outTable->hasBagOrEntry(myPackage, attr16, ident)) {
309 sourcePos.error("Attribute \"%s\" has already been defined\n",
310 String8(ident).string());
311 hasErrors = true;
312 return UNKNOWN_ERROR;
313 }
314
315 char numberStr[16];
316 sprintf(numberStr, "%d", type);
317 status_t err = outTable->addBag(sourcePos, myPackage,
318 attr16, ident, String16(""),
319 String16("^type"),
320 String16(numberStr), NULL, NULL);
321 if (err != NO_ERROR) {
322 hasErrors = true;
323 return err;
324 }
325 outTable->appendComment(myPackage, attr16, ident, comment, appendComment);
326 //printf("Attribute %s comment: %s\n", String8(ident).string(),
327 // String8(comment).string());
328 return err;
329 }
330};
331
332static status_t compileAttribute(const sp<AaptFile>& in,
333 ResXMLTree& block,
334 const String16& myPackage,
335 ResourceTable* outTable,
336 String16* outIdent = NULL,
337 bool inStyleable = false)
338{
339 PendingAttribute attr(myPackage, in, block, inStyleable);
340
341 const String16 attr16("attr");
342 const String16 id16("id");
343
344 // Attribute type constants.
345 const String16 enum16("enum");
346 const String16 flag16("flag");
347
348 ResXMLTree::event_code_t code;
349 size_t len;
350 status_t err;
351
352 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
353 if (identIdx >= 0) {
354 attr.ident = String16(block.getAttributeStringValue(identIdx, &len));
355 if (outIdent) {
356 *outIdent = attr.ident;
357 }
358 } else {
359 attr.sourcePos.error("A 'name' attribute is required for <attr>\n");
360 attr.hasErrors = true;
361 }
362
363 attr.comment = String16(
364 block.getComment(&len) ? block.getComment(&len) : nulStr);
365
366 ssize_t typeIdx = block.indexOfAttribute(NULL, "format");
367 if (typeIdx >= 0) {
368 String16 typeStr = String16(block.getAttributeStringValue(typeIdx, &len));
369 attr.type = parse_flags(typeStr.string(), typeStr.size(), gFormatFlags);
370 if (attr.type == 0) {
371 attr.sourcePos.error("Tag <attr> 'format' attribute value \"%s\" not valid\n",
372 String8(typeStr).string());
373 attr.hasErrors = true;
374 }
375 attr.createIfNeeded(outTable);
376 } else if (!inStyleable) {
377 // Attribute definitions outside of styleables always define the
378 // attribute as a generic value.
379 attr.createIfNeeded(outTable);
380 }
381
382 //printf("Attribute %s: type=0x%08x\n", String8(attr.ident).string(), attr.type);
383
384 ssize_t minIdx = block.indexOfAttribute(NULL, "min");
385 if (minIdx >= 0) {
386 String16 val = String16(block.getAttributeStringValue(minIdx, &len));
387 if (!ResTable::stringToInt(val.string(), val.size(), NULL)) {
388 attr.sourcePos.error("Tag <attr> 'min' attribute must be a number, not \"%s\"\n",
389 String8(val).string());
390 attr.hasErrors = true;
391 }
392 attr.createIfNeeded(outTable);
393 if (!attr.hasErrors) {
394 err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
395 String16(""), String16("^min"), String16(val), NULL, NULL);
396 if (err != NO_ERROR) {
397 attr.hasErrors = true;
398 }
399 }
400 }
401
402 ssize_t maxIdx = block.indexOfAttribute(NULL, "max");
403 if (maxIdx >= 0) {
404 String16 val = String16(block.getAttributeStringValue(maxIdx, &len));
405 if (!ResTable::stringToInt(val.string(), val.size(), NULL)) {
406 attr.sourcePos.error("Tag <attr> 'max' attribute must be a number, not \"%s\"\n",
407 String8(val).string());
408 attr.hasErrors = true;
409 }
410 attr.createIfNeeded(outTable);
411 if (!attr.hasErrors) {
412 err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
413 String16(""), String16("^max"), String16(val), NULL, NULL);
414 attr.hasErrors = true;
415 }
416 }
417
418 if ((minIdx >= 0 || maxIdx >= 0) && (attr.type&ResTable_map::TYPE_INTEGER) == 0) {
419 attr.sourcePos.error("Tag <attr> must have format=integer attribute if using max or min\n");
420 attr.hasErrors = true;
421 }
422
423 ssize_t l10nIdx = block.indexOfAttribute(NULL, "localization");
424 if (l10nIdx >= 0) {
Dan Albertf348c152014-09-08 18:28:00 -0700425 const char16_t* str = block.getAttributeStringValue(l10nIdx, &len);
Adam Lesinski282e1812014-01-23 18:17:42 -0800426 bool error;
427 uint32_t l10n_required = parse_flags(str, len, l10nRequiredFlags, &error);
428 if (error) {
429 attr.sourcePos.error("Tag <attr> 'localization' attribute value \"%s\" not valid\n",
430 String8(str).string());
431 attr.hasErrors = true;
432 }
433 attr.createIfNeeded(outTable);
434 if (!attr.hasErrors) {
435 char buf[11];
436 sprintf(buf, "%d", l10n_required);
437 err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
438 String16(""), String16("^l10n"), String16(buf), NULL, NULL);
439 if (err != NO_ERROR) {
440 attr.hasErrors = true;
441 }
442 }
443 }
444
445 String16 enumOrFlagsComment;
446
447 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
448 if (code == ResXMLTree::START_TAG) {
449 uint32_t localType = 0;
450 if (strcmp16(block.getElementName(&len), enum16.string()) == 0) {
451 localType = ResTable_map::TYPE_ENUM;
452 } else if (strcmp16(block.getElementName(&len), flag16.string()) == 0) {
453 localType = ResTable_map::TYPE_FLAGS;
454 } else {
455 SourcePos(in->getPrintableSource(), block.getLineNumber())
456 .error("Tag <%s> can not appear inside <attr>, only <enum> or <flag>\n",
457 String8(block.getElementName(&len)).string());
458 return UNKNOWN_ERROR;
459 }
460
461 attr.createIfNeeded(outTable);
462
463 if (attr.type == ResTable_map::TYPE_ANY) {
464 // No type was explicitly stated, so supplying enum tags
465 // implicitly creates an enum or flag.
466 attr.type = 0;
467 }
468
469 if ((attr.type&(ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS)) == 0) {
470 // Wasn't originally specified as an enum, so update its type.
471 attr.type |= localType;
472 if (!attr.hasErrors) {
473 char numberStr[16];
474 sprintf(numberStr, "%d", attr.type);
475 err = outTable->addBag(SourcePos(in->getPrintableSource(), block.getLineNumber()),
476 myPackage, attr16, attr.ident, String16(""),
477 String16("^type"), String16(numberStr), NULL, NULL, true);
478 if (err != NO_ERROR) {
479 attr.hasErrors = true;
480 }
481 }
482 } else if ((uint32_t)(attr.type&(ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS)) != localType) {
483 if (localType == ResTable_map::TYPE_ENUM) {
484 SourcePos(in->getPrintableSource(), block.getLineNumber())
485 .error("<enum> attribute can not be used inside a flags format\n");
486 attr.hasErrors = true;
487 } else {
488 SourcePos(in->getPrintableSource(), block.getLineNumber())
489 .error("<flag> attribute can not be used inside a enum format\n");
490 attr.hasErrors = true;
491 }
492 }
493
494 String16 itemIdent;
495 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "name");
496 if (itemIdentIdx >= 0) {
497 itemIdent = String16(block.getAttributeStringValue(itemIdentIdx, &len));
498 } else {
499 SourcePos(in->getPrintableSource(), block.getLineNumber())
500 .error("A 'name' attribute is required for <enum> or <flag>\n");
501 attr.hasErrors = true;
502 }
503
504 String16 value;
505 ssize_t valueIdx = block.indexOfAttribute(NULL, "value");
506 if (valueIdx >= 0) {
507 value = String16(block.getAttributeStringValue(valueIdx, &len));
508 } else {
509 SourcePos(in->getPrintableSource(), block.getLineNumber())
510 .error("A 'value' attribute is required for <enum> or <flag>\n");
511 attr.hasErrors = true;
512 }
513 if (!attr.hasErrors && !ResTable::stringToInt(value.string(), value.size(), NULL)) {
514 SourcePos(in->getPrintableSource(), block.getLineNumber())
515 .error("Tag <enum> or <flag> 'value' attribute must be a number,"
516 " not \"%s\"\n",
517 String8(value).string());
518 attr.hasErrors = true;
519 }
520
Adam Lesinski282e1812014-01-23 18:17:42 -0800521 if (!attr.hasErrors) {
522 if (enumOrFlagsComment.size() == 0) {
523 enumOrFlagsComment.append(mayOrMust(attr.type,
524 ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS));
525 enumOrFlagsComment.append((attr.type&ResTable_map::TYPE_ENUM)
526 ? String16(" be one of the following constant values.")
527 : String16(" be one or more (separated by '|') of the following constant values."));
528 enumOrFlagsComment.append(String16("</p>\n<table>\n"
529 "<colgroup align=\"left\" />\n"
530 "<colgroup align=\"left\" />\n"
531 "<colgroup align=\"left\" />\n"
532 "<tr><th>Constant</th><th>Value</th><th>Description</th></tr>"));
533 }
534
535 enumOrFlagsComment.append(String16("\n<tr><td><code>"));
536 enumOrFlagsComment.append(itemIdent);
537 enumOrFlagsComment.append(String16("</code></td><td>"));
538 enumOrFlagsComment.append(value);
539 enumOrFlagsComment.append(String16("</td><td>"));
540 if (block.getComment(&len)) {
541 enumOrFlagsComment.append(String16(block.getComment(&len)));
542 }
543 enumOrFlagsComment.append(String16("</td></tr>"));
544
545 err = outTable->addBag(SourcePos(in->getPrintableSource(), block.getLineNumber()),
546 myPackage,
547 attr16, attr.ident, String16(""),
548 itemIdent, value, NULL, NULL, false, true);
549 if (err != NO_ERROR) {
550 attr.hasErrors = true;
551 }
552 }
553 } else if (code == ResXMLTree::END_TAG) {
554 if (strcmp16(block.getElementName(&len), attr16.string()) == 0) {
555 break;
556 }
557 if ((attr.type&ResTable_map::TYPE_ENUM) != 0) {
558 if (strcmp16(block.getElementName(&len), enum16.string()) != 0) {
559 SourcePos(in->getPrintableSource(), block.getLineNumber())
560 .error("Found tag </%s> where </enum> is expected\n",
561 String8(block.getElementName(&len)).string());
562 return UNKNOWN_ERROR;
563 }
564 } else {
565 if (strcmp16(block.getElementName(&len), flag16.string()) != 0) {
566 SourcePos(in->getPrintableSource(), block.getLineNumber())
567 .error("Found tag </%s> where </flag> is expected\n",
568 String8(block.getElementName(&len)).string());
569 return UNKNOWN_ERROR;
570 }
571 }
572 }
573 }
574
575 if (!attr.hasErrors && attr.added) {
576 appendTypeInfo(outTable, myPackage, attr16, attr.ident, attr.type, gFormatFlags);
577 }
578
579 if (!attr.hasErrors && enumOrFlagsComment.size() > 0) {
580 enumOrFlagsComment.append(String16("\n</table>"));
581 outTable->appendTypeComment(myPackage, attr16, attr.ident, enumOrFlagsComment);
582 }
583
584
585 return NO_ERROR;
586}
587
588bool localeIsDefined(const ResTable_config& config)
589{
590 return config.locale == 0;
591}
592
593status_t parseAndAddBag(Bundle* bundle,
594 const sp<AaptFile>& in,
595 ResXMLTree* block,
596 const ResTable_config& config,
597 const String16& myPackage,
598 const String16& curType,
599 const String16& ident,
600 const String16& parentIdent,
601 const String16& itemIdent,
602 int32_t curFormat,
603 bool isFormatted,
Andreas Gampe2412f842014-09-30 20:55:57 -0700604 const String16& /* product */,
Anton Krumina2ef5c02014-03-12 14:46:44 -0700605 PseudolocalizationMethod pseudolocalize,
Adam Lesinski282e1812014-01-23 18:17:42 -0800606 const bool overwrite,
607 ResourceTable* outTable)
608{
609 status_t err;
610 const String16 item16("item");
Anton Krumina2ef5c02014-03-12 14:46:44 -0700611
Adam Lesinski282e1812014-01-23 18:17:42 -0800612 String16 str;
613 Vector<StringPool::entry_style_span> spans;
614 err = parseStyledString(bundle, in->getPrintableSource().string(),
615 block, item16, &str, &spans, isFormatted,
616 pseudolocalize);
617 if (err != NO_ERROR) {
618 return err;
619 }
Andreas Gampe2412f842014-09-30 20:55:57 -0700620
621 if (kIsDebug) {
622 printf("Adding resource bag entry l=%c%c c=%c%c orien=%d d=%d "
623 " pid=%s, bag=%s, id=%s: %s\n",
624 config.language[0], config.language[1],
625 config.country[0], config.country[1],
626 config.orientation, config.density,
627 String8(parentIdent).string(),
628 String8(ident).string(),
629 String8(itemIdent).string(),
630 String8(str).string());
631 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800632
633 err = outTable->addBag(SourcePos(in->getPrintableSource(), block->getLineNumber()),
634 myPackage, curType, ident, parentIdent, itemIdent, str,
635 &spans, &config, overwrite, false, curFormat);
636 return err;
637}
638
639/*
640 * Returns true if needle is one of the elements in the comma-separated list
641 * haystack, false otherwise.
642 */
643bool isInProductList(const String16& needle, const String16& haystack) {
644 const char16_t *needle2 = needle.string();
645 const char16_t *haystack2 = haystack.string();
646 size_t needlesize = needle.size();
647
648 while (*haystack2 != '\0') {
649 if (strncmp16(haystack2, needle2, needlesize) == 0) {
650 if (haystack2[needlesize] == '\0' || haystack2[needlesize] == ',') {
651 return true;
652 }
653 }
654
655 while (*haystack2 != '\0' && *haystack2 != ',') {
656 haystack2++;
657 }
658 if (*haystack2 == ',') {
659 haystack2++;
660 }
661 }
662
663 return false;
664}
665
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700666/*
667 * A simple container that holds a resource type and name. It is ordered first by type then
668 * by name.
669 */
670struct type_ident_pair_t {
671 String16 type;
672 String16 ident;
673
674 type_ident_pair_t() { };
675 type_ident_pair_t(const String16& t, const String16& i) : type(t), ident(i) { }
676 type_ident_pair_t(const type_ident_pair_t& o) : type(o.type), ident(o.ident) { }
677 inline bool operator < (const type_ident_pair_t& o) const {
678 int cmp = compare_type(type, o.type);
679 if (cmp < 0) {
680 return true;
681 } else if (cmp > 0) {
682 return false;
683 } else {
684 return strictly_order_type(ident, o.ident);
685 }
686 }
687};
688
689
Adam Lesinski282e1812014-01-23 18:17:42 -0800690status_t parseAndAddEntry(Bundle* bundle,
691 const sp<AaptFile>& in,
692 ResXMLTree* block,
693 const ResTable_config& config,
694 const String16& myPackage,
695 const String16& curType,
696 const String16& ident,
697 const String16& curTag,
698 bool curIsStyled,
699 int32_t curFormat,
700 bool isFormatted,
701 const String16& product,
Anton Krumina2ef5c02014-03-12 14:46:44 -0700702 PseudolocalizationMethod pseudolocalize,
Adam Lesinski282e1812014-01-23 18:17:42 -0800703 const bool overwrite,
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700704 KeyedVector<type_ident_pair_t, bool>* skippedResourceNames,
Adam Lesinski282e1812014-01-23 18:17:42 -0800705 ResourceTable* outTable)
706{
707 status_t err;
708
709 String16 str;
710 Vector<StringPool::entry_style_span> spans;
711 err = parseStyledString(bundle, in->getPrintableSource().string(), block,
712 curTag, &str, curIsStyled ? &spans : NULL,
713 isFormatted, pseudolocalize);
714
715 if (err < NO_ERROR) {
716 return err;
717 }
718
719 /*
720 * If a product type was specified on the command line
721 * and also in the string, and the two are not the same,
722 * return without adding the string.
723 */
724
725 const char *bundleProduct = bundle->getProduct();
726 if (bundleProduct == NULL) {
727 bundleProduct = "";
728 }
729
730 if (product.size() != 0) {
731 /*
732 * If the command-line-specified product is empty, only "default"
733 * matches. Other variants are skipped. This is so generation
734 * of the R.java file when the product is not known is predictable.
735 */
736
737 if (bundleProduct[0] == '\0') {
738 if (strcmp16(String16("default").string(), product.string()) != 0) {
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700739 /*
740 * This string has a product other than 'default'. Do not add it,
741 * but record it so that if we do not see the same string with
742 * product 'default' or no product, then report an error.
743 */
744 skippedResourceNames->replaceValueFor(
745 type_ident_pair_t(curType, ident), true);
Adam Lesinski282e1812014-01-23 18:17:42 -0800746 return NO_ERROR;
747 }
748 } else {
749 /*
750 * The command-line product is not empty.
751 * If the product for this string is on the command-line list,
752 * it matches. "default" also matches, but only if nothing
753 * else has matched already.
754 */
755
756 if (isInProductList(product, String16(bundleProduct))) {
757 ;
758 } else if (strcmp16(String16("default").string(), product.string()) == 0 &&
759 !outTable->hasBagOrEntry(myPackage, curType, ident, config)) {
760 ;
761 } else {
762 return NO_ERROR;
763 }
764 }
765 }
766
Andreas Gampe2412f842014-09-30 20:55:57 -0700767 if (kIsDebug) {
768 printf("Adding resource entry l=%c%c c=%c%c orien=%d d=%d id=%s: %s\n",
769 config.language[0], config.language[1],
770 config.country[0], config.country[1],
771 config.orientation, config.density,
772 String8(ident).string(), String8(str).string());
773 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800774
775 err = outTable->addEntry(SourcePos(in->getPrintableSource(), block->getLineNumber()),
776 myPackage, curType, ident, str, &spans, &config,
777 false, curFormat, overwrite);
778
779 return err;
780}
781
782status_t compileResourceFile(Bundle* bundle,
783 const sp<AaptAssets>& assets,
784 const sp<AaptFile>& in,
785 const ResTable_config& defParams,
786 const bool overwrite,
787 ResourceTable* outTable)
788{
789 ResXMLTree block;
790 status_t err = parseXMLResource(in, &block, false, true);
791 if (err != NO_ERROR) {
792 return err;
793 }
794
795 // Top-level tag.
796 const String16 resources16("resources");
797
798 // Identifier declaration tags.
799 const String16 declare_styleable16("declare-styleable");
800 const String16 attr16("attr");
801
802 // Data creation organizational tags.
803 const String16 string16("string");
804 const String16 drawable16("drawable");
805 const String16 color16("color");
806 const String16 bool16("bool");
807 const String16 integer16("integer");
808 const String16 dimen16("dimen");
809 const String16 fraction16("fraction");
810 const String16 style16("style");
811 const String16 plurals16("plurals");
812 const String16 array16("array");
813 const String16 string_array16("string-array");
814 const String16 integer_array16("integer-array");
815 const String16 public16("public");
816 const String16 public_padding16("public-padding");
817 const String16 private_symbols16("private-symbols");
818 const String16 java_symbol16("java-symbol");
819 const String16 add_resource16("add-resource");
820 const String16 skip16("skip");
821 const String16 eat_comment16("eat-comment");
822
823 // Data creation tags.
824 const String16 bag16("bag");
825 const String16 item16("item");
826
827 // Attribute type constants.
828 const String16 enum16("enum");
829
830 // plural values
831 const String16 other16("other");
832 const String16 quantityOther16("^other");
833 const String16 zero16("zero");
834 const String16 quantityZero16("^zero");
835 const String16 one16("one");
836 const String16 quantityOne16("^one");
837 const String16 two16("two");
838 const String16 quantityTwo16("^two");
839 const String16 few16("few");
840 const String16 quantityFew16("^few");
841 const String16 many16("many");
842 const String16 quantityMany16("^many");
843
844 // useful attribute names and special values
845 const String16 name16("name");
846 const String16 translatable16("translatable");
847 const String16 formatted16("formatted");
848 const String16 false16("false");
849
850 const String16 myPackage(assets->getPackage());
851
852 bool hasErrors = false;
853
854 bool fileIsTranslatable = true;
855 if (strstr(in->getPrintableSource().string(), "donottranslate") != NULL) {
856 fileIsTranslatable = false;
857 }
858
859 DefaultKeyedVector<String16, uint32_t> nextPublicId(0);
860
Adam Lesinski8ff15b42013-10-07 16:54:01 -0700861 // Stores the resource names that were skipped. Typically this happens when
862 // AAPT is invoked without a product specified and a resource has no
863 // 'default' product attribute.
864 KeyedVector<type_ident_pair_t, bool> skippedResourceNames;
865
Adam Lesinski282e1812014-01-23 18:17:42 -0800866 ResXMLTree::event_code_t code;
867 do {
868 code = block.next();
869 } while (code == ResXMLTree::START_NAMESPACE);
870
871 size_t len;
872 if (code != ResXMLTree::START_TAG) {
873 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
874 "No start tag found\n");
875 return UNKNOWN_ERROR;
876 }
877 if (strcmp16(block.getElementName(&len), resources16.string()) != 0) {
878 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
879 "Invalid start tag %s\n", String8(block.getElementName(&len)).string());
880 return UNKNOWN_ERROR;
881 }
882
883 ResTable_config curParams(defParams);
884
885 ResTable_config pseudoParams(curParams);
Anton Krumina2ef5c02014-03-12 14:46:44 -0700886 pseudoParams.language[0] = 'e';
887 pseudoParams.language[1] = 'n';
888 pseudoParams.country[0] = 'X';
889 pseudoParams.country[1] = 'A';
890
891 ResTable_config pseudoBidiParams(curParams);
892 pseudoBidiParams.language[0] = 'a';
893 pseudoBidiParams.language[1] = 'r';
894 pseudoBidiParams.country[0] = 'X';
895 pseudoBidiParams.country[1] = 'B';
Adam Lesinski282e1812014-01-23 18:17:42 -0800896
Igor Viarheichyk47843df12014-05-01 17:04:39 -0700897 // We should skip resources for pseudolocales if they were
898 // already added automatically. This is a fix for a transition period when
899 // manually pseudolocalized resources may be expected.
900 // TODO: remove this check after next SDK version release.
901 if ((bundle->getPseudolocalize() & PSEUDO_ACCENTED &&
902 curParams.locale == pseudoParams.locale) ||
903 (bundle->getPseudolocalize() & PSEUDO_BIDI &&
904 curParams.locale == pseudoBidiParams.locale)) {
905 SourcePos(in->getPrintableSource(), 0).warning(
906 "Resource file %s is skipped as pseudolocalization"
907 " was done automatically.",
908 in->getPrintableSource().string());
909 return NO_ERROR;
910 }
911
Adam Lesinski282e1812014-01-23 18:17:42 -0800912 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
913 if (code == ResXMLTree::START_TAG) {
914 const String16* curTag = NULL;
915 String16 curType;
916 int32_t curFormat = ResTable_map::TYPE_ANY;
917 bool curIsBag = false;
918 bool curIsBagReplaceOnOverwrite = false;
919 bool curIsStyled = false;
920 bool curIsPseudolocalizable = false;
921 bool curIsFormatted = fileIsTranslatable;
922 bool localHasErrors = false;
923
924 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
925 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
926 && code != ResXMLTree::BAD_DOCUMENT) {
927 if (code == ResXMLTree::END_TAG) {
928 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
929 break;
930 }
931 }
932 }
933 continue;
934
935 } else if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
936 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
937 && code != ResXMLTree::BAD_DOCUMENT) {
938 if (code == ResXMLTree::END_TAG) {
939 if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
940 break;
941 }
942 }
943 }
944 continue;
945
946 } else if (strcmp16(block.getElementName(&len), public16.string()) == 0) {
947 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
948
949 String16 type;
950 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
951 if (typeIdx < 0) {
952 srcPos.error("A 'type' attribute is required for <public>\n");
953 hasErrors = localHasErrors = true;
954 }
955 type = String16(block.getAttributeStringValue(typeIdx, &len));
956
957 String16 name;
958 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
959 if (nameIdx < 0) {
960 srcPos.error("A 'name' attribute is required for <public>\n");
961 hasErrors = localHasErrors = true;
962 }
963 name = String16(block.getAttributeStringValue(nameIdx, &len));
964
965 uint32_t ident = 0;
966 ssize_t identIdx = block.indexOfAttribute(NULL, "id");
967 if (identIdx >= 0) {
968 const char16_t* identStr = block.getAttributeStringValue(identIdx, &len);
969 Res_value identValue;
970 if (!ResTable::stringToInt(identStr, len, &identValue)) {
971 srcPos.error("Given 'id' attribute is not an integer: %s\n",
972 String8(block.getAttributeStringValue(identIdx, &len)).string());
973 hasErrors = localHasErrors = true;
974 } else {
975 ident = identValue.data;
976 nextPublicId.replaceValueFor(type, ident+1);
977 }
978 } else if (nextPublicId.indexOfKey(type) < 0) {
979 srcPos.error("No 'id' attribute supplied <public>,"
980 " and no previous id defined in this file.\n");
981 hasErrors = localHasErrors = true;
982 } else if (!localHasErrors) {
983 ident = nextPublicId.valueFor(type);
984 nextPublicId.replaceValueFor(type, ident+1);
985 }
986
987 if (!localHasErrors) {
988 err = outTable->addPublic(srcPos, myPackage, type, name, ident);
989 if (err < NO_ERROR) {
990 hasErrors = localHasErrors = true;
991 }
992 }
993 if (!localHasErrors) {
994 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
995 if (symbols != NULL) {
996 symbols = symbols->addNestedSymbol(String8(type), srcPos);
997 }
998 if (symbols != NULL) {
999 symbols->makeSymbolPublic(String8(name), srcPos);
1000 String16 comment(
1001 block.getComment(&len) ? block.getComment(&len) : nulStr);
1002 symbols->appendComment(String8(name), comment, srcPos);
1003 } else {
1004 srcPos.error("Unable to create symbols!\n");
1005 hasErrors = localHasErrors = true;
1006 }
1007 }
1008
1009 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1010 if (code == ResXMLTree::END_TAG) {
1011 if (strcmp16(block.getElementName(&len), public16.string()) == 0) {
1012 break;
1013 }
1014 }
1015 }
1016 continue;
1017
1018 } else if (strcmp16(block.getElementName(&len), public_padding16.string()) == 0) {
1019 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1020
1021 String16 type;
1022 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
1023 if (typeIdx < 0) {
1024 srcPos.error("A 'type' attribute is required for <public-padding>\n");
1025 hasErrors = localHasErrors = true;
1026 }
1027 type = String16(block.getAttributeStringValue(typeIdx, &len));
1028
1029 String16 name;
1030 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1031 if (nameIdx < 0) {
1032 srcPos.error("A 'name' attribute is required for <public-padding>\n");
1033 hasErrors = localHasErrors = true;
1034 }
1035 name = String16(block.getAttributeStringValue(nameIdx, &len));
1036
1037 uint32_t start = 0;
1038 ssize_t startIdx = block.indexOfAttribute(NULL, "start");
1039 if (startIdx >= 0) {
1040 const char16_t* startStr = block.getAttributeStringValue(startIdx, &len);
1041 Res_value startValue;
1042 if (!ResTable::stringToInt(startStr, len, &startValue)) {
1043 srcPos.error("Given 'start' attribute is not an integer: %s\n",
1044 String8(block.getAttributeStringValue(startIdx, &len)).string());
1045 hasErrors = localHasErrors = true;
1046 } else {
1047 start = startValue.data;
1048 }
1049 } else if (nextPublicId.indexOfKey(type) < 0) {
1050 srcPos.error("No 'start' attribute supplied <public-padding>,"
1051 " and no previous id defined in this file.\n");
1052 hasErrors = localHasErrors = true;
1053 } else if (!localHasErrors) {
1054 start = nextPublicId.valueFor(type);
1055 }
1056
1057 uint32_t end = 0;
1058 ssize_t endIdx = block.indexOfAttribute(NULL, "end");
1059 if (endIdx >= 0) {
1060 const char16_t* endStr = block.getAttributeStringValue(endIdx, &len);
1061 Res_value endValue;
1062 if (!ResTable::stringToInt(endStr, len, &endValue)) {
1063 srcPos.error("Given 'end' attribute is not an integer: %s\n",
1064 String8(block.getAttributeStringValue(endIdx, &len)).string());
1065 hasErrors = localHasErrors = true;
1066 } else {
1067 end = endValue.data;
1068 }
1069 } else {
1070 srcPos.error("No 'end' attribute supplied <public-padding>\n");
1071 hasErrors = localHasErrors = true;
1072 }
1073
1074 if (end >= start) {
1075 nextPublicId.replaceValueFor(type, end+1);
1076 } else {
1077 srcPos.error("Padding start '%ul' is after end '%ul'\n",
1078 start, end);
1079 hasErrors = localHasErrors = true;
1080 }
1081
1082 String16 comment(
1083 block.getComment(&len) ? block.getComment(&len) : nulStr);
1084 for (uint32_t curIdent=start; curIdent<=end; curIdent++) {
1085 if (localHasErrors) {
1086 break;
1087 }
1088 String16 curName(name);
1089 char buf[64];
1090 sprintf(buf, "%d", (int)(end-curIdent+1));
1091 curName.append(String16(buf));
1092
1093 err = outTable->addEntry(srcPos, myPackage, type, curName,
1094 String16("padding"), NULL, &curParams, false,
1095 ResTable_map::TYPE_STRING, overwrite);
1096 if (err < NO_ERROR) {
1097 hasErrors = localHasErrors = true;
1098 break;
1099 }
1100 err = outTable->addPublic(srcPos, myPackage, type,
1101 curName, curIdent);
1102 if (err < NO_ERROR) {
1103 hasErrors = localHasErrors = true;
1104 break;
1105 }
1106 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1107 if (symbols != NULL) {
1108 symbols = symbols->addNestedSymbol(String8(type), srcPos);
1109 }
1110 if (symbols != NULL) {
1111 symbols->makeSymbolPublic(String8(curName), srcPos);
1112 symbols->appendComment(String8(curName), comment, srcPos);
1113 } else {
1114 srcPos.error("Unable to create symbols!\n");
1115 hasErrors = localHasErrors = true;
1116 }
1117 }
1118
1119 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1120 if (code == ResXMLTree::END_TAG) {
1121 if (strcmp16(block.getElementName(&len), public_padding16.string()) == 0) {
1122 break;
1123 }
1124 }
1125 }
1126 continue;
1127
1128 } else if (strcmp16(block.getElementName(&len), private_symbols16.string()) == 0) {
1129 String16 pkg;
1130 ssize_t pkgIdx = block.indexOfAttribute(NULL, "package");
1131 if (pkgIdx < 0) {
1132 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1133 "A 'package' attribute is required for <private-symbols>\n");
1134 hasErrors = localHasErrors = true;
1135 }
1136 pkg = String16(block.getAttributeStringValue(pkgIdx, &len));
1137 if (!localHasErrors) {
1138 assets->setSymbolsPrivatePackage(String8(pkg));
1139 }
1140
1141 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1142 if (code == ResXMLTree::END_TAG) {
1143 if (strcmp16(block.getElementName(&len), private_symbols16.string()) == 0) {
1144 break;
1145 }
1146 }
1147 }
1148 continue;
1149
1150 } else if (strcmp16(block.getElementName(&len), java_symbol16.string()) == 0) {
1151 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1152
1153 String16 type;
1154 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
1155 if (typeIdx < 0) {
1156 srcPos.error("A 'type' attribute is required for <public>\n");
1157 hasErrors = localHasErrors = true;
1158 }
1159 type = String16(block.getAttributeStringValue(typeIdx, &len));
1160
1161 String16 name;
1162 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1163 if (nameIdx < 0) {
1164 srcPos.error("A 'name' attribute is required for <public>\n");
1165 hasErrors = localHasErrors = true;
1166 }
1167 name = String16(block.getAttributeStringValue(nameIdx, &len));
1168
1169 sp<AaptSymbols> symbols = assets->getJavaSymbolsFor(String8("R"));
1170 if (symbols != NULL) {
1171 symbols = symbols->addNestedSymbol(String8(type), srcPos);
1172 }
1173 if (symbols != NULL) {
1174 symbols->makeSymbolJavaSymbol(String8(name), srcPos);
1175 String16 comment(
1176 block.getComment(&len) ? block.getComment(&len) : nulStr);
1177 symbols->appendComment(String8(name), comment, srcPos);
1178 } else {
1179 srcPos.error("Unable to create symbols!\n");
1180 hasErrors = localHasErrors = true;
1181 }
1182
1183 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1184 if (code == ResXMLTree::END_TAG) {
1185 if (strcmp16(block.getElementName(&len), java_symbol16.string()) == 0) {
1186 break;
1187 }
1188 }
1189 }
1190 continue;
1191
1192
1193 } else if (strcmp16(block.getElementName(&len), add_resource16.string()) == 0) {
1194 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1195
1196 String16 typeName;
1197 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
1198 if (typeIdx < 0) {
1199 srcPos.error("A 'type' attribute is required for <add-resource>\n");
1200 hasErrors = localHasErrors = true;
1201 }
1202 typeName = String16(block.getAttributeStringValue(typeIdx, &len));
1203
1204 String16 name;
1205 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1206 if (nameIdx < 0) {
1207 srcPos.error("A 'name' attribute is required for <add-resource>\n");
1208 hasErrors = localHasErrors = true;
1209 }
1210 name = String16(block.getAttributeStringValue(nameIdx, &len));
1211
1212 outTable->canAddEntry(srcPos, myPackage, typeName, name);
1213
1214 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1215 if (code == ResXMLTree::END_TAG) {
1216 if (strcmp16(block.getElementName(&len), add_resource16.string()) == 0) {
1217 break;
1218 }
1219 }
1220 }
1221 continue;
1222
1223 } else if (strcmp16(block.getElementName(&len), declare_styleable16.string()) == 0) {
1224 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1225
1226 String16 ident;
1227 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
1228 if (identIdx < 0) {
1229 srcPos.error("A 'name' attribute is required for <declare-styleable>\n");
1230 hasErrors = localHasErrors = true;
1231 }
1232 ident = String16(block.getAttributeStringValue(identIdx, &len));
1233
1234 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1235 if (!localHasErrors) {
1236 if (symbols != NULL) {
1237 symbols = symbols->addNestedSymbol(String8("styleable"), srcPos);
1238 }
1239 sp<AaptSymbols> styleSymbols = symbols;
1240 if (symbols != NULL) {
1241 symbols = symbols->addNestedSymbol(String8(ident), srcPos);
1242 }
1243 if (symbols == NULL) {
1244 srcPos.error("Unable to create symbols!\n");
1245 return UNKNOWN_ERROR;
1246 }
1247
1248 String16 comment(
1249 block.getComment(&len) ? block.getComment(&len) : nulStr);
1250 styleSymbols->appendComment(String8(ident), comment, srcPos);
1251 } else {
1252 symbols = NULL;
1253 }
1254
1255 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1256 if (code == ResXMLTree::START_TAG) {
1257 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
1258 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1259 && code != ResXMLTree::BAD_DOCUMENT) {
1260 if (code == ResXMLTree::END_TAG) {
1261 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
1262 break;
1263 }
1264 }
1265 }
1266 continue;
1267 } else if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
1268 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1269 && code != ResXMLTree::BAD_DOCUMENT) {
1270 if (code == ResXMLTree::END_TAG) {
1271 if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
1272 break;
1273 }
1274 }
1275 }
1276 continue;
1277 } else if (strcmp16(block.getElementName(&len), attr16.string()) != 0) {
1278 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1279 "Tag <%s> can not appear inside <declare-styleable>, only <attr>\n",
1280 String8(block.getElementName(&len)).string());
1281 return UNKNOWN_ERROR;
1282 }
1283
1284 String16 comment(
1285 block.getComment(&len) ? block.getComment(&len) : nulStr);
1286 String16 itemIdent;
1287 err = compileAttribute(in, block, myPackage, outTable, &itemIdent, true);
1288 if (err != NO_ERROR) {
1289 hasErrors = localHasErrors = true;
1290 }
1291
1292 if (symbols != NULL) {
1293 SourcePos srcPos(String8(in->getPrintableSource()), block.getLineNumber());
1294 symbols->addSymbol(String8(itemIdent), 0, srcPos);
1295 symbols->appendComment(String8(itemIdent), comment, srcPos);
1296 //printf("Attribute %s comment: %s\n", String8(itemIdent).string(),
1297 // String8(comment).string());
1298 }
1299 } else if (code == ResXMLTree::END_TAG) {
1300 if (strcmp16(block.getElementName(&len), declare_styleable16.string()) == 0) {
1301 break;
1302 }
1303
1304 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1305 "Found tag </%s> where </attr> is expected\n",
1306 String8(block.getElementName(&len)).string());
1307 return UNKNOWN_ERROR;
1308 }
1309 }
1310 continue;
1311
1312 } else if (strcmp16(block.getElementName(&len), attr16.string()) == 0) {
1313 err = compileAttribute(in, block, myPackage, outTable, NULL);
1314 if (err != NO_ERROR) {
1315 hasErrors = true;
1316 }
1317 continue;
1318
1319 } else if (strcmp16(block.getElementName(&len), item16.string()) == 0) {
1320 curTag = &item16;
1321 ssize_t attri = block.indexOfAttribute(NULL, "type");
1322 if (attri >= 0) {
1323 curType = String16(block.getAttributeStringValue(attri, &len));
1324 ssize_t formatIdx = block.indexOfAttribute(NULL, "format");
1325 if (formatIdx >= 0) {
1326 String16 formatStr = String16(block.getAttributeStringValue(
1327 formatIdx, &len));
1328 curFormat = parse_flags(formatStr.string(), formatStr.size(),
1329 gFormatFlags);
1330 if (curFormat == 0) {
1331 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1332 "Tag <item> 'format' attribute value \"%s\" not valid\n",
1333 String8(formatStr).string());
1334 hasErrors = localHasErrors = true;
1335 }
1336 }
1337 } else {
1338 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1339 "A 'type' attribute is required for <item>\n");
1340 hasErrors = localHasErrors = true;
1341 }
1342 curIsStyled = true;
1343 } else if (strcmp16(block.getElementName(&len), string16.string()) == 0) {
1344 // Note the existence and locale of every string we process
Narayan Kamath91447d82014-01-21 15:32:36 +00001345 char rawLocale[RESTABLE_MAX_LOCALE_LEN];
1346 curParams.getBcp47Locale(rawLocale);
Adam Lesinski282e1812014-01-23 18:17:42 -08001347 String8 locale(rawLocale);
1348 String16 name;
1349 String16 translatable;
1350 String16 formatted;
1351
1352 size_t n = block.getAttributeCount();
1353 for (size_t i = 0; i < n; i++) {
1354 size_t length;
Dan Albertf348c152014-09-08 18:28:00 -07001355 const char16_t* attr = block.getAttributeName(i, &length);
Adam Lesinski282e1812014-01-23 18:17:42 -08001356 if (strcmp16(attr, name16.string()) == 0) {
1357 name.setTo(block.getAttributeStringValue(i, &length));
1358 } else if (strcmp16(attr, translatable16.string()) == 0) {
1359 translatable.setTo(block.getAttributeStringValue(i, &length));
1360 } else if (strcmp16(attr, formatted16.string()) == 0) {
1361 formatted.setTo(block.getAttributeStringValue(i, &length));
1362 }
1363 }
1364
1365 if (name.size() > 0) {
1366 if (translatable == false16) {
1367 curIsFormatted = false;
1368 // Untranslatable strings must only exist in the default [empty] locale
1369 if (locale.size() > 0) {
Adam Lesinskia01a9372014-03-20 18:04:57 -07001370 SourcePos(in->getPrintableSource(), block.getLineNumber()).warning(
1371 "string '%s' marked untranslatable but exists in locale '%s'\n",
1372 String8(name).string(),
Adam Lesinski282e1812014-01-23 18:17:42 -08001373 locale.string());
1374 // hasErrors = localHasErrors = true;
1375 } else {
1376 // Intentionally empty block:
1377 //
1378 // Don't add untranslatable strings to the localization table; that
1379 // way if we later see localizations of them, they'll be flagged as
1380 // having no default translation.
1381 }
1382 } else {
Adam Lesinskia01a9372014-03-20 18:04:57 -07001383 outTable->addLocalization(
1384 name,
1385 locale,
1386 SourcePos(in->getPrintableSource(), block.getLineNumber()));
Adam Lesinski282e1812014-01-23 18:17:42 -08001387 }
1388
1389 if (formatted == false16) {
1390 curIsFormatted = false;
1391 }
1392 }
1393
1394 curTag = &string16;
1395 curType = string16;
1396 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
1397 curIsStyled = true;
Igor Viarheichyk84410b02014-04-30 11:56:42 -07001398 curIsPseudolocalizable = fileIsTranslatable && (translatable != false16);
Adam Lesinski282e1812014-01-23 18:17:42 -08001399 } else if (strcmp16(block.getElementName(&len), drawable16.string()) == 0) {
1400 curTag = &drawable16;
1401 curType = drawable16;
1402 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
1403 } else if (strcmp16(block.getElementName(&len), color16.string()) == 0) {
1404 curTag = &color16;
1405 curType = color16;
1406 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
1407 } else if (strcmp16(block.getElementName(&len), bool16.string()) == 0) {
1408 curTag = &bool16;
1409 curType = bool16;
1410 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_BOOLEAN;
1411 } else if (strcmp16(block.getElementName(&len), integer16.string()) == 0) {
1412 curTag = &integer16;
1413 curType = integer16;
1414 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
1415 } else if (strcmp16(block.getElementName(&len), dimen16.string()) == 0) {
1416 curTag = &dimen16;
1417 curType = dimen16;
1418 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_DIMENSION;
1419 } else if (strcmp16(block.getElementName(&len), fraction16.string()) == 0) {
1420 curTag = &fraction16;
1421 curType = fraction16;
1422 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_FRACTION;
1423 } else if (strcmp16(block.getElementName(&len), bag16.string()) == 0) {
1424 curTag = &bag16;
1425 curIsBag = true;
1426 ssize_t attri = block.indexOfAttribute(NULL, "type");
1427 if (attri >= 0) {
1428 curType = String16(block.getAttributeStringValue(attri, &len));
1429 } else {
1430 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1431 "A 'type' attribute is required for <bag>\n");
1432 hasErrors = localHasErrors = true;
1433 }
1434 } else if (strcmp16(block.getElementName(&len), style16.string()) == 0) {
1435 curTag = &style16;
1436 curType = style16;
1437 curIsBag = true;
1438 } else if (strcmp16(block.getElementName(&len), plurals16.string()) == 0) {
1439 curTag = &plurals16;
1440 curType = plurals16;
1441 curIsBag = true;
Anton Krumina2ef5c02014-03-12 14:46:44 -07001442 curIsPseudolocalizable = fileIsTranslatable;
Adam Lesinski282e1812014-01-23 18:17:42 -08001443 } else if (strcmp16(block.getElementName(&len), array16.string()) == 0) {
1444 curTag = &array16;
1445 curType = array16;
1446 curIsBag = true;
1447 curIsBagReplaceOnOverwrite = true;
1448 ssize_t formatIdx = block.indexOfAttribute(NULL, "format");
1449 if (formatIdx >= 0) {
1450 String16 formatStr = String16(block.getAttributeStringValue(
1451 formatIdx, &len));
1452 curFormat = parse_flags(formatStr.string(), formatStr.size(),
1453 gFormatFlags);
1454 if (curFormat == 0) {
1455 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1456 "Tag <array> 'format' attribute value \"%s\" not valid\n",
1457 String8(formatStr).string());
1458 hasErrors = localHasErrors = true;
1459 }
1460 }
1461 } else if (strcmp16(block.getElementName(&len), string_array16.string()) == 0) {
1462 // Check whether these strings need valid formats.
1463 // (simplified form of what string16 does above)
Anton Krumina2ef5c02014-03-12 14:46:44 -07001464 bool isTranslatable = false;
Adam Lesinski282e1812014-01-23 18:17:42 -08001465 size_t n = block.getAttributeCount();
Narayan Kamath9a9fa162013-12-18 13:27:30 +00001466
1467 // Pseudolocalizable by default, unless this string array isn't
1468 // translatable.
Adam Lesinski282e1812014-01-23 18:17:42 -08001469 for (size_t i = 0; i < n; i++) {
1470 size_t length;
Dan Albertf348c152014-09-08 18:28:00 -07001471 const char16_t* attr = block.getAttributeName(i, &length);
Narayan Kamath9a9fa162013-12-18 13:27:30 +00001472 if (strcmp16(attr, formatted16.string()) == 0) {
Dan Albertf348c152014-09-08 18:28:00 -07001473 const char16_t* value = block.getAttributeStringValue(i, &length);
Adam Lesinski282e1812014-01-23 18:17:42 -08001474 if (strcmp16(value, false16.string()) == 0) {
1475 curIsFormatted = false;
Adam Lesinski282e1812014-01-23 18:17:42 -08001476 }
Anton Krumina2ef5c02014-03-12 14:46:44 -07001477 } else if (strcmp16(attr, translatable16.string()) == 0) {
Dan Albertf348c152014-09-08 18:28:00 -07001478 const char16_t* value = block.getAttributeStringValue(i, &length);
Anton Krumina2ef5c02014-03-12 14:46:44 -07001479 if (strcmp16(value, false16.string()) == 0) {
1480 isTranslatable = false;
1481 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001482 }
1483 }
1484
1485 curTag = &string_array16;
1486 curType = array16;
1487 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
1488 curIsBag = true;
1489 curIsBagReplaceOnOverwrite = true;
Anton Krumina2ef5c02014-03-12 14:46:44 -07001490 curIsPseudolocalizable = isTranslatable && fileIsTranslatable;
Adam Lesinski282e1812014-01-23 18:17:42 -08001491 } else if (strcmp16(block.getElementName(&len), integer_array16.string()) == 0) {
1492 curTag = &integer_array16;
1493 curType = array16;
1494 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
1495 curIsBag = true;
1496 curIsBagReplaceOnOverwrite = true;
1497 } else {
1498 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1499 "Found tag %s where item is expected\n",
1500 String8(block.getElementName(&len)).string());
1501 return UNKNOWN_ERROR;
1502 }
1503
1504 String16 ident;
1505 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
1506 if (identIdx >= 0) {
1507 ident = String16(block.getAttributeStringValue(identIdx, &len));
1508 } else {
1509 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1510 "A 'name' attribute is required for <%s>\n",
1511 String8(*curTag).string());
1512 hasErrors = localHasErrors = true;
1513 }
1514
1515 String16 product;
1516 identIdx = block.indexOfAttribute(NULL, "product");
1517 if (identIdx >= 0) {
1518 product = String16(block.getAttributeStringValue(identIdx, &len));
1519 }
1520
1521 String16 comment(block.getComment(&len) ? block.getComment(&len) : nulStr);
1522
1523 if (curIsBag) {
1524 // Figure out the parent of this bag...
1525 String16 parentIdent;
1526 ssize_t parentIdentIdx = block.indexOfAttribute(NULL, "parent");
1527 if (parentIdentIdx >= 0) {
1528 parentIdent = String16(block.getAttributeStringValue(parentIdentIdx, &len));
1529 } else {
1530 ssize_t sep = ident.findLast('.');
1531 if (sep >= 0) {
1532 parentIdent.setTo(ident, sep);
1533 }
1534 }
1535
1536 if (!localHasErrors) {
1537 err = outTable->startBag(SourcePos(in->getPrintableSource(),
1538 block.getLineNumber()), myPackage, curType, ident,
1539 parentIdent, &curParams,
1540 overwrite, curIsBagReplaceOnOverwrite);
1541 if (err != NO_ERROR) {
1542 hasErrors = localHasErrors = true;
1543 }
1544 }
1545
1546 ssize_t elmIndex = 0;
1547 char elmIndexStr[14];
1548 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1549 && code != ResXMLTree::BAD_DOCUMENT) {
1550
1551 if (code == ResXMLTree::START_TAG) {
1552 if (strcmp16(block.getElementName(&len), item16.string()) != 0) {
1553 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1554 "Tag <%s> can not appear inside <%s>, only <item>\n",
1555 String8(block.getElementName(&len)).string(),
1556 String8(*curTag).string());
1557 return UNKNOWN_ERROR;
1558 }
1559
1560 String16 itemIdent;
1561 if (curType == array16) {
1562 sprintf(elmIndexStr, "^index_%d", (int)elmIndex++);
1563 itemIdent = String16(elmIndexStr);
1564 } else if (curType == plurals16) {
1565 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "quantity");
1566 if (itemIdentIdx >= 0) {
1567 String16 quantity16(block.getAttributeStringValue(itemIdentIdx, &len));
1568 if (quantity16 == other16) {
1569 itemIdent = quantityOther16;
1570 }
1571 else if (quantity16 == zero16) {
1572 itemIdent = quantityZero16;
1573 }
1574 else if (quantity16 == one16) {
1575 itemIdent = quantityOne16;
1576 }
1577 else if (quantity16 == two16) {
1578 itemIdent = quantityTwo16;
1579 }
1580 else if (quantity16 == few16) {
1581 itemIdent = quantityFew16;
1582 }
1583 else if (quantity16 == many16) {
1584 itemIdent = quantityMany16;
1585 }
1586 else {
1587 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1588 "Illegal 'quantity' attribute is <item> inside <plurals>\n");
1589 hasErrors = localHasErrors = true;
1590 }
1591 } else {
1592 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1593 "A 'quantity' attribute is required for <item> inside <plurals>\n");
1594 hasErrors = localHasErrors = true;
1595 }
1596 } else {
1597 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "name");
1598 if (itemIdentIdx >= 0) {
1599 itemIdent = String16(block.getAttributeStringValue(itemIdentIdx, &len));
1600 } else {
1601 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1602 "A 'name' attribute is required for <item>\n");
1603 hasErrors = localHasErrors = true;
1604 }
1605 }
1606
1607 ResXMLParser::ResXMLPosition parserPosition;
1608 block.getPosition(&parserPosition);
1609
1610 err = parseAndAddBag(bundle, in, &block, curParams, myPackage, curType,
1611 ident, parentIdent, itemIdent, curFormat, curIsFormatted,
Anton Krumina2ef5c02014-03-12 14:46:44 -07001612 product, NO_PSEUDOLOCALIZATION, overwrite, outTable);
Adam Lesinski282e1812014-01-23 18:17:42 -08001613 if (err == NO_ERROR) {
1614 if (curIsPseudolocalizable && localeIsDefined(curParams)
Anton Krumina2ef5c02014-03-12 14:46:44 -07001615 && bundle->getPseudolocalize() > 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001616 // pseudolocalize here
Anton Krumina2ef5c02014-03-12 14:46:44 -07001617 if ((PSEUDO_ACCENTED & bundle->getPseudolocalize()) ==
1618 PSEUDO_ACCENTED) {
1619 block.setPosition(parserPosition);
1620 err = parseAndAddBag(bundle, in, &block, pseudoParams, myPackage,
1621 curType, ident, parentIdent, itemIdent, curFormat,
1622 curIsFormatted, product, PSEUDO_ACCENTED,
1623 overwrite, outTable);
1624 }
1625 if ((PSEUDO_BIDI & bundle->getPseudolocalize()) ==
1626 PSEUDO_BIDI) {
1627 block.setPosition(parserPosition);
1628 err = parseAndAddBag(bundle, in, &block, pseudoBidiParams, myPackage,
1629 curType, ident, parentIdent, itemIdent, curFormat,
1630 curIsFormatted, product, PSEUDO_BIDI,
1631 overwrite, outTable);
1632 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001633 }
Anton Krumina2ef5c02014-03-12 14:46:44 -07001634 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001635 if (err != NO_ERROR) {
1636 hasErrors = localHasErrors = true;
1637 }
1638 } else if (code == ResXMLTree::END_TAG) {
1639 if (strcmp16(block.getElementName(&len), curTag->string()) != 0) {
1640 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1641 "Found tag </%s> where </%s> is expected\n",
1642 String8(block.getElementName(&len)).string(),
1643 String8(*curTag).string());
1644 return UNKNOWN_ERROR;
1645 }
1646 break;
1647 }
1648 }
1649 } else {
1650 ResXMLParser::ResXMLPosition parserPosition;
1651 block.getPosition(&parserPosition);
1652
1653 err = parseAndAddEntry(bundle, in, &block, curParams, myPackage, curType, ident,
1654 *curTag, curIsStyled, curFormat, curIsFormatted,
Anton Krumina2ef5c02014-03-12 14:46:44 -07001655 product, NO_PSEUDOLOCALIZATION, overwrite, &skippedResourceNames, outTable);
Adam Lesinski282e1812014-01-23 18:17:42 -08001656
1657 if (err < NO_ERROR) { // Why err < NO_ERROR instead of err != NO_ERROR?
1658 hasErrors = localHasErrors = true;
1659 }
1660 else if (err == NO_ERROR) {
1661 if (curIsPseudolocalizable && localeIsDefined(curParams)
Anton Krumina2ef5c02014-03-12 14:46:44 -07001662 && bundle->getPseudolocalize() > 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001663 // pseudolocalize here
Anton Krumina2ef5c02014-03-12 14:46:44 -07001664 if ((PSEUDO_ACCENTED & bundle->getPseudolocalize()) ==
1665 PSEUDO_ACCENTED) {
1666 block.setPosition(parserPosition);
1667 err = parseAndAddEntry(bundle, in, &block, pseudoParams, myPackage, curType,
1668 ident, *curTag, curIsStyled, curFormat,
1669 curIsFormatted, product,
1670 PSEUDO_ACCENTED, overwrite, &skippedResourceNames, outTable);
1671 }
1672 if ((PSEUDO_BIDI & bundle->getPseudolocalize()) ==
1673 PSEUDO_BIDI) {
1674 block.setPosition(parserPosition);
1675 err = parseAndAddEntry(bundle, in, &block, pseudoBidiParams,
1676 myPackage, curType, ident, *curTag, curIsStyled, curFormat,
1677 curIsFormatted, product,
1678 PSEUDO_BIDI, overwrite, &skippedResourceNames, outTable);
1679 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001680 if (err != NO_ERROR) {
1681 hasErrors = localHasErrors = true;
1682 }
1683 }
1684 }
1685 }
1686
1687#if 0
1688 if (comment.size() > 0) {
1689 printf("Comment for @%s:%s/%s: %s\n", String8(myPackage).string(),
1690 String8(curType).string(), String8(ident).string(),
1691 String8(comment).string());
1692 }
1693#endif
1694 if (!localHasErrors) {
1695 outTable->appendComment(myPackage, curType, ident, comment, false);
1696 }
1697 }
1698 else if (code == ResXMLTree::END_TAG) {
1699 if (strcmp16(block.getElementName(&len), resources16.string()) != 0) {
1700 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1701 "Unexpected end tag %s\n", String8(block.getElementName(&len)).string());
1702 return UNKNOWN_ERROR;
1703 }
1704 }
1705 else if (code == ResXMLTree::START_NAMESPACE || code == ResXMLTree::END_NAMESPACE) {
1706 }
1707 else if (code == ResXMLTree::TEXT) {
1708 if (isWhitespace(block.getText(&len))) {
1709 continue;
1710 }
1711 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1712 "Found text \"%s\" where item tag is expected\n",
1713 String8(block.getText(&len)).string());
1714 return UNKNOWN_ERROR;
1715 }
1716 }
1717
Adam Lesinski8ff15b42013-10-07 16:54:01 -07001718 // For every resource defined, there must be exist one variant with a product attribute
1719 // set to 'default' (or no product attribute at all).
1720 // We check to see that for every resource that was ignored because of a mismatched
1721 // product attribute, some product variant of that resource was processed.
1722 for (size_t i = 0; i < skippedResourceNames.size(); i++) {
1723 if (skippedResourceNames[i]) {
1724 const type_ident_pair_t& p = skippedResourceNames.keyAt(i);
1725 if (!outTable->hasBagOrEntry(myPackage, p.type, p.ident)) {
1726 const char* bundleProduct =
1727 (bundle->getProduct() == NULL) ? "" : bundle->getProduct();
1728 fprintf(stderr, "In resource file %s: %s\n",
1729 in->getPrintableSource().string(),
1730 curParams.toString().string());
1731
1732 fprintf(stderr, "\t%s '%s' does not match product %s.\n"
1733 "\tYou may have forgotten to include a 'default' product variant"
1734 " of the resource.\n",
1735 String8(p.type).string(), String8(p.ident).string(),
1736 bundleProduct[0] == 0 ? "default" : bundleProduct);
1737 return UNKNOWN_ERROR;
1738 }
1739 }
1740 }
1741
Andreas Gampe2412f842014-09-30 20:55:57 -07001742 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001743}
1744
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001745ResourceTable::ResourceTable(Bundle* bundle, const String16& assetsPackage, ResourceTable::PackageType type)
1746 : mAssetsPackage(assetsPackage)
1747 , mPackageType(type)
1748 , mTypeIdOffset(0)
1749 , mNumLocal(0)
1750 , mBundle(bundle)
Adam Lesinski282e1812014-01-23 18:17:42 -08001751{
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001752 ssize_t packageId = -1;
1753 switch (mPackageType) {
1754 case App:
1755 case AppFeature:
1756 packageId = 0x7f;
1757 break;
1758
1759 case System:
1760 packageId = 0x01;
1761 break;
1762
1763 case SharedLibrary:
1764 packageId = 0x00;
1765 break;
1766
1767 default:
1768 assert(0);
1769 break;
1770 }
1771 sp<Package> package = new Package(mAssetsPackage, packageId);
1772 mPackages.add(assetsPackage, package);
1773 mOrderedPackages.add(package);
1774
1775 // Every resource table always has one first entry, the bag attributes.
1776 const SourcePos unknown(String8("????"), 0);
1777 getType(mAssetsPackage, String16("attr"), unknown);
1778}
1779
1780static uint32_t findLargestTypeIdForPackage(const ResTable& table, const String16& packageName) {
1781 const size_t basePackageCount = table.getBasePackageCount();
1782 for (size_t i = 0; i < basePackageCount; i++) {
1783 if (packageName == table.getBasePackageName(i)) {
1784 return table.getLastTypeIdForPackage(i);
1785 }
1786 }
1787 return 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08001788}
1789
1790status_t ResourceTable::addIncludedResources(Bundle* bundle, const sp<AaptAssets>& assets)
1791{
1792 status_t err = assets->buildIncludedResources(bundle);
1793 if (err != NO_ERROR) {
1794 return err;
1795 }
1796
Adam Lesinski282e1812014-01-23 18:17:42 -08001797 mAssets = assets;
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001798 mTypeIdOffset = findLargestTypeIdForPackage(assets->getIncludedResources(), mAssetsPackage);
Adam Lesinski282e1812014-01-23 18:17:42 -08001799
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001800 const String8& featureAfter = bundle->getFeatureAfterPackage();
1801 if (!featureAfter.isEmpty()) {
1802 AssetManager featureAssetManager;
1803 if (!featureAssetManager.addAssetPath(featureAfter, NULL)) {
1804 fprintf(stderr, "ERROR: Feature package '%s' not found.\n",
1805 featureAfter.string());
1806 return UNKNOWN_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001807 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001808
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001809 const ResTable& featureTable = featureAssetManager.getResources(false);
1810 mTypeIdOffset = max(mTypeIdOffset,
1811 findLargestTypeIdForPackage(featureTable, mAssetsPackage));
1812 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001813
1814 return NO_ERROR;
1815}
1816
1817status_t ResourceTable::addPublic(const SourcePos& sourcePos,
1818 const String16& package,
1819 const String16& type,
1820 const String16& name,
1821 const uint32_t ident)
1822{
1823 uint32_t rid = mAssets->getIncludedResources()
1824 .identifierForName(name.string(), name.size(),
1825 type.string(), type.size(),
1826 package.string(), package.size());
1827 if (rid != 0) {
1828 sourcePos.error("Error declaring public resource %s/%s for included package %s\n",
1829 String8(type).string(), String8(name).string(),
1830 String8(package).string());
1831 return UNKNOWN_ERROR;
1832 }
1833
1834 sp<Type> t = getType(package, type, sourcePos);
1835 if (t == NULL) {
1836 return UNKNOWN_ERROR;
1837 }
1838 return t->addPublic(sourcePos, name, ident);
1839}
1840
1841status_t ResourceTable::addEntry(const SourcePos& sourcePos,
1842 const String16& package,
1843 const String16& type,
1844 const String16& name,
1845 const String16& value,
1846 const Vector<StringPool::entry_style_span>* style,
1847 const ResTable_config* params,
1848 const bool doSetIndex,
1849 const int32_t format,
1850 const bool overwrite)
1851{
Adam Lesinski282e1812014-01-23 18:17:42 -08001852 uint32_t rid = mAssets->getIncludedResources()
1853 .identifierForName(name.string(), name.size(),
1854 type.string(), type.size(),
1855 package.string(), package.size());
1856 if (rid != 0) {
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001857 sourcePos.error("Resource entry %s/%s is already defined in package %s.",
1858 String8(type).string(), String8(name).string(), String8(package).string());
1859 return UNKNOWN_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001860 }
1861
Adam Lesinski282e1812014-01-23 18:17:42 -08001862 sp<Entry> e = getEntry(package, type, name, sourcePos, overwrite,
1863 params, doSetIndex);
1864 if (e == NULL) {
1865 return UNKNOWN_ERROR;
1866 }
1867 status_t err = e->setItem(sourcePos, value, style, format, overwrite);
1868 if (err == NO_ERROR) {
1869 mNumLocal++;
1870 }
1871 return err;
1872}
1873
1874status_t ResourceTable::startBag(const SourcePos& sourcePos,
1875 const String16& package,
1876 const String16& type,
1877 const String16& name,
1878 const String16& bagParent,
1879 const ResTable_config* params,
1880 bool overlay,
Andreas Gampe2412f842014-09-30 20:55:57 -07001881 bool replace, bool /* isId */)
Adam Lesinski282e1812014-01-23 18:17:42 -08001882{
1883 status_t result = NO_ERROR;
1884
1885 // Check for adding entries in other packages... for now we do
1886 // nothing. We need to do the right thing here to support skinning.
1887 uint32_t rid = mAssets->getIncludedResources()
1888 .identifierForName(name.string(), name.size(),
1889 type.string(), type.size(),
1890 package.string(), package.size());
1891 if (rid != 0) {
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001892 sourcePos.error("Resource entry %s/%s is already defined in package %s.",
1893 String8(type).string(), String8(name).string(), String8(package).string());
1894 return UNKNOWN_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001895 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07001896
Adam Lesinski282e1812014-01-23 18:17:42 -08001897 if (overlay && !mBundle->getAutoAddOverlay() && !hasBagOrEntry(package, type, name)) {
1898 bool canAdd = false;
1899 sp<Package> p = mPackages.valueFor(package);
1900 if (p != NULL) {
1901 sp<Type> t = p->getTypes().valueFor(type);
1902 if (t != NULL) {
1903 if (t->getCanAddEntries().indexOf(name) >= 0) {
1904 canAdd = true;
1905 }
1906 }
1907 }
1908 if (!canAdd) {
1909 sourcePos.error("Resource does not already exist in overlay at '%s'; use <add-resource> to add.\n",
1910 String8(name).string());
1911 return UNKNOWN_ERROR;
1912 }
1913 }
1914 sp<Entry> e = getEntry(package, type, name, sourcePos, overlay, params);
1915 if (e == NULL) {
1916 return UNKNOWN_ERROR;
1917 }
1918
1919 // If a parent is explicitly specified, set it.
1920 if (bagParent.size() > 0) {
1921 e->setParent(bagParent);
1922 }
1923
1924 if ((result = e->makeItABag(sourcePos)) != NO_ERROR) {
1925 return result;
1926 }
1927
1928 if (overlay && replace) {
1929 return e->emptyBag(sourcePos);
1930 }
1931 return result;
1932}
1933
1934status_t ResourceTable::addBag(const SourcePos& sourcePos,
1935 const String16& package,
1936 const String16& type,
1937 const String16& name,
1938 const String16& bagParent,
1939 const String16& bagKey,
1940 const String16& value,
1941 const Vector<StringPool::entry_style_span>* style,
1942 const ResTable_config* params,
1943 bool replace, bool isId, const int32_t format)
1944{
1945 // Check for adding entries in other packages... for now we do
1946 // nothing. We need to do the right thing here to support skinning.
1947 uint32_t rid = mAssets->getIncludedResources()
1948 .identifierForName(name.string(), name.size(),
1949 type.string(), type.size(),
1950 package.string(), package.size());
1951 if (rid != 0) {
1952 return NO_ERROR;
1953 }
1954
1955#if 0
1956 if (name == String16("left")) {
1957 printf("Adding bag left: file=%s, line=%d, type=%s\n",
1958 sourcePos.file.striing(), sourcePos.line, String8(type).string());
1959 }
1960#endif
1961 sp<Entry> e = getEntry(package, type, name, sourcePos, replace, params);
1962 if (e == NULL) {
1963 return UNKNOWN_ERROR;
1964 }
1965
1966 // If a parent is explicitly specified, set it.
1967 if (bagParent.size() > 0) {
1968 e->setParent(bagParent);
1969 }
1970
1971 const bool first = e->getBag().indexOfKey(bagKey) < 0;
1972 status_t err = e->addToBag(sourcePos, bagKey, value, style, replace, isId, format);
1973 if (err == NO_ERROR && first) {
1974 mNumLocal++;
1975 }
1976 return err;
1977}
1978
1979bool ResourceTable::hasBagOrEntry(const String16& package,
1980 const String16& type,
1981 const String16& name) const
1982{
1983 // First look for this in the included resources...
1984 uint32_t rid = mAssets->getIncludedResources()
1985 .identifierForName(name.string(), name.size(),
1986 type.string(), type.size(),
1987 package.string(), package.size());
1988 if (rid != 0) {
1989 return true;
1990 }
1991
1992 sp<Package> p = mPackages.valueFor(package);
1993 if (p != NULL) {
1994 sp<Type> t = p->getTypes().valueFor(type);
1995 if (t != NULL) {
1996 sp<ConfigList> c = t->getConfigs().valueFor(name);
1997 if (c != NULL) return true;
1998 }
1999 }
2000
2001 return false;
2002}
2003
2004bool ResourceTable::hasBagOrEntry(const String16& package,
2005 const String16& type,
2006 const String16& name,
2007 const ResTable_config& config) const
2008{
2009 // First look for this in the included resources...
2010 uint32_t rid = mAssets->getIncludedResources()
2011 .identifierForName(name.string(), name.size(),
2012 type.string(), type.size(),
2013 package.string(), package.size());
2014 if (rid != 0) {
2015 return true;
2016 }
2017
2018 sp<Package> p = mPackages.valueFor(package);
2019 if (p != NULL) {
2020 sp<Type> t = p->getTypes().valueFor(type);
2021 if (t != NULL) {
2022 sp<ConfigList> c = t->getConfigs().valueFor(name);
2023 if (c != NULL) {
2024 sp<Entry> e = c->getEntries().valueFor(config);
2025 if (e != NULL) {
2026 return true;
2027 }
2028 }
2029 }
2030 }
2031
2032 return false;
2033}
2034
2035bool ResourceTable::hasBagOrEntry(const String16& ref,
2036 const String16* defType,
2037 const String16* defPackage)
2038{
2039 String16 package, type, name;
2040 if (!ResTable::expandResourceRef(ref.string(), ref.size(), &package, &type, &name,
2041 defType, defPackage ? defPackage:&mAssetsPackage, NULL)) {
2042 return false;
2043 }
2044 return hasBagOrEntry(package, type, name);
2045}
2046
2047bool ResourceTable::appendComment(const String16& package,
2048 const String16& type,
2049 const String16& name,
2050 const String16& comment,
2051 bool onlyIfEmpty)
2052{
2053 if (comment.size() <= 0) {
2054 return true;
2055 }
2056
2057 sp<Package> p = mPackages.valueFor(package);
2058 if (p != NULL) {
2059 sp<Type> t = p->getTypes().valueFor(type);
2060 if (t != NULL) {
2061 sp<ConfigList> c = t->getConfigs().valueFor(name);
2062 if (c != NULL) {
2063 c->appendComment(comment, onlyIfEmpty);
2064 return true;
2065 }
2066 }
2067 }
2068 return false;
2069}
2070
2071bool ResourceTable::appendTypeComment(const String16& package,
2072 const String16& type,
2073 const String16& name,
2074 const String16& comment)
2075{
2076 if (comment.size() <= 0) {
2077 return true;
2078 }
2079
2080 sp<Package> p = mPackages.valueFor(package);
2081 if (p != NULL) {
2082 sp<Type> t = p->getTypes().valueFor(type);
2083 if (t != NULL) {
2084 sp<ConfigList> c = t->getConfigs().valueFor(name);
2085 if (c != NULL) {
2086 c->appendTypeComment(comment);
2087 return true;
2088 }
2089 }
2090 }
2091 return false;
2092}
2093
2094void ResourceTable::canAddEntry(const SourcePos& pos,
2095 const String16& package, const String16& type, const String16& name)
2096{
2097 sp<Type> t = getType(package, type, pos);
2098 if (t != NULL) {
2099 t->canAddEntry(name);
2100 }
2101}
2102
2103size_t ResourceTable::size() const {
2104 return mPackages.size();
2105}
2106
2107size_t ResourceTable::numLocalResources() const {
2108 return mNumLocal;
2109}
2110
2111bool ResourceTable::hasResources() const {
2112 return mNumLocal > 0;
2113}
2114
Adam Lesinski27f69f42014-08-21 13:19:12 -07002115sp<AaptFile> ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& filter,
2116 const bool isBase)
Adam Lesinski282e1812014-01-23 18:17:42 -08002117{
2118 sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
Adam Lesinski27f69f42014-08-21 13:19:12 -07002119 status_t err = flatten(bundle, filter, data, isBase);
Adam Lesinski282e1812014-01-23 18:17:42 -08002120 return err == NO_ERROR ? data : NULL;
2121}
2122
2123inline uint32_t ResourceTable::getResId(const sp<Package>& p,
2124 const sp<Type>& t,
2125 uint32_t nameId)
2126{
2127 return makeResId(p->getAssignedId(), t->getIndex(), nameId);
2128}
2129
2130uint32_t ResourceTable::getResId(const String16& package,
2131 const String16& type,
2132 const String16& name,
2133 bool onlyPublic) const
2134{
2135 uint32_t id = ResourceIdCache::lookup(package, type, name, onlyPublic);
2136 if (id != 0) return id; // cache hit
2137
Adam Lesinski282e1812014-01-23 18:17:42 -08002138 // First look for this in the included resources...
2139 uint32_t specFlags = 0;
2140 uint32_t rid = mAssets->getIncludedResources()
2141 .identifierForName(name.string(), name.size(),
2142 type.string(), type.size(),
2143 package.string(), package.size(),
2144 &specFlags);
2145 if (rid != 0) {
2146 if (onlyPublic) {
2147 if ((specFlags & ResTable_typeSpec::SPEC_PUBLIC) == 0) {
2148 return 0;
2149 }
2150 }
2151
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002152 return ResourceIdCache::store(package, type, name, onlyPublic, rid);
Adam Lesinski282e1812014-01-23 18:17:42 -08002153 }
2154
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002155 sp<Package> p = mPackages.valueFor(package);
2156 if (p == NULL) return 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08002157 sp<Type> t = p->getTypes().valueFor(type);
2158 if (t == NULL) return 0;
Adam Lesinski9b624c12014-11-19 17:49:26 -08002159 sp<ConfigList> c = t->getConfigs().valueFor(name);
2160 if (c == NULL) {
2161 if (type != String16("attr")) {
2162 return 0;
2163 }
2164 t = p->getTypes().valueFor(String16(kAttrPrivateType));
2165 if (t == NULL) return 0;
2166 c = t->getConfigs().valueFor(name);
2167 if (c == NULL) return 0;
2168 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002169 int32_t ei = c->getEntryIndex();
2170 if (ei < 0) return 0;
2171
2172 return ResourceIdCache::store(package, type, name, onlyPublic,
2173 getResId(p, t, ei));
2174}
2175
2176uint32_t ResourceTable::getResId(const String16& ref,
2177 const String16* defType,
2178 const String16* defPackage,
2179 const char** outErrorMsg,
2180 bool onlyPublic) const
2181{
2182 String16 package, type, name;
2183 bool refOnlyPublic = true;
2184 if (!ResTable::expandResourceRef(
2185 ref.string(), ref.size(), &package, &type, &name,
2186 defType, defPackage ? defPackage:&mAssetsPackage,
2187 outErrorMsg, &refOnlyPublic)) {
Andreas Gampe2412f842014-09-30 20:55:57 -07002188 if (kIsDebug) {
2189 printf("Expanding resource: ref=%s\n", String8(ref).string());
2190 printf("Expanding resource: defType=%s\n",
2191 defType ? String8(*defType).string() : "NULL");
2192 printf("Expanding resource: defPackage=%s\n",
2193 defPackage ? String8(*defPackage).string() : "NULL");
2194 printf("Expanding resource: ref=%s\n", String8(ref).string());
2195 printf("Expanded resource: p=%s, t=%s, n=%s, res=0\n",
2196 String8(package).string(), String8(type).string(),
2197 String8(name).string());
2198 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002199 return 0;
2200 }
2201 uint32_t res = getResId(package, type, name, onlyPublic && refOnlyPublic);
Andreas Gampe2412f842014-09-30 20:55:57 -07002202 if (kIsDebug) {
2203 printf("Expanded resource: p=%s, t=%s, n=%s, res=%d\n",
2204 String8(package).string(), String8(type).string(),
2205 String8(name).string(), res);
2206 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002207 if (res == 0) {
2208 if (outErrorMsg)
2209 *outErrorMsg = "No resource found that matches the given name";
2210 }
2211 return res;
2212}
2213
2214bool ResourceTable::isValidResourceName(const String16& s)
2215{
2216 const char16_t* p = s.string();
2217 bool first = true;
2218 while (*p) {
2219 if ((*p >= 'a' && *p <= 'z')
2220 || (*p >= 'A' && *p <= 'Z')
2221 || *p == '_'
2222 || (!first && *p >= '0' && *p <= '9')) {
2223 first = false;
2224 p++;
2225 continue;
2226 }
2227 return false;
2228 }
2229 return true;
2230}
2231
2232bool ResourceTable::stringToValue(Res_value* outValue, StringPool* pool,
2233 const String16& str,
2234 bool preserveSpaces, bool coerceType,
2235 uint32_t attrID,
2236 const Vector<StringPool::entry_style_span>* style,
2237 String16* outStr, void* accessorCookie,
2238 uint32_t attrType, const String8* configTypeName,
2239 const ConfigDescription* config)
2240{
2241 String16 finalStr;
2242
2243 bool res = true;
2244 if (style == NULL || style->size() == 0) {
2245 // Text is not styled so it can be any type... let's figure it out.
2246 res = mAssets->getIncludedResources()
2247 .stringToValue(outValue, &finalStr, str.string(), str.size(), preserveSpaces,
2248 coerceType, attrID, NULL, &mAssetsPackage, this,
2249 accessorCookie, attrType);
2250 } else {
2251 // Styled text can only be a string, and while collecting the style
2252 // information we have already processed that string!
2253 outValue->size = sizeof(Res_value);
2254 outValue->res0 = 0;
2255 outValue->dataType = outValue->TYPE_STRING;
2256 outValue->data = 0;
2257 finalStr = str;
2258 }
2259
2260 if (!res) {
2261 return false;
2262 }
2263
2264 if (outValue->dataType == outValue->TYPE_STRING) {
2265 // Should do better merging styles.
2266 if (pool) {
2267 String8 configStr;
2268 if (config != NULL) {
2269 configStr = config->toString();
2270 } else {
2271 configStr = "(null)";
2272 }
Andreas Gampe2412f842014-09-30 20:55:57 -07002273 if (kIsDebug) {
2274 printf("Adding to pool string style #%zu config %s: %s\n",
2275 style != NULL ? style->size() : 0U,
2276 configStr.string(), String8(finalStr).string());
2277 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002278 if (style != NULL && style->size() > 0) {
2279 outValue->data = pool->add(finalStr, *style, configTypeName, config);
2280 } else {
2281 outValue->data = pool->add(finalStr, true, configTypeName, config);
2282 }
2283 } else {
2284 // Caller will fill this in later.
2285 outValue->data = 0;
2286 }
2287
2288 if (outStr) {
2289 *outStr = finalStr;
2290 }
2291
2292 }
2293
2294 return true;
2295}
2296
2297uint32_t ResourceTable::getCustomResource(
2298 const String16& package, const String16& type, const String16& name) const
2299{
2300 //printf("getCustomResource: %s %s %s\n", String8(package).string(),
2301 // String8(type).string(), String8(name).string());
2302 sp<Package> p = mPackages.valueFor(package);
2303 if (p == NULL) return 0;
2304 sp<Type> t = p->getTypes().valueFor(type);
2305 if (t == NULL) return 0;
2306 sp<ConfigList> c = t->getConfigs().valueFor(name);
Adam Lesinski9b624c12014-11-19 17:49:26 -08002307 if (c == NULL) {
2308 if (type != String16("attr")) {
2309 return 0;
2310 }
2311 t = p->getTypes().valueFor(String16(kAttrPrivateType));
2312 if (t == NULL) return 0;
2313 c = t->getConfigs().valueFor(name);
2314 if (c == NULL) return 0;
2315 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002316 int32_t ei = c->getEntryIndex();
2317 if (ei < 0) return 0;
2318 return getResId(p, t, ei);
2319}
2320
2321uint32_t ResourceTable::getCustomResourceWithCreation(
2322 const String16& package, const String16& type, const String16& name,
2323 const bool createIfNotFound)
2324{
2325 uint32_t resId = getCustomResource(package, type, name);
2326 if (resId != 0 || !createIfNotFound) {
2327 return resId;
2328 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002329
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002330 if (mAssetsPackage != package) {
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002331 mCurrentXmlPos.error("creating resource for external package %s: %s/%s.",
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002332 String8(package).string(), String8(type).string(), String8(name).string());
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002333 if (package == String16("android")) {
2334 mCurrentXmlPos.printf("did you mean to use @+id instead of @+android:id?");
2335 }
2336 return 0;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -07002337 }
2338
2339 String16 value("false");
Adam Lesinski282e1812014-01-23 18:17:42 -08002340 status_t status = addEntry(mCurrentXmlPos, package, type, name, value, NULL, NULL, true);
2341 if (status == NO_ERROR) {
2342 resId = getResId(package, type, name);
2343 return resId;
2344 }
2345 return 0;
2346}
2347
2348uint32_t ResourceTable::getRemappedPackage(uint32_t origPackage) const
2349{
2350 return origPackage;
2351}
2352
2353bool ResourceTable::getAttributeType(uint32_t attrID, uint32_t* outType)
2354{
2355 //printf("getAttributeType #%08x\n", attrID);
2356 Res_value value;
2357 if (getItemValue(attrID, ResTable_map::ATTR_TYPE, &value)) {
2358 //printf("getAttributeType #%08x (%s): #%08x\n", attrID,
2359 // String8(getEntry(attrID)->getName()).string(), value.data);
2360 *outType = value.data;
2361 return true;
2362 }
2363 return false;
2364}
2365
2366bool ResourceTable::getAttributeMin(uint32_t attrID, uint32_t* outMin)
2367{
2368 //printf("getAttributeMin #%08x\n", attrID);
2369 Res_value value;
2370 if (getItemValue(attrID, ResTable_map::ATTR_MIN, &value)) {
2371 *outMin = value.data;
2372 return true;
2373 }
2374 return false;
2375}
2376
2377bool ResourceTable::getAttributeMax(uint32_t attrID, uint32_t* outMax)
2378{
2379 //printf("getAttributeMax #%08x\n", attrID);
2380 Res_value value;
2381 if (getItemValue(attrID, ResTable_map::ATTR_MAX, &value)) {
2382 *outMax = value.data;
2383 return true;
2384 }
2385 return false;
2386}
2387
2388uint32_t ResourceTable::getAttributeL10N(uint32_t attrID)
2389{
2390 //printf("getAttributeL10N #%08x\n", attrID);
2391 Res_value value;
2392 if (getItemValue(attrID, ResTable_map::ATTR_L10N, &value)) {
2393 return value.data;
2394 }
2395 return ResTable_map::L10N_NOT_REQUIRED;
2396}
2397
2398bool ResourceTable::getLocalizationSetting()
2399{
2400 return mBundle->getRequireLocalization();
2401}
2402
2403void ResourceTable::reportError(void* accessorCookie, const char* fmt, ...)
2404{
2405 if (accessorCookie != NULL && fmt != NULL) {
2406 AccessorCookie* ac = (AccessorCookie*)accessorCookie;
2407 int retval=0;
2408 char buf[1024];
2409 va_list ap;
2410 va_start(ap, fmt);
2411 retval = vsnprintf(buf, sizeof(buf), fmt, ap);
2412 va_end(ap);
2413 ac->sourcePos.error("Error: %s (at '%s' with value '%s').\n",
2414 buf, ac->attr.string(), ac->value.string());
2415 }
2416}
2417
2418bool ResourceTable::getAttributeKeys(
2419 uint32_t attrID, Vector<String16>* outKeys)
2420{
2421 sp<const Entry> e = getEntry(attrID);
2422 if (e != NULL) {
2423 const size_t N = e->getBag().size();
2424 for (size_t i=0; i<N; i++) {
2425 const String16& key = e->getBag().keyAt(i);
2426 if (key.size() > 0 && key.string()[0] != '^') {
2427 outKeys->add(key);
2428 }
2429 }
2430 return true;
2431 }
2432 return false;
2433}
2434
2435bool ResourceTable::getAttributeEnum(
2436 uint32_t attrID, const char16_t* name, size_t nameLen,
2437 Res_value* outValue)
2438{
2439 //printf("getAttributeEnum #%08x %s\n", attrID, String8(name, nameLen).string());
2440 String16 nameStr(name, nameLen);
2441 sp<const Entry> e = getEntry(attrID);
2442 if (e != NULL) {
2443 const size_t N = e->getBag().size();
2444 for (size_t i=0; i<N; i++) {
2445 //printf("Comparing %s to %s\n", String8(name, nameLen).string(),
2446 // String8(e->getBag().keyAt(i)).string());
2447 if (e->getBag().keyAt(i) == nameStr) {
2448 return getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, outValue);
2449 }
2450 }
2451 }
2452 return false;
2453}
2454
2455bool ResourceTable::getAttributeFlags(
2456 uint32_t attrID, const char16_t* name, size_t nameLen,
2457 Res_value* outValue)
2458{
2459 outValue->dataType = Res_value::TYPE_INT_HEX;
2460 outValue->data = 0;
2461
2462 //printf("getAttributeFlags #%08x %s\n", attrID, String8(name, nameLen).string());
2463 String16 nameStr(name, nameLen);
2464 sp<const Entry> e = getEntry(attrID);
2465 if (e != NULL) {
2466 const size_t N = e->getBag().size();
2467
2468 const char16_t* end = name + nameLen;
2469 const char16_t* pos = name;
2470 while (pos < end) {
2471 const char16_t* start = pos;
2472 while (pos < end && *pos != '|') {
2473 pos++;
2474 }
2475
2476 String16 nameStr(start, pos-start);
2477 size_t i;
2478 for (i=0; i<N; i++) {
2479 //printf("Comparing \"%s\" to \"%s\"\n", String8(nameStr).string(),
2480 // String8(e->getBag().keyAt(i)).string());
2481 if (e->getBag().keyAt(i) == nameStr) {
2482 Res_value val;
2483 bool got = getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, &val);
2484 if (!got) {
2485 return false;
2486 }
2487 //printf("Got value: 0x%08x\n", val.data);
2488 outValue->data |= val.data;
2489 break;
2490 }
2491 }
2492
2493 if (i >= N) {
2494 // Didn't find this flag identifier.
2495 return false;
2496 }
2497 pos++;
2498 }
2499
2500 return true;
2501 }
2502 return false;
2503}
2504
2505status_t ResourceTable::assignResourceIds()
2506{
2507 const size_t N = mOrderedPackages.size();
2508 size_t pi;
2509 status_t firstError = NO_ERROR;
2510
2511 // First generate all bag attributes and assign indices.
2512 for (pi=0; pi<N; pi++) {
2513 sp<Package> p = mOrderedPackages.itemAt(pi);
2514 if (p == NULL || p->getTypes().size() == 0) {
2515 // Empty, skip!
2516 continue;
2517 }
2518
Adam Lesinski9b624c12014-11-19 17:49:26 -08002519 if (mPackageType == System) {
2520 p->movePrivateAttrs();
2521 }
2522
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002523 // This has no sense for packages being built as AppFeature (aka with a non-zero offset).
Adam Lesinski282e1812014-01-23 18:17:42 -08002524 status_t err = p->applyPublicTypeOrder();
2525 if (err != NO_ERROR && firstError == NO_ERROR) {
2526 firstError = err;
2527 }
2528
2529 // Generate attributes...
2530 const size_t N = p->getOrderedTypes().size();
2531 size_t ti;
2532 for (ti=0; ti<N; ti++) {
2533 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2534 if (t == NULL) {
2535 continue;
2536 }
2537 const size_t N = t->getOrderedConfigs().size();
2538 for (size_t ci=0; ci<N; ci++) {
2539 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2540 if (c == NULL) {
2541 continue;
2542 }
2543 const size_t N = c->getEntries().size();
2544 for (size_t ei=0; ei<N; ei++) {
2545 sp<Entry> e = c->getEntries().valueAt(ei);
2546 if (e == NULL) {
2547 continue;
2548 }
2549 status_t err = e->generateAttributes(this, p->getName());
2550 if (err != NO_ERROR && firstError == NO_ERROR) {
2551 firstError = err;
2552 }
2553 }
2554 }
2555 }
2556
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002557 uint32_t typeIdOffset = 0;
2558 if (mPackageType == AppFeature && p->getName() == mAssetsPackage) {
2559 typeIdOffset = mTypeIdOffset;
2560 }
2561
Adam Lesinski282e1812014-01-23 18:17:42 -08002562 const SourcePos unknown(String8("????"), 0);
2563 sp<Type> attr = p->getType(String16("attr"), unknown);
2564
2565 // Assign indices...
Adam Lesinski43a0df02014-08-18 17:14:57 -07002566 const size_t typeCount = p->getOrderedTypes().size();
2567 for (size_t ti = 0; ti < typeCount; ti++) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002568 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2569 if (t == NULL) {
2570 continue;
2571 }
Adam Lesinski43a0df02014-08-18 17:14:57 -07002572
Adam Lesinski282e1812014-01-23 18:17:42 -08002573 err = t->applyPublicEntryOrder();
2574 if (err != NO_ERROR && firstError == NO_ERROR) {
2575 firstError = err;
2576 }
2577
2578 const size_t N = t->getOrderedConfigs().size();
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002579 t->setIndex(ti + 1 + typeIdOffset);
Adam Lesinski282e1812014-01-23 18:17:42 -08002580
2581 LOG_ALWAYS_FATAL_IF(ti == 0 && attr != t,
2582 "First type is not attr!");
2583
2584 for (size_t ei=0; ei<N; ei++) {
2585 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ei);
2586 if (c == NULL) {
2587 continue;
2588 }
2589 c->setEntryIndex(ei);
2590 }
2591 }
2592
Adam Lesinski9b624c12014-11-19 17:49:26 -08002593
Adam Lesinski282e1812014-01-23 18:17:42 -08002594 // Assign resource IDs to keys in bags...
Adam Lesinski43a0df02014-08-18 17:14:57 -07002595 for (size_t ti = 0; ti < typeCount; ti++) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002596 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2597 if (t == NULL) {
2598 continue;
2599 }
Adam Lesinski9b624c12014-11-19 17:49:26 -08002600
Adam Lesinski282e1812014-01-23 18:17:42 -08002601 const size_t N = t->getOrderedConfigs().size();
2602 for (size_t ci=0; ci<N; ci++) {
2603 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
Adam Lesinski9b624c12014-11-19 17:49:26 -08002604 if (c == NULL) {
2605 continue;
2606 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002607 //printf("Ordered config #%d: %p\n", ci, c.get());
2608 const size_t N = c->getEntries().size();
2609 for (size_t ei=0; ei<N; ei++) {
2610 sp<Entry> e = c->getEntries().valueAt(ei);
2611 if (e == NULL) {
2612 continue;
2613 }
2614 status_t err = e->assignResourceIds(this, p->getName());
2615 if (err != NO_ERROR && firstError == NO_ERROR) {
2616 firstError = err;
2617 }
2618 }
2619 }
2620 }
2621 }
2622 return firstError;
2623}
2624
2625status_t ResourceTable::addSymbols(const sp<AaptSymbols>& outSymbols) {
2626 const size_t N = mOrderedPackages.size();
2627 size_t pi;
2628
2629 for (pi=0; pi<N; pi++) {
2630 sp<Package> p = mOrderedPackages.itemAt(pi);
2631 if (p->getTypes().size() == 0) {
2632 // Empty, skip!
2633 continue;
2634 }
2635
2636 const size_t N = p->getOrderedTypes().size();
2637 size_t ti;
2638
2639 for (ti=0; ti<N; ti++) {
2640 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2641 if (t == NULL) {
2642 continue;
2643 }
Adam Lesinski9b624c12014-11-19 17:49:26 -08002644
Adam Lesinski282e1812014-01-23 18:17:42 -08002645 const size_t N = t->getOrderedConfigs().size();
Adam Lesinski9b624c12014-11-19 17:49:26 -08002646 sp<AaptSymbols> typeSymbols;
2647 if (t->getName() == String16(kAttrPrivateType)) {
2648 typeSymbols = outSymbols->addNestedSymbol(String8("attr"), t->getPos());
2649 } else {
2650 typeSymbols = outSymbols->addNestedSymbol(String8(t->getName()), t->getPos());
2651 }
2652
Adam Lesinski3fb8c9b2014-09-09 16:05:10 -07002653 if (typeSymbols == NULL) {
2654 return UNKNOWN_ERROR;
2655 }
2656
Adam Lesinski282e1812014-01-23 18:17:42 -08002657 for (size_t ci=0; ci<N; ci++) {
2658 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2659 if (c == NULL) {
2660 continue;
2661 }
2662 uint32_t rid = getResId(p, t, ci);
2663 if (rid == 0) {
2664 return UNKNOWN_ERROR;
2665 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002666 if (Res_GETPACKAGE(rid) + 1 == p->getAssignedId()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002667 typeSymbols->addSymbol(String8(c->getName()), rid, c->getPos());
2668
2669 String16 comment(c->getComment());
2670 typeSymbols->appendComment(String8(c->getName()), comment, c->getPos());
Adam Lesinski8ff15b42013-10-07 16:54:01 -07002671 //printf("Type symbol [%08x] %s comment: %s\n", rid,
2672 // String8(c->getName()).string(), String8(comment).string());
Adam Lesinski282e1812014-01-23 18:17:42 -08002673 comment = c->getTypeComment();
2674 typeSymbols->appendTypeComment(String8(c->getName()), comment);
Adam Lesinski282e1812014-01-23 18:17:42 -08002675 }
2676 }
2677 }
2678 }
2679 return NO_ERROR;
2680}
2681
2682
2683void
Adam Lesinskia01a9372014-03-20 18:04:57 -07002684ResourceTable::addLocalization(const String16& name, const String8& locale, const SourcePos& src)
Adam Lesinski282e1812014-01-23 18:17:42 -08002685{
Adam Lesinskia01a9372014-03-20 18:04:57 -07002686 mLocalizations[name][locale] = src;
Adam Lesinski282e1812014-01-23 18:17:42 -08002687}
2688
2689
2690/*!
2691 * Flag various sorts of localization problems. '+' indicates checks already implemented;
2692 * '-' indicates checks that will be implemented in the future.
2693 *
2694 * + A localized string for which no default-locale version exists => warning
2695 * + A string for which no version in an explicitly-requested locale exists => warning
2696 * + A localized translation of an translateable="false" string => warning
2697 * - A localized string not provided in every locale used by the table
2698 */
2699status_t
2700ResourceTable::validateLocalizations(void)
2701{
2702 status_t err = NO_ERROR;
2703 const String8 defaultLocale;
2704
2705 // For all strings...
Adam Lesinskia01a9372014-03-20 18:04:57 -07002706 for (map<String16, map<String8, SourcePos> >::iterator nameIter = mLocalizations.begin();
Adam Lesinski282e1812014-01-23 18:17:42 -08002707 nameIter != mLocalizations.end();
2708 nameIter++) {
Adam Lesinskia01a9372014-03-20 18:04:57 -07002709 const map<String8, SourcePos>& configSrcMap = nameIter->second;
Adam Lesinski282e1812014-01-23 18:17:42 -08002710
2711 // Look for strings with no default localization
Adam Lesinskia01a9372014-03-20 18:04:57 -07002712 if (configSrcMap.count(defaultLocale) == 0) {
2713 SourcePos().warning("string '%s' has no default translation.",
2714 String8(nameIter->first).string());
2715 if (mBundle->getVerbose()) {
2716 for (map<String8, SourcePos>::const_iterator locales = configSrcMap.begin();
2717 locales != configSrcMap.end();
2718 locales++) {
2719 locales->second.printf("locale %s found", locales->first.string());
2720 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002721 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002722 // !!! TODO: throw an error here in some circumstances
2723 }
2724
2725 // Check that all requested localizations are present for this string
Adam Lesinskifab50872014-04-16 14:40:42 -07002726 if (mBundle->getConfigurations().size() > 0 && mBundle->getRequireLocalization()) {
2727 const char* allConfigs = mBundle->getConfigurations().string();
Adam Lesinski282e1812014-01-23 18:17:42 -08002728 const char* start = allConfigs;
2729 const char* comma;
2730
Adam Lesinskia01a9372014-03-20 18:04:57 -07002731 set<String8> missingConfigs;
2732 AaptLocaleValue locale;
Adam Lesinski282e1812014-01-23 18:17:42 -08002733 do {
2734 String8 config;
2735 comma = strchr(start, ',');
2736 if (comma != NULL) {
2737 config.setTo(start, comma - start);
2738 start = comma + 1;
2739 } else {
2740 config.setTo(start);
2741 }
2742
Adam Lesinskia01a9372014-03-20 18:04:57 -07002743 if (!locale.initFromFilterString(config)) {
2744 continue;
2745 }
2746
Anton Krumina2ef5c02014-03-12 14:46:44 -07002747 // don't bother with the pseudolocale "en_XA" or "ar_XB"
2748 if (config != "en_XA" && config != "ar_XB") {
Adam Lesinskia01a9372014-03-20 18:04:57 -07002749 if (configSrcMap.find(config) == configSrcMap.end()) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002750 // okay, no specific localization found. it's possible that we are
2751 // requiring a specific regional localization [e.g. de_DE] but there is an
2752 // available string in the generic language localization [e.g. de];
2753 // consider that string to have fulfilled the localization requirement.
2754 String8 region(config.string(), 2);
Adam Lesinskia01a9372014-03-20 18:04:57 -07002755 if (configSrcMap.find(region) == configSrcMap.end() &&
2756 configSrcMap.count(defaultLocale) == 0) {
2757 missingConfigs.insert(config);
Adam Lesinski282e1812014-01-23 18:17:42 -08002758 }
2759 }
2760 }
Adam Lesinskia01a9372014-03-20 18:04:57 -07002761 } while (comma != NULL);
2762
2763 if (!missingConfigs.empty()) {
2764 String8 configStr;
2765 for (set<String8>::iterator iter = missingConfigs.begin();
2766 iter != missingConfigs.end();
2767 iter++) {
2768 configStr.appendFormat(" %s", iter->string());
2769 }
2770 SourcePos().warning("string '%s' is missing %u required localizations:%s",
2771 String8(nameIter->first).string(),
2772 (unsigned int)missingConfigs.size(),
2773 configStr.string());
2774 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002775 }
2776 }
2777
2778 return err;
2779}
2780
Adam Lesinski27f69f42014-08-21 13:19:12 -07002781status_t ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& filter,
2782 const sp<AaptFile>& dest,
2783 const bool isBase)
Adam Lesinski282e1812014-01-23 18:17:42 -08002784{
Adam Lesinski282e1812014-01-23 18:17:42 -08002785 const ConfigDescription nullConfig;
2786
2787 const size_t N = mOrderedPackages.size();
2788 size_t pi;
2789
2790 const static String16 mipmap16("mipmap");
2791
2792 bool useUTF8 = !bundle->getUTF16StringsOption();
2793
Adam Lesinskide898ff2014-01-29 18:20:45 -08002794 // The libraries this table references.
2795 Vector<sp<Package> > libraryPackages;
Adam Lesinski6022deb2014-08-20 14:59:19 -07002796 const ResTable& table = mAssets->getIncludedResources();
2797 const size_t basePackageCount = table.getBasePackageCount();
2798 for (size_t i = 0; i < basePackageCount; i++) {
2799 size_t packageId = table.getBasePackageId(i);
2800 String16 packageName(table.getBasePackageName(i));
2801 if (packageId > 0x01 && packageId != 0x7f &&
2802 packageName != String16("android")) {
2803 libraryPackages.add(sp<Package>(new Package(packageName, packageId)));
2804 }
2805 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08002806
Adam Lesinski282e1812014-01-23 18:17:42 -08002807 // Iterate through all data, collecting all values (strings,
2808 // references, etc).
2809 StringPool valueStrings(useUTF8);
2810 Vector<sp<Entry> > allEntries;
2811 for (pi=0; pi<N; pi++) {
2812 sp<Package> p = mOrderedPackages.itemAt(pi);
2813 if (p->getTypes().size() == 0) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002814 continue;
2815 }
2816
2817 StringPool typeStrings(useUTF8);
2818 StringPool keyStrings(useUTF8);
2819
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002820 ssize_t stringsAdded = 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08002821 const size_t N = p->getOrderedTypes().size();
2822 for (size_t ti=0; ti<N; ti++) {
2823 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2824 if (t == NULL) {
2825 typeStrings.add(String16("<empty>"), false);
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002826 stringsAdded++;
Adam Lesinski282e1812014-01-23 18:17:42 -08002827 continue;
2828 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002829
2830 while (stringsAdded < t->getIndex() - 1) {
2831 typeStrings.add(String16("<empty>"), false);
2832 stringsAdded++;
2833 }
2834
Adam Lesinski282e1812014-01-23 18:17:42 -08002835 const String16 typeName(t->getName());
2836 typeStrings.add(typeName, false);
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002837 stringsAdded++;
Adam Lesinski282e1812014-01-23 18:17:42 -08002838
2839 // This is a hack to tweak the sorting order of the final strings,
2840 // to put stuff that is generally not language-specific first.
2841 String8 configTypeName(typeName);
2842 if (configTypeName == "drawable" || configTypeName == "layout"
2843 || configTypeName == "color" || configTypeName == "anim"
2844 || configTypeName == "interpolator" || configTypeName == "animator"
2845 || configTypeName == "xml" || configTypeName == "menu"
2846 || configTypeName == "mipmap" || configTypeName == "raw") {
2847 configTypeName = "1complex";
2848 } else {
2849 configTypeName = "2value";
2850 }
2851
Adam Lesinski27f69f42014-08-21 13:19:12 -07002852 // mipmaps don't get filtered, so they will
2853 // allways end up in the base. Make sure they
2854 // don't end up in a split.
2855 if (typeName == mipmap16 && !isBase) {
2856 continue;
2857 }
2858
Adam Lesinski282e1812014-01-23 18:17:42 -08002859 const bool filterable = (typeName != mipmap16);
2860
2861 const size_t N = t->getOrderedConfigs().size();
2862 for (size_t ci=0; ci<N; ci++) {
2863 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2864 if (c == NULL) {
2865 continue;
2866 }
2867 const size_t N = c->getEntries().size();
2868 for (size_t ei=0; ei<N; ei++) {
2869 ConfigDescription config = c->getEntries().keyAt(ei);
Adam Lesinskifab50872014-04-16 14:40:42 -07002870 if (filterable && !filter->match(config)) {
Adam Lesinski282e1812014-01-23 18:17:42 -08002871 continue;
2872 }
2873 sp<Entry> e = c->getEntries().valueAt(ei);
2874 if (e == NULL) {
2875 continue;
2876 }
2877 e->setNameIndex(keyStrings.add(e->getName(), true));
2878
2879 // If this entry has no values for other configs,
2880 // and is the default config, then it is special. Otherwise
2881 // we want to add it with the config info.
2882 ConfigDescription* valueConfig = NULL;
2883 if (N != 1 || config == nullConfig) {
2884 valueConfig = &config;
2885 }
2886
2887 status_t err = e->prepareFlatten(&valueStrings, this,
2888 &configTypeName, &config);
2889 if (err != NO_ERROR) {
2890 return err;
2891 }
2892 allEntries.add(e);
2893 }
2894 }
2895 }
2896
2897 p->setTypeStrings(typeStrings.createStringBlock());
2898 p->setKeyStrings(keyStrings.createStringBlock());
2899 }
2900
2901 if (bundle->getOutputAPKFile() != NULL) {
2902 // Now we want to sort the value strings for better locality. This will
2903 // cause the positions of the strings to change, so we need to go back
2904 // through out resource entries and update them accordingly. Only need
2905 // to do this if actually writing the output file.
2906 valueStrings.sortByConfig();
2907 for (pi=0; pi<allEntries.size(); pi++) {
2908 allEntries[pi]->remapStringValue(&valueStrings);
2909 }
2910 }
2911
2912 ssize_t strAmt = 0;
Adam Lesinskide898ff2014-01-29 18:20:45 -08002913
Adam Lesinski282e1812014-01-23 18:17:42 -08002914 // Now build the array of package chunks.
2915 Vector<sp<AaptFile> > flatPackages;
2916 for (pi=0; pi<N; pi++) {
2917 sp<Package> p = mOrderedPackages.itemAt(pi);
2918 if (p->getTypes().size() == 0) {
2919 // Empty, skip!
2920 continue;
2921 }
2922
2923 const size_t N = p->getTypeStrings().size();
2924
2925 const size_t baseSize = sizeof(ResTable_package);
2926
2927 // Start the package data.
2928 sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
2929 ResTable_package* header = (ResTable_package*)data->editData(baseSize);
2930 if (header == NULL) {
2931 fprintf(stderr, "ERROR: out of memory creating ResTable_package\n");
2932 return NO_MEMORY;
2933 }
2934 memset(header, 0, sizeof(*header));
2935 header->header.type = htods(RES_TABLE_PACKAGE_TYPE);
2936 header->header.headerSize = htods(sizeof(*header));
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002937 header->id = htodl(static_cast<uint32_t>(p->getAssignedId()));
Adam Lesinski282e1812014-01-23 18:17:42 -08002938 strcpy16_htod(header->name, p->getName().string());
2939
2940 // Write the string blocks.
2941 const size_t typeStringsStart = data->getSize();
2942 sp<AaptFile> strFile = p->getTypeStringsData();
2943 ssize_t amt = data->writeData(strFile->getData(), strFile->getSize());
Andreas Gampe2412f842014-09-30 20:55:57 -07002944 if (kPrintStringMetrics) {
2945 fprintf(stderr, "**** type strings: %zd\n", SSIZE(amt));
2946 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002947 strAmt += amt;
2948 if (amt < 0) {
2949 return amt;
2950 }
2951 const size_t keyStringsStart = data->getSize();
2952 strFile = p->getKeyStringsData();
2953 amt = data->writeData(strFile->getData(), strFile->getSize());
Andreas Gampe2412f842014-09-30 20:55:57 -07002954 if (kPrintStringMetrics) {
2955 fprintf(stderr, "**** key strings: %zd\n", SSIZE(amt));
2956 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002957 strAmt += amt;
2958 if (amt < 0) {
2959 return amt;
2960 }
2961
Adam Lesinski27f69f42014-08-21 13:19:12 -07002962 if (isBase) {
2963 status_t err = flattenLibraryTable(data, libraryPackages);
2964 if (err != NO_ERROR) {
2965 fprintf(stderr, "ERROR: failed to write library table\n");
2966 return err;
2967 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08002968 }
2969
Adam Lesinski282e1812014-01-23 18:17:42 -08002970 // Build the type chunks inside of this package.
2971 for (size_t ti=0; ti<N; ti++) {
2972 // Retrieve them in the same order as the type string block.
2973 size_t len;
2974 String16 typeName(p->getTypeStrings().stringAt(ti, &len));
2975 sp<Type> t = p->getTypes().valueFor(typeName);
2976 LOG_ALWAYS_FATAL_IF(t == NULL && typeName != String16("<empty>"),
2977 "Type name %s not found",
2978 String8(typeName).string());
Adam Lesinski833f3cc2014-06-18 15:06:01 -07002979 if (t == NULL) {
2980 continue;
2981 }
Adam Lesinski282e1812014-01-23 18:17:42 -08002982 const bool filterable = (typeName != mipmap16);
Adam Lesinski27f69f42014-08-21 13:19:12 -07002983 const bool skipEntireType = (typeName == mipmap16 && !isBase);
Adam Lesinski282e1812014-01-23 18:17:42 -08002984
2985 const size_t N = t != NULL ? t->getOrderedConfigs().size() : 0;
2986
2987 // Until a non-NO_ENTRY value has been written for a resource,
2988 // that resource is invalid; validResources[i] represents
2989 // the item at t->getOrderedConfigs().itemAt(i).
2990 Vector<bool> validResources;
2991 validResources.insertAt(false, 0, N);
2992
2993 // First write the typeSpec chunk, containing information about
2994 // each resource entry in this type.
2995 {
2996 const size_t typeSpecSize = sizeof(ResTable_typeSpec) + sizeof(uint32_t)*N;
2997 const size_t typeSpecStart = data->getSize();
2998 ResTable_typeSpec* tsHeader = (ResTable_typeSpec*)
2999 (((uint8_t*)data->editData(typeSpecStart+typeSpecSize)) + typeSpecStart);
3000 if (tsHeader == NULL) {
3001 fprintf(stderr, "ERROR: out of memory creating ResTable_typeSpec\n");
3002 return NO_MEMORY;
3003 }
3004 memset(tsHeader, 0, sizeof(*tsHeader));
3005 tsHeader->header.type = htods(RES_TABLE_TYPE_SPEC_TYPE);
3006 tsHeader->header.headerSize = htods(sizeof(*tsHeader));
3007 tsHeader->header.size = htodl(typeSpecSize);
3008 tsHeader->id = ti+1;
3009 tsHeader->entryCount = htodl(N);
3010
3011 uint32_t* typeSpecFlags = (uint32_t*)
3012 (((uint8_t*)data->editData())
3013 + typeSpecStart + sizeof(ResTable_typeSpec));
3014 memset(typeSpecFlags, 0, sizeof(uint32_t)*N);
3015
3016 for (size_t ei=0; ei<N; ei++) {
3017 sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
Adam Lesinski9b624c12014-11-19 17:49:26 -08003018 if (cl == NULL) {
3019 continue;
3020 }
3021
Adam Lesinski282e1812014-01-23 18:17:42 -08003022 if (cl->getPublic()) {
3023 typeSpecFlags[ei] |= htodl(ResTable_typeSpec::SPEC_PUBLIC);
3024 }
Adam Lesinski27f69f42014-08-21 13:19:12 -07003025
3026 if (skipEntireType) {
3027 continue;
3028 }
3029
Adam Lesinski282e1812014-01-23 18:17:42 -08003030 const size_t CN = cl->getEntries().size();
3031 for (size_t ci=0; ci<CN; ci++) {
Adam Lesinskifab50872014-04-16 14:40:42 -07003032 if (filterable && !filter->match(cl->getEntries().keyAt(ci))) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003033 continue;
3034 }
3035 for (size_t cj=ci+1; cj<CN; cj++) {
Adam Lesinskifab50872014-04-16 14:40:42 -07003036 if (filterable && !filter->match(cl->getEntries().keyAt(cj))) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003037 continue;
3038 }
3039 typeSpecFlags[ei] |= htodl(
3040 cl->getEntries().keyAt(ci).diff(cl->getEntries().keyAt(cj)));
3041 }
3042 }
3043 }
3044 }
3045
Adam Lesinski27f69f42014-08-21 13:19:12 -07003046 if (skipEntireType) {
3047 continue;
3048 }
3049
Adam Lesinski282e1812014-01-23 18:17:42 -08003050 // We need to write one type chunk for each configuration for
3051 // which we have entries in this type.
Adam Lesinskie97908d2014-12-05 11:06:21 -08003052 SortedVector<ConfigDescription> uniqueConfigs;
3053 if (t != NULL) {
3054 uniqueConfigs = t->getUniqueConfigs();
3055 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003056
3057 const size_t typeSize = sizeof(ResTable_type) + sizeof(uint32_t)*N;
3058
Adam Lesinskie97908d2014-12-05 11:06:21 -08003059 const size_t NC = uniqueConfigs.size();
Adam Lesinski282e1812014-01-23 18:17:42 -08003060 for (size_t ci=0; ci<NC; ci++) {
Adam Lesinski9b624c12014-11-19 17:49:26 -08003061 const ConfigDescription& config = uniqueConfigs[ci];
Adam Lesinski282e1812014-01-23 18:17:42 -08003062
Andreas Gampe2412f842014-09-30 20:55:57 -07003063 if (kIsDebug) {
3064 printf("Writing config %zu config: imsi:%d/%d lang:%c%c cnt:%c%c "
3065 "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
3066 "sw%ddp w%ddp h%ddp layout:%d\n",
3067 ti + 1,
3068 config.mcc, config.mnc,
3069 config.language[0] ? config.language[0] : '-',
3070 config.language[1] ? config.language[1] : '-',
3071 config.country[0] ? config.country[0] : '-',
3072 config.country[1] ? config.country[1] : '-',
3073 config.orientation,
3074 config.uiMode,
3075 config.touchscreen,
3076 config.density,
3077 config.keyboard,
3078 config.inputFlags,
3079 config.navigation,
3080 config.screenWidth,
3081 config.screenHeight,
3082 config.smallestScreenWidthDp,
3083 config.screenWidthDp,
3084 config.screenHeightDp,
3085 config.screenLayout);
3086 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003087
Adam Lesinskifab50872014-04-16 14:40:42 -07003088 if (filterable && !filter->match(config)) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003089 continue;
3090 }
3091
3092 const size_t typeStart = data->getSize();
3093
3094 ResTable_type* tHeader = (ResTable_type*)
3095 (((uint8_t*)data->editData(typeStart+typeSize)) + typeStart);
3096 if (tHeader == NULL) {
3097 fprintf(stderr, "ERROR: out of memory creating ResTable_type\n");
3098 return NO_MEMORY;
3099 }
3100
3101 memset(tHeader, 0, sizeof(*tHeader));
3102 tHeader->header.type = htods(RES_TABLE_TYPE_TYPE);
3103 tHeader->header.headerSize = htods(sizeof(*tHeader));
3104 tHeader->id = ti+1;
3105 tHeader->entryCount = htodl(N);
3106 tHeader->entriesStart = htodl(typeSize);
3107 tHeader->config = config;
Andreas Gampe2412f842014-09-30 20:55:57 -07003108 if (kIsDebug) {
3109 printf("Writing type %zu config: imsi:%d/%d lang:%c%c cnt:%c%c "
3110 "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
3111 "sw%ddp w%ddp h%ddp layout:%d\n",
3112 ti + 1,
3113 tHeader->config.mcc, tHeader->config.mnc,
3114 tHeader->config.language[0] ? tHeader->config.language[0] : '-',
3115 tHeader->config.language[1] ? tHeader->config.language[1] : '-',
3116 tHeader->config.country[0] ? tHeader->config.country[0] : '-',
3117 tHeader->config.country[1] ? tHeader->config.country[1] : '-',
3118 tHeader->config.orientation,
3119 tHeader->config.uiMode,
3120 tHeader->config.touchscreen,
3121 tHeader->config.density,
3122 tHeader->config.keyboard,
3123 tHeader->config.inputFlags,
3124 tHeader->config.navigation,
3125 tHeader->config.screenWidth,
3126 tHeader->config.screenHeight,
3127 tHeader->config.smallestScreenWidthDp,
3128 tHeader->config.screenWidthDp,
3129 tHeader->config.screenHeightDp,
3130 tHeader->config.screenLayout);
3131 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003132 tHeader->config.swapHtoD();
3133
3134 // Build the entries inside of this type.
3135 for (size_t ei=0; ei<N; ei++) {
3136 sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
Adam Lesinski9b624c12014-11-19 17:49:26 -08003137 sp<Entry> e = NULL;
3138 if (cl != NULL) {
3139 e = cl->getEntries().valueFor(config);
3140 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003141
3142 // Set the offset for this entry in its type.
3143 uint32_t* index = (uint32_t*)
3144 (((uint8_t*)data->editData())
3145 + typeStart + sizeof(ResTable_type));
3146 if (e != NULL) {
3147 index[ei] = htodl(data->getSize()-typeStart-typeSize);
3148
3149 // Create the entry.
3150 ssize_t amt = e->flatten(bundle, data, cl->getPublic());
3151 if (amt < 0) {
3152 return amt;
3153 }
3154 validResources.editItemAt(ei) = true;
3155 } else {
3156 index[ei] = htodl(ResTable_type::NO_ENTRY);
3157 }
3158 }
3159
3160 // Fill in the rest of the type information.
3161 tHeader = (ResTable_type*)
3162 (((uint8_t*)data->editData()) + typeStart);
3163 tHeader->header.size = htodl(data->getSize()-typeStart);
3164 }
3165
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003166 // If we're building splits, then each invocation of the flattening
3167 // step will have 'missing' entries. Don't warn/error for this case.
3168 if (bundle->getSplitConfigurations().isEmpty()) {
3169 bool missing_entry = false;
3170 const char* log_prefix = bundle->getErrorOnMissingConfigEntry() ?
3171 "error" : "warning";
3172 for (size_t i = 0; i < N; ++i) {
3173 if (!validResources[i]) {
3174 sp<ConfigList> c = t->getOrderedConfigs().itemAt(i);
Adam Lesinski9b624c12014-11-19 17:49:26 -08003175 if (c != NULL) {
3176 fprintf(stderr, "%s: no entries written for %s/%s (0x%08x)\n", log_prefix,
3177 String8(typeName).string(), String8(c->getName()).string(),
3178 Res_MAKEID(p->getAssignedId() - 1, ti, i));
3179 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003180 missing_entry = true;
3181 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003182 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07003183 if (bundle->getErrorOnMissingConfigEntry() && missing_entry) {
3184 fprintf(stderr, "Error: Missing entries, quit!\n");
3185 return NOT_ENOUGH_DATA;
3186 }
Ying Wangcd28bd32013-11-14 17:12:10 -08003187 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003188 }
3189
3190 // Fill in the rest of the package information.
3191 header = (ResTable_package*)data->editData();
3192 header->header.size = htodl(data->getSize());
3193 header->typeStrings = htodl(typeStringsStart);
3194 header->lastPublicType = htodl(p->getTypeStrings().size());
3195 header->keyStrings = htodl(keyStringsStart);
3196 header->lastPublicKey = htodl(p->getKeyStrings().size());
3197
3198 flatPackages.add(data);
3199 }
3200
3201 // And now write out the final chunks.
3202 const size_t dataStart = dest->getSize();
3203
3204 {
3205 // blah
3206 ResTable_header header;
3207 memset(&header, 0, sizeof(header));
3208 header.header.type = htods(RES_TABLE_TYPE);
3209 header.header.headerSize = htods(sizeof(header));
3210 header.packageCount = htodl(flatPackages.size());
3211 status_t err = dest->writeData(&header, sizeof(header));
3212 if (err != NO_ERROR) {
3213 fprintf(stderr, "ERROR: out of memory creating ResTable_header\n");
3214 return err;
3215 }
3216 }
3217
3218 ssize_t strStart = dest->getSize();
Adam Lesinskifab50872014-04-16 14:40:42 -07003219 status_t err = valueStrings.writeStringBlock(dest);
Adam Lesinski282e1812014-01-23 18:17:42 -08003220 if (err != NO_ERROR) {
3221 return err;
3222 }
3223
3224 ssize_t amt = (dest->getSize()-strStart);
3225 strAmt += amt;
Andreas Gampe2412f842014-09-30 20:55:57 -07003226 if (kPrintStringMetrics) {
3227 fprintf(stderr, "**** value strings: %zd\n", SSIZE(amt));
3228 fprintf(stderr, "**** total strings: %zd\n", SSIZE(strAmt));
3229 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08003230
Adam Lesinski282e1812014-01-23 18:17:42 -08003231 for (pi=0; pi<flatPackages.size(); pi++) {
3232 err = dest->writeData(flatPackages[pi]->getData(),
3233 flatPackages[pi]->getSize());
3234 if (err != NO_ERROR) {
3235 fprintf(stderr, "ERROR: out of memory creating package chunk for ResTable_header\n");
3236 return err;
3237 }
3238 }
3239
3240 ResTable_header* header = (ResTable_header*)
3241 (((uint8_t*)dest->getData()) + dataStart);
3242 header->header.size = htodl(dest->getSize() - dataStart);
3243
Andreas Gampe2412f842014-09-30 20:55:57 -07003244 if (kPrintStringMetrics) {
3245 fprintf(stderr, "**** total resource table size: %zu / %zu%% strings\n",
3246 dest->getSize(), (size_t)(strAmt*100)/dest->getSize());
3247 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003248
3249 return NO_ERROR;
3250}
3251
Adam Lesinskide898ff2014-01-29 18:20:45 -08003252status_t ResourceTable::flattenLibraryTable(const sp<AaptFile>& dest, const Vector<sp<Package> >& libs) {
3253 // Write out the library table if necessary
3254 if (libs.size() > 0) {
Andreas Gampe87332a72014-10-01 22:03:58 -07003255 if (kIsDebug) {
3256 fprintf(stderr, "Writing library reference table\n");
3257 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08003258
3259 const size_t libStart = dest->getSize();
3260 const size_t count = libs.size();
Adam Lesinski6022deb2014-08-20 14:59:19 -07003261 ResTable_lib_header* libHeader = (ResTable_lib_header*) dest->editDataInRange(
3262 libStart, sizeof(ResTable_lib_header));
Adam Lesinskide898ff2014-01-29 18:20:45 -08003263
3264 memset(libHeader, 0, sizeof(*libHeader));
3265 libHeader->header.type = htods(RES_TABLE_LIBRARY_TYPE);
3266 libHeader->header.headerSize = htods(sizeof(*libHeader));
3267 libHeader->header.size = htodl(sizeof(*libHeader) + (sizeof(ResTable_lib_entry) * count));
3268 libHeader->count = htodl(count);
3269
3270 // Write the library entries
3271 for (size_t i = 0; i < count; i++) {
3272 const size_t entryStart = dest->getSize();
3273 sp<Package> libPackage = libs[i];
Andreas Gampe87332a72014-10-01 22:03:58 -07003274 if (kIsDebug) {
3275 fprintf(stderr, " Entry %s -> 0x%02x\n",
Adam Lesinskide898ff2014-01-29 18:20:45 -08003276 String8(libPackage->getName()).string(),
Andreas Gampe87332a72014-10-01 22:03:58 -07003277 (uint8_t)libPackage->getAssignedId());
3278 }
Adam Lesinskide898ff2014-01-29 18:20:45 -08003279
Adam Lesinski6022deb2014-08-20 14:59:19 -07003280 ResTable_lib_entry* entry = (ResTable_lib_entry*) dest->editDataInRange(
3281 entryStart, sizeof(ResTable_lib_entry));
Adam Lesinskide898ff2014-01-29 18:20:45 -08003282 memset(entry, 0, sizeof(*entry));
3283 entry->packageId = htodl(libPackage->getAssignedId());
3284 strcpy16_htod(entry->packageName, libPackage->getName().string());
3285 }
3286 }
3287 return NO_ERROR;
3288}
3289
Adam Lesinski282e1812014-01-23 18:17:42 -08003290void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp)
3291{
3292 fprintf(fp,
3293 "<!-- This file contains <public> resource definitions for all\n"
3294 " resources that were generated from the source data. -->\n"
3295 "\n"
3296 "<resources>\n");
3297
3298 writePublicDefinitions(package, fp, true);
3299 writePublicDefinitions(package, fp, false);
3300
3301 fprintf(fp,
3302 "\n"
3303 "</resources>\n");
3304}
3305
3306void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp, bool pub)
3307{
3308 bool didHeader = false;
3309
3310 sp<Package> pkg = mPackages.valueFor(package);
3311 if (pkg != NULL) {
3312 const size_t NT = pkg->getOrderedTypes().size();
3313 for (size_t i=0; i<NT; i++) {
3314 sp<Type> t = pkg->getOrderedTypes().itemAt(i);
3315 if (t == NULL) {
3316 continue;
3317 }
3318
3319 bool didType = false;
3320
3321 const size_t NC = t->getOrderedConfigs().size();
3322 for (size_t j=0; j<NC; j++) {
3323 sp<ConfigList> c = t->getOrderedConfigs().itemAt(j);
3324 if (c == NULL) {
3325 continue;
3326 }
3327
3328 if (c->getPublic() != pub) {
3329 continue;
3330 }
3331
3332 if (!didType) {
3333 fprintf(fp, "\n");
3334 didType = true;
3335 }
3336 if (!didHeader) {
3337 if (pub) {
3338 fprintf(fp," <!-- PUBLIC SECTION. These resources have been declared public.\n");
3339 fprintf(fp," Changes to these definitions will break binary compatibility. -->\n\n");
3340 } else {
3341 fprintf(fp," <!-- PRIVATE SECTION. These resources have not been declared public.\n");
3342 fprintf(fp," You can make them public my moving these lines into a file in res/values. -->\n\n");
3343 }
3344 didHeader = true;
3345 }
3346 if (!pub) {
3347 const size_t NE = c->getEntries().size();
3348 for (size_t k=0; k<NE; k++) {
3349 const SourcePos& pos = c->getEntries().valueAt(k)->getPos();
3350 if (pos.file != "") {
3351 fprintf(fp," <!-- Declared at %s:%d -->\n",
3352 pos.file.string(), pos.line);
3353 }
3354 }
3355 }
3356 fprintf(fp, " <public type=\"%s\" name=\"%s\" id=\"0x%08x\" />\n",
3357 String8(t->getName()).string(),
3358 String8(c->getName()).string(),
3359 getResId(pkg, t, c->getEntryIndex()));
3360 }
3361 }
3362 }
3363}
3364
3365ResourceTable::Item::Item(const SourcePos& _sourcePos,
3366 bool _isId,
3367 const String16& _value,
3368 const Vector<StringPool::entry_style_span>* _style,
3369 int32_t _format)
3370 : sourcePos(_sourcePos)
3371 , isId(_isId)
3372 , value(_value)
3373 , format(_format)
3374 , bagKeyId(0)
3375 , evaluating(false)
3376{
3377 if (_style) {
3378 style = *_style;
3379 }
3380}
3381
Adam Lesinski82a2dd82014-09-17 18:34:15 -07003382ResourceTable::Entry::Entry(const Entry& entry)
3383 : RefBase()
3384 , mName(entry.mName)
3385 , mParent(entry.mParent)
3386 , mType(entry.mType)
3387 , mItem(entry.mItem)
3388 , mItemFormat(entry.mItemFormat)
3389 , mBag(entry.mBag)
3390 , mNameIndex(entry.mNameIndex)
3391 , mParentId(entry.mParentId)
3392 , mPos(entry.mPos) {}
3393
Adam Lesinski978ab9d2014-09-24 19:02:52 -07003394ResourceTable::Entry& ResourceTable::Entry::operator=(const Entry& entry) {
3395 mName = entry.mName;
3396 mParent = entry.mParent;
3397 mType = entry.mType;
3398 mItem = entry.mItem;
3399 mItemFormat = entry.mItemFormat;
3400 mBag = entry.mBag;
3401 mNameIndex = entry.mNameIndex;
3402 mParentId = entry.mParentId;
3403 mPos = entry.mPos;
3404 return *this;
3405}
3406
Adam Lesinski282e1812014-01-23 18:17:42 -08003407status_t ResourceTable::Entry::makeItABag(const SourcePos& sourcePos)
3408{
3409 if (mType == TYPE_BAG) {
3410 return NO_ERROR;
3411 }
3412 if (mType == TYPE_UNKNOWN) {
3413 mType = TYPE_BAG;
3414 return NO_ERROR;
3415 }
3416 sourcePos.error("Resource entry %s is already defined as a single item.\n"
3417 "%s:%d: Originally defined here.\n",
3418 String8(mName).string(),
3419 mItem.sourcePos.file.string(), mItem.sourcePos.line);
3420 return UNKNOWN_ERROR;
3421}
3422
3423status_t ResourceTable::Entry::setItem(const SourcePos& sourcePos,
3424 const String16& value,
3425 const Vector<StringPool::entry_style_span>* style,
3426 int32_t format,
3427 const bool overwrite)
3428{
3429 Item item(sourcePos, false, value, style);
3430
3431 if (mType == TYPE_BAG) {
Adam Lesinski43a0df02014-08-18 17:14:57 -07003432 if (mBag.size() == 0) {
3433 sourcePos.error("Resource entry %s is already defined as a bag.",
3434 String8(mName).string());
3435 } else {
3436 const Item& item(mBag.valueAt(0));
3437 sourcePos.error("Resource entry %s is already defined as a bag.\n"
3438 "%s:%d: Originally defined here.\n",
3439 String8(mName).string(),
3440 item.sourcePos.file.string(), item.sourcePos.line);
3441 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003442 return UNKNOWN_ERROR;
3443 }
3444 if ( (mType != TYPE_UNKNOWN) && (overwrite == false) ) {
3445 sourcePos.error("Resource entry %s is already defined.\n"
3446 "%s:%d: Originally defined here.\n",
3447 String8(mName).string(),
3448 mItem.sourcePos.file.string(), mItem.sourcePos.line);
3449 return UNKNOWN_ERROR;
3450 }
3451
3452 mType = TYPE_ITEM;
3453 mItem = item;
3454 mItemFormat = format;
3455 return NO_ERROR;
3456}
3457
3458status_t ResourceTable::Entry::addToBag(const SourcePos& sourcePos,
3459 const String16& key, const String16& value,
3460 const Vector<StringPool::entry_style_span>* style,
3461 bool replace, bool isId, int32_t format)
3462{
3463 status_t err = makeItABag(sourcePos);
3464 if (err != NO_ERROR) {
3465 return err;
3466 }
3467
3468 Item item(sourcePos, isId, value, style, format);
3469
3470 // XXX NOTE: there is an error if you try to have a bag with two keys,
3471 // one an attr and one an id, with the same name. Not something we
3472 // currently ever have to worry about.
3473 ssize_t origKey = mBag.indexOfKey(key);
3474 if (origKey >= 0) {
3475 if (!replace) {
3476 const Item& item(mBag.valueAt(origKey));
3477 sourcePos.error("Resource entry %s already has bag item %s.\n"
3478 "%s:%d: Originally defined here.\n",
3479 String8(mName).string(), String8(key).string(),
3480 item.sourcePos.file.string(), item.sourcePos.line);
3481 return UNKNOWN_ERROR;
3482 }
3483 //printf("Replacing %s with %s\n",
3484 // String8(mBag.valueFor(key).value).string(), String8(value).string());
3485 mBag.replaceValueFor(key, item);
3486 }
3487
3488 mBag.add(key, item);
3489 return NO_ERROR;
3490}
3491
Adam Lesinski82a2dd82014-09-17 18:34:15 -07003492status_t ResourceTable::Entry::removeFromBag(const String16& key) {
3493 if (mType != Entry::TYPE_BAG) {
3494 return NO_ERROR;
3495 }
3496
3497 if (mBag.removeItem(key) >= 0) {
3498 return NO_ERROR;
3499 }
3500 return UNKNOWN_ERROR;
3501}
3502
Adam Lesinski282e1812014-01-23 18:17:42 -08003503status_t ResourceTable::Entry::emptyBag(const SourcePos& sourcePos)
3504{
3505 status_t err = makeItABag(sourcePos);
3506 if (err != NO_ERROR) {
3507 return err;
3508 }
3509
3510 mBag.clear();
3511 return NO_ERROR;
3512}
3513
3514status_t ResourceTable::Entry::generateAttributes(ResourceTable* table,
3515 const String16& package)
3516{
3517 const String16 attr16("attr");
3518 const String16 id16("id");
3519 const size_t N = mBag.size();
3520 for (size_t i=0; i<N; i++) {
3521 const String16& key = mBag.keyAt(i);
3522 const Item& it = mBag.valueAt(i);
3523 if (it.isId) {
3524 if (!table->hasBagOrEntry(key, &id16, &package)) {
3525 String16 value("false");
Andreas Gampe87332a72014-10-01 22:03:58 -07003526 if (kIsDebug) {
3527 fprintf(stderr, "Generating %s:id/%s\n",
3528 String8(package).string(),
3529 String8(key).string());
3530 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003531 status_t err = table->addEntry(SourcePos(String8("<generated>"), 0), package,
3532 id16, key, value);
3533 if (err != NO_ERROR) {
3534 return err;
3535 }
3536 }
3537 } else if (!table->hasBagOrEntry(key, &attr16, &package)) {
3538
3539#if 1
3540// fprintf(stderr, "ERROR: Bag attribute '%s' has not been defined.\n",
3541// String8(key).string());
3542// const Item& item(mBag.valueAt(i));
3543// fprintf(stderr, "Referenced from file %s line %d\n",
3544// item.sourcePos.file.string(), item.sourcePos.line);
3545// return UNKNOWN_ERROR;
3546#else
3547 char numberStr[16];
3548 sprintf(numberStr, "%d", ResTable_map::TYPE_ANY);
3549 status_t err = table->addBag(SourcePos("<generated>", 0), package,
3550 attr16, key, String16(""),
3551 String16("^type"),
3552 String16(numberStr), NULL, NULL);
3553 if (err != NO_ERROR) {
3554 return err;
3555 }
3556#endif
3557 }
3558 }
3559 return NO_ERROR;
3560}
3561
3562status_t ResourceTable::Entry::assignResourceIds(ResourceTable* table,
Andreas Gampe2412f842014-09-30 20:55:57 -07003563 const String16& /* package */)
Adam Lesinski282e1812014-01-23 18:17:42 -08003564{
3565 bool hasErrors = false;
3566
3567 if (mType == TYPE_BAG) {
3568 const char* errorMsg;
3569 const String16 style16("style");
3570 const String16 attr16("attr");
3571 const String16 id16("id");
3572 mParentId = 0;
3573 if (mParent.size() > 0) {
3574 mParentId = table->getResId(mParent, &style16, NULL, &errorMsg);
3575 if (mParentId == 0) {
3576 mPos.error("Error retrieving parent for item: %s '%s'.\n",
3577 errorMsg, String8(mParent).string());
3578 hasErrors = true;
3579 }
3580 }
3581 const size_t N = mBag.size();
3582 for (size_t i=0; i<N; i++) {
3583 const String16& key = mBag.keyAt(i);
3584 Item& it = mBag.editValueAt(i);
3585 it.bagKeyId = table->getResId(key,
3586 it.isId ? &id16 : &attr16, NULL, &errorMsg);
3587 //printf("Bag key of %s: #%08x\n", String8(key).string(), it.bagKeyId);
3588 if (it.bagKeyId == 0) {
3589 it.sourcePos.error("Error: %s: %s '%s'.\n", errorMsg,
3590 String8(it.isId ? id16 : attr16).string(),
3591 String8(key).string());
3592 hasErrors = true;
3593 }
3594 }
3595 }
Andreas Gampe2412f842014-09-30 20:55:57 -07003596 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08003597}
3598
3599status_t ResourceTable::Entry::prepareFlatten(StringPool* strings, ResourceTable* table,
3600 const String8* configTypeName, const ConfigDescription* config)
3601{
3602 if (mType == TYPE_ITEM) {
3603 Item& it = mItem;
3604 AccessorCookie ac(it.sourcePos, String8(mName), String8(it.value));
3605 if (!table->stringToValue(&it.parsedValue, strings,
3606 it.value, false, true, 0,
3607 &it.style, NULL, &ac, mItemFormat,
3608 configTypeName, config)) {
3609 return UNKNOWN_ERROR;
3610 }
3611 } else if (mType == TYPE_BAG) {
3612 const size_t N = mBag.size();
3613 for (size_t i=0; i<N; i++) {
3614 const String16& key = mBag.keyAt(i);
3615 Item& it = mBag.editValueAt(i);
3616 AccessorCookie ac(it.sourcePos, String8(key), String8(it.value));
3617 if (!table->stringToValue(&it.parsedValue, strings,
3618 it.value, false, true, it.bagKeyId,
3619 &it.style, NULL, &ac, it.format,
3620 configTypeName, config)) {
3621 return UNKNOWN_ERROR;
3622 }
3623 }
3624 } else {
3625 mPos.error("Error: entry %s is not a single item or a bag.\n",
3626 String8(mName).string());
3627 return UNKNOWN_ERROR;
3628 }
3629 return NO_ERROR;
3630}
3631
3632status_t ResourceTable::Entry::remapStringValue(StringPool* strings)
3633{
3634 if (mType == TYPE_ITEM) {
3635 Item& it = mItem;
3636 if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3637 it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3638 }
3639 } else if (mType == TYPE_BAG) {
3640 const size_t N = mBag.size();
3641 for (size_t i=0; i<N; i++) {
3642 Item& it = mBag.editValueAt(i);
3643 if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3644 it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3645 }
3646 }
3647 } else {
3648 mPos.error("Error: entry %s is not a single item or a bag.\n",
3649 String8(mName).string());
3650 return UNKNOWN_ERROR;
3651 }
3652 return NO_ERROR;
3653}
3654
Andreas Gampe2412f842014-09-30 20:55:57 -07003655ssize_t ResourceTable::Entry::flatten(Bundle* /* bundle */, const sp<AaptFile>& data, bool isPublic)
Adam Lesinski282e1812014-01-23 18:17:42 -08003656{
3657 size_t amt = 0;
3658 ResTable_entry header;
3659 memset(&header, 0, sizeof(header));
3660 header.size = htods(sizeof(header));
Andreas Gampe2412f842014-09-30 20:55:57 -07003661 const type ty = mType;
3662 if (ty == TYPE_BAG) {
3663 header.flags |= htods(header.FLAG_COMPLEX);
Adam Lesinski282e1812014-01-23 18:17:42 -08003664 }
Andreas Gampe2412f842014-09-30 20:55:57 -07003665 if (isPublic) {
3666 header.flags |= htods(header.FLAG_PUBLIC);
3667 }
3668 header.key.index = htodl(mNameIndex);
Adam Lesinski282e1812014-01-23 18:17:42 -08003669 if (ty != TYPE_BAG) {
3670 status_t err = data->writeData(&header, sizeof(header));
3671 if (err != NO_ERROR) {
3672 fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3673 return err;
3674 }
3675
3676 const Item& it = mItem;
3677 Res_value par;
3678 memset(&par, 0, sizeof(par));
3679 par.size = htods(it.parsedValue.size);
3680 par.dataType = it.parsedValue.dataType;
3681 par.res0 = it.parsedValue.res0;
3682 par.data = htodl(it.parsedValue.data);
3683 #if 0
3684 printf("Writing item (%s): type=%d, data=0x%x, res0=0x%x\n",
3685 String8(mName).string(), it.parsedValue.dataType,
3686 it.parsedValue.data, par.res0);
3687 #endif
3688 err = data->writeData(&par, it.parsedValue.size);
3689 if (err != NO_ERROR) {
3690 fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3691 return err;
3692 }
3693 amt += it.parsedValue.size;
3694 } else {
3695 size_t N = mBag.size();
3696 size_t i;
3697 // Create correct ordering of items.
3698 KeyedVector<uint32_t, const Item*> items;
3699 for (i=0; i<N; i++) {
3700 const Item& it = mBag.valueAt(i);
3701 items.add(it.bagKeyId, &it);
3702 }
3703 N = items.size();
3704
3705 ResTable_map_entry mapHeader;
3706 memcpy(&mapHeader, &header, sizeof(header));
3707 mapHeader.size = htods(sizeof(mapHeader));
3708 mapHeader.parent.ident = htodl(mParentId);
3709 mapHeader.count = htodl(N);
3710 status_t err = data->writeData(&mapHeader, sizeof(mapHeader));
3711 if (err != NO_ERROR) {
3712 fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3713 return err;
3714 }
3715
3716 for (i=0; i<N; i++) {
3717 const Item& it = *items.valueAt(i);
3718 ResTable_map map;
3719 map.name.ident = htodl(it.bagKeyId);
3720 map.value.size = htods(it.parsedValue.size);
3721 map.value.dataType = it.parsedValue.dataType;
3722 map.value.res0 = it.parsedValue.res0;
3723 map.value.data = htodl(it.parsedValue.data);
3724 err = data->writeData(&map, sizeof(map));
3725 if (err != NO_ERROR) {
3726 fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3727 return err;
3728 }
3729 amt += sizeof(map);
3730 }
3731 }
3732 return amt;
3733}
3734
3735void ResourceTable::ConfigList::appendComment(const String16& comment,
3736 bool onlyIfEmpty)
3737{
3738 if (comment.size() <= 0) {
3739 return;
3740 }
3741 if (onlyIfEmpty && mComment.size() > 0) {
3742 return;
3743 }
3744 if (mComment.size() > 0) {
3745 mComment.append(String16("\n"));
3746 }
3747 mComment.append(comment);
3748}
3749
3750void ResourceTable::ConfigList::appendTypeComment(const String16& comment)
3751{
3752 if (comment.size() <= 0) {
3753 return;
3754 }
3755 if (mTypeComment.size() > 0) {
3756 mTypeComment.append(String16("\n"));
3757 }
3758 mTypeComment.append(comment);
3759}
3760
3761status_t ResourceTable::Type::addPublic(const SourcePos& sourcePos,
3762 const String16& name,
3763 const uint32_t ident)
3764{
3765 #if 0
3766 int32_t entryIdx = Res_GETENTRY(ident);
3767 if (entryIdx < 0) {
3768 sourcePos.error("Public resource %s/%s has an invalid 0 identifier (0x%08x).\n",
3769 String8(mName).string(), String8(name).string(), ident);
3770 return UNKNOWN_ERROR;
3771 }
3772 #endif
3773
3774 int32_t typeIdx = Res_GETTYPE(ident);
3775 if (typeIdx >= 0) {
3776 typeIdx++;
3777 if (mPublicIndex > 0 && mPublicIndex != typeIdx) {
3778 sourcePos.error("Public resource %s/%s has conflicting type codes for its"
3779 " public identifiers (0x%x vs 0x%x).\n",
3780 String8(mName).string(), String8(name).string(),
3781 mPublicIndex, typeIdx);
3782 return UNKNOWN_ERROR;
3783 }
3784 mPublicIndex = typeIdx;
3785 }
3786
3787 if (mFirstPublicSourcePos == NULL) {
3788 mFirstPublicSourcePos = new SourcePos(sourcePos);
3789 }
3790
3791 if (mPublic.indexOfKey(name) < 0) {
3792 mPublic.add(name, Public(sourcePos, String16(), ident));
3793 } else {
3794 Public& p = mPublic.editValueFor(name);
3795 if (p.ident != ident) {
3796 sourcePos.error("Public resource %s/%s has conflicting public identifiers"
3797 " (0x%08x vs 0x%08x).\n"
3798 "%s:%d: Originally defined here.\n",
3799 String8(mName).string(), String8(name).string(), p.ident, ident,
3800 p.sourcePos.file.string(), p.sourcePos.line);
3801 return UNKNOWN_ERROR;
3802 }
3803 }
3804
3805 return NO_ERROR;
3806}
3807
3808void ResourceTable::Type::canAddEntry(const String16& name)
3809{
3810 mCanAddEntries.add(name);
3811}
3812
3813sp<ResourceTable::Entry> ResourceTable::Type::getEntry(const String16& entry,
3814 const SourcePos& sourcePos,
3815 const ResTable_config* config,
3816 bool doSetIndex,
3817 bool overlay,
3818 bool autoAddOverlay)
3819{
3820 int pos = -1;
3821 sp<ConfigList> c = mConfigs.valueFor(entry);
3822 if (c == NULL) {
3823 if (overlay && !autoAddOverlay && mCanAddEntries.indexOf(entry) < 0) {
3824 sourcePos.error("Resource at %s appears in overlay but not"
3825 " in the base package; use <add-resource> to add.\n",
3826 String8(entry).string());
3827 return NULL;
3828 }
3829 c = new ConfigList(entry, sourcePos);
3830 mConfigs.add(entry, c);
3831 pos = (int)mOrderedConfigs.size();
3832 mOrderedConfigs.add(c);
3833 if (doSetIndex) {
3834 c->setEntryIndex(pos);
3835 }
3836 }
3837
3838 ConfigDescription cdesc;
3839 if (config) cdesc = *config;
3840
3841 sp<Entry> e = c->getEntries().valueFor(cdesc);
3842 if (e == NULL) {
Andreas Gampe2412f842014-09-30 20:55:57 -07003843 if (kIsDebug) {
3844 if (config != NULL) {
3845 printf("New entry at %s:%d: imsi:%d/%d lang:%c%c cnt:%c%c "
Adam Lesinski282e1812014-01-23 18:17:42 -08003846 "orien:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
Andreas Gampe2412f842014-09-30 20:55:57 -07003847 "sw%ddp w%ddp h%ddp layout:%d\n",
Adam Lesinski282e1812014-01-23 18:17:42 -08003848 sourcePos.file.string(), sourcePos.line,
3849 config->mcc, config->mnc,
3850 config->language[0] ? config->language[0] : '-',
3851 config->language[1] ? config->language[1] : '-',
3852 config->country[0] ? config->country[0] : '-',
3853 config->country[1] ? config->country[1] : '-',
3854 config->orientation,
3855 config->touchscreen,
3856 config->density,
3857 config->keyboard,
3858 config->inputFlags,
3859 config->navigation,
3860 config->screenWidth,
3861 config->screenHeight,
3862 config->smallestScreenWidthDp,
3863 config->screenWidthDp,
3864 config->screenHeightDp,
Andreas Gampe2412f842014-09-30 20:55:57 -07003865 config->screenLayout);
3866 } else {
3867 printf("New entry at %s:%d: NULL config\n",
3868 sourcePos.file.string(), sourcePos.line);
3869 }
Adam Lesinski282e1812014-01-23 18:17:42 -08003870 }
3871 e = new Entry(entry, sourcePos);
3872 c->addEntry(cdesc, e);
3873 /*
3874 if (doSetIndex) {
3875 if (pos < 0) {
3876 for (pos=0; pos<(int)mOrderedConfigs.size(); pos++) {
3877 if (mOrderedConfigs[pos] == c) {
3878 break;
3879 }
3880 }
3881 if (pos >= (int)mOrderedConfigs.size()) {
3882 sourcePos.error("Internal error: config not found in mOrderedConfigs when adding entry");
3883 return NULL;
3884 }
3885 }
3886 e->setEntryIndex(pos);
3887 }
3888 */
3889 }
3890
Adam Lesinski282e1812014-01-23 18:17:42 -08003891 return e;
3892}
3893
Adam Lesinski9b624c12014-11-19 17:49:26 -08003894sp<ResourceTable::ConfigList> ResourceTable::Type::removeEntry(const String16& entry) {
3895 ssize_t idx = mConfigs.indexOfKey(entry);
3896 if (idx < 0) {
3897 return NULL;
3898 }
3899
3900 sp<ConfigList> removed = mConfigs.valueAt(idx);
3901 mConfigs.removeItemsAt(idx);
3902
3903 Vector<sp<ConfigList> >::iterator iter = std::find(
3904 mOrderedConfigs.begin(), mOrderedConfigs.end(), removed);
3905 if (iter != mOrderedConfigs.end()) {
3906 mOrderedConfigs.erase(iter);
3907 }
3908
3909 mPublic.removeItem(entry);
3910 return removed;
3911}
3912
3913SortedVector<ConfigDescription> ResourceTable::Type::getUniqueConfigs() const {
3914 SortedVector<ConfigDescription> unique;
3915 const size_t entryCount = mOrderedConfigs.size();
3916 for (size_t i = 0; i < entryCount; i++) {
3917 if (mOrderedConfigs[i] == NULL) {
3918 continue;
3919 }
3920 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& configs =
3921 mOrderedConfigs[i]->getEntries();
3922 const size_t configCount = configs.size();
3923 for (size_t j = 0; j < configCount; j++) {
3924 unique.add(configs.keyAt(j));
3925 }
3926 }
3927 return unique;
3928}
3929
Adam Lesinski282e1812014-01-23 18:17:42 -08003930status_t ResourceTable::Type::applyPublicEntryOrder()
3931{
3932 size_t N = mOrderedConfigs.size();
3933 Vector<sp<ConfigList> > origOrder(mOrderedConfigs);
3934 bool hasError = false;
3935
3936 size_t i;
3937 for (i=0; i<N; i++) {
3938 mOrderedConfigs.replaceAt(NULL, i);
3939 }
3940
3941 const size_t NP = mPublic.size();
3942 //printf("Ordering %d configs from %d public defs\n", N, NP);
3943 size_t j;
3944 for (j=0; j<NP; j++) {
3945 const String16& name = mPublic.keyAt(j);
3946 const Public& p = mPublic.valueAt(j);
3947 int32_t idx = Res_GETENTRY(p.ident);
3948 //printf("Looking for entry \"%s\"/\"%s\" (0x%08x) in %d...\n",
3949 // String8(mName).string(), String8(name).string(), p.ident, N);
3950 bool found = false;
3951 for (i=0; i<N; i++) {
3952 sp<ConfigList> e = origOrder.itemAt(i);
3953 //printf("#%d: \"%s\"\n", i, String8(e->getName()).string());
3954 if (e->getName() == name) {
3955 if (idx >= (int32_t)mOrderedConfigs.size()) {
Adam Lesinski9b624c12014-11-19 17:49:26 -08003956 mOrderedConfigs.resize(idx + 1);
3957 }
3958
3959 if (mOrderedConfigs.itemAt(idx) == NULL) {
Adam Lesinski282e1812014-01-23 18:17:42 -08003960 e->setPublic(true);
3961 e->setPublicSourcePos(p.sourcePos);
3962 mOrderedConfigs.replaceAt(e, idx);
3963 origOrder.removeAt(i);
3964 N--;
3965 found = true;
3966 break;
3967 } else {
3968 sp<ConfigList> oe = mOrderedConfigs.itemAt(idx);
3969
3970 p.sourcePos.error("Multiple entry names declared for public entry"
3971 " identifier 0x%x in type %s (%s vs %s).\n"
3972 "%s:%d: Originally defined here.",
3973 idx+1, String8(mName).string(),
3974 String8(oe->getName()).string(),
3975 String8(name).string(),
3976 oe->getPublicSourcePos().file.string(),
3977 oe->getPublicSourcePos().line);
3978 hasError = true;
3979 }
3980 }
3981 }
3982
3983 if (!found) {
3984 p.sourcePos.error("Public symbol %s/%s declared here is not defined.",
3985 String8(mName).string(), String8(name).string());
3986 hasError = true;
3987 }
3988 }
3989
3990 //printf("Copying back in %d non-public configs, have %d\n", N, origOrder.size());
3991
3992 if (N != origOrder.size()) {
3993 printf("Internal error: remaining private symbol count mismatch\n");
3994 N = origOrder.size();
3995 }
3996
3997 j = 0;
3998 for (i=0; i<N; i++) {
3999 sp<ConfigList> e = origOrder.itemAt(i);
4000 // There will always be enough room for the remaining entries.
4001 while (mOrderedConfigs.itemAt(j) != NULL) {
4002 j++;
4003 }
4004 mOrderedConfigs.replaceAt(e, j);
4005 j++;
4006 }
4007
Andreas Gampe2412f842014-09-30 20:55:57 -07004008 return hasError ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08004009}
4010
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004011ResourceTable::Package::Package(const String16& name, size_t packageId)
4012 : mName(name), mPackageId(packageId),
Adam Lesinski282e1812014-01-23 18:17:42 -08004013 mTypeStringsMapping(0xffffffff),
4014 mKeyStringsMapping(0xffffffff)
4015{
4016}
4017
4018sp<ResourceTable::Type> ResourceTable::Package::getType(const String16& type,
4019 const SourcePos& sourcePos,
4020 bool doSetIndex)
4021{
4022 sp<Type> t = mTypes.valueFor(type);
4023 if (t == NULL) {
4024 t = new Type(type, sourcePos);
4025 mTypes.add(type, t);
4026 mOrderedTypes.add(t);
4027 if (doSetIndex) {
4028 // For some reason the type's index is set to one plus the index
4029 // in the mOrderedTypes list, rather than just the index.
4030 t->setIndex(mOrderedTypes.size());
4031 }
4032 }
4033 return t;
4034}
4035
4036status_t ResourceTable::Package::setTypeStrings(const sp<AaptFile>& data)
4037{
Adam Lesinski282e1812014-01-23 18:17:42 -08004038 status_t err = setStrings(data, &mTypeStrings, &mTypeStringsMapping);
4039 if (err != NO_ERROR) {
4040 fprintf(stderr, "ERROR: Type string data is corrupt!\n");
Adam Lesinski57079512014-07-29 11:51:35 -07004041 return err;
Adam Lesinski282e1812014-01-23 18:17:42 -08004042 }
Adam Lesinski57079512014-07-29 11:51:35 -07004043
4044 // Retain a reference to the new data after we've successfully replaced
4045 // all uses of the old reference (in setStrings() ).
4046 mTypeStringsData = data;
4047 return NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08004048}
4049
4050status_t ResourceTable::Package::setKeyStrings(const sp<AaptFile>& data)
4051{
Adam Lesinski282e1812014-01-23 18:17:42 -08004052 status_t err = setStrings(data, &mKeyStrings, &mKeyStringsMapping);
4053 if (err != NO_ERROR) {
4054 fprintf(stderr, "ERROR: Key string data is corrupt!\n");
Adam Lesinski57079512014-07-29 11:51:35 -07004055 return err;
Adam Lesinski282e1812014-01-23 18:17:42 -08004056 }
Adam Lesinski57079512014-07-29 11:51:35 -07004057
4058 // Retain a reference to the new data after we've successfully replaced
4059 // all uses of the old reference (in setStrings() ).
4060 mKeyStringsData = data;
4061 return NO_ERROR;
Adam Lesinski282e1812014-01-23 18:17:42 -08004062}
4063
4064status_t ResourceTable::Package::setStrings(const sp<AaptFile>& data,
4065 ResStringPool* strings,
4066 DefaultKeyedVector<String16, uint32_t>* mappings)
4067{
4068 if (data->getData() == NULL) {
4069 return UNKNOWN_ERROR;
4070 }
4071
Adam Lesinski282e1812014-01-23 18:17:42 -08004072 status_t err = strings->setTo(data->getData(), data->getSize());
4073 if (err == NO_ERROR) {
4074 const size_t N = strings->size();
4075 for (size_t i=0; i<N; i++) {
4076 size_t len;
4077 mappings->add(String16(strings->stringAt(i, &len)), i);
4078 }
4079 }
4080 return err;
4081}
4082
4083status_t ResourceTable::Package::applyPublicTypeOrder()
4084{
4085 size_t N = mOrderedTypes.size();
4086 Vector<sp<Type> > origOrder(mOrderedTypes);
4087
4088 size_t i;
4089 for (i=0; i<N; i++) {
4090 mOrderedTypes.replaceAt(NULL, i);
4091 }
4092
4093 for (i=0; i<N; i++) {
4094 sp<Type> t = origOrder.itemAt(i);
4095 int32_t idx = t->getPublicIndex();
4096 if (idx > 0) {
4097 idx--;
4098 while (idx >= (int32_t)mOrderedTypes.size()) {
4099 mOrderedTypes.add();
4100 }
4101 if (mOrderedTypes.itemAt(idx) != NULL) {
4102 sp<Type> ot = mOrderedTypes.itemAt(idx);
4103 t->getFirstPublicSourcePos().error("Multiple type names declared for public type"
4104 " identifier 0x%x (%s vs %s).\n"
4105 "%s:%d: Originally defined here.",
4106 idx, String8(ot->getName()).string(),
4107 String8(t->getName()).string(),
4108 ot->getFirstPublicSourcePos().file.string(),
4109 ot->getFirstPublicSourcePos().line);
4110 return UNKNOWN_ERROR;
4111 }
4112 mOrderedTypes.replaceAt(t, idx);
4113 origOrder.removeAt(i);
4114 i--;
4115 N--;
4116 }
4117 }
4118
4119 size_t j=0;
4120 for (i=0; i<N; i++) {
4121 sp<Type> t = origOrder.itemAt(i);
4122 // There will always be enough room for the remaining types.
4123 while (mOrderedTypes.itemAt(j) != NULL) {
4124 j++;
4125 }
4126 mOrderedTypes.replaceAt(t, j);
4127 }
4128
4129 return NO_ERROR;
4130}
4131
Adam Lesinski9b624c12014-11-19 17:49:26 -08004132void ResourceTable::Package::movePrivateAttrs() {
4133 sp<Type> attr = mTypes.valueFor(String16("attr"));
4134 if (attr == NULL) {
4135 // Nothing to do.
4136 return;
4137 }
4138
4139 Vector<sp<ConfigList> > privateAttrs;
4140
4141 bool hasPublic = false;
4142 const Vector<sp<ConfigList> >& configs = attr->getOrderedConfigs();
4143 const size_t configCount = configs.size();
4144 for (size_t i = 0; i < configCount; i++) {
4145 if (configs[i] == NULL) {
4146 continue;
4147 }
4148
4149 if (attr->isPublic(configs[i]->getName())) {
4150 hasPublic = true;
4151 } else {
4152 privateAttrs.add(configs[i]);
4153 }
4154 }
4155
4156 // Only if we have public attributes do we create a separate type for
4157 // private attributes.
4158 if (!hasPublic) {
4159 return;
4160 }
4161
4162 // Create a new type for private attributes.
4163 sp<Type> privateAttrType = getType(String16(kAttrPrivateType), SourcePos());
4164
4165 const size_t privateAttrCount = privateAttrs.size();
4166 for (size_t i = 0; i < privateAttrCount; i++) {
4167 const sp<ConfigList>& cl = privateAttrs[i];
4168
4169 // Remove the private attributes from their current type.
4170 attr->removeEntry(cl->getName());
4171
4172 // Add it to the new type.
4173 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& entries = cl->getEntries();
4174 const size_t entryCount = entries.size();
4175 for (size_t j = 0; j < entryCount; j++) {
4176 const sp<Entry>& oldEntry = entries[j];
4177 sp<Entry> entry = privateAttrType->getEntry(
4178 cl->getName(), oldEntry->getPos(), &entries.keyAt(j));
4179 *entry = *oldEntry;
4180 }
4181
4182 // Move the symbols to the new type.
4183
4184 }
4185}
4186
Adam Lesinski282e1812014-01-23 18:17:42 -08004187sp<ResourceTable::Package> ResourceTable::getPackage(const String16& package)
4188{
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004189 if (package != mAssetsPackage) {
4190 return NULL;
Adam Lesinski282e1812014-01-23 18:17:42 -08004191 }
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004192 return mPackages.valueFor(package);
Adam Lesinski282e1812014-01-23 18:17:42 -08004193}
4194
4195sp<ResourceTable::Type> ResourceTable::getType(const String16& package,
4196 const String16& type,
4197 const SourcePos& sourcePos,
4198 bool doSetIndex)
4199{
4200 sp<Package> p = getPackage(package);
4201 if (p == NULL) {
4202 return NULL;
4203 }
4204 return p->getType(type, sourcePos, doSetIndex);
4205}
4206
4207sp<ResourceTable::Entry> ResourceTable::getEntry(const String16& package,
4208 const String16& type,
4209 const String16& name,
4210 const SourcePos& sourcePos,
4211 bool overlay,
4212 const ResTable_config* config,
4213 bool doSetIndex)
4214{
4215 sp<Type> t = getType(package, type, sourcePos, doSetIndex);
4216 if (t == NULL) {
4217 return NULL;
4218 }
4219 return t->getEntry(name, sourcePos, config, doSetIndex, overlay, mBundle->getAutoAddOverlay());
4220}
4221
Adam Lesinskie572c012014-09-19 15:10:04 -07004222sp<ResourceTable::ConfigList> ResourceTable::getConfigList(const String16& package,
4223 const String16& type, const String16& name) const
4224{
4225 const size_t packageCount = mOrderedPackages.size();
4226 for (size_t pi = 0; pi < packageCount; pi++) {
4227 const sp<Package>& p = mOrderedPackages[pi];
4228 if (p == NULL || p->getName() != package) {
4229 continue;
4230 }
4231
4232 const Vector<sp<Type> >& types = p->getOrderedTypes();
4233 const size_t typeCount = types.size();
4234 for (size_t ti = 0; ti < typeCount; ti++) {
4235 const sp<Type>& t = types[ti];
4236 if (t == NULL || t->getName() != type) {
4237 continue;
4238 }
4239
4240 const Vector<sp<ConfigList> >& configs = t->getOrderedConfigs();
4241 const size_t configCount = configs.size();
4242 for (size_t ci = 0; ci < configCount; ci++) {
4243 const sp<ConfigList>& cl = configs[ci];
4244 if (cl == NULL || cl->getName() != name) {
4245 continue;
4246 }
4247
4248 return cl;
4249 }
4250 }
4251 }
4252 return NULL;
4253}
4254
Adam Lesinski282e1812014-01-23 18:17:42 -08004255sp<const ResourceTable::Entry> ResourceTable::getEntry(uint32_t resID,
4256 const ResTable_config* config) const
4257{
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004258 size_t pid = Res_GETPACKAGE(resID)+1;
Adam Lesinski282e1812014-01-23 18:17:42 -08004259 const size_t N = mOrderedPackages.size();
Adam Lesinski282e1812014-01-23 18:17:42 -08004260 sp<Package> p;
Adam Lesinski833f3cc2014-06-18 15:06:01 -07004261 for (size_t i = 0; i < N; i++) {
Adam Lesinski282e1812014-01-23 18:17:42 -08004262 sp<Package> check = mOrderedPackages[i];
4263 if (check->getAssignedId() == pid) {
4264 p = check;
4265 break;
4266 }
4267
4268 }
4269 if (p == NULL) {
4270 fprintf(stderr, "warning: Package not found for resource #%08x\n", resID);
4271 return NULL;
4272 }
4273
4274 int tid = Res_GETTYPE(resID);
4275 if (tid < 0 || tid >= (int)p->getOrderedTypes().size()) {
4276 fprintf(stderr, "warning: Type not found for resource #%08x\n", resID);
4277 return NULL;
4278 }
4279 sp<Type> t = p->getOrderedTypes()[tid];
4280
4281 int eid = Res_GETENTRY(resID);
4282 if (eid < 0 || eid >= (int)t->getOrderedConfigs().size()) {
4283 fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
4284 return NULL;
4285 }
4286
4287 sp<ConfigList> c = t->getOrderedConfigs()[eid];
4288 if (c == NULL) {
4289 fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
4290 return NULL;
4291 }
4292
4293 ConfigDescription cdesc;
4294 if (config) cdesc = *config;
4295 sp<Entry> e = c->getEntries().valueFor(cdesc);
4296 if (c == NULL) {
4297 fprintf(stderr, "warning: Entry configuration not found for resource #%08x\n", resID);
4298 return NULL;
4299 }
4300
4301 return e;
4302}
4303
4304const ResourceTable::Item* ResourceTable::getItem(uint32_t resID, uint32_t attrID) const
4305{
4306 sp<const Entry> e = getEntry(resID);
4307 if (e == NULL) {
4308 return NULL;
4309 }
4310
4311 const size_t N = e->getBag().size();
4312 for (size_t i=0; i<N; i++) {
4313 const Item& it = e->getBag().valueAt(i);
4314 if (it.bagKeyId == 0) {
4315 fprintf(stderr, "warning: ID not yet assigned to '%s' in bag '%s'\n",
4316 String8(e->getName()).string(),
4317 String8(e->getBag().keyAt(i)).string());
4318 }
4319 if (it.bagKeyId == attrID) {
4320 return &it;
4321 }
4322 }
4323
4324 return NULL;
4325}
4326
4327bool ResourceTable::getItemValue(
4328 uint32_t resID, uint32_t attrID, Res_value* outValue)
4329{
4330 const Item* item = getItem(resID, attrID);
4331
4332 bool res = false;
4333 if (item != NULL) {
4334 if (item->evaluating) {
4335 sp<const Entry> e = getEntry(resID);
4336 const size_t N = e->getBag().size();
4337 size_t i;
4338 for (i=0; i<N; i++) {
4339 if (&e->getBag().valueAt(i) == item) {
4340 break;
4341 }
4342 }
4343 fprintf(stderr, "warning: Circular reference detected in key '%s' of bag '%s'\n",
4344 String8(e->getName()).string(),
4345 String8(e->getBag().keyAt(i)).string());
4346 return false;
4347 }
4348 item->evaluating = true;
4349 res = stringToValue(outValue, NULL, item->value, false, false, item->bagKeyId);
Andreas Gampe2412f842014-09-30 20:55:57 -07004350 if (kIsDebug) {
Adam Lesinski282e1812014-01-23 18:17:42 -08004351 if (res) {
4352 printf("getItemValue of #%08x[#%08x] (%s): type=#%08x, data=#%08x\n",
4353 resID, attrID, String8(getEntry(resID)->getName()).string(),
4354 outValue->dataType, outValue->data);
4355 } else {
4356 printf("getItemValue of #%08x[#%08x]: failed\n",
4357 resID, attrID);
4358 }
Andreas Gampe2412f842014-09-30 20:55:57 -07004359 }
Adam Lesinski282e1812014-01-23 18:17:42 -08004360 item->evaluating = false;
4361 }
4362 return res;
4363}
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004364
4365/**
Adam Lesinski28994d82015-01-13 13:42:41 -08004366 * Returns the SDK version at which the attribute was
4367 * made public, or -1 if the resource ID is not an attribute
4368 * or is not public.
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004369 */
Adam Lesinski28994d82015-01-13 13:42:41 -08004370int ResourceTable::getPublicAttributeSdkLevel(uint32_t attrId) const {
4371 if (Res_GETPACKAGE(attrId) + 1 != 0x01 || Res_GETTYPE(attrId) + 1 != 0x01) {
4372 return -1;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004373 }
4374
4375 uint32_t specFlags;
4376 if (!mAssets->getIncludedResources().getResourceFlags(attrId, &specFlags)) {
Adam Lesinski28994d82015-01-13 13:42:41 -08004377 return -1;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004378 }
4379
Adam Lesinski28994d82015-01-13 13:42:41 -08004380 if ((specFlags & ResTable_typeSpec::SPEC_PUBLIC) == 0) {
4381 return -1;
4382 }
4383
4384 const size_t entryId = Res_GETENTRY(attrId);
4385 if (entryId <= 0x021c) {
4386 return 1;
4387 } else if (entryId <= 0x021d) {
4388 return 2;
4389 } else if (entryId <= 0x0269) {
4390 return SDK_CUPCAKE;
4391 } else if (entryId <= 0x028d) {
4392 return SDK_DONUT;
4393 } else if (entryId <= 0x02ad) {
4394 return SDK_ECLAIR;
4395 } else if (entryId <= 0x02b3) {
4396 return SDK_ECLAIR_0_1;
4397 } else if (entryId <= 0x02b5) {
4398 return SDK_ECLAIR_MR1;
4399 } else if (entryId <= 0x02bd) {
4400 return SDK_FROYO;
4401 } else if (entryId <= 0x02cb) {
4402 return SDK_GINGERBREAD;
4403 } else if (entryId <= 0x0361) {
4404 return SDK_HONEYCOMB;
4405 } else if (entryId <= 0x0366) {
4406 return SDK_HONEYCOMB_MR1;
4407 } else if (entryId <= 0x03a6) {
4408 return SDK_HONEYCOMB_MR2;
4409 } else if (entryId <= 0x03ae) {
4410 return SDK_JELLY_BEAN;
4411 } else if (entryId <= 0x03cc) {
4412 return SDK_JELLY_BEAN_MR1;
4413 } else if (entryId <= 0x03da) {
4414 return SDK_JELLY_BEAN_MR2;
4415 } else if (entryId <= 0x03f1) {
4416 return SDK_KITKAT;
4417 } else if (entryId <= 0x03f6) {
4418 return SDK_KITKAT_WATCH;
4419 } else if (entryId <= 0x04ce) {
4420 return SDK_LOLLIPOP;
4421 } else {
4422 // Anything else is marked as defined in
4423 // SDK_LOLLIPOP_MR1 since after this
4424 // version no attribute compat work
4425 // needs to be done.
4426 return SDK_LOLLIPOP_MR1;
4427 }
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004428}
4429
Adam Lesinski28994d82015-01-13 13:42:41 -08004430/**
4431 * First check the Manifest, then check the command line flag.
4432 */
4433static int getMinSdkVersion(const Bundle* bundle) {
4434 if (bundle->getManifestMinSdkVersion() != NULL && strlen(bundle->getManifestMinSdkVersion()) > 0) {
4435 return atoi(bundle->getManifestMinSdkVersion());
4436 } else if (bundle->getMinSdkVersion() != NULL && strlen(bundle->getMinSdkVersion()) > 0) {
4437 return atoi(bundle->getMinSdkVersion());
Adam Lesinskie572c012014-09-19 15:10:04 -07004438 }
Adam Lesinski28994d82015-01-13 13:42:41 -08004439 return 0;
Adam Lesinskie572c012014-09-19 15:10:04 -07004440}
4441
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004442/**
4443 * Modifies the entries in the resource table to account for compatibility
4444 * issues with older versions of Android.
4445 *
4446 * This primarily handles the issue of private/public attribute clashes
4447 * in framework resources.
4448 *
4449 * AAPT has traditionally assigned resource IDs to public attributes,
4450 * and then followed those public definitions with private attributes.
4451 *
4452 * --- PUBLIC ---
4453 * | 0x01010234 | attr/color
4454 * | 0x01010235 | attr/background
4455 *
4456 * --- PRIVATE ---
4457 * | 0x01010236 | attr/secret
4458 * | 0x01010237 | attr/shhh
4459 *
4460 * Each release, when attributes are added, they take the place of the private
4461 * attributes and the private attributes are shifted down again.
4462 *
4463 * --- PUBLIC ---
4464 * | 0x01010234 | attr/color
4465 * | 0x01010235 | attr/background
4466 * | 0x01010236 | attr/shinyNewAttr
4467 * | 0x01010237 | attr/highlyValuedFeature
4468 *
4469 * --- PRIVATE ---
4470 * | 0x01010238 | attr/secret
4471 * | 0x01010239 | attr/shhh
4472 *
4473 * Platform code may look for private attributes set in a theme. If an app
4474 * compiled against a newer version of the platform uses a new public
4475 * attribute that happens to have the same ID as the private attribute
4476 * the older platform is expecting, then the behavior is undefined.
4477 *
4478 * We get around this by detecting any newly defined attributes (in L),
4479 * copy the resource into a -v21 qualified resource, and delete the
4480 * attribute from the original resource. This ensures that older platforms
4481 * don't see the new attribute, but when running on L+ platforms, the
4482 * attribute will be respected.
4483 */
4484status_t ResourceTable::modifyForCompat(const Bundle* bundle) {
Adam Lesinski28994d82015-01-13 13:42:41 -08004485 const int minSdk = getMinSdkVersion(bundle);
4486 if (minSdk >= SDK_LOLLIPOP_MR1) {
4487 // Lollipop MR1 and up handles public attributes differently, no
4488 // need to do any compat modifications.
Adam Lesinskie572c012014-09-19 15:10:04 -07004489 return NO_ERROR;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004490 }
4491
4492 const String16 attr16("attr");
4493
4494 const size_t packageCount = mOrderedPackages.size();
4495 for (size_t pi = 0; pi < packageCount; pi++) {
4496 sp<Package> p = mOrderedPackages.itemAt(pi);
4497 if (p == NULL || p->getTypes().size() == 0) {
4498 // Empty, skip!
4499 continue;
4500 }
4501
4502 const size_t typeCount = p->getOrderedTypes().size();
4503 for (size_t ti = 0; ti < typeCount; ti++) {
4504 sp<Type> t = p->getOrderedTypes().itemAt(ti);
4505 if (t == NULL) {
4506 continue;
4507 }
4508
4509 const size_t configCount = t->getOrderedConfigs().size();
4510 for (size_t ci = 0; ci < configCount; ci++) {
4511 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
4512 if (c == NULL) {
4513 continue;
4514 }
4515
4516 Vector<key_value_pair_t<ConfigDescription, sp<Entry> > > entriesToAdd;
4517 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& entries =
4518 c->getEntries();
4519 const size_t entryCount = entries.size();
4520 for (size_t ei = 0; ei < entryCount; ei++) {
4521 sp<Entry> e = entries.valueAt(ei);
4522 if (e == NULL || e->getType() != Entry::TYPE_BAG) {
4523 continue;
4524 }
4525
4526 const ConfigDescription& config = entries.keyAt(ei);
Adam Lesinski28994d82015-01-13 13:42:41 -08004527 if (config.sdkVersion >= SDK_LOLLIPOP_MR1) {
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004528 continue;
4529 }
4530
Adam Lesinski28994d82015-01-13 13:42:41 -08004531 KeyedVector<int, Vector<String16> > attributesToRemove;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004532 const KeyedVector<String16, Item>& bag = e->getBag();
4533 const size_t bagCount = bag.size();
4534 for (size_t bi = 0; bi < bagCount; bi++) {
4535 const Item& item = bag.valueAt(bi);
4536 const uint32_t attrId = getResId(bag.keyAt(bi), &attr16);
Adam Lesinski28994d82015-01-13 13:42:41 -08004537 const int sdkLevel = getPublicAttributeSdkLevel(attrId);
4538 if (sdkLevel > 1 && sdkLevel > config.sdkVersion && sdkLevel > minSdk) {
4539 AaptUtil::appendValue(attributesToRemove, sdkLevel, bag.keyAt(bi));
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004540 }
4541 }
4542
4543 if (attributesToRemove.isEmpty()) {
4544 continue;
4545 }
4546
Adam Lesinski28994d82015-01-13 13:42:41 -08004547 const size_t sdkCount = attributesToRemove.size();
4548 for (size_t i = 0; i < sdkCount; i++) {
4549 const int sdkLevel = attributesToRemove.keyAt(i);
4550
4551 // Duplicate the entry under the same configuration
4552 // but with sdkVersion == sdkLevel.
4553 ConfigDescription newConfig(config);
4554 newConfig.sdkVersion = sdkLevel;
4555
4556 sp<Entry> newEntry = new Entry(*e);
4557
4558 // Remove all items that have a higher SDK level than
4559 // the one we are synthesizing.
4560 for (size_t j = 0; j < sdkCount; j++) {
4561 if (j == i) {
4562 continue;
4563 }
4564
4565 if (attributesToRemove.keyAt(j) > sdkLevel) {
4566 const size_t attrCount = attributesToRemove[j].size();
4567 for (size_t k = 0; k < attrCount; k++) {
4568 newEntry->removeFromBag(attributesToRemove[j][k]);
4569 }
4570 }
4571 }
4572
4573 entriesToAdd.add(key_value_pair_t<ConfigDescription, sp<Entry> >(
4574 newConfig, newEntry));
4575 }
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004576
4577 // Remove the attribute from the original.
4578 for (size_t i = 0; i < attributesToRemove.size(); i++) {
Adam Lesinski28994d82015-01-13 13:42:41 -08004579 for (size_t j = 0; j < attributesToRemove[i].size(); j++) {
4580 e->removeFromBag(attributesToRemove[i][j]);
4581 }
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004582 }
4583 }
4584
4585 const size_t entriesToAddCount = entriesToAdd.size();
4586 for (size_t i = 0; i < entriesToAddCount; i++) {
4587 if (entries.indexOfKey(entriesToAdd[i].key) >= 0) {
4588 // An entry already exists for this config.
4589 // That means that any attributes that were
4590 // defined in L in the original bag will be overriden
4591 // anyways on L devices, so we do nothing.
4592 continue;
4593 }
4594
Adam Lesinskif15de2e2014-10-03 14:57:28 -07004595 if (bundle->getVerbose()) {
4596 entriesToAdd[i].value->getPos()
4597 .printf("using v%d attributes; synthesizing resource %s:%s/%s for configuration %s.",
Adam Lesinski28994d82015-01-13 13:42:41 -08004598 entriesToAdd[i].key.sdkVersion,
Adam Lesinskif15de2e2014-10-03 14:57:28 -07004599 String8(p->getName()).string(),
4600 String8(t->getName()).string(),
4601 String8(entriesToAdd[i].value->getName()).string(),
4602 entriesToAdd[i].key.toString().string());
4603 }
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004604
Adam Lesinski978ab9d2014-09-24 19:02:52 -07004605 sp<Entry> newEntry = t->getEntry(c->getName(),
4606 entriesToAdd[i].value->getPos(),
4607 &entriesToAdd[i].key);
4608
4609 *newEntry = *entriesToAdd[i].value;
Adam Lesinski82a2dd82014-09-17 18:34:15 -07004610 }
4611 }
4612 }
4613 }
4614 return NO_ERROR;
4615}
Adam Lesinskie572c012014-09-19 15:10:04 -07004616
4617status_t ResourceTable::modifyForCompat(const Bundle* bundle,
4618 const String16& resourceName,
4619 const sp<AaptFile>& target,
4620 const sp<XMLNode>& root) {
Adam Lesinski28994d82015-01-13 13:42:41 -08004621 const int minSdk = getMinSdkVersion(bundle);
4622 if (minSdk >= SDK_LOLLIPOP_MR1) {
4623 // Lollipop MR1 and up handles public attributes differently, no
4624 // need to do any compat modifications.
Adam Lesinskie572c012014-09-19 15:10:04 -07004625 return NO_ERROR;
4626 }
4627
Adam Lesinski28994d82015-01-13 13:42:41 -08004628 const ConfigDescription config(target->getGroupEntry().toParams());
4629 if (target->getResourceType() == "" || config.sdkVersion >= SDK_LOLLIPOP_MR1) {
Adam Lesinskie572c012014-09-19 15:10:04 -07004630 // Skip resources that have no type (AndroidManifest.xml) or are already version qualified with v21
4631 // or higher.
4632 return NO_ERROR;
4633 }
4634
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004635 sp<XMLNode> newRoot = NULL;
Adam Lesinski28994d82015-01-13 13:42:41 -08004636 ConfigDescription newConfig(target->getGroupEntry().toParams());
4637 newConfig.sdkVersion = SDK_LOLLIPOP_MR1;
Adam Lesinskie572c012014-09-19 15:10:04 -07004638
4639 Vector<sp<XMLNode> > nodesToVisit;
4640 nodesToVisit.push(root);
4641 while (!nodesToVisit.isEmpty()) {
4642 sp<XMLNode> node = nodesToVisit.top();
4643 nodesToVisit.pop();
4644
4645 const Vector<XMLNode::attribute_entry>& attrs = node->getAttributes();
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004646 for (size_t i = 0; i < attrs.size(); i++) {
Adam Lesinskie572c012014-09-19 15:10:04 -07004647 const XMLNode::attribute_entry& attr = attrs[i];
Adam Lesinski28994d82015-01-13 13:42:41 -08004648 const int sdkLevel = getPublicAttributeSdkLevel(attr.nameResId);
4649 if (sdkLevel > 1 && sdkLevel > config.sdkVersion && sdkLevel > minSdk) {
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004650 if (newRoot == NULL) {
4651 newRoot = root->clone();
4652 }
4653
Adam Lesinski28994d82015-01-13 13:42:41 -08004654 // Find the smallest sdk version that we need to synthesize for
4655 // and do that one. Subsequent versions will be processed on
4656 // the next pass.
4657 if (sdkLevel < newConfig.sdkVersion) {
4658 newConfig.sdkVersion = sdkLevel;
4659 }
4660
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004661 if (bundle->getVerbose()) {
4662 SourcePos(node->getFilename(), node->getStartLineNumber()).printf(
4663 "removing attribute %s%s%s from <%s>",
4664 String8(attr.ns).string(),
4665 (attr.ns.size() == 0 ? "" : ":"),
4666 String8(attr.name).string(),
4667 String8(node->getElementName()).string());
4668 }
4669 node->removeAttribute(i);
4670 i--;
Adam Lesinskie572c012014-09-19 15:10:04 -07004671 }
4672 }
4673
4674 // Schedule a visit to the children.
4675 const Vector<sp<XMLNode> >& children = node->getChildren();
4676 const size_t childCount = children.size();
4677 for (size_t i = 0; i < childCount; i++) {
4678 nodesToVisit.push(children[i]);
4679 }
4680 }
4681
Adam Lesinskiea4e5ec2014-12-10 15:46:51 -08004682 if (newRoot == NULL) {
Adam Lesinskie572c012014-09-19 15:10:04 -07004683 return NO_ERROR;
4684 }
4685
Adam Lesinskie572c012014-09-19 15:10:04 -07004686 // Look to see if we already have an overriding v21 configuration.
4687 sp<ConfigList> cl = getConfigList(String16(mAssets->getPackage()),
4688 String16(target->getResourceType()), resourceName);
4689 if (cl->getEntries().indexOfKey(newConfig) < 0) {
4690 // We don't have an overriding entry for v21, so we must duplicate this one.
Adam Lesinskie572c012014-09-19 15:10:04 -07004691 sp<AaptFile> newFile = new AaptFile(target->getSourceFile(),
4692 AaptGroupEntry(newConfig), target->getResourceType());
4693 String8 resPath = String8::format("res/%s/%s",
4694 newFile->getGroupEntry().toDirName(target->getResourceType()).string(),
Adam Lesinskiaff7c242014-10-20 12:15:25 -07004695 target->getSourceFile().getPathLeaf().string());
Adam Lesinskie572c012014-09-19 15:10:04 -07004696 resPath.convertToResPath();
4697
4698 // Add a resource table entry.
Adam Lesinskif15de2e2014-10-03 14:57:28 -07004699 if (bundle->getVerbose()) {
4700 SourcePos(target->getSourceFile(), -1).printf(
4701 "using v%d attributes; synthesizing resource %s:%s/%s for configuration %s.",
Adam Lesinski28994d82015-01-13 13:42:41 -08004702 newConfig.sdkVersion,
Adam Lesinskif15de2e2014-10-03 14:57:28 -07004703 mAssets->getPackage().string(),
4704 newFile->getResourceType().string(),
4705 String8(resourceName).string(),
4706 newConfig.toString().string());
4707 }
Adam Lesinskie572c012014-09-19 15:10:04 -07004708
4709 addEntry(SourcePos(),
4710 String16(mAssets->getPackage()),
4711 String16(target->getResourceType()),
4712 resourceName,
4713 String16(resPath),
4714 NULL,
4715 &newConfig);
4716
4717 // Schedule this to be compiled.
4718 CompileResourceWorkItem item;
4719 item.resourceName = resourceName;
4720 item.resPath = resPath;
4721 item.file = newFile;
4722 mWorkQueue.push(item);
4723 }
4724
Adam Lesinskie572c012014-09-19 15:10:04 -07004725 return NO_ERROR;
4726}
Adam Lesinskide7de472014-11-03 12:03:08 -08004727
4728void ResourceTable::getDensityVaryingResources(KeyedVector<Symbol, Vector<SymbolDefinition> >& resources) {
4729 const ConfigDescription nullConfig;
4730
4731 const size_t packageCount = mOrderedPackages.size();
4732 for (size_t p = 0; p < packageCount; p++) {
4733 const Vector<sp<Type> >& types = mOrderedPackages[p]->getOrderedTypes();
4734 const size_t typeCount = types.size();
4735 for (size_t t = 0; t < typeCount; t++) {
4736 const Vector<sp<ConfigList> >& configs = types[t]->getOrderedConfigs();
4737 const size_t configCount = configs.size();
4738 for (size_t c = 0; c < configCount; c++) {
4739 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& configEntries = configs[c]->getEntries();
4740 const size_t configEntryCount = configEntries.size();
4741 for (size_t ce = 0; ce < configEntryCount; ce++) {
4742 const ConfigDescription& config = configEntries.keyAt(ce);
4743 if (AaptConfig::isDensityOnly(config)) {
4744 // This configuration only varies with regards to density.
4745 const Symbol symbol(mOrderedPackages[p]->getName(),
4746 types[t]->getName(),
4747 configs[c]->getName(),
4748 getResId(mOrderedPackages[p], types[t], configs[c]->getEntryIndex()));
4749
4750 const sp<Entry>& entry = configEntries.valueAt(ce);
4751 AaptUtil::appendValue(resources, symbol, SymbolDefinition(symbol, config, entry->getPos()));
4752 }
4753 }
4754 }
4755 }
4756 }
4757}